var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __require = /* @__PURE__ */ ((x2) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x2, {
  get: (a3, b4) => (typeof require !== "undefined" ? require : a3)[b4]
}) : x2)(function(x2) {
  if (typeof require !== "undefined") return require.apply(this, arguments);
  throw Error('Dynamic require of "' + x2 + '" is not supported');
});
var __esm = (fn, res) => function __init() {
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
var __commonJS = (cb, mod) => function __require2() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i7 = decorators.length - 1, decorator; i7 >= 0; i7--)
    if (decorator = decorators[i7])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result) __defProp(target, key, result);
  return result;
};

// scripts/process-shim.js
var processShim, process_shim_default, process;
var init_process_shim = __esm({
  "scripts/process-shim.js"() {
    "use strict";
    processShim = {
      browser: true,
      env: {},
      cwd: () => "/",
      platform: "browser",
      version: "",
      versions: {},
      argv: [],
      pid: 0,
      title: "browser",
      nextTick: (fn, ...args) => Promise.resolve().then(() => fn(...args)),
      stderr: {},
      stdout: {},
      stdin: {}
    };
    process_shim_default = processShim;
    process = processShim;
  }
});

// ../pi-mono/node_modules/partial-json/dist/options.js
var require_options = __commonJS({
  "../pi-mono/node_modules/partial-json/dist/options.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Allow = exports.ALL = exports.COLLECTION = exports.ATOM = exports.SPECIAL = exports.INF = exports._INFINITY = exports.INFINITY = exports.NAN = exports.BOOL = exports.NULL = exports.OBJ = exports.ARR = exports.NUM = exports.STR = void 0;
    exports.STR = 1;
    exports.NUM = 2;
    exports.ARR = 4;
    exports.OBJ = 8;
    exports.NULL = 16;
    exports.BOOL = 32;
    exports.NAN = 64;
    exports.INFINITY = 128;
    exports._INFINITY = 256;
    exports.INF = exports.INFINITY | exports._INFINITY;
    exports.SPECIAL = exports.NULL | exports.BOOL | exports.INF | exports.NAN;
    exports.ATOM = exports.STR | exports.NUM | exports.SPECIAL;
    exports.COLLECTION = exports.ARR | exports.OBJ;
    exports.ALL = exports.ATOM | exports.COLLECTION;
    exports.Allow = { STR: exports.STR, NUM: exports.NUM, ARR: exports.ARR, OBJ: exports.OBJ, NULL: exports.NULL, BOOL: exports.BOOL, NAN: exports.NAN, INFINITY: exports.INFINITY, _INFINITY: exports._INFINITY, INF: exports.INF, SPECIAL: exports.SPECIAL, ATOM: exports.ATOM, COLLECTION: exports.COLLECTION, ALL: exports.ALL };
    exports.default = exports.Allow;
  }
});

// ../pi-mono/node_modules/partial-json/dist/index.js
var require_dist = __commonJS({
  "../pi-mono/node_modules/partial-json/dist/index.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __exportStar = exports && exports.__exportStar || function(m4, exports2) {
      for (var p4 in m4) if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4)) __createBinding(exports2, m4, p4);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Allow = exports.MalformedJSON = exports.PartialJSON = exports.parseJSON = exports.parse = void 0;
    var options_1 = require_options();
    Object.defineProperty(exports, "Allow", { enumerable: true, get: function() {
      return options_1.Allow;
    } });
    __exportStar(require_options(), exports);
    var PartialJSON2 = class extends Error {
    };
    exports.PartialJSON = PartialJSON2;
    var MalformedJSON2 = class extends Error {
    };
    exports.MalformedJSON = MalformedJSON2;
    function parseJSON3(jsonString, allowPartial = options_1.Allow.ALL) {
      if (typeof jsonString !== "string") {
        throw new TypeError(`expecting str, got ${typeof jsonString}`);
      }
      if (!jsonString.trim()) {
        throw new Error(`${jsonString} is empty`);
      }
      return _parseJSON2(jsonString.trim(), allowPartial);
    }
    exports.parseJSON = parseJSON3;
    var _parseJSON2 = (jsonString, allow) => {
      const length = jsonString.length;
      let index = 0;
      const markPartialJSON = (msg) => {
        throw new PartialJSON2(`${msg} at position ${index}`);
      };
      const throwMalformedError = (msg) => {
        throw new MalformedJSON2(`${msg} at position ${index}`);
      };
      const parseAny = () => {
        skipBlank();
        if (index >= length)
          markPartialJSON("Unexpected end of input");
        if (jsonString[index] === '"')
          return parseStr();
        if (jsonString[index] === "{")
          return parseObj();
        if (jsonString[index] === "[")
          return parseArr();
        if (jsonString.substring(index, index + 4) === "null" || options_1.Allow.NULL & allow && length - index < 4 && "null".startsWith(jsonString.substring(index))) {
          index += 4;
          return null;
        }
        if (jsonString.substring(index, index + 4) === "true" || options_1.Allow.BOOL & allow && length - index < 4 && "true".startsWith(jsonString.substring(index))) {
          index += 4;
          return true;
        }
        if (jsonString.substring(index, index + 5) === "false" || options_1.Allow.BOOL & allow && length - index < 5 && "false".startsWith(jsonString.substring(index))) {
          index += 5;
          return false;
        }
        if (jsonString.substring(index, index + 8) === "Infinity" || options_1.Allow.INFINITY & allow && length - index < 8 && "Infinity".startsWith(jsonString.substring(index))) {
          index += 8;
          return Infinity;
        }
        if (jsonString.substring(index, index + 9) === "-Infinity" || options_1.Allow._INFINITY & allow && 1 < length - index && length - index < 9 && "-Infinity".startsWith(jsonString.substring(index))) {
          index += 9;
          return -Infinity;
        }
        if (jsonString.substring(index, index + 3) === "NaN" || options_1.Allow.NAN & allow && length - index < 3 && "NaN".startsWith(jsonString.substring(index))) {
          index += 3;
          return NaN;
        }
        return parseNum();
      };
      const parseStr = () => {
        const start = index;
        let escape4 = false;
        index++;
        while (index < length && (jsonString[index] !== '"' || escape4 && jsonString[index - 1] === "\\")) {
          escape4 = jsonString[index] === "\\" ? !escape4 : false;
          index++;
        }
        if (jsonString.charAt(index) == '"') {
          try {
            return JSON.parse(jsonString.substring(start, ++index - Number(escape4)));
          } catch (e9) {
            throwMalformedError(String(e9));
          }
        } else if (options_1.Allow.STR & allow) {
          try {
            return JSON.parse(jsonString.substring(start, index - Number(escape4)) + '"');
          } catch (e9) {
            return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf("\\")) + '"');
          }
        }
        markPartialJSON("Unterminated string literal");
      };
      const parseObj = () => {
        index++;
        skipBlank();
        const obj = {};
        try {
          while (jsonString[index] !== "}") {
            skipBlank();
            if (index >= length && options_1.Allow.OBJ & allow)
              return obj;
            const key = parseStr();
            skipBlank();
            index++;
            try {
              const value = parseAny();
              obj[key] = value;
            } catch (e9) {
              if (options_1.Allow.OBJ & allow)
                return obj;
              else
                throw e9;
            }
            skipBlank();
            if (jsonString[index] === ",")
              index++;
          }
        } catch (e9) {
          if (options_1.Allow.OBJ & allow)
            return obj;
          else
            markPartialJSON("Expected '}' at end of object");
        }
        index++;
        return obj;
      };
      const parseArr = () => {
        index++;
        const arr = [];
        try {
          while (jsonString[index] !== "]") {
            arr.push(parseAny());
            skipBlank();
            if (jsonString[index] === ",") {
              index++;
            }
          }
        } catch (e9) {
          if (options_1.Allow.ARR & allow) {
            return arr;
          }
          markPartialJSON("Expected ']' at end of array");
        }
        index++;
        return arr;
      };
      const parseNum = () => {
        if (index === 0) {
          if (jsonString === "-")
            throwMalformedError("Not sure what '-' is");
          try {
            return JSON.parse(jsonString);
          } catch (e9) {
            if (options_1.Allow.NUM & allow)
              try {
                return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf("e")));
              } catch (e10) {
              }
            throwMalformedError(String(e9));
          }
        }
        const start = index;
        if (jsonString[index] === "-")
          index++;
        while (jsonString[index] && ",]}".indexOf(jsonString[index]) === -1)
          index++;
        if (index == length && !(options_1.Allow.NUM & allow))
          markPartialJSON("Unterminated number literal");
        try {
          return JSON.parse(jsonString.substring(start, index));
        } catch (e9) {
          if (jsonString.substring(start, index) === "-")
            markPartialJSON("Not sure what '-' is");
          try {
            return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf("e")));
          } catch (e10) {
            throwMalformedError(String(e10));
          }
        }
      };
      const skipBlank = () => {
        while (index < length && " \n\r	".includes(jsonString[index])) {
          index++;
        }
      };
      return parseAny();
    };
    var parse = parseJSON3;
    exports.parse = parse;
  }
});

// ../pi-mono/node_modules/retry/lib/retry_operation.js
var require_retry_operation = __commonJS({
  "../pi-mono/node_modules/retry/lib/retry_operation.js"(exports, module) {
    init_process_shim();
    function RetryOperation(timeouts, options) {
      if (typeof options === "boolean") {
        options = { forever: options };
      }
      this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));
      this._timeouts = timeouts;
      this._options = options || {};
      this._maxRetryTime = options && options.maxRetryTime || Infinity;
      this._fn = null;
      this._errors = [];
      this._attempts = 1;
      this._operationTimeout = null;
      this._operationTimeoutCb = null;
      this._timeout = null;
      this._operationStart = null;
      this._timer = null;
      if (this._options.forever) {
        this._cachedTimeouts = this._timeouts.slice(0);
      }
    }
    module.exports = RetryOperation;
    RetryOperation.prototype.reset = function() {
      this._attempts = 1;
      this._timeouts = this._originalTimeouts.slice(0);
    };
    RetryOperation.prototype.stop = function() {
      if (this._timeout) {
        clearTimeout(this._timeout);
      }
      if (this._timer) {
        clearTimeout(this._timer);
      }
      this._timeouts = [];
      this._cachedTimeouts = null;
    };
    RetryOperation.prototype.retry = function(err) {
      if (this._timeout) {
        clearTimeout(this._timeout);
      }
      if (!err) {
        return false;
      }
      var currentTime = (/* @__PURE__ */ new Date()).getTime();
      if (err && currentTime - this._operationStart >= this._maxRetryTime) {
        this._errors.push(err);
        this._errors.unshift(new Error("RetryOperation timeout occurred"));
        return false;
      }
      this._errors.push(err);
      var timeout = this._timeouts.shift();
      if (timeout === void 0) {
        if (this._cachedTimeouts) {
          this._errors.splice(0, this._errors.length - 1);
          timeout = this._cachedTimeouts.slice(-1);
        } else {
          return false;
        }
      }
      var self2 = this;
      this._timer = setTimeout(function() {
        self2._attempts++;
        if (self2._operationTimeoutCb) {
          self2._timeout = setTimeout(function() {
            self2._operationTimeoutCb(self2._attempts);
          }, self2._operationTimeout);
          if (self2._options.unref) {
            self2._timeout.unref();
          }
        }
        self2._fn(self2._attempts);
      }, timeout);
      if (this._options.unref) {
        this._timer.unref();
      }
      return true;
    };
    RetryOperation.prototype.attempt = function(fn, timeoutOps) {
      this._fn = fn;
      if (timeoutOps) {
        if (timeoutOps.timeout) {
          this._operationTimeout = timeoutOps.timeout;
        }
        if (timeoutOps.cb) {
          this._operationTimeoutCb = timeoutOps.cb;
        }
      }
      var self2 = this;
      if (this._operationTimeoutCb) {
        this._timeout = setTimeout(function() {
          self2._operationTimeoutCb();
        }, self2._operationTimeout);
      }
      this._operationStart = (/* @__PURE__ */ new Date()).getTime();
      this._fn(this._attempts);
    };
    RetryOperation.prototype.try = function(fn) {
      console.log("Using RetryOperation.try() is deprecated");
      this.attempt(fn);
    };
    RetryOperation.prototype.start = function(fn) {
      console.log("Using RetryOperation.start() is deprecated");
      this.attempt(fn);
    };
    RetryOperation.prototype.start = RetryOperation.prototype.try;
    RetryOperation.prototype.errors = function() {
      return this._errors;
    };
    RetryOperation.prototype.attempts = function() {
      return this._attempts;
    };
    RetryOperation.prototype.mainError = function() {
      if (this._errors.length === 0) {
        return null;
      }
      var counts = {};
      var mainError = null;
      var mainErrorCount = 0;
      for (var i7 = 0; i7 < this._errors.length; i7++) {
        var error = this._errors[i7];
        var message = error.message;
        var count = (counts[message] || 0) + 1;
        counts[message] = count;
        if (count >= mainErrorCount) {
          mainError = error;
          mainErrorCount = count;
        }
      }
      return mainError;
    };
  }
});

// ../pi-mono/node_modules/retry/lib/retry.js
var require_retry = __commonJS({
  "../pi-mono/node_modules/retry/lib/retry.js"(exports) {
    init_process_shim();
    var RetryOperation = require_retry_operation();
    exports.operation = function(options) {
      var timeouts = exports.timeouts(options);
      return new RetryOperation(timeouts, {
        forever: options && (options.forever || options.retries === Infinity),
        unref: options && options.unref,
        maxRetryTime: options && options.maxRetryTime
      });
    };
    exports.timeouts = function(options) {
      if (options instanceof Array) {
        return [].concat(options);
      }
      var opts = {
        retries: 10,
        factor: 2,
        minTimeout: 1 * 1e3,
        maxTimeout: Infinity,
        randomize: false
      };
      for (var key in options) {
        opts[key] = options[key];
      }
      if (opts.minTimeout > opts.maxTimeout) {
        throw new Error("minTimeout is greater than maxTimeout");
      }
      var timeouts = [];
      for (var i7 = 0; i7 < opts.retries; i7++) {
        timeouts.push(this.createTimeout(i7, opts));
      }
      if (options && options.forever && !timeouts.length) {
        timeouts.push(this.createTimeout(i7, opts));
      }
      timeouts.sort(function(a3, b4) {
        return a3 - b4;
      });
      return timeouts;
    };
    exports.createTimeout = function(attempt, opts) {
      var random = opts.randomize ? Math.random() + 1 : 1;
      var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt));
      timeout = Math.min(timeout, opts.maxTimeout);
      return timeout;
    };
    exports.wrap = function(obj, options, methods2) {
      if (options instanceof Array) {
        methods2 = options;
        options = null;
      }
      if (!methods2) {
        methods2 = [];
        for (var key in obj) {
          if (typeof obj[key] === "function") {
            methods2.push(key);
          }
        }
      }
      for (var i7 = 0; i7 < methods2.length; i7++) {
        var method = methods2[i7];
        var original = obj[method];
        obj[method] = function retryWrapper(original2) {
          var op2 = exports.operation(options);
          var args = Array.prototype.slice.call(arguments, 1);
          var callback = args.pop();
          args.push(function(err) {
            if (op2.retry(err)) {
              return;
            }
            if (err) {
              arguments[0] = op2.mainError();
            }
            callback.apply(this, arguments);
          });
          op2.attempt(function() {
            original2.apply(obj, args);
          });
        }.bind(obj, original);
        obj[method].options = options;
      }
    };
  }
});

// ../pi-mono/node_modules/retry/index.js
var require_retry2 = __commonJS({
  "../pi-mono/node_modules/retry/index.js"(exports, module) {
    init_process_shim();
    module.exports = require_retry();
  }
});

// ../pi-mono/node_modules/p-retry/index.js
var require_p_retry = __commonJS({
  "../pi-mono/node_modules/p-retry/index.js"(exports, module) {
    "use strict";
    init_process_shim();
    var retry = require_retry2();
    var networkErrorMsgs = [
      "Failed to fetch",
      // Chrome
      "NetworkError when attempting to fetch resource.",
      // Firefox
      "The Internet connection appears to be offline.",
      // Safari
      "Network request failed"
      // `cross-fetch`
    ];
    var AbortError2 = class extends Error {
      constructor(message) {
        super();
        if (message instanceof Error) {
          this.originalError = message;
          ({ message } = message);
        } else {
          this.originalError = new Error(message);
          this.originalError.stack = this.stack;
        }
        this.name = "AbortError";
        this.message = message;
      }
    };
    var decorateErrorWithCounts = (error, attemptNumber, options) => {
      const retriesLeft = options.retries - (attemptNumber - 1);
      error.attemptNumber = attemptNumber;
      error.retriesLeft = retriesLeft;
      return error;
    };
    var isNetworkError = (errorMessage) => networkErrorMsgs.includes(errorMessage);
    var pRetry2 = (input, options) => new Promise((resolve, reject) => {
      options = {
        onFailedAttempt: () => {
        },
        retries: 10,
        ...options
      };
      const operation = retry.operation(options);
      operation.attempt(async (attemptNumber) => {
        try {
          resolve(await input(attemptNumber));
        } catch (error) {
          if (!(error instanceof Error)) {
            reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`));
            return;
          }
          if (error instanceof AbortError2) {
            operation.stop();
            reject(error.originalError);
          } else if (error instanceof TypeError && !isNetworkError(error.message)) {
            operation.stop();
            reject(error);
          } else {
            decorateErrorWithCounts(error, attemptNumber, options);
            try {
              await options.onFailedAttempt(error);
            } catch (error2) {
              reject(error2);
              return;
            }
            if (!operation.retry(error)) {
              reject(operation.mainError());
            }
          }
        }
      });
    });
    module.exports = pRetry2;
    module.exports.default = pRetry2;
    module.exports.AbortError = AbortError2;
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/lib/url.js
var require_url = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/lib/url.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.pathToFunc = pathToFunc;
    var hasOwn4 = Object.prototype.hasOwnProperty;
    function pathToFunc(pathPattern, options) {
      const paramRE = /\{([a-zA-Z0-9_][a-zA-Z0-9_-]*?)\}/g;
      return function buildURLPath(params = {}) {
        return pathPattern.replace(paramRE, function(_3, placeholder) {
          if (!hasOwn4.call(params, placeholder)) {
            throw new Error(`Parameter '${placeholder}' is required`);
          }
          const value = params[placeholder];
          if (typeof value !== "string" && typeof value !== "number") {
            throw new Error(`Parameter '${placeholder}' must be a string or number`);
          }
          return options?.charEncoding === "percent" ? encodeURIComponent(`${value}`) : `${value}`;
        });
      };
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/lib/config.js
var require_config = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/lib/config.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SDK_METADATA = exports.ServerList = exports.ServerEu = void 0;
    exports.serverURLFromOptions = serverURLFromOptions;
    var url_js_1 = require_url();
    exports.ServerEu = "eu";
    exports.ServerList = {
      [exports.ServerEu]: "https://api.mistral.ai"
    };
    function serverURLFromOptions(options) {
      let serverURL = options.serverURL;
      const params = {};
      if (!serverURL) {
        const server = options.server ?? exports.ServerEu;
        serverURL = exports.ServerList[server] || "";
      }
      const u5 = (0, url_js_1.pathToFunc)(serverURL)(params);
      return new URL(u5);
    }
    exports.SDK_METADATA = {
      language: "typescript",
      openapiDocVersion: "1.0.0",
      sdkVersion: "1.14.1",
      genVersion: "2.797.1",
      userAgent: "speakeasy-sdk/typescript 1.14.1 2.797.1 1.0.0 @mistralai/mistralai"
    };
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/lib/files.js
var require_files = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/lib/files.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.readableStreamToArrayBuffer = readableStreamToArrayBuffer;
    exports.getContentTypeFromFileName = getContentTypeFromFileName;
    async function readableStreamToArrayBuffer(readable) {
      const reader = readable.getReader();
      const chunks = [];
      let totalLength = 0;
      let done = false;
      while (!done) {
        const { value, done: doneReading } = await reader.read();
        if (doneReading) {
          done = true;
        } else {
          chunks.push(value);
          totalLength += value.length;
        }
      }
      const concatenatedChunks = new Uint8Array(totalLength);
      let offset = 0;
      for (const chunk of chunks) {
        concatenatedChunks.set(chunk, offset);
        offset += chunk.length;
      }
      return concatenatedChunks.buffer;
    }
    function getContentTypeFromFileName(fileName) {
      if (!fileName)
        return null;
      const ext2 = fileName.toLowerCase().split(".").pop();
      if (!ext2)
        return null;
      const mimeTypes = {
        json: "application/json",
        xml: "application/xml",
        html: "text/html",
        htm: "text/html",
        txt: "text/plain",
        csv: "text/csv",
        pdf: "application/pdf",
        png: "image/png",
        jpg: "image/jpeg",
        jpeg: "image/jpeg",
        gif: "image/gif",
        svg: "image/svg+xml",
        js: "application/javascript",
        css: "text/css",
        zip: "application/zip",
        tar: "application/x-tar",
        gz: "application/gzip",
        mp4: "video/mp4",
        mp3: "audio/mpeg",
        wav: "audio/wav",
        webp: "image/webp",
        ico: "image/x-icon",
        woff: "font/woff",
        woff2: "font/woff2",
        ttf: "font/ttf",
        otf: "font/otf"
      };
      return mimeTypes[ext2] || null;
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/lib/http.js
var require_http = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/lib/http.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.HTTPClient = void 0;
    exports.matchContentType = matchContentType;
    exports.matchStatusCode = matchStatusCode;
    exports.matchResponse = matchResponse;
    exports.isConnectionError = isConnectionError;
    exports.isTimeoutError = isTimeoutError;
    exports.isAbortError = isAbortError4;
    var DEFAULT_FETCHER = (input, init) => {
      if (init == null) {
        return fetch(input);
      } else {
        return fetch(input, init);
      }
    };
    var HTTPClient = class _HTTPClient {
      constructor(options = {}) {
        this.options = options;
        this.requestHooks = [];
        this.requestErrorHooks = [];
        this.responseHooks = [];
        this.fetcher = options.fetcher || DEFAULT_FETCHER;
      }
      async request(request) {
        let req = request;
        for (const hook of this.requestHooks) {
          const nextRequest = await hook(req);
          if (nextRequest) {
            req = nextRequest;
          }
        }
        try {
          const res = await this.fetcher(req);
          for (const hook of this.responseHooks) {
            await hook(res, req);
          }
          return res;
        } catch (err) {
          for (const hook of this.requestErrorHooks) {
            await hook(err, req);
          }
          throw err;
        }
      }
      addHook(...args) {
        if (args[0] === "beforeRequest") {
          this.requestHooks.push(args[1]);
        } else if (args[0] === "requestError") {
          this.requestErrorHooks.push(args[1]);
        } else if (args[0] === "response") {
          this.responseHooks.push(args[1]);
        } else {
          throw new Error(`Invalid hook type: ${args[0]}`);
        }
        return this;
      }
      removeHook(...args) {
        let target;
        if (args[0] === "beforeRequest") {
          target = this.requestHooks;
        } else if (args[0] === "requestError") {
          target = this.requestErrorHooks;
        } else if (args[0] === "response") {
          target = this.responseHooks;
        } else {
          throw new Error(`Invalid hook type: ${args[0]}`);
        }
        const index = target.findIndex((v4) => v4 === args[1]);
        if (index >= 0) {
          target.splice(index, 1);
        }
        return this;
      }
      clone() {
        const child = new _HTTPClient(this.options);
        child.requestHooks = this.requestHooks.slice();
        child.requestErrorHooks = this.requestErrorHooks.slice();
        child.responseHooks = this.responseHooks.slice();
        return child;
      }
    };
    exports.HTTPClient = HTTPClient;
    var mediaParamSeparator = /\s*;\s*/g;
    function matchContentType(response, pattern) {
      if (pattern === "*") {
        return true;
      }
      let contentType = response.headers.get("content-type")?.trim() || "application/octet-stream";
      contentType = contentType.toLowerCase();
      const wantParts = pattern.toLowerCase().trim().split(mediaParamSeparator);
      const [wantType = "", ...wantParams] = wantParts;
      if (wantType.split("/").length !== 2) {
        return false;
      }
      const gotParts = contentType.split(mediaParamSeparator);
      const [gotType = "", ...gotParams] = gotParts;
      const [type = "", subtype = ""] = gotType.split("/");
      if (!type || !subtype) {
        return false;
      }
      if (wantType !== "*/*" && gotType !== wantType && `${type}/*` !== wantType && `*/${subtype}` !== wantType) {
        return false;
      }
      if (gotParams.length < wantParams.length) {
        return false;
      }
      const params = new Set(gotParams);
      for (const wantParam of wantParams) {
        if (!params.has(wantParam)) {
          return false;
        }
      }
      return true;
    }
    var codeRangeRE = new RegExp("^[0-9]xx$", "i");
    function matchStatusCode(response, codes) {
      const actual = `${response.status}`;
      const expectedCodes = Array.isArray(codes) ? codes : [codes];
      if (!expectedCodes.length) {
        return false;
      }
      return expectedCodes.some((ec) => {
        const code = `${ec}`;
        if (code === "default") {
          return true;
        }
        if (!codeRangeRE.test(`${code}`)) {
          return code === actual;
        }
        const expectFamily = code.charAt(0);
        if (!expectFamily) {
          throw new Error("Invalid status code range");
        }
        const actualFamily = actual.charAt(0);
        if (!actualFamily) {
          throw new Error(`Invalid response status code: ${actual}`);
        }
        return actualFamily === expectFamily;
      });
    }
    function matchResponse(response, code, contentTypePattern) {
      return matchStatusCode(response, code) && matchContentType(response, contentTypePattern);
    }
    function isConnectionError(err) {
      if (typeof err !== "object" || err == null) {
        return false;
      }
      const isBrowserErr = err instanceof TypeError && err.message.toLowerCase().startsWith("failed to fetch");
      const isNodeErr = err instanceof TypeError && err.message.toLowerCase().startsWith("fetch failed");
      const isBunErr = "name" in err && err.name === "ConnectionError";
      const isGenericErr = "code" in err && typeof err.code === "string" && err.code.toLowerCase() === "econnreset";
      return isBrowserErr || isNodeErr || isGenericErr || isBunErr;
    }
    function isTimeoutError(err) {
      if (typeof err !== "object" || err == null) {
        return false;
      }
      const isNative = "name" in err && err.name === "TimeoutError";
      const isLegacyNative = "code" in err && err.code === 23;
      const isGenericErr = "code" in err && typeof err.code === "string" && err.code.toLowerCase() === "econnaborted";
      return isNative || isLegacyNative || isGenericErr;
    }
    function isAbortError4(err) {
      if (typeof err !== "object" || err == null) {
        return false;
      }
      const isNative = "name" in err && err.name === "AbortError";
      const isLegacyNative = "code" in err && err.code === 20;
      const isGenericErr = "code" in err && typeof err.code === "string" && err.code.toLowerCase() === "econnaborted";
      return isNative || isLegacyNative || isGenericErr;
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/hooks/custom_user_agent.js
var require_custom_user_agent = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/hooks/custom_user_agent.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CustomUserAgentHook = void 0;
    var config_1 = require_config();
    var CustomUserAgentHook = class {
      beforeRequest(_3, request) {
        const version5 = config_1.SDK_METADATA.sdkVersion;
        const ua = `mistral-client-typescript/${version5}`;
        request.headers.set("user-agent", ua);
        if (!request.headers.get("user-agent")) {
          request.headers.set("x-mistral-user-agent", ua);
        }
        return request;
      }
    };
    exports.CustomUserAgentHook = CustomUserAgentHook;
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/hooks/deprecation_warning.js
var require_deprecation_warning = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/hooks/deprecation_warning.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DeprecationWarningHook = void 0;
    var HEADER_MODEL_DEPRECATION_TIMESTAMP = "x-model-deprecation-timestamp";
    var DeprecationWarningHook = class {
      afterSuccess(_3, response) {
        if (response.headers.has(HEADER_MODEL_DEPRECATION_TIMESTAMP)) {
          response.clone().json().then((body) => {
            const model = body.model;
            console.warn(`WARNING: The model ${model} is deprecated and will be removed on ${response.headers.get(HEADER_MODEL_DEPRECATION_TIMESTAMP)}. Please refer to https://docs.mistral.ai/getting-started/models/#api-versioning for more information.`);
          });
        }
        return response;
      }
    };
    exports.DeprecationWarningHook = DeprecationWarningHook;
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/hooks/registration.js
var require_registration = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/hooks/registration.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.initHooks = initHooks;
    var custom_user_agent_1 = require_custom_user_agent();
    var deprecation_warning_1 = require_deprecation_warning();
    function initHooks(hooks) {
      const customUserAgentHook = new custom_user_agent_1.CustomUserAgentHook();
      hooks.registerBeforeRequestHook(customUserAgentHook);
      const deprecationWarningHook = new deprecation_warning_1.DeprecationWarningHook();
      hooks.registerAfterSuccessHook(deprecationWarningHook);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/hooks/hooks.js
var require_hooks = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/hooks/hooks.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SDKHooks = void 0;
    var registration_js_1 = require_registration();
    var SDKHooks = class {
      constructor() {
        this.sdkInitHooks = [];
        this.beforeCreateRequestHooks = [];
        this.beforeRequestHooks = [];
        this.afterSuccessHooks = [];
        this.afterErrorHooks = [];
        const presetHooks = [];
        for (const hook of presetHooks) {
          if ("sdkInit" in hook) {
            this.registerSDKInitHook(hook);
          }
          if ("beforeCreateRequest" in hook) {
            this.registerBeforeCreateRequestHook(hook);
          }
          if ("beforeRequest" in hook) {
            this.registerBeforeRequestHook(hook);
          }
          if ("afterSuccess" in hook) {
            this.registerAfterSuccessHook(hook);
          }
          if ("afterError" in hook) {
            this.registerAfterErrorHook(hook);
          }
        }
        (0, registration_js_1.initHooks)(this);
      }
      registerSDKInitHook(hook) {
        this.sdkInitHooks.push(hook);
      }
      registerBeforeCreateRequestHook(hook) {
        this.beforeCreateRequestHooks.push(hook);
      }
      registerBeforeRequestHook(hook) {
        this.beforeRequestHooks.push(hook);
      }
      registerAfterSuccessHook(hook) {
        this.afterSuccessHooks.push(hook);
      }
      registerAfterErrorHook(hook) {
        this.afterErrorHooks.push(hook);
      }
      sdkInit(opts) {
        return this.sdkInitHooks.reduce((opts2, hook) => hook.sdkInit(opts2), opts);
      }
      beforeCreateRequest(hookCtx, input) {
        let inp = input;
        for (const hook of this.beforeCreateRequestHooks) {
          inp = hook.beforeCreateRequest(hookCtx, inp);
        }
        return inp;
      }
      async beforeRequest(hookCtx, request) {
        let req = request;
        for (const hook of this.beforeRequestHooks) {
          req = await hook.beforeRequest(hookCtx, req);
        }
        return req;
      }
      async afterSuccess(hookCtx, response) {
        let res = response;
        for (const hook of this.afterSuccessHooks) {
          res = await hook.afterSuccess(hookCtx, res);
        }
        return res;
      }
      async afterError(hookCtx, response, error) {
        let res = response;
        let err = error;
        for (const hook of this.afterErrorHooks) {
          const result = await hook.afterError(hookCtx, res, err);
          res = result.response;
          err = result.error;
        }
        return { response: res, error: err };
      }
    };
    exports.SDKHooks = SDKHooks;
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/errors/httpclienterrors.js
var require_httpclienterrors = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/errors/httpclienterrors.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ConnectionError = exports.RequestTimeoutError = exports.RequestAbortedError = exports.InvalidRequestError = exports.UnexpectedClientError = exports.HTTPClientError = void 0;
    var HTTPClientError = class extends Error {
      constructor(message, opts) {
        let msg = message;
        if (opts?.cause) {
          msg += `: ${opts.cause}`;
        }
        super(msg, opts);
        this.name = "HTTPClientError";
        if (typeof this.cause === "undefined") {
          this.cause = opts?.cause;
        }
      }
    };
    exports.HTTPClientError = HTTPClientError;
    var UnexpectedClientError = class extends HTTPClientError {
      constructor() {
        super(...arguments);
        this.name = "UnexpectedClientError";
      }
    };
    exports.UnexpectedClientError = UnexpectedClientError;
    var InvalidRequestError = class extends HTTPClientError {
      constructor() {
        super(...arguments);
        this.name = "InvalidRequestError";
      }
    };
    exports.InvalidRequestError = InvalidRequestError;
    var RequestAbortedError = class extends HTTPClientError {
      constructor() {
        super(...arguments);
        this.name = "RequestAbortedError";
      }
    };
    exports.RequestAbortedError = RequestAbortedError;
    var RequestTimeoutError = class extends HTTPClientError {
      constructor() {
        super(...arguments);
        this.name = "RequestTimeoutError";
      }
    };
    exports.RequestTimeoutError = RequestTimeoutError;
    var ConnectionError = class extends HTTPClientError {
      constructor() {
        super(...arguments);
        this.name = "ConnectionError";
      }
    };
    exports.ConnectionError = ConnectionError;
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/types/fp.js
var require_fp = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/types/fp.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OK = OK3;
    exports.ERR = ERR;
    exports.unwrap = unwrap;
    exports.unwrapAsync = unwrapAsync;
    function OK3(value) {
      return { ok: true, value };
    }
    function ERR(error) {
      return { ok: false, error };
    }
    function unwrap(r8) {
      if (!r8.ok) {
        throw r8.error;
      }
      return r8.value;
    }
    async function unwrapAsync(pr) {
      const r8 = await pr;
      if (!r8.ok) {
        throw r8.error;
      }
      return r8.value;
    }
  }
});

// ../pi-mono/node_modules/zod/v3/helpers/util.cjs
var require_util = __commonJS({
  "../pi-mono/node_modules/zod/v3/helpers/util.cjs"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.getParsedType = exports.ZodParsedType = exports.objectUtil = exports.util = void 0;
    var util3;
    (function(util4) {
      util4.assertEqual = (_3) => {
      };
      function assertIs(_arg) {
      }
      util4.assertIs = assertIs;
      function assertNever3(_x) {
        throw new Error();
      }
      util4.assertNever = assertNever3;
      util4.arrayToEnum = (items) => {
        const obj = {};
        for (const item of items) {
          obj[item] = item;
        }
        return obj;
      };
      util4.getValidEnumValues = (obj) => {
        const validKeys = util4.objectKeys(obj).filter((k2) => typeof obj[obj[k2]] !== "number");
        const filtered = {};
        for (const k2 of validKeys) {
          filtered[k2] = obj[k2];
        }
        return util4.objectValues(filtered);
      };
      util4.objectValues = (obj) => {
        return util4.objectKeys(obj).map(function(e9) {
          return obj[e9];
        });
      };
      util4.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
        const keys2 = [];
        for (const key in object) {
          if (Object.prototype.hasOwnProperty.call(object, key)) {
            keys2.push(key);
          }
        }
        return keys2;
      };
      util4.find = (arr, checker) => {
        for (const item of arr) {
          if (checker(item))
            return item;
        }
        return void 0;
      };
      util4.isInteger = typeof Number.isInteger === "function" ? (val2) => Number.isInteger(val2) : (val2) => typeof val2 === "number" && Number.isFinite(val2) && Math.floor(val2) === val2;
      function joinValues(array, separator = " | ") {
        return array.map((val2) => typeof val2 === "string" ? `'${val2}'` : val2).join(separator);
      }
      util4.joinValues = joinValues;
      util4.jsonStringifyReplacer = (_3, value) => {
        if (typeof value === "bigint") {
          return value.toString();
        }
        return value;
      };
    })(util3 || (exports.util = util3 = {}));
    var objectUtil3;
    (function(objectUtil4) {
      objectUtil4.mergeShapes = (first, second) => {
        return {
          ...first,
          ...second
          // second overwrites first
        };
      };
    })(objectUtil3 || (exports.objectUtil = objectUtil3 = {}));
    exports.ZodParsedType = util3.arrayToEnum([
      "string",
      "nan",
      "number",
      "integer",
      "float",
      "boolean",
      "date",
      "bigint",
      "symbol",
      "function",
      "undefined",
      "null",
      "array",
      "object",
      "unknown",
      "promise",
      "void",
      "never",
      "map",
      "set"
    ]);
    var getParsedType3 = (data) => {
      const t6 = typeof data;
      switch (t6) {
        case "undefined":
          return exports.ZodParsedType.undefined;
        case "string":
          return exports.ZodParsedType.string;
        case "number":
          return Number.isNaN(data) ? exports.ZodParsedType.nan : exports.ZodParsedType.number;
        case "boolean":
          return exports.ZodParsedType.boolean;
        case "function":
          return exports.ZodParsedType.function;
        case "bigint":
          return exports.ZodParsedType.bigint;
        case "symbol":
          return exports.ZodParsedType.symbol;
        case "object":
          if (Array.isArray(data)) {
            return exports.ZodParsedType.array;
          }
          if (data === null) {
            return exports.ZodParsedType.null;
          }
          if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
            return exports.ZodParsedType.promise;
          }
          if (typeof Map !== "undefined" && data instanceof Map) {
            return exports.ZodParsedType.map;
          }
          if (typeof Set !== "undefined" && data instanceof Set) {
            return exports.ZodParsedType.set;
          }
          if (typeof Date !== "undefined" && data instanceof Date) {
            return exports.ZodParsedType.date;
          }
          return exports.ZodParsedType.object;
        default:
          return exports.ZodParsedType.unknown;
      }
    };
    exports.getParsedType = getParsedType3;
  }
});

// ../pi-mono/node_modules/zod/v3/ZodError.cjs
var require_ZodError = __commonJS({
  "../pi-mono/node_modules/zod/v3/ZodError.cjs"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ZodError = exports.quotelessJson = exports.ZodIssueCode = void 0;
    var util_js_1 = require_util();
    exports.ZodIssueCode = util_js_1.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 quotelessJson2 = (obj) => {
      const json2 = JSON.stringify(obj, null, 2);
      return json2.replace(/"([^"]+)":/g, "$1:");
    };
    exports.quotelessJson = quotelessJson2;
    var ZodError3 = class _ZodError extends Error {
      get errors() {
        return this.issues;
      }
      constructor(issues) {
        super();
        this.issues = [];
        this.addIssue = (sub2) => {
          this.issues = [...this.issues, sub2];
        };
        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 i7 = 0;
              while (i7 < issue.path.length) {
                const el = issue.path[i7];
                const terminal = i7 === 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];
                i7++;
              }
            }
          }
        };
        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_js_1.util.jsonStringifyReplacer, 2);
      }
      get isEmpty() {
        return this.issues.length === 0;
      }
      flatten(mapper = (issue) => issue.message) {
        const fieldErrors = /* @__PURE__ */ Object.create(null);
        const formErrors = [];
        for (const sub2 of this.issues) {
          if (sub2.path.length > 0) {
            const firstEl = sub2.path[0];
            fieldErrors[firstEl] = fieldErrors[firstEl] || [];
            fieldErrors[firstEl].push(mapper(sub2));
          } else {
            formErrors.push(mapper(sub2));
          }
        }
        return { formErrors, fieldErrors };
      }
      get formErrors() {
        return this.flatten();
      }
    };
    exports.ZodError = ZodError3;
    ZodError3.create = (issues) => {
      const error = new ZodError3(issues);
      return error;
    };
  }
});

// ../pi-mono/node_modules/zod/v3/locales/en.cjs
var require_en = __commonJS({
  "../pi-mono/node_modules/zod/v3/locales/en.cjs"(exports, module) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    var ZodError_js_1 = require_ZodError();
    var util_js_1 = require_util();
    var errorMap3 = (issue, _ctx) => {
      let message;
      switch (issue.code) {
        case ZodError_js_1.ZodIssueCode.invalid_type:
          if (issue.received === util_js_1.ZodParsedType.undefined) {
            message = "Required";
          } else {
            message = `Expected ${issue.expected}, received ${issue.received}`;
          }
          break;
        case ZodError_js_1.ZodIssueCode.invalid_literal:
          message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util_js_1.util.jsonStringifyReplacer)}`;
          break;
        case ZodError_js_1.ZodIssueCode.unrecognized_keys:
          message = `Unrecognized key(s) in object: ${util_js_1.util.joinValues(issue.keys, ", ")}`;
          break;
        case ZodError_js_1.ZodIssueCode.invalid_union:
          message = `Invalid input`;
          break;
        case ZodError_js_1.ZodIssueCode.invalid_union_discriminator:
          message = `Invalid discriminator value. Expected ${util_js_1.util.joinValues(issue.options)}`;
          break;
        case ZodError_js_1.ZodIssueCode.invalid_enum_value:
          message = `Invalid enum value. Expected ${util_js_1.util.joinValues(issue.options)}, received '${issue.received}'`;
          break;
        case ZodError_js_1.ZodIssueCode.invalid_arguments:
          message = `Invalid function arguments`;
          break;
        case ZodError_js_1.ZodIssueCode.invalid_return_type:
          message = `Invalid function return type`;
          break;
        case ZodError_js_1.ZodIssueCode.invalid_date:
          message = `Invalid date`;
          break;
        case ZodError_js_1.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_js_1.util.assertNever(issue.validation);
            }
          } else if (issue.validation !== "regex") {
            message = `Invalid ${issue.validation}`;
          } else {
            message = "Invalid";
          }
          break;
        case ZodError_js_1.ZodIssueCode.too_small:
          if (issue.type === "array")
            message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
          else if (issue.type === "string")
            message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
          else if (issue.type === "number")
            message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
          else if (issue.type === "bigint")
            message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
          else if (issue.type === "date")
            message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
          else
            message = "Invalid input";
          break;
        case ZodError_js_1.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 ZodError_js_1.ZodIssueCode.custom:
          message = `Invalid input`;
          break;
        case ZodError_js_1.ZodIssueCode.invalid_intersection_types:
          message = `Intersection results could not be merged`;
          break;
        case ZodError_js_1.ZodIssueCode.not_multiple_of:
          message = `Number must be a multiple of ${issue.multipleOf}`;
          break;
        case ZodError_js_1.ZodIssueCode.not_finite:
          message = "Number must be finite";
          break;
        default:
          message = _ctx.defaultError;
          util_js_1.util.assertNever(issue);
      }
      return { message };
    };
    exports.default = errorMap3;
    module.exports = exports.default;
  }
});

// ../pi-mono/node_modules/zod/v3/errors.cjs
var require_errors = __commonJS({
  "../pi-mono/node_modules/zod/v3/errors.cjs"(exports) {
    "use strict";
    init_process_shim();
    var __importDefault = exports && exports.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.defaultErrorMap = void 0;
    exports.setErrorMap = setErrorMap2;
    exports.getErrorMap = getErrorMap3;
    var en_js_1 = __importDefault(require_en());
    exports.defaultErrorMap = en_js_1.default;
    var overrideErrorMap3 = en_js_1.default;
    function setErrorMap2(map) {
      overrideErrorMap3 = map;
    }
    function getErrorMap3() {
      return overrideErrorMap3;
    }
  }
});

// ../pi-mono/node_modules/zod/v3/helpers/parseUtil.cjs
var require_parseUtil = __commonJS({
  "../pi-mono/node_modules/zod/v3/helpers/parseUtil.cjs"(exports) {
    "use strict";
    init_process_shim();
    var __importDefault = exports && exports.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.isAsync = exports.isValid = exports.isDirty = exports.isAborted = exports.OK = exports.DIRTY = exports.INVALID = exports.ParseStatus = exports.EMPTY_PATH = exports.makeIssue = void 0;
    exports.addIssueToContext = addIssueToContext3;
    var errors_js_1 = require_errors();
    var en_js_1 = __importDefault(require_en());
    var makeIssue3 = (params) => {
      const { data, path: path6, errorMaps, issueData } = params;
      const fullPath = [...path6, ...issueData.path || []];
      const fullIssue = {
        ...issueData,
        path: fullPath
      };
      if (issueData.message !== void 0) {
        return {
          ...issueData,
          path: fullPath,
          message: issueData.message
        };
      }
      let errorMessage = "";
      const maps = errorMaps.filter((m4) => !!m4).slice().reverse();
      for (const map of maps) {
        errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
      }
      return {
        ...issueData,
        path: fullPath,
        message: errorMessage
      };
    };
    exports.makeIssue = makeIssue3;
    exports.EMPTY_PATH = [];
    function addIssueToContext3(ctx, issueData) {
      const overrideMap = (0, errors_js_1.getErrorMap)();
      const issue = (0, exports.makeIssue)({
        issueData,
        data: ctx.data,
        path: ctx.path,
        errorMaps: [
          ctx.common.contextualErrorMap,
          // contextual error map is first priority
          ctx.schemaErrorMap,
          // then schema-bound map if available
          overrideMap,
          // then global override map
          overrideMap === en_js_1.default ? void 0 : en_js_1.default
          // then global default map
        ].filter((x2) => !!x2)
      });
      ctx.common.issues.push(issue);
    }
    var ParseStatus3 = 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 s6 of results) {
          if (s6.status === "aborted")
            return exports.INVALID;
          if (s6.status === "dirty")
            status.dirty();
          arrayValue.push(s6.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 exports.INVALID;
          if (value.status === "aborted")
            return exports.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 };
      }
    };
    exports.ParseStatus = ParseStatus3;
    exports.INVALID = Object.freeze({
      status: "aborted"
    });
    var DIRTY3 = (value) => ({ status: "dirty", value });
    exports.DIRTY = DIRTY3;
    var OK3 = (value) => ({ status: "valid", value });
    exports.OK = OK3;
    var isAborted3 = (x2) => x2.status === "aborted";
    exports.isAborted = isAborted3;
    var isDirty3 = (x2) => x2.status === "dirty";
    exports.isDirty = isDirty3;
    var isValid3 = (x2) => x2.status === "valid";
    exports.isValid = isValid3;
    var isAsync3 = (x2) => typeof Promise !== "undefined" && x2 instanceof Promise;
    exports.isAsync = isAsync3;
  }
});

// ../pi-mono/node_modules/zod/v3/helpers/typeAliases.cjs
var require_typeAliases = __commonJS({
  "../pi-mono/node_modules/zod/v3/helpers/typeAliases.cjs"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// ../pi-mono/node_modules/zod/v3/helpers/errorUtil.cjs
var require_errorUtil = __commonJS({
  "../pi-mono/node_modules/zod/v3/helpers/errorUtil.cjs"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.errorUtil = void 0;
    var errorUtil3;
    (function(errorUtil4) {
      errorUtil4.errToObj = (message) => typeof message === "string" ? { message } : message || {};
      errorUtil4.toString = (message) => typeof message === "string" ? message : message?.message;
    })(errorUtil3 || (exports.errorUtil = errorUtil3 = {}));
  }
});

// ../pi-mono/node_modules/zod/v3/types.cjs
var require_types = __commonJS({
  "../pi-mono/node_modules/zod/v3/types.cjs"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.discriminatedUnion = exports.date = exports.boolean = exports.bigint = exports.array = exports.any = exports.coerce = exports.ZodFirstPartyTypeKind = exports.late = exports.ZodSchema = exports.Schema = exports.ZodReadonly = exports.ZodPipeline = exports.ZodBranded = exports.BRAND = exports.ZodNaN = exports.ZodCatch = exports.ZodDefault = exports.ZodNullable = exports.ZodOptional = exports.ZodTransformer = exports.ZodEffects = exports.ZodPromise = exports.ZodNativeEnum = exports.ZodEnum = exports.ZodLiteral = exports.ZodLazy = exports.ZodFunction = exports.ZodSet = exports.ZodMap = exports.ZodRecord = exports.ZodTuple = exports.ZodIntersection = exports.ZodDiscriminatedUnion = exports.ZodUnion = exports.ZodObject = exports.ZodArray = exports.ZodVoid = exports.ZodNever = exports.ZodUnknown = exports.ZodAny = exports.ZodNull = exports.ZodUndefined = exports.ZodSymbol = exports.ZodDate = exports.ZodBoolean = exports.ZodBigInt = exports.ZodNumber = exports.ZodString = exports.ZodType = void 0;
    exports.NEVER = exports.void = exports.unknown = exports.union = exports.undefined = exports.tuple = exports.transformer = exports.symbol = exports.string = exports.strictObject = exports.set = exports.record = exports.promise = exports.preprocess = exports.pipeline = exports.ostring = exports.optional = exports.onumber = exports.oboolean = exports.object = exports.number = exports.nullable = exports.null = exports.never = exports.nativeEnum = exports.nan = exports.map = exports.literal = exports.lazy = exports.intersection = exports.instanceof = exports.function = exports.enum = exports.effect = void 0;
    exports.datetimeRegex = datetimeRegex3;
    exports.custom = custom2;
    var ZodError_js_1 = require_ZodError();
    var errors_js_1 = require_errors();
    var errorUtil_js_1 = require_errorUtil();
    var parseUtil_js_1 = require_parseUtil();
    var util_js_1 = require_util();
    var ParseInputLazyPath3 = class {
      constructor(parent, value, path6, key) {
        this._cachedPath = [];
        this.parent = parent;
        this.data = value;
        this._path = path6;
        this._key = key;
      }
      get path() {
        if (!this._cachedPath.length) {
          if (Array.isArray(this._key)) {
            this._cachedPath.push(...this._path, ...this._key);
          } else {
            this._cachedPath.push(...this._path, this._key);
          }
        }
        return this._cachedPath;
      }
    };
    var handleResult3 = (ctx, result) => {
      if ((0, parseUtil_js_1.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_js_1.ZodError(ctx.common.issues);
            this._error = error;
            return this._error;
          }
        };
      }
    };
    function processCreateParams3(params) {
      if (!params)
        return {};
      const { errorMap: errorMap3, invalid_type_error, required_error, description } = params;
      if (errorMap3 && (invalid_type_error || required_error)) {
        throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
      }
      if (errorMap3)
        return { errorMap: errorMap3, description };
      const customMap = (iss, ctx) => {
        const { message } = params;
        if (iss.code === "invalid_enum_value") {
          return { message: message ?? ctx.defaultError };
        }
        if (typeof ctx.data === "undefined") {
          return { message: message ?? required_error ?? ctx.defaultError };
        }
        if (iss.code !== "invalid_type")
          return { message: ctx.defaultError };
        return { message: message ?? invalid_type_error ?? ctx.defaultError };
      };
      return { errorMap: customMap, description };
    }
    var ZodType3 = class {
      get description() {
        return this._def.description;
      }
      _getType(input) {
        return (0, util_js_1.getParsedType)(input.data);
      }
      _getOrReturnCtx(input, ctx) {
        return ctx || {
          common: input.parent.common,
          data: input.data,
          parsedType: (0, util_js_1.getParsedType)(input.data),
          schemaErrorMap: this._def.errorMap,
          path: input.path,
          parent: input.parent
        };
      }
      _processInputParams(input) {
        return {
          status: new parseUtil_js_1.ParseStatus(),
          ctx: {
            common: input.parent.common,
            data: input.data,
            parsedType: (0, util_js_1.getParsedType)(input.data),
            schemaErrorMap: this._def.errorMap,
            path: input.path,
            parent: input.parent
          }
        };
      }
      _parseSync(input) {
        const result = this._parse(input);
        if ((0, parseUtil_js_1.isAsync)(result)) {
          throw new Error("Synchronous parse encountered promise.");
        }
        return result;
      }
      _parseAsync(input) {
        const result = this._parse(input);
        return Promise.resolve(result);
      }
      parse(data, params) {
        const result = this.safeParse(data, params);
        if (result.success)
          return result.data;
        throw result.error;
      }
      safeParse(data, params) {
        const ctx = {
          common: {
            issues: [],
            async: params?.async ?? false,
            contextualErrorMap: params?.errorMap
          },
          path: params?.path || [],
          schemaErrorMap: this._def.errorMap,
          parent: null,
          data,
          parsedType: (0, util_js_1.getParsedType)(data)
        };
        const result = this._parseSync({ data, path: ctx.path, parent: ctx });
        return handleResult3(ctx, result);
      }
      "~validate"(data) {
        const ctx = {
          common: {
            issues: [],
            async: !!this["~standard"].async
          },
          path: [],
          schemaErrorMap: this._def.errorMap,
          parent: null,
          data,
          parsedType: (0, util_js_1.getParsedType)(data)
        };
        if (!this["~standard"].async) {
          try {
            const result = this._parseSync({ data, path: [], parent: ctx });
            return (0, parseUtil_js_1.isValid)(result) ? {
              value: result.value
            } : {
              issues: ctx.common.issues
            };
          } catch (err) {
            if (err?.message?.toLowerCase()?.includes("encountered")) {
              this["~standard"].async = true;
            }
            ctx.common = {
              issues: [],
              async: true
            };
          }
        }
        return this._parseAsync({ data, path: [], parent: ctx }).then((result) => (0, parseUtil_js_1.isValid)(result) ? {
          value: result.value
        } : {
          issues: ctx.common.issues
        });
      }
      async parseAsync(data, params) {
        const result = await this.safeParseAsync(data, params);
        if (result.success)
          return result.data;
        throw result.error;
      }
      async safeParseAsync(data, params) {
        const ctx = {
          common: {
            issues: [],
            contextualErrorMap: params?.errorMap,
            async: true
          },
          path: params?.path || [],
          schemaErrorMap: this._def.errorMap,
          parent: null,
          data,
          parsedType: (0, util_js_1.getParsedType)(data)
        };
        const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
        const result = await ((0, parseUtil_js_1.isAsync)(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
        return handleResult3(ctx, result);
      }
      refine(check, message) {
        const getIssueProperties = (val2) => {
          if (typeof message === "string" || typeof message === "undefined") {
            return { message };
          } else if (typeof message === "function") {
            return message(val2);
          } else {
            return message;
          }
        };
        return this._refinement((val2, ctx) => {
          const result = check(val2);
          const setError = () => ctx.addIssue({
            code: ZodError_js_1.ZodIssueCode.custom,
            ...getIssueProperties(val2)
          });
          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((val2, ctx) => {
          if (!check(val2)) {
            ctx.addIssue(typeof refinementData === "function" ? refinementData(val2, ctx) : refinementData);
            return false;
          } else {
            return true;
          }
        });
      }
      _refinement(refinement) {
        return new ZodEffects3({
          schema: this,
          typeName: ZodFirstPartyTypeKind3.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 ZodOptional3.create(this, this._def);
      }
      nullable() {
        return ZodNullable3.create(this, this._def);
      }
      nullish() {
        return this.nullable().optional();
      }
      array() {
        return ZodArray3.create(this);
      }
      promise() {
        return ZodPromise3.create(this, this._def);
      }
      or(option) {
        return ZodUnion3.create([this, option], this._def);
      }
      and(incoming) {
        return ZodIntersection3.create(this, incoming, this._def);
      }
      transform(transform) {
        return new ZodEffects3({
          ...processCreateParams3(this._def),
          schema: this,
          typeName: ZodFirstPartyTypeKind3.ZodEffects,
          effect: { type: "transform", transform }
        });
      }
      default(def) {
        const defaultValueFunc = typeof def === "function" ? def : () => def;
        return new ZodDefault3({
          ...processCreateParams3(this._def),
          innerType: this,
          defaultValue: defaultValueFunc,
          typeName: ZodFirstPartyTypeKind3.ZodDefault
        });
      }
      brand() {
        return new ZodBranded3({
          typeName: ZodFirstPartyTypeKind3.ZodBranded,
          type: this,
          ...processCreateParams3(this._def)
        });
      }
      catch(def) {
        const catchValueFunc = typeof def === "function" ? def : () => def;
        return new ZodCatch3({
          ...processCreateParams3(this._def),
          innerType: this,
          catchValue: catchValueFunc,
          typeName: ZodFirstPartyTypeKind3.ZodCatch
        });
      }
      describe(description) {
        const This = this.constructor;
        return new This({
          ...this._def,
          description
        });
      }
      pipe(target) {
        return ZodPipeline3.create(this, target);
      }
      readonly() {
        return ZodReadonly3.create(this);
      }
      isOptional() {
        return this.safeParse(void 0).success;
      }
      isNullable() {
        return this.safeParse(null).success;
      }
    };
    exports.ZodType = ZodType3;
    exports.Schema = ZodType3;
    exports.ZodSchema = ZodType3;
    var cuidRegex3 = /^c[^\s-]{8,}$/i;
    var cuid2Regex3 = /^[0-9a-z]+$/;
    var ulidRegex3 = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
    var uuidRegex3 = /^[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 nanoidRegex3 = /^[a-z0-9_-]{21}$/i;
    var jwtRegex3 = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
    var durationRegex3 = /^[-+]?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 emailRegex3 = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
    var _emojiRegex3 = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
    var emojiRegex5;
    var ipv4Regex3 = /^(?:(?: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 ipv4CidrRegex3 = /^(?:(?: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 ipv6Regex3 = /^(([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 ipv6CidrRegex3 = /^(([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 base64Regex3 = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
    var base64urlRegex3 = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
    var dateRegexSource3 = `((\\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 dateRegex3 = new RegExp(`^${dateRegexSource3}$`);
    function timeRegexSource3(args) {
      let secondsRegexSource = `[0-5]\\d`;
      if (args.precision) {
        secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
      } else if (args.precision == null) {
        secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
      }
      const secondsQuantifier = args.precision ? "+" : "?";
      return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
    }
    function timeRegex3(args) {
      return new RegExp(`^${timeRegexSource3(args)}$`);
    }
    function datetimeRegex3(args) {
      let regex = `${dateRegexSource3}T${timeRegexSource3(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 isValidIP3(ip, version5) {
      if ((version5 === "v4" || !version5) && ipv4Regex3.test(ip)) {
        return true;
      }
      if ((version5 === "v6" || !version5) && ipv6Regex3.test(ip)) {
        return true;
      }
      return false;
    }
    function isValidJWT3(jwt, alg) {
      if (!jwtRegex3.test(jwt))
        return false;
      try {
        const [header] = jwt.split(".");
        if (!header)
          return false;
        const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
        const decoded = JSON.parse(atob(base64));
        if (typeof decoded !== "object" || decoded === null)
          return false;
        if ("typ" in decoded && decoded?.typ !== "JWT")
          return false;
        if (!decoded.alg)
          return false;
        if (alg && decoded.alg !== alg)
          return false;
        return true;
      } catch {
        return false;
      }
    }
    function isValidCidr3(ip, version5) {
      if ((version5 === "v4" || !version5) && ipv4CidrRegex3.test(ip)) {
        return true;
      }
      if ((version5 === "v6" || !version5) && ipv6CidrRegex3.test(ip)) {
        return true;
      }
      return false;
    }
    var ZodString3 = class _ZodString extends ZodType3 {
      _parse(input) {
        if (this._def.coerce) {
          input.data = String(input.data);
        }
        const parsedType = this._getType(input);
        if (parsedType !== util_js_1.ZodParsedType.string) {
          const ctx2 = this._getOrReturnCtx(input);
          (0, parseUtil_js_1.addIssueToContext)(ctx2, {
            code: ZodError_js_1.ZodIssueCode.invalid_type,
            expected: util_js_1.ZodParsedType.string,
            received: ctx2.parsedType
          });
          return parseUtil_js_1.INVALID;
        }
        const status = new parseUtil_js_1.ParseStatus();
        let ctx = void 0;
        for (const check of this._def.checks) {
          if (check.kind === "min") {
            if (input.data.length < check.value) {
              ctx = this._getOrReturnCtx(input, ctx);
              (0, parseUtil_js_1.addIssueToContext)(ctx, {
                code: ZodError_js_1.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);
              (0, parseUtil_js_1.addIssueToContext)(ctx, {
                code: ZodError_js_1.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) {
                (0, parseUtil_js_1.addIssueToContext)(ctx, {
                  code: ZodError_js_1.ZodIssueCode.too_big,
                  maximum: check.value,
                  type: "string",
                  inclusive: true,
                  exact: true,
                  message: check.message
                });
              } else if (tooSmall) {
                (0, parseUtil_js_1.addIssueToContext)(ctx, {
                  code: ZodError_js_1.ZodIssueCode.too_small,
                  minimum: check.value,
                  type: "string",
                  inclusive: true,
                  exact: true,
                  message: check.message
                });
              }
              status.dirty();
            }
          } else if (check.kind === "email") {
            if (!emailRegex3.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              (0, parseUtil_js_1.addIssueToContext)(ctx, {
                validation: "email",
                code: ZodError_js_1.ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "emoji") {
            if (!emojiRegex5) {
              emojiRegex5 = new RegExp(_emojiRegex3, "u");
            }
            if (!emojiRegex5.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              (0, parseUtil_js_1.addIssueToContext)(ctx, {
                validation: "emoji",
                code: ZodError_js_1.ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "uuid") {
            if (!uuidRegex3.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              (0, parseUtil_js_1.addIssueToContext)(ctx, {
                validation: "uuid",
                code: ZodError_js_1.ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "nanoid") {
            if (!nanoidRegex3.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              (0, parseUtil_js_1.addIssueToContext)(ctx, {
                validation: "nanoid",
                code: ZodError_js_1.ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "cuid") {
            if (!cuidRegex3.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              (0, parseUtil_js_1.addIssueToContext)(ctx, {
                validation: "cuid",
                code: ZodError_js_1.ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "cuid2") {
            if (!cuid2Regex3.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              (0, parseUtil_js_1.addIssueToContext)(ctx, {
                validation: "cuid2",
                code: ZodError_js_1.ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "ulid") {
            if (!ulidRegex3.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              (0, parseUtil_js_1.addIssueToContext)(ctx, {
                validation: "ulid",
                code: ZodError_js_1.ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "url") {
            try {
              new URL(input.data);
            } catch {
              ctx = this._getOrReturnCtx(input, ctx);
              (0, parseUtil_js_1.addIssueToContext)(ctx, {
                validation: "url",
                code: ZodError_js_1.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);
              (0, parseUtil_js_1.addIssueToContext)(ctx, {
                validation: "regex",
                code: ZodError_js_1.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);
              (0, parseUtil_js_1.addIssueToContext)(ctx, {
                code: ZodError_js_1.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);
              (0, parseUtil_js_1.addIssueToContext)(ctx, {
                code: ZodError_js_1.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);
              (0, parseUtil_js_1.addIssueToContext)(ctx, {
                code: ZodError_js_1.ZodIssueCode.invalid_string,
                validation: { endsWith: check.value },
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "datetime") {
            const regex = datetimeRegex3(check);
            if (!regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              (0, parseUtil_js_1.addIssueToContext)(ctx, {
                code: ZodError_js_1.ZodIssueCode.invalid_string,
                validation: "datetime",
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "date") {
            const regex = dateRegex3;
            if (!regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              (0, parseUtil_js_1.addIssueToContext)(ctx, {
                code: ZodError_js_1.ZodIssueCode.invalid_string,
                validation: "date",
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "time") {
            const regex = timeRegex3(check);
            if (!regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              (0, parseUtil_js_1.addIssueToContext)(ctx, {
                code: ZodError_js_1.ZodIssueCode.invalid_string,
                validation: "time",
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "duration") {
            if (!durationRegex3.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              (0, parseUtil_js_1.addIssueToContext)(ctx, {
                validation: "duration",
                code: ZodError_js_1.ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "ip") {
            if (!isValidIP3(input.data, check.version)) {
              ctx = this._getOrReturnCtx(input, ctx);
              (0, parseUtil_js_1.addIssueToContext)(ctx, {
                validation: "ip",
                code: ZodError_js_1.ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "jwt") {
            if (!isValidJWT3(input.data, check.alg)) {
              ctx = this._getOrReturnCtx(input, ctx);
              (0, parseUtil_js_1.addIssueToContext)(ctx, {
                validation: "jwt",
                code: ZodError_js_1.ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "cidr") {
            if (!isValidCidr3(input.data, check.version)) {
              ctx = this._getOrReturnCtx(input, ctx);
              (0, parseUtil_js_1.addIssueToContext)(ctx, {
                validation: "cidr",
                code: ZodError_js_1.ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "base64") {
            if (!base64Regex3.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              (0, parseUtil_js_1.addIssueToContext)(ctx, {
                validation: "base64",
                code: ZodError_js_1.ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "base64url") {
            if (!base64urlRegex3.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              (0, parseUtil_js_1.addIssueToContext)(ctx, {
                validation: "base64url",
                code: ZodError_js_1.ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else {
            util_js_1.util.assertNever(check);
          }
        }
        return { status: status.value, value: input.data };
      }
      _regex(regex, validation, message) {
        return this.refinement((data) => regex.test(data), {
          validation,
          code: ZodError_js_1.ZodIssueCode.invalid_string,
          ...errorUtil_js_1.errorUtil.errToObj(message)
        });
      }
      _addCheck(check) {
        return new _ZodString({
          ...this._def,
          checks: [...this._def.checks, check]
        });
      }
      email(message) {
        return this._addCheck({ kind: "email", ...errorUtil_js_1.errorUtil.errToObj(message) });
      }
      url(message) {
        return this._addCheck({ kind: "url", ...errorUtil_js_1.errorUtil.errToObj(message) });
      }
      emoji(message) {
        return this._addCheck({ kind: "emoji", ...errorUtil_js_1.errorUtil.errToObj(message) });
      }
      uuid(message) {
        return this._addCheck({ kind: "uuid", ...errorUtil_js_1.errorUtil.errToObj(message) });
      }
      nanoid(message) {
        return this._addCheck({ kind: "nanoid", ...errorUtil_js_1.errorUtil.errToObj(message) });
      }
      cuid(message) {
        return this._addCheck({ kind: "cuid", ...errorUtil_js_1.errorUtil.errToObj(message) });
      }
      cuid2(message) {
        return this._addCheck({ kind: "cuid2", ...errorUtil_js_1.errorUtil.errToObj(message) });
      }
      ulid(message) {
        return this._addCheck({ kind: "ulid", ...errorUtil_js_1.errorUtil.errToObj(message) });
      }
      base64(message) {
        return this._addCheck({ kind: "base64", ...errorUtil_js_1.errorUtil.errToObj(message) });
      }
      base64url(message) {
        return this._addCheck({
          kind: "base64url",
          ...errorUtil_js_1.errorUtil.errToObj(message)
        });
      }
      jwt(options) {
        return this._addCheck({ kind: "jwt", ...errorUtil_js_1.errorUtil.errToObj(options) });
      }
      ip(options) {
        return this._addCheck({ kind: "ip", ...errorUtil_js_1.errorUtil.errToObj(options) });
      }
      cidr(options) {
        return this._addCheck({ kind: "cidr", ...errorUtil_js_1.errorUtil.errToObj(options) });
      }
      datetime(options) {
        if (typeof options === "string") {
          return this._addCheck({
            kind: "datetime",
            precision: null,
            offset: false,
            local: false,
            message: options
          });
        }
        return this._addCheck({
          kind: "datetime",
          precision: typeof options?.precision === "undefined" ? null : options?.precision,
          offset: options?.offset ?? false,
          local: options?.local ?? false,
          ...errorUtil_js_1.errorUtil.errToObj(options?.message)
        });
      }
      date(message) {
        return this._addCheck({ kind: "date", message });
      }
      time(options) {
        if (typeof options === "string") {
          return this._addCheck({
            kind: "time",
            precision: null,
            message: options
          });
        }
        return this._addCheck({
          kind: "time",
          precision: typeof options?.precision === "undefined" ? null : options?.precision,
          ...errorUtil_js_1.errorUtil.errToObj(options?.message)
        });
      }
      duration(message) {
        return this._addCheck({ kind: "duration", ...errorUtil_js_1.errorUtil.errToObj(message) });
      }
      regex(regex, message) {
        return this._addCheck({
          kind: "regex",
          regex,
          ...errorUtil_js_1.errorUtil.errToObj(message)
        });
      }
      includes(value, options) {
        return this._addCheck({
          kind: "includes",
          value,
          position: options?.position,
          ...errorUtil_js_1.errorUtil.errToObj(options?.message)
        });
      }
      startsWith(value, message) {
        return this._addCheck({
          kind: "startsWith",
          value,
          ...errorUtil_js_1.errorUtil.errToObj(message)
        });
      }
      endsWith(value, message) {
        return this._addCheck({
          kind: "endsWith",
          value,
          ...errorUtil_js_1.errorUtil.errToObj(message)
        });
      }
      min(minLength, message) {
        return this._addCheck({
          kind: "min",
          value: minLength,
          ...errorUtil_js_1.errorUtil.errToObj(message)
        });
      }
      max(maxLength, message) {
        return this._addCheck({
          kind: "max",
          value: maxLength,
          ...errorUtil_js_1.errorUtil.errToObj(message)
        });
      }
      length(len, message) {
        return this._addCheck({
          kind: "length",
          value: len,
          ...errorUtil_js_1.errorUtil.errToObj(message)
        });
      }
      /**
       * Equivalent to `.min(1)`
       */
      nonempty(message) {
        return this.min(1, errorUtil_js_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;
      }
    };
    exports.ZodString = ZodString3;
    ZodString3.create = (params) => {
      return new ZodString3({
        checks: [],
        typeName: ZodFirstPartyTypeKind3.ZodString,
        coerce: params?.coerce ?? false,
        ...processCreateParams3(params)
      });
    };
    function floatSafeRemainder3(val2, step) {
      const valDecCount = (val2.toString().split(".")[1] || "").length;
      const stepDecCount = (step.toString().split(".")[1] || "").length;
      const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
      const valInt = Number.parseInt(val2.toFixed(decCount).replace(".", ""));
      const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
      return valInt % stepInt / 10 ** decCount;
    }
    var ZodNumber3 = class _ZodNumber extends ZodType3 {
      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 !== util_js_1.ZodParsedType.number) {
          const ctx2 = this._getOrReturnCtx(input);
          (0, parseUtil_js_1.addIssueToContext)(ctx2, {
            code: ZodError_js_1.ZodIssueCode.invalid_type,
            expected: util_js_1.ZodParsedType.number,
            received: ctx2.parsedType
          });
          return parseUtil_js_1.INVALID;
        }
        let ctx = void 0;
        const status = new parseUtil_js_1.ParseStatus();
        for (const check of this._def.checks) {
          if (check.kind === "int") {
            if (!util_js_1.util.isInteger(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              (0, parseUtil_js_1.addIssueToContext)(ctx, {
                code: ZodError_js_1.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);
              (0, parseUtil_js_1.addIssueToContext)(ctx, {
                code: ZodError_js_1.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);
              (0, parseUtil_js_1.addIssueToContext)(ctx, {
                code: ZodError_js_1.ZodIssueCode.too_big,
                maximum: check.value,
                type: "number",
                inclusive: check.inclusive,
                exact: false,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "multipleOf") {
            if (floatSafeRemainder3(input.data, check.value) !== 0) {
              ctx = this._getOrReturnCtx(input, ctx);
              (0, parseUtil_js_1.addIssueToContext)(ctx, {
                code: ZodError_js_1.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);
              (0, parseUtil_js_1.addIssueToContext)(ctx, {
                code: ZodError_js_1.ZodIssueCode.not_finite,
                message: check.message
              });
              status.dirty();
            }
          } else {
            util_js_1.util.assertNever(check);
          }
        }
        return { status: status.value, value: input.data };
      }
      gte(value, message) {
        return this.setLimit("min", value, true, errorUtil_js_1.errorUtil.toString(message));
      }
      gt(value, message) {
        return this.setLimit("min", value, false, errorUtil_js_1.errorUtil.toString(message));
      }
      lte(value, message) {
        return this.setLimit("max", value, true, errorUtil_js_1.errorUtil.toString(message));
      }
      lt(value, message) {
        return this.setLimit("max", value, false, errorUtil_js_1.errorUtil.toString(message));
      }
      setLimit(kind, value, inclusive, message) {
        return new _ZodNumber({
          ...this._def,
          checks: [
            ...this._def.checks,
            {
              kind,
              value,
              inclusive,
              message: errorUtil_js_1.errorUtil.toString(message)
            }
          ]
        });
      }
      _addCheck(check) {
        return new _ZodNumber({
          ...this._def,
          checks: [...this._def.checks, check]
        });
      }
      int(message) {
        return this._addCheck({
          kind: "int",
          message: errorUtil_js_1.errorUtil.toString(message)
        });
      }
      positive(message) {
        return this._addCheck({
          kind: "min",
          value: 0,
          inclusive: false,
          message: errorUtil_js_1.errorUtil.toString(message)
        });
      }
      negative(message) {
        return this._addCheck({
          kind: "max",
          value: 0,
          inclusive: false,
          message: errorUtil_js_1.errorUtil.toString(message)
        });
      }
      nonpositive(message) {
        return this._addCheck({
          kind: "max",
          value: 0,
          inclusive: true,
          message: errorUtil_js_1.errorUtil.toString(message)
        });
      }
      nonnegative(message) {
        return this._addCheck({
          kind: "min",
          value: 0,
          inclusive: true,
          message: errorUtil_js_1.errorUtil.toString(message)
        });
      }
      multipleOf(value, message) {
        return this._addCheck({
          kind: "multipleOf",
          value,
          message: errorUtil_js_1.errorUtil.toString(message)
        });
      }
      finite(message) {
        return this._addCheck({
          kind: "finite",
          message: errorUtil_js_1.errorUtil.toString(message)
        });
      }
      safe(message) {
        return this._addCheck({
          kind: "min",
          inclusive: true,
          value: Number.MIN_SAFE_INTEGER,
          message: errorUtil_js_1.errorUtil.toString(message)
        })._addCheck({
          kind: "max",
          inclusive: true,
          value: Number.MAX_SAFE_INTEGER,
          message: errorUtil_js_1.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_js_1.util.isInteger(ch.value));
      }
      get isFinite() {
        let max = null;
        let min = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
            return true;
          } else if (ch.kind === "min") {
            if (min === null || ch.value > min)
              min = ch.value;
          } else if (ch.kind === "max") {
            if (max === null || ch.value < max)
              max = ch.value;
          }
        }
        return Number.isFinite(min) && Number.isFinite(max);
      }
    };
    exports.ZodNumber = ZodNumber3;
    ZodNumber3.create = (params) => {
      return new ZodNumber3({
        checks: [],
        typeName: ZodFirstPartyTypeKind3.ZodNumber,
        coerce: params?.coerce || false,
        ...processCreateParams3(params)
      });
    };
    var ZodBigInt3 = class _ZodBigInt extends ZodType3 {
      constructor() {
        super(...arguments);
        this.min = this.gte;
        this.max = this.lte;
      }
      _parse(input) {
        if (this._def.coerce) {
          try {
            input.data = BigInt(input.data);
          } catch {
            return this._getInvalidInput(input);
          }
        }
        const parsedType = this._getType(input);
        if (parsedType !== util_js_1.ZodParsedType.bigint) {
          return this._getInvalidInput(input);
        }
        let ctx = void 0;
        const status = new parseUtil_js_1.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);
              (0, parseUtil_js_1.addIssueToContext)(ctx, {
                code: ZodError_js_1.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);
              (0, parseUtil_js_1.addIssueToContext)(ctx, {
                code: ZodError_js_1.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);
              (0, parseUtil_js_1.addIssueToContext)(ctx, {
                code: ZodError_js_1.ZodIssueCode.not_multiple_of,
                multipleOf: check.value,
                message: check.message
              });
              status.dirty();
            }
          } else {
            util_js_1.util.assertNever(check);
          }
        }
        return { status: status.value, value: input.data };
      }
      _getInvalidInput(input) {
        const ctx = this._getOrReturnCtx(input);
        (0, parseUtil_js_1.addIssueToContext)(ctx, {
          code: ZodError_js_1.ZodIssueCode.invalid_type,
          expected: util_js_1.ZodParsedType.bigint,
          received: ctx.parsedType
        });
        return parseUtil_js_1.INVALID;
      }
      gte(value, message) {
        return this.setLimit("min", value, true, errorUtil_js_1.errorUtil.toString(message));
      }
      gt(value, message) {
        return this.setLimit("min", value, false, errorUtil_js_1.errorUtil.toString(message));
      }
      lte(value, message) {
        return this.setLimit("max", value, true, errorUtil_js_1.errorUtil.toString(message));
      }
      lt(value, message) {
        return this.setLimit("max", value, false, errorUtil_js_1.errorUtil.toString(message));
      }
      setLimit(kind, value, inclusive, message) {
        return new _ZodBigInt({
          ...this._def,
          checks: [
            ...this._def.checks,
            {
              kind,
              value,
              inclusive,
              message: errorUtil_js_1.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_js_1.errorUtil.toString(message)
        });
      }
      negative(message) {
        return this._addCheck({
          kind: "max",
          value: BigInt(0),
          inclusive: false,
          message: errorUtil_js_1.errorUtil.toString(message)
        });
      }
      nonpositive(message) {
        return this._addCheck({
          kind: "max",
          value: BigInt(0),
          inclusive: true,
          message: errorUtil_js_1.errorUtil.toString(message)
        });
      }
      nonnegative(message) {
        return this._addCheck({
          kind: "min",
          value: BigInt(0),
          inclusive: true,
          message: errorUtil_js_1.errorUtil.toString(message)
        });
      }
      multipleOf(value, message) {
        return this._addCheck({
          kind: "multipleOf",
          value,
          message: errorUtil_js_1.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;
      }
    };
    exports.ZodBigInt = ZodBigInt3;
    ZodBigInt3.create = (params) => {
      return new ZodBigInt3({
        checks: [],
        typeName: ZodFirstPartyTypeKind3.ZodBigInt,
        coerce: params?.coerce ?? false,
        ...processCreateParams3(params)
      });
    };
    var ZodBoolean3 = class extends ZodType3 {
      _parse(input) {
        if (this._def.coerce) {
          input.data = Boolean(input.data);
        }
        const parsedType = this._getType(input);
        if (parsedType !== util_js_1.ZodParsedType.boolean) {
          const ctx = this._getOrReturnCtx(input);
          (0, parseUtil_js_1.addIssueToContext)(ctx, {
            code: ZodError_js_1.ZodIssueCode.invalid_type,
            expected: util_js_1.ZodParsedType.boolean,
            received: ctx.parsedType
          });
          return parseUtil_js_1.INVALID;
        }
        return (0, parseUtil_js_1.OK)(input.data);
      }
    };
    exports.ZodBoolean = ZodBoolean3;
    ZodBoolean3.create = (params) => {
      return new ZodBoolean3({
        typeName: ZodFirstPartyTypeKind3.ZodBoolean,
        coerce: params?.coerce || false,
        ...processCreateParams3(params)
      });
    };
    var ZodDate3 = class _ZodDate extends ZodType3 {
      _parse(input) {
        if (this._def.coerce) {
          input.data = new Date(input.data);
        }
        const parsedType = this._getType(input);
        if (parsedType !== util_js_1.ZodParsedType.date) {
          const ctx2 = this._getOrReturnCtx(input);
          (0, parseUtil_js_1.addIssueToContext)(ctx2, {
            code: ZodError_js_1.ZodIssueCode.invalid_type,
            expected: util_js_1.ZodParsedType.date,
            received: ctx2.parsedType
          });
          return parseUtil_js_1.INVALID;
        }
        if (Number.isNaN(input.data.getTime())) {
          const ctx2 = this._getOrReturnCtx(input);
          (0, parseUtil_js_1.addIssueToContext)(ctx2, {
            code: ZodError_js_1.ZodIssueCode.invalid_date
          });
          return parseUtil_js_1.INVALID;
        }
        const status = new parseUtil_js_1.ParseStatus();
        let ctx = void 0;
        for (const check of this._def.checks) {
          if (check.kind === "min") {
            if (input.data.getTime() < check.value) {
              ctx = this._getOrReturnCtx(input, ctx);
              (0, parseUtil_js_1.addIssueToContext)(ctx, {
                code: ZodError_js_1.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);
              (0, parseUtil_js_1.addIssueToContext)(ctx, {
                code: ZodError_js_1.ZodIssueCode.too_big,
                message: check.message,
                inclusive: true,
                exact: false,
                maximum: check.value,
                type: "date"
              });
              status.dirty();
            }
          } else {
            util_js_1.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_js_1.errorUtil.toString(message)
        });
      }
      max(maxDate, message) {
        return this._addCheck({
          kind: "max",
          value: maxDate.getTime(),
          message: errorUtil_js_1.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;
      }
    };
    exports.ZodDate = ZodDate3;
    ZodDate3.create = (params) => {
      return new ZodDate3({
        checks: [],
        coerce: params?.coerce || false,
        typeName: ZodFirstPartyTypeKind3.ZodDate,
        ...processCreateParams3(params)
      });
    };
    var ZodSymbol3 = class extends ZodType3 {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== util_js_1.ZodParsedType.symbol) {
          const ctx = this._getOrReturnCtx(input);
          (0, parseUtil_js_1.addIssueToContext)(ctx, {
            code: ZodError_js_1.ZodIssueCode.invalid_type,
            expected: util_js_1.ZodParsedType.symbol,
            received: ctx.parsedType
          });
          return parseUtil_js_1.INVALID;
        }
        return (0, parseUtil_js_1.OK)(input.data);
      }
    };
    exports.ZodSymbol = ZodSymbol3;
    ZodSymbol3.create = (params) => {
      return new ZodSymbol3({
        typeName: ZodFirstPartyTypeKind3.ZodSymbol,
        ...processCreateParams3(params)
      });
    };
    var ZodUndefined3 = class extends ZodType3 {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== util_js_1.ZodParsedType.undefined) {
          const ctx = this._getOrReturnCtx(input);
          (0, parseUtil_js_1.addIssueToContext)(ctx, {
            code: ZodError_js_1.ZodIssueCode.invalid_type,
            expected: util_js_1.ZodParsedType.undefined,
            received: ctx.parsedType
          });
          return parseUtil_js_1.INVALID;
        }
        return (0, parseUtil_js_1.OK)(input.data);
      }
    };
    exports.ZodUndefined = ZodUndefined3;
    ZodUndefined3.create = (params) => {
      return new ZodUndefined3({
        typeName: ZodFirstPartyTypeKind3.ZodUndefined,
        ...processCreateParams3(params)
      });
    };
    var ZodNull3 = class extends ZodType3 {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== util_js_1.ZodParsedType.null) {
          const ctx = this._getOrReturnCtx(input);
          (0, parseUtil_js_1.addIssueToContext)(ctx, {
            code: ZodError_js_1.ZodIssueCode.invalid_type,
            expected: util_js_1.ZodParsedType.null,
            received: ctx.parsedType
          });
          return parseUtil_js_1.INVALID;
        }
        return (0, parseUtil_js_1.OK)(input.data);
      }
    };
    exports.ZodNull = ZodNull3;
    ZodNull3.create = (params) => {
      return new ZodNull3({
        typeName: ZodFirstPartyTypeKind3.ZodNull,
        ...processCreateParams3(params)
      });
    };
    var ZodAny3 = class extends ZodType3 {
      constructor() {
        super(...arguments);
        this._any = true;
      }
      _parse(input) {
        return (0, parseUtil_js_1.OK)(input.data);
      }
    };
    exports.ZodAny = ZodAny3;
    ZodAny3.create = (params) => {
      return new ZodAny3({
        typeName: ZodFirstPartyTypeKind3.ZodAny,
        ...processCreateParams3(params)
      });
    };
    var ZodUnknown3 = class extends ZodType3 {
      constructor() {
        super(...arguments);
        this._unknown = true;
      }
      _parse(input) {
        return (0, parseUtil_js_1.OK)(input.data);
      }
    };
    exports.ZodUnknown = ZodUnknown3;
    ZodUnknown3.create = (params) => {
      return new ZodUnknown3({
        typeName: ZodFirstPartyTypeKind3.ZodUnknown,
        ...processCreateParams3(params)
      });
    };
    var ZodNever3 = class extends ZodType3 {
      _parse(input) {
        const ctx = this._getOrReturnCtx(input);
        (0, parseUtil_js_1.addIssueToContext)(ctx, {
          code: ZodError_js_1.ZodIssueCode.invalid_type,
          expected: util_js_1.ZodParsedType.never,
          received: ctx.parsedType
        });
        return parseUtil_js_1.INVALID;
      }
    };
    exports.ZodNever = ZodNever3;
    ZodNever3.create = (params) => {
      return new ZodNever3({
        typeName: ZodFirstPartyTypeKind3.ZodNever,
        ...processCreateParams3(params)
      });
    };
    var ZodVoid3 = class extends ZodType3 {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== util_js_1.ZodParsedType.undefined) {
          const ctx = this._getOrReturnCtx(input);
          (0, parseUtil_js_1.addIssueToContext)(ctx, {
            code: ZodError_js_1.ZodIssueCode.invalid_type,
            expected: util_js_1.ZodParsedType.void,
            received: ctx.parsedType
          });
          return parseUtil_js_1.INVALID;
        }
        return (0, parseUtil_js_1.OK)(input.data);
      }
    };
    exports.ZodVoid = ZodVoid3;
    ZodVoid3.create = (params) => {
      return new ZodVoid3({
        typeName: ZodFirstPartyTypeKind3.ZodVoid,
        ...processCreateParams3(params)
      });
    };
    var ZodArray3 = class _ZodArray extends ZodType3 {
      _parse(input) {
        const { ctx, status } = this._processInputParams(input);
        const def = this._def;
        if (ctx.parsedType !== util_js_1.ZodParsedType.array) {
          (0, parseUtil_js_1.addIssueToContext)(ctx, {
            code: ZodError_js_1.ZodIssueCode.invalid_type,
            expected: util_js_1.ZodParsedType.array,
            received: ctx.parsedType
          });
          return parseUtil_js_1.INVALID;
        }
        if (def.exactLength !== null) {
          const tooBig = ctx.data.length > def.exactLength.value;
          const tooSmall = ctx.data.length < def.exactLength.value;
          if (tooBig || tooSmall) {
            (0, parseUtil_js_1.addIssueToContext)(ctx, {
              code: tooBig ? ZodError_js_1.ZodIssueCode.too_big : ZodError_js_1.ZodIssueCode.too_small,
              minimum: tooSmall ? def.exactLength.value : void 0,
              maximum: tooBig ? def.exactLength.value : void 0,
              type: "array",
              inclusive: true,
              exact: true,
              message: def.exactLength.message
            });
            status.dirty();
          }
        }
        if (def.minLength !== null) {
          if (ctx.data.length < def.minLength.value) {
            (0, parseUtil_js_1.addIssueToContext)(ctx, {
              code: ZodError_js_1.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) {
            (0, parseUtil_js_1.addIssueToContext)(ctx, {
              code: ZodError_js_1.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, i7) => {
            return def.type._parseAsync(new ParseInputLazyPath3(ctx, item, ctx.path, i7));
          })).then((result2) => {
            return parseUtil_js_1.ParseStatus.mergeArray(status, result2);
          });
        }
        const result = [...ctx.data].map((item, i7) => {
          return def.type._parseSync(new ParseInputLazyPath3(ctx, item, ctx.path, i7));
        });
        return parseUtil_js_1.ParseStatus.mergeArray(status, result);
      }
      get element() {
        return this._def.type;
      }
      min(minLength, message) {
        return new _ZodArray({
          ...this._def,
          minLength: { value: minLength, message: errorUtil_js_1.errorUtil.toString(message) }
        });
      }
      max(maxLength, message) {
        return new _ZodArray({
          ...this._def,
          maxLength: { value: maxLength, message: errorUtil_js_1.errorUtil.toString(message) }
        });
      }
      length(len, message) {
        return new _ZodArray({
          ...this._def,
          exactLength: { value: len, message: errorUtil_js_1.errorUtil.toString(message) }
        });
      }
      nonempty(message) {
        return this.min(1, message);
      }
    };
    exports.ZodArray = ZodArray3;
    ZodArray3.create = (schema, params) => {
      return new ZodArray3({
        type: schema,
        minLength: null,
        maxLength: null,
        exactLength: null,
        typeName: ZodFirstPartyTypeKind3.ZodArray,
        ...processCreateParams3(params)
      });
    };
    function deepPartialify3(schema) {
      if (schema instanceof ZodObject3) {
        const newShape = {};
        for (const key in schema.shape) {
          const fieldSchema = schema.shape[key];
          newShape[key] = ZodOptional3.create(deepPartialify3(fieldSchema));
        }
        return new ZodObject3({
          ...schema._def,
          shape: () => newShape
        });
      } else if (schema instanceof ZodArray3) {
        return new ZodArray3({
          ...schema._def,
          type: deepPartialify3(schema.element)
        });
      } else if (schema instanceof ZodOptional3) {
        return ZodOptional3.create(deepPartialify3(schema.unwrap()));
      } else if (schema instanceof ZodNullable3) {
        return ZodNullable3.create(deepPartialify3(schema.unwrap()));
      } else if (schema instanceof ZodTuple3) {
        return ZodTuple3.create(schema.items.map((item) => deepPartialify3(item)));
      } else {
        return schema;
      }
    }
    var ZodObject3 = class _ZodObject extends ZodType3 {
      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 keys2 = util_js_1.util.objectKeys(shape);
        this._cached = { shape, keys: keys2 };
        return this._cached;
      }
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== util_js_1.ZodParsedType.object) {
          const ctx2 = this._getOrReturnCtx(input);
          (0, parseUtil_js_1.addIssueToContext)(ctx2, {
            code: ZodError_js_1.ZodIssueCode.invalid_type,
            expected: util_js_1.ZodParsedType.object,
            received: ctx2.parsedType
          });
          return parseUtil_js_1.INVALID;
        }
        const { status, ctx } = this._processInputParams(input);
        const { shape, keys: shapeKeys } = this._getCached();
        const extraKeys = [];
        if (!(this._def.catchall instanceof ZodNever3 && 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 ParseInputLazyPath3(ctx, value, ctx.path, key)),
            alwaysSet: key in ctx.data
          });
        }
        if (this._def.catchall instanceof ZodNever3) {
          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) {
              (0, parseUtil_js_1.addIssueToContext)(ctx, {
                code: ZodError_js_1.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 ParseInputLazyPath3(ctx, value, ctx.path, key)
                //, ctx.child(key), value, getParsedType(value)
              ),
              alwaysSet: key in ctx.data
            });
          }
        }
        if (ctx.common.async) {
          return Promise.resolve().then(async () => {
            const syncPairs = [];
            for (const pair of pairs) {
              const key = await pair.key;
              const value = await pair.value;
              syncPairs.push({
                key,
                value,
                alwaysSet: pair.alwaysSet
              });
            }
            return syncPairs;
          }).then((syncPairs) => {
            return parseUtil_js_1.ParseStatus.mergeObjectSync(status, syncPairs);
          });
        } else {
          return parseUtil_js_1.ParseStatus.mergeObjectSync(status, pairs);
        }
      }
      get shape() {
        return this._def.shape();
      }
      strict(message) {
        errorUtil_js_1.errorUtil.errToObj;
        return new _ZodObject({
          ...this._def,
          unknownKeys: "strict",
          ...message !== void 0 ? {
            errorMap: (issue, ctx) => {
              const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
              if (issue.code === "unrecognized_keys")
                return {
                  message: errorUtil_js_1.errorUtil.errToObj(message).message ?? defaultError
                };
              return {
                message: defaultError
              };
            }
          } : {}
        });
      }
      strip() {
        return new _ZodObject({
          ...this._def,
          unknownKeys: "strip"
        });
      }
      passthrough() {
        return new _ZodObject({
          ...this._def,
          unknownKeys: "passthrough"
        });
      }
      // const AugmentFactory =
      //   <Def extends ZodObjectDef>(def: Def) =>
      //   <Augmentation extends ZodRawShape>(
      //     augmentation: Augmentation
      //   ): ZodObject<
      //     extendShape<ReturnType<Def["shape"]>, Augmentation>,
      //     Def["unknownKeys"],
      //     Def["catchall"]
      //   > => {
      //     return new ZodObject({
      //       ...def,
      //       shape: () => ({
      //         ...def.shape(),
      //         ...augmentation,
      //       }),
      //     }) as any;
      //   };
      extend(augmentation) {
        return new _ZodObject({
          ...this._def,
          shape: () => ({
            ...this._def.shape(),
            ...augmentation
          })
        });
      }
      /**
       * Prior to zod@1.0.12 there was a bug in the
       * inferred type of merged objects. Please
       * upgrade if you are experiencing issues.
       */
      merge(merging) {
        const merged = new _ZodObject({
          unknownKeys: merging._def.unknownKeys,
          catchall: merging._def.catchall,
          shape: () => ({
            ...this._def.shape(),
            ...merging._def.shape()
          }),
          typeName: ZodFirstPartyTypeKind3.ZodObject
        });
        return merged;
      }
      // merge<
      //   Incoming extends AnyZodObject,
      //   Augmentation extends Incoming["shape"],
      //   NewOutput extends {
      //     [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
      //       ? Augmentation[k]["_output"]
      //       : k extends keyof Output
      //       ? Output[k]
      //       : never;
      //   },
      //   NewInput extends {
      //     [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
      //       ? Augmentation[k]["_input"]
      //       : k extends keyof Input
      //       ? Input[k]
      //       : never;
      //   }
      // >(
      //   merging: Incoming
      // ): ZodObject<
      //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
      //   Incoming["_def"]["unknownKeys"],
      //   Incoming["_def"]["catchall"],
      //   NewOutput,
      //   NewInput
      // > {
      //   const merged: any = new ZodObject({
      //     unknownKeys: merging._def.unknownKeys,
      //     catchall: merging._def.catchall,
      //     shape: () =>
      //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
      //     typeName: ZodFirstPartyTypeKind.ZodObject,
      //   }) as any;
      //   return merged;
      // }
      setKey(key, schema) {
        return this.augment({ [key]: schema });
      }
      // merge<Incoming extends AnyZodObject>(
      //   merging: Incoming
      // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
      // ZodObject<
      //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
      //   Incoming["_def"]["unknownKeys"],
      //   Incoming["_def"]["catchall"]
      // > {
      //   // const mergedShape = objectUtil.mergeShapes(
      //   //   this._def.shape(),
      //   //   merging._def.shape()
      //   // );
      //   const merged: any = new ZodObject({
      //     unknownKeys: merging._def.unknownKeys,
      //     catchall: merging._def.catchall,
      //     shape: () =>
      //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
      //     typeName: ZodFirstPartyTypeKind.ZodObject,
      //   }) as any;
      //   return merged;
      // }
      catchall(index) {
        return new _ZodObject({
          ...this._def,
          catchall: index
        });
      }
      pick(mask) {
        const shape = {};
        for (const key of util_js_1.util.objectKeys(mask)) {
          if (mask[key] && this.shape[key]) {
            shape[key] = this.shape[key];
          }
        }
        return new _ZodObject({
          ...this._def,
          shape: () => shape
        });
      }
      omit(mask) {
        const shape = {};
        for (const key of util_js_1.util.objectKeys(this.shape)) {
          if (!mask[key]) {
            shape[key] = this.shape[key];
          }
        }
        return new _ZodObject({
          ...this._def,
          shape: () => shape
        });
      }
      /**
       * @deprecated
       */
      deepPartial() {
        return deepPartialify3(this);
      }
      partial(mask) {
        const newShape = {};
        for (const key of util_js_1.util.objectKeys(this.shape)) {
          const fieldSchema = this.shape[key];
          if (mask && !mask[key]) {
            newShape[key] = fieldSchema;
          } else {
            newShape[key] = fieldSchema.optional();
          }
        }
        return new _ZodObject({
          ...this._def,
          shape: () => newShape
        });
      }
      required(mask) {
        const newShape = {};
        for (const key of util_js_1.util.objectKeys(this.shape)) {
          if (mask && !mask[key]) {
            newShape[key] = this.shape[key];
          } else {
            const fieldSchema = this.shape[key];
            let newField = fieldSchema;
            while (newField instanceof ZodOptional3) {
              newField = newField._def.innerType;
            }
            newShape[key] = newField;
          }
        }
        return new _ZodObject({
          ...this._def,
          shape: () => newShape
        });
      }
      keyof() {
        return createZodEnum3(util_js_1.util.objectKeys(this.shape));
      }
    };
    exports.ZodObject = ZodObject3;
    ZodObject3.create = (shape, params) => {
      return new ZodObject3({
        shape: () => shape,
        unknownKeys: "strip",
        catchall: ZodNever3.create(),
        typeName: ZodFirstPartyTypeKind3.ZodObject,
        ...processCreateParams3(params)
      });
    };
    ZodObject3.strictCreate = (shape, params) => {
      return new ZodObject3({
        shape: () => shape,
        unknownKeys: "strict",
        catchall: ZodNever3.create(),
        typeName: ZodFirstPartyTypeKind3.ZodObject,
        ...processCreateParams3(params)
      });
    };
    ZodObject3.lazycreate = (shape, params) => {
      return new ZodObject3({
        shape,
        unknownKeys: "strip",
        catchall: ZodNever3.create(),
        typeName: ZodFirstPartyTypeKind3.ZodObject,
        ...processCreateParams3(params)
      });
    };
    var ZodUnion3 = class extends ZodType3 {
      _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_js_1.ZodError(result.ctx.common.issues));
          (0, parseUtil_js_1.addIssueToContext)(ctx, {
            code: ZodError_js_1.ZodIssueCode.invalid_union,
            unionErrors
          });
          return parseUtil_js_1.INVALID;
        }
        if (ctx.common.async) {
          return Promise.all(options.map(async (option) => {
            const childCtx = {
              ...ctx,
              common: {
                ...ctx.common,
                issues: []
              },
              parent: null
            };
            return {
              result: await option._parseAsync({
                data: ctx.data,
                path: ctx.path,
                parent: childCtx
              }),
              ctx: childCtx
            };
          })).then(handleResults);
        } else {
          let dirty = void 0;
          const issues = [];
          for (const option of options) {
            const childCtx = {
              ...ctx,
              common: {
                ...ctx.common,
                issues: []
              },
              parent: null
            };
            const result = option._parseSync({
              data: ctx.data,
              path: ctx.path,
              parent: childCtx
            });
            if (result.status === "valid") {
              return result;
            } else if (result.status === "dirty" && !dirty) {
              dirty = { result, ctx: childCtx };
            }
            if (childCtx.common.issues.length) {
              issues.push(childCtx.common.issues);
            }
          }
          if (dirty) {
            ctx.common.issues.push(...dirty.ctx.common.issues);
            return dirty.result;
          }
          const unionErrors = issues.map((issues2) => new ZodError_js_1.ZodError(issues2));
          (0, parseUtil_js_1.addIssueToContext)(ctx, {
            code: ZodError_js_1.ZodIssueCode.invalid_union,
            unionErrors
          });
          return parseUtil_js_1.INVALID;
        }
      }
      get options() {
        return this._def.options;
      }
    };
    exports.ZodUnion = ZodUnion3;
    ZodUnion3.create = (types2, params) => {
      return new ZodUnion3({
        options: types2,
        typeName: ZodFirstPartyTypeKind3.ZodUnion,
        ...processCreateParams3(params)
      });
    };
    var getDiscriminator3 = (type) => {
      if (type instanceof ZodLazy3) {
        return getDiscriminator3(type.schema);
      } else if (type instanceof ZodEffects3) {
        return getDiscriminator3(type.innerType());
      } else if (type instanceof ZodLiteral3) {
        return [type.value];
      } else if (type instanceof ZodEnum3) {
        return type.options;
      } else if (type instanceof ZodNativeEnum3) {
        return util_js_1.util.objectValues(type.enum);
      } else if (type instanceof ZodDefault3) {
        return getDiscriminator3(type._def.innerType);
      } else if (type instanceof ZodUndefined3) {
        return [void 0];
      } else if (type instanceof ZodNull3) {
        return [null];
      } else if (type instanceof ZodOptional3) {
        return [void 0, ...getDiscriminator3(type.unwrap())];
      } else if (type instanceof ZodNullable3) {
        return [null, ...getDiscriminator3(type.unwrap())];
      } else if (type instanceof ZodBranded3) {
        return getDiscriminator3(type.unwrap());
      } else if (type instanceof ZodReadonly3) {
        return getDiscriminator3(type.unwrap());
      } else if (type instanceof ZodCatch3) {
        return getDiscriminator3(type._def.innerType);
      } else {
        return [];
      }
    };
    var ZodDiscriminatedUnion3 = class _ZodDiscriminatedUnion extends ZodType3 {
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        if (ctx.parsedType !== util_js_1.ZodParsedType.object) {
          (0, parseUtil_js_1.addIssueToContext)(ctx, {
            code: ZodError_js_1.ZodIssueCode.invalid_type,
            expected: util_js_1.ZodParsedType.object,
            received: ctx.parsedType
          });
          return parseUtil_js_1.INVALID;
        }
        const discriminator = this.discriminator;
        const discriminatorValue = ctx.data[discriminator];
        const option = this.optionsMap.get(discriminatorValue);
        if (!option) {
          (0, parseUtil_js_1.addIssueToContext)(ctx, {
            code: ZodError_js_1.ZodIssueCode.invalid_union_discriminator,
            options: Array.from(this.optionsMap.keys()),
            path: [discriminator]
          });
          return parseUtil_js_1.INVALID;
        }
        if (ctx.common.async) {
          return option._parseAsync({
            data: ctx.data,
            path: ctx.path,
            parent: ctx
          });
        } else {
          return option._parseSync({
            data: ctx.data,
            path: ctx.path,
            parent: ctx
          });
        }
      }
      get discriminator() {
        return this._def.discriminator;
      }
      get options() {
        return this._def.options;
      }
      get optionsMap() {
        return this._def.optionsMap;
      }
      /**
       * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
       * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
       * have a different value for each object in the union.
       * @param discriminator the name of the discriminator property
       * @param types an array of object schemas
       * @param params
       */
      static create(discriminator, options, params) {
        const optionsMap = /* @__PURE__ */ new Map();
        for (const type of options) {
          const discriminatorValues = getDiscriminator3(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: ZodFirstPartyTypeKind3.ZodDiscriminatedUnion,
          discriminator,
          options,
          optionsMap,
          ...processCreateParams3(params)
        });
      }
    };
    exports.ZodDiscriminatedUnion = ZodDiscriminatedUnion3;
    function mergeValues3(a3, b4) {
      const aType = (0, util_js_1.getParsedType)(a3);
      const bType = (0, util_js_1.getParsedType)(b4);
      if (a3 === b4) {
        return { valid: true, data: a3 };
      } else if (aType === util_js_1.ZodParsedType.object && bType === util_js_1.ZodParsedType.object) {
        const bKeys = util_js_1.util.objectKeys(b4);
        const sharedKeys = util_js_1.util.objectKeys(a3).filter((key) => bKeys.indexOf(key) !== -1);
        const newObj = { ...a3, ...b4 };
        for (const key of sharedKeys) {
          const sharedValue = mergeValues3(a3[key], b4[key]);
          if (!sharedValue.valid) {
            return { valid: false };
          }
          newObj[key] = sharedValue.data;
        }
        return { valid: true, data: newObj };
      } else if (aType === util_js_1.ZodParsedType.array && bType === util_js_1.ZodParsedType.array) {
        if (a3.length !== b4.length) {
          return { valid: false };
        }
        const newArray = [];
        for (let index = 0; index < a3.length; index++) {
          const itemA = a3[index];
          const itemB = b4[index];
          const sharedValue = mergeValues3(itemA, itemB);
          if (!sharedValue.valid) {
            return { valid: false };
          }
          newArray.push(sharedValue.data);
        }
        return { valid: true, data: newArray };
      } else if (aType === util_js_1.ZodParsedType.date && bType === util_js_1.ZodParsedType.date && +a3 === +b4) {
        return { valid: true, data: a3 };
      } else {
        return { valid: false };
      }
    }
    var ZodIntersection3 = class extends ZodType3 {
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        const handleParsed = (parsedLeft, parsedRight) => {
          if ((0, parseUtil_js_1.isAborted)(parsedLeft) || (0, parseUtil_js_1.isAborted)(parsedRight)) {
            return parseUtil_js_1.INVALID;
          }
          const merged = mergeValues3(parsedLeft.value, parsedRight.value);
          if (!merged.valid) {
            (0, parseUtil_js_1.addIssueToContext)(ctx, {
              code: ZodError_js_1.ZodIssueCode.invalid_intersection_types
            });
            return parseUtil_js_1.INVALID;
          }
          if ((0, parseUtil_js_1.isDirty)(parsedLeft) || (0, parseUtil_js_1.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
          }));
        }
      }
    };
    exports.ZodIntersection = ZodIntersection3;
    ZodIntersection3.create = (left, right, params) => {
      return new ZodIntersection3({
        left,
        right,
        typeName: ZodFirstPartyTypeKind3.ZodIntersection,
        ...processCreateParams3(params)
      });
    };
    var ZodTuple3 = class _ZodTuple extends ZodType3 {
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== util_js_1.ZodParsedType.array) {
          (0, parseUtil_js_1.addIssueToContext)(ctx, {
            code: ZodError_js_1.ZodIssueCode.invalid_type,
            expected: util_js_1.ZodParsedType.array,
            received: ctx.parsedType
          });
          return parseUtil_js_1.INVALID;
        }
        if (ctx.data.length < this._def.items.length) {
          (0, parseUtil_js_1.addIssueToContext)(ctx, {
            code: ZodError_js_1.ZodIssueCode.too_small,
            minimum: this._def.items.length,
            inclusive: true,
            exact: false,
            type: "array"
          });
          return parseUtil_js_1.INVALID;
        }
        const rest = this._def.rest;
        if (!rest && ctx.data.length > this._def.items.length) {
          (0, parseUtil_js_1.addIssueToContext)(ctx, {
            code: ZodError_js_1.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 ParseInputLazyPath3(ctx, item, ctx.path, itemIndex));
        }).filter((x2) => !!x2);
        if (ctx.common.async) {
          return Promise.all(items).then((results) => {
            return parseUtil_js_1.ParseStatus.mergeArray(status, results);
          });
        } else {
          return parseUtil_js_1.ParseStatus.mergeArray(status, items);
        }
      }
      get items() {
        return this._def.items;
      }
      rest(rest) {
        return new _ZodTuple({
          ...this._def,
          rest
        });
      }
    };
    exports.ZodTuple = ZodTuple3;
    ZodTuple3.create = (schemas, params) => {
      if (!Array.isArray(schemas)) {
        throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
      }
      return new ZodTuple3({
        items: schemas,
        typeName: ZodFirstPartyTypeKind3.ZodTuple,
        rest: null,
        ...processCreateParams3(params)
      });
    };
    var ZodRecord3 = class _ZodRecord extends ZodType3 {
      get keySchema() {
        return this._def.keyType;
      }
      get valueSchema() {
        return this._def.valueType;
      }
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== util_js_1.ZodParsedType.object) {
          (0, parseUtil_js_1.addIssueToContext)(ctx, {
            code: ZodError_js_1.ZodIssueCode.invalid_type,
            expected: util_js_1.ZodParsedType.object,
            received: ctx.parsedType
          });
          return parseUtil_js_1.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 ParseInputLazyPath3(ctx, key, ctx.path, key)),
            value: valueType._parse(new ParseInputLazyPath3(ctx, ctx.data[key], ctx.path, key)),
            alwaysSet: key in ctx.data
          });
        }
        if (ctx.common.async) {
          return parseUtil_js_1.ParseStatus.mergeObjectAsync(status, pairs);
        } else {
          return parseUtil_js_1.ParseStatus.mergeObjectSync(status, pairs);
        }
      }
      get element() {
        return this._def.valueType;
      }
      static create(first, second, third) {
        if (second instanceof ZodType3) {
          return new _ZodRecord({
            keyType: first,
            valueType: second,
            typeName: ZodFirstPartyTypeKind3.ZodRecord,
            ...processCreateParams3(third)
          });
        }
        return new _ZodRecord({
          keyType: ZodString3.create(),
          valueType: first,
          typeName: ZodFirstPartyTypeKind3.ZodRecord,
          ...processCreateParams3(second)
        });
      }
    };
    exports.ZodRecord = ZodRecord3;
    var ZodMap3 = class extends ZodType3 {
      get keySchema() {
        return this._def.keyType;
      }
      get valueSchema() {
        return this._def.valueType;
      }
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== util_js_1.ZodParsedType.map) {
          (0, parseUtil_js_1.addIssueToContext)(ctx, {
            code: ZodError_js_1.ZodIssueCode.invalid_type,
            expected: util_js_1.ZodParsedType.map,
            received: ctx.parsedType
          });
          return parseUtil_js_1.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 ParseInputLazyPath3(ctx, key, ctx.path, [index, "key"])),
            value: valueType._parse(new ParseInputLazyPath3(ctx, value, ctx.path, [index, "value"]))
          };
        });
        if (ctx.common.async) {
          const finalMap = /* @__PURE__ */ new Map();
          return Promise.resolve().then(async () => {
            for (const pair of pairs) {
              const key = await pair.key;
              const value = await pair.value;
              if (key.status === "aborted" || value.status === "aborted") {
                return parseUtil_js_1.INVALID;
              }
              if (key.status === "dirty" || value.status === "dirty") {
                status.dirty();
              }
              finalMap.set(key.value, value.value);
            }
            return { status: status.value, value: finalMap };
          });
        } else {
          const finalMap = /* @__PURE__ */ new Map();
          for (const pair of pairs) {
            const key = pair.key;
            const value = pair.value;
            if (key.status === "aborted" || value.status === "aborted") {
              return parseUtil_js_1.INVALID;
            }
            if (key.status === "dirty" || value.status === "dirty") {
              status.dirty();
            }
            finalMap.set(key.value, value.value);
          }
          return { status: status.value, value: finalMap };
        }
      }
    };
    exports.ZodMap = ZodMap3;
    ZodMap3.create = (keyType, valueType, params) => {
      return new ZodMap3({
        valueType,
        keyType,
        typeName: ZodFirstPartyTypeKind3.ZodMap,
        ...processCreateParams3(params)
      });
    };
    var ZodSet3 = class _ZodSet extends ZodType3 {
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== util_js_1.ZodParsedType.set) {
          (0, parseUtil_js_1.addIssueToContext)(ctx, {
            code: ZodError_js_1.ZodIssueCode.invalid_type,
            expected: util_js_1.ZodParsedType.set,
            received: ctx.parsedType
          });
          return parseUtil_js_1.INVALID;
        }
        const def = this._def;
        if (def.minSize !== null) {
          if (ctx.data.size < def.minSize.value) {
            (0, parseUtil_js_1.addIssueToContext)(ctx, {
              code: ZodError_js_1.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) {
            (0, parseUtil_js_1.addIssueToContext)(ctx, {
              code: ZodError_js_1.ZodIssueCode.too_big,
              maximum: def.maxSize.value,
              type: "set",
              inclusive: true,
              exact: false,
              message: def.maxSize.message
            });
            status.dirty();
          }
        }
        const valueType = this._def.valueType;
        function finalizeSet(elements2) {
          const parsedSet = /* @__PURE__ */ new Set();
          for (const element of elements2) {
            if (element.status === "aborted")
              return parseUtil_js_1.INVALID;
            if (element.status === "dirty")
              status.dirty();
            parsedSet.add(element.value);
          }
          return { status: status.value, value: parsedSet };
        }
        const elements = [...ctx.data.values()].map((item, i7) => valueType._parse(new ParseInputLazyPath3(ctx, item, ctx.path, i7)));
        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_js_1.errorUtil.toString(message) }
        });
      }
      max(maxSize, message) {
        return new _ZodSet({
          ...this._def,
          maxSize: { value: maxSize, message: errorUtil_js_1.errorUtil.toString(message) }
        });
      }
      size(size, message) {
        return this.min(size, message).max(size, message);
      }
      nonempty(message) {
        return this.min(1, message);
      }
    };
    exports.ZodSet = ZodSet3;
    ZodSet3.create = (valueType, params) => {
      return new ZodSet3({
        valueType,
        minSize: null,
        maxSize: null,
        typeName: ZodFirstPartyTypeKind3.ZodSet,
        ...processCreateParams3(params)
      });
    };
    var ZodFunction3 = class _ZodFunction extends ZodType3 {
      constructor() {
        super(...arguments);
        this.validate = this.implement;
      }
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        if (ctx.parsedType !== util_js_1.ZodParsedType.function) {
          (0, parseUtil_js_1.addIssueToContext)(ctx, {
            code: ZodError_js_1.ZodIssueCode.invalid_type,
            expected: util_js_1.ZodParsedType.function,
            received: ctx.parsedType
          });
          return parseUtil_js_1.INVALID;
        }
        function makeArgsIssue(args, error) {
          return (0, parseUtil_js_1.makeIssue)({
            data: args,
            path: ctx.path,
            errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, (0, errors_js_1.getErrorMap)(), errors_js_1.defaultErrorMap].filter((x2) => !!x2),
            issueData: {
              code: ZodError_js_1.ZodIssueCode.invalid_arguments,
              argumentsError: error
            }
          });
        }
        function makeReturnsIssue(returns, error) {
          return (0, parseUtil_js_1.makeIssue)({
            data: returns,
            path: ctx.path,
            errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, (0, errors_js_1.getErrorMap)(), errors_js_1.defaultErrorMap].filter((x2) => !!x2),
            issueData: {
              code: ZodError_js_1.ZodIssueCode.invalid_return_type,
              returnTypeError: error
            }
          });
        }
        const params = { errorMap: ctx.common.contextualErrorMap };
        const fn = ctx.data;
        if (this._def.returns instanceof ZodPromise3) {
          const me = this;
          return (0, parseUtil_js_1.OK)(async function(...args) {
            const error = new ZodError_js_1.ZodError([]);
            const parsedArgs = await me._def.args.parseAsync(args, params).catch((e9) => {
              error.addIssue(makeArgsIssue(args, e9));
              throw error;
            });
            const result = await Reflect.apply(fn, this, parsedArgs);
            const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e9) => {
              error.addIssue(makeReturnsIssue(result, e9));
              throw error;
            });
            return parsedReturns;
          });
        } else {
          const me = this;
          return (0, parseUtil_js_1.OK)(function(...args) {
            const parsedArgs = me._def.args.safeParse(args, params);
            if (!parsedArgs.success) {
              throw new ZodError_js_1.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_js_1.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: ZodTuple3.create(items).rest(ZodUnknown3.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 : ZodTuple3.create([]).rest(ZodUnknown3.create()),
          returns: returns || ZodUnknown3.create(),
          typeName: ZodFirstPartyTypeKind3.ZodFunction,
          ...processCreateParams3(params)
        });
      }
    };
    exports.ZodFunction = ZodFunction3;
    var ZodLazy3 = class extends ZodType3 {
      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 });
      }
    };
    exports.ZodLazy = ZodLazy3;
    ZodLazy3.create = (getter, params) => {
      return new ZodLazy3({
        getter,
        typeName: ZodFirstPartyTypeKind3.ZodLazy,
        ...processCreateParams3(params)
      });
    };
    var ZodLiteral3 = class extends ZodType3 {
      _parse(input) {
        if (input.data !== this._def.value) {
          const ctx = this._getOrReturnCtx(input);
          (0, parseUtil_js_1.addIssueToContext)(ctx, {
            received: ctx.data,
            code: ZodError_js_1.ZodIssueCode.invalid_literal,
            expected: this._def.value
          });
          return parseUtil_js_1.INVALID;
        }
        return { status: "valid", value: input.data };
      }
      get value() {
        return this._def.value;
      }
    };
    exports.ZodLiteral = ZodLiteral3;
    ZodLiteral3.create = (value, params) => {
      return new ZodLiteral3({
        value,
        typeName: ZodFirstPartyTypeKind3.ZodLiteral,
        ...processCreateParams3(params)
      });
    };
    function createZodEnum3(values2, params) {
      return new ZodEnum3({
        values: values2,
        typeName: ZodFirstPartyTypeKind3.ZodEnum,
        ...processCreateParams3(params)
      });
    }
    var ZodEnum3 = class _ZodEnum extends ZodType3 {
      _parse(input) {
        if (typeof input.data !== "string") {
          const ctx = this._getOrReturnCtx(input);
          const expectedValues = this._def.values;
          (0, parseUtil_js_1.addIssueToContext)(ctx, {
            expected: util_js_1.util.joinValues(expectedValues),
            received: ctx.parsedType,
            code: ZodError_js_1.ZodIssueCode.invalid_type
          });
          return parseUtil_js_1.INVALID;
        }
        if (!this._cache) {
          this._cache = new Set(this._def.values);
        }
        if (!this._cache.has(input.data)) {
          const ctx = this._getOrReturnCtx(input);
          const expectedValues = this._def.values;
          (0, parseUtil_js_1.addIssueToContext)(ctx, {
            received: ctx.data,
            code: ZodError_js_1.ZodIssueCode.invalid_enum_value,
            options: expectedValues
          });
          return parseUtil_js_1.INVALID;
        }
        return (0, parseUtil_js_1.OK)(input.data);
      }
      get options() {
        return this._def.values;
      }
      get enum() {
        const enumValues = {};
        for (const val2 of this._def.values) {
          enumValues[val2] = val2;
        }
        return enumValues;
      }
      get Values() {
        const enumValues = {};
        for (const val2 of this._def.values) {
          enumValues[val2] = val2;
        }
        return enumValues;
      }
      get Enum() {
        const enumValues = {};
        for (const val2 of this._def.values) {
          enumValues[val2] = val2;
        }
        return enumValues;
      }
      extract(values2, newDef = this._def) {
        return _ZodEnum.create(values2, {
          ...this._def,
          ...newDef
        });
      }
      exclude(values2, newDef = this._def) {
        return _ZodEnum.create(this.options.filter((opt) => !values2.includes(opt)), {
          ...this._def,
          ...newDef
        });
      }
    };
    exports.ZodEnum = ZodEnum3;
    ZodEnum3.create = createZodEnum3;
    var ZodNativeEnum3 = class extends ZodType3 {
      _parse(input) {
        const nativeEnumValues = util_js_1.util.getValidEnumValues(this._def.values);
        const ctx = this._getOrReturnCtx(input);
        if (ctx.parsedType !== util_js_1.ZodParsedType.string && ctx.parsedType !== util_js_1.ZodParsedType.number) {
          const expectedValues = util_js_1.util.objectValues(nativeEnumValues);
          (0, parseUtil_js_1.addIssueToContext)(ctx, {
            expected: util_js_1.util.joinValues(expectedValues),
            received: ctx.parsedType,
            code: ZodError_js_1.ZodIssueCode.invalid_type
          });
          return parseUtil_js_1.INVALID;
        }
        if (!this._cache) {
          this._cache = new Set(util_js_1.util.getValidEnumValues(this._def.values));
        }
        if (!this._cache.has(input.data)) {
          const expectedValues = util_js_1.util.objectValues(nativeEnumValues);
          (0, parseUtil_js_1.addIssueToContext)(ctx, {
            received: ctx.data,
            code: ZodError_js_1.ZodIssueCode.invalid_enum_value,
            options: expectedValues
          });
          return parseUtil_js_1.INVALID;
        }
        return (0, parseUtil_js_1.OK)(input.data);
      }
      get enum() {
        return this._def.values;
      }
    };
    exports.ZodNativeEnum = ZodNativeEnum3;
    ZodNativeEnum3.create = (values2, params) => {
      return new ZodNativeEnum3({
        values: values2,
        typeName: ZodFirstPartyTypeKind3.ZodNativeEnum,
        ...processCreateParams3(params)
      });
    };
    var ZodPromise3 = class extends ZodType3 {
      unwrap() {
        return this._def.type;
      }
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        if (ctx.parsedType !== util_js_1.ZodParsedType.promise && ctx.common.async === false) {
          (0, parseUtil_js_1.addIssueToContext)(ctx, {
            code: ZodError_js_1.ZodIssueCode.invalid_type,
            expected: util_js_1.ZodParsedType.promise,
            received: ctx.parsedType
          });
          return parseUtil_js_1.INVALID;
        }
        const promisified = ctx.parsedType === util_js_1.ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
        return (0, parseUtil_js_1.OK)(promisified.then((data) => {
          return this._def.type.parseAsync(data, {
            path: ctx.path,
            errorMap: ctx.common.contextualErrorMap
          });
        }));
      }
    };
    exports.ZodPromise = ZodPromise3;
    ZodPromise3.create = (schema, params) => {
      return new ZodPromise3({
        type: schema,
        typeName: ZodFirstPartyTypeKind3.ZodPromise,
        ...processCreateParams3(params)
      });
    };
    var ZodEffects3 = class extends ZodType3 {
      innerType() {
        return this._def.schema;
      }
      sourceType() {
        return this._def.schema._def.typeName === ZodFirstPartyTypeKind3.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) => {
            (0, parseUtil_js_1.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 parseUtil_js_1.INVALID;
              const result = await this._def.schema._parseAsync({
                data: processed2,
                path: ctx.path,
                parent: ctx
              });
              if (result.status === "aborted")
                return parseUtil_js_1.INVALID;
              if (result.status === "dirty")
                return (0, parseUtil_js_1.DIRTY)(result.value);
              if (status.value === "dirty")
                return (0, parseUtil_js_1.DIRTY)(result.value);
              return result;
            });
          } else {
            if (status.value === "aborted")
              return parseUtil_js_1.INVALID;
            const result = this._def.schema._parseSync({
              data: processed,
              path: ctx.path,
              parent: ctx
            });
            if (result.status === "aborted")
              return parseUtil_js_1.INVALID;
            if (result.status === "dirty")
              return (0, parseUtil_js_1.DIRTY)(result.value);
            if (status.value === "dirty")
              return (0, parseUtil_js_1.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 inner2 = this._def.schema._parseSync({
              data: ctx.data,
              path: ctx.path,
              parent: ctx
            });
            if (inner2.status === "aborted")
              return parseUtil_js_1.INVALID;
            if (inner2.status === "dirty")
              status.dirty();
            executeRefinement(inner2.value);
            return { status: status.value, value: inner2.value };
          } else {
            return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner2) => {
              if (inner2.status === "aborted")
                return parseUtil_js_1.INVALID;
              if (inner2.status === "dirty")
                status.dirty();
              return executeRefinement(inner2.value).then(() => {
                return { status: status.value, value: inner2.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 (!(0, parseUtil_js_1.isValid)(base))
              return parseUtil_js_1.INVALID;
            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 (!(0, parseUtil_js_1.isValid)(base))
                return parseUtil_js_1.INVALID;
              return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
                status: status.value,
                value: result
              }));
            });
          }
        }
        util_js_1.util.assertNever(effect);
      }
    };
    exports.ZodEffects = ZodEffects3;
    exports.ZodTransformer = ZodEffects3;
    ZodEffects3.create = (schema, effect, params) => {
      return new ZodEffects3({
        schema,
        typeName: ZodFirstPartyTypeKind3.ZodEffects,
        effect,
        ...processCreateParams3(params)
      });
    };
    ZodEffects3.createWithPreprocess = (preprocess, schema, params) => {
      return new ZodEffects3({
        schema,
        effect: { type: "preprocess", transform: preprocess },
        typeName: ZodFirstPartyTypeKind3.ZodEffects,
        ...processCreateParams3(params)
      });
    };
    var ZodOptional3 = class extends ZodType3 {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType === util_js_1.ZodParsedType.undefined) {
          return (0, parseUtil_js_1.OK)(void 0);
        }
        return this._def.innerType._parse(input);
      }
      unwrap() {
        return this._def.innerType;
      }
    };
    exports.ZodOptional = ZodOptional3;
    ZodOptional3.create = (type, params) => {
      return new ZodOptional3({
        innerType: type,
        typeName: ZodFirstPartyTypeKind3.ZodOptional,
        ...processCreateParams3(params)
      });
    };
    var ZodNullable3 = class extends ZodType3 {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType === util_js_1.ZodParsedType.null) {
          return (0, parseUtil_js_1.OK)(null);
        }
        return this._def.innerType._parse(input);
      }
      unwrap() {
        return this._def.innerType;
      }
    };
    exports.ZodNullable = ZodNullable3;
    ZodNullable3.create = (type, params) => {
      return new ZodNullable3({
        innerType: type,
        typeName: ZodFirstPartyTypeKind3.ZodNullable,
        ...processCreateParams3(params)
      });
    };
    var ZodDefault3 = class extends ZodType3 {
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        let data = ctx.data;
        if (ctx.parsedType === util_js_1.ZodParsedType.undefined) {
          data = this._def.defaultValue();
        }
        return this._def.innerType._parse({
          data,
          path: ctx.path,
          parent: ctx
        });
      }
      removeDefault() {
        return this._def.innerType;
      }
    };
    exports.ZodDefault = ZodDefault3;
    ZodDefault3.create = (type, params) => {
      return new ZodDefault3({
        innerType: type,
        typeName: ZodFirstPartyTypeKind3.ZodDefault,
        defaultValue: typeof params.default === "function" ? params.default : () => params.default,
        ...processCreateParams3(params)
      });
    };
    var ZodCatch3 = class extends ZodType3 {
      _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 ((0, parseUtil_js_1.isAsync)(result)) {
          return result.then((result2) => {
            return {
              status: "valid",
              value: result2.status === "valid" ? result2.value : this._def.catchValue({
                get error() {
                  return new ZodError_js_1.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_js_1.ZodError(newCtx.common.issues);
              },
              input: newCtx.data
            })
          };
        }
      }
      removeCatch() {
        return this._def.innerType;
      }
    };
    exports.ZodCatch = ZodCatch3;
    ZodCatch3.create = (type, params) => {
      return new ZodCatch3({
        innerType: type,
        typeName: ZodFirstPartyTypeKind3.ZodCatch,
        catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
        ...processCreateParams3(params)
      });
    };
    var ZodNaN3 = class extends ZodType3 {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== util_js_1.ZodParsedType.nan) {
          const ctx = this._getOrReturnCtx(input);
          (0, parseUtil_js_1.addIssueToContext)(ctx, {
            code: ZodError_js_1.ZodIssueCode.invalid_type,
            expected: util_js_1.ZodParsedType.nan,
            received: ctx.parsedType
          });
          return parseUtil_js_1.INVALID;
        }
        return { status: "valid", value: input.data };
      }
    };
    exports.ZodNaN = ZodNaN3;
    ZodNaN3.create = (params) => {
      return new ZodNaN3({
        typeName: ZodFirstPartyTypeKind3.ZodNaN,
        ...processCreateParams3(params)
      });
    };
    exports.BRAND = Symbol("zod_brand");
    var ZodBranded3 = class extends ZodType3 {
      _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;
      }
    };
    exports.ZodBranded = ZodBranded3;
    var ZodPipeline3 = class _ZodPipeline extends ZodType3 {
      _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 parseUtil_js_1.INVALID;
            if (inResult.status === "dirty") {
              status.dirty();
              return (0, parseUtil_js_1.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 parseUtil_js_1.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(a3, b4) {
        return new _ZodPipeline({
          in: a3,
          out: b4,
          typeName: ZodFirstPartyTypeKind3.ZodPipeline
        });
      }
    };
    exports.ZodPipeline = ZodPipeline3;
    var ZodReadonly3 = class extends ZodType3 {
      _parse(input) {
        const result = this._def.innerType._parse(input);
        const freeze2 = (data) => {
          if ((0, parseUtil_js_1.isValid)(data)) {
            data.value = Object.freeze(data.value);
          }
          return data;
        };
        return (0, parseUtil_js_1.isAsync)(result) ? result.then((data) => freeze2(data)) : freeze2(result);
      }
      unwrap() {
        return this._def.innerType;
      }
    };
    exports.ZodReadonly = ZodReadonly3;
    ZodReadonly3.create = (type, params) => {
      return new ZodReadonly3({
        innerType: type,
        typeName: ZodFirstPartyTypeKind3.ZodReadonly,
        ...processCreateParams3(params)
      });
    };
    function cleanParams2(params, data) {
      const p4 = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
      const p22 = typeof p4 === "string" ? { message: p4 } : p4;
      return p22;
    }
    function custom2(check, _params = {}, fatal) {
      if (check)
        return ZodAny3.create().superRefine((data, ctx) => {
          const r8 = check(data);
          if (r8 instanceof Promise) {
            return r8.then((r9) => {
              if (!r9) {
                const params = cleanParams2(_params, data);
                const _fatal = params.fatal ?? fatal ?? true;
                ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
              }
            });
          }
          if (!r8) {
            const params = cleanParams2(_params, data);
            const _fatal = params.fatal ?? fatal ?? true;
            ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
          }
          return;
        });
      return ZodAny3.create();
    }
    exports.late = {
      object: ZodObject3.lazycreate
    };
    var ZodFirstPartyTypeKind3;
    (function(ZodFirstPartyTypeKind4) {
      ZodFirstPartyTypeKind4["ZodString"] = "ZodString";
      ZodFirstPartyTypeKind4["ZodNumber"] = "ZodNumber";
      ZodFirstPartyTypeKind4["ZodNaN"] = "ZodNaN";
      ZodFirstPartyTypeKind4["ZodBigInt"] = "ZodBigInt";
      ZodFirstPartyTypeKind4["ZodBoolean"] = "ZodBoolean";
      ZodFirstPartyTypeKind4["ZodDate"] = "ZodDate";
      ZodFirstPartyTypeKind4["ZodSymbol"] = "ZodSymbol";
      ZodFirstPartyTypeKind4["ZodUndefined"] = "ZodUndefined";
      ZodFirstPartyTypeKind4["ZodNull"] = "ZodNull";
      ZodFirstPartyTypeKind4["ZodAny"] = "ZodAny";
      ZodFirstPartyTypeKind4["ZodUnknown"] = "ZodUnknown";
      ZodFirstPartyTypeKind4["ZodNever"] = "ZodNever";
      ZodFirstPartyTypeKind4["ZodVoid"] = "ZodVoid";
      ZodFirstPartyTypeKind4["ZodArray"] = "ZodArray";
      ZodFirstPartyTypeKind4["ZodObject"] = "ZodObject";
      ZodFirstPartyTypeKind4["ZodUnion"] = "ZodUnion";
      ZodFirstPartyTypeKind4["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
      ZodFirstPartyTypeKind4["ZodIntersection"] = "ZodIntersection";
      ZodFirstPartyTypeKind4["ZodTuple"] = "ZodTuple";
      ZodFirstPartyTypeKind4["ZodRecord"] = "ZodRecord";
      ZodFirstPartyTypeKind4["ZodMap"] = "ZodMap";
      ZodFirstPartyTypeKind4["ZodSet"] = "ZodSet";
      ZodFirstPartyTypeKind4["ZodFunction"] = "ZodFunction";
      ZodFirstPartyTypeKind4["ZodLazy"] = "ZodLazy";
      ZodFirstPartyTypeKind4["ZodLiteral"] = "ZodLiteral";
      ZodFirstPartyTypeKind4["ZodEnum"] = "ZodEnum";
      ZodFirstPartyTypeKind4["ZodEffects"] = "ZodEffects";
      ZodFirstPartyTypeKind4["ZodNativeEnum"] = "ZodNativeEnum";
      ZodFirstPartyTypeKind4["ZodOptional"] = "ZodOptional";
      ZodFirstPartyTypeKind4["ZodNullable"] = "ZodNullable";
      ZodFirstPartyTypeKind4["ZodDefault"] = "ZodDefault";
      ZodFirstPartyTypeKind4["ZodCatch"] = "ZodCatch";
      ZodFirstPartyTypeKind4["ZodPromise"] = "ZodPromise";
      ZodFirstPartyTypeKind4["ZodBranded"] = "ZodBranded";
      ZodFirstPartyTypeKind4["ZodPipeline"] = "ZodPipeline";
      ZodFirstPartyTypeKind4["ZodReadonly"] = "ZodReadonly";
    })(ZodFirstPartyTypeKind3 || (exports.ZodFirstPartyTypeKind = ZodFirstPartyTypeKind3 = {}));
    var instanceOfType2 = (cls, params = {
      message: `Input not instance of ${cls.name}`
    }) => custom2((data) => data instanceof cls, params);
    exports.instanceof = instanceOfType2;
    var stringType3 = ZodString3.create;
    exports.string = stringType3;
    var numberType3 = ZodNumber3.create;
    exports.number = numberType3;
    var nanType3 = ZodNaN3.create;
    exports.nan = nanType3;
    var bigIntType3 = ZodBigInt3.create;
    exports.bigint = bigIntType3;
    var booleanType3 = ZodBoolean3.create;
    exports.boolean = booleanType3;
    var dateType3 = ZodDate3.create;
    exports.date = dateType3;
    var symbolType3 = ZodSymbol3.create;
    exports.symbol = symbolType3;
    var undefinedType3 = ZodUndefined3.create;
    exports.undefined = undefinedType3;
    var nullType3 = ZodNull3.create;
    exports.null = nullType3;
    var anyType3 = ZodAny3.create;
    exports.any = anyType3;
    var unknownType3 = ZodUnknown3.create;
    exports.unknown = unknownType3;
    var neverType3 = ZodNever3.create;
    exports.never = neverType3;
    var voidType3 = ZodVoid3.create;
    exports.void = voidType3;
    var arrayType3 = ZodArray3.create;
    exports.array = arrayType3;
    var objectType3 = ZodObject3.create;
    exports.object = objectType3;
    var strictObjectType3 = ZodObject3.strictCreate;
    exports.strictObject = strictObjectType3;
    var unionType3 = ZodUnion3.create;
    exports.union = unionType3;
    var discriminatedUnionType3 = ZodDiscriminatedUnion3.create;
    exports.discriminatedUnion = discriminatedUnionType3;
    var intersectionType3 = ZodIntersection3.create;
    exports.intersection = intersectionType3;
    var tupleType3 = ZodTuple3.create;
    exports.tuple = tupleType3;
    var recordType3 = ZodRecord3.create;
    exports.record = recordType3;
    var mapType3 = ZodMap3.create;
    exports.map = mapType3;
    var setType3 = ZodSet3.create;
    exports.set = setType3;
    var functionType3 = ZodFunction3.create;
    exports.function = functionType3;
    var lazyType3 = ZodLazy3.create;
    exports.lazy = lazyType3;
    var literalType3 = ZodLiteral3.create;
    exports.literal = literalType3;
    var enumType3 = ZodEnum3.create;
    exports.enum = enumType3;
    var nativeEnumType3 = ZodNativeEnum3.create;
    exports.nativeEnum = nativeEnumType3;
    var promiseType3 = ZodPromise3.create;
    exports.promise = promiseType3;
    var effectsType3 = ZodEffects3.create;
    exports.effect = effectsType3;
    exports.transformer = effectsType3;
    var optionalType3 = ZodOptional3.create;
    exports.optional = optionalType3;
    var nullableType3 = ZodNullable3.create;
    exports.nullable = nullableType3;
    var preprocessType3 = ZodEffects3.createWithPreprocess;
    exports.preprocess = preprocessType3;
    var pipelineType3 = ZodPipeline3.create;
    exports.pipeline = pipelineType3;
    var ostring2 = () => stringType3().optional();
    exports.ostring = ostring2;
    var onumber2 = () => numberType3().optional();
    exports.onumber = onumber2;
    var oboolean2 = () => booleanType3().optional();
    exports.oboolean = oboolean2;
    exports.coerce = {
      string: ((arg) => ZodString3.create({ ...arg, coerce: true })),
      number: ((arg) => ZodNumber3.create({ ...arg, coerce: true })),
      boolean: ((arg) => ZodBoolean3.create({
        ...arg,
        coerce: true
      })),
      bigint: ((arg) => ZodBigInt3.create({ ...arg, coerce: true })),
      date: ((arg) => ZodDate3.create({ ...arg, coerce: true }))
    };
    exports.NEVER = parseUtil_js_1.INVALID;
  }
});

// ../pi-mono/node_modules/zod/v3/external.cjs
var require_external = __commonJS({
  "../pi-mono/node_modules/zod/v3/external.cjs"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __exportStar = exports && exports.__exportStar || function(m4, exports2) {
      for (var p4 in m4) if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4)) __createBinding(exports2, m4, p4);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar(require_errors(), exports);
    __exportStar(require_parseUtil(), exports);
    __exportStar(require_typeAliases(), exports);
    __exportStar(require_util(), exports);
    __exportStar(require_types(), exports);
    __exportStar(require_ZodError(), exports);
  }
});

// ../pi-mono/node_modules/zod/v3/index.cjs
var require_v3 = __commonJS({
  "../pi-mono/node_modules/zod/v3/index.cjs"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k2 in mod) if (k2 !== "default" && Object.prototype.hasOwnProperty.call(mod, k2)) __createBinding(result, mod, k2);
      }
      __setModuleDefault(result, mod);
      return result;
    };
    var __exportStar = exports && exports.__exportStar || function(m4, exports2) {
      for (var p4 in m4) if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4)) __createBinding(exports2, m4, p4);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.z = void 0;
    var z3 = __importStar(require_external());
    exports.z = z3;
    __exportStar(require_external(), exports);
    exports.default = z3;
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/lib/base64.js
var require_base64 = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/lib/base64.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.zodInbound = exports.zodOutbound = void 0;
    exports.bytesToBase64 = bytesToBase64;
    exports.bytesFromBase64 = bytesFromBase64;
    exports.stringToBytes = stringToBytes2;
    exports.stringFromBytes = stringFromBytes;
    exports.stringToBase64 = stringToBase64;
    exports.stringFromBase64 = stringFromBase64;
    var z3 = __importStar(require_v3());
    function bytesToBase64(u8arr) {
      return btoa(String.fromCodePoint(...u8arr));
    }
    function bytesFromBase64(encoded) {
      return Uint8Array.from(atob(encoded), (c6) => c6.charCodeAt(0));
    }
    function stringToBytes2(str2) {
      return new TextEncoder().encode(str2);
    }
    function stringFromBytes(u8arr) {
      return new TextDecoder().decode(u8arr);
    }
    function stringToBase64(str2) {
      return bytesToBase64(stringToBytes2(str2));
    }
    function stringFromBase64(b64str) {
      return stringFromBytes(bytesFromBase64(b64str));
    }
    exports.zodOutbound = z3.instanceof(Uint8Array).or(z3.string().transform(stringToBytes2));
    exports.zodInbound = z3.instanceof(Uint8Array).or(z3.string().transform(bytesFromBase64));
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/lib/is-plain-object.js
var require_is_plain_object = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/lib/is-plain-object.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.isPlainObject = isPlainObject2;
    function isPlainObject2(value) {
      if (typeof value !== "object" || value === null) {
        return false;
      }
      const prototype = Object.getPrototypeOf(value);
      return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/lib/encodings.js
var require_encodings = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/lib/encodings.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.encodeDeepObjectQuery = exports.encodePipeDelimitedQuery = exports.encodeSpaceDelimitedQuery = exports.encodeFormQuery = exports.encodeJSONQuery = exports.encodeSimple = exports.encodePipeDelimited = exports.encodeSpaceDelimited = exports.encodeForm = exports.EncodingError = void 0;
    exports.encodeMatrix = encodeMatrix;
    exports.encodeLabel = encodeLabel;
    exports.encodeBodyForm = encodeBodyForm;
    exports.encodeDeepObject = encodeDeepObject;
    exports.encodeDeepObjectObject = encodeDeepObjectObject;
    exports.encodeJSON = encodeJSON;
    exports.queryJoin = queryJoin;
    exports.queryEncoder = queryEncoder;
    exports.appendForm = appendForm;
    var base64_js_1 = require_base64();
    var is_plain_object_js_1 = require_is_plain_object();
    var EncodingError = class extends Error {
      constructor(message) {
        super(message);
        this.name = "EncodingError";
      }
    };
    exports.EncodingError = EncodingError;
    function encodeMatrix(key, value, options) {
      let out = "";
      const pairs = options?.explode ? explode(key, value) : [[key, value]];
      if (pairs.every(([_3, v4]) => v4 == null)) {
        return;
      }
      const encodeString = (v4) => {
        return options?.charEncoding === "percent" ? encodeURIComponent(v4) : v4;
      };
      const encodeValue = (v4) => encodeString(serializeValue(v4));
      pairs.forEach(([pk, pv]) => {
        let tmp = "";
        let encValue = null;
        if (pv == null) {
          return;
        } else if (Array.isArray(pv)) {
          encValue = mapDefined(pv, (v4) => `${encodeValue(v4)}`)?.join(",");
        } else if ((0, is_plain_object_js_1.isPlainObject)(pv)) {
          const mapped = mapDefinedEntries(Object.entries(pv), ([k2, v4]) => {
            return `,${encodeString(k2)},${encodeValue(v4)}`;
          });
          encValue = mapped?.join("").slice(1);
        } else {
          encValue = `${encodeValue(pv)}`;
        }
        if (encValue == null) {
          return;
        }
        const keyPrefix = encodeString(pk);
        tmp = `${keyPrefix}=${encValue}`;
        if (tmp === `${keyPrefix}=`) {
          tmp = tmp.slice(0, -1);
        }
        if (!tmp) {
          return;
        }
        out += `;${tmp}`;
      });
      return out;
    }
    function encodeLabel(key, value, options) {
      let out = "";
      const pairs = options?.explode ? explode(key, value) : [[key, value]];
      if (pairs.every(([_3, v4]) => v4 == null)) {
        return;
      }
      const encodeString = (v4) => {
        return options?.charEncoding === "percent" ? encodeURIComponent(v4) : v4;
      };
      const encodeValue = (v4) => encodeString(serializeValue(v4));
      pairs.forEach(([pk, pv]) => {
        let encValue = "";
        if (pv == null) {
          return;
        } else if (Array.isArray(pv)) {
          encValue = mapDefined(pv, (v4) => `${encodeValue(v4)}`)?.join(".");
        } else if ((0, is_plain_object_js_1.isPlainObject)(pv)) {
          const mapped = mapDefinedEntries(Object.entries(pv), ([k2, v4]) => {
            return `.${encodeString(k2)}.${encodeValue(v4)}`;
          });
          encValue = mapped?.join("").slice(1);
        } else {
          const k2 = options?.explode && (0, is_plain_object_js_1.isPlainObject)(value) ? `${encodeString(pk)}=` : "";
          encValue = `${k2}${encodeValue(pv)}`;
        }
        out += encValue == null ? "" : `.${encValue}`;
      });
      return out;
    }
    function formEncoder(sep2) {
      return (key, value, options) => {
        let out = "";
        const pairs = options?.explode ? explode(key, value) : [[key, value]];
        if (pairs.every(([_3, v4]) => v4 == null)) {
          return;
        }
        const encodeString = (v4) => {
          return options?.charEncoding === "percent" ? encodeURIComponent(v4) : v4;
        };
        const encodeValue = (v4) => encodeString(serializeValue(v4));
        const encodedSep = encodeString(sep2);
        pairs.forEach(([pk, pv]) => {
          let tmp = "";
          let encValue = null;
          if (pv == null) {
            return;
          } else if (Array.isArray(pv)) {
            encValue = mapDefined(pv, (v4) => `${encodeValue(v4)}`)?.join(encodedSep);
          } else if ((0, is_plain_object_js_1.isPlainObject)(pv)) {
            encValue = mapDefinedEntries(Object.entries(pv), ([k2, v4]) => {
              return `${encodeString(k2)}${encodedSep}${encodeValue(v4)}`;
            })?.join(encodedSep);
          } else {
            encValue = `${encodeValue(pv)}`;
          }
          if (encValue == null) {
            return;
          }
          tmp = `${encodeString(pk)}=${encValue}`;
          if (!tmp || tmp === "=") {
            return;
          }
          out += `&${tmp}`;
        });
        return out.slice(1);
      };
    }
    exports.encodeForm = formEncoder(",");
    exports.encodeSpaceDelimited = formEncoder(" ");
    exports.encodePipeDelimited = formEncoder("|");
    function encodeBodyForm(key, value, options) {
      let out = "";
      const pairs = options?.explode ? explode(key, value) : [[key, value]];
      const encodeString = (v4) => {
        return options?.charEncoding === "percent" ? encodeURIComponent(v4) : v4;
      };
      const encodeValue = (v4) => encodeString(serializeValue(v4));
      pairs.forEach(([pk, pv]) => {
        let tmp = "";
        let encValue = "";
        if (pv == null) {
          return;
        } else if (Array.isArray(pv)) {
          encValue = JSON.stringify(pv, jsonReplacer);
        } else if ((0, is_plain_object_js_1.isPlainObject)(pv)) {
          encValue = JSON.stringify(pv, jsonReplacer);
        } else {
          encValue = `${encodeValue(pv)}`;
        }
        tmp = `${encodeString(pk)}=${encValue}`;
        if (!tmp || tmp === "=") {
          return;
        }
        out += `&${tmp}`;
      });
      return out.slice(1);
    }
    function encodeDeepObject(key, value, options) {
      if (value == null) {
        return;
      }
      if (!(0, is_plain_object_js_1.isPlainObject)(value)) {
        throw new EncodingError(`Value of parameter '${key}' which uses deepObject encoding must be an object or null`);
      }
      return encodeDeepObjectObject(key, value, options);
    }
    function encodeDeepObjectObject(key, value, options) {
      if (value == null) {
        return;
      }
      let out = "";
      const encodeString = (v4) => {
        return options?.charEncoding === "percent" ? encodeURIComponent(v4) : v4;
      };
      if (!(0, is_plain_object_js_1.isPlainObject)(value)) {
        throw new EncodingError(`Expected parameter '${key}' to be an object.`);
      }
      Object.entries(value).forEach(([ck, cv]) => {
        if (cv == null) {
          return;
        }
        const pk = `${key}[${ck}]`;
        if ((0, is_plain_object_js_1.isPlainObject)(cv)) {
          const objOut = encodeDeepObjectObject(pk, cv, options);
          out += objOut == null ? "" : `&${objOut}`;
          return;
        }
        const pairs = Array.isArray(cv) ? cv : [cv];
        const encoded = mapDefined(pairs, (v4) => {
          return `${encodeString(pk)}=${encodeString(serializeValue(v4))}`;
        })?.join("&");
        out += encoded == null ? "" : `&${encoded}`;
      });
      return out.slice(1);
    }
    function encodeJSON(key, value, options) {
      if (typeof value === "undefined") {
        return;
      }
      const encodeString = (v4) => {
        return options?.charEncoding === "percent" ? encodeURIComponent(v4) : v4;
      };
      const encVal = encodeString(JSON.stringify(value, jsonReplacer));
      return options?.explode ? encVal : `${encodeString(key)}=${encVal}`;
    }
    var encodeSimple = (key, value, options) => {
      let out = "";
      const pairs = options?.explode ? explode(key, value) : [[key, value]];
      if (pairs.every(([_3, v4]) => v4 == null)) {
        return;
      }
      const encodeString = (v4) => {
        return options?.charEncoding === "percent" ? encodeURIComponent(v4) : v4;
      };
      const encodeValue = (v4) => encodeString(serializeValue(v4));
      pairs.forEach(([pk, pv]) => {
        let tmp = "";
        if (pv == null) {
          return;
        } else if (Array.isArray(pv)) {
          tmp = mapDefined(pv, (v4) => `${encodeValue(v4)}`)?.join(",");
        } else if ((0, is_plain_object_js_1.isPlainObject)(pv)) {
          const mapped = mapDefinedEntries(Object.entries(pv), ([k2, v4]) => {
            return `,${encodeString(k2)},${encodeValue(v4)}`;
          });
          tmp = mapped?.join("").slice(1);
        } else {
          const k2 = options?.explode && (0, is_plain_object_js_1.isPlainObject)(value) ? `${pk}=` : "";
          tmp = `${k2}${encodeValue(pv)}`;
        }
        out += tmp ? `,${tmp}` : "";
      });
      return out.slice(1);
    };
    exports.encodeSimple = encodeSimple;
    function explode(key, value) {
      if (Array.isArray(value)) {
        return value.map((v4) => [key, v4]);
      } else if ((0, is_plain_object_js_1.isPlainObject)(value)) {
        const o9 = value ?? {};
        return Object.entries(o9).map(([k2, v4]) => [k2, v4]);
      } else {
        return [[key, value]];
      }
    }
    function serializeValue(value) {
      if (value == null) {
        return "";
      } else if (value instanceof Date) {
        return value.toISOString();
      } else if (value instanceof Uint8Array) {
        return (0, base64_js_1.bytesToBase64)(value);
      } else if (typeof value === "object") {
        return JSON.stringify(value, jsonReplacer);
      }
      return `${value}`;
    }
    function jsonReplacer(_3, value) {
      if (value instanceof Uint8Array) {
        return (0, base64_js_1.bytesToBase64)(value);
      } else {
        return value;
      }
    }
    function mapDefined(inp, mapper) {
      const res = inp.reduce((acc, v4) => {
        if (v4 == null) {
          return acc;
        }
        const m4 = mapper(v4);
        if (m4 == null) {
          return acc;
        }
        acc.push(m4);
        return acc;
      }, []);
      return res.length ? res : null;
    }
    function mapDefinedEntries(inp, mapper) {
      const acc = [];
      for (const [k2, v4] of inp) {
        if (v4 == null) {
          continue;
        }
        const m4 = mapper([k2, v4]);
        if (m4 == null) {
          continue;
        }
        acc.push(m4);
      }
      return acc.length ? acc : null;
    }
    function queryJoin(...args) {
      return args.filter(Boolean).join("&");
    }
    function queryEncoder(f4) {
      const bulkEncode = function(values2, options) {
        const opts = {
          ...options,
          explode: options?.explode ?? true,
          charEncoding: options?.charEncoding ?? "percent"
        };
        const allowEmptySet = new Set(options?.allowEmptyValue ?? []);
        const encoded = Object.entries(values2).map(([key, value]) => {
          if (allowEmptySet.has(key)) {
            if (value === void 0 || value === null || value === "" || Array.isArray(value) && value.length === 0) {
              return `${encodeURIComponent(key)}=`;
            }
          }
          return f4(key, value, opts);
        });
        return queryJoin(...encoded);
      };
      return bulkEncode;
    }
    exports.encodeJSONQuery = queryEncoder(encodeJSON);
    exports.encodeFormQuery = queryEncoder(exports.encodeForm);
    exports.encodeSpaceDelimitedQuery = queryEncoder(exports.encodeSpaceDelimited);
    exports.encodePipeDelimitedQuery = queryEncoder(exports.encodePipeDelimited);
    exports.encodeDeepObjectQuery = queryEncoder(encodeDeepObject);
    function appendForm(fd, key, value, fileName) {
      if (value == null) {
        return;
      } else if (value instanceof Blob && fileName) {
        fd.append(key, value, fileName);
      } else if (value instanceof Blob) {
        fd.append(key, value);
      } else {
        fd.append(key, String(value));
      }
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/lib/dlv.js
var require_dlv = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/lib/dlv.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.dlv = dlv;
    function dlv(obj, key, def, p4, undef) {
      key = Array.isArray(key) ? key : key.split(".");
      for (p4 = 0; p4 < key.length; p4++) {
        const k2 = key[p4];
        obj = k2 != null && obj ? obj[k2] : undef;
      }
      return obj === undef ? def : obj;
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/lib/env.js
var require_env = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/lib/env.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.envSchema = void 0;
    exports.env = env;
    exports.resetEnv = resetEnv;
    var z3 = __importStar(require_v3());
    var dlv_js_1 = require_dlv();
    exports.envSchema = z3.object({
      MISTRAL_API_KEY: z3.string().optional(),
      MISTRAL_DEBUG: z3.coerce.boolean().optional()
    });
    function isDeno() {
      if ("Deno" in globalThis) {
        return true;
      }
      return false;
    }
    var envMemo = void 0;
    function env() {
      if (envMemo) {
        return envMemo;
      }
      let envObject = {};
      if (isDeno()) {
        envObject = globalThis.Deno?.env?.toObject?.() ?? {};
      } else {
        envObject = (0, dlv_js_1.dlv)(globalThis, "process.env") ?? {};
      }
      envMemo = exports.envSchema.parse(envObject);
      return envMemo;
    }
    function resetEnv() {
      envMemo = void 0;
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/lib/retries.js
var require_retries = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/lib/retries.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TemporaryError = exports.PermanentError = void 0;
    exports.retry = retry;
    var http_js_1 = require_http();
    var defaultBackoff = {
      initialInterval: 500,
      maxInterval: 6e4,
      exponent: 1.5,
      maxElapsedTime: 36e5
    };
    var PermanentError = class _PermanentError extends Error {
      constructor(message, options) {
        let msg = message;
        if (options?.cause) {
          msg += `: ${options.cause}`;
        }
        super(msg, options);
        this.name = "PermanentError";
        if (typeof this.cause === "undefined") {
          this.cause = options?.cause;
        }
        Object.setPrototypeOf(this, _PermanentError.prototype);
      }
    };
    exports.PermanentError = PermanentError;
    var TemporaryError = class _TemporaryError extends Error {
      constructor(message, response) {
        super(message);
        this.response = response;
        this.name = "TemporaryError";
        Object.setPrototypeOf(this, _TemporaryError.prototype);
      }
    };
    exports.TemporaryError = TemporaryError;
    async function retry(fetchFn, options) {
      switch (options.config.strategy) {
        case "backoff":
          return retryBackoff(wrapFetcher(fetchFn, {
            statusCodes: options.statusCodes,
            retryConnectionErrors: !!options.config.retryConnectionErrors
          }), options.config.backoff ?? defaultBackoff);
        default:
          return await fetchFn();
      }
    }
    function wrapFetcher(fn, options) {
      return async () => {
        try {
          const res = await fn();
          if (isRetryableResponse(res, options.statusCodes)) {
            throw new TemporaryError("Response failed with retryable status code", res);
          }
          return res;
        } catch (err) {
          if (err instanceof TemporaryError) {
            throw err;
          }
          if (options.retryConnectionErrors && ((0, http_js_1.isTimeoutError)(err) || (0, http_js_1.isConnectionError)(err))) {
            throw err;
          }
          throw new PermanentError("Permanent error", { cause: err });
        }
      };
    }
    var codeRangeRE = new RegExp("^[0-9]xx$", "i");
    function isRetryableResponse(res, statusCodes) {
      const actual = `${res.status}`;
      return statusCodes.some((code) => {
        if (!codeRangeRE.test(code)) {
          return code === actual;
        }
        const expectFamily = code.charAt(0);
        if (!expectFamily) {
          throw new Error("Invalid status code range");
        }
        const actualFamily = actual.charAt(0);
        if (!actualFamily) {
          throw new Error(`Invalid response status code: ${actual}`);
        }
        return actualFamily === expectFamily;
      });
    }
    async function retryBackoff(fn, strategy) {
      const { maxElapsedTime, initialInterval, exponent, maxInterval } = strategy;
      const start = Date.now();
      let x2 = 0;
      while (true) {
        try {
          const res = await fn();
          return res;
        } catch (err) {
          if (err instanceof PermanentError) {
            throw err.cause;
          }
          const elapsed = Date.now() - start;
          if (elapsed > maxElapsedTime) {
            if (err instanceof TemporaryError) {
              return err.response;
            }
            throw err;
          }
          let retryInterval = 0;
          if (err instanceof TemporaryError) {
            retryInterval = retryIntervalFromResponse(err.response);
          }
          if (retryInterval <= 0) {
            retryInterval = initialInterval * Math.pow(x2, exponent) + Math.random() * 1e3;
          }
          const d4 = Math.min(retryInterval, maxInterval);
          await delay(d4);
          x2++;
        }
      }
    }
    function retryIntervalFromResponse(res) {
      const retryVal = res.headers.get("retry-after") || "";
      if (!retryVal) {
        return 0;
      }
      const parsedNumber = Number(retryVal);
      if (Number.isInteger(parsedNumber)) {
        return parsedNumber * 1e3;
      }
      const parsedDate = Date.parse(retryVal);
      if (Number.isInteger(parsedDate)) {
        const deltaMS = parsedDate - Date.now();
        return deltaMS > 0 ? Math.ceil(deltaMS) : 0;
      }
      return 0;
    }
    async function delay(delay2) {
      return new Promise((resolve) => setTimeout(resolve, delay2));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/lib/sdks.js
var require_sdks = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/lib/sdks.js"(exports) {
    "use strict";
    init_process_shim();
    var __classPrivateFieldSet3 = exports && exports.__classPrivateFieldSet || function(receiver, state, value, kind, f4) {
      if (kind === "m") throw new TypeError("Private method is not writable");
      if (kind === "a" && !f4) throw new TypeError("Private accessor was defined without a setter");
      if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
      return kind === "a" ? f4.call(receiver, value) : f4 ? f4.value = value : state.set(receiver, value), value;
    };
    var __classPrivateFieldGet3 = exports && exports.__classPrivateFieldGet || function(receiver, state, kind, f4) {
      if (kind === "a" && !f4) throw new TypeError("Private accessor was defined without a getter");
      if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
      return kind === "m" ? f4 : kind === "a" ? f4.call(receiver) : f4 ? f4.value : state.get(receiver);
    };
    var _ClientSDK_httpClient;
    var _ClientSDK_hooks;
    var _ClientSDK_logger;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ClientSDK = void 0;
    var hooks_js_1 = require_hooks();
    var httpclienterrors_js_1 = require_httpclienterrors();
    var fp_js_1 = require_fp();
    var base64_js_1 = require_base64();
    var config_js_1 = require_config();
    var encodings_js_1 = require_encodings();
    var env_js_1 = require_env();
    var http_js_1 = require_http();
    var retries_js_1 = require_retries();
    var gt = typeof globalThis === "undefined" ? null : globalThis;
    var webWorkerLike = typeof gt === "object" && gt != null && "importScripts" in gt && typeof gt["importScripts"] === "function";
    var isBrowserLike = webWorkerLike || typeof navigator !== "undefined" && "serviceWorker" in navigator || typeof window === "object" && typeof window.document !== "undefined";
    var ClientSDK = class {
      constructor(options = {}) {
        _ClientSDK_httpClient.set(this, void 0);
        _ClientSDK_hooks.set(this, void 0);
        _ClientSDK_logger.set(this, void 0);
        const opt = options;
        if (typeof opt === "object" && opt != null && "hooks" in opt && opt.hooks instanceof hooks_js_1.SDKHooks) {
          __classPrivateFieldSet3(this, _ClientSDK_hooks, opt.hooks, "f");
        } else {
          __classPrivateFieldSet3(this, _ClientSDK_hooks, new hooks_js_1.SDKHooks(), "f");
        }
        const url = (0, config_js_1.serverURLFromOptions)(options);
        if (url) {
          url.pathname = url.pathname.replace(/\/+$/, "") + "/";
        }
        const { baseURL, client } = __classPrivateFieldGet3(this, _ClientSDK_hooks, "f").sdkInit({
          baseURL: url,
          client: options.httpClient || new http_js_1.HTTPClient()
        });
        this._baseURL = baseURL;
        __classPrivateFieldSet3(this, _ClientSDK_httpClient, client, "f");
        this._options = { ...options, hooks: __classPrivateFieldGet3(this, _ClientSDK_hooks, "f") };
        __classPrivateFieldSet3(this, _ClientSDK_logger, this._options.debugLogger, "f");
        if (!__classPrivateFieldGet3(this, _ClientSDK_logger, "f") && (0, env_js_1.env)().MISTRAL_DEBUG) {
          __classPrivateFieldSet3(this, _ClientSDK_logger, console, "f");
        }
      }
      _createRequest(context, conf, options) {
        const { method, path: path6, query, headers: opHeaders, security } = conf;
        const base = conf.baseURL ?? this._baseURL;
        if (!base) {
          return (0, fp_js_1.ERR)(new httpclienterrors_js_1.InvalidRequestError("No base URL provided for operation"));
        }
        const reqURL = new URL(base);
        const inputURL = new URL(path6, reqURL);
        if (path6) {
          reqURL.pathname += reqURL.pathname.endsWith("/") ? "" : "/";
          reqURL.pathname += inputURL.pathname.replace(/^\/+/, "");
        }
        let finalQuery = query || "";
        const secQuery = [];
        for (const [k2, v4] of Object.entries(security?.queryParams || {})) {
          const q2 = (0, encodings_js_1.encodeForm)(k2, v4, { charEncoding: "percent" });
          if (typeof q2 !== "undefined") {
            secQuery.push(q2);
          }
        }
        if (secQuery.length) {
          finalQuery += `&${secQuery.join("&")}`;
        }
        if (finalQuery) {
          const q2 = finalQuery.startsWith("&") ? finalQuery.slice(1) : finalQuery;
          reqURL.search = `?${q2}`;
        }
        const headers = new Headers(opHeaders);
        const username = security?.basic.username;
        const password = security?.basic.password;
        if (username != null || password != null) {
          const encoded = (0, base64_js_1.stringToBase64)([username || "", password || ""].join(":"));
          headers.set("Authorization", `Basic ${encoded}`);
        }
        const securityHeaders = new Headers(security?.headers || {});
        for (const [k2, v4] of securityHeaders) {
          headers.set(k2, v4);
        }
        let cookie = headers.get("cookie") || "";
        for (const [k2, v4] of Object.entries(security?.cookies || {})) {
          cookie += `; ${k2}=${v4}`;
        }
        cookie = cookie.startsWith("; ") ? cookie.slice(2) : cookie;
        headers.set("cookie", cookie);
        const userHeaders = new Headers(options?.headers ?? options?.fetchOptions?.headers);
        for (const [k2, v4] of userHeaders) {
          headers.set(k2, v4);
        }
        if (!isBrowserLike) {
          headers.set(conf.uaHeader ?? "user-agent", conf.userAgent ?? config_js_1.SDK_METADATA.userAgent);
        }
        const fetchOptions = {
          ...options?.fetchOptions,
          ...options
        };
        if (!fetchOptions?.signal && conf.timeoutMs && conf.timeoutMs > 0) {
          const timeoutSignal = AbortSignal.timeout(conf.timeoutMs);
          fetchOptions.signal = timeoutSignal;
        }
        if (conf.body instanceof ReadableStream) {
          Object.assign(fetchOptions, { duplex: "half" });
        }
        let input;
        try {
          input = __classPrivateFieldGet3(this, _ClientSDK_hooks, "f").beforeCreateRequest(context, {
            url: reqURL,
            options: {
              ...fetchOptions,
              body: conf.body ?? null,
              headers,
              method
            }
          });
        } catch (err) {
          return (0, fp_js_1.ERR)(new httpclienterrors_js_1.UnexpectedClientError("Create request hook failed to execute", {
            cause: err
          }));
        }
        return (0, fp_js_1.OK)(new Request(input.url, input.options));
      }
      async _do(request, options) {
        const { context, errorCodes } = options;
        return (0, retries_js_1.retry)(async () => {
          const req = await __classPrivateFieldGet3(this, _ClientSDK_hooks, "f").beforeRequest(context, request.clone());
          await logRequest(__classPrivateFieldGet3(this, _ClientSDK_logger, "f"), req).catch((e9) => __classPrivateFieldGet3(this, _ClientSDK_logger, "f")?.log("Failed to log request:", e9));
          let response = await __classPrivateFieldGet3(this, _ClientSDK_httpClient, "f").request(req);
          try {
            if ((0, http_js_1.matchStatusCode)(response, errorCodes)) {
              const result = await __classPrivateFieldGet3(this, _ClientSDK_hooks, "f").afterError(context, response, null);
              if (result.error) {
                throw result.error;
              }
              response = result.response || response;
            } else {
              response = await __classPrivateFieldGet3(this, _ClientSDK_hooks, "f").afterSuccess(context, response);
            }
          } finally {
            await logResponse(__classPrivateFieldGet3(this, _ClientSDK_logger, "f"), response, req).catch((e9) => __classPrivateFieldGet3(this, _ClientSDK_logger, "f")?.log("Failed to log response:", e9));
          }
          return response;
        }, { config: options.retryConfig, statusCodes: options.retryCodes }).then((r8) => (0, fp_js_1.OK)(r8), (err) => {
          switch (true) {
            case (0, http_js_1.isAbortError)(err):
              return (0, fp_js_1.ERR)(new httpclienterrors_js_1.RequestAbortedError("Request aborted by client", {
                cause: err
              }));
            case (0, http_js_1.isTimeoutError)(err):
              return (0, fp_js_1.ERR)(new httpclienterrors_js_1.RequestTimeoutError("Request timed out", { cause: err }));
            case (0, http_js_1.isConnectionError)(err):
              return (0, fp_js_1.ERR)(new httpclienterrors_js_1.ConnectionError("Unable to make request", { cause: err }));
            default:
              return (0, fp_js_1.ERR)(new httpclienterrors_js_1.UnexpectedClientError("Unexpected HTTP client error", {
                cause: err
              }));
          }
        });
      }
    };
    exports.ClientSDK = ClientSDK;
    _ClientSDK_httpClient = /* @__PURE__ */ new WeakMap(), _ClientSDK_hooks = /* @__PURE__ */ new WeakMap(), _ClientSDK_logger = /* @__PURE__ */ new WeakMap();
    var jsonLikeContentTypeRE = /^(application|text)\/([^+]+\+)*json.*/;
    var jsonlLikeContentTypeRE = /^(application|text)\/([^+]+\+)*(jsonl|x-ndjson)\b.*/;
    async function logRequest(logger2, req) {
      if (!logger2) {
        return;
      }
      const contentType = req.headers.get("content-type");
      const ct = contentType?.split(";")[0] || "";
      logger2.group(`> Request: ${req.method} ${req.url}`);
      logger2.group("Headers:");
      for (const [k2, v4] of req.headers.entries()) {
        logger2.log(`${k2}: ${v4}`);
      }
      logger2.groupEnd();
      logger2.group("Body:");
      switch (true) {
        case jsonLikeContentTypeRE.test(ct):
          logger2.log(await req.clone().json());
          break;
        case ct.startsWith("text/"):
          logger2.log(await req.clone().text());
          break;
        case ct === "multipart/form-data": {
          const body = await req.clone().formData();
          for (const [k2, v4] of body) {
            const vlabel = v4 instanceof Blob ? "<Blob>" : v4;
            logger2.log(`${k2}: ${vlabel}`);
          }
          break;
        }
        default:
          logger2.log(`<${contentType}>`);
          break;
      }
      logger2.groupEnd();
      logger2.groupEnd();
    }
    async function logResponse(logger2, res, req) {
      if (!logger2) {
        return;
      }
      const contentType = res.headers.get("content-type");
      const ct = contentType?.split(";")[0] || "";
      logger2.group(`< Response: ${req.method} ${req.url}`);
      logger2.log("Status Code:", res.status, res.statusText);
      logger2.group("Headers:");
      for (const [k2, v4] of res.headers.entries()) {
        logger2.log(`${k2}: ${v4}`);
      }
      logger2.groupEnd();
      logger2.group("Body:");
      switch (true) {
        case ((0, http_js_1.matchContentType)(res, "application/json") || jsonLikeContentTypeRE.test(ct) && !jsonlLikeContentTypeRE.test(ct)):
          logger2.log(await res.clone().json());
          break;
        case ((0, http_js_1.matchContentType)(res, "application/jsonl") || jsonlLikeContentTypeRE.test(ct)):
          logger2.log(await res.clone().text());
          break;
        case (0, http_js_1.matchContentType)(res, "text/event-stream"):
          logger2.log(`<${contentType}>`);
          break;
        case (0, http_js_1.matchContentType)(res, "text/*"):
          logger2.log(await res.clone().text());
          break;
        case (0, http_js_1.matchContentType)(res, "multipart/form-data"): {
          const body = await res.clone().formData();
          for (const [k2, v4] of body) {
            const vlabel = v4 instanceof Blob ? "<Blob>" : v4;
            logger2.log(`${k2}: ${vlabel}`);
          }
          break;
        }
        default:
          logger2.log(`<${contentType}>`);
          break;
      }
      logger2.groupEnd();
      logger2.groupEnd();
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/errors/mistralerror.js
var require_mistralerror = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/errors/mistralerror.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MistralError = void 0;
    var MistralError = class extends Error {
      constructor(message, httpMeta) {
        super(message);
        this.statusCode = httpMeta.response.status;
        this.body = httpMeta.body;
        this.headers = httpMeta.response.headers;
        this.contentType = httpMeta.response.headers.get("content-type") || "";
        this.rawResponse = httpMeta.response;
        this.name = "MistralError";
      }
    };
    exports.MistralError = MistralError;
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/errors/sdkvalidationerror.js
var require_sdkvalidationerror = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/errors/sdkvalidationerror.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SDKValidationError = void 0;
    exports.formatZodError = formatZodError;
    var z3 = __importStar(require_v3());
    var SDKValidationError = class extends Error {
      // Allows for backwards compatibility for `instanceof` checks of `ResponseValidationError`
      static [Symbol.hasInstance](instance) {
        if (!(instance instanceof Error))
          return false;
        if (!("rawValue" in instance))
          return false;
        if (!("rawMessage" in instance))
          return false;
        if (!("pretty" in instance))
          return false;
        if (typeof instance.pretty !== "function")
          return false;
        return true;
      }
      constructor(message, cause, rawValue) {
        super(`${message}: ${cause}`);
        this.name = "SDKValidationError";
        this.cause = cause;
        this.rawValue = rawValue;
        this.rawMessage = message;
      }
      /**
       * Return a pretty-formatted error message if the underlying validation error
       * is a ZodError or some other recognized error type, otherwise return the
       * default error message.
       */
      pretty() {
        if (this.cause instanceof z3.ZodError) {
          return `${this.rawMessage}
${formatZodError(this.cause)}`;
        } else {
          return this.toString();
        }
      }
    };
    exports.SDKValidationError = SDKValidationError;
    function formatZodError(err, level = 0) {
      let pre = "  ".repeat(level);
      pre = level > 0 ? `\u2502${pre}` : pre;
      pre += " ".repeat(level);
      let message = "";
      const append = (str2) => message += `
${pre}${str2}`;
      const len = err.issues.length;
      const headline = len === 1 ? `${len} issue found` : `${len} issues found`;
      if (len) {
        append(`\u250C ${headline}:`);
      }
      for (const issue of err.issues) {
        let path6 = issue.path.join(".");
        path6 = path6 ? `<root>.${path6}` : "<root>";
        append(`\u2502 \u2022 [${path6}]: ${issue.message} (${issue.code})`);
        switch (issue.code) {
          case "invalid_literal":
          case "invalid_type": {
            append(`\u2502     Want: ${issue.expected}`);
            append(`\u2502      Got: ${issue.received}`);
            break;
          }
          case "unrecognized_keys": {
            append(`\u2502     Keys: ${issue.keys.join(", ")}`);
            break;
          }
          case "invalid_enum_value": {
            append(`\u2502     Allowed: ${issue.options.join(", ")}`);
            append(`\u2502         Got: ${issue.received}`);
            break;
          }
          case "invalid_union_discriminator": {
            append(`\u2502     Allowed: ${issue.options.join(", ")}`);
            break;
          }
          case "invalid_union": {
            const len2 = issue.unionErrors.length;
            append(`\u2502   \u2716\uFE0E Attemped to deserialize into one of ${len2} union members:`);
            issue.unionErrors.forEach((err2, i7) => {
              append(`\u2502   \u2716\uFE0E Member ${i7 + 1} of ${len2}`);
              append(`${formatZodError(err2, level + 1)}`);
            });
          }
        }
      }
      if (err.issues.length) {
        append(`\u2514\u2500*`);
      }
      return message.slice(1);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/errors/responsevalidationerror.js
var require_responsevalidationerror = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/errors/responsevalidationerror.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ResponseValidationError = void 0;
    var z3 = __importStar(require_v3());
    var mistralerror_js_1 = require_mistralerror();
    var sdkvalidationerror_js_1 = require_sdkvalidationerror();
    var ResponseValidationError = class extends mistralerror_js_1.MistralError {
      constructor(message, extra) {
        super(message, extra);
        this.name = "ResponseValidationError";
        this.cause = extra.cause;
        this.rawValue = extra.rawValue;
        this.rawMessage = extra.rawMessage;
      }
      /**
       * Return a pretty-formatted error message if the underlying validation error
       * is a ZodError or some other recognized error type, otherwise return the
       * default error message.
       */
      pretty() {
        if (this.cause instanceof z3.ZodError) {
          return `${this.rawMessage}
${(0, sdkvalidationerror_js_1.formatZodError)(this.cause)}`;
        } else {
          return this.toString();
        }
      }
    };
    exports.ResponseValidationError = ResponseValidationError;
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/errors/sdkerror.js
var require_sdkerror = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/errors/sdkerror.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SDKError = void 0;
    var mistralerror_js_1 = require_mistralerror();
    var SDKError = class extends mistralerror_js_1.MistralError {
      constructor(message, httpMeta) {
        if (message) {
          message += `: `;
        }
        message += `Status ${httpMeta.response.status}`;
        const contentType = httpMeta.response.headers.get("content-type") || `""`;
        if (contentType !== "application/json") {
          message += ` Content-Type ${contentType.includes(" ") ? `"${contentType}"` : contentType}`;
        }
        const body = httpMeta.body || `""`;
        message += body.length > 100 ? "\n" : ". ";
        let bodyDisplay = body;
        if (body.length > 1e4) {
          const truncated = body.substring(0, 1e4);
          const remaining = body.length - 1e4;
          bodyDisplay = `${truncated}...and ${remaining} more chars`;
        }
        message += `Body: ${bodyDisplay}`;
        message = message.trim();
        super(message, httpMeta);
        this.name = "SDKError";
      }
    };
    exports.SDKError = SDKError;
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/lib/matchers.js
var require_matchers = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/lib/matchers.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.jsonErr = jsonErr;
    exports.json = json2;
    exports.jsonl = jsonl;
    exports.jsonlErr = jsonlErr;
    exports.textErr = textErr;
    exports.text = text3;
    exports.bytesErr = bytesErr;
    exports.bytes = bytes;
    exports.streamErr = streamErr;
    exports.stream = stream2;
    exports.sseErr = sseErr;
    exports.sse = sse;
    exports.nilErr = nilErr;
    exports.nil = nil;
    exports.fail = fail;
    exports.match = match2;
    exports.unpackHeaders = unpackHeaders;
    var responsevalidationerror_js_1 = require_responsevalidationerror();
    var sdkerror_js_1 = require_sdkerror();
    var fp_js_1 = require_fp();
    var http_js_1 = require_http();
    var is_plain_object_js_1 = require_is_plain_object();
    var DEFAULT_CONTENT_TYPES = {
      jsonl: "application/jsonl",
      json: "application/json",
      text: "text/plain",
      bytes: "application/octet-stream",
      stream: "application/octet-stream",
      sse: "text/event-stream",
      nil: "*",
      fail: "*"
    };
    function jsonErr(codes, schema, options) {
      return { ...options, err: true, enc: "json", codes, schema };
    }
    function json2(codes, schema, options) {
      return { ...options, enc: "json", codes, schema };
    }
    function jsonl(codes, schema, options) {
      return { ...options, enc: "jsonl", codes, schema };
    }
    function jsonlErr(codes, schema, options) {
      return { ...options, err: true, enc: "jsonl", codes, schema };
    }
    function textErr(codes, schema, options) {
      return { ...options, err: true, enc: "text", codes, schema };
    }
    function text3(codes, schema, options) {
      return { ...options, enc: "text", codes, schema };
    }
    function bytesErr(codes, schema, options) {
      return { ...options, err: true, enc: "bytes", codes, schema };
    }
    function bytes(codes, schema, options) {
      return { ...options, enc: "bytes", codes, schema };
    }
    function streamErr(codes, schema, options) {
      return { ...options, err: true, enc: "stream", codes, schema };
    }
    function stream2(codes, schema, options) {
      return { ...options, enc: "stream", codes, schema };
    }
    function sseErr(codes, schema, options) {
      return { ...options, err: true, enc: "sse", codes, schema };
    }
    function sse(codes, schema, options) {
      return { ...options, enc: "sse", codes, schema };
    }
    function nilErr(codes, schema, options) {
      return { ...options, err: true, enc: "nil", codes, schema };
    }
    function nil(codes, schema, options) {
      return { ...options, enc: "nil", codes, schema };
    }
    function fail(codes) {
      return { enc: "fail", codes };
    }
    function match2(...matchers) {
      return async function matchFunc(response, request, options) {
        let raw;
        let matcher;
        for (const match3 of matchers) {
          const { codes } = match3;
          const ctpattern = "ctype" in match3 ? match3.ctype : DEFAULT_CONTENT_TYPES[match3.enc];
          if (ctpattern && (0, http_js_1.matchResponse)(response, codes, ctpattern)) {
            matcher = match3;
            break;
          } else if (!ctpattern && (0, http_js_1.matchStatusCode)(response, codes)) {
            matcher = match3;
            break;
          }
        }
        if (!matcher) {
          return [{
            ok: false,
            error: new sdkerror_js_1.SDKError("Unexpected Status or Content-Type", {
              response,
              request,
              body: await response.text().catch(() => "")
            })
          }, raw];
        }
        const encoding = matcher.enc;
        let body = "";
        switch (encoding) {
          case "json":
            body = await response.text();
            raw = JSON.parse(body);
            break;
          case "jsonl":
            raw = response.body;
            break;
          case "bytes":
            raw = new Uint8Array(await response.arrayBuffer());
            break;
          case "stream":
            raw = response.body;
            break;
          case "text":
            body = await response.text();
            raw = body;
            break;
          case "sse":
            raw = response.body;
            break;
          case "nil":
            body = await response.text();
            raw = void 0;
            break;
          case "fail":
            body = await response.text();
            raw = body;
            break;
          default:
            encoding;
            throw new Error(`Unsupported response type: ${encoding}`);
        }
        if (matcher.enc === "fail") {
          return [{
            ok: false,
            error: new sdkerror_js_1.SDKError("API error occurred", { request, response, body })
          }, raw];
        }
        const resultKey = matcher.key || options?.resultKey;
        let data;
        if ("err" in matcher) {
          data = {
            ...options?.extraFields,
            ...matcher.hdrs ? { Headers: unpackHeaders(response.headers) } : null,
            ...(0, is_plain_object_js_1.isPlainObject)(raw) ? raw : null,
            request$: request,
            response$: response,
            body$: body
          };
        } else if (resultKey) {
          data = {
            ...options?.extraFields,
            ...matcher.hdrs ? { Headers: unpackHeaders(response.headers) } : null,
            [resultKey]: raw
          };
        } else if (matcher.hdrs) {
          data = {
            ...options?.extraFields,
            ...matcher.hdrs ? { Headers: unpackHeaders(response.headers) } : null,
            ...(0, is_plain_object_js_1.isPlainObject)(raw) ? raw : null
          };
        } else {
          data = raw;
        }
        if ("err" in matcher) {
          const result = safeParseResponse(data, (v4) => matcher.schema.parse(v4), "Response validation failed", { request, response, body });
          return [result.ok ? { ok: false, error: result.value } : result, raw];
        } else {
          return [
            safeParseResponse(data, (v4) => matcher.schema.parse(v4), "Response validation failed", { request, response, body }),
            raw
          ];
        }
      };
    }
    var headerValRE = /, */;
    function unpackHeaders(headers) {
      const out = {};
      for (const [k2, v4] of headers.entries()) {
        out[k2] = v4.split(headerValRE);
      }
      return out;
    }
    function safeParseResponse(rawValue, fn, errorMessage, httpMeta) {
      try {
        return (0, fp_js_1.OK)(fn(rawValue));
      } catch (err) {
        return (0, fp_js_1.ERR)(new responsevalidationerror_js_1.ResponseValidationError(errorMessage, {
          cause: err,
          rawValue,
          rawMessage: errorMessage,
          ...httpMeta
        }));
      }
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/lib/primitives.js
var require_primitives = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/lib/primitives.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.invariant = invariant;
    exports.remap = remap;
    exports.combineSignals = combineSignals;
    exports.abortSignalAny = abortSignalAny;
    exports.compactMap = compactMap;
    exports.allRequired = allRequired;
    var InvariantError = class extends Error {
      constructor(message) {
        super(message);
        this.name = "InvariantError";
      }
    };
    function invariant(condition, message) {
      if (!condition) {
        throw new InvariantError(message);
      }
    }
    function remap(inp, mappings) {
      let out = {};
      if (!Object.keys(mappings).length) {
        out = inp;
        return out;
      }
      for (const [k2, v4] of Object.entries(inp)) {
        const j3 = mappings[k2];
        if (j3 === null) {
          continue;
        }
        out[j3 ?? k2] = v4;
      }
      return out;
    }
    function combineSignals(...signals) {
      const filtered = [];
      for (const signal of signals) {
        if (signal) {
          filtered.push(signal);
        }
      }
      switch (filtered.length) {
        case 0:
        case 1:
          return filtered[0] || null;
        default:
          if ("any" in AbortSignal && typeof AbortSignal.any === "function") {
            return AbortSignal.any(filtered);
          }
          return abortSignalAny(filtered);
      }
    }
    function abortSignalAny(signals) {
      const controller = new AbortController();
      const result = controller.signal;
      if (!signals.length) {
        return controller.signal;
      }
      if (signals.length === 1) {
        return signals[0] || controller.signal;
      }
      for (const signal of signals) {
        if (signal.aborted) {
          return signal;
        }
      }
      function abort() {
        controller.abort(this.reason);
        clean();
      }
      const signalRefs = [];
      function clean() {
        for (const signalRef of signalRefs) {
          const signal = signalRef.deref();
          if (signal) {
            signal.removeEventListener("abort", abort);
          }
        }
      }
      for (const signal of signals) {
        signalRefs.push(new WeakRef(signal));
        signal.addEventListener("abort", abort);
      }
      return result;
    }
    function compactMap(values2) {
      const out = {};
      for (const [k2, v4] of Object.entries(values2)) {
        if (typeof v4 !== "undefined") {
          out[k2] = v4;
        }
      }
      return out;
    }
    function allRequired(v4) {
      if (Object.values(v4).every((x2) => x2 == null)) {
        return void 0;
      }
      return v4;
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/lib/schemas.js
var require_schemas = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/lib/schemas.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.parse = parse;
    exports.safeParse = safeParse;
    exports.collectExtraKeys = collectExtraKeys;
    var v3_1 = require_v3();
    var sdkvalidationerror_js_1 = require_sdkvalidationerror();
    var fp_js_1 = require_fp();
    function parse(rawValue, fn, errorMessage) {
      try {
        return fn(rawValue);
      } catch (err) {
        if (err instanceof v3_1.ZodError) {
          throw new sdkvalidationerror_js_1.SDKValidationError(errorMessage, err, rawValue);
        }
        throw err;
      }
    }
    function safeParse(rawValue, fn, errorMessage) {
      try {
        return (0, fp_js_1.OK)(fn(rawValue));
      } catch (err) {
        return (0, fp_js_1.ERR)(new sdkvalidationerror_js_1.SDKValidationError(errorMessage, err, rawValue));
      }
    }
    function collectExtraKeys(obj, extrasKey, optional) {
      return obj.transform((val2) => {
        const extras = {};
        const { shape } = obj;
        for (const [key] of Object.entries(val2)) {
          if (key in shape) {
            continue;
          }
          const v4 = val2[key];
          if (typeof v4 === "undefined") {
            continue;
          }
          extras[key] = v4;
          delete val2[key];
        }
        if (optional && Object.keys(extras).length === 0) {
          return val2;
        }
        return { ...val2, [extrasKey]: extras };
      });
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/lib/security.js
var require_security = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/lib/security.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SecurityError = exports.SecurityErrorCode = void 0;
    exports.resolveSecurity = resolveSecurity;
    exports.resolveGlobalSecurity = resolveGlobalSecurity;
    exports.extractSecurity = extractSecurity;
    var env_js_1 = require_env();
    var SecurityErrorCode;
    (function(SecurityErrorCode2) {
      SecurityErrorCode2["Incomplete"] = "incomplete";
      SecurityErrorCode2["UnrecognisedSecurityType"] = "unrecognized_security_type";
    })(SecurityErrorCode || (exports.SecurityErrorCode = SecurityErrorCode = {}));
    var SecurityError = class _SecurityError extends Error {
      constructor(code, message) {
        super(message);
        this.code = code;
        this.name = "SecurityError";
      }
      static incomplete() {
        return new _SecurityError(SecurityErrorCode.Incomplete, "Security requirements not met in order to perform the operation");
      }
      static unrecognizedType(type) {
        return new _SecurityError(SecurityErrorCode.UnrecognisedSecurityType, `Unrecognised security type: ${type}`);
      }
    };
    exports.SecurityError = SecurityError;
    function resolveSecurity(...options) {
      const state = {
        basic: {},
        headers: {},
        queryParams: {},
        cookies: {},
        oauth2: { type: "none" }
      };
      const option = options.find((opts) => {
        return opts.every((o9) => {
          if (o9.value == null) {
            return false;
          } else if (o9.type === "http:basic") {
            return o9.value.username != null || o9.value.password != null;
          } else if (o9.type === "http:custom") {
            return null;
          } else if (o9.type === "oauth2:password") {
            return typeof o9.value === "string" && !!o9.value;
          } else if (o9.type === "oauth2:client_credentials") {
            if (typeof o9.value == "string") {
              return !!o9.value;
            }
            return o9.value.clientID != null || o9.value.clientSecret != null;
          } else if (typeof o9.value === "string") {
            return !!o9.value;
          } else {
            throw new Error(`Unrecognized security type: ${o9.type} (value type: ${typeof o9.value})`);
          }
        });
      });
      if (option == null) {
        return null;
      }
      option.forEach((spec) => {
        if (spec.value == null) {
          return;
        }
        const { type } = spec;
        switch (type) {
          case "apiKey:header":
            state.headers[spec.fieldName] = spec.value;
            break;
          case "apiKey:query":
            state.queryParams[spec.fieldName] = spec.value;
            break;
          case "apiKey:cookie":
            state.cookies[spec.fieldName] = spec.value;
            break;
          case "http:basic":
            applyBasic(state, spec);
            break;
          case "http:custom":
            break;
          case "http:bearer":
            applyBearer(state, spec);
            break;
          case "oauth2":
            applyBearer(state, spec);
            break;
          case "oauth2:password":
            applyBearer(state, spec);
            break;
          case "oauth2:client_credentials":
            break;
          case "openIdConnect":
            applyBearer(state, spec);
            break;
          default:
            spec;
            throw SecurityError.unrecognizedType(type);
        }
      });
      return state;
    }
    function applyBasic(state, spec) {
      if (spec.value == null) {
        return;
      }
      state.basic = spec.value;
    }
    function applyBearer(state, spec) {
      if (typeof spec.value !== "string" || !spec.value) {
        return;
      }
      let value = spec.value;
      if (value.slice(0, 7).toLowerCase() !== "bearer ") {
        value = `Bearer ${value}`;
      }
      if (spec.fieldName !== void 0) {
        state.headers[spec.fieldName] = value;
      }
    }
    function resolveGlobalSecurity(security) {
      return resolveSecurity([
        {
          fieldName: "Authorization",
          type: "http:bearer",
          value: security?.apiKey ?? (0, env_js_1.env)().MISTRAL_API_KEY
        }
      ]);
    }
    async function extractSecurity(sec) {
      if (sec == null) {
        return;
      }
      return typeof sec === "function" ? sec() : sec;
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/toolconfiguration.js
var require_toolconfiguration = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/toolconfiguration.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ToolConfiguration$outboundSchema = exports.ToolConfiguration$inboundSchema = void 0;
    exports.toolConfigurationToJSON = toolConfigurationToJSON;
    exports.toolConfigurationFromJSON = toolConfigurationFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    exports.ToolConfiguration$inboundSchema = z3.object({
      exclude: z3.nullable(z3.array(z3.string())).optional(),
      include: z3.nullable(z3.array(z3.string())).optional(),
      requires_confirmation: z3.nullable(z3.array(z3.string())).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "requires_confirmation": "requiresConfirmation"
      });
    });
    exports.ToolConfiguration$outboundSchema = z3.object({
      exclude: z3.nullable(z3.array(z3.string())).optional(),
      include: z3.nullable(z3.array(z3.string())).optional(),
      requiresConfirmation: z3.nullable(z3.array(z3.string())).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        requiresConfirmation: "requires_confirmation"
      });
    });
    function toolConfigurationToJSON(toolConfiguration) {
      return JSON.stringify(exports.ToolConfiguration$outboundSchema.parse(toolConfiguration));
    }
    function toolConfigurationFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ToolConfiguration$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ToolConfiguration' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/codeinterpretertool.js
var require_codeinterpretertool = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/codeinterpretertool.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CodeInterpreterTool$outboundSchema = exports.CodeInterpreterTool$inboundSchema = exports.CodeInterpreterToolType$outboundSchema = exports.CodeInterpreterToolType$inboundSchema = exports.CodeInterpreterToolType = void 0;
    exports.codeInterpreterToolToJSON = codeInterpreterToolToJSON;
    exports.codeInterpreterToolFromJSON = codeInterpreterToolFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var toolconfiguration_js_1 = require_toolconfiguration();
    exports.CodeInterpreterToolType = {
      CodeInterpreter: "code_interpreter"
    };
    exports.CodeInterpreterToolType$inboundSchema = z3.nativeEnum(exports.CodeInterpreterToolType);
    exports.CodeInterpreterToolType$outboundSchema = exports.CodeInterpreterToolType$inboundSchema;
    exports.CodeInterpreterTool$inboundSchema = z3.object({
      tool_configuration: z3.nullable(toolconfiguration_js_1.ToolConfiguration$inboundSchema).optional(),
      type: exports.CodeInterpreterToolType$inboundSchema.default("code_interpreter")
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "tool_configuration": "toolConfiguration"
      });
    });
    exports.CodeInterpreterTool$outboundSchema = z3.object({
      toolConfiguration: z3.nullable(toolconfiguration_js_1.ToolConfiguration$outboundSchema).optional(),
      type: exports.CodeInterpreterToolType$outboundSchema.default("code_interpreter")
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        toolConfiguration: "tool_configuration"
      });
    });
    function codeInterpreterToolToJSON(codeInterpreterTool) {
      return JSON.stringify(exports.CodeInterpreterTool$outboundSchema.parse(codeInterpreterTool));
    }
    function codeInterpreterToolFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.CodeInterpreterTool$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'CodeInterpreterTool' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/completionargsstop.js
var require_completionargsstop = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/completionargsstop.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CompletionArgsStop$outboundSchema = exports.CompletionArgsStop$inboundSchema = void 0;
    exports.completionArgsStopToJSON = completionArgsStopToJSON;
    exports.completionArgsStopFromJSON = completionArgsStopFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    exports.CompletionArgsStop$inboundSchema = z3.union([z3.string(), z3.array(z3.string())]);
    exports.CompletionArgsStop$outboundSchema = z3.union([z3.string(), z3.array(z3.string())]);
    function completionArgsStopToJSON(completionArgsStop) {
      return JSON.stringify(exports.CompletionArgsStop$outboundSchema.parse(completionArgsStop));
    }
    function completionArgsStopFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.CompletionArgsStop$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'CompletionArgsStop' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/prediction.js
var require_prediction = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/prediction.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Prediction$outboundSchema = exports.Prediction$inboundSchema = void 0;
    exports.predictionToJSON = predictionToJSON;
    exports.predictionFromJSON = predictionFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    exports.Prediction$inboundSchema = z3.object({
      type: z3.literal("content").default("content"),
      content: z3.string().default("")
    });
    exports.Prediction$outboundSchema = z3.object({
      type: z3.literal("content").default("content"),
      content: z3.string().default("")
    });
    function predictionToJSON(prediction) {
      return JSON.stringify(exports.Prediction$outboundSchema.parse(prediction));
    }
    function predictionFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.Prediction$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'Prediction' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/jsonschema.js
var require_jsonschema = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/jsonschema.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.JsonSchema$outboundSchema = exports.JsonSchema$inboundSchema = void 0;
    exports.jsonSchemaToJSON = jsonSchemaToJSON;
    exports.jsonSchemaFromJSON = jsonSchemaFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    exports.JsonSchema$inboundSchema = z3.object({
      name: z3.string(),
      description: z3.nullable(z3.string()).optional(),
      schema: z3.record(z3.any()),
      strict: z3.boolean().optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "schema": "schemaDefinition"
      });
    });
    exports.JsonSchema$outboundSchema = z3.object({
      name: z3.string(),
      description: z3.nullable(z3.string()).optional(),
      schemaDefinition: z3.record(z3.any()),
      strict: z3.boolean().optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        schemaDefinition: "schema"
      });
    });
    function jsonSchemaToJSON(jsonSchema) {
      return JSON.stringify(exports.JsonSchema$outboundSchema.parse(jsonSchema));
    }
    function jsonSchemaFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.JsonSchema$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'JsonSchema' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/responseformats.js
var require_responseformats = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/responseformats.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ResponseFormats$outboundSchema = exports.ResponseFormats$inboundSchema = exports.ResponseFormats = void 0;
    var z3 = __importStar(require_v3());
    exports.ResponseFormats = {
      Text: "text",
      JsonObject: "json_object",
      JsonSchema: "json_schema"
    };
    exports.ResponseFormats$inboundSchema = z3.nativeEnum(exports.ResponseFormats);
    exports.ResponseFormats$outboundSchema = exports.ResponseFormats$inboundSchema;
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/responseformat.js
var require_responseformat = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/responseformat.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ResponseFormat$outboundSchema = exports.ResponseFormat$inboundSchema = void 0;
    exports.responseFormatToJSON = responseFormatToJSON;
    exports.responseFormatFromJSON = responseFormatFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var jsonschema_js_1 = require_jsonschema();
    var responseformats_js_1 = require_responseformats();
    exports.ResponseFormat$inboundSchema = z3.object({
      type: responseformats_js_1.ResponseFormats$inboundSchema.optional(),
      json_schema: z3.nullable(jsonschema_js_1.JsonSchema$inboundSchema).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "json_schema": "jsonSchema"
      });
    });
    exports.ResponseFormat$outboundSchema = z3.object({
      type: responseformats_js_1.ResponseFormats$outboundSchema.optional(),
      jsonSchema: z3.nullable(jsonschema_js_1.JsonSchema$outboundSchema).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        jsonSchema: "json_schema"
      });
    });
    function responseFormatToJSON(responseFormat) {
      return JSON.stringify(exports.ResponseFormat$outboundSchema.parse(responseFormat));
    }
    function responseFormatFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ResponseFormat$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ResponseFormat' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/toolchoiceenum.js
var require_toolchoiceenum = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/toolchoiceenum.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ToolChoiceEnum$outboundSchema = exports.ToolChoiceEnum$inboundSchema = exports.ToolChoiceEnum = void 0;
    var z3 = __importStar(require_v3());
    exports.ToolChoiceEnum = {
      Auto: "auto",
      None: "none",
      Any: "any",
      Required: "required"
    };
    exports.ToolChoiceEnum$inboundSchema = z3.nativeEnum(exports.ToolChoiceEnum);
    exports.ToolChoiceEnum$outboundSchema = exports.ToolChoiceEnum$inboundSchema;
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/completionargs.js
var require_completionargs = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/completionargs.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CompletionArgs$outboundSchema = exports.CompletionArgs$inboundSchema = void 0;
    exports.completionArgsToJSON = completionArgsToJSON;
    exports.completionArgsFromJSON = completionArgsFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var completionargsstop_js_1 = require_completionargsstop();
    var prediction_js_1 = require_prediction();
    var responseformat_js_1 = require_responseformat();
    var toolchoiceenum_js_1 = require_toolchoiceenum();
    exports.CompletionArgs$inboundSchema = z3.object({
      stop: z3.nullable(completionargsstop_js_1.CompletionArgsStop$inboundSchema).optional(),
      presence_penalty: z3.nullable(z3.number()).optional(),
      frequency_penalty: z3.nullable(z3.number()).optional(),
      temperature: z3.nullable(z3.number()).optional(),
      top_p: z3.nullable(z3.number()).optional(),
      max_tokens: z3.nullable(z3.number().int()).optional(),
      random_seed: z3.nullable(z3.number().int()).optional(),
      prediction: z3.nullable(prediction_js_1.Prediction$inboundSchema).optional(),
      response_format: z3.nullable(responseformat_js_1.ResponseFormat$inboundSchema).optional(),
      tool_choice: toolchoiceenum_js_1.ToolChoiceEnum$inboundSchema.optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "presence_penalty": "presencePenalty",
        "frequency_penalty": "frequencyPenalty",
        "top_p": "topP",
        "max_tokens": "maxTokens",
        "random_seed": "randomSeed",
        "response_format": "responseFormat",
        "tool_choice": "toolChoice"
      });
    });
    exports.CompletionArgs$outboundSchema = z3.object({
      stop: z3.nullable(completionargsstop_js_1.CompletionArgsStop$outboundSchema).optional(),
      presencePenalty: z3.nullable(z3.number()).optional(),
      frequencyPenalty: z3.nullable(z3.number()).optional(),
      temperature: z3.nullable(z3.number()).optional(),
      topP: z3.nullable(z3.number()).optional(),
      maxTokens: z3.nullable(z3.number().int()).optional(),
      randomSeed: z3.nullable(z3.number().int()).optional(),
      prediction: z3.nullable(prediction_js_1.Prediction$outboundSchema).optional(),
      responseFormat: z3.nullable(responseformat_js_1.ResponseFormat$outboundSchema).optional(),
      toolChoice: toolchoiceenum_js_1.ToolChoiceEnum$outboundSchema.optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        presencePenalty: "presence_penalty",
        frequencyPenalty: "frequency_penalty",
        topP: "top_p",
        maxTokens: "max_tokens",
        randomSeed: "random_seed",
        responseFormat: "response_format",
        toolChoice: "tool_choice"
      });
    });
    function completionArgsToJSON(completionArgs) {
      return JSON.stringify(exports.CompletionArgs$outboundSchema.parse(completionArgs));
    }
    function completionArgsFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.CompletionArgs$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'CompletionArgs' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/documentlibrarytool.js
var require_documentlibrarytool = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/documentlibrarytool.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DocumentLibraryTool$outboundSchema = exports.DocumentLibraryTool$inboundSchema = exports.DocumentLibraryToolType$outboundSchema = exports.DocumentLibraryToolType$inboundSchema = exports.DocumentLibraryToolType = void 0;
    exports.documentLibraryToolToJSON = documentLibraryToolToJSON;
    exports.documentLibraryToolFromJSON = documentLibraryToolFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var toolconfiguration_js_1 = require_toolconfiguration();
    exports.DocumentLibraryToolType = {
      DocumentLibrary: "document_library"
    };
    exports.DocumentLibraryToolType$inboundSchema = z3.nativeEnum(exports.DocumentLibraryToolType);
    exports.DocumentLibraryToolType$outboundSchema = exports.DocumentLibraryToolType$inboundSchema;
    exports.DocumentLibraryTool$inboundSchema = z3.object({
      tool_configuration: z3.nullable(toolconfiguration_js_1.ToolConfiguration$inboundSchema).optional(),
      type: exports.DocumentLibraryToolType$inboundSchema.default("document_library"),
      library_ids: z3.array(z3.string())
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "tool_configuration": "toolConfiguration",
        "library_ids": "libraryIds"
      });
    });
    exports.DocumentLibraryTool$outboundSchema = z3.object({
      toolConfiguration: z3.nullable(toolconfiguration_js_1.ToolConfiguration$outboundSchema).optional(),
      type: exports.DocumentLibraryToolType$outboundSchema.default("document_library"),
      libraryIds: z3.array(z3.string())
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        toolConfiguration: "tool_configuration",
        libraryIds: "library_ids"
      });
    });
    function documentLibraryToolToJSON(documentLibraryTool) {
      return JSON.stringify(exports.DocumentLibraryTool$outboundSchema.parse(documentLibraryTool));
    }
    function documentLibraryToolFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.DocumentLibraryTool$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'DocumentLibraryTool' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/function.js
var require_function = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/function.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FunctionT$outboundSchema = exports.FunctionT$inboundSchema = void 0;
    exports.functionToJSON = functionToJSON;
    exports.functionFromJSON = functionFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    exports.FunctionT$inboundSchema = z3.object({
      name: z3.string(),
      description: z3.string().optional(),
      strict: z3.boolean().optional(),
      parameters: z3.record(z3.any())
    });
    exports.FunctionT$outboundSchema = z3.object({
      name: z3.string(),
      description: z3.string().optional(),
      strict: z3.boolean().optional(),
      parameters: z3.record(z3.any())
    });
    function functionToJSON(functionT) {
      return JSON.stringify(exports.FunctionT$outboundSchema.parse(functionT));
    }
    function functionFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.FunctionT$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'FunctionT' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/functiontool.js
var require_functiontool = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/functiontool.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FunctionTool$outboundSchema = exports.FunctionTool$inboundSchema = exports.Type$outboundSchema = exports.Type$inboundSchema = exports.Type = void 0;
    exports.functionToolToJSON = functionToolToJSON;
    exports.functionToolFromJSON = functionToolFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    var function_js_1 = require_function();
    exports.Type = {
      Function: "function"
    };
    exports.Type$inboundSchema = z3.nativeEnum(exports.Type);
    exports.Type$outboundSchema = exports.Type$inboundSchema;
    exports.FunctionTool$inboundSchema = z3.object({
      type: exports.Type$inboundSchema.default("function"),
      function: function_js_1.FunctionT$inboundSchema
    });
    exports.FunctionTool$outboundSchema = z3.object({
      type: exports.Type$outboundSchema.default("function"),
      function: function_js_1.FunctionT$outboundSchema
    });
    function functionToolToJSON(functionTool) {
      return JSON.stringify(exports.FunctionTool$outboundSchema.parse(functionTool));
    }
    function functionToolFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.FunctionTool$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'FunctionTool' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/imagegenerationtool.js
var require_imagegenerationtool = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/imagegenerationtool.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ImageGenerationTool$outboundSchema = exports.ImageGenerationTool$inboundSchema = exports.ImageGenerationToolType$outboundSchema = exports.ImageGenerationToolType$inboundSchema = exports.ImageGenerationToolType = void 0;
    exports.imageGenerationToolToJSON = imageGenerationToolToJSON;
    exports.imageGenerationToolFromJSON = imageGenerationToolFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var toolconfiguration_js_1 = require_toolconfiguration();
    exports.ImageGenerationToolType = {
      ImageGeneration: "image_generation"
    };
    exports.ImageGenerationToolType$inboundSchema = z3.nativeEnum(exports.ImageGenerationToolType);
    exports.ImageGenerationToolType$outboundSchema = exports.ImageGenerationToolType$inboundSchema;
    exports.ImageGenerationTool$inboundSchema = z3.object({
      tool_configuration: z3.nullable(toolconfiguration_js_1.ToolConfiguration$inboundSchema).optional(),
      type: exports.ImageGenerationToolType$inboundSchema.default("image_generation")
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "tool_configuration": "toolConfiguration"
      });
    });
    exports.ImageGenerationTool$outboundSchema = z3.object({
      toolConfiguration: z3.nullable(toolconfiguration_js_1.ToolConfiguration$outboundSchema).optional(),
      type: exports.ImageGenerationToolType$outboundSchema.default("image_generation")
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        toolConfiguration: "tool_configuration"
      });
    });
    function imageGenerationToolToJSON(imageGenerationTool) {
      return JSON.stringify(exports.ImageGenerationTool$outboundSchema.parse(imageGenerationTool));
    }
    function imageGenerationToolFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ImageGenerationTool$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ImageGenerationTool' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/websearchpremiumtool.js
var require_websearchpremiumtool = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/websearchpremiumtool.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.WebSearchPremiumTool$outboundSchema = exports.WebSearchPremiumTool$inboundSchema = exports.WebSearchPremiumToolType$outboundSchema = exports.WebSearchPremiumToolType$inboundSchema = exports.WebSearchPremiumToolType = void 0;
    exports.webSearchPremiumToolToJSON = webSearchPremiumToolToJSON;
    exports.webSearchPremiumToolFromJSON = webSearchPremiumToolFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var toolconfiguration_js_1 = require_toolconfiguration();
    exports.WebSearchPremiumToolType = {
      WebSearchPremium: "web_search_premium"
    };
    exports.WebSearchPremiumToolType$inboundSchema = z3.nativeEnum(exports.WebSearchPremiumToolType);
    exports.WebSearchPremiumToolType$outboundSchema = exports.WebSearchPremiumToolType$inboundSchema;
    exports.WebSearchPremiumTool$inboundSchema = z3.object({
      tool_configuration: z3.nullable(toolconfiguration_js_1.ToolConfiguration$inboundSchema).optional(),
      type: exports.WebSearchPremiumToolType$inboundSchema.default("web_search_premium")
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "tool_configuration": "toolConfiguration"
      });
    });
    exports.WebSearchPremiumTool$outboundSchema = z3.object({
      toolConfiguration: z3.nullable(toolconfiguration_js_1.ToolConfiguration$outboundSchema).optional(),
      type: exports.WebSearchPremiumToolType$outboundSchema.default("web_search_premium")
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        toolConfiguration: "tool_configuration"
      });
    });
    function webSearchPremiumToolToJSON(webSearchPremiumTool) {
      return JSON.stringify(exports.WebSearchPremiumTool$outboundSchema.parse(webSearchPremiumTool));
    }
    function webSearchPremiumToolFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.WebSearchPremiumTool$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'WebSearchPremiumTool' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/websearchtool.js
var require_websearchtool = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/websearchtool.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.WebSearchTool$outboundSchema = exports.WebSearchTool$inboundSchema = exports.WebSearchToolType$outboundSchema = exports.WebSearchToolType$inboundSchema = exports.WebSearchToolType = void 0;
    exports.webSearchToolToJSON = webSearchToolToJSON;
    exports.webSearchToolFromJSON = webSearchToolFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var toolconfiguration_js_1 = require_toolconfiguration();
    exports.WebSearchToolType = {
      WebSearch: "web_search"
    };
    exports.WebSearchToolType$inboundSchema = z3.nativeEnum(exports.WebSearchToolType);
    exports.WebSearchToolType$outboundSchema = exports.WebSearchToolType$inboundSchema;
    exports.WebSearchTool$inboundSchema = z3.object({
      tool_configuration: z3.nullable(toolconfiguration_js_1.ToolConfiguration$inboundSchema).optional(),
      type: exports.WebSearchToolType$inboundSchema.default("web_search")
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "tool_configuration": "toolConfiguration"
      });
    });
    exports.WebSearchTool$outboundSchema = z3.object({
      toolConfiguration: z3.nullable(toolconfiguration_js_1.ToolConfiguration$outboundSchema).optional(),
      type: exports.WebSearchToolType$outboundSchema.default("web_search")
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        toolConfiguration: "tool_configuration"
      });
    });
    function webSearchToolToJSON(webSearchTool) {
      return JSON.stringify(exports.WebSearchTool$outboundSchema.parse(webSearchTool));
    }
    function webSearchToolFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.WebSearchTool$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'WebSearchTool' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/agent.js
var require_agent = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/agent.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Agent$inboundSchema = exports.AgentTools$inboundSchema = void 0;
    exports.agentToolsFromJSON = agentToolsFromJSON;
    exports.agentFromJSON = agentFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var codeinterpretertool_js_1 = require_codeinterpretertool();
    var completionargs_js_1 = require_completionargs();
    var documentlibrarytool_js_1 = require_documentlibrarytool();
    var functiontool_js_1 = require_functiontool();
    var imagegenerationtool_js_1 = require_imagegenerationtool();
    var websearchpremiumtool_js_1 = require_websearchpremiumtool();
    var websearchtool_js_1 = require_websearchtool();
    exports.AgentTools$inboundSchema = z3.union([
      codeinterpretertool_js_1.CodeInterpreterTool$inboundSchema.and(z3.object({ type: z3.literal("code_interpreter") })),
      documentlibrarytool_js_1.DocumentLibraryTool$inboundSchema.and(z3.object({ type: z3.literal("document_library") })),
      functiontool_js_1.FunctionTool$inboundSchema.and(z3.object({ type: z3.literal("function") })),
      imagegenerationtool_js_1.ImageGenerationTool$inboundSchema.and(z3.object({ type: z3.literal("image_generation") })),
      websearchtool_js_1.WebSearchTool$inboundSchema.and(z3.object({ type: z3.literal("web_search") })),
      websearchpremiumtool_js_1.WebSearchPremiumTool$inboundSchema.and(z3.object({ type: z3.literal("web_search_premium") }))
    ]);
    function agentToolsFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.AgentTools$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'AgentTools' from JSON`);
    }
    exports.Agent$inboundSchema = z3.object({
      instructions: z3.nullable(z3.string()).optional(),
      tools: z3.array(z3.union([
        codeinterpretertool_js_1.CodeInterpreterTool$inboundSchema.and(z3.object({ type: z3.literal("code_interpreter") })),
        documentlibrarytool_js_1.DocumentLibraryTool$inboundSchema.and(z3.object({ type: z3.literal("document_library") })),
        functiontool_js_1.FunctionTool$inboundSchema.and(z3.object({ type: z3.literal("function") })),
        imagegenerationtool_js_1.ImageGenerationTool$inboundSchema.and(z3.object({ type: z3.literal("image_generation") })),
        websearchtool_js_1.WebSearchTool$inboundSchema.and(z3.object({ type: z3.literal("web_search") })),
        websearchpremiumtool_js_1.WebSearchPremiumTool$inboundSchema.and(z3.object({ type: z3.literal("web_search_premium") }))
      ])).optional(),
      completion_args: completionargs_js_1.CompletionArgs$inboundSchema.optional(),
      model: z3.string(),
      name: z3.string(),
      description: z3.nullable(z3.string()).optional(),
      handoffs: z3.nullable(z3.array(z3.string())).optional(),
      metadata: z3.nullable(z3.record(z3.any())).optional(),
      object: z3.literal("agent").default("agent"),
      id: z3.string(),
      version: z3.number().int(),
      versions: z3.array(z3.number().int()),
      created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)),
      updated_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)),
      deployment_chat: z3.boolean(),
      source: z3.string(),
      version_message: z3.nullable(z3.string()).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "completion_args": "completionArgs",
        "created_at": "createdAt",
        "updated_at": "updatedAt",
        "deployment_chat": "deploymentChat",
        "version_message": "versionMessage"
      });
    });
    function agentFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.Agent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'Agent' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/agentaliasresponse.js
var require_agentaliasresponse = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/agentaliasresponse.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AgentAliasResponse$inboundSchema = void 0;
    exports.agentAliasResponseFromJSON = agentAliasResponseFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    exports.AgentAliasResponse$inboundSchema = z3.object({
      alias: z3.string(),
      version: z3.number().int(),
      created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)),
      updated_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4))
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "created_at": "createdAt",
        "updated_at": "updatedAt"
      });
    });
    function agentAliasResponseFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.AgentAliasResponse$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'AgentAliasResponse' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/agentconversation.js
var require_agentconversation = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/agentconversation.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AgentConversation$inboundSchema = exports.AgentConversationAgentVersion$inboundSchema = void 0;
    exports.agentConversationAgentVersionFromJSON = agentConversationAgentVersionFromJSON;
    exports.agentConversationFromJSON = agentConversationFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    exports.AgentConversationAgentVersion$inboundSchema = z3.union([z3.string(), z3.number().int()]);
    function agentConversationAgentVersionFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.AgentConversationAgentVersion$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'AgentConversationAgentVersion' from JSON`);
    }
    exports.AgentConversation$inboundSchema = z3.object({
      name: z3.nullable(z3.string()).optional(),
      description: z3.nullable(z3.string()).optional(),
      metadata: z3.nullable(z3.record(z3.any())).optional(),
      object: z3.literal("conversation").default("conversation"),
      id: z3.string(),
      created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)),
      updated_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)),
      agent_id: z3.string(),
      agent_version: z3.nullable(z3.union([z3.string(), z3.number().int()])).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "created_at": "createdAt",
        "updated_at": "updatedAt",
        "agent_id": "agentId",
        "agent_version": "agentVersion"
      });
    });
    function agentConversationFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.AgentConversation$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'AgentConversation' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/agentcreationrequest.js
var require_agentcreationrequest = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/agentcreationrequest.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AgentCreationRequest$outboundSchema = exports.AgentCreationRequestTools$outboundSchema = void 0;
    exports.agentCreationRequestToolsToJSON = agentCreationRequestToolsToJSON;
    exports.agentCreationRequestToJSON = agentCreationRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var codeinterpretertool_js_1 = require_codeinterpretertool();
    var completionargs_js_1 = require_completionargs();
    var documentlibrarytool_js_1 = require_documentlibrarytool();
    var functiontool_js_1 = require_functiontool();
    var imagegenerationtool_js_1 = require_imagegenerationtool();
    var websearchpremiumtool_js_1 = require_websearchpremiumtool();
    var websearchtool_js_1 = require_websearchtool();
    exports.AgentCreationRequestTools$outboundSchema = z3.union([
      codeinterpretertool_js_1.CodeInterpreterTool$outboundSchema.and(z3.object({ type: z3.literal("code_interpreter") })),
      documentlibrarytool_js_1.DocumentLibraryTool$outboundSchema.and(z3.object({ type: z3.literal("document_library") })),
      functiontool_js_1.FunctionTool$outboundSchema.and(z3.object({ type: z3.literal("function") })),
      imagegenerationtool_js_1.ImageGenerationTool$outboundSchema.and(z3.object({ type: z3.literal("image_generation") })),
      websearchtool_js_1.WebSearchTool$outboundSchema.and(z3.object({ type: z3.literal("web_search") })),
      websearchpremiumtool_js_1.WebSearchPremiumTool$outboundSchema.and(z3.object({ type: z3.literal("web_search_premium") }))
    ]);
    function agentCreationRequestToolsToJSON(agentCreationRequestTools) {
      return JSON.stringify(exports.AgentCreationRequestTools$outboundSchema.parse(agentCreationRequestTools));
    }
    exports.AgentCreationRequest$outboundSchema = z3.object({
      instructions: z3.nullable(z3.string()).optional(),
      tools: z3.array(z3.union([
        codeinterpretertool_js_1.CodeInterpreterTool$outboundSchema.and(z3.object({ type: z3.literal("code_interpreter") })),
        documentlibrarytool_js_1.DocumentLibraryTool$outboundSchema.and(z3.object({ type: z3.literal("document_library") })),
        functiontool_js_1.FunctionTool$outboundSchema.and(z3.object({ type: z3.literal("function") })),
        imagegenerationtool_js_1.ImageGenerationTool$outboundSchema.and(z3.object({ type: z3.literal("image_generation") })),
        websearchtool_js_1.WebSearchTool$outboundSchema.and(z3.object({ type: z3.literal("web_search") })),
        websearchpremiumtool_js_1.WebSearchPremiumTool$outboundSchema.and(z3.object({ type: z3.literal("web_search_premium") }))
      ])).optional(),
      completionArgs: completionargs_js_1.CompletionArgs$outboundSchema.optional(),
      model: z3.string(),
      name: z3.string(),
      description: z3.nullable(z3.string()).optional(),
      handoffs: z3.nullable(z3.array(z3.string())).optional(),
      metadata: z3.nullable(z3.record(z3.any())).optional(),
      versionMessage: z3.nullable(z3.string()).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        completionArgs: "completion_args",
        versionMessage: "version_message"
      });
    });
    function agentCreationRequestToJSON(agentCreationRequest) {
      return JSON.stringify(exports.AgentCreationRequest$outboundSchema.parse(agentCreationRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/agenthandoffdoneevent.js
var require_agenthandoffdoneevent = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/agenthandoffdoneevent.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AgentHandoffDoneEvent$inboundSchema = void 0;
    exports.agentHandoffDoneEventFromJSON = agentHandoffDoneEventFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    exports.AgentHandoffDoneEvent$inboundSchema = z3.object({
      type: z3.literal("agent.handoff.done").default("agent.handoff.done"),
      created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(),
      output_index: z3.number().int().default(0),
      id: z3.string(),
      next_agent_id: z3.string(),
      next_agent_name: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "created_at": "createdAt",
        "output_index": "outputIndex",
        "next_agent_id": "nextAgentId",
        "next_agent_name": "nextAgentName"
      });
    });
    function agentHandoffDoneEventFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.AgentHandoffDoneEvent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'AgentHandoffDoneEvent' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/agenthandoffentry.js
var require_agenthandoffentry = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/agenthandoffentry.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AgentHandoffEntry$outboundSchema = exports.AgentHandoffEntry$inboundSchema = void 0;
    exports.agentHandoffEntryToJSON = agentHandoffEntryToJSON;
    exports.agentHandoffEntryFromJSON = agentHandoffEntryFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    exports.AgentHandoffEntry$inboundSchema = z3.object({
      object: z3.literal("entry").default("entry"),
      type: z3.literal("agent.handoff").default("agent.handoff"),
      created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(),
      completed_at: z3.nullable(z3.string().datetime({ offset: true }).transform((v4) => new Date(v4))).optional(),
      id: z3.string().optional(),
      previous_agent_id: z3.string(),
      previous_agent_name: z3.string(),
      next_agent_id: z3.string(),
      next_agent_name: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "created_at": "createdAt",
        "completed_at": "completedAt",
        "previous_agent_id": "previousAgentId",
        "previous_agent_name": "previousAgentName",
        "next_agent_id": "nextAgentId",
        "next_agent_name": "nextAgentName"
      });
    });
    exports.AgentHandoffEntry$outboundSchema = z3.object({
      object: z3.literal("entry").default("entry"),
      type: z3.literal("agent.handoff").default("agent.handoff"),
      createdAt: z3.date().transform((v4) => v4.toISOString()).optional(),
      completedAt: z3.nullable(z3.date().transform((v4) => v4.toISOString())).optional(),
      id: z3.string().optional(),
      previousAgentId: z3.string(),
      previousAgentName: z3.string(),
      nextAgentId: z3.string(),
      nextAgentName: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        createdAt: "created_at",
        completedAt: "completed_at",
        previousAgentId: "previous_agent_id",
        previousAgentName: "previous_agent_name",
        nextAgentId: "next_agent_id",
        nextAgentName: "next_agent_name"
      });
    });
    function agentHandoffEntryToJSON(agentHandoffEntry) {
      return JSON.stringify(exports.AgentHandoffEntry$outboundSchema.parse(agentHandoffEntry));
    }
    function agentHandoffEntryFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.AgentHandoffEntry$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'AgentHandoffEntry' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/agenthandoffstartedevent.js
var require_agenthandoffstartedevent = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/agenthandoffstartedevent.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AgentHandoffStartedEvent$inboundSchema = void 0;
    exports.agentHandoffStartedEventFromJSON = agentHandoffStartedEventFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    exports.AgentHandoffStartedEvent$inboundSchema = z3.object({
      type: z3.literal("agent.handoff.started").default("agent.handoff.started"),
      created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(),
      output_index: z3.number().int().default(0),
      id: z3.string(),
      previous_agent_id: z3.string(),
      previous_agent_name: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "created_at": "createdAt",
        "output_index": "outputIndex",
        "previous_agent_id": "previousAgentId",
        "previous_agent_name": "previousAgentName"
      });
    });
    function agentHandoffStartedEventFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.AgentHandoffStartedEvent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'AgentHandoffStartedEvent' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/audiochunk.js
var require_audiochunk = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/audiochunk.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AudioChunk$outboundSchema = exports.AudioChunk$inboundSchema = void 0;
    exports.audioChunkToJSON = audioChunkToJSON;
    exports.audioChunkFromJSON = audioChunkFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    exports.AudioChunk$inboundSchema = z3.object({
      type: z3.literal("input_audio").default("input_audio"),
      input_audio: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "input_audio": "inputAudio"
      });
    });
    exports.AudioChunk$outboundSchema = z3.object({
      type: z3.literal("input_audio").default("input_audio"),
      inputAudio: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        inputAudio: "input_audio"
      });
    });
    function audioChunkToJSON(audioChunk) {
      return JSON.stringify(exports.AudioChunk$outboundSchema.parse(audioChunk));
    }
    function audioChunkFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.AudioChunk$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'AudioChunk' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/documenturlchunk.js
var require_documenturlchunk = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/documenturlchunk.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DocumentURLChunk$outboundSchema = exports.DocumentURLChunk$inboundSchema = void 0;
    exports.documentURLChunkToJSON = documentURLChunkToJSON;
    exports.documentURLChunkFromJSON = documentURLChunkFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    exports.DocumentURLChunk$inboundSchema = z3.object({
      type: z3.literal("document_url").default("document_url"),
      document_url: z3.string(),
      document_name: z3.nullable(z3.string()).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "document_url": "documentUrl",
        "document_name": "documentName"
      });
    });
    exports.DocumentURLChunk$outboundSchema = z3.object({
      type: z3.literal("document_url").default("document_url"),
      documentUrl: z3.string(),
      documentName: z3.nullable(z3.string()).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        documentUrl: "document_url",
        documentName: "document_name"
      });
    });
    function documentURLChunkToJSON(documentURLChunk) {
      return JSON.stringify(exports.DocumentURLChunk$outboundSchema.parse(documentURLChunk));
    }
    function documentURLChunkFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.DocumentURLChunk$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'DocumentURLChunk' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/filechunk.js
var require_filechunk = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/filechunk.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FileChunk$outboundSchema = exports.FileChunk$inboundSchema = void 0;
    exports.fileChunkToJSON = fileChunkToJSON;
    exports.fileChunkFromJSON = fileChunkFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    exports.FileChunk$inboundSchema = z3.object({
      type: z3.literal("file").default("file"),
      file_id: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "file_id": "fileId"
      });
    });
    exports.FileChunk$outboundSchema = z3.object({
      type: z3.literal("file").default("file"),
      fileId: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        fileId: "file_id"
      });
    });
    function fileChunkToJSON(fileChunk) {
      return JSON.stringify(exports.FileChunk$outboundSchema.parse(fileChunk));
    }
    function fileChunkFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.FileChunk$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'FileChunk' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/imagedetail.js
var require_imagedetail = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/imagedetail.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ImageDetail$outboundSchema = exports.ImageDetail$inboundSchema = exports.ImageDetail = void 0;
    var z3 = __importStar(require_v3());
    exports.ImageDetail = {
      Low: "low",
      Auto: "auto",
      High: "high"
    };
    exports.ImageDetail$inboundSchema = z3.nativeEnum(exports.ImageDetail);
    exports.ImageDetail$outboundSchema = exports.ImageDetail$inboundSchema;
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/imageurl.js
var require_imageurl = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/imageurl.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ImageURL$outboundSchema = exports.ImageURL$inboundSchema = void 0;
    exports.imageURLToJSON = imageURLToJSON;
    exports.imageURLFromJSON = imageURLFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    var imagedetail_js_1 = require_imagedetail();
    exports.ImageURL$inboundSchema = z3.object({
      url: z3.string(),
      detail: z3.nullable(imagedetail_js_1.ImageDetail$inboundSchema).optional()
    });
    exports.ImageURL$outboundSchema = z3.object({
      url: z3.string(),
      detail: z3.nullable(imagedetail_js_1.ImageDetail$outboundSchema).optional()
    });
    function imageURLToJSON(imageURL) {
      return JSON.stringify(exports.ImageURL$outboundSchema.parse(imageURL));
    }
    function imageURLFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ImageURL$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ImageURL' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/imageurlchunk.js
var require_imageurlchunk = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/imageurlchunk.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ImageURLChunk$outboundSchema = exports.ImageURLChunk$inboundSchema = exports.ImageURLChunkImageURL$outboundSchema = exports.ImageURLChunkImageURL$inboundSchema = void 0;
    exports.imageURLChunkImageURLToJSON = imageURLChunkImageURLToJSON;
    exports.imageURLChunkImageURLFromJSON = imageURLChunkImageURLFromJSON;
    exports.imageURLChunkToJSON = imageURLChunkToJSON;
    exports.imageURLChunkFromJSON = imageURLChunkFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var imageurl_js_1 = require_imageurl();
    exports.ImageURLChunkImageURL$inboundSchema = z3.union([imageurl_js_1.ImageURL$inboundSchema, z3.string()]);
    exports.ImageURLChunkImageURL$outboundSchema = z3.union([imageurl_js_1.ImageURL$outboundSchema, z3.string()]);
    function imageURLChunkImageURLToJSON(imageURLChunkImageURL) {
      return JSON.stringify(exports.ImageURLChunkImageURL$outboundSchema.parse(imageURLChunkImageURL));
    }
    function imageURLChunkImageURLFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ImageURLChunkImageURL$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ImageURLChunkImageURL' from JSON`);
    }
    exports.ImageURLChunk$inboundSchema = z3.object({
      type: z3.literal("image_url").default("image_url"),
      image_url: z3.union([imageurl_js_1.ImageURL$inboundSchema, z3.string()])
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "image_url": "imageUrl"
      });
    });
    exports.ImageURLChunk$outboundSchema = z3.object({
      type: z3.literal("image_url").default("image_url"),
      imageUrl: z3.union([imageurl_js_1.ImageURL$outboundSchema, z3.string()])
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        imageUrl: "image_url"
      });
    });
    function imageURLChunkToJSON(imageURLChunk) {
      return JSON.stringify(exports.ImageURLChunk$outboundSchema.parse(imageURLChunk));
    }
    function imageURLChunkFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ImageURLChunk$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ImageURLChunk' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/referencechunk.js
var require_referencechunk = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/referencechunk.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ReferenceChunk$outboundSchema = exports.ReferenceChunk$inboundSchema = void 0;
    exports.referenceChunkToJSON = referenceChunkToJSON;
    exports.referenceChunkFromJSON = referenceChunkFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    exports.ReferenceChunk$inboundSchema = z3.object({
      type: z3.literal("reference").default("reference"),
      reference_ids: z3.array(z3.number().int())
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "reference_ids": "referenceIds"
      });
    });
    exports.ReferenceChunk$outboundSchema = z3.object({
      type: z3.literal("reference").default("reference"),
      referenceIds: z3.array(z3.number().int())
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        referenceIds: "reference_ids"
      });
    });
    function referenceChunkToJSON(referenceChunk) {
      return JSON.stringify(exports.ReferenceChunk$outboundSchema.parse(referenceChunk));
    }
    function referenceChunkFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ReferenceChunk$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ReferenceChunk' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/textchunk.js
var require_textchunk = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/textchunk.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TextChunk$outboundSchema = exports.TextChunk$inboundSchema = void 0;
    exports.textChunkToJSON = textChunkToJSON;
    exports.textChunkFromJSON = textChunkFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    exports.TextChunk$inboundSchema = z3.object({
      type: z3.literal("text").default("text"),
      text: z3.string()
    });
    exports.TextChunk$outboundSchema = z3.object({
      type: z3.literal("text").default("text"),
      text: z3.string()
    });
    function textChunkToJSON(textChunk) {
      return JSON.stringify(exports.TextChunk$outboundSchema.parse(textChunk));
    }
    function textChunkFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.TextChunk$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'TextChunk' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/builtinconnectors.js
var require_builtinconnectors = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/builtinconnectors.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BuiltInConnectors$outboundSchema = exports.BuiltInConnectors$inboundSchema = exports.BuiltInConnectors = void 0;
    var z3 = __importStar(require_v3());
    exports.BuiltInConnectors = {
      WebSearch: "web_search",
      WebSearchPremium: "web_search_premium",
      CodeInterpreter: "code_interpreter",
      ImageGeneration: "image_generation",
      DocumentLibrary: "document_library"
    };
    exports.BuiltInConnectors$inboundSchema = z3.nativeEnum(exports.BuiltInConnectors);
    exports.BuiltInConnectors$outboundSchema = exports.BuiltInConnectors$inboundSchema;
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/toolreferencechunk.js
var require_toolreferencechunk = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/toolreferencechunk.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ToolReferenceChunk$outboundSchema = exports.ToolReferenceChunk$inboundSchema = exports.ToolReferenceChunkTool$outboundSchema = exports.ToolReferenceChunkTool$inboundSchema = void 0;
    exports.toolReferenceChunkToolToJSON = toolReferenceChunkToolToJSON;
    exports.toolReferenceChunkToolFromJSON = toolReferenceChunkToolFromJSON;
    exports.toolReferenceChunkToJSON = toolReferenceChunkToJSON;
    exports.toolReferenceChunkFromJSON = toolReferenceChunkFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    var builtinconnectors_js_1 = require_builtinconnectors();
    exports.ToolReferenceChunkTool$inboundSchema = z3.union([builtinconnectors_js_1.BuiltInConnectors$inboundSchema, z3.string()]);
    exports.ToolReferenceChunkTool$outboundSchema = z3.union([builtinconnectors_js_1.BuiltInConnectors$outboundSchema, z3.string()]);
    function toolReferenceChunkToolToJSON(toolReferenceChunkTool) {
      return JSON.stringify(exports.ToolReferenceChunkTool$outboundSchema.parse(toolReferenceChunkTool));
    }
    function toolReferenceChunkToolFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ToolReferenceChunkTool$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ToolReferenceChunkTool' from JSON`);
    }
    exports.ToolReferenceChunk$inboundSchema = z3.object({
      type: z3.literal("tool_reference").default("tool_reference"),
      tool: z3.union([builtinconnectors_js_1.BuiltInConnectors$inboundSchema, z3.string()]),
      title: z3.string(),
      url: z3.nullable(z3.string()).optional(),
      favicon: z3.nullable(z3.string()).optional(),
      description: z3.nullable(z3.string()).optional()
    });
    exports.ToolReferenceChunk$outboundSchema = z3.object({
      type: z3.literal("tool_reference").default("tool_reference"),
      tool: z3.union([builtinconnectors_js_1.BuiltInConnectors$outboundSchema, z3.string()]),
      title: z3.string(),
      url: z3.nullable(z3.string()).optional(),
      favicon: z3.nullable(z3.string()).optional(),
      description: z3.nullable(z3.string()).optional()
    });
    function toolReferenceChunkToJSON(toolReferenceChunk) {
      return JSON.stringify(exports.ToolReferenceChunk$outboundSchema.parse(toolReferenceChunk));
    }
    function toolReferenceChunkFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ToolReferenceChunk$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ToolReferenceChunk' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/thinkchunk.js
var require_thinkchunk = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/thinkchunk.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ThinkChunk$outboundSchema = exports.ThinkChunk$inboundSchema = exports.Thinking$outboundSchema = exports.Thinking$inboundSchema = void 0;
    exports.thinkingToJSON = thinkingToJSON;
    exports.thinkingFromJSON = thinkingFromJSON;
    exports.thinkChunkToJSON = thinkChunkToJSON;
    exports.thinkChunkFromJSON = thinkChunkFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    var textchunk_js_1 = require_textchunk();
    var toolreferencechunk_js_1 = require_toolreferencechunk();
    exports.Thinking$inboundSchema = z3.union([toolreferencechunk_js_1.ToolReferenceChunk$inboundSchema, textchunk_js_1.TextChunk$inboundSchema]);
    exports.Thinking$outboundSchema = z3.union([toolreferencechunk_js_1.ToolReferenceChunk$outboundSchema, textchunk_js_1.TextChunk$outboundSchema]);
    function thinkingToJSON(thinking) {
      return JSON.stringify(exports.Thinking$outboundSchema.parse(thinking));
    }
    function thinkingFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.Thinking$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'Thinking' from JSON`);
    }
    exports.ThinkChunk$inboundSchema = z3.object({
      type: z3.literal("thinking").default("thinking"),
      thinking: z3.array(z3.union([toolreferencechunk_js_1.ToolReferenceChunk$inboundSchema, textchunk_js_1.TextChunk$inboundSchema])),
      closed: z3.boolean().default(true)
    });
    exports.ThinkChunk$outboundSchema = z3.object({
      type: z3.literal("thinking").default("thinking"),
      thinking: z3.array(z3.union([toolreferencechunk_js_1.ToolReferenceChunk$outboundSchema, textchunk_js_1.TextChunk$outboundSchema])),
      closed: z3.boolean().default(true)
    });
    function thinkChunkToJSON(thinkChunk) {
      return JSON.stringify(exports.ThinkChunk$outboundSchema.parse(thinkChunk));
    }
    function thinkChunkFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ThinkChunk$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ThinkChunk' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/contentchunk.js
var require_contentchunk = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/contentchunk.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ContentChunk$outboundSchema = exports.ContentChunk$inboundSchema = void 0;
    exports.contentChunkToJSON = contentChunkToJSON;
    exports.contentChunkFromJSON = contentChunkFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    var audiochunk_js_1 = require_audiochunk();
    var documenturlchunk_js_1 = require_documenturlchunk();
    var filechunk_js_1 = require_filechunk();
    var imageurlchunk_js_1 = require_imageurlchunk();
    var referencechunk_js_1 = require_referencechunk();
    var textchunk_js_1 = require_textchunk();
    var thinkchunk_js_1 = require_thinkchunk();
    exports.ContentChunk$inboundSchema = z3.union([
      imageurlchunk_js_1.ImageURLChunk$inboundSchema.and(z3.object({ type: z3.literal("image_url") })),
      documenturlchunk_js_1.DocumentURLChunk$inboundSchema.and(z3.object({ type: z3.literal("document_url") })),
      textchunk_js_1.TextChunk$inboundSchema.and(z3.object({ type: z3.literal("text") })),
      referencechunk_js_1.ReferenceChunk$inboundSchema.and(z3.object({ type: z3.literal("reference") })),
      filechunk_js_1.FileChunk$inboundSchema.and(z3.object({ type: z3.literal("file") })),
      thinkchunk_js_1.ThinkChunk$inboundSchema.and(z3.object({ type: z3.literal("thinking") })),
      audiochunk_js_1.AudioChunk$inboundSchema.and(z3.object({ type: z3.literal("input_audio") }))
    ]);
    exports.ContentChunk$outboundSchema = z3.union([
      imageurlchunk_js_1.ImageURLChunk$outboundSchema.and(z3.object({ type: z3.literal("image_url") })),
      documenturlchunk_js_1.DocumentURLChunk$outboundSchema.and(z3.object({ type: z3.literal("document_url") })),
      textchunk_js_1.TextChunk$outboundSchema.and(z3.object({ type: z3.literal("text") })),
      referencechunk_js_1.ReferenceChunk$outboundSchema.and(z3.object({ type: z3.literal("reference") })),
      filechunk_js_1.FileChunk$outboundSchema.and(z3.object({ type: z3.literal("file") })),
      thinkchunk_js_1.ThinkChunk$outboundSchema.and(z3.object({ type: z3.literal("thinking") })),
      audiochunk_js_1.AudioChunk$outboundSchema.and(z3.object({ type: z3.literal("input_audio") }))
    ]);
    function contentChunkToJSON(contentChunk) {
      return JSON.stringify(exports.ContentChunk$outboundSchema.parse(contentChunk));
    }
    function contentChunkFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ContentChunk$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ContentChunk' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/functioncall.js
var require_functioncall = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/functioncall.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FunctionCall$outboundSchema = exports.FunctionCall$inboundSchema = exports.Arguments$outboundSchema = exports.Arguments$inboundSchema = void 0;
    exports.argumentsToJSON = argumentsToJSON;
    exports.argumentsFromJSON = argumentsFromJSON;
    exports.functionCallToJSON = functionCallToJSON;
    exports.functionCallFromJSON = functionCallFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    exports.Arguments$inboundSchema = z3.union([z3.record(z3.any()), z3.string()]);
    exports.Arguments$outboundSchema = z3.union([z3.record(z3.any()), z3.string()]);
    function argumentsToJSON(value) {
      return JSON.stringify(exports.Arguments$outboundSchema.parse(value));
    }
    function argumentsFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.Arguments$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'Arguments' from JSON`);
    }
    exports.FunctionCall$inboundSchema = z3.object({
      name: z3.string(),
      arguments: z3.union([z3.record(z3.any()), z3.string()])
    });
    exports.FunctionCall$outboundSchema = z3.object({
      name: z3.string(),
      arguments: z3.union([z3.record(z3.any()), z3.string()])
    });
    function functionCallToJSON(functionCall) {
      return JSON.stringify(exports.FunctionCall$outboundSchema.parse(functionCall));
    }
    function functionCallFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.FunctionCall$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'FunctionCall' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/types/unrecognized.js
var require_unrecognized = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/types/unrecognized.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.startCountingUnrecognized = startCountingUnrecognized;
    exports.unrecognized = unrecognized;
    function unrecognized(value) {
      globalCount++;
      return value;
    }
    var globalCount = 0;
    var refCount = 0;
    function startCountingUnrecognized() {
      refCount++;
      const start = globalCount;
      return {
        /**
         * Ends counting and returns the delta.
         * @param delta - If provided, only this amount is added to the parent counter
         *   (used for nested unions where we only want to record the winning option's count).
         *   If not provided, records all counts since start().
         */
        end: (delta) => {
          const count = globalCount - start;
          globalCount = start + (delta ?? count);
          if (--refCount === 0)
            globalCount = 0;
          return count;
        }
      };
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/types/enums.js
var require_enums = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/types/enums.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.inboundSchema = inboundSchema;
    exports.inboundSchemaInt = inboundSchemaInt;
    exports.outboundSchema = outboundSchema;
    exports.outboundSchemaInt = outboundSchemaInt;
    var z3 = __importStar(require_v3());
    var unrecognized_js_1 = require_unrecognized();
    function inboundSchema(enumObj) {
      const options = Object.values(enumObj);
      return z3.union([
        ...options.map((x2) => z3.literal(x2)),
        z3.string().transform((x2) => (0, unrecognized_js_1.unrecognized)(x2))
      ]);
    }
    function inboundSchemaInt(enumObj) {
      const options = Object.values(enumObj).filter((v4) => typeof v4 === "number");
      return z3.union([
        ...options.map((x2) => z3.literal(x2)),
        z3.number().int().transform((x2) => (0, unrecognized_js_1.unrecognized)(x2))
      ]);
    }
    function outboundSchema(_3) {
      return z3.string();
    }
    function outboundSchemaInt(_3) {
      return z3.number().int();
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/tooltypes.js
var require_tooltypes = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/tooltypes.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ToolTypes$outboundSchema = exports.ToolTypes$inboundSchema = exports.ToolTypes = void 0;
    var openEnums = __importStar(require_enums());
    exports.ToolTypes = {
      Function: "function"
    };
    exports.ToolTypes$inboundSchema = openEnums.inboundSchema(exports.ToolTypes);
    exports.ToolTypes$outboundSchema = openEnums.outboundSchema(exports.ToolTypes);
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/toolcall.js
var require_toolcall = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/toolcall.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ToolCall$outboundSchema = exports.ToolCall$inboundSchema = void 0;
    exports.toolCallToJSON = toolCallToJSON;
    exports.toolCallFromJSON = toolCallFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    var functioncall_js_1 = require_functioncall();
    var tooltypes_js_1 = require_tooltypes();
    exports.ToolCall$inboundSchema = z3.object({
      id: z3.string().default("null"),
      type: tooltypes_js_1.ToolTypes$inboundSchema.optional(),
      function: functioncall_js_1.FunctionCall$inboundSchema,
      index: z3.number().int().default(0)
    });
    exports.ToolCall$outboundSchema = z3.object({
      id: z3.string().default("null"),
      type: tooltypes_js_1.ToolTypes$outboundSchema.optional(),
      function: functioncall_js_1.FunctionCall$outboundSchema,
      index: z3.number().int().default(0)
    });
    function toolCallToJSON(toolCall) {
      return JSON.stringify(exports.ToolCall$outboundSchema.parse(toolCall));
    }
    function toolCallFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ToolCall$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ToolCall' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/assistantmessage.js
var require_assistantmessage = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/assistantmessage.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AssistantMessage$outboundSchema = exports.AssistantMessage$inboundSchema = exports.AssistantMessageContent$outboundSchema = exports.AssistantMessageContent$inboundSchema = void 0;
    exports.assistantMessageContentToJSON = assistantMessageContentToJSON;
    exports.assistantMessageContentFromJSON = assistantMessageContentFromJSON;
    exports.assistantMessageToJSON = assistantMessageToJSON;
    exports.assistantMessageFromJSON = assistantMessageFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var contentchunk_js_1 = require_contentchunk();
    var toolcall_js_1 = require_toolcall();
    exports.AssistantMessageContent$inboundSchema = z3.union([z3.string(), z3.array(contentchunk_js_1.ContentChunk$inboundSchema)]);
    exports.AssistantMessageContent$outboundSchema = z3.union([z3.string(), z3.array(contentchunk_js_1.ContentChunk$outboundSchema)]);
    function assistantMessageContentToJSON(assistantMessageContent) {
      return JSON.stringify(exports.AssistantMessageContent$outboundSchema.parse(assistantMessageContent));
    }
    function assistantMessageContentFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.AssistantMessageContent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'AssistantMessageContent' from JSON`);
    }
    exports.AssistantMessage$inboundSchema = z3.object({
      role: z3.literal("assistant").default("assistant"),
      content: z3.nullable(z3.union([z3.string(), z3.array(contentchunk_js_1.ContentChunk$inboundSchema)])).optional(),
      tool_calls: z3.nullable(z3.array(toolcall_js_1.ToolCall$inboundSchema)).optional(),
      prefix: z3.boolean().default(false)
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "tool_calls": "toolCalls"
      });
    });
    exports.AssistantMessage$outboundSchema = z3.object({
      role: z3.literal("assistant").default("assistant"),
      content: z3.nullable(z3.union([z3.string(), z3.array(contentchunk_js_1.ContentChunk$outboundSchema)])).optional(),
      toolCalls: z3.nullable(z3.array(toolcall_js_1.ToolCall$outboundSchema)).optional(),
      prefix: z3.boolean().default(false)
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        toolCalls: "tool_calls"
      });
    });
    function assistantMessageToJSON(assistantMessage) {
      return JSON.stringify(exports.AssistantMessage$outboundSchema.parse(assistantMessage));
    }
    function assistantMessageFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.AssistantMessage$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'AssistantMessage' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/mistralpromptmode.js
var require_mistralpromptmode = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/mistralpromptmode.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MistralPromptMode$outboundSchema = exports.MistralPromptMode = void 0;
    var openEnums = __importStar(require_enums());
    exports.MistralPromptMode = {
      Reasoning: "reasoning"
    };
    exports.MistralPromptMode$outboundSchema = openEnums.outboundSchema(exports.MistralPromptMode);
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/systemmessagecontentchunks.js
var require_systemmessagecontentchunks = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/systemmessagecontentchunks.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SystemMessageContentChunks$outboundSchema = void 0;
    exports.systemMessageContentChunksToJSON = systemMessageContentChunksToJSON;
    var z3 = __importStar(require_v3());
    var textchunk_js_1 = require_textchunk();
    var thinkchunk_js_1 = require_thinkchunk();
    exports.SystemMessageContentChunks$outboundSchema = z3.union([
      textchunk_js_1.TextChunk$outboundSchema.and(z3.object({ type: z3.literal("text") })),
      thinkchunk_js_1.ThinkChunk$outboundSchema.and(z3.object({ type: z3.literal("thinking") }))
    ]);
    function systemMessageContentChunksToJSON(systemMessageContentChunks) {
      return JSON.stringify(exports.SystemMessageContentChunks$outboundSchema.parse(systemMessageContentChunks));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/systemmessage.js
var require_systemmessage = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/systemmessage.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SystemMessage$outboundSchema = exports.SystemMessageContent$outboundSchema = void 0;
    exports.systemMessageContentToJSON = systemMessageContentToJSON;
    exports.systemMessageToJSON = systemMessageToJSON;
    var z3 = __importStar(require_v3());
    var systemmessagecontentchunks_js_1 = require_systemmessagecontentchunks();
    exports.SystemMessageContent$outboundSchema = z3.union([z3.string(), z3.array(systemmessagecontentchunks_js_1.SystemMessageContentChunks$outboundSchema)]);
    function systemMessageContentToJSON(systemMessageContent) {
      return JSON.stringify(exports.SystemMessageContent$outboundSchema.parse(systemMessageContent));
    }
    exports.SystemMessage$outboundSchema = z3.object({
      role: z3.literal("system").default("system"),
      content: z3.union([
        z3.string(),
        z3.array(systemmessagecontentchunks_js_1.SystemMessageContentChunks$outboundSchema)
      ])
    });
    function systemMessageToJSON(systemMessage) {
      return JSON.stringify(exports.SystemMessage$outboundSchema.parse(systemMessage));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/tool.js
var require_tool = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/tool.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Tool$outboundSchema = void 0;
    exports.toolToJSON = toolToJSON;
    var z3 = __importStar(require_v3());
    var function_js_1 = require_function();
    var tooltypes_js_1 = require_tooltypes();
    exports.Tool$outboundSchema = z3.object({
      type: tooltypes_js_1.ToolTypes$outboundSchema.optional(),
      function: function_js_1.FunctionT$outboundSchema
    });
    function toolToJSON(tool) {
      return JSON.stringify(exports.Tool$outboundSchema.parse(tool));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/functionname.js
var require_functionname = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/functionname.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FunctionName$outboundSchema = void 0;
    exports.functionNameToJSON = functionNameToJSON;
    var z3 = __importStar(require_v3());
    exports.FunctionName$outboundSchema = z3.object({
      name: z3.string()
    });
    function functionNameToJSON(functionName) {
      return JSON.stringify(exports.FunctionName$outboundSchema.parse(functionName));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/toolchoice.js
var require_toolchoice = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/toolchoice.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ToolChoice$outboundSchema = void 0;
    exports.toolChoiceToJSON = toolChoiceToJSON;
    var z3 = __importStar(require_v3());
    var functionname_js_1 = require_functionname();
    var tooltypes_js_1 = require_tooltypes();
    exports.ToolChoice$outboundSchema = z3.object({
      type: tooltypes_js_1.ToolTypes$outboundSchema.optional(),
      function: functionname_js_1.FunctionName$outboundSchema
    });
    function toolChoiceToJSON(toolChoice) {
      return JSON.stringify(exports.ToolChoice$outboundSchema.parse(toolChoice));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/toolmessage.js
var require_toolmessage = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/toolmessage.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ToolMessage$outboundSchema = exports.ToolMessageContent$outboundSchema = void 0;
    exports.toolMessageContentToJSON = toolMessageContentToJSON;
    exports.toolMessageToJSON = toolMessageToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var contentchunk_js_1 = require_contentchunk();
    exports.ToolMessageContent$outboundSchema = z3.union([z3.string(), z3.array(contentchunk_js_1.ContentChunk$outboundSchema)]);
    function toolMessageContentToJSON(toolMessageContent) {
      return JSON.stringify(exports.ToolMessageContent$outboundSchema.parse(toolMessageContent));
    }
    exports.ToolMessage$outboundSchema = z3.object({
      role: z3.literal("tool").default("tool"),
      content: z3.nullable(z3.union([z3.string(), z3.array(contentchunk_js_1.ContentChunk$outboundSchema)])),
      toolCallId: z3.nullable(z3.string()).optional(),
      name: z3.nullable(z3.string()).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        toolCallId: "tool_call_id"
      });
    });
    function toolMessageToJSON(toolMessage) {
      return JSON.stringify(exports.ToolMessage$outboundSchema.parse(toolMessage));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/usermessage.js
var require_usermessage = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/usermessage.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.UserMessage$outboundSchema = exports.UserMessageContent$outboundSchema = void 0;
    exports.userMessageContentToJSON = userMessageContentToJSON;
    exports.userMessageToJSON = userMessageToJSON;
    var z3 = __importStar(require_v3());
    var contentchunk_js_1 = require_contentchunk();
    exports.UserMessageContent$outboundSchema = z3.union([z3.string(), z3.array(contentchunk_js_1.ContentChunk$outboundSchema)]);
    function userMessageContentToJSON(userMessageContent) {
      return JSON.stringify(exports.UserMessageContent$outboundSchema.parse(userMessageContent));
    }
    exports.UserMessage$outboundSchema = z3.object({
      role: z3.literal("user").default("user"),
      content: z3.nullable(z3.union([z3.string(), z3.array(contentchunk_js_1.ContentChunk$outboundSchema)]))
    });
    function userMessageToJSON(userMessage) {
      return JSON.stringify(exports.UserMessage$outboundSchema.parse(userMessage));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/agentscompletionrequest.js
var require_agentscompletionrequest = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/agentscompletionrequest.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AgentsCompletionRequest$outboundSchema = exports.AgentsCompletionRequestToolChoice$outboundSchema = exports.AgentsCompletionRequestMessages$outboundSchema = exports.AgentsCompletionRequestStop$outboundSchema = void 0;
    exports.agentsCompletionRequestStopToJSON = agentsCompletionRequestStopToJSON;
    exports.agentsCompletionRequestMessagesToJSON = agentsCompletionRequestMessagesToJSON;
    exports.agentsCompletionRequestToolChoiceToJSON = agentsCompletionRequestToolChoiceToJSON;
    exports.agentsCompletionRequestToJSON = agentsCompletionRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var assistantmessage_js_1 = require_assistantmessage();
    var mistralpromptmode_js_1 = require_mistralpromptmode();
    var prediction_js_1 = require_prediction();
    var responseformat_js_1 = require_responseformat();
    var systemmessage_js_1 = require_systemmessage();
    var tool_js_1 = require_tool();
    var toolchoice_js_1 = require_toolchoice();
    var toolchoiceenum_js_1 = require_toolchoiceenum();
    var toolmessage_js_1 = require_toolmessage();
    var usermessage_js_1 = require_usermessage();
    exports.AgentsCompletionRequestStop$outboundSchema = z3.union([z3.string(), z3.array(z3.string())]);
    function agentsCompletionRequestStopToJSON(agentsCompletionRequestStop) {
      return JSON.stringify(exports.AgentsCompletionRequestStop$outboundSchema.parse(agentsCompletionRequestStop));
    }
    exports.AgentsCompletionRequestMessages$outboundSchema = z3.union([
      assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })),
      systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })),
      toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })),
      usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") }))
    ]);
    function agentsCompletionRequestMessagesToJSON(agentsCompletionRequestMessages) {
      return JSON.stringify(exports.AgentsCompletionRequestMessages$outboundSchema.parse(agentsCompletionRequestMessages));
    }
    exports.AgentsCompletionRequestToolChoice$outboundSchema = z3.union([toolchoice_js_1.ToolChoice$outboundSchema, toolchoiceenum_js_1.ToolChoiceEnum$outboundSchema]);
    function agentsCompletionRequestToolChoiceToJSON(agentsCompletionRequestToolChoice) {
      return JSON.stringify(exports.AgentsCompletionRequestToolChoice$outboundSchema.parse(agentsCompletionRequestToolChoice));
    }
    exports.AgentsCompletionRequest$outboundSchema = z3.object({
      maxTokens: z3.nullable(z3.number().int()).optional(),
      stream: z3.boolean().default(false),
      stop: z3.union([z3.string(), z3.array(z3.string())]).optional(),
      randomSeed: z3.nullable(z3.number().int()).optional(),
      metadata: z3.nullable(z3.record(z3.any())).optional(),
      messages: z3.array(z3.union([
        assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })),
        systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })),
        toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })),
        usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") }))
      ])),
      responseFormat: responseformat_js_1.ResponseFormat$outboundSchema.optional(),
      tools: z3.nullable(z3.array(tool_js_1.Tool$outboundSchema)).optional(),
      toolChoice: z3.union([
        toolchoice_js_1.ToolChoice$outboundSchema,
        toolchoiceenum_js_1.ToolChoiceEnum$outboundSchema
      ]).optional(),
      presencePenalty: z3.number().optional(),
      frequencyPenalty: z3.number().optional(),
      n: z3.nullable(z3.number().int()).optional(),
      prediction: prediction_js_1.Prediction$outboundSchema.optional(),
      parallelToolCalls: z3.boolean().optional(),
      promptMode: z3.nullable(mistralpromptmode_js_1.MistralPromptMode$outboundSchema).optional(),
      agentId: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        maxTokens: "max_tokens",
        randomSeed: "random_seed",
        responseFormat: "response_format",
        toolChoice: "tool_choice",
        presencePenalty: "presence_penalty",
        frequencyPenalty: "frequency_penalty",
        parallelToolCalls: "parallel_tool_calls",
        promptMode: "prompt_mode",
        agentId: "agent_id"
      });
    });
    function agentsCompletionRequestToJSON(agentsCompletionRequest) {
      return JSON.stringify(exports.AgentsCompletionRequest$outboundSchema.parse(agentsCompletionRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/agentscompletionstreamrequest.js
var require_agentscompletionstreamrequest = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/agentscompletionstreamrequest.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AgentsCompletionStreamRequest$outboundSchema = exports.AgentsCompletionStreamRequestToolChoice$outboundSchema = exports.AgentsCompletionStreamRequestMessages$outboundSchema = exports.AgentsCompletionStreamRequestStop$outboundSchema = void 0;
    exports.agentsCompletionStreamRequestStopToJSON = agentsCompletionStreamRequestStopToJSON;
    exports.agentsCompletionStreamRequestMessagesToJSON = agentsCompletionStreamRequestMessagesToJSON;
    exports.agentsCompletionStreamRequestToolChoiceToJSON = agentsCompletionStreamRequestToolChoiceToJSON;
    exports.agentsCompletionStreamRequestToJSON = agentsCompletionStreamRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var assistantmessage_js_1 = require_assistantmessage();
    var mistralpromptmode_js_1 = require_mistralpromptmode();
    var prediction_js_1 = require_prediction();
    var responseformat_js_1 = require_responseformat();
    var systemmessage_js_1 = require_systemmessage();
    var tool_js_1 = require_tool();
    var toolchoice_js_1 = require_toolchoice();
    var toolchoiceenum_js_1 = require_toolchoiceenum();
    var toolmessage_js_1 = require_toolmessage();
    var usermessage_js_1 = require_usermessage();
    exports.AgentsCompletionStreamRequestStop$outboundSchema = z3.union([z3.string(), z3.array(z3.string())]);
    function agentsCompletionStreamRequestStopToJSON(agentsCompletionStreamRequestStop) {
      return JSON.stringify(exports.AgentsCompletionStreamRequestStop$outboundSchema.parse(agentsCompletionStreamRequestStop));
    }
    exports.AgentsCompletionStreamRequestMessages$outboundSchema = z3.union([
      assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })),
      systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })),
      toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })),
      usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") }))
    ]);
    function agentsCompletionStreamRequestMessagesToJSON(agentsCompletionStreamRequestMessages) {
      return JSON.stringify(exports.AgentsCompletionStreamRequestMessages$outboundSchema.parse(agentsCompletionStreamRequestMessages));
    }
    exports.AgentsCompletionStreamRequestToolChoice$outboundSchema = z3.union([toolchoice_js_1.ToolChoice$outboundSchema, toolchoiceenum_js_1.ToolChoiceEnum$outboundSchema]);
    function agentsCompletionStreamRequestToolChoiceToJSON(agentsCompletionStreamRequestToolChoice) {
      return JSON.stringify(exports.AgentsCompletionStreamRequestToolChoice$outboundSchema.parse(agentsCompletionStreamRequestToolChoice));
    }
    exports.AgentsCompletionStreamRequest$outboundSchema = z3.object({
      maxTokens: z3.nullable(z3.number().int()).optional(),
      stream: z3.boolean().default(true),
      stop: z3.union([z3.string(), z3.array(z3.string())]).optional(),
      randomSeed: z3.nullable(z3.number().int()).optional(),
      metadata: z3.nullable(z3.record(z3.any())).optional(),
      messages: z3.array(z3.union([
        assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })),
        systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })),
        toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })),
        usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") }))
      ])),
      responseFormat: responseformat_js_1.ResponseFormat$outboundSchema.optional(),
      tools: z3.nullable(z3.array(tool_js_1.Tool$outboundSchema)).optional(),
      toolChoice: z3.union([
        toolchoice_js_1.ToolChoice$outboundSchema,
        toolchoiceenum_js_1.ToolChoiceEnum$outboundSchema
      ]).optional(),
      presencePenalty: z3.number().optional(),
      frequencyPenalty: z3.number().optional(),
      n: z3.nullable(z3.number().int()).optional(),
      prediction: prediction_js_1.Prediction$outboundSchema.optional(),
      parallelToolCalls: z3.boolean().optional(),
      promptMode: z3.nullable(mistralpromptmode_js_1.MistralPromptMode$outboundSchema).optional(),
      agentId: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        maxTokens: "max_tokens",
        randomSeed: "random_seed",
        responseFormat: "response_format",
        toolChoice: "tool_choice",
        presencePenalty: "presence_penalty",
        frequencyPenalty: "frequency_penalty",
        parallelToolCalls: "parallel_tool_calls",
        promptMode: "prompt_mode",
        agentId: "agent_id"
      });
    });
    function agentsCompletionStreamRequestToJSON(agentsCompletionStreamRequest) {
      return JSON.stringify(exports.AgentsCompletionStreamRequest$outboundSchema.parse(agentsCompletionStreamRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/agentupdaterequest.js
var require_agentupdaterequest = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/agentupdaterequest.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AgentUpdateRequest$outboundSchema = exports.AgentUpdateRequestTools$outboundSchema = void 0;
    exports.agentUpdateRequestToolsToJSON = agentUpdateRequestToolsToJSON;
    exports.agentUpdateRequestToJSON = agentUpdateRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var codeinterpretertool_js_1 = require_codeinterpretertool();
    var completionargs_js_1 = require_completionargs();
    var documentlibrarytool_js_1 = require_documentlibrarytool();
    var functiontool_js_1 = require_functiontool();
    var imagegenerationtool_js_1 = require_imagegenerationtool();
    var websearchpremiumtool_js_1 = require_websearchpremiumtool();
    var websearchtool_js_1 = require_websearchtool();
    exports.AgentUpdateRequestTools$outboundSchema = z3.union([
      codeinterpretertool_js_1.CodeInterpreterTool$outboundSchema.and(z3.object({ type: z3.literal("code_interpreter") })),
      documentlibrarytool_js_1.DocumentLibraryTool$outboundSchema.and(z3.object({ type: z3.literal("document_library") })),
      functiontool_js_1.FunctionTool$outboundSchema.and(z3.object({ type: z3.literal("function") })),
      imagegenerationtool_js_1.ImageGenerationTool$outboundSchema.and(z3.object({ type: z3.literal("image_generation") })),
      websearchtool_js_1.WebSearchTool$outboundSchema.and(z3.object({ type: z3.literal("web_search") })),
      websearchpremiumtool_js_1.WebSearchPremiumTool$outboundSchema.and(z3.object({ type: z3.literal("web_search_premium") }))
    ]);
    function agentUpdateRequestToolsToJSON(agentUpdateRequestTools) {
      return JSON.stringify(exports.AgentUpdateRequestTools$outboundSchema.parse(agentUpdateRequestTools));
    }
    exports.AgentUpdateRequest$outboundSchema = z3.object({
      instructions: z3.nullable(z3.string()).optional(),
      tools: z3.array(z3.union([
        codeinterpretertool_js_1.CodeInterpreterTool$outboundSchema.and(z3.object({ type: z3.literal("code_interpreter") })),
        documentlibrarytool_js_1.DocumentLibraryTool$outboundSchema.and(z3.object({ type: z3.literal("document_library") })),
        functiontool_js_1.FunctionTool$outboundSchema.and(z3.object({ type: z3.literal("function") })),
        imagegenerationtool_js_1.ImageGenerationTool$outboundSchema.and(z3.object({ type: z3.literal("image_generation") })),
        websearchtool_js_1.WebSearchTool$outboundSchema.and(z3.object({ type: z3.literal("web_search") })),
        websearchpremiumtool_js_1.WebSearchPremiumTool$outboundSchema.and(z3.object({ type: z3.literal("web_search_premium") }))
      ])).optional(),
      completionArgs: completionargs_js_1.CompletionArgs$outboundSchema.optional(),
      model: z3.nullable(z3.string()).optional(),
      name: z3.nullable(z3.string()).optional(),
      description: z3.nullable(z3.string()).optional(),
      handoffs: z3.nullable(z3.array(z3.string())).optional(),
      deploymentChat: z3.nullable(z3.boolean()).optional(),
      metadata: z3.nullable(z3.record(z3.any())).optional(),
      versionMessage: z3.nullable(z3.string()).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        completionArgs: "completion_args",
        deploymentChat: "deployment_chat",
        versionMessage: "version_message"
      });
    });
    function agentUpdateRequestToJSON(agentUpdateRequest) {
      return JSON.stringify(exports.AgentUpdateRequest$outboundSchema.parse(agentUpdateRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/apiendpoint.js
var require_apiendpoint = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/apiendpoint.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ApiEndpoint$outboundSchema = exports.ApiEndpoint = void 0;
    var openEnums = __importStar(require_enums());
    exports.ApiEndpoint = {
      RootV1ChatCompletions: "/v1/chat/completions",
      RootV1Embeddings: "/v1/embeddings",
      RootV1FimCompletions: "/v1/fim/completions",
      RootV1Moderations: "/v1/moderations",
      RootV1ChatModerations: "/v1/chat/moderations",
      RootV1Ocr: "/v1/ocr",
      RootV1Classifications: "/v1/classifications",
      RootV1ChatClassifications: "/v1/chat/classifications",
      RootV1Conversations: "/v1/conversations",
      RootV1AudioTranscriptions: "/v1/audio/transcriptions"
    };
    exports.ApiEndpoint$outboundSchema = openEnums.outboundSchema(exports.ApiEndpoint);
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/archiveftmodelout.js
var require_archiveftmodelout = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/archiveftmodelout.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ArchiveFTModelOut$inboundSchema = void 0;
    exports.archiveFTModelOutFromJSON = archiveFTModelOutFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    exports.ArchiveFTModelOut$inboundSchema = z3.object({
      id: z3.string(),
      object: z3.literal("model").default("model"),
      archived: z3.boolean().default(true)
    });
    function archiveFTModelOutFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ArchiveFTModelOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ArchiveFTModelOut' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/audioencoding.js
var require_audioencoding = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/audioencoding.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AudioEncoding$outboundSchema = exports.AudioEncoding$inboundSchema = exports.AudioEncoding = void 0;
    var openEnums = __importStar(require_enums());
    exports.AudioEncoding = {
      PcmS16le: "pcm_s16le",
      PcmS32le: "pcm_s32le",
      PcmF16le: "pcm_f16le",
      PcmF32le: "pcm_f32le",
      PcmMulaw: "pcm_mulaw",
      PcmAlaw: "pcm_alaw"
    };
    exports.AudioEncoding$inboundSchema = openEnums.inboundSchema(exports.AudioEncoding);
    exports.AudioEncoding$outboundSchema = openEnums.outboundSchema(exports.AudioEncoding);
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/audioformat.js
var require_audioformat = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/audioformat.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AudioFormat$outboundSchema = exports.AudioFormat$inboundSchema = void 0;
    exports.audioFormatToJSON = audioFormatToJSON;
    exports.audioFormatFromJSON = audioFormatFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var audioencoding_js_1 = require_audioencoding();
    exports.AudioFormat$inboundSchema = z3.object({
      encoding: audioencoding_js_1.AudioEncoding$inboundSchema,
      sample_rate: z3.number().int()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "sample_rate": "sampleRate"
      });
    });
    exports.AudioFormat$outboundSchema = z3.object({
      encoding: audioencoding_js_1.AudioEncoding$outboundSchema,
      sampleRate: z3.number().int()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        sampleRate: "sample_rate"
      });
    });
    function audioFormatToJSON(audioFormat) {
      return JSON.stringify(exports.AudioFormat$outboundSchema.parse(audioFormat));
    }
    function audioFormatFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.AudioFormat$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'AudioFormat' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/types/blobs.js
var require_blobs = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/types/blobs.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.blobLikeSchema = void 0;
    exports.isBlobLike = isBlobLike4;
    var z3 = __importStar(require_v3());
    exports.blobLikeSchema = z3.custom(isBlobLike4, {
      message: "expected a Blob, File or Blob-like object",
      fatal: true
    });
    function isBlobLike4(val2) {
      if (val2 instanceof Blob) {
        return true;
      }
      if (typeof val2 !== "object" || val2 == null || !(Symbol.toStringTag in val2)) {
        return false;
      }
      const name = val2[Symbol.toStringTag];
      if (typeof name !== "string") {
        return false;
      }
      if (name !== "Blob" && name !== "File") {
        return false;
      }
      return "stream" in val2 && typeof val2.stream === "function";
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/file.js
var require_file = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/file.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FileT$outboundSchema = void 0;
    exports.fileToJSON = fileToJSON;
    var z3 = __importStar(require_v3());
    exports.FileT$outboundSchema = z3.object({
      fileName: z3.string(),
      content: z3.union([
        z3.instanceof(ReadableStream),
        z3.instanceof(Blob),
        z3.instanceof(ArrayBuffer),
        z3.instanceof(Uint8Array)
      ])
    });
    function fileToJSON(fileT) {
      return JSON.stringify(exports.FileT$outboundSchema.parse(fileT));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/timestampgranularity.js
var require_timestampgranularity = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/timestampgranularity.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TimestampGranularity$outboundSchema = exports.TimestampGranularity = void 0;
    var z3 = __importStar(require_v3());
    exports.TimestampGranularity = {
      Segment: "segment",
      Word: "word"
    };
    exports.TimestampGranularity$outboundSchema = z3.nativeEnum(exports.TimestampGranularity);
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/audiotranscriptionrequest.js
var require_audiotranscriptionrequest = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/audiotranscriptionrequest.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AudioTranscriptionRequest$outboundSchema = void 0;
    exports.audioTranscriptionRequestToJSON = audioTranscriptionRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var blobs_js_1 = require_blobs();
    var file_js_1 = require_file();
    var timestampgranularity_js_1 = require_timestampgranularity();
    exports.AudioTranscriptionRequest$outboundSchema = z3.object({
      model: z3.string(),
      file: file_js_1.FileT$outboundSchema.or(blobs_js_1.blobLikeSchema).optional(),
      fileUrl: z3.nullable(z3.string()).optional(),
      fileId: z3.nullable(z3.string()).optional(),
      language: z3.nullable(z3.string()).optional(),
      temperature: z3.nullable(z3.number()).optional(),
      stream: z3.literal(false).default(false),
      diarize: z3.boolean().default(false),
      contextBias: z3.array(z3.string()).optional(),
      timestampGranularities: z3.array(timestampgranularity_js_1.TimestampGranularity$outboundSchema).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        fileUrl: "file_url",
        fileId: "file_id",
        contextBias: "context_bias",
        timestampGranularities: "timestamp_granularities"
      });
    });
    function audioTranscriptionRequestToJSON(audioTranscriptionRequest) {
      return JSON.stringify(exports.AudioTranscriptionRequest$outboundSchema.parse(audioTranscriptionRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/audiotranscriptionrequeststream.js
var require_audiotranscriptionrequeststream = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/audiotranscriptionrequeststream.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AudioTranscriptionRequestStream$outboundSchema = void 0;
    exports.audioTranscriptionRequestStreamToJSON = audioTranscriptionRequestStreamToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var blobs_js_1 = require_blobs();
    var file_js_1 = require_file();
    var timestampgranularity_js_1 = require_timestampgranularity();
    exports.AudioTranscriptionRequestStream$outboundSchema = z3.object({
      model: z3.string(),
      file: file_js_1.FileT$outboundSchema.or(blobs_js_1.blobLikeSchema).optional(),
      fileUrl: z3.nullable(z3.string()).optional(),
      fileId: z3.nullable(z3.string()).optional(),
      language: z3.nullable(z3.string()).optional(),
      temperature: z3.nullable(z3.number()).optional(),
      stream: z3.literal(true).default(true),
      diarize: z3.boolean().default(false),
      contextBias: z3.array(z3.string()).optional(),
      timestampGranularities: z3.array(timestampgranularity_js_1.TimestampGranularity$outboundSchema).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        fileUrl: "file_url",
        fileId: "file_id",
        contextBias: "context_bias",
        timestampGranularities: "timestamp_granularities"
      });
    });
    function audioTranscriptionRequestStreamToJSON(audioTranscriptionRequestStream) {
      return JSON.stringify(exports.AudioTranscriptionRequestStream$outboundSchema.parse(audioTranscriptionRequestStream));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/modelcapabilities.js
var require_modelcapabilities = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/modelcapabilities.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ModelCapabilities$inboundSchema = void 0;
    exports.modelCapabilitiesFromJSON = modelCapabilitiesFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    exports.ModelCapabilities$inboundSchema = z3.object({
      completion_chat: z3.boolean().default(false),
      function_calling: z3.boolean().default(false),
      completion_fim: z3.boolean().default(false),
      fine_tuning: z3.boolean().default(false),
      vision: z3.boolean().default(false),
      ocr: z3.boolean().default(false),
      classification: z3.boolean().default(false),
      moderation: z3.boolean().default(false),
      audio: z3.boolean().default(false),
      audio_transcription: z3.boolean().default(false)
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "completion_chat": "completionChat",
        "function_calling": "functionCalling",
        "completion_fim": "completionFim",
        "fine_tuning": "fineTuning",
        "audio_transcription": "audioTranscription"
      });
    });
    function modelCapabilitiesFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ModelCapabilities$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ModelCapabilities' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/basemodelcard.js
var require_basemodelcard = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/basemodelcard.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BaseModelCard$inboundSchema = void 0;
    exports.baseModelCardFromJSON = baseModelCardFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var modelcapabilities_js_1 = require_modelcapabilities();
    exports.BaseModelCard$inboundSchema = z3.object({
      id: z3.string(),
      object: z3.string().default("model"),
      created: z3.number().int().optional(),
      owned_by: z3.string().default("mistralai"),
      capabilities: modelcapabilities_js_1.ModelCapabilities$inboundSchema,
      name: z3.nullable(z3.string()).optional(),
      description: z3.nullable(z3.string()).optional(),
      max_context_length: z3.number().int().default(32768),
      aliases: z3.array(z3.string()).optional(),
      deprecation: z3.nullable(z3.string().datetime({ offset: true }).transform((v4) => new Date(v4))).optional(),
      deprecation_replacement_model: z3.nullable(z3.string()).optional(),
      default_model_temperature: z3.nullable(z3.number()).optional(),
      type: z3.literal("base").default("base")
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "owned_by": "ownedBy",
        "max_context_length": "maxContextLength",
        "deprecation_replacement_model": "deprecationReplacementModel",
        "default_model_temperature": "defaultModelTemperature"
      });
    });
    function baseModelCardFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.BaseModelCard$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'BaseModelCard' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/batcherror.js
var require_batcherror = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/batcherror.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BatchError$inboundSchema = void 0;
    exports.batchErrorFromJSON = batchErrorFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    exports.BatchError$inboundSchema = z3.object({
      message: z3.string(),
      count: z3.number().int().default(1)
    });
    function batchErrorFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.BatchError$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'BatchError' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/batchrequest.js
var require_batchrequest = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/batchrequest.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BatchRequest$outboundSchema = void 0;
    exports.batchRequestToJSON = batchRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    exports.BatchRequest$outboundSchema = z3.object({
      customId: z3.nullable(z3.string()).optional(),
      body: z3.record(z3.any())
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        customId: "custom_id"
      });
    });
    function batchRequestToJSON(batchRequest) {
      return JSON.stringify(exports.BatchRequest$outboundSchema.parse(batchRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/batchjobin.js
var require_batchjobin = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/batchjobin.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BatchJobIn$outboundSchema = void 0;
    exports.batchJobInToJSON = batchJobInToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var apiendpoint_js_1 = require_apiendpoint();
    var batchrequest_js_1 = require_batchrequest();
    exports.BatchJobIn$outboundSchema = z3.object({
      inputFiles: z3.nullable(z3.array(z3.string())).optional(),
      requests: z3.nullable(z3.array(batchrequest_js_1.BatchRequest$outboundSchema)).optional(),
      endpoint: apiendpoint_js_1.ApiEndpoint$outboundSchema,
      model: z3.nullable(z3.string()).optional(),
      agentId: z3.nullable(z3.string()).optional(),
      metadata: z3.nullable(z3.record(z3.string())).optional(),
      timeoutHours: z3.number().int().default(24)
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        inputFiles: "input_files",
        agentId: "agent_id",
        timeoutHours: "timeout_hours"
      });
    });
    function batchJobInToJSON(batchJobIn) {
      return JSON.stringify(exports.BatchJobIn$outboundSchema.parse(batchJobIn));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/batchjobstatus.js
var require_batchjobstatus = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/batchjobstatus.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BatchJobStatus$outboundSchema = exports.BatchJobStatus$inboundSchema = exports.BatchJobStatus = void 0;
    var z3 = __importStar(require_v3());
    exports.BatchJobStatus = {
      Queued: "QUEUED",
      Running: "RUNNING",
      Success: "SUCCESS",
      Failed: "FAILED",
      TimeoutExceeded: "TIMEOUT_EXCEEDED",
      CancellationRequested: "CANCELLATION_REQUESTED",
      Cancelled: "CANCELLED"
    };
    exports.BatchJobStatus$inboundSchema = z3.nativeEnum(exports.BatchJobStatus);
    exports.BatchJobStatus$outboundSchema = exports.BatchJobStatus$inboundSchema;
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/batchjobout.js
var require_batchjobout = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/batchjobout.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BatchJobOut$inboundSchema = void 0;
    exports.batchJobOutFromJSON = batchJobOutFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var batcherror_js_1 = require_batcherror();
    var batchjobstatus_js_1 = require_batchjobstatus();
    exports.BatchJobOut$inboundSchema = z3.object({
      id: z3.string(),
      object: z3.literal("batch").default("batch"),
      input_files: z3.array(z3.string()),
      metadata: z3.nullable(z3.record(z3.any())).optional(),
      endpoint: z3.string(),
      model: z3.nullable(z3.string()).optional(),
      agent_id: z3.nullable(z3.string()).optional(),
      output_file: z3.nullable(z3.string()).optional(),
      error_file: z3.nullable(z3.string()).optional(),
      errors: z3.array(batcherror_js_1.BatchError$inboundSchema),
      outputs: z3.nullable(z3.array(z3.record(z3.any()))).optional(),
      status: batchjobstatus_js_1.BatchJobStatus$inboundSchema,
      created_at: z3.number().int(),
      total_requests: z3.number().int(),
      completed_requests: z3.number().int(),
      succeeded_requests: z3.number().int(),
      failed_requests: z3.number().int(),
      started_at: z3.nullable(z3.number().int()).optional(),
      completed_at: z3.nullable(z3.number().int()).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "input_files": "inputFiles",
        "agent_id": "agentId",
        "output_file": "outputFile",
        "error_file": "errorFile",
        "created_at": "createdAt",
        "total_requests": "totalRequests",
        "completed_requests": "completedRequests",
        "succeeded_requests": "succeededRequests",
        "failed_requests": "failedRequests",
        "started_at": "startedAt",
        "completed_at": "completedAt"
      });
    });
    function batchJobOutFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.BatchJobOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'BatchJobOut' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/batchjobsout.js
var require_batchjobsout = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/batchjobsout.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BatchJobsOut$inboundSchema = void 0;
    exports.batchJobsOutFromJSON = batchJobsOutFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    var batchjobout_js_1 = require_batchjobout();
    exports.BatchJobsOut$inboundSchema = z3.object({
      data: z3.array(batchjobout_js_1.BatchJobOut$inboundSchema).optional(),
      object: z3.literal("list").default("list"),
      total: z3.number().int()
    });
    function batchJobsOutFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.BatchJobsOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'BatchJobsOut' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/instructrequest.js
var require_instructrequest = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/instructrequest.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.InstructRequest$outboundSchema = exports.InstructRequestMessages$outboundSchema = void 0;
    exports.instructRequestMessagesToJSON = instructRequestMessagesToJSON;
    exports.instructRequestToJSON = instructRequestToJSON;
    var z3 = __importStar(require_v3());
    var assistantmessage_js_1 = require_assistantmessage();
    var systemmessage_js_1 = require_systemmessage();
    var toolmessage_js_1 = require_toolmessage();
    var usermessage_js_1 = require_usermessage();
    exports.InstructRequestMessages$outboundSchema = z3.union([
      assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })),
      systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })),
      toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })),
      usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") }))
    ]);
    function instructRequestMessagesToJSON(instructRequestMessages) {
      return JSON.stringify(exports.InstructRequestMessages$outboundSchema.parse(instructRequestMessages));
    }
    exports.InstructRequest$outboundSchema = z3.object({
      messages: z3.array(z3.union([
        assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })),
        systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })),
        toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })),
        usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") }))
      ]))
    });
    function instructRequestToJSON(instructRequest) {
      return JSON.stringify(exports.InstructRequest$outboundSchema.parse(instructRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/inputs.js
var require_inputs = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/inputs.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Inputs$outboundSchema = void 0;
    exports.inputsToJSON = inputsToJSON;
    var z3 = __importStar(require_v3());
    var instructrequest_js_1 = require_instructrequest();
    exports.Inputs$outboundSchema = z3.union([
      instructrequest_js_1.InstructRequest$outboundSchema,
      z3.array(instructrequest_js_1.InstructRequest$outboundSchema)
    ]);
    function inputsToJSON(inputs) {
      return JSON.stringify(exports.Inputs$outboundSchema.parse(inputs));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/chatclassificationrequest.js
var require_chatclassificationrequest = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/chatclassificationrequest.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatClassificationRequest$outboundSchema = void 0;
    exports.chatClassificationRequestToJSON = chatClassificationRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var inputs_js_1 = require_inputs();
    exports.ChatClassificationRequest$outboundSchema = z3.object({
      model: z3.string(),
      inputs: inputs_js_1.Inputs$outboundSchema
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        inputs: "input"
      });
    });
    function chatClassificationRequestToJSON(chatClassificationRequest) {
      return JSON.stringify(exports.ChatClassificationRequest$outboundSchema.parse(chatClassificationRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/chatcompletionchoice.js
var require_chatcompletionchoice = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/chatcompletionchoice.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatCompletionChoice$inboundSchema = exports.FinishReason$inboundSchema = exports.FinishReason = void 0;
    exports.chatCompletionChoiceFromJSON = chatCompletionChoiceFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var openEnums = __importStar(require_enums());
    var assistantmessage_js_1 = require_assistantmessage();
    exports.FinishReason = {
      Stop: "stop",
      Length: "length",
      ModelLength: "model_length",
      Error: "error",
      ToolCalls: "tool_calls"
    };
    exports.FinishReason$inboundSchema = openEnums.inboundSchema(exports.FinishReason);
    exports.ChatCompletionChoice$inboundSchema = z3.object({
      index: z3.number().int(),
      message: assistantmessage_js_1.AssistantMessage$inboundSchema,
      finish_reason: exports.FinishReason$inboundSchema
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "finish_reason": "finishReason"
      });
    });
    function chatCompletionChoiceFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ChatCompletionChoice$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ChatCompletionChoice' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/chatcompletionrequest.js
var require_chatcompletionrequest = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/chatcompletionrequest.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatCompletionRequest$outboundSchema = exports.ChatCompletionRequestToolChoice$outboundSchema = exports.Messages$outboundSchema = exports.Stop$outboundSchema = void 0;
    exports.stopToJSON = stopToJSON;
    exports.messagesToJSON = messagesToJSON;
    exports.chatCompletionRequestToolChoiceToJSON = chatCompletionRequestToolChoiceToJSON;
    exports.chatCompletionRequestToJSON = chatCompletionRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var assistantmessage_js_1 = require_assistantmessage();
    var mistralpromptmode_js_1 = require_mistralpromptmode();
    var prediction_js_1 = require_prediction();
    var responseformat_js_1 = require_responseformat();
    var systemmessage_js_1 = require_systemmessage();
    var tool_js_1 = require_tool();
    var toolchoice_js_1 = require_toolchoice();
    var toolchoiceenum_js_1 = require_toolchoiceenum();
    var toolmessage_js_1 = require_toolmessage();
    var usermessage_js_1 = require_usermessage();
    exports.Stop$outboundSchema = z3.union([z3.string(), z3.array(z3.string())]);
    function stopToJSON(stop) {
      return JSON.stringify(exports.Stop$outboundSchema.parse(stop));
    }
    exports.Messages$outboundSchema = z3.union([
      assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })),
      systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })),
      toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })),
      usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") }))
    ]);
    function messagesToJSON(messages) {
      return JSON.stringify(exports.Messages$outboundSchema.parse(messages));
    }
    exports.ChatCompletionRequestToolChoice$outboundSchema = z3.union([toolchoice_js_1.ToolChoice$outboundSchema, toolchoiceenum_js_1.ToolChoiceEnum$outboundSchema]);
    function chatCompletionRequestToolChoiceToJSON(chatCompletionRequestToolChoice) {
      return JSON.stringify(exports.ChatCompletionRequestToolChoice$outboundSchema.parse(chatCompletionRequestToolChoice));
    }
    exports.ChatCompletionRequest$outboundSchema = z3.object({
      model: z3.string(),
      temperature: z3.nullable(z3.number()).optional(),
      topP: z3.number().optional(),
      maxTokens: z3.nullable(z3.number().int()).optional(),
      stream: z3.boolean().default(false),
      stop: z3.union([z3.string(), z3.array(z3.string())]).optional(),
      randomSeed: z3.nullable(z3.number().int()).optional(),
      metadata: z3.nullable(z3.record(z3.any())).optional(),
      messages: z3.array(z3.union([
        assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })),
        systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })),
        toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })),
        usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") }))
      ])),
      responseFormat: responseformat_js_1.ResponseFormat$outboundSchema.optional(),
      tools: z3.nullable(z3.array(tool_js_1.Tool$outboundSchema)).optional(),
      toolChoice: z3.union([
        toolchoice_js_1.ToolChoice$outboundSchema,
        toolchoiceenum_js_1.ToolChoiceEnum$outboundSchema
      ]).optional(),
      presencePenalty: z3.number().optional(),
      frequencyPenalty: z3.number().optional(),
      n: z3.nullable(z3.number().int()).optional(),
      prediction: prediction_js_1.Prediction$outboundSchema.optional(),
      parallelToolCalls: z3.boolean().optional(),
      promptMode: z3.nullable(mistralpromptmode_js_1.MistralPromptMode$outboundSchema).optional(),
      safePrompt: z3.boolean().optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        topP: "top_p",
        maxTokens: "max_tokens",
        randomSeed: "random_seed",
        responseFormat: "response_format",
        toolChoice: "tool_choice",
        presencePenalty: "presence_penalty",
        frequencyPenalty: "frequency_penalty",
        parallelToolCalls: "parallel_tool_calls",
        promptMode: "prompt_mode",
        safePrompt: "safe_prompt"
      });
    });
    function chatCompletionRequestToJSON(chatCompletionRequest) {
      return JSON.stringify(exports.ChatCompletionRequest$outboundSchema.parse(chatCompletionRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/usageinfo.js
var require_usageinfo = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/usageinfo.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.UsageInfo$outboundSchema = exports.UsageInfo$inboundSchema = void 0;
    exports.usageInfoToJSON = usageInfoToJSON;
    exports.usageInfoFromJSON = usageInfoFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    exports.UsageInfo$inboundSchema = (0, schemas_js_1.collectExtraKeys)(z3.object({
      prompt_tokens: z3.number().int().default(0),
      completion_tokens: z3.number().int().default(0),
      total_tokens: z3.number().int().default(0),
      prompt_audio_seconds: z3.nullable(z3.number().int()).optional()
    }).catchall(z3.any()), "additionalProperties", true).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "prompt_tokens": "promptTokens",
        "completion_tokens": "completionTokens",
        "total_tokens": "totalTokens",
        "prompt_audio_seconds": "promptAudioSeconds"
      });
    });
    exports.UsageInfo$outboundSchema = z3.object({
      promptTokens: z3.number().int().default(0),
      completionTokens: z3.number().int().default(0),
      totalTokens: z3.number().int().default(0),
      promptAudioSeconds: z3.nullable(z3.number().int()).optional(),
      additionalProperties: z3.record(z3.any()).optional()
    }).transform((v4) => {
      return {
        ...v4.additionalProperties,
        ...(0, primitives_js_1.remap)(v4, {
          promptTokens: "prompt_tokens",
          completionTokens: "completion_tokens",
          totalTokens: "total_tokens",
          promptAudioSeconds: "prompt_audio_seconds",
          additionalProperties: null
        })
      };
    });
    function usageInfoToJSON(usageInfo) {
      return JSON.stringify(exports.UsageInfo$outboundSchema.parse(usageInfo));
    }
    function usageInfoFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.UsageInfo$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'UsageInfo' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/chatcompletionresponse.js
var require_chatcompletionresponse = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/chatcompletionresponse.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatCompletionResponse$inboundSchema = void 0;
    exports.chatCompletionResponseFromJSON = chatCompletionResponseFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    var chatcompletionchoice_js_1 = require_chatcompletionchoice();
    var usageinfo_js_1 = require_usageinfo();
    exports.ChatCompletionResponse$inboundSchema = z3.object({
      id: z3.string(),
      object: z3.string(),
      model: z3.string(),
      usage: usageinfo_js_1.UsageInfo$inboundSchema,
      created: z3.number().int(),
      choices: z3.array(chatcompletionchoice_js_1.ChatCompletionChoice$inboundSchema)
    });
    function chatCompletionResponseFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ChatCompletionResponse$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ChatCompletionResponse' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/chatcompletionstreamrequest.js
var require_chatcompletionstreamrequest = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/chatcompletionstreamrequest.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatCompletionStreamRequest$outboundSchema = exports.ChatCompletionStreamRequestToolChoice$outboundSchema = exports.ChatCompletionStreamRequestMessages$outboundSchema = exports.ChatCompletionStreamRequestStop$outboundSchema = void 0;
    exports.chatCompletionStreamRequestStopToJSON = chatCompletionStreamRequestStopToJSON;
    exports.chatCompletionStreamRequestMessagesToJSON = chatCompletionStreamRequestMessagesToJSON;
    exports.chatCompletionStreamRequestToolChoiceToJSON = chatCompletionStreamRequestToolChoiceToJSON;
    exports.chatCompletionStreamRequestToJSON = chatCompletionStreamRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var assistantmessage_js_1 = require_assistantmessage();
    var mistralpromptmode_js_1 = require_mistralpromptmode();
    var prediction_js_1 = require_prediction();
    var responseformat_js_1 = require_responseformat();
    var systemmessage_js_1 = require_systemmessage();
    var tool_js_1 = require_tool();
    var toolchoice_js_1 = require_toolchoice();
    var toolchoiceenum_js_1 = require_toolchoiceenum();
    var toolmessage_js_1 = require_toolmessage();
    var usermessage_js_1 = require_usermessage();
    exports.ChatCompletionStreamRequestStop$outboundSchema = z3.union([z3.string(), z3.array(z3.string())]);
    function chatCompletionStreamRequestStopToJSON(chatCompletionStreamRequestStop) {
      return JSON.stringify(exports.ChatCompletionStreamRequestStop$outboundSchema.parse(chatCompletionStreamRequestStop));
    }
    exports.ChatCompletionStreamRequestMessages$outboundSchema = z3.union([
      assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })),
      systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })),
      toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })),
      usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") }))
    ]);
    function chatCompletionStreamRequestMessagesToJSON(chatCompletionStreamRequestMessages) {
      return JSON.stringify(exports.ChatCompletionStreamRequestMessages$outboundSchema.parse(chatCompletionStreamRequestMessages));
    }
    exports.ChatCompletionStreamRequestToolChoice$outboundSchema = z3.union([toolchoice_js_1.ToolChoice$outboundSchema, toolchoiceenum_js_1.ToolChoiceEnum$outboundSchema]);
    function chatCompletionStreamRequestToolChoiceToJSON(chatCompletionStreamRequestToolChoice) {
      return JSON.stringify(exports.ChatCompletionStreamRequestToolChoice$outboundSchema.parse(chatCompletionStreamRequestToolChoice));
    }
    exports.ChatCompletionStreamRequest$outboundSchema = z3.object({
      model: z3.string(),
      temperature: z3.nullable(z3.number()).optional(),
      topP: z3.number().optional(),
      maxTokens: z3.nullable(z3.number().int()).optional(),
      stream: z3.boolean().default(true),
      stop: z3.union([z3.string(), z3.array(z3.string())]).optional(),
      randomSeed: z3.nullable(z3.number().int()).optional(),
      metadata: z3.nullable(z3.record(z3.any())).optional(),
      messages: z3.array(z3.union([
        assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })),
        systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })),
        toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })),
        usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") }))
      ])),
      responseFormat: responseformat_js_1.ResponseFormat$outboundSchema.optional(),
      tools: z3.nullable(z3.array(tool_js_1.Tool$outboundSchema)).optional(),
      toolChoice: z3.union([
        toolchoice_js_1.ToolChoice$outboundSchema,
        toolchoiceenum_js_1.ToolChoiceEnum$outboundSchema
      ]).optional(),
      presencePenalty: z3.number().optional(),
      frequencyPenalty: z3.number().optional(),
      n: z3.nullable(z3.number().int()).optional(),
      prediction: prediction_js_1.Prediction$outboundSchema.optional(),
      parallelToolCalls: z3.boolean().optional(),
      promptMode: z3.nullable(mistralpromptmode_js_1.MistralPromptMode$outboundSchema).optional(),
      safePrompt: z3.boolean().optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        topP: "top_p",
        maxTokens: "max_tokens",
        randomSeed: "random_seed",
        responseFormat: "response_format",
        toolChoice: "tool_choice",
        presencePenalty: "presence_penalty",
        frequencyPenalty: "frequency_penalty",
        parallelToolCalls: "parallel_tool_calls",
        promptMode: "prompt_mode",
        safePrompt: "safe_prompt"
      });
    });
    function chatCompletionStreamRequestToJSON(chatCompletionStreamRequest) {
      return JSON.stringify(exports.ChatCompletionStreamRequest$outboundSchema.parse(chatCompletionStreamRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/chatmoderationrequest.js
var require_chatmoderationrequest = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/chatmoderationrequest.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatModerationRequest$outboundSchema = exports.ChatModerationRequestInputs$outboundSchema = exports.One$outboundSchema = exports.Two$outboundSchema = void 0;
    exports.twoToJSON = twoToJSON;
    exports.oneToJSON = oneToJSON;
    exports.chatModerationRequestInputsToJSON = chatModerationRequestInputsToJSON;
    exports.chatModerationRequestToJSON = chatModerationRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var assistantmessage_js_1 = require_assistantmessage();
    var systemmessage_js_1 = require_systemmessage();
    var toolmessage_js_1 = require_toolmessage();
    var usermessage_js_1 = require_usermessage();
    exports.Two$outboundSchema = z3.union([
      assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })),
      systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })),
      toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })),
      usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") }))
    ]);
    function twoToJSON(two) {
      return JSON.stringify(exports.Two$outboundSchema.parse(two));
    }
    exports.One$outboundSchema = z3.union([
      assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })),
      systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })),
      toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })),
      usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") }))
    ]);
    function oneToJSON(one) {
      return JSON.stringify(exports.One$outboundSchema.parse(one));
    }
    exports.ChatModerationRequestInputs$outboundSchema = z3.union([
      z3.array(z3.union([
        assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })),
        systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })),
        toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })),
        usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") }))
      ])),
      z3.array(z3.array(z3.union([
        assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })),
        systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })),
        toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })),
        usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") }))
      ])))
    ]);
    function chatModerationRequestInputsToJSON(chatModerationRequestInputs) {
      return JSON.stringify(exports.ChatModerationRequestInputs$outboundSchema.parse(chatModerationRequestInputs));
    }
    exports.ChatModerationRequest$outboundSchema = z3.object({
      inputs: z3.union([
        z3.array(z3.union([
          assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })),
          systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })),
          toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })),
          usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") }))
        ])),
        z3.array(z3.array(z3.union([
          assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })),
          systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })),
          toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })),
          usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") }))
        ])))
      ]),
      model: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        inputs: "input"
      });
    });
    function chatModerationRequestToJSON(chatModerationRequest) {
      return JSON.stringify(exports.ChatModerationRequest$outboundSchema.parse(chatModerationRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/metricout.js
var require_metricout = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/metricout.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MetricOut$inboundSchema = void 0;
    exports.metricOutFromJSON = metricOutFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    exports.MetricOut$inboundSchema = z3.object({
      train_loss: z3.nullable(z3.number()).optional(),
      valid_loss: z3.nullable(z3.number()).optional(),
      valid_mean_token_accuracy: z3.nullable(z3.number()).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "train_loss": "trainLoss",
        "valid_loss": "validLoss",
        "valid_mean_token_accuracy": "validMeanTokenAccuracy"
      });
    });
    function metricOutFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.MetricOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'MetricOut' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/checkpointout.js
var require_checkpointout = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/checkpointout.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CheckpointOut$inboundSchema = void 0;
    exports.checkpointOutFromJSON = checkpointOutFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var metricout_js_1 = require_metricout();
    exports.CheckpointOut$inboundSchema = z3.object({
      metrics: metricout_js_1.MetricOut$inboundSchema,
      step_number: z3.number().int(),
      created_at: z3.number().int()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "step_number": "stepNumber",
        "created_at": "createdAt"
      });
    });
    function checkpointOutFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.CheckpointOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'CheckpointOut' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/classificationrequest.js
var require_classificationrequest = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/classificationrequest.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ClassificationRequest$outboundSchema = exports.ClassificationRequestInputs$outboundSchema = void 0;
    exports.classificationRequestInputsToJSON = classificationRequestInputsToJSON;
    exports.classificationRequestToJSON = classificationRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    exports.ClassificationRequestInputs$outboundSchema = z3.union([z3.string(), z3.array(z3.string())]);
    function classificationRequestInputsToJSON(classificationRequestInputs) {
      return JSON.stringify(exports.ClassificationRequestInputs$outboundSchema.parse(classificationRequestInputs));
    }
    exports.ClassificationRequest$outboundSchema = z3.object({
      model: z3.string(),
      metadata: z3.nullable(z3.record(z3.any())).optional(),
      inputs: z3.union([z3.string(), z3.array(z3.string())])
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        inputs: "input"
      });
    });
    function classificationRequestToJSON(classificationRequest) {
      return JSON.stringify(exports.ClassificationRequest$outboundSchema.parse(classificationRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/classificationtargetresult.js
var require_classificationtargetresult = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/classificationtargetresult.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ClassificationTargetResult$inboundSchema = void 0;
    exports.classificationTargetResultFromJSON = classificationTargetResultFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    exports.ClassificationTargetResult$inboundSchema = z3.object({
      scores: z3.record(z3.number())
    });
    function classificationTargetResultFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ClassificationTargetResult$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ClassificationTargetResult' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/classificationresponse.js
var require_classificationresponse = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/classificationresponse.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ClassificationResponse$inboundSchema = void 0;
    exports.classificationResponseFromJSON = classificationResponseFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    var classificationtargetresult_js_1 = require_classificationtargetresult();
    exports.ClassificationResponse$inboundSchema = z3.object({
      id: z3.string(),
      model: z3.string(),
      results: z3.array(z3.record(classificationtargetresult_js_1.ClassificationTargetResult$inboundSchema))
    });
    function classificationResponseFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ClassificationResponse$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ClassificationResponse' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/ftclassifierlossfunction.js
var require_ftclassifierlossfunction = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/ftclassifierlossfunction.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FTClassifierLossFunction$outboundSchema = exports.FTClassifierLossFunction$inboundSchema = exports.FTClassifierLossFunction = void 0;
    var z3 = __importStar(require_v3());
    exports.FTClassifierLossFunction = {
      SingleClass: "single_class",
      MultiClass: "multi_class"
    };
    exports.FTClassifierLossFunction$inboundSchema = z3.nativeEnum(exports.FTClassifierLossFunction);
    exports.FTClassifierLossFunction$outboundSchema = exports.FTClassifierLossFunction$inboundSchema;
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/classifiertargetout.js
var require_classifiertargetout = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/classifiertargetout.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ClassifierTargetOut$inboundSchema = void 0;
    exports.classifierTargetOutFromJSON = classifierTargetOutFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var ftclassifierlossfunction_js_1 = require_ftclassifierlossfunction();
    exports.ClassifierTargetOut$inboundSchema = z3.object({
      name: z3.string(),
      labels: z3.array(z3.string()),
      weight: z3.number(),
      loss_function: ftclassifierlossfunction_js_1.FTClassifierLossFunction$inboundSchema
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "loss_function": "lossFunction"
      });
    });
    function classifierTargetOutFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ClassifierTargetOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ClassifierTargetOut' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/classifiertrainingparameters.js
var require_classifiertrainingparameters = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/classifiertrainingparameters.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ClassifierTrainingParameters$inboundSchema = void 0;
    exports.classifierTrainingParametersFromJSON = classifierTrainingParametersFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    exports.ClassifierTrainingParameters$inboundSchema = z3.object({
      training_steps: z3.nullable(z3.number().int()).optional(),
      learning_rate: z3.number().default(1e-4),
      weight_decay: z3.nullable(z3.number()).optional(),
      warmup_fraction: z3.nullable(z3.number()).optional(),
      epochs: z3.nullable(z3.number()).optional(),
      seq_len: z3.nullable(z3.number().int()).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "training_steps": "trainingSteps",
        "learning_rate": "learningRate",
        "weight_decay": "weightDecay",
        "warmup_fraction": "warmupFraction",
        "seq_len": "seqLen"
      });
    });
    function classifierTrainingParametersFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ClassifierTrainingParameters$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ClassifierTrainingParameters' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/eventout.js
var require_eventout = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/eventout.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EventOut$inboundSchema = void 0;
    exports.eventOutFromJSON = eventOutFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    exports.EventOut$inboundSchema = z3.object({
      name: z3.string(),
      data: z3.nullable(z3.record(z3.any())).optional(),
      created_at: z3.number().int()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "created_at": "createdAt"
      });
    });
    function eventOutFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.EventOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'EventOut' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/jobmetadataout.js
var require_jobmetadataout = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/jobmetadataout.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.JobMetadataOut$inboundSchema = void 0;
    exports.jobMetadataOutFromJSON = jobMetadataOutFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    exports.JobMetadataOut$inboundSchema = z3.object({
      expected_duration_seconds: z3.nullable(z3.number().int()).optional(),
      cost: z3.nullable(z3.number()).optional(),
      cost_currency: z3.nullable(z3.string()).optional(),
      train_tokens_per_step: z3.nullable(z3.number().int()).optional(),
      train_tokens: z3.nullable(z3.number().int()).optional(),
      data_tokens: z3.nullable(z3.number().int()).optional(),
      estimated_start_time: z3.nullable(z3.number().int()).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "expected_duration_seconds": "expectedDurationSeconds",
        "cost_currency": "costCurrency",
        "train_tokens_per_step": "trainTokensPerStep",
        "train_tokens": "trainTokens",
        "data_tokens": "dataTokens",
        "estimated_start_time": "estimatedStartTime"
      });
    });
    function jobMetadataOutFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.JobMetadataOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'JobMetadataOut' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/wandbintegrationout.js
var require_wandbintegrationout = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/wandbintegrationout.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.WandbIntegrationOut$inboundSchema = void 0;
    exports.wandbIntegrationOutFromJSON = wandbIntegrationOutFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    exports.WandbIntegrationOut$inboundSchema = z3.object({
      type: z3.literal("wandb").default("wandb"),
      project: z3.string(),
      name: z3.nullable(z3.string()).optional(),
      run_name: z3.nullable(z3.string()).optional(),
      url: z3.nullable(z3.string()).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "run_name": "runName"
      });
    });
    function wandbIntegrationOutFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.WandbIntegrationOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'WandbIntegrationOut' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/classifierdetailedjobout.js
var require_classifierdetailedjobout = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/classifierdetailedjobout.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ClassifierDetailedJobOut$inboundSchema = exports.ClassifierDetailedJobOutIntegrations$inboundSchema = exports.ClassifierDetailedJobOutStatus$inboundSchema = exports.ClassifierDetailedJobOutStatus = void 0;
    exports.classifierDetailedJobOutIntegrationsFromJSON = classifierDetailedJobOutIntegrationsFromJSON;
    exports.classifierDetailedJobOutFromJSON = classifierDetailedJobOutFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var checkpointout_js_1 = require_checkpointout();
    var classifiertargetout_js_1 = require_classifiertargetout();
    var classifiertrainingparameters_js_1 = require_classifiertrainingparameters();
    var eventout_js_1 = require_eventout();
    var jobmetadataout_js_1 = require_jobmetadataout();
    var wandbintegrationout_js_1 = require_wandbintegrationout();
    exports.ClassifierDetailedJobOutStatus = {
      Queued: "QUEUED",
      Started: "STARTED",
      Validating: "VALIDATING",
      Validated: "VALIDATED",
      Running: "RUNNING",
      FailedValidation: "FAILED_VALIDATION",
      Failed: "FAILED",
      Success: "SUCCESS",
      Cancelled: "CANCELLED",
      CancellationRequested: "CANCELLATION_REQUESTED"
    };
    exports.ClassifierDetailedJobOutStatus$inboundSchema = z3.nativeEnum(exports.ClassifierDetailedJobOutStatus);
    exports.ClassifierDetailedJobOutIntegrations$inboundSchema = wandbintegrationout_js_1.WandbIntegrationOut$inboundSchema;
    function classifierDetailedJobOutIntegrationsFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ClassifierDetailedJobOutIntegrations$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ClassifierDetailedJobOutIntegrations' from JSON`);
    }
    exports.ClassifierDetailedJobOut$inboundSchema = z3.object({
      id: z3.string(),
      auto_start: z3.boolean(),
      model: z3.string(),
      status: exports.ClassifierDetailedJobOutStatus$inboundSchema,
      created_at: z3.number().int(),
      modified_at: z3.number().int(),
      training_files: z3.array(z3.string()),
      validation_files: z3.nullable(z3.array(z3.string())).optional(),
      object: z3.literal("job").default("job"),
      fine_tuned_model: z3.nullable(z3.string()).optional(),
      suffix: z3.nullable(z3.string()).optional(),
      integrations: z3.nullable(z3.array(wandbintegrationout_js_1.WandbIntegrationOut$inboundSchema)).optional(),
      trained_tokens: z3.nullable(z3.number().int()).optional(),
      metadata: z3.nullable(jobmetadataout_js_1.JobMetadataOut$inboundSchema).optional(),
      job_type: z3.literal("classifier").default("classifier"),
      hyperparameters: classifiertrainingparameters_js_1.ClassifierTrainingParameters$inboundSchema,
      events: z3.array(eventout_js_1.EventOut$inboundSchema).optional(),
      checkpoints: z3.array(checkpointout_js_1.CheckpointOut$inboundSchema).optional(),
      classifier_targets: z3.array(classifiertargetout_js_1.ClassifierTargetOut$inboundSchema)
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "auto_start": "autoStart",
        "created_at": "createdAt",
        "modified_at": "modifiedAt",
        "training_files": "trainingFiles",
        "validation_files": "validationFiles",
        "fine_tuned_model": "fineTunedModel",
        "trained_tokens": "trainedTokens",
        "job_type": "jobType",
        "classifier_targets": "classifierTargets"
      });
    });
    function classifierDetailedJobOutFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ClassifierDetailedJobOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ClassifierDetailedJobOut' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/ftmodelcapabilitiesout.js
var require_ftmodelcapabilitiesout = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/ftmodelcapabilitiesout.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FTModelCapabilitiesOut$inboundSchema = void 0;
    exports.ftModelCapabilitiesOutFromJSON = ftModelCapabilitiesOutFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    exports.FTModelCapabilitiesOut$inboundSchema = z3.object({
      completion_chat: z3.boolean().default(true),
      completion_fim: z3.boolean().default(false),
      function_calling: z3.boolean().default(false),
      fine_tuning: z3.boolean().default(false),
      classification: z3.boolean().default(false)
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "completion_chat": "completionChat",
        "completion_fim": "completionFim",
        "function_calling": "functionCalling",
        "fine_tuning": "fineTuning"
      });
    });
    function ftModelCapabilitiesOutFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.FTModelCapabilitiesOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'FTModelCapabilitiesOut' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/classifierftmodelout.js
var require_classifierftmodelout = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/classifierftmodelout.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ClassifierFTModelOut$inboundSchema = void 0;
    exports.classifierFTModelOutFromJSON = classifierFTModelOutFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var classifiertargetout_js_1 = require_classifiertargetout();
    var ftmodelcapabilitiesout_js_1 = require_ftmodelcapabilitiesout();
    exports.ClassifierFTModelOut$inboundSchema = z3.object({
      id: z3.string(),
      object: z3.literal("model").default("model"),
      created: z3.number().int(),
      owned_by: z3.string(),
      workspace_id: z3.string(),
      root: z3.string(),
      root_version: z3.string(),
      archived: z3.boolean(),
      name: z3.nullable(z3.string()).optional(),
      description: z3.nullable(z3.string()).optional(),
      capabilities: ftmodelcapabilitiesout_js_1.FTModelCapabilitiesOut$inboundSchema,
      max_context_length: z3.number().int().default(32768),
      aliases: z3.array(z3.string()).optional(),
      job: z3.string(),
      classifier_targets: z3.array(classifiertargetout_js_1.ClassifierTargetOut$inboundSchema),
      model_type: z3.literal("classifier").default("classifier")
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "owned_by": "ownedBy",
        "workspace_id": "workspaceId",
        "root_version": "rootVersion",
        "max_context_length": "maxContextLength",
        "classifier_targets": "classifierTargets",
        "model_type": "modelType"
      });
    });
    function classifierFTModelOutFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ClassifierFTModelOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ClassifierFTModelOut' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/classifierjobout.js
var require_classifierjobout = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/classifierjobout.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ClassifierJobOut$inboundSchema = exports.ClassifierJobOutIntegrations$inboundSchema = exports.ClassifierJobOutStatus$inboundSchema = exports.ClassifierJobOutStatus = void 0;
    exports.classifierJobOutIntegrationsFromJSON = classifierJobOutIntegrationsFromJSON;
    exports.classifierJobOutFromJSON = classifierJobOutFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var classifiertrainingparameters_js_1 = require_classifiertrainingparameters();
    var jobmetadataout_js_1 = require_jobmetadataout();
    var wandbintegrationout_js_1 = require_wandbintegrationout();
    exports.ClassifierJobOutStatus = {
      Queued: "QUEUED",
      Started: "STARTED",
      Validating: "VALIDATING",
      Validated: "VALIDATED",
      Running: "RUNNING",
      FailedValidation: "FAILED_VALIDATION",
      Failed: "FAILED",
      Success: "SUCCESS",
      Cancelled: "CANCELLED",
      CancellationRequested: "CANCELLATION_REQUESTED"
    };
    exports.ClassifierJobOutStatus$inboundSchema = z3.nativeEnum(exports.ClassifierJobOutStatus);
    exports.ClassifierJobOutIntegrations$inboundSchema = wandbintegrationout_js_1.WandbIntegrationOut$inboundSchema;
    function classifierJobOutIntegrationsFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ClassifierJobOutIntegrations$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ClassifierJobOutIntegrations' from JSON`);
    }
    exports.ClassifierJobOut$inboundSchema = z3.object({
      id: z3.string(),
      auto_start: z3.boolean(),
      model: z3.string(),
      status: exports.ClassifierJobOutStatus$inboundSchema,
      created_at: z3.number().int(),
      modified_at: z3.number().int(),
      training_files: z3.array(z3.string()),
      validation_files: z3.nullable(z3.array(z3.string())).optional(),
      object: z3.literal("job").default("job"),
      fine_tuned_model: z3.nullable(z3.string()).optional(),
      suffix: z3.nullable(z3.string()).optional(),
      integrations: z3.nullable(z3.array(wandbintegrationout_js_1.WandbIntegrationOut$inboundSchema)).optional(),
      trained_tokens: z3.nullable(z3.number().int()).optional(),
      metadata: z3.nullable(jobmetadataout_js_1.JobMetadataOut$inboundSchema).optional(),
      job_type: z3.literal("classifier").default("classifier"),
      hyperparameters: classifiertrainingparameters_js_1.ClassifierTrainingParameters$inboundSchema
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "auto_start": "autoStart",
        "created_at": "createdAt",
        "modified_at": "modifiedAt",
        "training_files": "trainingFiles",
        "validation_files": "validationFiles",
        "fine_tuned_model": "fineTunedModel",
        "trained_tokens": "trainedTokens",
        "job_type": "jobType"
      });
    });
    function classifierJobOutFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ClassifierJobOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ClassifierJobOut' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/classifiertargetin.js
var require_classifiertargetin = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/classifiertargetin.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ClassifierTargetIn$outboundSchema = void 0;
    exports.classifierTargetInToJSON = classifierTargetInToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var ftclassifierlossfunction_js_1 = require_ftclassifierlossfunction();
    exports.ClassifierTargetIn$outboundSchema = z3.object({
      name: z3.string(),
      labels: z3.array(z3.string()),
      weight: z3.number().default(1),
      lossFunction: z3.nullable(ftclassifierlossfunction_js_1.FTClassifierLossFunction$outboundSchema).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        lossFunction: "loss_function"
      });
    });
    function classifierTargetInToJSON(classifierTargetIn) {
      return JSON.stringify(exports.ClassifierTargetIn$outboundSchema.parse(classifierTargetIn));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/classifiertrainingparametersin.js
var require_classifiertrainingparametersin = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/classifiertrainingparametersin.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ClassifierTrainingParametersIn$outboundSchema = void 0;
    exports.classifierTrainingParametersInToJSON = classifierTrainingParametersInToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    exports.ClassifierTrainingParametersIn$outboundSchema = z3.object({
      trainingSteps: z3.nullable(z3.number().int()).optional(),
      learningRate: z3.number().default(1e-4),
      weightDecay: z3.nullable(z3.number()).optional(),
      warmupFraction: z3.nullable(z3.number()).optional(),
      epochs: z3.nullable(z3.number()).optional(),
      seqLen: z3.nullable(z3.number().int()).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        trainingSteps: "training_steps",
        learningRate: "learning_rate",
        weightDecay: "weight_decay",
        warmupFraction: "warmup_fraction",
        seqLen: "seq_len"
      });
    });
    function classifierTrainingParametersInToJSON(classifierTrainingParametersIn) {
      return JSON.stringify(exports.ClassifierTrainingParametersIn$outboundSchema.parse(classifierTrainingParametersIn));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/deltamessage.js
var require_deltamessage = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/deltamessage.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DeltaMessage$inboundSchema = exports.Content$inboundSchema = void 0;
    exports.contentFromJSON = contentFromJSON;
    exports.deltaMessageFromJSON = deltaMessageFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var contentchunk_js_1 = require_contentchunk();
    var toolcall_js_1 = require_toolcall();
    exports.Content$inboundSchema = z3.union([z3.string(), z3.array(contentchunk_js_1.ContentChunk$inboundSchema)]);
    function contentFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.Content$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'Content' from JSON`);
    }
    exports.DeltaMessage$inboundSchema = z3.object({
      role: z3.nullable(z3.string()).optional(),
      content: z3.nullable(z3.union([z3.string(), z3.array(contentchunk_js_1.ContentChunk$inboundSchema)])).optional(),
      tool_calls: z3.nullable(z3.array(toolcall_js_1.ToolCall$inboundSchema)).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "tool_calls": "toolCalls"
      });
    });
    function deltaMessageFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.DeltaMessage$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'DeltaMessage' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/completionresponsestreamchoice.js
var require_completionresponsestreamchoice = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/completionresponsestreamchoice.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CompletionResponseStreamChoice$inboundSchema = exports.CompletionResponseStreamChoiceFinishReason$inboundSchema = exports.CompletionResponseStreamChoiceFinishReason = void 0;
    exports.completionResponseStreamChoiceFromJSON = completionResponseStreamChoiceFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var openEnums = __importStar(require_enums());
    var deltamessage_js_1 = require_deltamessage();
    exports.CompletionResponseStreamChoiceFinishReason = {
      Stop: "stop",
      Length: "length",
      Error: "error",
      ToolCalls: "tool_calls"
    };
    exports.CompletionResponseStreamChoiceFinishReason$inboundSchema = openEnums.inboundSchema(exports.CompletionResponseStreamChoiceFinishReason);
    exports.CompletionResponseStreamChoice$inboundSchema = z3.object({
      index: z3.number().int(),
      delta: deltamessage_js_1.DeltaMessage$inboundSchema,
      finish_reason: z3.nullable(exports.CompletionResponseStreamChoiceFinishReason$inboundSchema)
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "finish_reason": "finishReason"
      });
    });
    function completionResponseStreamChoiceFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.CompletionResponseStreamChoice$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'CompletionResponseStreamChoice' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/completionchunk.js
var require_completionchunk = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/completionchunk.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CompletionChunk$inboundSchema = void 0;
    exports.completionChunkFromJSON = completionChunkFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    var completionresponsestreamchoice_js_1 = require_completionresponsestreamchoice();
    var usageinfo_js_1 = require_usageinfo();
    exports.CompletionChunk$inboundSchema = z3.object({
      id: z3.string(),
      object: z3.string().optional(),
      created: z3.number().int().optional(),
      model: z3.string(),
      usage: usageinfo_js_1.UsageInfo$inboundSchema.optional(),
      choices: z3.array(completionresponsestreamchoice_js_1.CompletionResponseStreamChoice$inboundSchema)
    });
    function completionChunkFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.CompletionChunk$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'CompletionChunk' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/completiontrainingparameters.js
var require_completiontrainingparameters = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/completiontrainingparameters.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CompletionTrainingParameters$inboundSchema = void 0;
    exports.completionTrainingParametersFromJSON = completionTrainingParametersFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    exports.CompletionTrainingParameters$inboundSchema = z3.object({
      training_steps: z3.nullable(z3.number().int()).optional(),
      learning_rate: z3.number().default(1e-4),
      weight_decay: z3.nullable(z3.number()).optional(),
      warmup_fraction: z3.nullable(z3.number()).optional(),
      epochs: z3.nullable(z3.number()).optional(),
      seq_len: z3.nullable(z3.number().int()).optional(),
      fim_ratio: z3.nullable(z3.number()).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "training_steps": "trainingSteps",
        "learning_rate": "learningRate",
        "weight_decay": "weightDecay",
        "warmup_fraction": "warmupFraction",
        "seq_len": "seqLen",
        "fim_ratio": "fimRatio"
      });
    });
    function completionTrainingParametersFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.CompletionTrainingParameters$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'CompletionTrainingParameters' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/githubrepositoryout.js
var require_githubrepositoryout = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/githubrepositoryout.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.GithubRepositoryOut$inboundSchema = void 0;
    exports.githubRepositoryOutFromJSON = githubRepositoryOutFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    exports.GithubRepositoryOut$inboundSchema = z3.object({
      type: z3.literal("github").default("github"),
      name: z3.string(),
      owner: z3.string(),
      ref: z3.nullable(z3.string()).optional(),
      weight: z3.number().default(1),
      commit_id: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "commit_id": "commitId"
      });
    });
    function githubRepositoryOutFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.GithubRepositoryOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'GithubRepositoryOut' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/completiondetailedjobout.js
var require_completiondetailedjobout = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/completiondetailedjobout.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CompletionDetailedJobOut$inboundSchema = exports.CompletionDetailedJobOutRepositories$inboundSchema = exports.CompletionDetailedJobOutIntegrations$inboundSchema = exports.CompletionDetailedJobOutStatus$inboundSchema = exports.CompletionDetailedJobOutStatus = void 0;
    exports.completionDetailedJobOutIntegrationsFromJSON = completionDetailedJobOutIntegrationsFromJSON;
    exports.completionDetailedJobOutRepositoriesFromJSON = completionDetailedJobOutRepositoriesFromJSON;
    exports.completionDetailedJobOutFromJSON = completionDetailedJobOutFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var checkpointout_js_1 = require_checkpointout();
    var completiontrainingparameters_js_1 = require_completiontrainingparameters();
    var eventout_js_1 = require_eventout();
    var githubrepositoryout_js_1 = require_githubrepositoryout();
    var jobmetadataout_js_1 = require_jobmetadataout();
    var wandbintegrationout_js_1 = require_wandbintegrationout();
    exports.CompletionDetailedJobOutStatus = {
      Queued: "QUEUED",
      Started: "STARTED",
      Validating: "VALIDATING",
      Validated: "VALIDATED",
      Running: "RUNNING",
      FailedValidation: "FAILED_VALIDATION",
      Failed: "FAILED",
      Success: "SUCCESS",
      Cancelled: "CANCELLED",
      CancellationRequested: "CANCELLATION_REQUESTED"
    };
    exports.CompletionDetailedJobOutStatus$inboundSchema = z3.nativeEnum(exports.CompletionDetailedJobOutStatus);
    exports.CompletionDetailedJobOutIntegrations$inboundSchema = wandbintegrationout_js_1.WandbIntegrationOut$inboundSchema;
    function completionDetailedJobOutIntegrationsFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.CompletionDetailedJobOutIntegrations$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'CompletionDetailedJobOutIntegrations' from JSON`);
    }
    exports.CompletionDetailedJobOutRepositories$inboundSchema = githubrepositoryout_js_1.GithubRepositoryOut$inboundSchema;
    function completionDetailedJobOutRepositoriesFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.CompletionDetailedJobOutRepositories$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'CompletionDetailedJobOutRepositories' from JSON`);
    }
    exports.CompletionDetailedJobOut$inboundSchema = z3.object({
      id: z3.string(),
      auto_start: z3.boolean(),
      model: z3.string(),
      status: exports.CompletionDetailedJobOutStatus$inboundSchema,
      created_at: z3.number().int(),
      modified_at: z3.number().int(),
      training_files: z3.array(z3.string()),
      validation_files: z3.nullable(z3.array(z3.string())).optional(),
      object: z3.literal("job").default("job"),
      fine_tuned_model: z3.nullable(z3.string()).optional(),
      suffix: z3.nullable(z3.string()).optional(),
      integrations: z3.nullable(z3.array(wandbintegrationout_js_1.WandbIntegrationOut$inboundSchema)).optional(),
      trained_tokens: z3.nullable(z3.number().int()).optional(),
      metadata: z3.nullable(jobmetadataout_js_1.JobMetadataOut$inboundSchema).optional(),
      job_type: z3.literal("completion").default("completion"),
      hyperparameters: completiontrainingparameters_js_1.CompletionTrainingParameters$inboundSchema,
      repositories: z3.array(githubrepositoryout_js_1.GithubRepositoryOut$inboundSchema).optional(),
      events: z3.array(eventout_js_1.EventOut$inboundSchema).optional(),
      checkpoints: z3.array(checkpointout_js_1.CheckpointOut$inboundSchema).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "auto_start": "autoStart",
        "created_at": "createdAt",
        "modified_at": "modifiedAt",
        "training_files": "trainingFiles",
        "validation_files": "validationFiles",
        "fine_tuned_model": "fineTunedModel",
        "trained_tokens": "trainedTokens",
        "job_type": "jobType"
      });
    });
    function completionDetailedJobOutFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.CompletionDetailedJobOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'CompletionDetailedJobOut' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/completionevent.js
var require_completionevent = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/completionevent.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CompletionEvent$inboundSchema = void 0;
    exports.completionEventFromJSON = completionEventFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    var completionchunk_js_1 = require_completionchunk();
    exports.CompletionEvent$inboundSchema = z3.object({
      data: z3.string().transform((v4, ctx) => {
        try {
          return JSON.parse(v4);
        } catch (err) {
          ctx.addIssue({ code: "custom", message: `malformed json: ${err}` });
          return z3.NEVER;
        }
      }).pipe(completionchunk_js_1.CompletionChunk$inboundSchema)
    });
    function completionEventFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.CompletionEvent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'CompletionEvent' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/completionftmodelout.js
var require_completionftmodelout = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/completionftmodelout.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CompletionFTModelOut$inboundSchema = void 0;
    exports.completionFTModelOutFromJSON = completionFTModelOutFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var ftmodelcapabilitiesout_js_1 = require_ftmodelcapabilitiesout();
    exports.CompletionFTModelOut$inboundSchema = z3.object({
      id: z3.string(),
      object: z3.literal("model").default("model"),
      created: z3.number().int(),
      owned_by: z3.string(),
      workspace_id: z3.string(),
      root: z3.string(),
      root_version: z3.string(),
      archived: z3.boolean(),
      name: z3.nullable(z3.string()).optional(),
      description: z3.nullable(z3.string()).optional(),
      capabilities: ftmodelcapabilitiesout_js_1.FTModelCapabilitiesOut$inboundSchema,
      max_context_length: z3.number().int().default(32768),
      aliases: z3.array(z3.string()).optional(),
      job: z3.string(),
      model_type: z3.literal("completion").default("completion")
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "owned_by": "ownedBy",
        "workspace_id": "workspaceId",
        "root_version": "rootVersion",
        "max_context_length": "maxContextLength",
        "model_type": "modelType"
      });
    });
    function completionFTModelOutFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.CompletionFTModelOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'CompletionFTModelOut' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/completionjobout.js
var require_completionjobout = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/completionjobout.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CompletionJobOut$inboundSchema = exports.Repositories$inboundSchema = exports.Integrations$inboundSchema = exports.Status$inboundSchema = exports.Status = void 0;
    exports.integrationsFromJSON = integrationsFromJSON;
    exports.repositoriesFromJSON = repositoriesFromJSON;
    exports.completionJobOutFromJSON = completionJobOutFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var completiontrainingparameters_js_1 = require_completiontrainingparameters();
    var githubrepositoryout_js_1 = require_githubrepositoryout();
    var jobmetadataout_js_1 = require_jobmetadataout();
    var wandbintegrationout_js_1 = require_wandbintegrationout();
    exports.Status = {
      Queued: "QUEUED",
      Started: "STARTED",
      Validating: "VALIDATING",
      Validated: "VALIDATED",
      Running: "RUNNING",
      FailedValidation: "FAILED_VALIDATION",
      Failed: "FAILED",
      Success: "SUCCESS",
      Cancelled: "CANCELLED",
      CancellationRequested: "CANCELLATION_REQUESTED"
    };
    exports.Status$inboundSchema = z3.nativeEnum(exports.Status);
    exports.Integrations$inboundSchema = wandbintegrationout_js_1.WandbIntegrationOut$inboundSchema;
    function integrationsFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.Integrations$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'Integrations' from JSON`);
    }
    exports.Repositories$inboundSchema = githubrepositoryout_js_1.GithubRepositoryOut$inboundSchema;
    function repositoriesFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.Repositories$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'Repositories' from JSON`);
    }
    exports.CompletionJobOut$inboundSchema = z3.object({
      id: z3.string(),
      auto_start: z3.boolean(),
      model: z3.string(),
      status: exports.Status$inboundSchema,
      created_at: z3.number().int(),
      modified_at: z3.number().int(),
      training_files: z3.array(z3.string()),
      validation_files: z3.nullable(z3.array(z3.string())).optional(),
      object: z3.literal("job").default("job"),
      fine_tuned_model: z3.nullable(z3.string()).optional(),
      suffix: z3.nullable(z3.string()).optional(),
      integrations: z3.nullable(z3.array(wandbintegrationout_js_1.WandbIntegrationOut$inboundSchema)).optional(),
      trained_tokens: z3.nullable(z3.number().int()).optional(),
      metadata: z3.nullable(jobmetadataout_js_1.JobMetadataOut$inboundSchema).optional(),
      job_type: z3.literal("completion").default("completion"),
      hyperparameters: completiontrainingparameters_js_1.CompletionTrainingParameters$inboundSchema,
      repositories: z3.array(githubrepositoryout_js_1.GithubRepositoryOut$inboundSchema).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "auto_start": "autoStart",
        "created_at": "createdAt",
        "modified_at": "modifiedAt",
        "training_files": "trainingFiles",
        "validation_files": "validationFiles",
        "fine_tuned_model": "fineTunedModel",
        "trained_tokens": "trainedTokens",
        "job_type": "jobType"
      });
    });
    function completionJobOutFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.CompletionJobOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'CompletionJobOut' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/completiontrainingparametersin.js
var require_completiontrainingparametersin = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/completiontrainingparametersin.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CompletionTrainingParametersIn$outboundSchema = void 0;
    exports.completionTrainingParametersInToJSON = completionTrainingParametersInToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    exports.CompletionTrainingParametersIn$outboundSchema = z3.object({
      trainingSteps: z3.nullable(z3.number().int()).optional(),
      learningRate: z3.number().default(1e-4),
      weightDecay: z3.nullable(z3.number()).optional(),
      warmupFraction: z3.nullable(z3.number()).optional(),
      epochs: z3.nullable(z3.number()).optional(),
      seqLen: z3.nullable(z3.number().int()).optional(),
      fimRatio: z3.nullable(z3.number()).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        trainingSteps: "training_steps",
        learningRate: "learning_rate",
        weightDecay: "weight_decay",
        warmupFraction: "warmup_fraction",
        seqLen: "seq_len",
        fimRatio: "fim_ratio"
      });
    });
    function completionTrainingParametersInToJSON(completionTrainingParametersIn) {
      return JSON.stringify(exports.CompletionTrainingParametersIn$outboundSchema.parse(completionTrainingParametersIn));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/functioncallentryarguments.js
var require_functioncallentryarguments = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/functioncallentryarguments.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FunctionCallEntryArguments$outboundSchema = exports.FunctionCallEntryArguments$inboundSchema = void 0;
    exports.functionCallEntryArgumentsToJSON = functionCallEntryArgumentsToJSON;
    exports.functionCallEntryArgumentsFromJSON = functionCallEntryArgumentsFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    exports.FunctionCallEntryArguments$inboundSchema = z3.union([z3.record(z3.any()), z3.string()]);
    exports.FunctionCallEntryArguments$outboundSchema = z3.union([z3.record(z3.any()), z3.string()]);
    function functionCallEntryArgumentsToJSON(functionCallEntryArguments) {
      return JSON.stringify(exports.FunctionCallEntryArguments$outboundSchema.parse(functionCallEntryArguments));
    }
    function functionCallEntryArgumentsFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.FunctionCallEntryArguments$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'FunctionCallEntryArguments' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/functioncallentry.js
var require_functioncallentry = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/functioncallentry.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FunctionCallEntry$outboundSchema = exports.FunctionCallEntry$inboundSchema = exports.ConfirmationStatus$outboundSchema = exports.ConfirmationStatus$inboundSchema = exports.ConfirmationStatus = void 0;
    exports.functionCallEntryToJSON = functionCallEntryToJSON;
    exports.functionCallEntryFromJSON = functionCallEntryFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var functioncallentryarguments_js_1 = require_functioncallentryarguments();
    exports.ConfirmationStatus = {
      Pending: "pending",
      Allowed: "allowed",
      Denied: "denied"
    };
    exports.ConfirmationStatus$inboundSchema = z3.nativeEnum(exports.ConfirmationStatus);
    exports.ConfirmationStatus$outboundSchema = exports.ConfirmationStatus$inboundSchema;
    exports.FunctionCallEntry$inboundSchema = z3.object({
      object: z3.literal("entry").default("entry"),
      type: z3.literal("function.call").default("function.call"),
      created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(),
      completed_at: z3.nullable(z3.string().datetime({ offset: true }).transform((v4) => new Date(v4))).optional(),
      id: z3.string().optional(),
      tool_call_id: z3.string(),
      name: z3.string(),
      arguments: functioncallentryarguments_js_1.FunctionCallEntryArguments$inboundSchema,
      confirmation_status: z3.nullable(exports.ConfirmationStatus$inboundSchema).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "created_at": "createdAt",
        "completed_at": "completedAt",
        "tool_call_id": "toolCallId",
        "confirmation_status": "confirmationStatus"
      });
    });
    exports.FunctionCallEntry$outboundSchema = z3.object({
      object: z3.literal("entry").default("entry"),
      type: z3.literal("function.call").default("function.call"),
      createdAt: z3.date().transform((v4) => v4.toISOString()).optional(),
      completedAt: z3.nullable(z3.date().transform((v4) => v4.toISOString())).optional(),
      id: z3.string().optional(),
      toolCallId: z3.string(),
      name: z3.string(),
      arguments: functioncallentryarguments_js_1.FunctionCallEntryArguments$outboundSchema,
      confirmationStatus: z3.nullable(exports.ConfirmationStatus$outboundSchema).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        createdAt: "created_at",
        completedAt: "completed_at",
        toolCallId: "tool_call_id",
        confirmationStatus: "confirmation_status"
      });
    });
    function functionCallEntryToJSON(functionCallEntry) {
      return JSON.stringify(exports.FunctionCallEntry$outboundSchema.parse(functionCallEntry));
    }
    function functionCallEntryFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.FunctionCallEntry$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'FunctionCallEntry' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/functionresultentry.js
var require_functionresultentry = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/functionresultentry.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FunctionResultEntry$outboundSchema = exports.FunctionResultEntry$inboundSchema = void 0;
    exports.functionResultEntryToJSON = functionResultEntryToJSON;
    exports.functionResultEntryFromJSON = functionResultEntryFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    exports.FunctionResultEntry$inboundSchema = z3.object({
      object: z3.literal("entry").default("entry"),
      type: z3.literal("function.result").default("function.result"),
      created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(),
      completed_at: z3.nullable(z3.string().datetime({ offset: true }).transform((v4) => new Date(v4))).optional(),
      id: z3.string().optional(),
      tool_call_id: z3.string(),
      result: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "created_at": "createdAt",
        "completed_at": "completedAt",
        "tool_call_id": "toolCallId"
      });
    });
    exports.FunctionResultEntry$outboundSchema = z3.object({
      object: z3.literal("entry").default("entry"),
      type: z3.literal("function.result").default("function.result"),
      createdAt: z3.date().transform((v4) => v4.toISOString()).optional(),
      completedAt: z3.nullable(z3.date().transform((v4) => v4.toISOString())).optional(),
      id: z3.string().optional(),
      toolCallId: z3.string(),
      result: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        createdAt: "created_at",
        completedAt: "completed_at",
        toolCallId: "tool_call_id"
      });
    });
    function functionResultEntryToJSON(functionResultEntry) {
      return JSON.stringify(exports.FunctionResultEntry$outboundSchema.parse(functionResultEntry));
    }
    function functionResultEntryFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.FunctionResultEntry$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'FunctionResultEntry' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/toolfilechunk.js
var require_toolfilechunk = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/toolfilechunk.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ToolFileChunk$outboundSchema = exports.ToolFileChunk$inboundSchema = exports.ToolFileChunkTool$outboundSchema = exports.ToolFileChunkTool$inboundSchema = void 0;
    exports.toolFileChunkToolToJSON = toolFileChunkToolToJSON;
    exports.toolFileChunkToolFromJSON = toolFileChunkToolFromJSON;
    exports.toolFileChunkToJSON = toolFileChunkToJSON;
    exports.toolFileChunkFromJSON = toolFileChunkFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var builtinconnectors_js_1 = require_builtinconnectors();
    exports.ToolFileChunkTool$inboundSchema = z3.union([builtinconnectors_js_1.BuiltInConnectors$inboundSchema, z3.string()]);
    exports.ToolFileChunkTool$outboundSchema = z3.union([builtinconnectors_js_1.BuiltInConnectors$outboundSchema, z3.string()]);
    function toolFileChunkToolToJSON(toolFileChunkTool) {
      return JSON.stringify(exports.ToolFileChunkTool$outboundSchema.parse(toolFileChunkTool));
    }
    function toolFileChunkToolFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ToolFileChunkTool$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ToolFileChunkTool' from JSON`);
    }
    exports.ToolFileChunk$inboundSchema = z3.object({
      type: z3.literal("tool_file").default("tool_file"),
      tool: z3.union([builtinconnectors_js_1.BuiltInConnectors$inboundSchema, z3.string()]),
      file_id: z3.string(),
      file_name: z3.nullable(z3.string()).optional(),
      file_type: z3.nullable(z3.string()).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "file_id": "fileId",
        "file_name": "fileName",
        "file_type": "fileType"
      });
    });
    exports.ToolFileChunk$outboundSchema = z3.object({
      type: z3.literal("tool_file").default("tool_file"),
      tool: z3.union([builtinconnectors_js_1.BuiltInConnectors$outboundSchema, z3.string()]),
      fileId: z3.string(),
      fileName: z3.nullable(z3.string()).optional(),
      fileType: z3.nullable(z3.string()).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        fileId: "file_id",
        fileName: "file_name",
        fileType: "file_type"
      });
    });
    function toolFileChunkToJSON(toolFileChunk) {
      return JSON.stringify(exports.ToolFileChunk$outboundSchema.parse(toolFileChunk));
    }
    function toolFileChunkFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ToolFileChunk$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ToolFileChunk' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/messageinputcontentchunks.js
var require_messageinputcontentchunks = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/messageinputcontentchunks.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MessageInputContentChunks$outboundSchema = exports.MessageInputContentChunks$inboundSchema = void 0;
    exports.messageInputContentChunksToJSON = messageInputContentChunksToJSON;
    exports.messageInputContentChunksFromJSON = messageInputContentChunksFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    var documenturlchunk_js_1 = require_documenturlchunk();
    var imageurlchunk_js_1 = require_imageurlchunk();
    var textchunk_js_1 = require_textchunk();
    var thinkchunk_js_1 = require_thinkchunk();
    var toolfilechunk_js_1 = require_toolfilechunk();
    exports.MessageInputContentChunks$inboundSchema = z3.union([
      toolfilechunk_js_1.ToolFileChunk$inboundSchema,
      textchunk_js_1.TextChunk$inboundSchema,
      imageurlchunk_js_1.ImageURLChunk$inboundSchema,
      documenturlchunk_js_1.DocumentURLChunk$inboundSchema,
      thinkchunk_js_1.ThinkChunk$inboundSchema
    ]);
    exports.MessageInputContentChunks$outboundSchema = z3.union([
      toolfilechunk_js_1.ToolFileChunk$outboundSchema,
      textchunk_js_1.TextChunk$outboundSchema,
      imageurlchunk_js_1.ImageURLChunk$outboundSchema,
      documenturlchunk_js_1.DocumentURLChunk$outboundSchema,
      thinkchunk_js_1.ThinkChunk$outboundSchema
    ]);
    function messageInputContentChunksToJSON(messageInputContentChunks) {
      return JSON.stringify(exports.MessageInputContentChunks$outboundSchema.parse(messageInputContentChunks));
    }
    function messageInputContentChunksFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.MessageInputContentChunks$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'MessageInputContentChunks' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/messageinputentry.js
var require_messageinputentry = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/messageinputentry.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MessageInputEntry$outboundSchema = exports.MessageInputEntry$inboundSchema = exports.MessageInputEntryContent$outboundSchema = exports.MessageInputEntryContent$inboundSchema = exports.Role$outboundSchema = exports.Role$inboundSchema = exports.Role = void 0;
    exports.messageInputEntryContentToJSON = messageInputEntryContentToJSON;
    exports.messageInputEntryContentFromJSON = messageInputEntryContentFromJSON;
    exports.messageInputEntryToJSON = messageInputEntryToJSON;
    exports.messageInputEntryFromJSON = messageInputEntryFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var messageinputcontentchunks_js_1 = require_messageinputcontentchunks();
    exports.Role = {
      Assistant: "assistant",
      User: "user"
    };
    exports.Role$inboundSchema = z3.nativeEnum(exports.Role);
    exports.Role$outboundSchema = exports.Role$inboundSchema;
    exports.MessageInputEntryContent$inboundSchema = z3.union([z3.string(), z3.array(messageinputcontentchunks_js_1.MessageInputContentChunks$inboundSchema)]);
    exports.MessageInputEntryContent$outboundSchema = z3.union([z3.string(), z3.array(messageinputcontentchunks_js_1.MessageInputContentChunks$outboundSchema)]);
    function messageInputEntryContentToJSON(messageInputEntryContent) {
      return JSON.stringify(exports.MessageInputEntryContent$outboundSchema.parse(messageInputEntryContent));
    }
    function messageInputEntryContentFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.MessageInputEntryContent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'MessageInputEntryContent' from JSON`);
    }
    exports.MessageInputEntry$inboundSchema = z3.object({
      object: z3.literal("entry").default("entry"),
      type: z3.literal("message.input").default("message.input"),
      created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(),
      completed_at: z3.nullable(z3.string().datetime({ offset: true }).transform((v4) => new Date(v4))).optional(),
      id: z3.string().optional(),
      role: exports.Role$inboundSchema,
      content: z3.union([
        z3.string(),
        z3.array(messageinputcontentchunks_js_1.MessageInputContentChunks$inboundSchema)
      ]),
      prefix: z3.boolean().default(false)
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "created_at": "createdAt",
        "completed_at": "completedAt"
      });
    });
    exports.MessageInputEntry$outboundSchema = z3.object({
      object: z3.literal("entry").default("entry"),
      type: z3.literal("message.input").default("message.input"),
      createdAt: z3.date().transform((v4) => v4.toISOString()).optional(),
      completedAt: z3.nullable(z3.date().transform((v4) => v4.toISOString())).optional(),
      id: z3.string().optional(),
      role: exports.Role$outboundSchema,
      content: z3.union([
        z3.string(),
        z3.array(messageinputcontentchunks_js_1.MessageInputContentChunks$outboundSchema)
      ]),
      prefix: z3.boolean().default(false)
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        createdAt: "created_at",
        completedAt: "completed_at"
      });
    });
    function messageInputEntryToJSON(messageInputEntry) {
      return JSON.stringify(exports.MessageInputEntry$outboundSchema.parse(messageInputEntry));
    }
    function messageInputEntryFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.MessageInputEntry$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'MessageInputEntry' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/messageoutputcontentchunks.js
var require_messageoutputcontentchunks = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/messageoutputcontentchunks.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MessageOutputContentChunks$outboundSchema = exports.MessageOutputContentChunks$inboundSchema = void 0;
    exports.messageOutputContentChunksToJSON = messageOutputContentChunksToJSON;
    exports.messageOutputContentChunksFromJSON = messageOutputContentChunksFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    var documenturlchunk_js_1 = require_documenturlchunk();
    var imageurlchunk_js_1 = require_imageurlchunk();
    var textchunk_js_1 = require_textchunk();
    var thinkchunk_js_1 = require_thinkchunk();
    var toolfilechunk_js_1 = require_toolfilechunk();
    var toolreferencechunk_js_1 = require_toolreferencechunk();
    exports.MessageOutputContentChunks$inboundSchema = z3.union([
      toolfilechunk_js_1.ToolFileChunk$inboundSchema,
      toolreferencechunk_js_1.ToolReferenceChunk$inboundSchema,
      textchunk_js_1.TextChunk$inboundSchema,
      imageurlchunk_js_1.ImageURLChunk$inboundSchema,
      documenturlchunk_js_1.DocumentURLChunk$inboundSchema,
      thinkchunk_js_1.ThinkChunk$inboundSchema
    ]);
    exports.MessageOutputContentChunks$outboundSchema = z3.union([
      toolfilechunk_js_1.ToolFileChunk$outboundSchema,
      toolreferencechunk_js_1.ToolReferenceChunk$outboundSchema,
      textchunk_js_1.TextChunk$outboundSchema,
      imageurlchunk_js_1.ImageURLChunk$outboundSchema,
      documenturlchunk_js_1.DocumentURLChunk$outboundSchema,
      thinkchunk_js_1.ThinkChunk$outboundSchema
    ]);
    function messageOutputContentChunksToJSON(messageOutputContentChunks) {
      return JSON.stringify(exports.MessageOutputContentChunks$outboundSchema.parse(messageOutputContentChunks));
    }
    function messageOutputContentChunksFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.MessageOutputContentChunks$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'MessageOutputContentChunks' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/messageoutputentry.js
var require_messageoutputentry = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/messageoutputentry.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MessageOutputEntry$outboundSchema = exports.MessageOutputEntry$inboundSchema = exports.MessageOutputEntryContent$outboundSchema = exports.MessageOutputEntryContent$inboundSchema = void 0;
    exports.messageOutputEntryContentToJSON = messageOutputEntryContentToJSON;
    exports.messageOutputEntryContentFromJSON = messageOutputEntryContentFromJSON;
    exports.messageOutputEntryToJSON = messageOutputEntryToJSON;
    exports.messageOutputEntryFromJSON = messageOutputEntryFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var messageoutputcontentchunks_js_1 = require_messageoutputcontentchunks();
    exports.MessageOutputEntryContent$inboundSchema = z3.union([z3.string(), z3.array(messageoutputcontentchunks_js_1.MessageOutputContentChunks$inboundSchema)]);
    exports.MessageOutputEntryContent$outboundSchema = z3.union([z3.string(), z3.array(messageoutputcontentchunks_js_1.MessageOutputContentChunks$outboundSchema)]);
    function messageOutputEntryContentToJSON(messageOutputEntryContent) {
      return JSON.stringify(exports.MessageOutputEntryContent$outboundSchema.parse(messageOutputEntryContent));
    }
    function messageOutputEntryContentFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.MessageOutputEntryContent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'MessageOutputEntryContent' from JSON`);
    }
    exports.MessageOutputEntry$inboundSchema = z3.object({
      object: z3.literal("entry").default("entry"),
      type: z3.literal("message.output").default("message.output"),
      created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(),
      completed_at: z3.nullable(z3.string().datetime({ offset: true }).transform((v4) => new Date(v4))).optional(),
      id: z3.string().optional(),
      agent_id: z3.nullable(z3.string()).optional(),
      model: z3.nullable(z3.string()).optional(),
      role: z3.literal("assistant").default("assistant"),
      content: z3.union([
        z3.string(),
        z3.array(messageoutputcontentchunks_js_1.MessageOutputContentChunks$inboundSchema)
      ])
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "created_at": "createdAt",
        "completed_at": "completedAt",
        "agent_id": "agentId"
      });
    });
    exports.MessageOutputEntry$outboundSchema = z3.object({
      object: z3.literal("entry").default("entry"),
      type: z3.literal("message.output").default("message.output"),
      createdAt: z3.date().transform((v4) => v4.toISOString()).optional(),
      completedAt: z3.nullable(z3.date().transform((v4) => v4.toISOString())).optional(),
      id: z3.string().optional(),
      agentId: z3.nullable(z3.string()).optional(),
      model: z3.nullable(z3.string()).optional(),
      role: z3.literal("assistant").default("assistant"),
      content: z3.union([
        z3.string(),
        z3.array(messageoutputcontentchunks_js_1.MessageOutputContentChunks$outboundSchema)
      ])
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        createdAt: "created_at",
        completedAt: "completed_at",
        agentId: "agent_id"
      });
    });
    function messageOutputEntryToJSON(messageOutputEntry) {
      return JSON.stringify(exports.MessageOutputEntry$outboundSchema.parse(messageOutputEntry));
    }
    function messageOutputEntryFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.MessageOutputEntry$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'MessageOutputEntry' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/toolexecutionentry.js
var require_toolexecutionentry = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/toolexecutionentry.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ToolExecutionEntry$outboundSchema = exports.ToolExecutionEntry$inboundSchema = exports.Name$outboundSchema = exports.Name$inboundSchema = void 0;
    exports.nameToJSON = nameToJSON;
    exports.nameFromJSON = nameFromJSON;
    exports.toolExecutionEntryToJSON = toolExecutionEntryToJSON;
    exports.toolExecutionEntryFromJSON = toolExecutionEntryFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var builtinconnectors_js_1 = require_builtinconnectors();
    exports.Name$inboundSchema = z3.union([builtinconnectors_js_1.BuiltInConnectors$inboundSchema, z3.string()]);
    exports.Name$outboundSchema = z3.union([builtinconnectors_js_1.BuiltInConnectors$outboundSchema, z3.string()]);
    function nameToJSON(name) {
      return JSON.stringify(exports.Name$outboundSchema.parse(name));
    }
    function nameFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.Name$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'Name' from JSON`);
    }
    exports.ToolExecutionEntry$inboundSchema = z3.object({
      object: z3.literal("entry").default("entry"),
      type: z3.literal("tool.execution").default("tool.execution"),
      created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(),
      completed_at: z3.nullable(z3.string().datetime({ offset: true }).transform((v4) => new Date(v4))).optional(),
      id: z3.string().optional(),
      name: z3.union([builtinconnectors_js_1.BuiltInConnectors$inboundSchema, z3.string()]),
      arguments: z3.string(),
      info: z3.record(z3.any()).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "created_at": "createdAt",
        "completed_at": "completedAt"
      });
    });
    exports.ToolExecutionEntry$outboundSchema = z3.object({
      object: z3.literal("entry").default("entry"),
      type: z3.literal("tool.execution").default("tool.execution"),
      createdAt: z3.date().transform((v4) => v4.toISOString()).optional(),
      completedAt: z3.nullable(z3.date().transform((v4) => v4.toISOString())).optional(),
      id: z3.string().optional(),
      name: z3.union([builtinconnectors_js_1.BuiltInConnectors$outboundSchema, z3.string()]),
      arguments: z3.string(),
      info: z3.record(z3.any()).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        createdAt: "created_at",
        completedAt: "completed_at"
      });
    });
    function toolExecutionEntryToJSON(toolExecutionEntry) {
      return JSON.stringify(exports.ToolExecutionEntry$outboundSchema.parse(toolExecutionEntry));
    }
    function toolExecutionEntryFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ToolExecutionEntry$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ToolExecutionEntry' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/inputentries.js
var require_inputentries = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/inputentries.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.InputEntries$outboundSchema = void 0;
    exports.inputEntriesToJSON = inputEntriesToJSON;
    var z3 = __importStar(require_v3());
    var agenthandoffentry_js_1 = require_agenthandoffentry();
    var functioncallentry_js_1 = require_functioncallentry();
    var functionresultentry_js_1 = require_functionresultentry();
    var messageinputentry_js_1 = require_messageinputentry();
    var messageoutputentry_js_1 = require_messageoutputentry();
    var toolexecutionentry_js_1 = require_toolexecutionentry();
    exports.InputEntries$outboundSchema = z3.union([
      agenthandoffentry_js_1.AgentHandoffEntry$outboundSchema,
      functioncallentry_js_1.FunctionCallEntry$outboundSchema,
      messageinputentry_js_1.MessageInputEntry$outboundSchema,
      functionresultentry_js_1.FunctionResultEntry$outboundSchema,
      toolexecutionentry_js_1.ToolExecutionEntry$outboundSchema,
      messageoutputentry_js_1.MessageOutputEntry$outboundSchema
    ]);
    function inputEntriesToJSON(inputEntries) {
      return JSON.stringify(exports.InputEntries$outboundSchema.parse(inputEntries));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationinputs.js
var require_conversationinputs = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationinputs.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ConversationInputs$outboundSchema = void 0;
    exports.conversationInputsToJSON = conversationInputsToJSON;
    var z3 = __importStar(require_v3());
    var inputentries_js_1 = require_inputentries();
    exports.ConversationInputs$outboundSchema = z3.union([z3.string(), z3.array(inputentries_js_1.InputEntries$outboundSchema)]);
    function conversationInputsToJSON(conversationInputs) {
      return JSON.stringify(exports.ConversationInputs$outboundSchema.parse(conversationInputs));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/toolcallconfirmation.js
var require_toolcallconfirmation = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/toolcallconfirmation.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ToolCallConfirmation$outboundSchema = exports.Confirmation$outboundSchema = exports.Confirmation = void 0;
    exports.toolCallConfirmationToJSON = toolCallConfirmationToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    exports.Confirmation = {
      Allow: "allow",
      Deny: "deny"
    };
    exports.Confirmation$outboundSchema = z3.nativeEnum(exports.Confirmation);
    exports.ToolCallConfirmation$outboundSchema = z3.object({
      toolCallId: z3.string(),
      confirmation: exports.Confirmation$outboundSchema
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        toolCallId: "tool_call_id"
      });
    });
    function toolCallConfirmationToJSON(toolCallConfirmation) {
      return JSON.stringify(exports.ToolCallConfirmation$outboundSchema.parse(toolCallConfirmation));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationappendrequest.js
var require_conversationappendrequest = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationappendrequest.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ConversationAppendRequest$outboundSchema = exports.ConversationAppendRequestHandoffExecution$outboundSchema = exports.ConversationAppendRequestHandoffExecution = void 0;
    exports.conversationAppendRequestToJSON = conversationAppendRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var completionargs_js_1 = require_completionargs();
    var conversationinputs_js_1 = require_conversationinputs();
    var toolcallconfirmation_js_1 = require_toolcallconfirmation();
    exports.ConversationAppendRequestHandoffExecution = {
      Client: "client",
      Server: "server"
    };
    exports.ConversationAppendRequestHandoffExecution$outboundSchema = z3.nativeEnum(exports.ConversationAppendRequestHandoffExecution);
    exports.ConversationAppendRequest$outboundSchema = z3.object({
      inputs: conversationinputs_js_1.ConversationInputs$outboundSchema.optional(),
      stream: z3.boolean().default(false),
      store: z3.boolean().default(true),
      handoffExecution: exports.ConversationAppendRequestHandoffExecution$outboundSchema.default("server"),
      completionArgs: completionargs_js_1.CompletionArgs$outboundSchema.optional(),
      toolConfirmations: z3.nullable(z3.array(toolcallconfirmation_js_1.ToolCallConfirmation$outboundSchema)).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        handoffExecution: "handoff_execution",
        completionArgs: "completion_args",
        toolConfirmations: "tool_confirmations"
      });
    });
    function conversationAppendRequestToJSON(conversationAppendRequest) {
      return JSON.stringify(exports.ConversationAppendRequest$outboundSchema.parse(conversationAppendRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationappendstreamrequest.js
var require_conversationappendstreamrequest = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationappendstreamrequest.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ConversationAppendStreamRequest$outboundSchema = exports.ConversationAppendStreamRequestHandoffExecution$outboundSchema = exports.ConversationAppendStreamRequestHandoffExecution = void 0;
    exports.conversationAppendStreamRequestToJSON = conversationAppendStreamRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var completionargs_js_1 = require_completionargs();
    var conversationinputs_js_1 = require_conversationinputs();
    var toolcallconfirmation_js_1 = require_toolcallconfirmation();
    exports.ConversationAppendStreamRequestHandoffExecution = {
      Client: "client",
      Server: "server"
    };
    exports.ConversationAppendStreamRequestHandoffExecution$outboundSchema = z3.nativeEnum(exports.ConversationAppendStreamRequestHandoffExecution);
    exports.ConversationAppendStreamRequest$outboundSchema = z3.object({
      inputs: conversationinputs_js_1.ConversationInputs$outboundSchema.optional(),
      stream: z3.boolean().default(true),
      store: z3.boolean().default(true),
      handoffExecution: exports.ConversationAppendStreamRequestHandoffExecution$outboundSchema.default("server"),
      completionArgs: completionargs_js_1.CompletionArgs$outboundSchema.optional(),
      toolConfirmations: z3.nullable(z3.array(toolcallconfirmation_js_1.ToolCallConfirmation$outboundSchema)).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        handoffExecution: "handoff_execution",
        completionArgs: "completion_args",
        toolConfirmations: "tool_confirmations"
      });
    });
    function conversationAppendStreamRequestToJSON(conversationAppendStreamRequest) {
      return JSON.stringify(exports.ConversationAppendStreamRequest$outboundSchema.parse(conversationAppendStreamRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/functioncallevent.js
var require_functioncallevent = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/functioncallevent.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FunctionCallEvent$inboundSchema = exports.FunctionCallEventConfirmationStatus$inboundSchema = exports.FunctionCallEventConfirmationStatus = void 0;
    exports.functionCallEventFromJSON = functionCallEventFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    exports.FunctionCallEventConfirmationStatus = {
      Pending: "pending",
      Allowed: "allowed",
      Denied: "denied"
    };
    exports.FunctionCallEventConfirmationStatus$inboundSchema = z3.nativeEnum(exports.FunctionCallEventConfirmationStatus);
    exports.FunctionCallEvent$inboundSchema = z3.object({
      type: z3.literal("function.call.delta").default("function.call.delta"),
      created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(),
      output_index: z3.number().int().default(0),
      id: z3.string(),
      name: z3.string(),
      tool_call_id: z3.string(),
      arguments: z3.string(),
      confirmation_status: z3.nullable(exports.FunctionCallEventConfirmationStatus$inboundSchema).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "created_at": "createdAt",
        "output_index": "outputIndex",
        "tool_call_id": "toolCallId",
        "confirmation_status": "confirmationStatus"
      });
    });
    function functionCallEventFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.FunctionCallEvent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'FunctionCallEvent' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/outputcontentchunks.js
var require_outputcontentchunks = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/outputcontentchunks.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OutputContentChunks$inboundSchema = void 0;
    exports.outputContentChunksFromJSON = outputContentChunksFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    var documenturlchunk_js_1 = require_documenturlchunk();
    var imageurlchunk_js_1 = require_imageurlchunk();
    var textchunk_js_1 = require_textchunk();
    var thinkchunk_js_1 = require_thinkchunk();
    var toolfilechunk_js_1 = require_toolfilechunk();
    var toolreferencechunk_js_1 = require_toolreferencechunk();
    exports.OutputContentChunks$inboundSchema = z3.union([
      toolfilechunk_js_1.ToolFileChunk$inboundSchema,
      toolreferencechunk_js_1.ToolReferenceChunk$inboundSchema,
      textchunk_js_1.TextChunk$inboundSchema,
      imageurlchunk_js_1.ImageURLChunk$inboundSchema,
      documenturlchunk_js_1.DocumentURLChunk$inboundSchema,
      thinkchunk_js_1.ThinkChunk$inboundSchema
    ]);
    function outputContentChunksFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.OutputContentChunks$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'OutputContentChunks' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/messageoutputevent.js
var require_messageoutputevent = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/messageoutputevent.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MessageOutputEvent$inboundSchema = exports.MessageOutputEventContent$inboundSchema = void 0;
    exports.messageOutputEventContentFromJSON = messageOutputEventContentFromJSON;
    exports.messageOutputEventFromJSON = messageOutputEventFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var outputcontentchunks_js_1 = require_outputcontentchunks();
    exports.MessageOutputEventContent$inboundSchema = z3.union([z3.string(), outputcontentchunks_js_1.OutputContentChunks$inboundSchema]);
    function messageOutputEventContentFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.MessageOutputEventContent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'MessageOutputEventContent' from JSON`);
    }
    exports.MessageOutputEvent$inboundSchema = z3.object({
      type: z3.literal("message.output.delta").default("message.output.delta"),
      created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(),
      output_index: z3.number().int().default(0),
      id: z3.string(),
      content_index: z3.number().int().default(0),
      model: z3.nullable(z3.string()).optional(),
      agent_id: z3.nullable(z3.string()).optional(),
      role: z3.literal("assistant").default("assistant"),
      content: z3.union([z3.string(), outputcontentchunks_js_1.OutputContentChunks$inboundSchema])
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "created_at": "createdAt",
        "output_index": "outputIndex",
        "content_index": "contentIndex",
        "agent_id": "agentId"
      });
    });
    function messageOutputEventFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.MessageOutputEvent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'MessageOutputEvent' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationusageinfo.js
var require_conversationusageinfo = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationusageinfo.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ConversationUsageInfo$inboundSchema = void 0;
    exports.conversationUsageInfoFromJSON = conversationUsageInfoFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    exports.ConversationUsageInfo$inboundSchema = z3.object({
      prompt_tokens: z3.number().int().default(0),
      completion_tokens: z3.number().int().default(0),
      total_tokens: z3.number().int().default(0),
      connector_tokens: z3.nullable(z3.number().int()).optional(),
      connectors: z3.nullable(z3.record(z3.number().int())).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "prompt_tokens": "promptTokens",
        "completion_tokens": "completionTokens",
        "total_tokens": "totalTokens",
        "connector_tokens": "connectorTokens"
      });
    });
    function conversationUsageInfoFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ConversationUsageInfo$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ConversationUsageInfo' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/responsedoneevent.js
var require_responsedoneevent = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/responsedoneevent.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ResponseDoneEvent$inboundSchema = void 0;
    exports.responseDoneEventFromJSON = responseDoneEventFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var conversationusageinfo_js_1 = require_conversationusageinfo();
    exports.ResponseDoneEvent$inboundSchema = z3.object({
      type: z3.literal("conversation.response.done").default("conversation.response.done"),
      created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(),
      usage: conversationusageinfo_js_1.ConversationUsageInfo$inboundSchema
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "created_at": "createdAt"
      });
    });
    function responseDoneEventFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ResponseDoneEvent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ResponseDoneEvent' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/responseerrorevent.js
var require_responseerrorevent = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/responseerrorevent.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ResponseErrorEvent$inboundSchema = void 0;
    exports.responseErrorEventFromJSON = responseErrorEventFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    exports.ResponseErrorEvent$inboundSchema = z3.object({
      type: z3.literal("conversation.response.error").default("conversation.response.error"),
      created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(),
      message: z3.string(),
      code: z3.number().int()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "created_at": "createdAt"
      });
    });
    function responseErrorEventFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ResponseErrorEvent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ResponseErrorEvent' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/responsestartedevent.js
var require_responsestartedevent = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/responsestartedevent.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ResponseStartedEvent$inboundSchema = void 0;
    exports.responseStartedEventFromJSON = responseStartedEventFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    exports.ResponseStartedEvent$inboundSchema = z3.object({
      type: z3.literal("conversation.response.started").default("conversation.response.started"),
      created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(),
      conversation_id: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "created_at": "createdAt",
        "conversation_id": "conversationId"
      });
    });
    function responseStartedEventFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ResponseStartedEvent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ResponseStartedEvent' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/ssetypes.js
var require_ssetypes = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/ssetypes.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SSETypes$inboundSchema = exports.SSETypes = void 0;
    var z3 = __importStar(require_v3());
    exports.SSETypes = {
      ConversationResponseStarted: "conversation.response.started",
      ConversationResponseDone: "conversation.response.done",
      ConversationResponseError: "conversation.response.error",
      MessageOutputDelta: "message.output.delta",
      ToolExecutionStarted: "tool.execution.started",
      ToolExecutionDelta: "tool.execution.delta",
      ToolExecutionDone: "tool.execution.done",
      AgentHandoffStarted: "agent.handoff.started",
      AgentHandoffDone: "agent.handoff.done",
      FunctionCallDelta: "function.call.delta"
    };
    exports.SSETypes$inboundSchema = z3.nativeEnum(exports.SSETypes);
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/toolexecutiondeltaevent.js
var require_toolexecutiondeltaevent = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/toolexecutiondeltaevent.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ToolExecutionDeltaEvent$inboundSchema = exports.ToolExecutionDeltaEventName$inboundSchema = void 0;
    exports.toolExecutionDeltaEventNameFromJSON = toolExecutionDeltaEventNameFromJSON;
    exports.toolExecutionDeltaEventFromJSON = toolExecutionDeltaEventFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var builtinconnectors_js_1 = require_builtinconnectors();
    exports.ToolExecutionDeltaEventName$inboundSchema = z3.union([builtinconnectors_js_1.BuiltInConnectors$inboundSchema, z3.string()]);
    function toolExecutionDeltaEventNameFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ToolExecutionDeltaEventName$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ToolExecutionDeltaEventName' from JSON`);
    }
    exports.ToolExecutionDeltaEvent$inboundSchema = z3.object({
      type: z3.literal("tool.execution.delta").default("tool.execution.delta"),
      created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(),
      output_index: z3.number().int().default(0),
      id: z3.string(),
      name: z3.union([builtinconnectors_js_1.BuiltInConnectors$inboundSchema, z3.string()]),
      arguments: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "created_at": "createdAt",
        "output_index": "outputIndex"
      });
    });
    function toolExecutionDeltaEventFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ToolExecutionDeltaEvent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ToolExecutionDeltaEvent' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/toolexecutiondoneevent.js
var require_toolexecutiondoneevent = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/toolexecutiondoneevent.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ToolExecutionDoneEvent$inboundSchema = exports.ToolExecutionDoneEventName$inboundSchema = void 0;
    exports.toolExecutionDoneEventNameFromJSON = toolExecutionDoneEventNameFromJSON;
    exports.toolExecutionDoneEventFromJSON = toolExecutionDoneEventFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var builtinconnectors_js_1 = require_builtinconnectors();
    exports.ToolExecutionDoneEventName$inboundSchema = z3.union([builtinconnectors_js_1.BuiltInConnectors$inboundSchema, z3.string()]);
    function toolExecutionDoneEventNameFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ToolExecutionDoneEventName$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ToolExecutionDoneEventName' from JSON`);
    }
    exports.ToolExecutionDoneEvent$inboundSchema = z3.object({
      type: z3.literal("tool.execution.done").default("tool.execution.done"),
      created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(),
      output_index: z3.number().int().default(0),
      id: z3.string(),
      name: z3.union([builtinconnectors_js_1.BuiltInConnectors$inboundSchema, z3.string()]),
      info: z3.record(z3.any()).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "created_at": "createdAt",
        "output_index": "outputIndex"
      });
    });
    function toolExecutionDoneEventFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ToolExecutionDoneEvent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ToolExecutionDoneEvent' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/toolexecutionstartedevent.js
var require_toolexecutionstartedevent = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/toolexecutionstartedevent.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ToolExecutionStartedEvent$inboundSchema = exports.ToolExecutionStartedEventName$inboundSchema = void 0;
    exports.toolExecutionStartedEventNameFromJSON = toolExecutionStartedEventNameFromJSON;
    exports.toolExecutionStartedEventFromJSON = toolExecutionStartedEventFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var builtinconnectors_js_1 = require_builtinconnectors();
    exports.ToolExecutionStartedEventName$inboundSchema = z3.union([builtinconnectors_js_1.BuiltInConnectors$inboundSchema, z3.string()]);
    function toolExecutionStartedEventNameFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ToolExecutionStartedEventName$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ToolExecutionStartedEventName' from JSON`);
    }
    exports.ToolExecutionStartedEvent$inboundSchema = z3.object({
      type: z3.literal("tool.execution.started").default("tool.execution.started"),
      created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(),
      output_index: z3.number().int().default(0),
      id: z3.string(),
      name: z3.union([builtinconnectors_js_1.BuiltInConnectors$inboundSchema, z3.string()]),
      arguments: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "created_at": "createdAt",
        "output_index": "outputIndex"
      });
    });
    function toolExecutionStartedEventFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ToolExecutionStartedEvent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ToolExecutionStartedEvent' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationevents.js
var require_conversationevents = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationevents.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ConversationEvents$inboundSchema = exports.ConversationEventsData$inboundSchema = void 0;
    exports.conversationEventsDataFromJSON = conversationEventsDataFromJSON;
    exports.conversationEventsFromJSON = conversationEventsFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    var agenthandoffdoneevent_js_1 = require_agenthandoffdoneevent();
    var agenthandoffstartedevent_js_1 = require_agenthandoffstartedevent();
    var functioncallevent_js_1 = require_functioncallevent();
    var messageoutputevent_js_1 = require_messageoutputevent();
    var responsedoneevent_js_1 = require_responsedoneevent();
    var responseerrorevent_js_1 = require_responseerrorevent();
    var responsestartedevent_js_1 = require_responsestartedevent();
    var ssetypes_js_1 = require_ssetypes();
    var toolexecutiondeltaevent_js_1 = require_toolexecutiondeltaevent();
    var toolexecutiondoneevent_js_1 = require_toolexecutiondoneevent();
    var toolexecutionstartedevent_js_1 = require_toolexecutionstartedevent();
    exports.ConversationEventsData$inboundSchema = z3.union([
      agenthandoffdoneevent_js_1.AgentHandoffDoneEvent$inboundSchema.and(z3.object({ type: z3.literal("agent.handoff.done") })),
      agenthandoffstartedevent_js_1.AgentHandoffStartedEvent$inboundSchema.and(z3.object({ type: z3.literal("agent.handoff.started") })),
      responsedoneevent_js_1.ResponseDoneEvent$inboundSchema.and(z3.object({ type: z3.literal("conversation.response.done") })),
      responseerrorevent_js_1.ResponseErrorEvent$inboundSchema.and(z3.object({ type: z3.literal("conversation.response.error") })),
      responsestartedevent_js_1.ResponseStartedEvent$inboundSchema.and(z3.object({ type: z3.literal("conversation.response.started") })),
      functioncallevent_js_1.FunctionCallEvent$inboundSchema.and(z3.object({ type: z3.literal("function.call.delta") })),
      messageoutputevent_js_1.MessageOutputEvent$inboundSchema.and(z3.object({ type: z3.literal("message.output.delta") })),
      toolexecutiondeltaevent_js_1.ToolExecutionDeltaEvent$inboundSchema.and(z3.object({ type: z3.literal("tool.execution.delta") })),
      toolexecutiondoneevent_js_1.ToolExecutionDoneEvent$inboundSchema.and(z3.object({ type: z3.literal("tool.execution.done") })),
      toolexecutionstartedevent_js_1.ToolExecutionStartedEvent$inboundSchema.and(z3.object({ type: z3.literal("tool.execution.started") }))
    ]);
    function conversationEventsDataFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ConversationEventsData$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ConversationEventsData' from JSON`);
    }
    exports.ConversationEvents$inboundSchema = z3.object({
      event: ssetypes_js_1.SSETypes$inboundSchema,
      data: z3.string().transform((v4, ctx) => {
        try {
          return JSON.parse(v4);
        } catch (err) {
          ctx.addIssue({ code: "custom", message: `malformed json: ${err}` });
          return z3.NEVER;
        }
      }).pipe(z3.union([
        agenthandoffdoneevent_js_1.AgentHandoffDoneEvent$inboundSchema.and(z3.object({ type: z3.literal("agent.handoff.done") })),
        agenthandoffstartedevent_js_1.AgentHandoffStartedEvent$inboundSchema.and(z3.object({ type: z3.literal("agent.handoff.started") })),
        responsedoneevent_js_1.ResponseDoneEvent$inboundSchema.and(z3.object({ type: z3.literal("conversation.response.done") })),
        responseerrorevent_js_1.ResponseErrorEvent$inboundSchema.and(z3.object({ type: z3.literal("conversation.response.error") })),
        responsestartedevent_js_1.ResponseStartedEvent$inboundSchema.and(z3.object({ type: z3.literal("conversation.response.started") })),
        functioncallevent_js_1.FunctionCallEvent$inboundSchema.and(z3.object({ type: z3.literal("function.call.delta") })),
        messageoutputevent_js_1.MessageOutputEvent$inboundSchema.and(z3.object({ type: z3.literal("message.output.delta") })),
        toolexecutiondeltaevent_js_1.ToolExecutionDeltaEvent$inboundSchema.and(z3.object({ type: z3.literal("tool.execution.delta") })),
        toolexecutiondoneevent_js_1.ToolExecutionDoneEvent$inboundSchema.and(z3.object({ type: z3.literal("tool.execution.done") })),
        toolexecutionstartedevent_js_1.ToolExecutionStartedEvent$inboundSchema.and(z3.object({ type: z3.literal("tool.execution.started") }))
      ]))
    });
    function conversationEventsFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ConversationEvents$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ConversationEvents' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationhistory.js
var require_conversationhistory = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationhistory.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ConversationHistory$inboundSchema = exports.Entries$inboundSchema = void 0;
    exports.entriesFromJSON = entriesFromJSON;
    exports.conversationHistoryFromJSON = conversationHistoryFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var agenthandoffentry_js_1 = require_agenthandoffentry();
    var functioncallentry_js_1 = require_functioncallentry();
    var functionresultentry_js_1 = require_functionresultentry();
    var messageinputentry_js_1 = require_messageinputentry();
    var messageoutputentry_js_1 = require_messageoutputentry();
    var toolexecutionentry_js_1 = require_toolexecutionentry();
    exports.Entries$inboundSchema = z3.union([
      agenthandoffentry_js_1.AgentHandoffEntry$inboundSchema,
      functioncallentry_js_1.FunctionCallEntry$inboundSchema,
      messageinputentry_js_1.MessageInputEntry$inboundSchema,
      functionresultentry_js_1.FunctionResultEntry$inboundSchema,
      toolexecutionentry_js_1.ToolExecutionEntry$inboundSchema,
      messageoutputentry_js_1.MessageOutputEntry$inboundSchema
    ]);
    function entriesFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.Entries$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'Entries' from JSON`);
    }
    exports.ConversationHistory$inboundSchema = z3.object({
      object: z3.literal("conversation.history").default("conversation.history"),
      conversation_id: z3.string(),
      entries: z3.array(z3.union([
        agenthandoffentry_js_1.AgentHandoffEntry$inboundSchema,
        functioncallentry_js_1.FunctionCallEntry$inboundSchema,
        messageinputentry_js_1.MessageInputEntry$inboundSchema,
        functionresultentry_js_1.FunctionResultEntry$inboundSchema,
        toolexecutionentry_js_1.ToolExecutionEntry$inboundSchema,
        messageoutputentry_js_1.MessageOutputEntry$inboundSchema
      ]))
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "conversation_id": "conversationId"
      });
    });
    function conversationHistoryFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ConversationHistory$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ConversationHistory' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/messageentries.js
var require_messageentries = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/messageentries.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MessageEntries$inboundSchema = void 0;
    exports.messageEntriesFromJSON = messageEntriesFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    var messageinputentry_js_1 = require_messageinputentry();
    var messageoutputentry_js_1 = require_messageoutputentry();
    exports.MessageEntries$inboundSchema = z3.union([
      messageinputentry_js_1.MessageInputEntry$inboundSchema,
      messageoutputentry_js_1.MessageOutputEntry$inboundSchema
    ]);
    function messageEntriesFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.MessageEntries$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'MessageEntries' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationmessages.js
var require_conversationmessages = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationmessages.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ConversationMessages$inboundSchema = void 0;
    exports.conversationMessagesFromJSON = conversationMessagesFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var messageentries_js_1 = require_messageentries();
    exports.ConversationMessages$inboundSchema = z3.object({
      object: z3.literal("conversation.messages").default("conversation.messages"),
      conversation_id: z3.string(),
      messages: z3.array(messageentries_js_1.MessageEntries$inboundSchema)
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "conversation_id": "conversationId"
      });
    });
    function conversationMessagesFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ConversationMessages$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ConversationMessages' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationrequest.js
var require_conversationrequest = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationrequest.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ConversationRequest$outboundSchema = exports.AgentVersion$outboundSchema = exports.Tools$outboundSchema = exports.HandoffExecution$outboundSchema = exports.HandoffExecution = void 0;
    exports.toolsToJSON = toolsToJSON;
    exports.agentVersionToJSON = agentVersionToJSON;
    exports.conversationRequestToJSON = conversationRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var codeinterpretertool_js_1 = require_codeinterpretertool();
    var completionargs_js_1 = require_completionargs();
    var conversationinputs_js_1 = require_conversationinputs();
    var documentlibrarytool_js_1 = require_documentlibrarytool();
    var functiontool_js_1 = require_functiontool();
    var imagegenerationtool_js_1 = require_imagegenerationtool();
    var websearchpremiumtool_js_1 = require_websearchpremiumtool();
    var websearchtool_js_1 = require_websearchtool();
    exports.HandoffExecution = {
      Client: "client",
      Server: "server"
    };
    exports.HandoffExecution$outboundSchema = z3.nativeEnum(exports.HandoffExecution);
    exports.Tools$outboundSchema = z3.union([
      codeinterpretertool_js_1.CodeInterpreterTool$outboundSchema.and(z3.object({ type: z3.literal("code_interpreter") })),
      documentlibrarytool_js_1.DocumentLibraryTool$outboundSchema.and(z3.object({ type: z3.literal("document_library") })),
      functiontool_js_1.FunctionTool$outboundSchema.and(z3.object({ type: z3.literal("function") })),
      imagegenerationtool_js_1.ImageGenerationTool$outboundSchema.and(z3.object({ type: z3.literal("image_generation") })),
      websearchtool_js_1.WebSearchTool$outboundSchema.and(z3.object({ type: z3.literal("web_search") })),
      websearchpremiumtool_js_1.WebSearchPremiumTool$outboundSchema.and(z3.object({ type: z3.literal("web_search_premium") }))
    ]);
    function toolsToJSON(tools) {
      return JSON.stringify(exports.Tools$outboundSchema.parse(tools));
    }
    exports.AgentVersion$outboundSchema = z3.union([z3.string(), z3.number().int()]);
    function agentVersionToJSON(agentVersion) {
      return JSON.stringify(exports.AgentVersion$outboundSchema.parse(agentVersion));
    }
    exports.ConversationRequest$outboundSchema = z3.object({
      inputs: conversationinputs_js_1.ConversationInputs$outboundSchema,
      stream: z3.boolean().default(false),
      store: z3.nullable(z3.boolean()).optional(),
      handoffExecution: z3.nullable(exports.HandoffExecution$outboundSchema).optional(),
      instructions: z3.nullable(z3.string()).optional(),
      tools: z3.array(z3.union([
        codeinterpretertool_js_1.CodeInterpreterTool$outboundSchema.and(z3.object({ type: z3.literal("code_interpreter") })),
        documentlibrarytool_js_1.DocumentLibraryTool$outboundSchema.and(z3.object({ type: z3.literal("document_library") })),
        functiontool_js_1.FunctionTool$outboundSchema.and(z3.object({ type: z3.literal("function") })),
        imagegenerationtool_js_1.ImageGenerationTool$outboundSchema.and(z3.object({ type: z3.literal("image_generation") })),
        websearchtool_js_1.WebSearchTool$outboundSchema.and(z3.object({ type: z3.literal("web_search") })),
        websearchpremiumtool_js_1.WebSearchPremiumTool$outboundSchema.and(z3.object({ type: z3.literal("web_search_premium") }))
      ])).optional(),
      completionArgs: z3.nullable(completionargs_js_1.CompletionArgs$outboundSchema).optional(),
      name: z3.nullable(z3.string()).optional(),
      description: z3.nullable(z3.string()).optional(),
      metadata: z3.nullable(z3.record(z3.any())).optional(),
      agentId: z3.nullable(z3.string()).optional(),
      agentVersion: z3.nullable(z3.union([z3.string(), z3.number().int()])).optional(),
      model: z3.nullable(z3.string()).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        handoffExecution: "handoff_execution",
        completionArgs: "completion_args",
        agentId: "agent_id",
        agentVersion: "agent_version"
      });
    });
    function conversationRequestToJSON(conversationRequest) {
      return JSON.stringify(exports.ConversationRequest$outboundSchema.parse(conversationRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationresponse.js
var require_conversationresponse = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationresponse.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ConversationResponse$inboundSchema = exports.Outputs$inboundSchema = void 0;
    exports.outputsFromJSON = outputsFromJSON;
    exports.conversationResponseFromJSON = conversationResponseFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var agenthandoffentry_js_1 = require_agenthandoffentry();
    var conversationusageinfo_js_1 = require_conversationusageinfo();
    var functioncallentry_js_1 = require_functioncallentry();
    var messageoutputentry_js_1 = require_messageoutputentry();
    var toolexecutionentry_js_1 = require_toolexecutionentry();
    exports.Outputs$inboundSchema = z3.union([
      agenthandoffentry_js_1.AgentHandoffEntry$inboundSchema,
      functioncallentry_js_1.FunctionCallEntry$inboundSchema,
      toolexecutionentry_js_1.ToolExecutionEntry$inboundSchema,
      messageoutputentry_js_1.MessageOutputEntry$inboundSchema
    ]);
    function outputsFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.Outputs$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'Outputs' from JSON`);
    }
    exports.ConversationResponse$inboundSchema = z3.object({
      object: z3.literal("conversation.response").default("conversation.response"),
      conversation_id: z3.string(),
      outputs: z3.array(z3.union([
        agenthandoffentry_js_1.AgentHandoffEntry$inboundSchema,
        functioncallentry_js_1.FunctionCallEntry$inboundSchema,
        toolexecutionentry_js_1.ToolExecutionEntry$inboundSchema,
        messageoutputentry_js_1.MessageOutputEntry$inboundSchema
      ])),
      usage: conversationusageinfo_js_1.ConversationUsageInfo$inboundSchema
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "conversation_id": "conversationId"
      });
    });
    function conversationResponseFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ConversationResponse$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ConversationResponse' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationrestartrequest.js
var require_conversationrestartrequest = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationrestartrequest.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ConversationRestartRequest$outboundSchema = exports.ConversationRestartRequestAgentVersion$outboundSchema = exports.ConversationRestartRequestHandoffExecution$outboundSchema = exports.ConversationRestartRequestHandoffExecution = void 0;
    exports.conversationRestartRequestAgentVersionToJSON = conversationRestartRequestAgentVersionToJSON;
    exports.conversationRestartRequestToJSON = conversationRestartRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var completionargs_js_1 = require_completionargs();
    var conversationinputs_js_1 = require_conversationinputs();
    exports.ConversationRestartRequestHandoffExecution = {
      Client: "client",
      Server: "server"
    };
    exports.ConversationRestartRequestHandoffExecution$outboundSchema = z3.nativeEnum(exports.ConversationRestartRequestHandoffExecution);
    exports.ConversationRestartRequestAgentVersion$outboundSchema = z3.union([z3.string(), z3.number().int()]);
    function conversationRestartRequestAgentVersionToJSON(conversationRestartRequestAgentVersion) {
      return JSON.stringify(exports.ConversationRestartRequestAgentVersion$outboundSchema.parse(conversationRestartRequestAgentVersion));
    }
    exports.ConversationRestartRequest$outboundSchema = z3.object({
      inputs: conversationinputs_js_1.ConversationInputs$outboundSchema.optional(),
      stream: z3.boolean().default(false),
      store: z3.boolean().default(true),
      handoffExecution: exports.ConversationRestartRequestHandoffExecution$outboundSchema.default("server"),
      completionArgs: completionargs_js_1.CompletionArgs$outboundSchema.optional(),
      metadata: z3.nullable(z3.record(z3.any())).optional(),
      fromEntryId: z3.string(),
      agentVersion: z3.nullable(z3.union([z3.string(), z3.number().int()])).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        handoffExecution: "handoff_execution",
        completionArgs: "completion_args",
        fromEntryId: "from_entry_id",
        agentVersion: "agent_version"
      });
    });
    function conversationRestartRequestToJSON(conversationRestartRequest) {
      return JSON.stringify(exports.ConversationRestartRequest$outboundSchema.parse(conversationRestartRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationrestartstreamrequest.js
var require_conversationrestartstreamrequest = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationrestartstreamrequest.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ConversationRestartStreamRequest$outboundSchema = exports.ConversationRestartStreamRequestAgentVersion$outboundSchema = exports.ConversationRestartStreamRequestHandoffExecution$outboundSchema = exports.ConversationRestartStreamRequestHandoffExecution = void 0;
    exports.conversationRestartStreamRequestAgentVersionToJSON = conversationRestartStreamRequestAgentVersionToJSON;
    exports.conversationRestartStreamRequestToJSON = conversationRestartStreamRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var completionargs_js_1 = require_completionargs();
    var conversationinputs_js_1 = require_conversationinputs();
    exports.ConversationRestartStreamRequestHandoffExecution = {
      Client: "client",
      Server: "server"
    };
    exports.ConversationRestartStreamRequestHandoffExecution$outboundSchema = z3.nativeEnum(exports.ConversationRestartStreamRequestHandoffExecution);
    exports.ConversationRestartStreamRequestAgentVersion$outboundSchema = z3.union([z3.string(), z3.number().int()]);
    function conversationRestartStreamRequestAgentVersionToJSON(conversationRestartStreamRequestAgentVersion) {
      return JSON.stringify(exports.ConversationRestartStreamRequestAgentVersion$outboundSchema.parse(conversationRestartStreamRequestAgentVersion));
    }
    exports.ConversationRestartStreamRequest$outboundSchema = z3.object({
      inputs: conversationinputs_js_1.ConversationInputs$outboundSchema.optional(),
      stream: z3.boolean().default(true),
      store: z3.boolean().default(true),
      handoffExecution: exports.ConversationRestartStreamRequestHandoffExecution$outboundSchema.default("server"),
      completionArgs: completionargs_js_1.CompletionArgs$outboundSchema.optional(),
      metadata: z3.nullable(z3.record(z3.any())).optional(),
      fromEntryId: z3.string(),
      agentVersion: z3.nullable(z3.union([z3.string(), z3.number().int()])).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        handoffExecution: "handoff_execution",
        completionArgs: "completion_args",
        fromEntryId: "from_entry_id",
        agentVersion: "agent_version"
      });
    });
    function conversationRestartStreamRequestToJSON(conversationRestartStreamRequest) {
      return JSON.stringify(exports.ConversationRestartStreamRequest$outboundSchema.parse(conversationRestartStreamRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationstreamrequest.js
var require_conversationstreamrequest = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationstreamrequest.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ConversationStreamRequest$outboundSchema = exports.ConversationStreamRequestAgentVersion$outboundSchema = exports.ConversationStreamRequestTools$outboundSchema = exports.ConversationStreamRequestHandoffExecution$outboundSchema = exports.ConversationStreamRequestHandoffExecution = void 0;
    exports.conversationStreamRequestToolsToJSON = conversationStreamRequestToolsToJSON;
    exports.conversationStreamRequestAgentVersionToJSON = conversationStreamRequestAgentVersionToJSON;
    exports.conversationStreamRequestToJSON = conversationStreamRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var codeinterpretertool_js_1 = require_codeinterpretertool();
    var completionargs_js_1 = require_completionargs();
    var conversationinputs_js_1 = require_conversationinputs();
    var documentlibrarytool_js_1 = require_documentlibrarytool();
    var functiontool_js_1 = require_functiontool();
    var imagegenerationtool_js_1 = require_imagegenerationtool();
    var websearchpremiumtool_js_1 = require_websearchpremiumtool();
    var websearchtool_js_1 = require_websearchtool();
    exports.ConversationStreamRequestHandoffExecution = {
      Client: "client",
      Server: "server"
    };
    exports.ConversationStreamRequestHandoffExecution$outboundSchema = z3.nativeEnum(exports.ConversationStreamRequestHandoffExecution);
    exports.ConversationStreamRequestTools$outboundSchema = z3.union([
      codeinterpretertool_js_1.CodeInterpreterTool$outboundSchema.and(z3.object({ type: z3.literal("code_interpreter") })),
      documentlibrarytool_js_1.DocumentLibraryTool$outboundSchema.and(z3.object({ type: z3.literal("document_library") })),
      functiontool_js_1.FunctionTool$outboundSchema.and(z3.object({ type: z3.literal("function") })),
      imagegenerationtool_js_1.ImageGenerationTool$outboundSchema.and(z3.object({ type: z3.literal("image_generation") })),
      websearchtool_js_1.WebSearchTool$outboundSchema.and(z3.object({ type: z3.literal("web_search") })),
      websearchpremiumtool_js_1.WebSearchPremiumTool$outboundSchema.and(z3.object({ type: z3.literal("web_search_premium") }))
    ]);
    function conversationStreamRequestToolsToJSON(conversationStreamRequestTools) {
      return JSON.stringify(exports.ConversationStreamRequestTools$outboundSchema.parse(conversationStreamRequestTools));
    }
    exports.ConversationStreamRequestAgentVersion$outboundSchema = z3.union([z3.string(), z3.number().int()]);
    function conversationStreamRequestAgentVersionToJSON(conversationStreamRequestAgentVersion) {
      return JSON.stringify(exports.ConversationStreamRequestAgentVersion$outboundSchema.parse(conversationStreamRequestAgentVersion));
    }
    exports.ConversationStreamRequest$outboundSchema = z3.object({
      inputs: conversationinputs_js_1.ConversationInputs$outboundSchema,
      stream: z3.boolean().default(true),
      store: z3.nullable(z3.boolean()).optional(),
      handoffExecution: z3.nullable(exports.ConversationStreamRequestHandoffExecution$outboundSchema).optional(),
      instructions: z3.nullable(z3.string()).optional(),
      tools: z3.array(z3.union([
        codeinterpretertool_js_1.CodeInterpreterTool$outboundSchema.and(z3.object({ type: z3.literal("code_interpreter") })),
        documentlibrarytool_js_1.DocumentLibraryTool$outboundSchema.and(z3.object({ type: z3.literal("document_library") })),
        functiontool_js_1.FunctionTool$outboundSchema.and(z3.object({ type: z3.literal("function") })),
        imagegenerationtool_js_1.ImageGenerationTool$outboundSchema.and(z3.object({ type: z3.literal("image_generation") })),
        websearchtool_js_1.WebSearchTool$outboundSchema.and(z3.object({ type: z3.literal("web_search") })),
        websearchpremiumtool_js_1.WebSearchPremiumTool$outboundSchema.and(z3.object({ type: z3.literal("web_search_premium") }))
      ])).optional(),
      completionArgs: z3.nullable(completionargs_js_1.CompletionArgs$outboundSchema).optional(),
      name: z3.nullable(z3.string()).optional(),
      description: z3.nullable(z3.string()).optional(),
      metadata: z3.nullable(z3.record(z3.any())).optional(),
      agentId: z3.nullable(z3.string()).optional(),
      agentVersion: z3.nullable(z3.union([z3.string(), z3.number().int()])).optional(),
      model: z3.nullable(z3.string()).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        handoffExecution: "handoff_execution",
        completionArgs: "completion_args",
        agentId: "agent_id",
        agentVersion: "agent_version"
      });
    });
    function conversationStreamRequestToJSON(conversationStreamRequest) {
      return JSON.stringify(exports.ConversationStreamRequest$outboundSchema.parse(conversationStreamRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/deletefileout.js
var require_deletefileout = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/deletefileout.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DeleteFileOut$inboundSchema = void 0;
    exports.deleteFileOutFromJSON = deleteFileOutFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    exports.DeleteFileOut$inboundSchema = z3.object({
      id: z3.string(),
      object: z3.string(),
      deleted: z3.boolean()
    });
    function deleteFileOutFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.DeleteFileOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'DeleteFileOut' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/deletemodelout.js
var require_deletemodelout = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/deletemodelout.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DeleteModelOut$inboundSchema = void 0;
    exports.deleteModelOutFromJSON = deleteModelOutFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    exports.DeleteModelOut$inboundSchema = z3.object({
      id: z3.string(),
      object: z3.string().default("model"),
      deleted: z3.boolean().default(true)
    });
    function deleteModelOutFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.DeleteModelOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'DeleteModelOut' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/documentout.js
var require_documentout = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/documentout.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DocumentOut$inboundSchema = void 0;
    exports.documentOutFromJSON = documentOutFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    exports.DocumentOut$inboundSchema = z3.object({
      id: z3.string(),
      library_id: z3.string(),
      hash: z3.nullable(z3.string()),
      mime_type: z3.nullable(z3.string()),
      extension: z3.nullable(z3.string()),
      size: z3.nullable(z3.number().int()),
      name: z3.string(),
      summary: z3.nullable(z3.string()).optional(),
      created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)),
      last_processed_at: z3.nullable(z3.string().datetime({ offset: true }).transform((v4) => new Date(v4))).optional(),
      number_of_pages: z3.nullable(z3.number().int()).optional(),
      uploaded_by_id: z3.nullable(z3.string()),
      uploaded_by_type: z3.string(),
      tokens_processing_main_content: z3.nullable(z3.number().int()).optional(),
      tokens_processing_summary: z3.nullable(z3.number().int()).optional(),
      url: z3.nullable(z3.string()).optional(),
      attributes: z3.nullable(z3.record(z3.any())).optional(),
      processing_status: z3.string(),
      tokens_processing_total: z3.number().int()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "library_id": "libraryId",
        "mime_type": "mimeType",
        "created_at": "createdAt",
        "last_processed_at": "lastProcessedAt",
        "number_of_pages": "numberOfPages",
        "uploaded_by_id": "uploadedById",
        "uploaded_by_type": "uploadedByType",
        "tokens_processing_main_content": "tokensProcessingMainContent",
        "tokens_processing_summary": "tokensProcessingSummary",
        "processing_status": "processingStatus",
        "tokens_processing_total": "tokensProcessingTotal"
      });
    });
    function documentOutFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.DocumentOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'DocumentOut' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/documenttextcontent.js
var require_documenttextcontent = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/documenttextcontent.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DocumentTextContent$inboundSchema = void 0;
    exports.documentTextContentFromJSON = documentTextContentFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    exports.DocumentTextContent$inboundSchema = z3.object({
      text: z3.string()
    });
    function documentTextContentFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.DocumentTextContent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'DocumentTextContent' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/documentupdatein.js
var require_documentupdatein = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/documentupdatein.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DocumentUpdateIn$outboundSchema = exports.Attributes$outboundSchema = void 0;
    exports.attributesToJSON = attributesToJSON;
    exports.documentUpdateInToJSON = documentUpdateInToJSON;
    var z3 = __importStar(require_v3());
    exports.Attributes$outboundSchema = z3.union([
      z3.boolean(),
      z3.string(),
      z3.number().int(),
      z3.number(),
      z3.date().transform((v4) => v4.toISOString()),
      z3.array(z3.string()),
      z3.array(z3.number().int()),
      z3.array(z3.number()),
      z3.array(z3.boolean())
    ]);
    function attributesToJSON(attributes) {
      return JSON.stringify(exports.Attributes$outboundSchema.parse(attributes));
    }
    exports.DocumentUpdateIn$outboundSchema = z3.object({
      name: z3.nullable(z3.string()).optional(),
      attributes: z3.nullable(z3.record(z3.union([
        z3.boolean(),
        z3.string(),
        z3.number().int(),
        z3.number(),
        z3.date().transform((v4) => v4.toISOString()),
        z3.array(z3.string()),
        z3.array(z3.number().int()),
        z3.array(z3.number()),
        z3.array(z3.boolean())
      ]))).optional()
    });
    function documentUpdateInToJSON(documentUpdateIn) {
      return JSON.stringify(exports.DocumentUpdateIn$outboundSchema.parse(documentUpdateIn));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/embeddingdtype.js
var require_embeddingdtype = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/embeddingdtype.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EmbeddingDtype$outboundSchema = exports.EmbeddingDtype = void 0;
    var z3 = __importStar(require_v3());
    exports.EmbeddingDtype = {
      Float: "float",
      Int8: "int8",
      Uint8: "uint8",
      Binary: "binary",
      Ubinary: "ubinary"
    };
    exports.EmbeddingDtype$outboundSchema = z3.nativeEnum(exports.EmbeddingDtype);
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/encodingformat.js
var require_encodingformat = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/encodingformat.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EncodingFormat$outboundSchema = exports.EncodingFormat = void 0;
    var z3 = __importStar(require_v3());
    exports.EncodingFormat = {
      Float: "float",
      Base64: "base64"
    };
    exports.EncodingFormat$outboundSchema = z3.nativeEnum(exports.EncodingFormat);
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/embeddingrequest.js
var require_embeddingrequest = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/embeddingrequest.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EmbeddingRequest$outboundSchema = exports.EmbeddingRequestInputs$outboundSchema = void 0;
    exports.embeddingRequestInputsToJSON = embeddingRequestInputsToJSON;
    exports.embeddingRequestToJSON = embeddingRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var embeddingdtype_js_1 = require_embeddingdtype();
    var encodingformat_js_1 = require_encodingformat();
    exports.EmbeddingRequestInputs$outboundSchema = z3.union([z3.string(), z3.array(z3.string())]);
    function embeddingRequestInputsToJSON(embeddingRequestInputs) {
      return JSON.stringify(exports.EmbeddingRequestInputs$outboundSchema.parse(embeddingRequestInputs));
    }
    exports.EmbeddingRequest$outboundSchema = z3.object({
      model: z3.string(),
      metadata: z3.nullable(z3.record(z3.any())).optional(),
      inputs: z3.union([z3.string(), z3.array(z3.string())]),
      outputDimension: z3.nullable(z3.number().int()).optional(),
      outputDtype: embeddingdtype_js_1.EmbeddingDtype$outboundSchema.optional(),
      encodingFormat: encodingformat_js_1.EncodingFormat$outboundSchema.optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        inputs: "input",
        outputDimension: "output_dimension",
        outputDtype: "output_dtype",
        encodingFormat: "encoding_format"
      });
    });
    function embeddingRequestToJSON(embeddingRequest) {
      return JSON.stringify(exports.EmbeddingRequest$outboundSchema.parse(embeddingRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/embeddingresponsedata.js
var require_embeddingresponsedata = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/embeddingresponsedata.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EmbeddingResponseData$inboundSchema = void 0;
    exports.embeddingResponseDataFromJSON = embeddingResponseDataFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    exports.EmbeddingResponseData$inboundSchema = z3.object({
      object: z3.string().optional(),
      embedding: z3.array(z3.number()).optional(),
      index: z3.number().int().optional()
    });
    function embeddingResponseDataFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.EmbeddingResponseData$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'EmbeddingResponseData' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/embeddingresponse.js
var require_embeddingresponse = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/embeddingresponse.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EmbeddingResponse$inboundSchema = void 0;
    exports.embeddingResponseFromJSON = embeddingResponseFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    var embeddingresponsedata_js_1 = require_embeddingresponsedata();
    var usageinfo_js_1 = require_usageinfo();
    exports.EmbeddingResponse$inboundSchema = z3.object({
      id: z3.string(),
      object: z3.string(),
      model: z3.string(),
      usage: usageinfo_js_1.UsageInfo$inboundSchema,
      data: z3.array(embeddingresponsedata_js_1.EmbeddingResponseData$inboundSchema)
    });
    function embeddingResponseFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.EmbeddingResponse$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'EmbeddingResponse' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/entitytype.js
var require_entitytype = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/entitytype.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EntityType$outboundSchema = exports.EntityType = void 0;
    var openEnums = __importStar(require_enums());
    exports.EntityType = {
      User: "User",
      Workspace: "Workspace",
      Org: "Org"
    };
    exports.EntityType$outboundSchema = openEnums.outboundSchema(exports.EntityType);
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/filepurpose.js
var require_filepurpose = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/filepurpose.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FilePurpose$outboundSchema = exports.FilePurpose$inboundSchema = exports.FilePurpose = void 0;
    var openEnums = __importStar(require_enums());
    exports.FilePurpose = {
      FineTune: "fine-tune",
      Batch: "batch",
      Ocr: "ocr"
    };
    exports.FilePurpose$inboundSchema = openEnums.inboundSchema(exports.FilePurpose);
    exports.FilePurpose$outboundSchema = openEnums.outboundSchema(exports.FilePurpose);
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/sampletype.js
var require_sampletype = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/sampletype.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SampleType$outboundSchema = exports.SampleType$inboundSchema = exports.SampleType = void 0;
    var openEnums = __importStar(require_enums());
    exports.SampleType = {
      Pretrain: "pretrain",
      Instruct: "instruct",
      BatchRequest: "batch_request",
      BatchResult: "batch_result",
      BatchError: "batch_error"
    };
    exports.SampleType$inboundSchema = openEnums.inboundSchema(exports.SampleType);
    exports.SampleType$outboundSchema = openEnums.outboundSchema(exports.SampleType);
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/source.js
var require_source = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/source.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Source$outboundSchema = exports.Source$inboundSchema = exports.Source = void 0;
    var openEnums = __importStar(require_enums());
    exports.Source = {
      Upload: "upload",
      Repository: "repository",
      Mistral: "mistral"
    };
    exports.Source$inboundSchema = openEnums.inboundSchema(exports.Source);
    exports.Source$outboundSchema = openEnums.outboundSchema(exports.Source);
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/fileschema.js
var require_fileschema = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/fileschema.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FileSchema$inboundSchema = void 0;
    exports.fileSchemaFromJSON = fileSchemaFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var filepurpose_js_1 = require_filepurpose();
    var sampletype_js_1 = require_sampletype();
    var source_js_1 = require_source();
    exports.FileSchema$inboundSchema = z3.object({
      id: z3.string(),
      object: z3.string(),
      bytes: z3.number().int(),
      created_at: z3.number().int(),
      filename: z3.string(),
      purpose: filepurpose_js_1.FilePurpose$inboundSchema,
      sample_type: sampletype_js_1.SampleType$inboundSchema,
      num_lines: z3.nullable(z3.number().int()).optional(),
      mimetype: z3.nullable(z3.string()).optional(),
      source: source_js_1.Source$inboundSchema,
      signature: z3.nullable(z3.string()).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "bytes": "sizeBytes",
        "created_at": "createdAt",
        "sample_type": "sampleType",
        "num_lines": "numLines"
      });
    });
    function fileSchemaFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.FileSchema$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'FileSchema' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/filesignedurl.js
var require_filesignedurl = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/filesignedurl.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FileSignedURL$inboundSchema = void 0;
    exports.fileSignedURLFromJSON = fileSignedURLFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    exports.FileSignedURL$inboundSchema = z3.object({
      url: z3.string()
    });
    function fileSignedURLFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.FileSignedURL$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'FileSignedURL' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/fimcompletionrequest.js
var require_fimcompletionrequest = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/fimcompletionrequest.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FIMCompletionRequest$outboundSchema = exports.FIMCompletionRequestStop$outboundSchema = void 0;
    exports.fimCompletionRequestStopToJSON = fimCompletionRequestStopToJSON;
    exports.fimCompletionRequestToJSON = fimCompletionRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    exports.FIMCompletionRequestStop$outboundSchema = z3.union([z3.string(), z3.array(z3.string())]);
    function fimCompletionRequestStopToJSON(fimCompletionRequestStop) {
      return JSON.stringify(exports.FIMCompletionRequestStop$outboundSchema.parse(fimCompletionRequestStop));
    }
    exports.FIMCompletionRequest$outboundSchema = z3.object({
      model: z3.string(),
      temperature: z3.nullable(z3.number()).optional(),
      topP: z3.number().default(1),
      maxTokens: z3.nullable(z3.number().int()).optional(),
      stream: z3.boolean().default(false),
      stop: z3.union([z3.string(), z3.array(z3.string())]).optional(),
      randomSeed: z3.nullable(z3.number().int()).optional(),
      metadata: z3.nullable(z3.record(z3.any())).optional(),
      prompt: z3.string(),
      suffix: z3.nullable(z3.string()).optional(),
      minTokens: z3.nullable(z3.number().int()).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        topP: "top_p",
        maxTokens: "max_tokens",
        randomSeed: "random_seed",
        minTokens: "min_tokens"
      });
    });
    function fimCompletionRequestToJSON(fimCompletionRequest) {
      return JSON.stringify(exports.FIMCompletionRequest$outboundSchema.parse(fimCompletionRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/fimcompletionresponse.js
var require_fimcompletionresponse = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/fimcompletionresponse.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FIMCompletionResponse$inboundSchema = void 0;
    exports.fimCompletionResponseFromJSON = fimCompletionResponseFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    var chatcompletionchoice_js_1 = require_chatcompletionchoice();
    var usageinfo_js_1 = require_usageinfo();
    exports.FIMCompletionResponse$inboundSchema = z3.object({
      id: z3.string(),
      object: z3.string(),
      model: z3.string(),
      usage: usageinfo_js_1.UsageInfo$inboundSchema,
      created: z3.number().int(),
      choices: z3.array(chatcompletionchoice_js_1.ChatCompletionChoice$inboundSchema)
    });
    function fimCompletionResponseFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.FIMCompletionResponse$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'FIMCompletionResponse' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/fimcompletionstreamrequest.js
var require_fimcompletionstreamrequest = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/fimcompletionstreamrequest.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FIMCompletionStreamRequest$outboundSchema = exports.FIMCompletionStreamRequestStop$outboundSchema = void 0;
    exports.fimCompletionStreamRequestStopToJSON = fimCompletionStreamRequestStopToJSON;
    exports.fimCompletionStreamRequestToJSON = fimCompletionStreamRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    exports.FIMCompletionStreamRequestStop$outboundSchema = z3.union([z3.string(), z3.array(z3.string())]);
    function fimCompletionStreamRequestStopToJSON(fimCompletionStreamRequestStop) {
      return JSON.stringify(exports.FIMCompletionStreamRequestStop$outboundSchema.parse(fimCompletionStreamRequestStop));
    }
    exports.FIMCompletionStreamRequest$outboundSchema = z3.object({
      model: z3.string(),
      temperature: z3.nullable(z3.number()).optional(),
      topP: z3.number().default(1),
      maxTokens: z3.nullable(z3.number().int()).optional(),
      stream: z3.boolean().default(true),
      stop: z3.union([z3.string(), z3.array(z3.string())]).optional(),
      randomSeed: z3.nullable(z3.number().int()).optional(),
      metadata: z3.nullable(z3.record(z3.any())).optional(),
      prompt: z3.string(),
      suffix: z3.nullable(z3.string()).optional(),
      minTokens: z3.nullable(z3.number().int()).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        topP: "top_p",
        maxTokens: "max_tokens",
        randomSeed: "random_seed",
        minTokens: "min_tokens"
      });
    });
    function fimCompletionStreamRequestToJSON(fimCompletionStreamRequest) {
      return JSON.stringify(exports.FIMCompletionStreamRequest$outboundSchema.parse(fimCompletionStreamRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/finetuneablemodeltype.js
var require_finetuneablemodeltype = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/finetuneablemodeltype.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FineTuneableModelType$outboundSchema = exports.FineTuneableModelType = void 0;
    var z3 = __importStar(require_v3());
    exports.FineTuneableModelType = {
      Completion: "completion",
      Classifier: "classifier"
    };
    exports.FineTuneableModelType$outboundSchema = z3.nativeEnum(exports.FineTuneableModelType);
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/ftmodelcard.js
var require_ftmodelcard = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/ftmodelcard.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FTModelCard$inboundSchema = void 0;
    exports.ftModelCardFromJSON = ftModelCardFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var modelcapabilities_js_1 = require_modelcapabilities();
    exports.FTModelCard$inboundSchema = z3.object({
      id: z3.string(),
      object: z3.string().default("model"),
      created: z3.number().int().optional(),
      owned_by: z3.string().default("mistralai"),
      capabilities: modelcapabilities_js_1.ModelCapabilities$inboundSchema,
      name: z3.nullable(z3.string()).optional(),
      description: z3.nullable(z3.string()).optional(),
      max_context_length: z3.number().int().default(32768),
      aliases: z3.array(z3.string()).optional(),
      deprecation: z3.nullable(z3.string().datetime({ offset: true }).transform((v4) => new Date(v4))).optional(),
      deprecation_replacement_model: z3.nullable(z3.string()).optional(),
      default_model_temperature: z3.nullable(z3.number()).optional(),
      type: z3.literal("fine-tuned").default("fine-tuned"),
      job: z3.string(),
      root: z3.string(),
      archived: z3.boolean().default(false)
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "owned_by": "ownedBy",
        "max_context_length": "maxContextLength",
        "deprecation_replacement_model": "deprecationReplacementModel",
        "default_model_temperature": "defaultModelTemperature"
      });
    });
    function ftModelCardFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.FTModelCard$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'FTModelCard' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/githubrepositoryin.js
var require_githubrepositoryin = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/githubrepositoryin.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.GithubRepositoryIn$outboundSchema = void 0;
    exports.githubRepositoryInToJSON = githubRepositoryInToJSON;
    var z3 = __importStar(require_v3());
    exports.GithubRepositoryIn$outboundSchema = z3.object({
      type: z3.literal("github").default("github"),
      name: z3.string(),
      owner: z3.string(),
      ref: z3.nullable(z3.string()).optional(),
      weight: z3.number().default(1),
      token: z3.string()
    });
    function githubRepositoryInToJSON(githubRepositoryIn) {
      return JSON.stringify(exports.GithubRepositoryIn$outboundSchema.parse(githubRepositoryIn));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/trainingfile.js
var require_trainingfile = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/trainingfile.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TrainingFile$outboundSchema = void 0;
    exports.trainingFileToJSON = trainingFileToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    exports.TrainingFile$outboundSchema = z3.object({
      fileId: z3.string(),
      weight: z3.number().default(1)
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        fileId: "file_id"
      });
    });
    function trainingFileToJSON(trainingFile) {
      return JSON.stringify(exports.TrainingFile$outboundSchema.parse(trainingFile));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/wandbintegration.js
var require_wandbintegration = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/wandbintegration.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.WandbIntegration$outboundSchema = void 0;
    exports.wandbIntegrationToJSON = wandbIntegrationToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    exports.WandbIntegration$outboundSchema = z3.object({
      type: z3.literal("wandb").default("wandb"),
      project: z3.string(),
      name: z3.nullable(z3.string()).optional(),
      apiKey: z3.string(),
      runName: z3.nullable(z3.string()).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        apiKey: "api_key",
        runName: "run_name"
      });
    });
    function wandbIntegrationToJSON(wandbIntegration) {
      return JSON.stringify(exports.WandbIntegration$outboundSchema.parse(wandbIntegration));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/jobin.js
var require_jobin = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/jobin.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.JobIn$outboundSchema = exports.JobInRepositories$outboundSchema = exports.Hyperparameters$outboundSchema = exports.JobInIntegrations$outboundSchema = void 0;
    exports.jobInIntegrationsToJSON = jobInIntegrationsToJSON;
    exports.hyperparametersToJSON = hyperparametersToJSON;
    exports.jobInRepositoriesToJSON = jobInRepositoriesToJSON;
    exports.jobInToJSON = jobInToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var classifiertargetin_js_1 = require_classifiertargetin();
    var classifiertrainingparametersin_js_1 = require_classifiertrainingparametersin();
    var completiontrainingparametersin_js_1 = require_completiontrainingparametersin();
    var finetuneablemodeltype_js_1 = require_finetuneablemodeltype();
    var githubrepositoryin_js_1 = require_githubrepositoryin();
    var trainingfile_js_1 = require_trainingfile();
    var wandbintegration_js_1 = require_wandbintegration();
    exports.JobInIntegrations$outboundSchema = wandbintegration_js_1.WandbIntegration$outboundSchema;
    function jobInIntegrationsToJSON(jobInIntegrations) {
      return JSON.stringify(exports.JobInIntegrations$outboundSchema.parse(jobInIntegrations));
    }
    exports.Hyperparameters$outboundSchema = z3.union([
      completiontrainingparametersin_js_1.CompletionTrainingParametersIn$outboundSchema,
      classifiertrainingparametersin_js_1.ClassifierTrainingParametersIn$outboundSchema
    ]);
    function hyperparametersToJSON(hyperparameters) {
      return JSON.stringify(exports.Hyperparameters$outboundSchema.parse(hyperparameters));
    }
    exports.JobInRepositories$outboundSchema = githubrepositoryin_js_1.GithubRepositoryIn$outboundSchema;
    function jobInRepositoriesToJSON(jobInRepositories) {
      return JSON.stringify(exports.JobInRepositories$outboundSchema.parse(jobInRepositories));
    }
    exports.JobIn$outboundSchema = z3.object({
      model: z3.string(),
      trainingFiles: z3.array(trainingfile_js_1.TrainingFile$outboundSchema).optional(),
      validationFiles: z3.nullable(z3.array(z3.string())).optional(),
      suffix: z3.nullable(z3.string()).optional(),
      integrations: z3.nullable(z3.array(wandbintegration_js_1.WandbIntegration$outboundSchema)).optional(),
      autoStart: z3.boolean().optional(),
      invalidSampleSkipPercentage: z3.number().default(0),
      jobType: z3.nullable(finetuneablemodeltype_js_1.FineTuneableModelType$outboundSchema).optional(),
      hyperparameters: z3.union([
        completiontrainingparametersin_js_1.CompletionTrainingParametersIn$outboundSchema,
        classifiertrainingparametersin_js_1.ClassifierTrainingParametersIn$outboundSchema
      ]),
      repositories: z3.nullable(z3.array(githubrepositoryin_js_1.GithubRepositoryIn$outboundSchema)).optional(),
      classifierTargets: z3.nullable(z3.array(classifiertargetin_js_1.ClassifierTargetIn$outboundSchema)).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        trainingFiles: "training_files",
        validationFiles: "validation_files",
        autoStart: "auto_start",
        invalidSampleSkipPercentage: "invalid_sample_skip_percentage",
        jobType: "job_type",
        classifierTargets: "classifier_targets"
      });
    });
    function jobInToJSON(jobIn) {
      return JSON.stringify(exports.JobIn$outboundSchema.parse(jobIn));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/jobsout.js
var require_jobsout = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/jobsout.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.JobsOut$inboundSchema = exports.JobsOutData$inboundSchema = void 0;
    exports.jobsOutDataFromJSON = jobsOutDataFromJSON;
    exports.jobsOutFromJSON = jobsOutFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    var classifierjobout_js_1 = require_classifierjobout();
    var completionjobout_js_1 = require_completionjobout();
    exports.JobsOutData$inboundSchema = z3.union([
      classifierjobout_js_1.ClassifierJobOut$inboundSchema.and(z3.object({ job_type: z3.literal("classifier") }).transform((v4) => ({
        jobType: v4.job_type
      }))),
      completionjobout_js_1.CompletionJobOut$inboundSchema.and(z3.object({ job_type: z3.literal("completion") }).transform((v4) => ({
        jobType: v4.job_type
      })))
    ]);
    function jobsOutDataFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.JobsOutData$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'JobsOutData' from JSON`);
    }
    exports.JobsOut$inboundSchema = z3.object({
      data: z3.array(z3.union([
        classifierjobout_js_1.ClassifierJobOut$inboundSchema.and(z3.object({ job_type: z3.literal("classifier") }).transform((v4) => ({
          jobType: v4.job_type
        }))),
        completionjobout_js_1.CompletionJobOut$inboundSchema.and(z3.object({ job_type: z3.literal("completion") }).transform((v4) => ({
          jobType: v4.job_type
        })))
      ])).optional(),
      object: z3.literal("list").default("list"),
      total: z3.number().int()
    });
    function jobsOutFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.JobsOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'JobsOut' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/legacyjobmetadataout.js
var require_legacyjobmetadataout = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/legacyjobmetadataout.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LegacyJobMetadataOut$inboundSchema = void 0;
    exports.legacyJobMetadataOutFromJSON = legacyJobMetadataOutFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    exports.LegacyJobMetadataOut$inboundSchema = z3.object({
      expected_duration_seconds: z3.nullable(z3.number().int()).optional(),
      cost: z3.nullable(z3.number()).optional(),
      cost_currency: z3.nullable(z3.string()).optional(),
      train_tokens_per_step: z3.nullable(z3.number().int()).optional(),
      train_tokens: z3.nullable(z3.number().int()).optional(),
      data_tokens: z3.nullable(z3.number().int()).optional(),
      estimated_start_time: z3.nullable(z3.number().int()).optional(),
      deprecated: z3.boolean().default(true),
      details: z3.string(),
      epochs: z3.nullable(z3.number()).optional(),
      training_steps: z3.nullable(z3.number().int()).optional(),
      object: z3.literal("job.metadata").default("job.metadata")
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "expected_duration_seconds": "expectedDurationSeconds",
        "cost_currency": "costCurrency",
        "train_tokens_per_step": "trainTokensPerStep",
        "train_tokens": "trainTokens",
        "data_tokens": "dataTokens",
        "estimated_start_time": "estimatedStartTime",
        "training_steps": "trainingSteps"
      });
    });
    function legacyJobMetadataOutFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.LegacyJobMetadataOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'LegacyJobMetadataOut' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/libraryin.js
var require_libraryin = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/libraryin.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LibraryIn$outboundSchema = void 0;
    exports.libraryInToJSON = libraryInToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    exports.LibraryIn$outboundSchema = z3.object({
      name: z3.string(),
      description: z3.nullable(z3.string()).optional(),
      chunkSize: z3.nullable(z3.number().int()).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        chunkSize: "chunk_size"
      });
    });
    function libraryInToJSON(libraryIn) {
      return JSON.stringify(exports.LibraryIn$outboundSchema.parse(libraryIn));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/libraryinupdate.js
var require_libraryinupdate = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/libraryinupdate.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LibraryInUpdate$outboundSchema = void 0;
    exports.libraryInUpdateToJSON = libraryInUpdateToJSON;
    var z3 = __importStar(require_v3());
    exports.LibraryInUpdate$outboundSchema = z3.object({
      name: z3.nullable(z3.string()).optional(),
      description: z3.nullable(z3.string()).optional()
    });
    function libraryInUpdateToJSON(libraryInUpdate) {
      return JSON.stringify(exports.LibraryInUpdate$outboundSchema.parse(libraryInUpdate));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/libraryout.js
var require_libraryout = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/libraryout.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LibraryOut$inboundSchema = void 0;
    exports.libraryOutFromJSON = libraryOutFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    exports.LibraryOut$inboundSchema = z3.object({
      id: z3.string(),
      name: z3.string(),
      created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)),
      updated_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)),
      owner_id: z3.nullable(z3.string()),
      owner_type: z3.string(),
      total_size: z3.number().int(),
      nb_documents: z3.number().int(),
      chunk_size: z3.nullable(z3.number().int()),
      emoji: z3.nullable(z3.string()).optional(),
      description: z3.nullable(z3.string()).optional(),
      generated_description: z3.nullable(z3.string()).optional(),
      explicit_user_members_count: z3.nullable(z3.number().int()).optional(),
      explicit_workspace_members_count: z3.nullable(z3.number().int()).optional(),
      org_sharing_role: z3.nullable(z3.string()).optional(),
      generated_name: z3.nullable(z3.string()).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "created_at": "createdAt",
        "updated_at": "updatedAt",
        "owner_id": "ownerId",
        "owner_type": "ownerType",
        "total_size": "totalSize",
        "nb_documents": "nbDocuments",
        "chunk_size": "chunkSize",
        "generated_description": "generatedDescription",
        "explicit_user_members_count": "explicitUserMembersCount",
        "explicit_workspace_members_count": "explicitWorkspaceMembersCount",
        "org_sharing_role": "orgSharingRole",
        "generated_name": "generatedName"
      });
    });
    function libraryOutFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.LibraryOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'LibraryOut' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/paginationinfo.js
var require_paginationinfo = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/paginationinfo.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.PaginationInfo$inboundSchema = void 0;
    exports.paginationInfoFromJSON = paginationInfoFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    exports.PaginationInfo$inboundSchema = z3.object({
      total_items: z3.number().int(),
      total_pages: z3.number().int(),
      current_page: z3.number().int(),
      page_size: z3.number().int(),
      has_more: z3.boolean()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "total_items": "totalItems",
        "total_pages": "totalPages",
        "current_page": "currentPage",
        "page_size": "pageSize",
        "has_more": "hasMore"
      });
    });
    function paginationInfoFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.PaginationInfo$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'PaginationInfo' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/listdocumentout.js
var require_listdocumentout = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/listdocumentout.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ListDocumentOut$inboundSchema = void 0;
    exports.listDocumentOutFromJSON = listDocumentOutFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    var documentout_js_1 = require_documentout();
    var paginationinfo_js_1 = require_paginationinfo();
    exports.ListDocumentOut$inboundSchema = z3.object({
      pagination: paginationinfo_js_1.PaginationInfo$inboundSchema,
      data: z3.array(documentout_js_1.DocumentOut$inboundSchema)
    });
    function listDocumentOutFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ListDocumentOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ListDocumentOut' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/listfilesout.js
var require_listfilesout = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/listfilesout.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ListFilesOut$inboundSchema = void 0;
    exports.listFilesOutFromJSON = listFilesOutFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    var fileschema_js_1 = require_fileschema();
    exports.ListFilesOut$inboundSchema = z3.object({
      data: z3.array(fileschema_js_1.FileSchema$inboundSchema),
      object: z3.string(),
      total: z3.nullable(z3.number().int()).optional()
    });
    function listFilesOutFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ListFilesOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ListFilesOut' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/listlibraryout.js
var require_listlibraryout = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/listlibraryout.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ListLibraryOut$inboundSchema = void 0;
    exports.listLibraryOutFromJSON = listLibraryOutFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    var libraryout_js_1 = require_libraryout();
    exports.ListLibraryOut$inboundSchema = z3.object({
      data: z3.array(libraryout_js_1.LibraryOut$inboundSchema)
    });
    function listLibraryOutFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ListLibraryOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ListLibraryOut' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/sharingout.js
var require_sharingout = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/sharingout.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SharingOut$inboundSchema = void 0;
    exports.sharingOutFromJSON = sharingOutFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    exports.SharingOut$inboundSchema = z3.object({
      library_id: z3.string(),
      user_id: z3.nullable(z3.string()).optional(),
      org_id: z3.string(),
      role: z3.string(),
      share_with_type: z3.string(),
      share_with_uuid: z3.nullable(z3.string())
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "library_id": "libraryId",
        "user_id": "userId",
        "org_id": "orgId",
        "share_with_type": "shareWithType",
        "share_with_uuid": "shareWithUuid"
      });
    });
    function sharingOutFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.SharingOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'SharingOut' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/listsharingout.js
var require_listsharingout = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/listsharingout.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ListSharingOut$inboundSchema = void 0;
    exports.listSharingOutFromJSON = listSharingOutFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    var sharingout_js_1 = require_sharingout();
    exports.ListSharingOut$inboundSchema = z3.object({
      data: z3.array(sharingout_js_1.SharingOut$inboundSchema)
    });
    function listSharingOutFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ListSharingOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ListSharingOut' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/modelconversation.js
var require_modelconversation = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/modelconversation.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ModelConversation$inboundSchema = exports.ModelConversationTools$inboundSchema = void 0;
    exports.modelConversationToolsFromJSON = modelConversationToolsFromJSON;
    exports.modelConversationFromJSON = modelConversationFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var codeinterpretertool_js_1 = require_codeinterpretertool();
    var completionargs_js_1 = require_completionargs();
    var documentlibrarytool_js_1 = require_documentlibrarytool();
    var functiontool_js_1 = require_functiontool();
    var imagegenerationtool_js_1 = require_imagegenerationtool();
    var websearchpremiumtool_js_1 = require_websearchpremiumtool();
    var websearchtool_js_1 = require_websearchtool();
    exports.ModelConversationTools$inboundSchema = z3.union([
      codeinterpretertool_js_1.CodeInterpreterTool$inboundSchema.and(z3.object({ type: z3.literal("code_interpreter") })),
      documentlibrarytool_js_1.DocumentLibraryTool$inboundSchema.and(z3.object({ type: z3.literal("document_library") })),
      functiontool_js_1.FunctionTool$inboundSchema.and(z3.object({ type: z3.literal("function") })),
      imagegenerationtool_js_1.ImageGenerationTool$inboundSchema.and(z3.object({ type: z3.literal("image_generation") })),
      websearchtool_js_1.WebSearchTool$inboundSchema.and(z3.object({ type: z3.literal("web_search") })),
      websearchpremiumtool_js_1.WebSearchPremiumTool$inboundSchema.and(z3.object({ type: z3.literal("web_search_premium") }))
    ]);
    function modelConversationToolsFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ModelConversationTools$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ModelConversationTools' from JSON`);
    }
    exports.ModelConversation$inboundSchema = z3.object({
      instructions: z3.nullable(z3.string()).optional(),
      tools: z3.array(z3.union([
        codeinterpretertool_js_1.CodeInterpreterTool$inboundSchema.and(z3.object({ type: z3.literal("code_interpreter") })),
        documentlibrarytool_js_1.DocumentLibraryTool$inboundSchema.and(z3.object({ type: z3.literal("document_library") })),
        functiontool_js_1.FunctionTool$inboundSchema.and(z3.object({ type: z3.literal("function") })),
        imagegenerationtool_js_1.ImageGenerationTool$inboundSchema.and(z3.object({ type: z3.literal("image_generation") })),
        websearchtool_js_1.WebSearchTool$inboundSchema.and(z3.object({ type: z3.literal("web_search") })),
        websearchpremiumtool_js_1.WebSearchPremiumTool$inboundSchema.and(z3.object({ type: z3.literal("web_search_premium") }))
      ])).optional(),
      completion_args: completionargs_js_1.CompletionArgs$inboundSchema.optional(),
      name: z3.nullable(z3.string()).optional(),
      description: z3.nullable(z3.string()).optional(),
      metadata: z3.nullable(z3.record(z3.any())).optional(),
      object: z3.literal("conversation").default("conversation"),
      id: z3.string(),
      created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)),
      updated_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)),
      model: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "completion_args": "completionArgs",
        "created_at": "createdAt",
        "updated_at": "updatedAt"
      });
    });
    function modelConversationFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ModelConversation$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ModelConversation' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/modellist.js
var require_modellist = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/modellist.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ModelList$inboundSchema = exports.Data$inboundSchema = void 0;
    exports.dataFromJSON = dataFromJSON;
    exports.modelListFromJSON = modelListFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    var basemodelcard_js_1 = require_basemodelcard();
    var ftmodelcard_js_1 = require_ftmodelcard();
    exports.Data$inboundSchema = z3.union([
      basemodelcard_js_1.BaseModelCard$inboundSchema.and(z3.object({ type: z3.literal("base") })),
      ftmodelcard_js_1.FTModelCard$inboundSchema.and(z3.object({ type: z3.literal("fine-tuned") }))
    ]);
    function dataFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.Data$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'Data' from JSON`);
    }
    exports.ModelList$inboundSchema = z3.object({
      object: z3.string().default("list"),
      data: z3.array(z3.union([
        basemodelcard_js_1.BaseModelCard$inboundSchema.and(z3.object({ type: z3.literal("base") })),
        ftmodelcard_js_1.FTModelCard$inboundSchema.and(z3.object({ type: z3.literal("fine-tuned") }))
      ])).optional()
    });
    function modelListFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ModelList$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ModelList' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/moderationobject.js
var require_moderationobject = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/moderationobject.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ModerationObject$inboundSchema = void 0;
    exports.moderationObjectFromJSON = moderationObjectFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    exports.ModerationObject$inboundSchema = z3.object({
      categories: z3.record(z3.boolean()).optional(),
      category_scores: z3.record(z3.number()).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "category_scores": "categoryScores"
      });
    });
    function moderationObjectFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ModerationObject$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ModerationObject' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/moderationresponse.js
var require_moderationresponse = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/moderationresponse.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ModerationResponse$inboundSchema = void 0;
    exports.moderationResponseFromJSON = moderationResponseFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    var moderationobject_js_1 = require_moderationobject();
    exports.ModerationResponse$inboundSchema = z3.object({
      id: z3.string(),
      model: z3.string(),
      results: z3.array(moderationobject_js_1.ModerationObject$inboundSchema)
    });
    function moderationResponseFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ModerationResponse$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ModerationResponse' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/ocrimageobject.js
var require_ocrimageobject = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/ocrimageobject.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OCRImageObject$inboundSchema = void 0;
    exports.ocrImageObjectFromJSON = ocrImageObjectFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    exports.OCRImageObject$inboundSchema = z3.object({
      id: z3.string(),
      top_left_x: z3.nullable(z3.number().int()),
      top_left_y: z3.nullable(z3.number().int()),
      bottom_right_x: z3.nullable(z3.number().int()),
      bottom_right_y: z3.nullable(z3.number().int()),
      image_base64: z3.nullable(z3.string()).optional(),
      image_annotation: z3.nullable(z3.string()).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "top_left_x": "topLeftX",
        "top_left_y": "topLeftY",
        "bottom_right_x": "bottomRightX",
        "bottom_right_y": "bottomRightY",
        "image_base64": "imageBase64",
        "image_annotation": "imageAnnotation"
      });
    });
    function ocrImageObjectFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.OCRImageObject$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'OCRImageObject' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/ocrpagedimensions.js
var require_ocrpagedimensions = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/ocrpagedimensions.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OCRPageDimensions$inboundSchema = void 0;
    exports.ocrPageDimensionsFromJSON = ocrPageDimensionsFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    exports.OCRPageDimensions$inboundSchema = z3.object({
      dpi: z3.number().int(),
      height: z3.number().int(),
      width: z3.number().int()
    });
    function ocrPageDimensionsFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.OCRPageDimensions$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'OCRPageDimensions' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/ocrtableobject.js
var require_ocrtableobject = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/ocrtableobject.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OCRTableObject$inboundSchema = exports.Format$inboundSchema = exports.Format = void 0;
    exports.ocrTableObjectFromJSON = ocrTableObjectFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    exports.Format = {
      Markdown: "markdown",
      Html: "html"
    };
    exports.Format$inboundSchema = z3.nativeEnum(exports.Format);
    exports.OCRTableObject$inboundSchema = z3.object({
      id: z3.string(),
      content: z3.string(),
      format: exports.Format$inboundSchema
    });
    function ocrTableObjectFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.OCRTableObject$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'OCRTableObject' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/ocrpageobject.js
var require_ocrpageobject = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/ocrpageobject.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OCRPageObject$inboundSchema = void 0;
    exports.ocrPageObjectFromJSON = ocrPageObjectFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    var ocrimageobject_js_1 = require_ocrimageobject();
    var ocrpagedimensions_js_1 = require_ocrpagedimensions();
    var ocrtableobject_js_1 = require_ocrtableobject();
    exports.OCRPageObject$inboundSchema = z3.object({
      index: z3.number().int(),
      markdown: z3.string(),
      images: z3.array(ocrimageobject_js_1.OCRImageObject$inboundSchema),
      tables: z3.array(ocrtableobject_js_1.OCRTableObject$inboundSchema).optional(),
      hyperlinks: z3.array(z3.string()).optional(),
      header: z3.nullable(z3.string()).optional(),
      footer: z3.nullable(z3.string()).optional(),
      dimensions: z3.nullable(ocrpagedimensions_js_1.OCRPageDimensions$inboundSchema)
    });
    function ocrPageObjectFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.OCRPageObject$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'OCRPageObject' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/ocrrequest.js
var require_ocrrequest = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/ocrrequest.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OCRRequest$outboundSchema = exports.TableFormat$outboundSchema = exports.Document$outboundSchema = exports.TableFormat = void 0;
    exports.documentToJSON = documentToJSON;
    exports.ocrRequestToJSON = ocrRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var documenturlchunk_js_1 = require_documenturlchunk();
    var filechunk_js_1 = require_filechunk();
    var imageurlchunk_js_1 = require_imageurlchunk();
    var responseformat_js_1 = require_responseformat();
    exports.TableFormat = {
      Markdown: "markdown",
      Html: "html"
    };
    exports.Document$outboundSchema = z3.union([
      filechunk_js_1.FileChunk$outboundSchema,
      documenturlchunk_js_1.DocumentURLChunk$outboundSchema,
      imageurlchunk_js_1.ImageURLChunk$outboundSchema
    ]);
    function documentToJSON(document2) {
      return JSON.stringify(exports.Document$outboundSchema.parse(document2));
    }
    exports.TableFormat$outboundSchema = z3.nativeEnum(exports.TableFormat);
    exports.OCRRequest$outboundSchema = z3.object({
      model: z3.nullable(z3.string()),
      id: z3.string().optional(),
      document: z3.union([
        filechunk_js_1.FileChunk$outboundSchema,
        documenturlchunk_js_1.DocumentURLChunk$outboundSchema,
        imageurlchunk_js_1.ImageURLChunk$outboundSchema
      ]),
      pages: z3.nullable(z3.array(z3.number().int())).optional(),
      includeImageBase64: z3.nullable(z3.boolean()).optional(),
      imageLimit: z3.nullable(z3.number().int()).optional(),
      imageMinSize: z3.nullable(z3.number().int()).optional(),
      bboxAnnotationFormat: z3.nullable(responseformat_js_1.ResponseFormat$outboundSchema).optional(),
      documentAnnotationFormat: z3.nullable(responseformat_js_1.ResponseFormat$outboundSchema).optional(),
      documentAnnotationPrompt: z3.nullable(z3.string()).optional(),
      tableFormat: z3.nullable(exports.TableFormat$outboundSchema).optional(),
      extractHeader: z3.boolean().optional(),
      extractFooter: z3.boolean().optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        includeImageBase64: "include_image_base64",
        imageLimit: "image_limit",
        imageMinSize: "image_min_size",
        bboxAnnotationFormat: "bbox_annotation_format",
        documentAnnotationFormat: "document_annotation_format",
        documentAnnotationPrompt: "document_annotation_prompt",
        tableFormat: "table_format",
        extractHeader: "extract_header",
        extractFooter: "extract_footer"
      });
    });
    function ocrRequestToJSON(ocrRequest) {
      return JSON.stringify(exports.OCRRequest$outboundSchema.parse(ocrRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/ocrusageinfo.js
var require_ocrusageinfo = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/ocrusageinfo.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OCRUsageInfo$inboundSchema = void 0;
    exports.ocrUsageInfoFromJSON = ocrUsageInfoFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    exports.OCRUsageInfo$inboundSchema = z3.object({
      pages_processed: z3.number().int(),
      doc_size_bytes: z3.nullable(z3.number().int()).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "pages_processed": "pagesProcessed",
        "doc_size_bytes": "docSizeBytes"
      });
    });
    function ocrUsageInfoFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.OCRUsageInfo$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'OCRUsageInfo' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/ocrresponse.js
var require_ocrresponse = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/ocrresponse.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OCRResponse$inboundSchema = void 0;
    exports.ocrResponseFromJSON = ocrResponseFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var ocrpageobject_js_1 = require_ocrpageobject();
    var ocrusageinfo_js_1 = require_ocrusageinfo();
    exports.OCRResponse$inboundSchema = z3.object({
      pages: z3.array(ocrpageobject_js_1.OCRPageObject$inboundSchema),
      model: z3.string(),
      document_annotation: z3.nullable(z3.string()).optional(),
      usage_info: ocrusageinfo_js_1.OCRUsageInfo$inboundSchema
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "document_annotation": "documentAnnotation",
        "usage_info": "usageInfo"
      });
    });
    function ocrResponseFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.OCRResponse$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'OCRResponse' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/processingstatusout.js
var require_processingstatusout = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/processingstatusout.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ProcessingStatusOut$inboundSchema = void 0;
    exports.processingStatusOutFromJSON = processingStatusOutFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    exports.ProcessingStatusOut$inboundSchema = z3.object({
      document_id: z3.string(),
      processing_status: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "document_id": "documentId",
        "processing_status": "processingStatus"
      });
    });
    function processingStatusOutFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ProcessingStatusOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ProcessingStatusOut' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptionerrordetail.js
var require_realtimetranscriptionerrordetail = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptionerrordetail.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RealtimeTranscriptionErrorDetail$outboundSchema = exports.RealtimeTranscriptionErrorDetail$inboundSchema = exports.Message$outboundSchema = exports.Message$inboundSchema = void 0;
    exports.messageToJSON = messageToJSON;
    exports.messageFromJSON = messageFromJSON;
    exports.realtimeTranscriptionErrorDetailToJSON = realtimeTranscriptionErrorDetailToJSON;
    exports.realtimeTranscriptionErrorDetailFromJSON = realtimeTranscriptionErrorDetailFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    exports.Message$inboundSchema = z3.union([z3.string(), z3.record(z3.any())]);
    exports.Message$outboundSchema = z3.union([z3.string(), z3.record(z3.any())]);
    function messageToJSON(message) {
      return JSON.stringify(exports.Message$outboundSchema.parse(message));
    }
    function messageFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.Message$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'Message' from JSON`);
    }
    exports.RealtimeTranscriptionErrorDetail$inboundSchema = z3.object({
      message: z3.union([z3.string(), z3.record(z3.any())]),
      code: z3.number().int()
    });
    exports.RealtimeTranscriptionErrorDetail$outboundSchema = z3.object({
      message: z3.union([z3.string(), z3.record(z3.any())]),
      code: z3.number().int()
    });
    function realtimeTranscriptionErrorDetailToJSON(realtimeTranscriptionErrorDetail) {
      return JSON.stringify(exports.RealtimeTranscriptionErrorDetail$outboundSchema.parse(realtimeTranscriptionErrorDetail));
    }
    function realtimeTranscriptionErrorDetailFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.RealtimeTranscriptionErrorDetail$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'RealtimeTranscriptionErrorDetail' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptionerror.js
var require_realtimetranscriptionerror = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptionerror.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RealtimeTranscriptionError$outboundSchema = exports.RealtimeTranscriptionError$inboundSchema = void 0;
    exports.realtimeTranscriptionErrorToJSON = realtimeTranscriptionErrorToJSON;
    exports.realtimeTranscriptionErrorFromJSON = realtimeTranscriptionErrorFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    var realtimetranscriptionerrordetail_js_1 = require_realtimetranscriptionerrordetail();
    exports.RealtimeTranscriptionError$inboundSchema = z3.object({
      type: z3.literal("error").default("error"),
      error: realtimetranscriptionerrordetail_js_1.RealtimeTranscriptionErrorDetail$inboundSchema
    });
    exports.RealtimeTranscriptionError$outboundSchema = z3.object({
      type: z3.literal("error").default("error"),
      error: realtimetranscriptionerrordetail_js_1.RealtimeTranscriptionErrorDetail$outboundSchema
    });
    function realtimeTranscriptionErrorToJSON(realtimeTranscriptionError) {
      return JSON.stringify(exports.RealtimeTranscriptionError$outboundSchema.parse(realtimeTranscriptionError));
    }
    function realtimeTranscriptionErrorFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.RealtimeTranscriptionError$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'RealtimeTranscriptionError' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptioninputaudioappend.js
var require_realtimetranscriptioninputaudioappend = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptioninputaudioappend.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RealtimeTranscriptionInputAudioAppend$outboundSchema = exports.RealtimeTranscriptionInputAudioAppend$inboundSchema = void 0;
    exports.realtimeTranscriptionInputAudioAppendToJSON = realtimeTranscriptionInputAudioAppendToJSON;
    exports.realtimeTranscriptionInputAudioAppendFromJSON = realtimeTranscriptionInputAudioAppendFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    exports.RealtimeTranscriptionInputAudioAppend$inboundSchema = z3.object({
      type: z3.literal("input_audio.append").default("input_audio.append"),
      audio: z3.string()
    });
    exports.RealtimeTranscriptionInputAudioAppend$outboundSchema = z3.object({
      type: z3.literal("input_audio.append").default("input_audio.append"),
      audio: z3.string()
    });
    function realtimeTranscriptionInputAudioAppendToJSON(realtimeTranscriptionInputAudioAppend) {
      return JSON.stringify(exports.RealtimeTranscriptionInputAudioAppend$outboundSchema.parse(realtimeTranscriptionInputAudioAppend));
    }
    function realtimeTranscriptionInputAudioAppendFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.RealtimeTranscriptionInputAudioAppend$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'RealtimeTranscriptionInputAudioAppend' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptioninputaudioend.js
var require_realtimetranscriptioninputaudioend = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptioninputaudioend.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RealtimeTranscriptionInputAudioEnd$outboundSchema = exports.RealtimeTranscriptionInputAudioEnd$inboundSchema = void 0;
    exports.realtimeTranscriptionInputAudioEndToJSON = realtimeTranscriptionInputAudioEndToJSON;
    exports.realtimeTranscriptionInputAudioEndFromJSON = realtimeTranscriptionInputAudioEndFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    exports.RealtimeTranscriptionInputAudioEnd$inboundSchema = z3.object({
      type: z3.literal("input_audio.end").default("input_audio.end")
    });
    exports.RealtimeTranscriptionInputAudioEnd$outboundSchema = z3.object({
      type: z3.literal("input_audio.end").default("input_audio.end")
    });
    function realtimeTranscriptionInputAudioEndToJSON(realtimeTranscriptionInputAudioEnd) {
      return JSON.stringify(exports.RealtimeTranscriptionInputAudioEnd$outboundSchema.parse(realtimeTranscriptionInputAudioEnd));
    }
    function realtimeTranscriptionInputAudioEndFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.RealtimeTranscriptionInputAudioEnd$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'RealtimeTranscriptionInputAudioEnd' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptioninputaudioflush.js
var require_realtimetranscriptioninputaudioflush = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptioninputaudioflush.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RealtimeTranscriptionInputAudioFlush$outboundSchema = exports.RealtimeTranscriptionInputAudioFlush$inboundSchema = void 0;
    exports.realtimeTranscriptionInputAudioFlushToJSON = realtimeTranscriptionInputAudioFlushToJSON;
    exports.realtimeTranscriptionInputAudioFlushFromJSON = realtimeTranscriptionInputAudioFlushFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    exports.RealtimeTranscriptionInputAudioFlush$inboundSchema = z3.object({
      type: z3.literal("input_audio.flush").default("input_audio.flush")
    });
    exports.RealtimeTranscriptionInputAudioFlush$outboundSchema = z3.object({
      type: z3.literal("input_audio.flush").default("input_audio.flush")
    });
    function realtimeTranscriptionInputAudioFlushToJSON(realtimeTranscriptionInputAudioFlush) {
      return JSON.stringify(exports.RealtimeTranscriptionInputAudioFlush$outboundSchema.parse(realtimeTranscriptionInputAudioFlush));
    }
    function realtimeTranscriptionInputAudioFlushFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.RealtimeTranscriptionInputAudioFlush$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'RealtimeTranscriptionInputAudioFlush' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptionsession.js
var require_realtimetranscriptionsession = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptionsession.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RealtimeTranscriptionSession$outboundSchema = exports.RealtimeTranscriptionSession$inboundSchema = void 0;
    exports.realtimeTranscriptionSessionToJSON = realtimeTranscriptionSessionToJSON;
    exports.realtimeTranscriptionSessionFromJSON = realtimeTranscriptionSessionFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var audioformat_js_1 = require_audioformat();
    exports.RealtimeTranscriptionSession$inboundSchema = z3.object({
      request_id: z3.string(),
      model: z3.string(),
      audio_format: audioformat_js_1.AudioFormat$inboundSchema,
      target_streaming_delay_ms: z3.nullable(z3.number().int()).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "request_id": "requestId",
        "audio_format": "audioFormat",
        "target_streaming_delay_ms": "targetStreamingDelayMs"
      });
    });
    exports.RealtimeTranscriptionSession$outboundSchema = z3.object({
      requestId: z3.string(),
      model: z3.string(),
      audioFormat: audioformat_js_1.AudioFormat$outboundSchema,
      targetStreamingDelayMs: z3.nullable(z3.number().int()).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        requestId: "request_id",
        audioFormat: "audio_format",
        targetStreamingDelayMs: "target_streaming_delay_ms"
      });
    });
    function realtimeTranscriptionSessionToJSON(realtimeTranscriptionSession) {
      return JSON.stringify(exports.RealtimeTranscriptionSession$outboundSchema.parse(realtimeTranscriptionSession));
    }
    function realtimeTranscriptionSessionFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.RealtimeTranscriptionSession$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'RealtimeTranscriptionSession' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptionsessioncreated.js
var require_realtimetranscriptionsessioncreated = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptionsessioncreated.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RealtimeTranscriptionSessionCreated$outboundSchema = exports.RealtimeTranscriptionSessionCreated$inboundSchema = void 0;
    exports.realtimeTranscriptionSessionCreatedToJSON = realtimeTranscriptionSessionCreatedToJSON;
    exports.realtimeTranscriptionSessionCreatedFromJSON = realtimeTranscriptionSessionCreatedFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    var realtimetranscriptionsession_js_1 = require_realtimetranscriptionsession();
    exports.RealtimeTranscriptionSessionCreated$inboundSchema = z3.object({
      type: z3.literal("session.created").default("session.created"),
      session: realtimetranscriptionsession_js_1.RealtimeTranscriptionSession$inboundSchema
    });
    exports.RealtimeTranscriptionSessionCreated$outboundSchema = z3.object({
      type: z3.literal("session.created").default("session.created"),
      session: realtimetranscriptionsession_js_1.RealtimeTranscriptionSession$outboundSchema
    });
    function realtimeTranscriptionSessionCreatedToJSON(realtimeTranscriptionSessionCreated) {
      return JSON.stringify(exports.RealtimeTranscriptionSessionCreated$outboundSchema.parse(realtimeTranscriptionSessionCreated));
    }
    function realtimeTranscriptionSessionCreatedFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.RealtimeTranscriptionSessionCreated$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'RealtimeTranscriptionSessionCreated' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptionsessionupdated.js
var require_realtimetranscriptionsessionupdated = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptionsessionupdated.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RealtimeTranscriptionSessionUpdated$outboundSchema = exports.RealtimeTranscriptionSessionUpdated$inboundSchema = void 0;
    exports.realtimeTranscriptionSessionUpdatedToJSON = realtimeTranscriptionSessionUpdatedToJSON;
    exports.realtimeTranscriptionSessionUpdatedFromJSON = realtimeTranscriptionSessionUpdatedFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    var realtimetranscriptionsession_js_1 = require_realtimetranscriptionsession();
    exports.RealtimeTranscriptionSessionUpdated$inboundSchema = z3.object({
      type: z3.literal("session.updated").default("session.updated"),
      session: realtimetranscriptionsession_js_1.RealtimeTranscriptionSession$inboundSchema
    });
    exports.RealtimeTranscriptionSessionUpdated$outboundSchema = z3.object({
      type: z3.literal("session.updated").default("session.updated"),
      session: realtimetranscriptionsession_js_1.RealtimeTranscriptionSession$outboundSchema
    });
    function realtimeTranscriptionSessionUpdatedToJSON(realtimeTranscriptionSessionUpdated) {
      return JSON.stringify(exports.RealtimeTranscriptionSessionUpdated$outboundSchema.parse(realtimeTranscriptionSessionUpdated));
    }
    function realtimeTranscriptionSessionUpdatedFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.RealtimeTranscriptionSessionUpdated$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'RealtimeTranscriptionSessionUpdated' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptionsessionupdatepayload.js
var require_realtimetranscriptionsessionupdatepayload = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptionsessionupdatepayload.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RealtimeTranscriptionSessionUpdatePayload$outboundSchema = exports.RealtimeTranscriptionSessionUpdatePayload$inboundSchema = void 0;
    exports.realtimeTranscriptionSessionUpdatePayloadToJSON = realtimeTranscriptionSessionUpdatePayloadToJSON;
    exports.realtimeTranscriptionSessionUpdatePayloadFromJSON = realtimeTranscriptionSessionUpdatePayloadFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var audioformat_js_1 = require_audioformat();
    exports.RealtimeTranscriptionSessionUpdatePayload$inboundSchema = z3.object({
      audio_format: z3.nullable(audioformat_js_1.AudioFormat$inboundSchema).optional(),
      target_streaming_delay_ms: z3.nullable(z3.number().int()).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "audio_format": "audioFormat",
        "target_streaming_delay_ms": "targetStreamingDelayMs"
      });
    });
    exports.RealtimeTranscriptionSessionUpdatePayload$outboundSchema = z3.object({
      audioFormat: z3.nullable(audioformat_js_1.AudioFormat$outboundSchema).optional(),
      targetStreamingDelayMs: z3.nullable(z3.number().int()).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        audioFormat: "audio_format",
        targetStreamingDelayMs: "target_streaming_delay_ms"
      });
    });
    function realtimeTranscriptionSessionUpdatePayloadToJSON(realtimeTranscriptionSessionUpdatePayload) {
      return JSON.stringify(exports.RealtimeTranscriptionSessionUpdatePayload$outboundSchema.parse(realtimeTranscriptionSessionUpdatePayload));
    }
    function realtimeTranscriptionSessionUpdatePayloadFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.RealtimeTranscriptionSessionUpdatePayload$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'RealtimeTranscriptionSessionUpdatePayload' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptionsessionupdatemessage.js
var require_realtimetranscriptionsessionupdatemessage = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptionsessionupdatemessage.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RealtimeTranscriptionSessionUpdateMessage$outboundSchema = exports.RealtimeTranscriptionSessionUpdateMessage$inboundSchema = void 0;
    exports.realtimeTranscriptionSessionUpdateMessageToJSON = realtimeTranscriptionSessionUpdateMessageToJSON;
    exports.realtimeTranscriptionSessionUpdateMessageFromJSON = realtimeTranscriptionSessionUpdateMessageFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    var realtimetranscriptionsessionupdatepayload_js_1 = require_realtimetranscriptionsessionupdatepayload();
    exports.RealtimeTranscriptionSessionUpdateMessage$inboundSchema = z3.object({
      type: z3.literal("session.update").default("session.update"),
      session: realtimetranscriptionsessionupdatepayload_js_1.RealtimeTranscriptionSessionUpdatePayload$inboundSchema
    });
    exports.RealtimeTranscriptionSessionUpdateMessage$outboundSchema = z3.object({
      type: z3.literal("session.update").default("session.update"),
      session: realtimetranscriptionsessionupdatepayload_js_1.RealtimeTranscriptionSessionUpdatePayload$outboundSchema
    });
    function realtimeTranscriptionSessionUpdateMessageToJSON(realtimeTranscriptionSessionUpdateMessage) {
      return JSON.stringify(exports.RealtimeTranscriptionSessionUpdateMessage$outboundSchema.parse(realtimeTranscriptionSessionUpdateMessage));
    }
    function realtimeTranscriptionSessionUpdateMessageFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.RealtimeTranscriptionSessionUpdateMessage$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'RealtimeTranscriptionSessionUpdateMessage' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/requestsource.js
var require_requestsource = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/requestsource.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RequestSource$outboundSchema = exports.RequestSource = void 0;
    var z3 = __importStar(require_v3());
    exports.RequestSource = {
      Api: "api",
      Playground: "playground",
      AgentBuilderV1: "agent_builder_v1"
    };
    exports.RequestSource$outboundSchema = z3.nativeEnum(exports.RequestSource);
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/retrievefileout.js
var require_retrievefileout = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/retrievefileout.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RetrieveFileOut$inboundSchema = void 0;
    exports.retrieveFileOutFromJSON = retrieveFileOutFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var filepurpose_js_1 = require_filepurpose();
    var sampletype_js_1 = require_sampletype();
    var source_js_1 = require_source();
    exports.RetrieveFileOut$inboundSchema = z3.object({
      id: z3.string(),
      object: z3.string(),
      bytes: z3.number().int(),
      created_at: z3.number().int(),
      filename: z3.string(),
      purpose: filepurpose_js_1.FilePurpose$inboundSchema,
      sample_type: sampletype_js_1.SampleType$inboundSchema,
      num_lines: z3.nullable(z3.number().int()).optional(),
      mimetype: z3.nullable(z3.string()).optional(),
      source: source_js_1.Source$inboundSchema,
      signature: z3.nullable(z3.string()).optional(),
      deleted: z3.boolean()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "bytes": "sizeBytes",
        "created_at": "createdAt",
        "sample_type": "sampleType",
        "num_lines": "numLines"
      });
    });
    function retrieveFileOutFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.RetrieveFileOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'RetrieveFileOut' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/security.js
var require_security2 = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/security.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Security$outboundSchema = void 0;
    exports.securityToJSON = securityToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    exports.Security$outboundSchema = z3.object({
      apiKey: z3.string().optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        apiKey: "ApiKey"
      });
    });
    function securityToJSON(security) {
      return JSON.stringify(exports.Security$outboundSchema.parse(security));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/shareenum.js
var require_shareenum = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/shareenum.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ShareEnum$outboundSchema = exports.ShareEnum = void 0;
    var openEnums = __importStar(require_enums());
    exports.ShareEnum = {
      Viewer: "Viewer",
      Editor: "Editor"
    };
    exports.ShareEnum$outboundSchema = openEnums.outboundSchema(exports.ShareEnum);
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/sharingdelete.js
var require_sharingdelete = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/sharingdelete.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SharingDelete$outboundSchema = void 0;
    exports.sharingDeleteToJSON = sharingDeleteToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var entitytype_js_1 = require_entitytype();
    exports.SharingDelete$outboundSchema = z3.object({
      orgId: z3.nullable(z3.string()).optional(),
      shareWithUuid: z3.string(),
      shareWithType: entitytype_js_1.EntityType$outboundSchema
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        orgId: "org_id",
        shareWithUuid: "share_with_uuid",
        shareWithType: "share_with_type"
      });
    });
    function sharingDeleteToJSON(sharingDelete) {
      return JSON.stringify(exports.SharingDelete$outboundSchema.parse(sharingDelete));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/sharingin.js
var require_sharingin = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/sharingin.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SharingIn$outboundSchema = void 0;
    exports.sharingInToJSON = sharingInToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var entitytype_js_1 = require_entitytype();
    var shareenum_js_1 = require_shareenum();
    exports.SharingIn$outboundSchema = z3.object({
      orgId: z3.nullable(z3.string()).optional(),
      level: shareenum_js_1.ShareEnum$outboundSchema,
      shareWithUuid: z3.string(),
      shareWithType: entitytype_js_1.EntityType$outboundSchema
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        orgId: "org_id",
        shareWithUuid: "share_with_uuid",
        shareWithType: "share_with_type"
      });
    });
    function sharingInToJSON(sharingIn) {
      return JSON.stringify(exports.SharingIn$outboundSchema.parse(sharingIn));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionsegmentchunk.js
var require_transcriptionsegmentchunk = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionsegmentchunk.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TranscriptionSegmentChunk$outboundSchema = exports.TranscriptionSegmentChunk$inboundSchema = void 0;
    exports.transcriptionSegmentChunkToJSON = transcriptionSegmentChunkToJSON;
    exports.transcriptionSegmentChunkFromJSON = transcriptionSegmentChunkFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    exports.TranscriptionSegmentChunk$inboundSchema = (0, schemas_js_1.collectExtraKeys)(z3.object({
      type: z3.literal("transcription_segment").default("transcription_segment"),
      text: z3.string(),
      start: z3.number(),
      end: z3.number(),
      score: z3.nullable(z3.number()).optional(),
      speaker_id: z3.nullable(z3.string()).optional()
    }).catchall(z3.any()), "additionalProperties", true).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "speaker_id": "speakerId"
      });
    });
    exports.TranscriptionSegmentChunk$outboundSchema = z3.object({
      type: z3.literal("transcription_segment").default("transcription_segment"),
      text: z3.string(),
      start: z3.number(),
      end: z3.number(),
      score: z3.nullable(z3.number()).optional(),
      speakerId: z3.nullable(z3.string()).optional(),
      additionalProperties: z3.record(z3.any()).optional()
    }).transform((v4) => {
      return {
        ...v4.additionalProperties,
        ...(0, primitives_js_1.remap)(v4, {
          speakerId: "speaker_id",
          additionalProperties: null
        })
      };
    });
    function transcriptionSegmentChunkToJSON(transcriptionSegmentChunk) {
      return JSON.stringify(exports.TranscriptionSegmentChunk$outboundSchema.parse(transcriptionSegmentChunk));
    }
    function transcriptionSegmentChunkFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.TranscriptionSegmentChunk$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'TranscriptionSegmentChunk' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionresponse.js
var require_transcriptionresponse = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionresponse.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TranscriptionResponse$inboundSchema = void 0;
    exports.transcriptionResponseFromJSON = transcriptionResponseFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    var transcriptionsegmentchunk_js_1 = require_transcriptionsegmentchunk();
    var usageinfo_js_1 = require_usageinfo();
    exports.TranscriptionResponse$inboundSchema = (0, schemas_js_1.collectExtraKeys)(z3.object({
      model: z3.string(),
      text: z3.string(),
      segments: z3.array(transcriptionsegmentchunk_js_1.TranscriptionSegmentChunk$inboundSchema).optional(),
      usage: usageinfo_js_1.UsageInfo$inboundSchema,
      language: z3.nullable(z3.string())
    }).catchall(z3.any()), "additionalProperties", true);
    function transcriptionResponseFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.TranscriptionResponse$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'TranscriptionResponse' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionstreamdone.js
var require_transcriptionstreamdone = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionstreamdone.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TranscriptionStreamDone$outboundSchema = exports.TranscriptionStreamDone$inboundSchema = void 0;
    exports.transcriptionStreamDoneToJSON = transcriptionStreamDoneToJSON;
    exports.transcriptionStreamDoneFromJSON = transcriptionStreamDoneFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var transcriptionsegmentchunk_js_1 = require_transcriptionsegmentchunk();
    var usageinfo_js_1 = require_usageinfo();
    exports.TranscriptionStreamDone$inboundSchema = (0, schemas_js_1.collectExtraKeys)(z3.object({
      model: z3.string(),
      text: z3.string(),
      segments: z3.array(transcriptionsegmentchunk_js_1.TranscriptionSegmentChunk$inboundSchema).optional(),
      usage: usageinfo_js_1.UsageInfo$inboundSchema,
      type: z3.literal("transcription.done").default("transcription.done"),
      language: z3.nullable(z3.string())
    }).catchall(z3.any()), "additionalProperties", true);
    exports.TranscriptionStreamDone$outboundSchema = z3.object({
      model: z3.string(),
      text: z3.string(),
      segments: z3.array(transcriptionsegmentchunk_js_1.TranscriptionSegmentChunk$outboundSchema).optional(),
      usage: usageinfo_js_1.UsageInfo$outboundSchema,
      type: z3.literal("transcription.done").default("transcription.done"),
      language: z3.nullable(z3.string()),
      additionalProperties: z3.record(z3.any()).optional()
    }).transform((v4) => {
      return {
        ...v4.additionalProperties,
        ...(0, primitives_js_1.remap)(v4, {
          additionalProperties: null
        })
      };
    });
    function transcriptionStreamDoneToJSON(transcriptionStreamDone) {
      return JSON.stringify(exports.TranscriptionStreamDone$outboundSchema.parse(transcriptionStreamDone));
    }
    function transcriptionStreamDoneFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.TranscriptionStreamDone$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'TranscriptionStreamDone' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionstreameventtypes.js
var require_transcriptionstreameventtypes = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionstreameventtypes.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TranscriptionStreamEventTypes$inboundSchema = exports.TranscriptionStreamEventTypes = void 0;
    var z3 = __importStar(require_v3());
    exports.TranscriptionStreamEventTypes = {
      TranscriptionLanguage: "transcription.language",
      TranscriptionSegment: "transcription.segment",
      TranscriptionTextDelta: "transcription.text.delta",
      TranscriptionDone: "transcription.done"
    };
    exports.TranscriptionStreamEventTypes$inboundSchema = z3.nativeEnum(exports.TranscriptionStreamEventTypes);
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionstreamlanguage.js
var require_transcriptionstreamlanguage = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionstreamlanguage.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TranscriptionStreamLanguage$outboundSchema = exports.TranscriptionStreamLanguage$inboundSchema = void 0;
    exports.transcriptionStreamLanguageToJSON = transcriptionStreamLanguageToJSON;
    exports.transcriptionStreamLanguageFromJSON = transcriptionStreamLanguageFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    exports.TranscriptionStreamLanguage$inboundSchema = (0, schemas_js_1.collectExtraKeys)(z3.object({
      type: z3.literal("transcription.language").default("transcription.language"),
      audio_language: z3.string()
    }).catchall(z3.any()), "additionalProperties", true).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "audio_language": "audioLanguage"
      });
    });
    exports.TranscriptionStreamLanguage$outboundSchema = z3.object({
      type: z3.literal("transcription.language").default("transcription.language"),
      audioLanguage: z3.string(),
      additionalProperties: z3.record(z3.any()).optional()
    }).transform((v4) => {
      return {
        ...v4.additionalProperties,
        ...(0, primitives_js_1.remap)(v4, {
          audioLanguage: "audio_language",
          additionalProperties: null
        })
      };
    });
    function transcriptionStreamLanguageToJSON(transcriptionStreamLanguage) {
      return JSON.stringify(exports.TranscriptionStreamLanguage$outboundSchema.parse(transcriptionStreamLanguage));
    }
    function transcriptionStreamLanguageFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.TranscriptionStreamLanguage$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'TranscriptionStreamLanguage' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionstreamsegmentdelta.js
var require_transcriptionstreamsegmentdelta = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionstreamsegmentdelta.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TranscriptionStreamSegmentDelta$inboundSchema = void 0;
    exports.transcriptionStreamSegmentDeltaFromJSON = transcriptionStreamSegmentDeltaFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    exports.TranscriptionStreamSegmentDelta$inboundSchema = (0, schemas_js_1.collectExtraKeys)(z3.object({
      type: z3.literal("transcription.segment").default("transcription.segment"),
      text: z3.string(),
      start: z3.number(),
      end: z3.number(),
      speaker_id: z3.nullable(z3.string()).optional()
    }).catchall(z3.any()), "additionalProperties", true).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "speaker_id": "speakerId"
      });
    });
    function transcriptionStreamSegmentDeltaFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.TranscriptionStreamSegmentDelta$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'TranscriptionStreamSegmentDelta' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionstreamtextdelta.js
var require_transcriptionstreamtextdelta = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionstreamtextdelta.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TranscriptionStreamTextDelta$outboundSchema = exports.TranscriptionStreamTextDelta$inboundSchema = void 0;
    exports.transcriptionStreamTextDeltaToJSON = transcriptionStreamTextDeltaToJSON;
    exports.transcriptionStreamTextDeltaFromJSON = transcriptionStreamTextDeltaFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    exports.TranscriptionStreamTextDelta$inboundSchema = (0, schemas_js_1.collectExtraKeys)(z3.object({
      type: z3.literal("transcription.text.delta").default("transcription.text.delta"),
      text: z3.string()
    }).catchall(z3.any()), "additionalProperties", true);
    exports.TranscriptionStreamTextDelta$outboundSchema = z3.object({
      type: z3.literal("transcription.text.delta").default("transcription.text.delta"),
      text: z3.string(),
      additionalProperties: z3.record(z3.any()).optional()
    }).transform((v4) => {
      return {
        ...v4.additionalProperties,
        ...(0, primitives_js_1.remap)(v4, {
          additionalProperties: null
        })
      };
    });
    function transcriptionStreamTextDeltaToJSON(transcriptionStreamTextDelta) {
      return JSON.stringify(exports.TranscriptionStreamTextDelta$outboundSchema.parse(transcriptionStreamTextDelta));
    }
    function transcriptionStreamTextDeltaFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.TranscriptionStreamTextDelta$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'TranscriptionStreamTextDelta' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionstreamevents.js
var require_transcriptionstreamevents = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionstreamevents.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TranscriptionStreamEvents$inboundSchema = exports.TranscriptionStreamEventsData$inboundSchema = void 0;
    exports.transcriptionStreamEventsDataFromJSON = transcriptionStreamEventsDataFromJSON;
    exports.transcriptionStreamEventsFromJSON = transcriptionStreamEventsFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    var transcriptionstreamdone_js_1 = require_transcriptionstreamdone();
    var transcriptionstreameventtypes_js_1 = require_transcriptionstreameventtypes();
    var transcriptionstreamlanguage_js_1 = require_transcriptionstreamlanguage();
    var transcriptionstreamsegmentdelta_js_1 = require_transcriptionstreamsegmentdelta();
    var transcriptionstreamtextdelta_js_1 = require_transcriptionstreamtextdelta();
    exports.TranscriptionStreamEventsData$inboundSchema = z3.union([
      transcriptionstreamdone_js_1.TranscriptionStreamDone$inboundSchema.and(z3.object({ type: z3.literal("transcription.done") })),
      transcriptionstreamlanguage_js_1.TranscriptionStreamLanguage$inboundSchema.and(z3.object({ type: z3.literal("transcription.language") })),
      transcriptionstreamsegmentdelta_js_1.TranscriptionStreamSegmentDelta$inboundSchema.and(z3.object({ type: z3.literal("transcription.segment") })),
      transcriptionstreamtextdelta_js_1.TranscriptionStreamTextDelta$inboundSchema.and(z3.object({ type: z3.literal("transcription.text.delta") }))
    ]);
    function transcriptionStreamEventsDataFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.TranscriptionStreamEventsData$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'TranscriptionStreamEventsData' from JSON`);
    }
    exports.TranscriptionStreamEvents$inboundSchema = z3.object({
      event: transcriptionstreameventtypes_js_1.TranscriptionStreamEventTypes$inboundSchema,
      data: z3.string().transform((v4, ctx) => {
        try {
          return JSON.parse(v4);
        } catch (err) {
          ctx.addIssue({ code: "custom", message: `malformed json: ${err}` });
          return z3.NEVER;
        }
      }).pipe(z3.union([
        transcriptionstreamdone_js_1.TranscriptionStreamDone$inboundSchema.and(z3.object({ type: z3.literal("transcription.done") })),
        transcriptionstreamlanguage_js_1.TranscriptionStreamLanguage$inboundSchema.and(z3.object({ type: z3.literal("transcription.language") })),
        transcriptionstreamsegmentdelta_js_1.TranscriptionStreamSegmentDelta$inboundSchema.and(z3.object({ type: z3.literal("transcription.segment") })),
        transcriptionstreamtextdelta_js_1.TranscriptionStreamTextDelta$inboundSchema.and(z3.object({ type: z3.literal("transcription.text.delta") }))
      ]))
    });
    function transcriptionStreamEventsFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.TranscriptionStreamEvents$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'TranscriptionStreamEvents' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/unarchiveftmodelout.js
var require_unarchiveftmodelout = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/unarchiveftmodelout.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.UnarchiveFTModelOut$inboundSchema = void 0;
    exports.unarchiveFTModelOutFromJSON = unarchiveFTModelOutFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    exports.UnarchiveFTModelOut$inboundSchema = z3.object({
      id: z3.string(),
      object: z3.literal("model").default("model"),
      archived: z3.boolean().default(false)
    });
    function unarchiveFTModelOutFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.UnarchiveFTModelOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'UnarchiveFTModelOut' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/updateftmodelin.js
var require_updateftmodelin = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/updateftmodelin.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.UpdateFTModelIn$outboundSchema = void 0;
    exports.updateFTModelInToJSON = updateFTModelInToJSON;
    var z3 = __importStar(require_v3());
    exports.UpdateFTModelIn$outboundSchema = z3.object({
      name: z3.nullable(z3.string()).optional(),
      description: z3.nullable(z3.string()).optional()
    });
    function updateFTModelInToJSON(updateFTModelIn) {
      return JSON.stringify(exports.UpdateFTModelIn$outboundSchema.parse(updateFTModelIn));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/uploadfileout.js
var require_uploadfileout = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/uploadfileout.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.UploadFileOut$inboundSchema = void 0;
    exports.uploadFileOutFromJSON = uploadFileOutFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var filepurpose_js_1 = require_filepurpose();
    var sampletype_js_1 = require_sampletype();
    var source_js_1 = require_source();
    exports.UploadFileOut$inboundSchema = z3.object({
      id: z3.string(),
      object: z3.string(),
      bytes: z3.number().int(),
      created_at: z3.number().int(),
      filename: z3.string(),
      purpose: filepurpose_js_1.FilePurpose$inboundSchema,
      sample_type: sampletype_js_1.SampleType$inboundSchema,
      num_lines: z3.nullable(z3.number().int()).optional(),
      mimetype: z3.nullable(z3.string()).optional(),
      source: source_js_1.Source$inboundSchema,
      signature: z3.nullable(z3.string()).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        "bytes": "sizeBytes",
        "created_at": "createdAt",
        "sample_type": "sampleType",
        "num_lines": "numLines"
      });
    });
    function uploadFileOutFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.UploadFileOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'UploadFileOut' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/validationerror.js
var require_validationerror = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/validationerror.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ValidationError$inboundSchema = exports.Loc$inboundSchema = void 0;
    exports.locFromJSON = locFromJSON;
    exports.validationErrorFromJSON = validationErrorFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    exports.Loc$inboundSchema = z3.union([z3.string(), z3.number().int()]);
    function locFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.Loc$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'Loc' from JSON`);
    }
    exports.ValidationError$inboundSchema = z3.object({
      loc: z3.array(z3.union([z3.string(), z3.number().int()])),
      msg: z3.string(),
      type: z3.string()
    });
    function validationErrorFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ValidationError$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ValidationError' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/components/index.js
var require_components = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/components/index.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __exportStar = exports && exports.__exportStar || function(m4, exports2) {
      for (var p4 in m4) if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4)) __createBinding(exports2, m4, p4);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar(require_agent(), exports);
    __exportStar(require_agentaliasresponse(), exports);
    __exportStar(require_agentconversation(), exports);
    __exportStar(require_agentcreationrequest(), exports);
    __exportStar(require_agenthandoffdoneevent(), exports);
    __exportStar(require_agenthandoffentry(), exports);
    __exportStar(require_agenthandoffstartedevent(), exports);
    __exportStar(require_agentscompletionrequest(), exports);
    __exportStar(require_agentscompletionstreamrequest(), exports);
    __exportStar(require_agentupdaterequest(), exports);
    __exportStar(require_apiendpoint(), exports);
    __exportStar(require_archiveftmodelout(), exports);
    __exportStar(require_assistantmessage(), exports);
    __exportStar(require_audiochunk(), exports);
    __exportStar(require_audioencoding(), exports);
    __exportStar(require_audioformat(), exports);
    __exportStar(require_audiotranscriptionrequest(), exports);
    __exportStar(require_audiotranscriptionrequeststream(), exports);
    __exportStar(require_basemodelcard(), exports);
    __exportStar(require_batcherror(), exports);
    __exportStar(require_batchjobin(), exports);
    __exportStar(require_batchjobout(), exports);
    __exportStar(require_batchjobsout(), exports);
    __exportStar(require_batchjobstatus(), exports);
    __exportStar(require_batchrequest(), exports);
    __exportStar(require_builtinconnectors(), exports);
    __exportStar(require_chatclassificationrequest(), exports);
    __exportStar(require_chatcompletionchoice(), exports);
    __exportStar(require_chatcompletionrequest(), exports);
    __exportStar(require_chatcompletionresponse(), exports);
    __exportStar(require_chatcompletionstreamrequest(), exports);
    __exportStar(require_chatmoderationrequest(), exports);
    __exportStar(require_checkpointout(), exports);
    __exportStar(require_classificationrequest(), exports);
    __exportStar(require_classificationresponse(), exports);
    __exportStar(require_classificationtargetresult(), exports);
    __exportStar(require_classifierdetailedjobout(), exports);
    __exportStar(require_classifierftmodelout(), exports);
    __exportStar(require_classifierjobout(), exports);
    __exportStar(require_classifiertargetin(), exports);
    __exportStar(require_classifiertargetout(), exports);
    __exportStar(require_classifiertrainingparameters(), exports);
    __exportStar(require_classifiertrainingparametersin(), exports);
    __exportStar(require_codeinterpretertool(), exports);
    __exportStar(require_completionargs(), exports);
    __exportStar(require_completionargsstop(), exports);
    __exportStar(require_completionchunk(), exports);
    __exportStar(require_completiondetailedjobout(), exports);
    __exportStar(require_completionevent(), exports);
    __exportStar(require_completionftmodelout(), exports);
    __exportStar(require_completionjobout(), exports);
    __exportStar(require_completionresponsestreamchoice(), exports);
    __exportStar(require_completiontrainingparameters(), exports);
    __exportStar(require_completiontrainingparametersin(), exports);
    __exportStar(require_contentchunk(), exports);
    __exportStar(require_conversationappendrequest(), exports);
    __exportStar(require_conversationappendstreamrequest(), exports);
    __exportStar(require_conversationevents(), exports);
    __exportStar(require_conversationhistory(), exports);
    __exportStar(require_conversationinputs(), exports);
    __exportStar(require_conversationmessages(), exports);
    __exportStar(require_conversationrequest(), exports);
    __exportStar(require_conversationresponse(), exports);
    __exportStar(require_conversationrestartrequest(), exports);
    __exportStar(require_conversationrestartstreamrequest(), exports);
    __exportStar(require_conversationstreamrequest(), exports);
    __exportStar(require_conversationusageinfo(), exports);
    __exportStar(require_deletefileout(), exports);
    __exportStar(require_deletemodelout(), exports);
    __exportStar(require_deltamessage(), exports);
    __exportStar(require_documentlibrarytool(), exports);
    __exportStar(require_documentout(), exports);
    __exportStar(require_documenttextcontent(), exports);
    __exportStar(require_documentupdatein(), exports);
    __exportStar(require_documenturlchunk(), exports);
    __exportStar(require_embeddingdtype(), exports);
    __exportStar(require_embeddingrequest(), exports);
    __exportStar(require_embeddingresponse(), exports);
    __exportStar(require_embeddingresponsedata(), exports);
    __exportStar(require_encodingformat(), exports);
    __exportStar(require_entitytype(), exports);
    __exportStar(require_eventout(), exports);
    __exportStar(require_file(), exports);
    __exportStar(require_filechunk(), exports);
    __exportStar(require_filepurpose(), exports);
    __exportStar(require_fileschema(), exports);
    __exportStar(require_filesignedurl(), exports);
    __exportStar(require_fimcompletionrequest(), exports);
    __exportStar(require_fimcompletionresponse(), exports);
    __exportStar(require_fimcompletionstreamrequest(), exports);
    __exportStar(require_finetuneablemodeltype(), exports);
    __exportStar(require_ftclassifierlossfunction(), exports);
    __exportStar(require_ftmodelcapabilitiesout(), exports);
    __exportStar(require_ftmodelcard(), exports);
    __exportStar(require_function(), exports);
    __exportStar(require_functioncall(), exports);
    __exportStar(require_functioncallentry(), exports);
    __exportStar(require_functioncallentryarguments(), exports);
    __exportStar(require_functioncallevent(), exports);
    __exportStar(require_functionname(), exports);
    __exportStar(require_functionresultentry(), exports);
    __exportStar(require_functiontool(), exports);
    __exportStar(require_githubrepositoryin(), exports);
    __exportStar(require_githubrepositoryout(), exports);
    __exportStar(require_imagedetail(), exports);
    __exportStar(require_imagegenerationtool(), exports);
    __exportStar(require_imageurl(), exports);
    __exportStar(require_imageurlchunk(), exports);
    __exportStar(require_inputentries(), exports);
    __exportStar(require_inputs(), exports);
    __exportStar(require_instructrequest(), exports);
    __exportStar(require_jobin(), exports);
    __exportStar(require_jobmetadataout(), exports);
    __exportStar(require_jobsout(), exports);
    __exportStar(require_jsonschema(), exports);
    __exportStar(require_legacyjobmetadataout(), exports);
    __exportStar(require_libraryin(), exports);
    __exportStar(require_libraryinupdate(), exports);
    __exportStar(require_libraryout(), exports);
    __exportStar(require_listdocumentout(), exports);
    __exportStar(require_listfilesout(), exports);
    __exportStar(require_listlibraryout(), exports);
    __exportStar(require_listsharingout(), exports);
    __exportStar(require_messageentries(), exports);
    __exportStar(require_messageinputcontentchunks(), exports);
    __exportStar(require_messageinputentry(), exports);
    __exportStar(require_messageoutputcontentchunks(), exports);
    __exportStar(require_messageoutputentry(), exports);
    __exportStar(require_messageoutputevent(), exports);
    __exportStar(require_metricout(), exports);
    __exportStar(require_mistralpromptmode(), exports);
    __exportStar(require_modelcapabilities(), exports);
    __exportStar(require_modelconversation(), exports);
    __exportStar(require_modellist(), exports);
    __exportStar(require_moderationobject(), exports);
    __exportStar(require_moderationresponse(), exports);
    __exportStar(require_ocrimageobject(), exports);
    __exportStar(require_ocrpagedimensions(), exports);
    __exportStar(require_ocrpageobject(), exports);
    __exportStar(require_ocrrequest(), exports);
    __exportStar(require_ocrresponse(), exports);
    __exportStar(require_ocrtableobject(), exports);
    __exportStar(require_ocrusageinfo(), exports);
    __exportStar(require_outputcontentchunks(), exports);
    __exportStar(require_paginationinfo(), exports);
    __exportStar(require_prediction(), exports);
    __exportStar(require_processingstatusout(), exports);
    __exportStar(require_realtimetranscriptionerror(), exports);
    __exportStar(require_realtimetranscriptionerrordetail(), exports);
    __exportStar(require_realtimetranscriptioninputaudioappend(), exports);
    __exportStar(require_realtimetranscriptioninputaudioend(), exports);
    __exportStar(require_realtimetranscriptioninputaudioflush(), exports);
    __exportStar(require_realtimetranscriptionsession(), exports);
    __exportStar(require_realtimetranscriptionsessioncreated(), exports);
    __exportStar(require_realtimetranscriptionsessionupdated(), exports);
    __exportStar(require_realtimetranscriptionsessionupdatemessage(), exports);
    __exportStar(require_realtimetranscriptionsessionupdatepayload(), exports);
    __exportStar(require_referencechunk(), exports);
    __exportStar(require_requestsource(), exports);
    __exportStar(require_responsedoneevent(), exports);
    __exportStar(require_responseerrorevent(), exports);
    __exportStar(require_responseformat(), exports);
    __exportStar(require_responseformats(), exports);
    __exportStar(require_responsestartedevent(), exports);
    __exportStar(require_retrievefileout(), exports);
    __exportStar(require_sampletype(), exports);
    __exportStar(require_security2(), exports);
    __exportStar(require_shareenum(), exports);
    __exportStar(require_sharingdelete(), exports);
    __exportStar(require_sharingin(), exports);
    __exportStar(require_sharingout(), exports);
    __exportStar(require_source(), exports);
    __exportStar(require_ssetypes(), exports);
    __exportStar(require_systemmessage(), exports);
    __exportStar(require_systemmessagecontentchunks(), exports);
    __exportStar(require_textchunk(), exports);
    __exportStar(require_thinkchunk(), exports);
    __exportStar(require_timestampgranularity(), exports);
    __exportStar(require_tool(), exports);
    __exportStar(require_toolcall(), exports);
    __exportStar(require_toolcallconfirmation(), exports);
    __exportStar(require_toolchoice(), exports);
    __exportStar(require_toolchoiceenum(), exports);
    __exportStar(require_toolconfiguration(), exports);
    __exportStar(require_toolexecutiondeltaevent(), exports);
    __exportStar(require_toolexecutiondoneevent(), exports);
    __exportStar(require_toolexecutionentry(), exports);
    __exportStar(require_toolexecutionstartedevent(), exports);
    __exportStar(require_toolfilechunk(), exports);
    __exportStar(require_toolmessage(), exports);
    __exportStar(require_toolreferencechunk(), exports);
    __exportStar(require_tooltypes(), exports);
    __exportStar(require_trainingfile(), exports);
    __exportStar(require_transcriptionresponse(), exports);
    __exportStar(require_transcriptionsegmentchunk(), exports);
    __exportStar(require_transcriptionstreamdone(), exports);
    __exportStar(require_transcriptionstreamevents(), exports);
    __exportStar(require_transcriptionstreameventtypes(), exports);
    __exportStar(require_transcriptionstreamlanguage(), exports);
    __exportStar(require_transcriptionstreamsegmentdelta(), exports);
    __exportStar(require_transcriptionstreamtextdelta(), exports);
    __exportStar(require_unarchiveftmodelout(), exports);
    __exportStar(require_updateftmodelin(), exports);
    __exportStar(require_uploadfileout(), exports);
    __exportStar(require_usageinfo(), exports);
    __exportStar(require_usermessage(), exports);
    __exportStar(require_validationerror(), exports);
    __exportStar(require_wandbintegration(), exports);
    __exportStar(require_wandbintegrationout(), exports);
    __exportStar(require_websearchpremiumtool(), exports);
    __exportStar(require_websearchtool(), exports);
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/errors/httpvalidationerror.js
var require_httpvalidationerror = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/errors/httpvalidationerror.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.HTTPValidationError$inboundSchema = exports.HTTPValidationError = void 0;
    var z3 = __importStar(require_v3());
    var components = __importStar(require_components());
    var mistralerror_js_1 = require_mistralerror();
    var HTTPValidationError = class extends mistralerror_js_1.MistralError {
      constructor(err, httpMeta) {
        const message = "message" in err && typeof err.message === "string" ? err.message : `API error occurred: ${JSON.stringify(err)}`;
        super(message, httpMeta);
        this.data$ = err;
        if (err.detail != null)
          this.detail = err.detail;
        this.name = "HTTPValidationError";
      }
    };
    exports.HTTPValidationError = HTTPValidationError;
    exports.HTTPValidationError$inboundSchema = z3.object({
      detail: z3.array(components.ValidationError$inboundSchema).optional(),
      request$: z3.instanceof(Request),
      response$: z3.instanceof(Response),
      body$: z3.string()
    }).transform((v4) => {
      return new HTTPValidationError(v4, {
        request: v4.request$,
        response: v4.response$,
        body: v4.body$
      });
    });
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/errors/index.js
var require_errors2 = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/errors/index.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __exportStar = exports && exports.__exportStar || function(m4, exports2) {
      for (var p4 in m4) if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4)) __createBinding(exports2, m4, p4);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar(require_httpclienterrors(), exports);
    __exportStar(require_httpvalidationerror(), exports);
    __exportStar(require_mistralerror(), exports);
    __exportStar(require_responsevalidationerror(), exports);
    __exportStar(require_sdkerror(), exports);
    __exportStar(require_sdkvalidationerror(), exports);
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/types/async.js
var require_async = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/types/async.js"(exports) {
    "use strict";
    init_process_shim();
    var __classPrivateFieldSet3 = exports && exports.__classPrivateFieldSet || function(receiver, state, value, kind, f4) {
      if (kind === "m") throw new TypeError("Private method is not writable");
      if (kind === "a" && !f4) throw new TypeError("Private accessor was defined without a setter");
      if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
      return kind === "a" ? f4.call(receiver, value) : f4 ? f4.value = value : state.set(receiver, value), value;
    };
    var __classPrivateFieldGet3 = exports && exports.__classPrivateFieldGet || function(receiver, state, kind, f4) {
      if (kind === "a" && !f4) throw new TypeError("Private accessor was defined without a getter");
      if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
      return kind === "m" ? f4 : kind === "a" ? f4.call(receiver) : f4 ? f4.value : state.get(receiver);
    };
    var _APIPromise_promise;
    var _APIPromise_unwrapped;
    var _a7;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.APIPromise = void 0;
    var APIPromise4 = class {
      constructor(p4) {
        _APIPromise_promise.set(this, void 0);
        _APIPromise_unwrapped.set(this, void 0);
        this[_a7] = "APIPromise";
        __classPrivateFieldSet3(this, _APIPromise_promise, p4 instanceof Promise ? p4 : Promise.resolve(p4), "f");
        __classPrivateFieldSet3(this, _APIPromise_unwrapped, p4 instanceof Promise ? __classPrivateFieldGet3(this, _APIPromise_promise, "f").then(([value]) => value) : Promise.resolve(p4[0]), "f");
      }
      then(onfulfilled, onrejected) {
        return __classPrivateFieldGet3(this, _APIPromise_promise, "f").then(onfulfilled ? ([value]) => onfulfilled(value) : void 0, onrejected);
      }
      catch(onrejected) {
        return __classPrivateFieldGet3(this, _APIPromise_unwrapped, "f").catch(onrejected);
      }
      finally(onfinally) {
        return __classPrivateFieldGet3(this, _APIPromise_unwrapped, "f").finally(onfinally);
      }
      $inspect() {
        return __classPrivateFieldGet3(this, _APIPromise_promise, "f");
      }
    };
    exports.APIPromise = APIPromise4;
    _APIPromise_promise = /* @__PURE__ */ new WeakMap(), _APIPromise_unwrapped = /* @__PURE__ */ new WeakMap(), _a7 = Symbol.toStringTag;
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/agentsComplete.js
var require_agentsComplete = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/agentsComplete.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.agentsComplete = agentsComplete;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var errors = __importStar(require_errors2());
    var async_js_1 = require_async();
    function agentsComplete(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.AgentsCompletionRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true });
      const path6 = (0, url_js_1.pathToFunc)("/v1/agents/completions")();
      const headers = new Headers((0, primitives_js_1.compactMap)({
        "Content-Type": "application/json",
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "agents_completion_v1_agents_completions_post",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "POST",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.json(200, components.ChatCompletionResponse$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/lib/event-streams.js
var require_event_streams = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/lib/event-streams.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EventStream = void 0;
    var EventStream3 = class extends ReadableStream {
      constructor(responseBody, parse) {
        const upstream = responseBody.getReader();
        let buffer = new Uint8Array();
        super({
          async pull(downstream) {
            try {
              while (true) {
                const match2 = findBoundary(buffer);
                if (!match2) {
                  const chunk = await upstream.read();
                  if (chunk.done)
                    return downstream.close();
                  buffer = concatBuffer(buffer, chunk.value);
                  continue;
                }
                const message = buffer.slice(0, match2.index);
                buffer = buffer.slice(match2.index + match2.length);
                const item = parseMessage2(message, parse);
                if (item && !item.done)
                  return downstream.enqueue(item.value);
                if (item?.done) {
                  await upstream.cancel("done");
                  return downstream.close();
                }
              }
            } catch (e9) {
              downstream.error(e9);
              await upstream.cancel(e9);
            }
          },
          cancel: (reason) => upstream.cancel(reason)
        });
      }
      // Polyfill for older browsers
      [Symbol.asyncIterator]() {
        const fn = ReadableStream.prototype[Symbol.asyncIterator];
        if (typeof fn === "function")
          return fn.call(this);
        const reader = this.getReader();
        return {
          next: async () => {
            const r8 = await reader.read();
            if (r8.done) {
              reader.releaseLock();
              return { done: true, value: void 0 };
            }
            return { done: false, value: r8.value };
          },
          throw: async (e9) => {
            await reader.cancel(e9);
            reader.releaseLock();
            return { done: true, value: void 0 };
          },
          return: async () => {
            await reader.cancel("done");
            reader.releaseLock();
            return { done: true, value: void 0 };
          },
          [Symbol.asyncIterator]() {
            return this;
          }
        };
      }
    };
    exports.EventStream = EventStream3;
    function concatBuffer(a3, b4) {
      const c6 = new Uint8Array(a3.length + b4.length);
      c6.set(a3, 0);
      c6.set(b4, a3.length);
      return c6;
    }
    function findBoundary(buf) {
      const len = buf.length;
      for (let i7 = 0; i7 < len; i7++) {
        if (i7 <= len - 4 && buf[i7] === 13 && buf[i7 + 1] === 10 && buf[i7 + 2] === 13 && buf[i7 + 3] === 10) {
          return { index: i7, length: 4 };
        }
        if (i7 <= len - 2 && buf[i7] === 13 && buf[i7 + 1] === 13) {
          return { index: i7, length: 2 };
        }
        if (i7 <= len - 2 && buf[i7] === 10 && buf[i7 + 1] === 10) {
          return { index: i7, length: 2 };
        }
      }
      return null;
    }
    function parseMessage2(chunk, parse) {
      const text3 = new TextDecoder().decode(chunk);
      const lines = text3.split(/\r\n|\r|\n/);
      const dataLines = [];
      const ret = {};
      let ignore = true;
      for (const line of lines) {
        if (!line || line.startsWith(":"))
          continue;
        ignore = false;
        const i7 = line.indexOf(":");
        const field = line.slice(0, i7);
        const value = line[i7 + 1] === " " ? line.slice(i7 + 2) : line.slice(i7 + 1);
        if (field === "data")
          dataLines.push(value);
        else if (field === "event")
          ret.event = value;
        else if (field === "id")
          ret.id = value;
        else if (field === "retry") {
          const n7 = Number(value);
          if (!isNaN(n7))
            ret.retry = n7;
        }
      }
      if (ignore)
        return;
      if (dataLines.length)
        ret.data = dataLines.join("\n");
      return parse(ret);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/agentsStream.js
var require_agentsStream = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/agentsStream.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.agentsStream = agentsStream;
    var z3 = __importStar(require_v3());
    var encodings_js_1 = require_encodings();
    var event_streams_js_1 = require_event_streams();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var errors = __importStar(require_errors2());
    var async_js_1 = require_async();
    function agentsStream(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.AgentsCompletionStreamRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true });
      const path6 = (0, url_js_1.pathToFunc)("/v1/agents/completions#stream")();
      const headers = new Headers((0, primitives_js_1.compactMap)({
        "Content-Type": "application/json",
        Accept: "text/event-stream"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "stream_agents",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "POST",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.sse(200, z3.instanceof(ReadableStream).transform((stream2) => {
        return new event_streams_js_1.EventStream(stream2, (rawEvent) => {
          if (rawEvent.data === "[DONE]")
            return { done: true };
          return {
            value: components.CompletionEvent$inboundSchema.parse(rawEvent)
          };
        });
      })), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/sdk/agents.js
var require_agents = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/sdk/agents.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Agents = void 0;
    var agentsComplete_js_1 = require_agentsComplete();
    var agentsStream_js_1 = require_agentsStream();
    var sdks_js_1 = require_sdks();
    var fp_js_1 = require_fp();
    var Agents = class extends sdks_js_1.ClientSDK {
      /**
       * Agents Completion
       */
      async complete(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, agentsComplete_js_1.agentsComplete)(this, request, options));
      }
      /**
       * Stream Agents completion
       *
       * @remarks
       * Mistral AI provides the ability to stream responses back to a client in order to allow partial results for certain requests. Tokens will be sent as data-only server-sent events as they become available, with the stream terminated by a data: [DONE] message. Otherwise, the server will hold the request open until the timeout or until completion, with the response containing the full result as JSON.
       */
      async stream(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, agentsStream_js_1.agentsStream)(this, request, options));
      }
    };
    exports.Agents = Agents;
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/types/streams.js
var require_streams = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/types/streams.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.isReadableStream = isReadableStream;
    function isReadableStream(val2) {
      if (typeof val2 !== "object" || val2 === null) {
        return false;
      }
      const stream2 = val2;
      return typeof stream2.getReader === "function" && typeof stream2.cancel === "function" && typeof stream2.tee === "function";
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/audioTranscriptionsComplete.js
var require_audioTranscriptionsComplete = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/audioTranscriptionsComplete.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.audioTranscriptionsComplete = audioTranscriptionsComplete;
    var encodings_js_1 = require_encodings();
    var files_js_1 = require_files();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var async_js_1 = require_async();
    var blobs_js_1 = require_blobs();
    var streams_js_1 = require_streams();
    function audioTranscriptionsComplete(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.AudioTranscriptionRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = new FormData();
      (0, encodings_js_1.appendForm)(body, "model", payload.model);
      if (payload.context_bias !== void 0) {
        (0, encodings_js_1.appendForm)(body, "context_bias", payload.context_bias);
      }
      if (payload.diarize !== void 0) {
        (0, encodings_js_1.appendForm)(body, "diarize", payload.diarize);
      }
      if (payload.file !== void 0) {
        if ((0, blobs_js_1.isBlobLike)(payload.file)) {
          (0, encodings_js_1.appendForm)(body, "file", payload.file);
        } else if ((0, streams_js_1.isReadableStream)(payload.file.content)) {
          const buffer = await (0, files_js_1.readableStreamToArrayBuffer)(payload.file.content);
          const contentType = (0, files_js_1.getContentTypeFromFileName)(payload.file.fileName) || "application/octet-stream";
          const blob = new Blob([buffer], { type: contentType });
          (0, encodings_js_1.appendForm)(body, "file", blob, payload.file.fileName);
        } else {
          const contentType = (0, files_js_1.getContentTypeFromFileName)(payload.file.fileName) || "application/octet-stream";
          (0, encodings_js_1.appendForm)(body, "file", new Blob([payload.file.content], { type: contentType }), payload.file.fileName);
        }
      }
      if (payload.file_id !== void 0) {
        (0, encodings_js_1.appendForm)(body, "file_id", payload.file_id);
      }
      if (payload.file_url !== void 0) {
        (0, encodings_js_1.appendForm)(body, "file_url", payload.file_url);
      }
      if (payload.language !== void 0) {
        (0, encodings_js_1.appendForm)(body, "language", payload.language);
      }
      if (payload.stream !== void 0) {
        (0, encodings_js_1.appendForm)(body, "stream", payload.stream);
      }
      if (payload.temperature !== void 0) {
        (0, encodings_js_1.appendForm)(body, "temperature", payload.temperature);
      }
      if (payload.timestamp_granularities !== void 0) {
        (0, encodings_js_1.appendForm)(body, "timestamp_granularities", payload.timestamp_granularities);
      }
      const path6 = (0, url_js_1.pathToFunc)("/v1/audio/transcriptions")();
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "audio_api_v1_transcriptions_post",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "POST",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const [result] = await M4.match(M4.json(200, components.TranscriptionResponse$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req);
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/audioTranscriptionsStream.js
var require_audioTranscriptionsStream = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/audioTranscriptionsStream.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.audioTranscriptionsStream = audioTranscriptionsStream;
    var z3 = __importStar(require_v3());
    var encodings_js_1 = require_encodings();
    var event_streams_js_1 = require_event_streams();
    var files_js_1 = require_files();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var async_js_1 = require_async();
    var blobs_js_1 = require_blobs();
    var streams_js_1 = require_streams();
    function audioTranscriptionsStream(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.AudioTranscriptionRequestStream$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = new FormData();
      (0, encodings_js_1.appendForm)(body, "model", payload.model);
      if (payload.context_bias !== void 0) {
        (0, encodings_js_1.appendForm)(body, "context_bias", payload.context_bias);
      }
      if (payload.diarize !== void 0) {
        (0, encodings_js_1.appendForm)(body, "diarize", payload.diarize);
      }
      if (payload.file !== void 0) {
        if ((0, blobs_js_1.isBlobLike)(payload.file)) {
          (0, encodings_js_1.appendForm)(body, "file", payload.file);
        } else if ((0, streams_js_1.isReadableStream)(payload.file.content)) {
          const buffer = await (0, files_js_1.readableStreamToArrayBuffer)(payload.file.content);
          const contentType = (0, files_js_1.getContentTypeFromFileName)(payload.file.fileName) || "application/octet-stream";
          const blob = new Blob([buffer], { type: contentType });
          (0, encodings_js_1.appendForm)(body, "file", blob, payload.file.fileName);
        } else {
          const contentType = (0, files_js_1.getContentTypeFromFileName)(payload.file.fileName) || "application/octet-stream";
          (0, encodings_js_1.appendForm)(body, "file", new Blob([payload.file.content], { type: contentType }), payload.file.fileName);
        }
      }
      if (payload.file_id !== void 0) {
        (0, encodings_js_1.appendForm)(body, "file_id", payload.file_id);
      }
      if (payload.file_url !== void 0) {
        (0, encodings_js_1.appendForm)(body, "file_url", payload.file_url);
      }
      if (payload.language !== void 0) {
        (0, encodings_js_1.appendForm)(body, "language", payload.language);
      }
      if (payload.stream !== void 0) {
        (0, encodings_js_1.appendForm)(body, "stream", payload.stream);
      }
      if (payload.temperature !== void 0) {
        (0, encodings_js_1.appendForm)(body, "temperature", payload.temperature);
      }
      if (payload.timestamp_granularities !== void 0) {
        (0, encodings_js_1.appendForm)(body, "timestamp_granularities", payload.timestamp_granularities);
      }
      const path6 = (0, url_js_1.pathToFunc)("/v1/audio/transcriptions#stream")();
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "text/event-stream"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "audio_api_v1_transcriptions_post_stream",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "POST",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const [result] = await M4.match(M4.sse(200, z3.instanceof(ReadableStream).transform((stream2) => {
        return new event_streams_js_1.EventStream(stream2, (rawEvent) => {
          return {
            value: components.TranscriptionStreamEvents$inboundSchema.parse(rawEvent)
          };
        });
      })), M4.fail("4XX"), M4.fail("5XX"))(response, req);
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/sdk/transcriptions.js
var require_transcriptions = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/sdk/transcriptions.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Transcriptions = void 0;
    var audioTranscriptionsComplete_js_1 = require_audioTranscriptionsComplete();
    var audioTranscriptionsStream_js_1 = require_audioTranscriptionsStream();
    var sdks_js_1 = require_sdks();
    var fp_js_1 = require_fp();
    var Transcriptions2 = class extends sdks_js_1.ClientSDK {
      /**
       * Create Transcription
       */
      async complete(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, audioTranscriptionsComplete_js_1.audioTranscriptionsComplete)(this, request, options));
      }
      /**
       * Create Streaming Transcription (SSE)
       */
      async stream(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, audioTranscriptionsStream_js_1.audioTranscriptionsStream)(this, request, options));
      }
    };
    exports.Transcriptions = Transcriptions2;
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/sdk/audio.js
var require_audio = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/sdk/audio.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Audio = void 0;
    var sdks_js_1 = require_sdks();
    var transcriptions_js_1 = require_transcriptions();
    var Audio2 = class extends sdks_js_1.ClientSDK {
      get transcriptions() {
        return this._transcriptions ?? (this._transcriptions = new transcriptions_js_1.Transcriptions(this._options));
      }
    };
    exports.Audio = Audio2;
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentscreateorupdatealias.js
var require_agentsapiv1agentscreateorupdatealias = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentscreateorupdatealias.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AgentsApiV1AgentsCreateOrUpdateAliasRequest$outboundSchema = void 0;
    exports.agentsApiV1AgentsCreateOrUpdateAliasRequestToJSON = agentsApiV1AgentsCreateOrUpdateAliasRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    exports.AgentsApiV1AgentsCreateOrUpdateAliasRequest$outboundSchema = z3.object({
      agentId: z3.string(),
      alias: z3.string(),
      version: z3.number().int()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        agentId: "agent_id"
      });
    });
    function agentsApiV1AgentsCreateOrUpdateAliasRequestToJSON(agentsApiV1AgentsCreateOrUpdateAliasRequest) {
      return JSON.stringify(exports.AgentsApiV1AgentsCreateOrUpdateAliasRequest$outboundSchema.parse(agentsApiV1AgentsCreateOrUpdateAliasRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentsdelete.js
var require_agentsapiv1agentsdelete = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentsdelete.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AgentsApiV1AgentsDeleteRequest$outboundSchema = void 0;
    exports.agentsApiV1AgentsDeleteRequestToJSON = agentsApiV1AgentsDeleteRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    exports.AgentsApiV1AgentsDeleteRequest$outboundSchema = z3.object({
      agentId: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        agentId: "agent_id"
      });
    });
    function agentsApiV1AgentsDeleteRequestToJSON(agentsApiV1AgentsDeleteRequest) {
      return JSON.stringify(exports.AgentsApiV1AgentsDeleteRequest$outboundSchema.parse(agentsApiV1AgentsDeleteRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentsdeletealias.js
var require_agentsapiv1agentsdeletealias = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentsdeletealias.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AgentsApiV1AgentsDeleteAliasRequest$outboundSchema = void 0;
    exports.agentsApiV1AgentsDeleteAliasRequestToJSON = agentsApiV1AgentsDeleteAliasRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    exports.AgentsApiV1AgentsDeleteAliasRequest$outboundSchema = z3.object({
      agentId: z3.string(),
      alias: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        agentId: "agent_id"
      });
    });
    function agentsApiV1AgentsDeleteAliasRequestToJSON(agentsApiV1AgentsDeleteAliasRequest) {
      return JSON.stringify(exports.AgentsApiV1AgentsDeleteAliasRequest$outboundSchema.parse(agentsApiV1AgentsDeleteAliasRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentsget.js
var require_agentsapiv1agentsget = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentsget.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AgentsApiV1AgentsGetRequest$outboundSchema = exports.AgentVersion$outboundSchema = void 0;
    exports.agentVersionToJSON = agentVersionToJSON;
    exports.agentsApiV1AgentsGetRequestToJSON = agentsApiV1AgentsGetRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    exports.AgentVersion$outboundSchema = z3.union([z3.number().int(), z3.string()]);
    function agentVersionToJSON(agentVersion) {
      return JSON.stringify(exports.AgentVersion$outboundSchema.parse(agentVersion));
    }
    exports.AgentsApiV1AgentsGetRequest$outboundSchema = z3.object({
      agentId: z3.string(),
      agentVersion: z3.nullable(z3.union([z3.number().int(), z3.string()])).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        agentId: "agent_id",
        agentVersion: "agent_version"
      });
    });
    function agentsApiV1AgentsGetRequestToJSON(agentsApiV1AgentsGetRequest) {
      return JSON.stringify(exports.AgentsApiV1AgentsGetRequest$outboundSchema.parse(agentsApiV1AgentsGetRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentsgetversion.js
var require_agentsapiv1agentsgetversion = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentsgetversion.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AgentsApiV1AgentsGetVersionRequest$outboundSchema = void 0;
    exports.agentsApiV1AgentsGetVersionRequestToJSON = agentsApiV1AgentsGetVersionRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    exports.AgentsApiV1AgentsGetVersionRequest$outboundSchema = z3.object({
      agentId: z3.string(),
      version: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        agentId: "agent_id"
      });
    });
    function agentsApiV1AgentsGetVersionRequestToJSON(agentsApiV1AgentsGetVersionRequest) {
      return JSON.stringify(exports.AgentsApiV1AgentsGetVersionRequest$outboundSchema.parse(agentsApiV1AgentsGetVersionRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentslist.js
var require_agentsapiv1agentslist = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentslist.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AgentsApiV1AgentsListRequest$outboundSchema = void 0;
    exports.agentsApiV1AgentsListRequestToJSON = agentsApiV1AgentsListRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var components = __importStar(require_components());
    exports.AgentsApiV1AgentsListRequest$outboundSchema = z3.object({
      page: z3.number().int().default(0),
      pageSize: z3.number().int().default(20),
      deploymentChat: z3.nullable(z3.boolean()).optional(),
      sources: z3.nullable(z3.array(components.RequestSource$outboundSchema)).optional(),
      name: z3.nullable(z3.string()).optional(),
      search: z3.nullable(z3.string()).optional(),
      id: z3.nullable(z3.string()).optional(),
      metadata: z3.nullable(z3.record(z3.any())).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        pageSize: "page_size",
        deploymentChat: "deployment_chat"
      });
    });
    function agentsApiV1AgentsListRequestToJSON(agentsApiV1AgentsListRequest) {
      return JSON.stringify(exports.AgentsApiV1AgentsListRequest$outboundSchema.parse(agentsApiV1AgentsListRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentslistversionaliases.js
var require_agentsapiv1agentslistversionaliases = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentslistversionaliases.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AgentsApiV1AgentsListVersionAliasesRequest$outboundSchema = void 0;
    exports.agentsApiV1AgentsListVersionAliasesRequestToJSON = agentsApiV1AgentsListVersionAliasesRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    exports.AgentsApiV1AgentsListVersionAliasesRequest$outboundSchema = z3.object({
      agentId: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        agentId: "agent_id"
      });
    });
    function agentsApiV1AgentsListVersionAliasesRequestToJSON(agentsApiV1AgentsListVersionAliasesRequest) {
      return JSON.stringify(exports.AgentsApiV1AgentsListVersionAliasesRequest$outboundSchema.parse(agentsApiV1AgentsListVersionAliasesRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentslistversions.js
var require_agentsapiv1agentslistversions = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentslistversions.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AgentsApiV1AgentsListVersionsRequest$outboundSchema = void 0;
    exports.agentsApiV1AgentsListVersionsRequestToJSON = agentsApiV1AgentsListVersionsRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    exports.AgentsApiV1AgentsListVersionsRequest$outboundSchema = z3.object({
      agentId: z3.string(),
      page: z3.number().int().default(0),
      pageSize: z3.number().int().default(20)
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        agentId: "agent_id",
        pageSize: "page_size"
      });
    });
    function agentsApiV1AgentsListVersionsRequestToJSON(agentsApiV1AgentsListVersionsRequest) {
      return JSON.stringify(exports.AgentsApiV1AgentsListVersionsRequest$outboundSchema.parse(agentsApiV1AgentsListVersionsRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentsupdate.js
var require_agentsapiv1agentsupdate = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentsupdate.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AgentsApiV1AgentsUpdateRequest$outboundSchema = void 0;
    exports.agentsApiV1AgentsUpdateRequestToJSON = agentsApiV1AgentsUpdateRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var components = __importStar(require_components());
    exports.AgentsApiV1AgentsUpdateRequest$outboundSchema = z3.object({
      agentId: z3.string(),
      agentUpdateRequest: components.AgentUpdateRequest$outboundSchema
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        agentId: "agent_id",
        agentUpdateRequest: "AgentUpdateRequest"
      });
    });
    function agentsApiV1AgentsUpdateRequestToJSON(agentsApiV1AgentsUpdateRequest) {
      return JSON.stringify(exports.AgentsApiV1AgentsUpdateRequest$outboundSchema.parse(agentsApiV1AgentsUpdateRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentsupdateversion.js
var require_agentsapiv1agentsupdateversion = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentsupdateversion.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AgentsApiV1AgentsUpdateVersionRequest$outboundSchema = void 0;
    exports.agentsApiV1AgentsUpdateVersionRequestToJSON = agentsApiV1AgentsUpdateVersionRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    exports.AgentsApiV1AgentsUpdateVersionRequest$outboundSchema = z3.object({
      agentId: z3.string(),
      version: z3.number().int()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        agentId: "agent_id"
      });
    });
    function agentsApiV1AgentsUpdateVersionRequestToJSON(agentsApiV1AgentsUpdateVersionRequest) {
      return JSON.stringify(exports.AgentsApiV1AgentsUpdateVersionRequest$outboundSchema.parse(agentsApiV1AgentsUpdateVersionRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationsappend.js
var require_agentsapiv1conversationsappend = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationsappend.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AgentsApiV1ConversationsAppendRequest$outboundSchema = void 0;
    exports.agentsApiV1ConversationsAppendRequestToJSON = agentsApiV1ConversationsAppendRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var components = __importStar(require_components());
    exports.AgentsApiV1ConversationsAppendRequest$outboundSchema = z3.object({
      conversationId: z3.string(),
      conversationAppendRequest: components.ConversationAppendRequest$outboundSchema
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        conversationId: "conversation_id",
        conversationAppendRequest: "ConversationAppendRequest"
      });
    });
    function agentsApiV1ConversationsAppendRequestToJSON(agentsApiV1ConversationsAppendRequest) {
      return JSON.stringify(exports.AgentsApiV1ConversationsAppendRequest$outboundSchema.parse(agentsApiV1ConversationsAppendRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationsappendstream.js
var require_agentsapiv1conversationsappendstream = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationsappendstream.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AgentsApiV1ConversationsAppendStreamRequest$outboundSchema = void 0;
    exports.agentsApiV1ConversationsAppendStreamRequestToJSON = agentsApiV1ConversationsAppendStreamRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var components = __importStar(require_components());
    exports.AgentsApiV1ConversationsAppendStreamRequest$outboundSchema = z3.object({
      conversationId: z3.string(),
      conversationAppendStreamRequest: components.ConversationAppendStreamRequest$outboundSchema
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        conversationId: "conversation_id",
        conversationAppendStreamRequest: "ConversationAppendStreamRequest"
      });
    });
    function agentsApiV1ConversationsAppendStreamRequestToJSON(agentsApiV1ConversationsAppendStreamRequest) {
      return JSON.stringify(exports.AgentsApiV1ConversationsAppendStreamRequest$outboundSchema.parse(agentsApiV1ConversationsAppendStreamRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationsdelete.js
var require_agentsapiv1conversationsdelete = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationsdelete.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AgentsApiV1ConversationsDeleteRequest$outboundSchema = void 0;
    exports.agentsApiV1ConversationsDeleteRequestToJSON = agentsApiV1ConversationsDeleteRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    exports.AgentsApiV1ConversationsDeleteRequest$outboundSchema = z3.object({
      conversationId: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        conversationId: "conversation_id"
      });
    });
    function agentsApiV1ConversationsDeleteRequestToJSON(agentsApiV1ConversationsDeleteRequest) {
      return JSON.stringify(exports.AgentsApiV1ConversationsDeleteRequest$outboundSchema.parse(agentsApiV1ConversationsDeleteRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationsget.js
var require_agentsapiv1conversationsget = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationsget.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AgentsApiV1ConversationsGetResponseV1ConversationsGet$inboundSchema = exports.AgentsApiV1ConversationsGetRequest$outboundSchema = void 0;
    exports.agentsApiV1ConversationsGetRequestToJSON = agentsApiV1ConversationsGetRequestToJSON;
    exports.agentsApiV1ConversationsGetResponseV1ConversationsGetFromJSON = agentsApiV1ConversationsGetResponseV1ConversationsGetFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var components = __importStar(require_components());
    exports.AgentsApiV1ConversationsGetRequest$outboundSchema = z3.object({
      conversationId: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        conversationId: "conversation_id"
      });
    });
    function agentsApiV1ConversationsGetRequestToJSON(agentsApiV1ConversationsGetRequest) {
      return JSON.stringify(exports.AgentsApiV1ConversationsGetRequest$outboundSchema.parse(agentsApiV1ConversationsGetRequest));
    }
    exports.AgentsApiV1ConversationsGetResponseV1ConversationsGet$inboundSchema = z3.union([
      components.ModelConversation$inboundSchema,
      components.AgentConversation$inboundSchema
    ]);
    function agentsApiV1ConversationsGetResponseV1ConversationsGetFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.AgentsApiV1ConversationsGetResponseV1ConversationsGet$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'AgentsApiV1ConversationsGetResponseV1ConversationsGet' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationshistory.js
var require_agentsapiv1conversationshistory = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationshistory.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AgentsApiV1ConversationsHistoryRequest$outboundSchema = void 0;
    exports.agentsApiV1ConversationsHistoryRequestToJSON = agentsApiV1ConversationsHistoryRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    exports.AgentsApiV1ConversationsHistoryRequest$outboundSchema = z3.object({
      conversationId: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        conversationId: "conversation_id"
      });
    });
    function agentsApiV1ConversationsHistoryRequestToJSON(agentsApiV1ConversationsHistoryRequest) {
      return JSON.stringify(exports.AgentsApiV1ConversationsHistoryRequest$outboundSchema.parse(agentsApiV1ConversationsHistoryRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationslist.js
var require_agentsapiv1conversationslist = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationslist.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ResponseBody$inboundSchema = exports.AgentsApiV1ConversationsListRequest$outboundSchema = void 0;
    exports.agentsApiV1ConversationsListRequestToJSON = agentsApiV1ConversationsListRequestToJSON;
    exports.responseBodyFromJSON = responseBodyFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var components = __importStar(require_components());
    exports.AgentsApiV1ConversationsListRequest$outboundSchema = z3.object({
      page: z3.number().int().default(0),
      pageSize: z3.number().int().default(100),
      metadata: z3.nullable(z3.record(z3.any())).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        pageSize: "page_size"
      });
    });
    function agentsApiV1ConversationsListRequestToJSON(agentsApiV1ConversationsListRequest) {
      return JSON.stringify(exports.AgentsApiV1ConversationsListRequest$outboundSchema.parse(agentsApiV1ConversationsListRequest));
    }
    exports.ResponseBody$inboundSchema = z3.union([
      components.ModelConversation$inboundSchema,
      components.AgentConversation$inboundSchema
    ]);
    function responseBodyFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ResponseBody$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ResponseBody' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationsmessages.js
var require_agentsapiv1conversationsmessages = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationsmessages.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AgentsApiV1ConversationsMessagesRequest$outboundSchema = void 0;
    exports.agentsApiV1ConversationsMessagesRequestToJSON = agentsApiV1ConversationsMessagesRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    exports.AgentsApiV1ConversationsMessagesRequest$outboundSchema = z3.object({
      conversationId: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        conversationId: "conversation_id"
      });
    });
    function agentsApiV1ConversationsMessagesRequestToJSON(agentsApiV1ConversationsMessagesRequest) {
      return JSON.stringify(exports.AgentsApiV1ConversationsMessagesRequest$outboundSchema.parse(agentsApiV1ConversationsMessagesRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationsrestart.js
var require_agentsapiv1conversationsrestart = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationsrestart.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AgentsApiV1ConversationsRestartRequest$outboundSchema = void 0;
    exports.agentsApiV1ConversationsRestartRequestToJSON = agentsApiV1ConversationsRestartRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var components = __importStar(require_components());
    exports.AgentsApiV1ConversationsRestartRequest$outboundSchema = z3.object({
      conversationId: z3.string(),
      conversationRestartRequest: components.ConversationRestartRequest$outboundSchema
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        conversationId: "conversation_id",
        conversationRestartRequest: "ConversationRestartRequest"
      });
    });
    function agentsApiV1ConversationsRestartRequestToJSON(agentsApiV1ConversationsRestartRequest) {
      return JSON.stringify(exports.AgentsApiV1ConversationsRestartRequest$outboundSchema.parse(agentsApiV1ConversationsRestartRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationsrestartstream.js
var require_agentsapiv1conversationsrestartstream = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationsrestartstream.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AgentsApiV1ConversationsRestartStreamRequest$outboundSchema = void 0;
    exports.agentsApiV1ConversationsRestartStreamRequestToJSON = agentsApiV1ConversationsRestartStreamRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var components = __importStar(require_components());
    exports.AgentsApiV1ConversationsRestartStreamRequest$outboundSchema = z3.object({
      conversationId: z3.string(),
      conversationRestartStreamRequest: components.ConversationRestartStreamRequest$outboundSchema
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        conversationId: "conversation_id",
        conversationRestartStreamRequest: "ConversationRestartStreamRequest"
      });
    });
    function agentsApiV1ConversationsRestartStreamRequestToJSON(agentsApiV1ConversationsRestartStreamRequest) {
      return JSON.stringify(exports.AgentsApiV1ConversationsRestartStreamRequest$outboundSchema.parse(agentsApiV1ConversationsRestartStreamRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/deletemodelv1modelsmodeliddelete.js
var require_deletemodelv1modelsmodeliddelete = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/deletemodelv1modelsmodeliddelete.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DeleteModelV1ModelsModelIdDeleteRequest$outboundSchema = void 0;
    exports.deleteModelV1ModelsModelIdDeleteRequestToJSON = deleteModelV1ModelsModelIdDeleteRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    exports.DeleteModelV1ModelsModelIdDeleteRequest$outboundSchema = z3.object({
      modelId: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        modelId: "model_id"
      });
    });
    function deleteModelV1ModelsModelIdDeleteRequestToJSON(deleteModelV1ModelsModelIdDeleteRequest) {
      return JSON.stringify(exports.DeleteModelV1ModelsModelIdDeleteRequest$outboundSchema.parse(deleteModelV1ModelsModelIdDeleteRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/filesapiroutesdeletefile.js
var require_filesapiroutesdeletefile = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/filesapiroutesdeletefile.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FilesApiRoutesDeleteFileRequest$outboundSchema = void 0;
    exports.filesApiRoutesDeleteFileRequestToJSON = filesApiRoutesDeleteFileRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    exports.FilesApiRoutesDeleteFileRequest$outboundSchema = z3.object({
      fileId: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        fileId: "file_id"
      });
    });
    function filesApiRoutesDeleteFileRequestToJSON(filesApiRoutesDeleteFileRequest) {
      return JSON.stringify(exports.FilesApiRoutesDeleteFileRequest$outboundSchema.parse(filesApiRoutesDeleteFileRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/filesapiroutesdownloadfile.js
var require_filesapiroutesdownloadfile = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/filesapiroutesdownloadfile.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FilesApiRoutesDownloadFileRequest$outboundSchema = void 0;
    exports.filesApiRoutesDownloadFileRequestToJSON = filesApiRoutesDownloadFileRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    exports.FilesApiRoutesDownloadFileRequest$outboundSchema = z3.object({
      fileId: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        fileId: "file_id"
      });
    });
    function filesApiRoutesDownloadFileRequestToJSON(filesApiRoutesDownloadFileRequest) {
      return JSON.stringify(exports.FilesApiRoutesDownloadFileRequest$outboundSchema.parse(filesApiRoutesDownloadFileRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/filesapiroutesgetsignedurl.js
var require_filesapiroutesgetsignedurl = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/filesapiroutesgetsignedurl.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FilesApiRoutesGetSignedUrlRequest$outboundSchema = void 0;
    exports.filesApiRoutesGetSignedUrlRequestToJSON = filesApiRoutesGetSignedUrlRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    exports.FilesApiRoutesGetSignedUrlRequest$outboundSchema = z3.object({
      fileId: z3.string(),
      expiry: z3.number().int().default(24)
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        fileId: "file_id"
      });
    });
    function filesApiRoutesGetSignedUrlRequestToJSON(filesApiRoutesGetSignedUrlRequest) {
      return JSON.stringify(exports.FilesApiRoutesGetSignedUrlRequest$outboundSchema.parse(filesApiRoutesGetSignedUrlRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/filesapirouteslistfiles.js
var require_filesapirouteslistfiles = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/filesapirouteslistfiles.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FilesApiRoutesListFilesRequest$outboundSchema = void 0;
    exports.filesApiRoutesListFilesRequestToJSON = filesApiRoutesListFilesRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var components = __importStar(require_components());
    exports.FilesApiRoutesListFilesRequest$outboundSchema = z3.object({
      page: z3.number().int().default(0),
      pageSize: z3.number().int().default(100),
      includeTotal: z3.boolean().default(true),
      sampleType: z3.nullable(z3.array(components.SampleType$outboundSchema)).optional(),
      source: z3.nullable(z3.array(components.Source$outboundSchema)).optional(),
      search: z3.nullable(z3.string()).optional(),
      purpose: z3.nullable(components.FilePurpose$outboundSchema).optional(),
      mimetypes: z3.nullable(z3.array(z3.string())).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        pageSize: "page_size",
        includeTotal: "include_total",
        sampleType: "sample_type"
      });
    });
    function filesApiRoutesListFilesRequestToJSON(filesApiRoutesListFilesRequest) {
      return JSON.stringify(exports.FilesApiRoutesListFilesRequest$outboundSchema.parse(filesApiRoutesListFilesRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/filesapiroutesretrievefile.js
var require_filesapiroutesretrievefile = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/filesapiroutesretrievefile.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FilesApiRoutesRetrieveFileRequest$outboundSchema = void 0;
    exports.filesApiRoutesRetrieveFileRequestToJSON = filesApiRoutesRetrieveFileRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    exports.FilesApiRoutesRetrieveFileRequest$outboundSchema = z3.object({
      fileId: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        fileId: "file_id"
      });
    });
    function filesApiRoutesRetrieveFileRequestToJSON(filesApiRoutesRetrieveFileRequest) {
      return JSON.stringify(exports.FilesApiRoutesRetrieveFileRequest$outboundSchema.parse(filesApiRoutesRetrieveFileRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/filesapiroutesuploadfile.js
var require_filesapiroutesuploadfile = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/filesapiroutesuploadfile.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FilesApiRoutesUploadFileMultiPartBodyParams$outboundSchema = void 0;
    exports.filesApiRoutesUploadFileMultiPartBodyParamsToJSON = filesApiRoutesUploadFileMultiPartBodyParamsToJSON;
    var z3 = __importStar(require_v3());
    var blobs_js_1 = require_blobs();
    var components = __importStar(require_components());
    exports.FilesApiRoutesUploadFileMultiPartBodyParams$outboundSchema = z3.object({
      purpose: components.FilePurpose$outboundSchema.optional(),
      file: components.FileT$outboundSchema.or(blobs_js_1.blobLikeSchema)
    });
    function filesApiRoutesUploadFileMultiPartBodyParamsToJSON(filesApiRoutesUploadFileMultiPartBodyParams) {
      return JSON.stringify(exports.FilesApiRoutesUploadFileMultiPartBodyParams$outboundSchema.parse(filesApiRoutesUploadFileMultiPartBodyParams));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesbatchcancelbatchjob.js
var require_jobsapiroutesbatchcancelbatchjob = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesbatchcancelbatchjob.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.JobsApiRoutesBatchCancelBatchJobRequest$outboundSchema = void 0;
    exports.jobsApiRoutesBatchCancelBatchJobRequestToJSON = jobsApiRoutesBatchCancelBatchJobRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    exports.JobsApiRoutesBatchCancelBatchJobRequest$outboundSchema = z3.object({
      jobId: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        jobId: "job_id"
      });
    });
    function jobsApiRoutesBatchCancelBatchJobRequestToJSON(jobsApiRoutesBatchCancelBatchJobRequest) {
      return JSON.stringify(exports.JobsApiRoutesBatchCancelBatchJobRequest$outboundSchema.parse(jobsApiRoutesBatchCancelBatchJobRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesbatchgetbatchjob.js
var require_jobsapiroutesbatchgetbatchjob = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesbatchgetbatchjob.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.JobsApiRoutesBatchGetBatchJobRequest$outboundSchema = void 0;
    exports.jobsApiRoutesBatchGetBatchJobRequestToJSON = jobsApiRoutesBatchGetBatchJobRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    exports.JobsApiRoutesBatchGetBatchJobRequest$outboundSchema = z3.object({
      jobId: z3.string(),
      inline: z3.nullable(z3.boolean()).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        jobId: "job_id"
      });
    });
    function jobsApiRoutesBatchGetBatchJobRequestToJSON(jobsApiRoutesBatchGetBatchJobRequest) {
      return JSON.stringify(exports.JobsApiRoutesBatchGetBatchJobRequest$outboundSchema.parse(jobsApiRoutesBatchGetBatchJobRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesbatchgetbatchjobs.js
var require_jobsapiroutesbatchgetbatchjobs = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesbatchgetbatchjobs.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.JobsApiRoutesBatchGetBatchJobsRequest$outboundSchema = exports.OrderBy$outboundSchema = exports.OrderBy = void 0;
    exports.jobsApiRoutesBatchGetBatchJobsRequestToJSON = jobsApiRoutesBatchGetBatchJobsRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var components = __importStar(require_components());
    exports.OrderBy = {
      Created: "created",
      MinusCreated: "-created"
    };
    exports.OrderBy$outboundSchema = z3.nativeEnum(exports.OrderBy);
    exports.JobsApiRoutesBatchGetBatchJobsRequest$outboundSchema = z3.object({
      page: z3.number().int().default(0),
      pageSize: z3.number().int().default(100),
      model: z3.nullable(z3.string()).optional(),
      agentId: z3.nullable(z3.string()).optional(),
      metadata: z3.nullable(z3.record(z3.any())).optional(),
      createdAfter: z3.nullable(z3.date().transform((v4) => v4.toISOString())).optional(),
      createdByMe: z3.boolean().default(false),
      status: z3.nullable(z3.array(components.BatchJobStatus$outboundSchema)).optional(),
      orderBy: exports.OrderBy$outboundSchema.default("-created")
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        pageSize: "page_size",
        agentId: "agent_id",
        createdAfter: "created_after",
        createdByMe: "created_by_me",
        orderBy: "order_by"
      });
    });
    function jobsApiRoutesBatchGetBatchJobsRequestToJSON(jobsApiRoutesBatchGetBatchJobsRequest) {
      return JSON.stringify(exports.JobsApiRoutesBatchGetBatchJobsRequest$outboundSchema.parse(jobsApiRoutesBatchGetBatchJobsRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuningarchivefinetunedmodel.js
var require_jobsapiroutesfinetuningarchivefinetunedmodel = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuningarchivefinetunedmodel.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.JobsApiRoutesFineTuningArchiveFineTunedModelRequest$outboundSchema = void 0;
    exports.jobsApiRoutesFineTuningArchiveFineTunedModelRequestToJSON = jobsApiRoutesFineTuningArchiveFineTunedModelRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    exports.JobsApiRoutesFineTuningArchiveFineTunedModelRequest$outboundSchema = z3.object({
      modelId: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        modelId: "model_id"
      });
    });
    function jobsApiRoutesFineTuningArchiveFineTunedModelRequestToJSON(jobsApiRoutesFineTuningArchiveFineTunedModelRequest) {
      return JSON.stringify(exports.JobsApiRoutesFineTuningArchiveFineTunedModelRequest$outboundSchema.parse(jobsApiRoutesFineTuningArchiveFineTunedModelRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuningcancelfinetuningjob.js
var require_jobsapiroutesfinetuningcancelfinetuningjob = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuningcancelfinetuningjob.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.JobsApiRoutesFineTuningCancelFineTuningJobResponse$inboundSchema = exports.JobsApiRoutesFineTuningCancelFineTuningJobRequest$outboundSchema = void 0;
    exports.jobsApiRoutesFineTuningCancelFineTuningJobRequestToJSON = jobsApiRoutesFineTuningCancelFineTuningJobRequestToJSON;
    exports.jobsApiRoutesFineTuningCancelFineTuningJobResponseFromJSON = jobsApiRoutesFineTuningCancelFineTuningJobResponseFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var components = __importStar(require_components());
    exports.JobsApiRoutesFineTuningCancelFineTuningJobRequest$outboundSchema = z3.object({
      jobId: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        jobId: "job_id"
      });
    });
    function jobsApiRoutesFineTuningCancelFineTuningJobRequestToJSON(jobsApiRoutesFineTuningCancelFineTuningJobRequest) {
      return JSON.stringify(exports.JobsApiRoutesFineTuningCancelFineTuningJobRequest$outboundSchema.parse(jobsApiRoutesFineTuningCancelFineTuningJobRequest));
    }
    exports.JobsApiRoutesFineTuningCancelFineTuningJobResponse$inboundSchema = z3.union([
      components.ClassifierDetailedJobOut$inboundSchema.and(z3.object({ job_type: z3.literal("classifier") }).transform((v4) => ({
        jobType: v4.job_type
      }))),
      components.CompletionDetailedJobOut$inboundSchema.and(z3.object({ job_type: z3.literal("completion") }).transform((v4) => ({
        jobType: v4.job_type
      })))
    ]);
    function jobsApiRoutesFineTuningCancelFineTuningJobResponseFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.JobsApiRoutesFineTuningCancelFineTuningJobResponse$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'JobsApiRoutesFineTuningCancelFineTuningJobResponse' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuningcreatefinetuningjob.js
var require_jobsapiroutesfinetuningcreatefinetuningjob = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuningcreatefinetuningjob.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.JobsApiRoutesFineTuningCreateFineTuningJobResponse$inboundSchema = exports.One$inboundSchema = void 0;
    exports.oneFromJSON = oneFromJSON;
    exports.jobsApiRoutesFineTuningCreateFineTuningJobResponseFromJSON = jobsApiRoutesFineTuningCreateFineTuningJobResponseFromJSON;
    var z3 = __importStar(require_v3());
    var schemas_js_1 = require_schemas();
    var components = __importStar(require_components());
    exports.One$inboundSchema = z3.union([
      components.ClassifierJobOut$inboundSchema.and(z3.object({ job_type: z3.literal("classifier") }).transform((v4) => ({
        jobType: v4.job_type
      }))),
      components.CompletionJobOut$inboundSchema.and(z3.object({ job_type: z3.literal("completion") }).transform((v4) => ({
        jobType: v4.job_type
      })))
    ]);
    function oneFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.One$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'One' from JSON`);
    }
    exports.JobsApiRoutesFineTuningCreateFineTuningJobResponse$inboundSchema = z3.union([
      components.LegacyJobMetadataOut$inboundSchema,
      z3.union([
        components.ClassifierJobOut$inboundSchema.and(z3.object({ job_type: z3.literal("classifier") }).transform((v4) => ({
          jobType: v4.job_type
        }))),
        components.CompletionJobOut$inboundSchema.and(z3.object({ job_type: z3.literal("completion") }).transform((v4) => ({
          jobType: v4.job_type
        })))
      ])
    ]);
    function jobsApiRoutesFineTuningCreateFineTuningJobResponseFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.JobsApiRoutesFineTuningCreateFineTuningJobResponse$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'JobsApiRoutesFineTuningCreateFineTuningJobResponse' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuninggetfinetuningjob.js
var require_jobsapiroutesfinetuninggetfinetuningjob = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuninggetfinetuningjob.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.JobsApiRoutesFineTuningGetFineTuningJobResponse$inboundSchema = exports.JobsApiRoutesFineTuningGetFineTuningJobRequest$outboundSchema = void 0;
    exports.jobsApiRoutesFineTuningGetFineTuningJobRequestToJSON = jobsApiRoutesFineTuningGetFineTuningJobRequestToJSON;
    exports.jobsApiRoutesFineTuningGetFineTuningJobResponseFromJSON = jobsApiRoutesFineTuningGetFineTuningJobResponseFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var components = __importStar(require_components());
    exports.JobsApiRoutesFineTuningGetFineTuningJobRequest$outboundSchema = z3.object({
      jobId: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        jobId: "job_id"
      });
    });
    function jobsApiRoutesFineTuningGetFineTuningJobRequestToJSON(jobsApiRoutesFineTuningGetFineTuningJobRequest) {
      return JSON.stringify(exports.JobsApiRoutesFineTuningGetFineTuningJobRequest$outboundSchema.parse(jobsApiRoutesFineTuningGetFineTuningJobRequest));
    }
    exports.JobsApiRoutesFineTuningGetFineTuningJobResponse$inboundSchema = z3.union([
      components.ClassifierDetailedJobOut$inboundSchema.and(z3.object({ job_type: z3.literal("classifier") }).transform((v4) => ({
        jobType: v4.job_type
      }))),
      components.CompletionDetailedJobOut$inboundSchema.and(z3.object({ job_type: z3.literal("completion") }).transform((v4) => ({
        jobType: v4.job_type
      })))
    ]);
    function jobsApiRoutesFineTuningGetFineTuningJobResponseFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.JobsApiRoutesFineTuningGetFineTuningJobResponse$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'JobsApiRoutesFineTuningGetFineTuningJobResponse' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuninggetfinetuningjobs.js
var require_jobsapiroutesfinetuninggetfinetuningjobs = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuninggetfinetuningjobs.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.JobsApiRoutesFineTuningGetFineTuningJobsRequest$outboundSchema = exports.Status$outboundSchema = exports.Status = void 0;
    exports.jobsApiRoutesFineTuningGetFineTuningJobsRequestToJSON = jobsApiRoutesFineTuningGetFineTuningJobsRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    exports.Status = {
      Queued: "QUEUED",
      Started: "STARTED",
      Validating: "VALIDATING",
      Validated: "VALIDATED",
      Running: "RUNNING",
      FailedValidation: "FAILED_VALIDATION",
      Failed: "FAILED",
      Success: "SUCCESS",
      Cancelled: "CANCELLED",
      CancellationRequested: "CANCELLATION_REQUESTED"
    };
    exports.Status$outboundSchema = z3.nativeEnum(exports.Status);
    exports.JobsApiRoutesFineTuningGetFineTuningJobsRequest$outboundSchema = z3.object({
      page: z3.number().int().default(0),
      pageSize: z3.number().int().default(100),
      model: z3.nullable(z3.string()).optional(),
      createdAfter: z3.nullable(z3.date().transform((v4) => v4.toISOString())).optional(),
      createdBefore: z3.nullable(z3.date().transform((v4) => v4.toISOString())).optional(),
      createdByMe: z3.boolean().default(false),
      status: z3.nullable(exports.Status$outboundSchema).optional(),
      wandbProject: z3.nullable(z3.string()).optional(),
      wandbName: z3.nullable(z3.string()).optional(),
      suffix: z3.nullable(z3.string()).optional()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        pageSize: "page_size",
        createdAfter: "created_after",
        createdBefore: "created_before",
        createdByMe: "created_by_me",
        wandbProject: "wandb_project",
        wandbName: "wandb_name"
      });
    });
    function jobsApiRoutesFineTuningGetFineTuningJobsRequestToJSON(jobsApiRoutesFineTuningGetFineTuningJobsRequest) {
      return JSON.stringify(exports.JobsApiRoutesFineTuningGetFineTuningJobsRequest$outboundSchema.parse(jobsApiRoutesFineTuningGetFineTuningJobsRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuningstartfinetuningjob.js
var require_jobsapiroutesfinetuningstartfinetuningjob = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuningstartfinetuningjob.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.JobsApiRoutesFineTuningStartFineTuningJobResponse$inboundSchema = exports.JobsApiRoutesFineTuningStartFineTuningJobRequest$outboundSchema = void 0;
    exports.jobsApiRoutesFineTuningStartFineTuningJobRequestToJSON = jobsApiRoutesFineTuningStartFineTuningJobRequestToJSON;
    exports.jobsApiRoutesFineTuningStartFineTuningJobResponseFromJSON = jobsApiRoutesFineTuningStartFineTuningJobResponseFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var components = __importStar(require_components());
    exports.JobsApiRoutesFineTuningStartFineTuningJobRequest$outboundSchema = z3.object({
      jobId: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        jobId: "job_id"
      });
    });
    function jobsApiRoutesFineTuningStartFineTuningJobRequestToJSON(jobsApiRoutesFineTuningStartFineTuningJobRequest) {
      return JSON.stringify(exports.JobsApiRoutesFineTuningStartFineTuningJobRequest$outboundSchema.parse(jobsApiRoutesFineTuningStartFineTuningJobRequest));
    }
    exports.JobsApiRoutesFineTuningStartFineTuningJobResponse$inboundSchema = z3.union([
      components.ClassifierDetailedJobOut$inboundSchema.and(z3.object({ job_type: z3.literal("classifier") }).transform((v4) => ({
        jobType: v4.job_type
      }))),
      components.CompletionDetailedJobOut$inboundSchema.and(z3.object({ job_type: z3.literal("completion") }).transform((v4) => ({
        jobType: v4.job_type
      })))
    ]);
    function jobsApiRoutesFineTuningStartFineTuningJobResponseFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.JobsApiRoutesFineTuningStartFineTuningJobResponse$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'JobsApiRoutesFineTuningStartFineTuningJobResponse' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuningunarchivefinetunedmodel.js
var require_jobsapiroutesfinetuningunarchivefinetunedmodel = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuningunarchivefinetunedmodel.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.JobsApiRoutesFineTuningUnarchiveFineTunedModelRequest$outboundSchema = void 0;
    exports.jobsApiRoutesFineTuningUnarchiveFineTunedModelRequestToJSON = jobsApiRoutesFineTuningUnarchiveFineTunedModelRequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    exports.JobsApiRoutesFineTuningUnarchiveFineTunedModelRequest$outboundSchema = z3.object({
      modelId: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        modelId: "model_id"
      });
    });
    function jobsApiRoutesFineTuningUnarchiveFineTunedModelRequestToJSON(jobsApiRoutesFineTuningUnarchiveFineTunedModelRequest) {
      return JSON.stringify(exports.JobsApiRoutesFineTuningUnarchiveFineTunedModelRequest$outboundSchema.parse(jobsApiRoutesFineTuningUnarchiveFineTunedModelRequest));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuningupdatefinetunedmodel.js
var require_jobsapiroutesfinetuningupdatefinetunedmodel = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuningupdatefinetunedmodel.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.JobsApiRoutesFineTuningUpdateFineTunedModelResponse$inboundSchema = exports.JobsApiRoutesFineTuningUpdateFineTunedModelRequest$outboundSchema = void 0;
    exports.jobsApiRoutesFineTuningUpdateFineTunedModelRequestToJSON = jobsApiRoutesFineTuningUpdateFineTunedModelRequestToJSON;
    exports.jobsApiRoutesFineTuningUpdateFineTunedModelResponseFromJSON = jobsApiRoutesFineTuningUpdateFineTunedModelResponseFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var components = __importStar(require_components());
    exports.JobsApiRoutesFineTuningUpdateFineTunedModelRequest$outboundSchema = z3.object({
      modelId: z3.string(),
      updateFTModelIn: components.UpdateFTModelIn$outboundSchema
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        modelId: "model_id",
        updateFTModelIn: "UpdateFTModelIn"
      });
    });
    function jobsApiRoutesFineTuningUpdateFineTunedModelRequestToJSON(jobsApiRoutesFineTuningUpdateFineTunedModelRequest) {
      return JSON.stringify(exports.JobsApiRoutesFineTuningUpdateFineTunedModelRequest$outboundSchema.parse(jobsApiRoutesFineTuningUpdateFineTunedModelRequest));
    }
    exports.JobsApiRoutesFineTuningUpdateFineTunedModelResponse$inboundSchema = z3.union([
      components.ClassifierFTModelOut$inboundSchema.and(z3.object({ model_type: z3.literal("classifier") }).transform((v4) => ({
        modelType: v4.model_type
      }))),
      components.CompletionFTModelOut$inboundSchema.and(z3.object({ model_type: z3.literal("completion") }).transform((v4) => ({
        modelType: v4.model_type
      })))
    ]);
    function jobsApiRoutesFineTuningUpdateFineTunedModelResponseFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.JobsApiRoutesFineTuningUpdateFineTunedModelResponse$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'JobsApiRoutesFineTuningUpdateFineTunedModelResponse' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdeletev1.js
var require_librariesdeletev1 = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdeletev1.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LibrariesDeleteV1Request$outboundSchema = void 0;
    exports.librariesDeleteV1RequestToJSON = librariesDeleteV1RequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    exports.LibrariesDeleteV1Request$outboundSchema = z3.object({
      libraryId: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        libraryId: "library_id"
      });
    });
    function librariesDeleteV1RequestToJSON(librariesDeleteV1Request) {
      return JSON.stringify(exports.LibrariesDeleteV1Request$outboundSchema.parse(librariesDeleteV1Request));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsdeletev1.js
var require_librariesdocumentsdeletev1 = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsdeletev1.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LibrariesDocumentsDeleteV1Request$outboundSchema = void 0;
    exports.librariesDocumentsDeleteV1RequestToJSON = librariesDocumentsDeleteV1RequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    exports.LibrariesDocumentsDeleteV1Request$outboundSchema = z3.object({
      libraryId: z3.string(),
      documentId: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        libraryId: "library_id",
        documentId: "document_id"
      });
    });
    function librariesDocumentsDeleteV1RequestToJSON(librariesDocumentsDeleteV1Request) {
      return JSON.stringify(exports.LibrariesDocumentsDeleteV1Request$outboundSchema.parse(librariesDocumentsDeleteV1Request));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsgetextractedtextsignedurlv1.js
var require_librariesdocumentsgetextractedtextsignedurlv1 = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsgetextractedtextsignedurlv1.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LibrariesDocumentsGetExtractedTextSignedUrlV1Request$outboundSchema = void 0;
    exports.librariesDocumentsGetExtractedTextSignedUrlV1RequestToJSON = librariesDocumentsGetExtractedTextSignedUrlV1RequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    exports.LibrariesDocumentsGetExtractedTextSignedUrlV1Request$outboundSchema = z3.object({
      libraryId: z3.string(),
      documentId: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        libraryId: "library_id",
        documentId: "document_id"
      });
    });
    function librariesDocumentsGetExtractedTextSignedUrlV1RequestToJSON(librariesDocumentsGetExtractedTextSignedUrlV1Request) {
      return JSON.stringify(exports.LibrariesDocumentsGetExtractedTextSignedUrlV1Request$outboundSchema.parse(librariesDocumentsGetExtractedTextSignedUrlV1Request));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsgetsignedurlv1.js
var require_librariesdocumentsgetsignedurlv1 = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsgetsignedurlv1.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LibrariesDocumentsGetSignedUrlV1Request$outboundSchema = void 0;
    exports.librariesDocumentsGetSignedUrlV1RequestToJSON = librariesDocumentsGetSignedUrlV1RequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    exports.LibrariesDocumentsGetSignedUrlV1Request$outboundSchema = z3.object({
      libraryId: z3.string(),
      documentId: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        libraryId: "library_id",
        documentId: "document_id"
      });
    });
    function librariesDocumentsGetSignedUrlV1RequestToJSON(librariesDocumentsGetSignedUrlV1Request) {
      return JSON.stringify(exports.LibrariesDocumentsGetSignedUrlV1Request$outboundSchema.parse(librariesDocumentsGetSignedUrlV1Request));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsgetstatusv1.js
var require_librariesdocumentsgetstatusv1 = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsgetstatusv1.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LibrariesDocumentsGetStatusV1Request$outboundSchema = void 0;
    exports.librariesDocumentsGetStatusV1RequestToJSON = librariesDocumentsGetStatusV1RequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    exports.LibrariesDocumentsGetStatusV1Request$outboundSchema = z3.object({
      libraryId: z3.string(),
      documentId: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        libraryId: "library_id",
        documentId: "document_id"
      });
    });
    function librariesDocumentsGetStatusV1RequestToJSON(librariesDocumentsGetStatusV1Request) {
      return JSON.stringify(exports.LibrariesDocumentsGetStatusV1Request$outboundSchema.parse(librariesDocumentsGetStatusV1Request));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsgettextcontentv1.js
var require_librariesdocumentsgettextcontentv1 = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsgettextcontentv1.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LibrariesDocumentsGetTextContentV1Request$outboundSchema = void 0;
    exports.librariesDocumentsGetTextContentV1RequestToJSON = librariesDocumentsGetTextContentV1RequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    exports.LibrariesDocumentsGetTextContentV1Request$outboundSchema = z3.object({
      libraryId: z3.string(),
      documentId: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        libraryId: "library_id",
        documentId: "document_id"
      });
    });
    function librariesDocumentsGetTextContentV1RequestToJSON(librariesDocumentsGetTextContentV1Request) {
      return JSON.stringify(exports.LibrariesDocumentsGetTextContentV1Request$outboundSchema.parse(librariesDocumentsGetTextContentV1Request));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsgetv1.js
var require_librariesdocumentsgetv1 = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsgetv1.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LibrariesDocumentsGetV1Request$outboundSchema = void 0;
    exports.librariesDocumentsGetV1RequestToJSON = librariesDocumentsGetV1RequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    exports.LibrariesDocumentsGetV1Request$outboundSchema = z3.object({
      libraryId: z3.string(),
      documentId: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        libraryId: "library_id",
        documentId: "document_id"
      });
    });
    function librariesDocumentsGetV1RequestToJSON(librariesDocumentsGetV1Request) {
      return JSON.stringify(exports.LibrariesDocumentsGetV1Request$outboundSchema.parse(librariesDocumentsGetV1Request));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentslistv1.js
var require_librariesdocumentslistv1 = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentslistv1.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LibrariesDocumentsListV1Request$outboundSchema = void 0;
    exports.librariesDocumentsListV1RequestToJSON = librariesDocumentsListV1RequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    exports.LibrariesDocumentsListV1Request$outboundSchema = z3.object({
      libraryId: z3.string(),
      search: z3.nullable(z3.string()).optional(),
      pageSize: z3.number().int().default(100),
      page: z3.number().int().default(0),
      filtersAttributes: z3.nullable(z3.string()).optional(),
      sortBy: z3.string().default("created_at"),
      sortOrder: z3.string().default("desc")
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        libraryId: "library_id",
        pageSize: "page_size",
        filtersAttributes: "filters_attributes",
        sortBy: "sort_by",
        sortOrder: "sort_order"
      });
    });
    function librariesDocumentsListV1RequestToJSON(librariesDocumentsListV1Request) {
      return JSON.stringify(exports.LibrariesDocumentsListV1Request$outboundSchema.parse(librariesDocumentsListV1Request));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsreprocessv1.js
var require_librariesdocumentsreprocessv1 = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsreprocessv1.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LibrariesDocumentsReprocessV1Request$outboundSchema = void 0;
    exports.librariesDocumentsReprocessV1RequestToJSON = librariesDocumentsReprocessV1RequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    exports.LibrariesDocumentsReprocessV1Request$outboundSchema = z3.object({
      libraryId: z3.string(),
      documentId: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        libraryId: "library_id",
        documentId: "document_id"
      });
    });
    function librariesDocumentsReprocessV1RequestToJSON(librariesDocumentsReprocessV1Request) {
      return JSON.stringify(exports.LibrariesDocumentsReprocessV1Request$outboundSchema.parse(librariesDocumentsReprocessV1Request));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsupdatev1.js
var require_librariesdocumentsupdatev1 = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsupdatev1.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LibrariesDocumentsUpdateV1Request$outboundSchema = void 0;
    exports.librariesDocumentsUpdateV1RequestToJSON = librariesDocumentsUpdateV1RequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var components = __importStar(require_components());
    exports.LibrariesDocumentsUpdateV1Request$outboundSchema = z3.object({
      libraryId: z3.string(),
      documentId: z3.string(),
      documentUpdateIn: components.DocumentUpdateIn$outboundSchema
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        libraryId: "library_id",
        documentId: "document_id",
        documentUpdateIn: "DocumentUpdateIn"
      });
    });
    function librariesDocumentsUpdateV1RequestToJSON(librariesDocumentsUpdateV1Request) {
      return JSON.stringify(exports.LibrariesDocumentsUpdateV1Request$outboundSchema.parse(librariesDocumentsUpdateV1Request));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsuploadv1.js
var require_librariesdocumentsuploadv1 = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsuploadv1.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LibrariesDocumentsUploadV1Request$outboundSchema = exports.LibrariesDocumentsUploadV1DocumentUpload$outboundSchema = void 0;
    exports.librariesDocumentsUploadV1DocumentUploadToJSON = librariesDocumentsUploadV1DocumentUploadToJSON;
    exports.librariesDocumentsUploadV1RequestToJSON = librariesDocumentsUploadV1RequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var blobs_js_1 = require_blobs();
    var components = __importStar(require_components());
    exports.LibrariesDocumentsUploadV1DocumentUpload$outboundSchema = z3.object({
      file: components.FileT$outboundSchema.or(blobs_js_1.blobLikeSchema)
    });
    function librariesDocumentsUploadV1DocumentUploadToJSON(librariesDocumentsUploadV1DocumentUpload) {
      return JSON.stringify(exports.LibrariesDocumentsUploadV1DocumentUpload$outboundSchema.parse(librariesDocumentsUploadV1DocumentUpload));
    }
    exports.LibrariesDocumentsUploadV1Request$outboundSchema = z3.object({
      libraryId: z3.string(),
      requestBody: z3.lazy(() => exports.LibrariesDocumentsUploadV1DocumentUpload$outboundSchema)
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        libraryId: "library_id",
        requestBody: "RequestBody"
      });
    });
    function librariesDocumentsUploadV1RequestToJSON(librariesDocumentsUploadV1Request) {
      return JSON.stringify(exports.LibrariesDocumentsUploadV1Request$outboundSchema.parse(librariesDocumentsUploadV1Request));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesgetv1.js
var require_librariesgetv1 = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesgetv1.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LibrariesGetV1Request$outboundSchema = void 0;
    exports.librariesGetV1RequestToJSON = librariesGetV1RequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    exports.LibrariesGetV1Request$outboundSchema = z3.object({
      libraryId: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        libraryId: "library_id"
      });
    });
    function librariesGetV1RequestToJSON(librariesGetV1Request) {
      return JSON.stringify(exports.LibrariesGetV1Request$outboundSchema.parse(librariesGetV1Request));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariessharecreatev1.js
var require_librariessharecreatev1 = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariessharecreatev1.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LibrariesShareCreateV1Request$outboundSchema = void 0;
    exports.librariesShareCreateV1RequestToJSON = librariesShareCreateV1RequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var components = __importStar(require_components());
    exports.LibrariesShareCreateV1Request$outboundSchema = z3.object({
      libraryId: z3.string(),
      sharingIn: components.SharingIn$outboundSchema
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        libraryId: "library_id",
        sharingIn: "SharingIn"
      });
    });
    function librariesShareCreateV1RequestToJSON(librariesShareCreateV1Request) {
      return JSON.stringify(exports.LibrariesShareCreateV1Request$outboundSchema.parse(librariesShareCreateV1Request));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariessharedeletev1.js
var require_librariessharedeletev1 = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariessharedeletev1.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LibrariesShareDeleteV1Request$outboundSchema = void 0;
    exports.librariesShareDeleteV1RequestToJSON = librariesShareDeleteV1RequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var components = __importStar(require_components());
    exports.LibrariesShareDeleteV1Request$outboundSchema = z3.object({
      libraryId: z3.string(),
      sharingDelete: components.SharingDelete$outboundSchema
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        libraryId: "library_id",
        sharingDelete: "SharingDelete"
      });
    });
    function librariesShareDeleteV1RequestToJSON(librariesShareDeleteV1Request) {
      return JSON.stringify(exports.LibrariesShareDeleteV1Request$outboundSchema.parse(librariesShareDeleteV1Request));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariessharelistv1.js
var require_librariessharelistv1 = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariessharelistv1.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LibrariesShareListV1Request$outboundSchema = void 0;
    exports.librariesShareListV1RequestToJSON = librariesShareListV1RequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    exports.LibrariesShareListV1Request$outboundSchema = z3.object({
      libraryId: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        libraryId: "library_id"
      });
    });
    function librariesShareListV1RequestToJSON(librariesShareListV1Request) {
      return JSON.stringify(exports.LibrariesShareListV1Request$outboundSchema.parse(librariesShareListV1Request));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesupdatev1.js
var require_librariesupdatev1 = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesupdatev1.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LibrariesUpdateV1Request$outboundSchema = void 0;
    exports.librariesUpdateV1RequestToJSON = librariesUpdateV1RequestToJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var components = __importStar(require_components());
    exports.LibrariesUpdateV1Request$outboundSchema = z3.object({
      libraryId: z3.string(),
      libraryInUpdate: components.LibraryInUpdate$outboundSchema
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        libraryId: "library_id",
        libraryInUpdate: "LibraryInUpdate"
      });
    });
    function librariesUpdateV1RequestToJSON(librariesUpdateV1Request) {
      return JSON.stringify(exports.LibrariesUpdateV1Request$outboundSchema.parse(librariesUpdateV1Request));
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/retrievemodelv1modelsmodelidget.js
var require_retrievemodelv1modelsmodelidget = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/retrievemodelv1modelsmodelidget.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RetrieveModelV1ModelsModelIdGetResponseRetrieveModelV1ModelsModelIdGet$inboundSchema = exports.RetrieveModelV1ModelsModelIdGetRequest$outboundSchema = void 0;
    exports.retrieveModelV1ModelsModelIdGetRequestToJSON = retrieveModelV1ModelsModelIdGetRequestToJSON;
    exports.retrieveModelV1ModelsModelIdGetResponseRetrieveModelV1ModelsModelIdGetFromJSON = retrieveModelV1ModelsModelIdGetResponseRetrieveModelV1ModelsModelIdGetFromJSON;
    var z3 = __importStar(require_v3());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var components = __importStar(require_components());
    exports.RetrieveModelV1ModelsModelIdGetRequest$outboundSchema = z3.object({
      modelId: z3.string()
    }).transform((v4) => {
      return (0, primitives_js_1.remap)(v4, {
        modelId: "model_id"
      });
    });
    function retrieveModelV1ModelsModelIdGetRequestToJSON(retrieveModelV1ModelsModelIdGetRequest) {
      return JSON.stringify(exports.RetrieveModelV1ModelsModelIdGetRequest$outboundSchema.parse(retrieveModelV1ModelsModelIdGetRequest));
    }
    exports.RetrieveModelV1ModelsModelIdGetResponseRetrieveModelV1ModelsModelIdGet$inboundSchema = z3.union([
      components.BaseModelCard$inboundSchema.and(z3.object({ type: z3.literal("base") })),
      components.FTModelCard$inboundSchema.and(z3.object({ type: z3.literal("fine-tuned") }))
    ]);
    function retrieveModelV1ModelsModelIdGetResponseRetrieveModelV1ModelsModelIdGetFromJSON(jsonString) {
      return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.RetrieveModelV1ModelsModelIdGetResponseRetrieveModelV1ModelsModelIdGet$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'RetrieveModelV1ModelsModelIdGetResponseRetrieveModelV1ModelsModelIdGet' from JSON`);
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/index.js
var require_operations = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/models/operations/index.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __exportStar = exports && exports.__exportStar || function(m4, exports2) {
      for (var p4 in m4) if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4)) __createBinding(exports2, m4, p4);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar(require_agentsapiv1agentscreateorupdatealias(), exports);
    __exportStar(require_agentsapiv1agentsdelete(), exports);
    __exportStar(require_agentsapiv1agentsdeletealias(), exports);
    __exportStar(require_agentsapiv1agentsget(), exports);
    __exportStar(require_agentsapiv1agentsgetversion(), exports);
    __exportStar(require_agentsapiv1agentslist(), exports);
    __exportStar(require_agentsapiv1agentslistversionaliases(), exports);
    __exportStar(require_agentsapiv1agentslistversions(), exports);
    __exportStar(require_agentsapiv1agentsupdate(), exports);
    __exportStar(require_agentsapiv1agentsupdateversion(), exports);
    __exportStar(require_agentsapiv1conversationsappend(), exports);
    __exportStar(require_agentsapiv1conversationsappendstream(), exports);
    __exportStar(require_agentsapiv1conversationsdelete(), exports);
    __exportStar(require_agentsapiv1conversationsget(), exports);
    __exportStar(require_agentsapiv1conversationshistory(), exports);
    __exportStar(require_agentsapiv1conversationslist(), exports);
    __exportStar(require_agentsapiv1conversationsmessages(), exports);
    __exportStar(require_agentsapiv1conversationsrestart(), exports);
    __exportStar(require_agentsapiv1conversationsrestartstream(), exports);
    __exportStar(require_deletemodelv1modelsmodeliddelete(), exports);
    __exportStar(require_filesapiroutesdeletefile(), exports);
    __exportStar(require_filesapiroutesdownloadfile(), exports);
    __exportStar(require_filesapiroutesgetsignedurl(), exports);
    __exportStar(require_filesapirouteslistfiles(), exports);
    __exportStar(require_filesapiroutesretrievefile(), exports);
    __exportStar(require_filesapiroutesuploadfile(), exports);
    __exportStar(require_jobsapiroutesbatchcancelbatchjob(), exports);
    __exportStar(require_jobsapiroutesbatchgetbatchjob(), exports);
    __exportStar(require_jobsapiroutesbatchgetbatchjobs(), exports);
    __exportStar(require_jobsapiroutesfinetuningarchivefinetunedmodel(), exports);
    __exportStar(require_jobsapiroutesfinetuningcancelfinetuningjob(), exports);
    __exportStar(require_jobsapiroutesfinetuningcreatefinetuningjob(), exports);
    __exportStar(require_jobsapiroutesfinetuninggetfinetuningjob(), exports);
    __exportStar(require_jobsapiroutesfinetuninggetfinetuningjobs(), exports);
    __exportStar(require_jobsapiroutesfinetuningstartfinetuningjob(), exports);
    __exportStar(require_jobsapiroutesfinetuningunarchivefinetunedmodel(), exports);
    __exportStar(require_jobsapiroutesfinetuningupdatefinetunedmodel(), exports);
    __exportStar(require_librariesdeletev1(), exports);
    __exportStar(require_librariesdocumentsdeletev1(), exports);
    __exportStar(require_librariesdocumentsgetextractedtextsignedurlv1(), exports);
    __exportStar(require_librariesdocumentsgetsignedurlv1(), exports);
    __exportStar(require_librariesdocumentsgetstatusv1(), exports);
    __exportStar(require_librariesdocumentsgettextcontentv1(), exports);
    __exportStar(require_librariesdocumentsgetv1(), exports);
    __exportStar(require_librariesdocumentslistv1(), exports);
    __exportStar(require_librariesdocumentsreprocessv1(), exports);
    __exportStar(require_librariesdocumentsupdatev1(), exports);
    __exportStar(require_librariesdocumentsuploadv1(), exports);
    __exportStar(require_librariesgetv1(), exports);
    __exportStar(require_librariessharecreatev1(), exports);
    __exportStar(require_librariessharedeletev1(), exports);
    __exportStar(require_librariessharelistv1(), exports);
    __exportStar(require_librariesupdatev1(), exports);
    __exportStar(require_retrievemodelv1modelsmodelidget(), exports);
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/batchJobsCancel.js
var require_batchJobsCancel = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/batchJobsCancel.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.batchJobsCancel = batchJobsCancel;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function batchJobsCancel(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.JobsApiRoutesBatchCancelBatchJobRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = null;
      const pathParams = {
        job_id: (0, encodings_js_1.encodeSimple)("job_id", payload.job_id, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/batch/jobs/{job_id}/cancel")(pathParams);
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "jobs_api_routes_batch_cancel_batch_job",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "POST",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const [result] = await M4.match(M4.json(200, components.BatchJobOut$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req);
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/batchJobsCreate.js
var require_batchJobsCreate = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/batchJobsCreate.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.batchJobsCreate = batchJobsCreate;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var async_js_1 = require_async();
    function batchJobsCreate(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.BatchJobIn$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true });
      const path6 = (0, url_js_1.pathToFunc)("/v1/batch/jobs")();
      const headers = new Headers((0, primitives_js_1.compactMap)({
        "Content-Type": "application/json",
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "jobs_api_routes_batch_create_batch_job",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "POST",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const [result] = await M4.match(M4.json(200, components.BatchJobOut$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req);
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/batchJobsGet.js
var require_batchJobsGet = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/batchJobsGet.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.batchJobsGet = batchJobsGet;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function batchJobsGet(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.JobsApiRoutesBatchGetBatchJobRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = null;
      const pathParams = {
        job_id: (0, encodings_js_1.encodeSimple)("job_id", payload.job_id, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/batch/jobs/{job_id}")(pathParams);
      const query = (0, encodings_js_1.encodeFormQuery)({
        "inline": payload.inline
      });
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "jobs_api_routes_batch_get_batch_job",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "GET",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        query,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const [result] = await M4.match(M4.json(200, components.BatchJobOut$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req);
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/batchJobsList.js
var require_batchJobsList = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/batchJobsList.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.batchJobsList = batchJobsList;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function batchJobsList(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.JobsApiRoutesBatchGetBatchJobsRequest$outboundSchema.optional().parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = null;
      const path6 = (0, url_js_1.pathToFunc)("/v1/batch/jobs")();
      const query = (0, encodings_js_1.encodeFormQuery)({
        "agent_id": payload?.agent_id,
        "created_after": payload?.created_after,
        "created_by_me": payload?.created_by_me,
        "metadata": payload?.metadata,
        "model": payload?.model,
        "order_by": payload?.order_by,
        "page": payload?.page,
        "page_size": payload?.page_size,
        "status": payload?.status
      });
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "jobs_api_routes_batch_get_batch_jobs",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "GET",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        query,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const [result] = await M4.match(M4.json(200, components.BatchJobsOut$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req);
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/sdk/mistraljobs.js
var require_mistraljobs = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/sdk/mistraljobs.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MistralJobs = void 0;
    var batchJobsCancel_js_1 = require_batchJobsCancel();
    var batchJobsCreate_js_1 = require_batchJobsCreate();
    var batchJobsGet_js_1 = require_batchJobsGet();
    var batchJobsList_js_1 = require_batchJobsList();
    var sdks_js_1 = require_sdks();
    var fp_js_1 = require_fp();
    var MistralJobs = class extends sdks_js_1.ClientSDK {
      /**
       * Get Batch Jobs
       *
       * @remarks
       * Get a list of batch jobs for your organization and user.
       */
      async list(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, batchJobsList_js_1.batchJobsList)(this, request, options));
      }
      /**
       * Create Batch Job
       *
       * @remarks
       * Create a new batch job, it will be queued for processing.
       */
      async create(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, batchJobsCreate_js_1.batchJobsCreate)(this, request, options));
      }
      /**
       * Get Batch Job
       *
       * @remarks
       * Get a batch job details by its UUID.
       *
       * Args:
       *     inline: If True, return results inline in the response.
       */
      async get(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, batchJobsGet_js_1.batchJobsGet)(this, request, options));
      }
      /**
       * Cancel Batch Job
       *
       * @remarks
       * Request the cancellation of a batch job.
       */
      async cancel(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, batchJobsCancel_js_1.batchJobsCancel)(this, request, options));
      }
    };
    exports.MistralJobs = MistralJobs;
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/sdk/batch.js
var require_batch = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/sdk/batch.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Batch = void 0;
    var sdks_js_1 = require_sdks();
    var mistraljobs_js_1 = require_mistraljobs();
    var Batch = class extends sdks_js_1.ClientSDK {
      get jobs() {
        return this._jobs ?? (this._jobs = new mistraljobs_js_1.MistralJobs(this._options));
      }
    };
    exports.Batch = Batch;
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsAppend.js
var require_betaConversationsAppend = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsAppend.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.betaConversationsAppend = betaConversationsAppend;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var errors = __importStar(require_errors2());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function betaConversationsAppend(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1ConversationsAppendRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = (0, encodings_js_1.encodeJSON)("body", payload.ConversationAppendRequest, {
        explode: true
      });
      const pathParams = {
        conversation_id: (0, encodings_js_1.encodeSimple)("conversation_id", payload.conversation_id, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/conversations/{conversation_id}")(pathParams);
      const headers = new Headers((0, primitives_js_1.compactMap)({
        "Content-Type": "application/json",
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "agents_api_v1_conversations_append",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "POST",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.json(200, components.ConversationResponse$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsAppendStream.js
var require_betaConversationsAppendStream = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsAppendStream.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.betaConversationsAppendStream = betaConversationsAppendStream;
    var z3 = __importStar(require_v3());
    var encodings_js_1 = require_encodings();
    var event_streams_js_1 = require_event_streams();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var errors = __importStar(require_errors2());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function betaConversationsAppendStream(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1ConversationsAppendStreamRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = (0, encodings_js_1.encodeJSON)("body", payload.ConversationAppendStreamRequest, {
        explode: true
      });
      const pathParams = {
        conversation_id: (0, encodings_js_1.encodeSimple)("conversation_id", payload.conversation_id, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/conversations/{conversation_id}#stream")(pathParams);
      const headers = new Headers((0, primitives_js_1.compactMap)({
        "Content-Type": "application/json",
        Accept: "text/event-stream"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "agents_api_v1_conversations_append_stream",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "POST",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.sse(200, z3.instanceof(ReadableStream).transform((stream2) => {
        return new event_streams_js_1.EventStream(stream2, (rawEvent) => {
          return {
            value: components.ConversationEvents$inboundSchema.parse(rawEvent)
          };
        });
      })), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsDelete.js
var require_betaConversationsDelete = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsDelete.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.betaConversationsDelete = betaConversationsDelete;
    var z3 = __importStar(require_v3());
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var errors = __importStar(require_errors2());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function betaConversationsDelete(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1ConversationsDeleteRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = null;
      const pathParams = {
        conversation_id: (0, encodings_js_1.encodeSimple)("conversation_id", payload.conversation_id, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/conversations/{conversation_id}")(pathParams);
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "agents_api_v1_conversations_delete",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "DELETE",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.nil(204, z3.void()), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsGet.js
var require_betaConversationsGet = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsGet.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.betaConversationsGet = betaConversationsGet;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var errors = __importStar(require_errors2());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function betaConversationsGet(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1ConversationsGetRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = null;
      const pathParams = {
        conversation_id: (0, encodings_js_1.encodeSimple)("conversation_id", payload.conversation_id, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/conversations/{conversation_id}")(pathParams);
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "agents_api_v1_conversations_get",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "GET",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.json(200, operations.AgentsApiV1ConversationsGetResponseV1ConversationsGet$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsGetHistory.js
var require_betaConversationsGetHistory = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsGetHistory.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.betaConversationsGetHistory = betaConversationsGetHistory;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var errors = __importStar(require_errors2());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function betaConversationsGetHistory(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1ConversationsHistoryRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = null;
      const pathParams = {
        conversation_id: (0, encodings_js_1.encodeSimple)("conversation_id", payload.conversation_id, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/conversations/{conversation_id}/history")(pathParams);
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "agents_api_v1_conversations_history",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "GET",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.json(200, components.ConversationHistory$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsGetMessages.js
var require_betaConversationsGetMessages = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsGetMessages.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.betaConversationsGetMessages = betaConversationsGetMessages;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var errors = __importStar(require_errors2());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function betaConversationsGetMessages(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1ConversationsMessagesRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = null;
      const pathParams = {
        conversation_id: (0, encodings_js_1.encodeSimple)("conversation_id", payload.conversation_id, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/conversations/{conversation_id}/messages")(pathParams);
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "agents_api_v1_conversations_messages",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "GET",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.json(200, components.ConversationMessages$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsList.js
var require_betaConversationsList = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsList.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.betaConversationsList = betaConversationsList;
    var z3 = __importStar(require_v3());
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var errors = __importStar(require_errors2());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function betaConversationsList(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1ConversationsListRequest$outboundSchema.optional().parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = null;
      const path6 = (0, url_js_1.pathToFunc)("/v1/conversations")();
      const query = (0, encodings_js_1.queryJoin)((0, encodings_js_1.encodeFormQuery)({
        "page": payload?.page,
        "page_size": payload?.page_size
      }), (0, encodings_js_1.encodeJSONQuery)({
        "metadata": payload?.metadata
      }, { explode: false }));
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "agents_api_v1_conversations_list",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "GET",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        query,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.json(200, z3.array(operations.ResponseBody$inboundSchema)), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsRestart.js
var require_betaConversationsRestart = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsRestart.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.betaConversationsRestart = betaConversationsRestart;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var errors = __importStar(require_errors2());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function betaConversationsRestart(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1ConversationsRestartRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = (0, encodings_js_1.encodeJSON)("body", payload.ConversationRestartRequest, {
        explode: true
      });
      const pathParams = {
        conversation_id: (0, encodings_js_1.encodeSimple)("conversation_id", payload.conversation_id, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/conversations/{conversation_id}/restart")(pathParams);
      const headers = new Headers((0, primitives_js_1.compactMap)({
        "Content-Type": "application/json",
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "agents_api_v1_conversations_restart",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "POST",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.json(200, components.ConversationResponse$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsRestartStream.js
var require_betaConversationsRestartStream = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsRestartStream.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.betaConversationsRestartStream = betaConversationsRestartStream;
    var z3 = __importStar(require_v3());
    var encodings_js_1 = require_encodings();
    var event_streams_js_1 = require_event_streams();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var errors = __importStar(require_errors2());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function betaConversationsRestartStream(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1ConversationsRestartStreamRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = (0, encodings_js_1.encodeJSON)("body", payload.ConversationRestartStreamRequest, {
        explode: true
      });
      const pathParams = {
        conversation_id: (0, encodings_js_1.encodeSimple)("conversation_id", payload.conversation_id, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/conversations/{conversation_id}/restart#stream")(pathParams);
      const headers = new Headers((0, primitives_js_1.compactMap)({
        "Content-Type": "application/json",
        Accept: "text/event-stream"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "agents_api_v1_conversations_restart_stream",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "POST",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.sse(200, z3.instanceof(ReadableStream).transform((stream2) => {
        return new event_streams_js_1.EventStream(stream2, (rawEvent) => {
          return {
            value: components.ConversationEvents$inboundSchema.parse(rawEvent)
          };
        });
      })), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsStart.js
var require_betaConversationsStart = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsStart.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.betaConversationsStart = betaConversationsStart;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var errors = __importStar(require_errors2());
    var async_js_1 = require_async();
    function betaConversationsStart(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.ConversationRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true });
      const path6 = (0, url_js_1.pathToFunc)("/v1/conversations")();
      const headers = new Headers((0, primitives_js_1.compactMap)({
        "Content-Type": "application/json",
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "agents_api_v1_conversations_start",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "POST",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.json(200, components.ConversationResponse$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsStartStream.js
var require_betaConversationsStartStream = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsStartStream.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.betaConversationsStartStream = betaConversationsStartStream;
    var z3 = __importStar(require_v3());
    var encodings_js_1 = require_encodings();
    var event_streams_js_1 = require_event_streams();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var errors = __importStar(require_errors2());
    var async_js_1 = require_async();
    function betaConversationsStartStream(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.ConversationStreamRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true });
      const path6 = (0, url_js_1.pathToFunc)("/v1/conversations#stream")();
      const headers = new Headers((0, primitives_js_1.compactMap)({
        "Content-Type": "application/json",
        Accept: "text/event-stream"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "agents_api_v1_conversations_start_stream",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "POST",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.sse(200, z3.instanceof(ReadableStream).transform((stream2) => {
        return new event_streams_js_1.EventStream(stream2, (rawEvent) => {
          return {
            value: components.ConversationEvents$inboundSchema.parse(rawEvent)
          };
        });
      })), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/sdk/conversations.js
var require_conversations = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/sdk/conversations.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Conversations = void 0;
    var betaConversationsAppend_js_1 = require_betaConversationsAppend();
    var betaConversationsAppendStream_js_1 = require_betaConversationsAppendStream();
    var betaConversationsDelete_js_1 = require_betaConversationsDelete();
    var betaConversationsGet_js_1 = require_betaConversationsGet();
    var betaConversationsGetHistory_js_1 = require_betaConversationsGetHistory();
    var betaConversationsGetMessages_js_1 = require_betaConversationsGetMessages();
    var betaConversationsList_js_1 = require_betaConversationsList();
    var betaConversationsRestart_js_1 = require_betaConversationsRestart();
    var betaConversationsRestartStream_js_1 = require_betaConversationsRestartStream();
    var betaConversationsStart_js_1 = require_betaConversationsStart();
    var betaConversationsStartStream_js_1 = require_betaConversationsStartStream();
    var sdks_js_1 = require_sdks();
    var fp_js_1 = require_fp();
    var Conversations2 = class extends sdks_js_1.ClientSDK {
      /**
       * Create a conversation and append entries to it.
       *
       * @remarks
       * Create a new conversation, using a base model or an agent and append entries. Completion and tool executions are run and the response is appended to the conversation.Use the returned conversation_id to continue the conversation.
       */
      async start(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, betaConversationsStart_js_1.betaConversationsStart)(this, request, options));
      }
      /**
       * List all created conversations.
       *
       * @remarks
       * Retrieve a list of conversation entities sorted by creation time.
       */
      async list(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, betaConversationsList_js_1.betaConversationsList)(this, request, options));
      }
      /**
       * Retrieve a conversation information.
       *
       * @remarks
       * Given a conversation_id retrieve a conversation entity with its attributes.
       */
      async get(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, betaConversationsGet_js_1.betaConversationsGet)(this, request, options));
      }
      /**
       * Delete a conversation.
       *
       * @remarks
       * Delete a conversation given a conversation_id.
       */
      async delete(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, betaConversationsDelete_js_1.betaConversationsDelete)(this, request, options));
      }
      /**
       * Append new entries to an existing conversation.
       *
       * @remarks
       * Run completion on the history of the conversation and the user entries. Return the new created entries.
       */
      async append(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, betaConversationsAppend_js_1.betaConversationsAppend)(this, request, options));
      }
      /**
       * Retrieve all entries in a conversation.
       *
       * @remarks
       * Given a conversation_id retrieve all the entries belonging to that conversation. The entries are sorted in the order they were appended, those can be messages, connectors or function_call.
       */
      async getHistory(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, betaConversationsGetHistory_js_1.betaConversationsGetHistory)(this, request, options));
      }
      /**
       * Retrieve all messages in a conversation.
       *
       * @remarks
       * Given a conversation_id retrieve all the messages belonging to that conversation. This is similar to retrieving all entries except we filter the messages only.
       */
      async getMessages(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, betaConversationsGetMessages_js_1.betaConversationsGetMessages)(this, request, options));
      }
      /**
       * Restart a conversation starting from a given entry.
       *
       * @remarks
       * Given a conversation_id and an id, recreate a conversation from this point and run completion. A new conversation is returned with the new entries returned.
       */
      async restart(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, betaConversationsRestart_js_1.betaConversationsRestart)(this, request, options));
      }
      /**
       * Create a conversation and append entries to it.
       *
       * @remarks
       * Create a new conversation, using a base model or an agent and append entries. Completion and tool executions are run and the response is appended to the conversation.Use the returned conversation_id to continue the conversation.
       */
      async startStream(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, betaConversationsStartStream_js_1.betaConversationsStartStream)(this, request, options));
      }
      /**
       * Append new entries to an existing conversation.
       *
       * @remarks
       * Run completion on the history of the conversation and the user entries. Return the new created entries.
       */
      async appendStream(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, betaConversationsAppendStream_js_1.betaConversationsAppendStream)(this, request, options));
      }
      /**
       * Restart a conversation starting from a given entry.
       *
       * @remarks
       * Given a conversation_id and an id, recreate a conversation from this point and run completion. A new conversation is returned with the new entries returned.
       */
      async restartStream(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, betaConversationsRestartStream_js_1.betaConversationsRestartStream)(this, request, options));
      }
    };
    exports.Conversations = Conversations2;
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesCreate.js
var require_betaLibrariesCreate = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesCreate.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.betaLibrariesCreate = betaLibrariesCreate;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var errors = __importStar(require_errors2());
    var async_js_1 = require_async();
    function betaLibrariesCreate(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.LibraryIn$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true });
      const path6 = (0, url_js_1.pathToFunc)("/v1/libraries")();
      const headers = new Headers((0, primitives_js_1.compactMap)({
        "Content-Type": "application/json",
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "libraries_create_v1",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "POST",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.json(201, components.LibraryOut$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDelete.js
var require_betaLibrariesDelete = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDelete.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.betaLibrariesDelete = betaLibrariesDelete;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var errors = __importStar(require_errors2());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function betaLibrariesDelete(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesDeleteV1Request$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = null;
      const pathParams = {
        library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}")(pathParams);
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "libraries_delete_v1",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "DELETE",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.json(200, components.LibraryOut$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesGet.js
var require_betaLibrariesGet = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesGet.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.betaLibrariesGet = betaLibrariesGet;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var errors = __importStar(require_errors2());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function betaLibrariesGet(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesGetV1Request$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = null;
      const pathParams = {
        library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}")(pathParams);
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "libraries_get_v1",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "GET",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.json(200, components.LibraryOut$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesList.js
var require_betaLibrariesList = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesList.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.betaLibrariesList = betaLibrariesList;
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var async_js_1 = require_async();
    function betaLibrariesList(client, options) {
      return new async_js_1.APIPromise($do(client, options));
    }
    async function $do(client, options) {
      const path6 = (0, url_js_1.pathToFunc)("/v1/libraries")();
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "libraries_list_v1",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "GET",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const [result] = await M4.match(M4.json(200, components.ListLibraryOut$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req);
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesUpdate.js
var require_betaLibrariesUpdate = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesUpdate.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.betaLibrariesUpdate = betaLibrariesUpdate;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var errors = __importStar(require_errors2());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function betaLibrariesUpdate(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesUpdateV1Request$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = (0, encodings_js_1.encodeJSON)("body", payload.LibraryInUpdate, { explode: true });
      const pathParams = {
        library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}")(pathParams);
      const headers = new Headers((0, primitives_js_1.compactMap)({
        "Content-Type": "application/json",
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "libraries_update_v1",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "PUT",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.json(200, components.LibraryOut$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesAccessesDelete.js
var require_betaLibrariesAccessesDelete = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesAccessesDelete.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.betaLibrariesAccessesDelete = betaLibrariesAccessesDelete;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var errors = __importStar(require_errors2());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function betaLibrariesAccessesDelete(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesShareDeleteV1Request$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = (0, encodings_js_1.encodeJSON)("body", payload.SharingDelete, { explode: true });
      const pathParams = {
        library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}/share")(pathParams);
      const headers = new Headers((0, primitives_js_1.compactMap)({
        "Content-Type": "application/json",
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "libraries_share_delete_v1",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "DELETE",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.json(200, components.SharingOut$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesAccessesList.js
var require_betaLibrariesAccessesList = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesAccessesList.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.betaLibrariesAccessesList = betaLibrariesAccessesList;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var errors = __importStar(require_errors2());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function betaLibrariesAccessesList(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesShareListV1Request$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = null;
      const pathParams = {
        library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}/share")(pathParams);
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "libraries_share_list_v1",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "GET",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.json(200, components.ListSharingOut$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesAccessesUpdateOrCreate.js
var require_betaLibrariesAccessesUpdateOrCreate = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesAccessesUpdateOrCreate.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.betaLibrariesAccessesUpdateOrCreate = betaLibrariesAccessesUpdateOrCreate;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var errors = __importStar(require_errors2());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function betaLibrariesAccessesUpdateOrCreate(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesShareCreateV1Request$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = (0, encodings_js_1.encodeJSON)("body", payload.SharingIn, { explode: true });
      const pathParams = {
        library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}/share")(pathParams);
      const headers = new Headers((0, primitives_js_1.compactMap)({
        "Content-Type": "application/json",
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "libraries_share_create_v1",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "PUT",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.json(200, components.SharingOut$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/sdk/accesses.js
var require_accesses = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/sdk/accesses.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Accesses = void 0;
    var betaLibrariesAccessesDelete_js_1 = require_betaLibrariesAccessesDelete();
    var betaLibrariesAccessesList_js_1 = require_betaLibrariesAccessesList();
    var betaLibrariesAccessesUpdateOrCreate_js_1 = require_betaLibrariesAccessesUpdateOrCreate();
    var sdks_js_1 = require_sdks();
    var fp_js_1 = require_fp();
    var Accesses = class extends sdks_js_1.ClientSDK {
      /**
       * List all of the access to this library.
       *
       * @remarks
       * Given a library, list all of the Entity that have access and to what level.
       */
      async list(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, betaLibrariesAccessesList_js_1.betaLibrariesAccessesList)(this, request, options));
      }
      /**
       * Create or update an access level.
       *
       * @remarks
       * Given a library id, you can create or update the access level of an entity. You have to be owner of the library to share a library. An owner cannot change their own role. A library cannot be shared outside of the organization.
       */
      async updateOrCreate(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, betaLibrariesAccessesUpdateOrCreate_js_1.betaLibrariesAccessesUpdateOrCreate)(this, request, options));
      }
      /**
       * Delete an access level.
       *
       * @remarks
       * Given a library id, you can delete the access level of an entity. An owner cannot delete it's own access. You have to be the owner of the library to delete an acces other than yours.
       */
      async delete(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, betaLibrariesAccessesDelete_js_1.betaLibrariesAccessesDelete)(this, request, options));
      }
    };
    exports.Accesses = Accesses;
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsDelete.js
var require_betaLibrariesDocumentsDelete = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsDelete.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.betaLibrariesDocumentsDelete = betaLibrariesDocumentsDelete;
    var z3 = __importStar(require_v3());
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var errors = __importStar(require_errors2());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function betaLibrariesDocumentsDelete(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesDocumentsDeleteV1Request$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = null;
      const pathParams = {
        document_id: (0, encodings_js_1.encodeSimple)("document_id", payload.document_id, {
          explode: false,
          charEncoding: "percent"
        }),
        library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}/documents/{document_id}")(pathParams);
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "libraries_documents_delete_v1",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "DELETE",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.nil(204, z3.void()), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsExtractedTextSignedUrl.js
var require_betaLibrariesDocumentsExtractedTextSignedUrl = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsExtractedTextSignedUrl.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.betaLibrariesDocumentsExtractedTextSignedUrl = betaLibrariesDocumentsExtractedTextSignedUrl;
    var z3 = __importStar(require_v3());
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var errors = __importStar(require_errors2());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function betaLibrariesDocumentsExtractedTextSignedUrl(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesDocumentsGetExtractedTextSignedUrlV1Request$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = null;
      const pathParams = {
        document_id: (0, encodings_js_1.encodeSimple)("document_id", payload.document_id, {
          explode: false,
          charEncoding: "percent"
        }),
        library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}/documents/{document_id}/extracted-text-signed-url")(pathParams);
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "libraries_documents_get_extracted_text_signed_url_v1",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "GET",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.json(200, z3.string()), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsGet.js
var require_betaLibrariesDocumentsGet = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsGet.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.betaLibrariesDocumentsGet = betaLibrariesDocumentsGet;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var errors = __importStar(require_errors2());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function betaLibrariesDocumentsGet(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesDocumentsGetV1Request$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = null;
      const pathParams = {
        document_id: (0, encodings_js_1.encodeSimple)("document_id", payload.document_id, {
          explode: false,
          charEncoding: "percent"
        }),
        library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}/documents/{document_id}")(pathParams);
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "libraries_documents_get_v1",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "GET",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.json(200, components.DocumentOut$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsGetSignedUrl.js
var require_betaLibrariesDocumentsGetSignedUrl = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsGetSignedUrl.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.betaLibrariesDocumentsGetSignedUrl = betaLibrariesDocumentsGetSignedUrl;
    var z3 = __importStar(require_v3());
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var errors = __importStar(require_errors2());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function betaLibrariesDocumentsGetSignedUrl(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesDocumentsGetSignedUrlV1Request$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = null;
      const pathParams = {
        document_id: (0, encodings_js_1.encodeSimple)("document_id", payload.document_id, {
          explode: false,
          charEncoding: "percent"
        }),
        library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}/documents/{document_id}/signed-url")(pathParams);
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "libraries_documents_get_signed_url_v1",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "GET",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.json(200, z3.string()), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsList.js
var require_betaLibrariesDocumentsList = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsList.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.betaLibrariesDocumentsList = betaLibrariesDocumentsList;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var errors = __importStar(require_errors2());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function betaLibrariesDocumentsList(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesDocumentsListV1Request$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = null;
      const pathParams = {
        library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}/documents")(pathParams);
      const query = (0, encodings_js_1.encodeFormQuery)({
        "filters_attributes": payload.filters_attributes,
        "page": payload.page,
        "page_size": payload.page_size,
        "search": payload.search,
        "sort_by": payload.sort_by,
        "sort_order": payload.sort_order
      });
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "libraries_documents_list_v1",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "GET",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        query,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.json(200, components.ListDocumentOut$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsReprocess.js
var require_betaLibrariesDocumentsReprocess = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsReprocess.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.betaLibrariesDocumentsReprocess = betaLibrariesDocumentsReprocess;
    var z3 = __importStar(require_v3());
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var errors = __importStar(require_errors2());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function betaLibrariesDocumentsReprocess(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesDocumentsReprocessV1Request$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = null;
      const pathParams = {
        document_id: (0, encodings_js_1.encodeSimple)("document_id", payload.document_id, {
          explode: false,
          charEncoding: "percent"
        }),
        library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}/documents/{document_id}/reprocess")(pathParams);
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "libraries_documents_reprocess_v1",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "POST",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.nil(204, z3.void()), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsStatus.js
var require_betaLibrariesDocumentsStatus = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsStatus.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.betaLibrariesDocumentsStatus = betaLibrariesDocumentsStatus;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var errors = __importStar(require_errors2());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function betaLibrariesDocumentsStatus(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesDocumentsGetStatusV1Request$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = null;
      const pathParams = {
        document_id: (0, encodings_js_1.encodeSimple)("document_id", payload.document_id, {
          explode: false,
          charEncoding: "percent"
        }),
        library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}/documents/{document_id}/status")(pathParams);
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "libraries_documents_get_status_v1",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "GET",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.json(200, components.ProcessingStatusOut$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsTextContent.js
var require_betaLibrariesDocumentsTextContent = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsTextContent.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.betaLibrariesDocumentsTextContent = betaLibrariesDocumentsTextContent;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var errors = __importStar(require_errors2());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function betaLibrariesDocumentsTextContent(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesDocumentsGetTextContentV1Request$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = null;
      const pathParams = {
        document_id: (0, encodings_js_1.encodeSimple)("document_id", payload.document_id, {
          explode: false,
          charEncoding: "percent"
        }),
        library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}/documents/{document_id}/text_content")(pathParams);
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "libraries_documents_get_text_content_v1",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "GET",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.json(200, components.DocumentTextContent$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsUpdate.js
var require_betaLibrariesDocumentsUpdate = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsUpdate.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.betaLibrariesDocumentsUpdate = betaLibrariesDocumentsUpdate;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var errors = __importStar(require_errors2());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function betaLibrariesDocumentsUpdate(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesDocumentsUpdateV1Request$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = (0, encodings_js_1.encodeJSON)("body", payload.DocumentUpdateIn, { explode: true });
      const pathParams = {
        document_id: (0, encodings_js_1.encodeSimple)("document_id", payload.document_id, {
          explode: false,
          charEncoding: "percent"
        }),
        library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}/documents/{document_id}")(pathParams);
      const headers = new Headers((0, primitives_js_1.compactMap)({
        "Content-Type": "application/json",
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "libraries_documents_update_v1",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "PUT",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.json(200, components.DocumentOut$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsUpload.js
var require_betaLibrariesDocumentsUpload = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsUpload.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.betaLibrariesDocumentsUpload = betaLibrariesDocumentsUpload;
    var encodings_js_1 = require_encodings();
    var files_js_1 = require_files();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var errors = __importStar(require_errors2());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    var blobs_js_1 = require_blobs();
    var streams_js_1 = require_streams();
    function betaLibrariesDocumentsUpload(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesDocumentsUploadV1Request$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = new FormData();
      if ((0, blobs_js_1.isBlobLike)(payload.RequestBody.file)) {
        (0, encodings_js_1.appendForm)(body, "file", payload.RequestBody.file);
      } else if ((0, streams_js_1.isReadableStream)(payload.RequestBody.file.content)) {
        const buffer = await (0, files_js_1.readableStreamToArrayBuffer)(payload.RequestBody.file.content);
        const contentType = (0, files_js_1.getContentTypeFromFileName)(payload.RequestBody.file.fileName) || "application/octet-stream";
        const blob = new Blob([buffer], { type: contentType });
        (0, encodings_js_1.appendForm)(body, "file", blob, payload.RequestBody.file.fileName);
      } else {
        const contentType = (0, files_js_1.getContentTypeFromFileName)(payload.RequestBody.file.fileName) || "application/octet-stream";
        (0, encodings_js_1.appendForm)(body, "file", new Blob([payload.RequestBody.file.content], { type: contentType }), payload.RequestBody.file.fileName);
      }
      const pathParams = {
        library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}/documents")(pathParams);
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "libraries_documents_upload_v1",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "POST",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.json([200, 201], components.DocumentOut$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/sdk/documents.js
var require_documents = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/sdk/documents.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Documents = void 0;
    var betaLibrariesDocumentsDelete_js_1 = require_betaLibrariesDocumentsDelete();
    var betaLibrariesDocumentsExtractedTextSignedUrl_js_1 = require_betaLibrariesDocumentsExtractedTextSignedUrl();
    var betaLibrariesDocumentsGet_js_1 = require_betaLibrariesDocumentsGet();
    var betaLibrariesDocumentsGetSignedUrl_js_1 = require_betaLibrariesDocumentsGetSignedUrl();
    var betaLibrariesDocumentsList_js_1 = require_betaLibrariesDocumentsList();
    var betaLibrariesDocumentsReprocess_js_1 = require_betaLibrariesDocumentsReprocess();
    var betaLibrariesDocumentsStatus_js_1 = require_betaLibrariesDocumentsStatus();
    var betaLibrariesDocumentsTextContent_js_1 = require_betaLibrariesDocumentsTextContent();
    var betaLibrariesDocumentsUpdate_js_1 = require_betaLibrariesDocumentsUpdate();
    var betaLibrariesDocumentsUpload_js_1 = require_betaLibrariesDocumentsUpload();
    var sdks_js_1 = require_sdks();
    var fp_js_1 = require_fp();
    var Documents2 = class extends sdks_js_1.ClientSDK {
      /**
       * List documents in a given library.
       *
       * @remarks
       * Given a library, lists the document that have been uploaded to that library.
       */
      async list(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, betaLibrariesDocumentsList_js_1.betaLibrariesDocumentsList)(this, request, options));
      }
      /**
       * Upload a new document.
       *
       * @remarks
       * Given a library, upload a new document to that library. It is queued for processing, it status will change it has been processed. The processing has to be completed in order be discoverable for the library search
       */
      async upload(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, betaLibrariesDocumentsUpload_js_1.betaLibrariesDocumentsUpload)(this, request, options));
      }
      /**
       * Retrieve the metadata of a specific document.
       *
       * @remarks
       * Given a library and a document in this library, you can retrieve the metadata of that document.
       */
      async get(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, betaLibrariesDocumentsGet_js_1.betaLibrariesDocumentsGet)(this, request, options));
      }
      /**
       * Update the metadata of a specific document.
       *
       * @remarks
       * Given a library and a document in that library, update the name of that document.
       */
      async update(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, betaLibrariesDocumentsUpdate_js_1.betaLibrariesDocumentsUpdate)(this, request, options));
      }
      /**
       * Delete a document.
       *
       * @remarks
       * Given a library and a document in that library, delete that document. The document will be deleted from the library and the search index.
       */
      async delete(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, betaLibrariesDocumentsDelete_js_1.betaLibrariesDocumentsDelete)(this, request, options));
      }
      /**
       * Retrieve the text content of a specific document.
       *
       * @remarks
       * Given a library and a document in that library, you can retrieve the text content of that document if it exists. For documents like pdf, docx and pptx the text content results from our processing using Mistral OCR.
       */
      async textContent(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, betaLibrariesDocumentsTextContent_js_1.betaLibrariesDocumentsTextContent)(this, request, options));
      }
      /**
       * Retrieve the processing status of a specific document.
       *
       * @remarks
       * Given a library and a document in that library, retrieve the processing status of that document.
       */
      async status(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, betaLibrariesDocumentsStatus_js_1.betaLibrariesDocumentsStatus)(this, request, options));
      }
      /**
       * Retrieve the signed URL of a specific document.
       *
       * @remarks
       * Given a library and a document in that library, retrieve the signed URL of a specific document.The url will expire after 30 minutes and can be accessed by anyone with the link.
       */
      async getSignedUrl(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, betaLibrariesDocumentsGetSignedUrl_js_1.betaLibrariesDocumentsGetSignedUrl)(this, request, options));
      }
      /**
       * Retrieve the signed URL of text extracted from a given document.
       *
       * @remarks
       * Given a library and a document in that library, retrieve the signed URL of text extracted. For documents that are sent to the OCR this returns the result of the OCR queries.
       */
      async extractedTextSignedUrl(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, betaLibrariesDocumentsExtractedTextSignedUrl_js_1.betaLibrariesDocumentsExtractedTextSignedUrl)(this, request, options));
      }
      /**
       * Reprocess a document.
       *
       * @remarks
       * Given a library and a document in that library, reprocess that document, it will be billed again.
       */
      async reprocess(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, betaLibrariesDocumentsReprocess_js_1.betaLibrariesDocumentsReprocess)(this, request, options));
      }
    };
    exports.Documents = Documents2;
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/sdk/libraries.js
var require_libraries = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/sdk/libraries.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Libraries = void 0;
    var betaLibrariesCreate_js_1 = require_betaLibrariesCreate();
    var betaLibrariesDelete_js_1 = require_betaLibrariesDelete();
    var betaLibrariesGet_js_1 = require_betaLibrariesGet();
    var betaLibrariesList_js_1 = require_betaLibrariesList();
    var betaLibrariesUpdate_js_1 = require_betaLibrariesUpdate();
    var sdks_js_1 = require_sdks();
    var fp_js_1 = require_fp();
    var accesses_js_1 = require_accesses();
    var documents_js_1 = require_documents();
    var Libraries = class extends sdks_js_1.ClientSDK {
      get documents() {
        return this._documents ?? (this._documents = new documents_js_1.Documents(this._options));
      }
      get accesses() {
        return this._accesses ?? (this._accesses = new accesses_js_1.Accesses(this._options));
      }
      /**
       * List all libraries you have access to.
       *
       * @remarks
       * List all libraries that you have created or have been shared with you.
       */
      async list(options) {
        return (0, fp_js_1.unwrapAsync)((0, betaLibrariesList_js_1.betaLibrariesList)(this, options));
      }
      /**
       * Create a new Library.
       *
       * @remarks
       * Create a new Library, you will be marked as the owner and only you will have the possibility to share it with others. When first created this will only be accessible by you.
       */
      async create(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, betaLibrariesCreate_js_1.betaLibrariesCreate)(this, request, options));
      }
      /**
       * Detailed information about a specific Library.
       *
       * @remarks
       * Given a library id, details information about that Library.
       */
      async get(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, betaLibrariesGet_js_1.betaLibrariesGet)(this, request, options));
      }
      /**
       * Delete a library and all of it's document.
       *
       * @remarks
       * Given a library id, deletes it together with all documents that have been uploaded to that library.
       */
      async delete(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, betaLibrariesDelete_js_1.betaLibrariesDelete)(this, request, options));
      }
      /**
       * Update a library.
       *
       * @remarks
       * Given a library id, you can update the name and description.
       */
      async update(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, betaLibrariesUpdate_js_1.betaLibrariesUpdate)(this, request, options));
      }
    };
    exports.Libraries = Libraries;
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsCreate.js
var require_betaAgentsCreate = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsCreate.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.betaAgentsCreate = betaAgentsCreate;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var errors = __importStar(require_errors2());
    var async_js_1 = require_async();
    function betaAgentsCreate(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.AgentCreationRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true });
      const path6 = (0, url_js_1.pathToFunc)("/v1/agents")();
      const headers = new Headers((0, primitives_js_1.compactMap)({
        "Content-Type": "application/json",
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "agents_api_v1_agents_create",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "POST",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.json(200, components.Agent$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsCreateVersionAlias.js
var require_betaAgentsCreateVersionAlias = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsCreateVersionAlias.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.betaAgentsCreateVersionAlias = betaAgentsCreateVersionAlias;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var errors = __importStar(require_errors2());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function betaAgentsCreateVersionAlias(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1AgentsCreateOrUpdateAliasRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = null;
      const pathParams = {
        agent_id: (0, encodings_js_1.encodeSimple)("agent_id", payload.agent_id, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/agents/{agent_id}/aliases")(pathParams);
      const query = (0, encodings_js_1.encodeFormQuery)({
        "alias": payload.alias,
        "version": payload.version
      });
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "agents_api_v1_agents_create_or_update_alias",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "PUT",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        query,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.json(200, components.AgentAliasResponse$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsDelete.js
var require_betaAgentsDelete = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsDelete.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.betaAgentsDelete = betaAgentsDelete;
    var z3 = __importStar(require_v3());
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var errors = __importStar(require_errors2());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function betaAgentsDelete(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1AgentsDeleteRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = null;
      const pathParams = {
        agent_id: (0, encodings_js_1.encodeSimple)("agent_id", payload.agent_id, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/agents/{agent_id}")(pathParams);
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "agents_api_v1_agents_delete",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "DELETE",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.nil(204, z3.void()), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsDeleteVersionAlias.js
var require_betaAgentsDeleteVersionAlias = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsDeleteVersionAlias.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.betaAgentsDeleteVersionAlias = betaAgentsDeleteVersionAlias;
    var z3 = __importStar(require_v3());
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var errors = __importStar(require_errors2());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function betaAgentsDeleteVersionAlias(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1AgentsDeleteAliasRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = null;
      const pathParams = {
        agent_id: (0, encodings_js_1.encodeSimple)("agent_id", payload.agent_id, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/agents/{agent_id}/aliases")(pathParams);
      const query = (0, encodings_js_1.encodeFormQuery)({
        "alias": payload.alias
      });
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "agents_api_v1_agents_delete_alias",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "DELETE",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        query,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.nil(204, z3.void()), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsGet.js
var require_betaAgentsGet = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsGet.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.betaAgentsGet = betaAgentsGet;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var errors = __importStar(require_errors2());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function betaAgentsGet(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1AgentsGetRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = null;
      const pathParams = {
        agent_id: (0, encodings_js_1.encodeSimple)("agent_id", payload.agent_id, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/agents/{agent_id}")(pathParams);
      const query = (0, encodings_js_1.encodeFormQuery)({
        "agent_version": payload.agent_version
      });
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "agents_api_v1_agents_get",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "GET",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        query,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.json(200, components.Agent$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsGetVersion.js
var require_betaAgentsGetVersion = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsGetVersion.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.betaAgentsGetVersion = betaAgentsGetVersion;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var errors = __importStar(require_errors2());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function betaAgentsGetVersion(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1AgentsGetVersionRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = null;
      const pathParams = {
        agent_id: (0, encodings_js_1.encodeSimple)("agent_id", payload.agent_id, {
          explode: false,
          charEncoding: "percent"
        }),
        version: (0, encodings_js_1.encodeSimple)("version", payload.version, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/agents/{agent_id}/versions/{version}")(pathParams);
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "agents_api_v1_agents_get_version",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "GET",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.json(200, components.Agent$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsList.js
var require_betaAgentsList = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsList.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.betaAgentsList = betaAgentsList;
    var z3 = __importStar(require_v3());
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var errors = __importStar(require_errors2());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function betaAgentsList(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1AgentsListRequest$outboundSchema.optional().parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = null;
      const path6 = (0, url_js_1.pathToFunc)("/v1/agents")();
      const query = (0, encodings_js_1.queryJoin)((0, encodings_js_1.encodeFormQuery)({
        "deployment_chat": payload?.deployment_chat,
        "id": payload?.id,
        "name": payload?.name,
        "page": payload?.page,
        "page_size": payload?.page_size,
        "search": payload?.search,
        "sources": payload?.sources
      }), (0, encodings_js_1.encodeJSONQuery)({
        "metadata": payload?.metadata
      }, { explode: false }));
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "agents_api_v1_agents_list",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "GET",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        query,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.json(200, z3.array(components.Agent$inboundSchema)), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsListVersionAliases.js
var require_betaAgentsListVersionAliases = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsListVersionAliases.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.betaAgentsListVersionAliases = betaAgentsListVersionAliases;
    var z3 = __importStar(require_v3());
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var errors = __importStar(require_errors2());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function betaAgentsListVersionAliases(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1AgentsListVersionAliasesRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = null;
      const pathParams = {
        agent_id: (0, encodings_js_1.encodeSimple)("agent_id", payload.agent_id, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/agents/{agent_id}/aliases")(pathParams);
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "agents_api_v1_agents_list_version_aliases",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "GET",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.json(200, z3.array(components.AgentAliasResponse$inboundSchema)), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsListVersions.js
var require_betaAgentsListVersions = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsListVersions.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.betaAgentsListVersions = betaAgentsListVersions;
    var z3 = __importStar(require_v3());
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var errors = __importStar(require_errors2());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function betaAgentsListVersions(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1AgentsListVersionsRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = null;
      const pathParams = {
        agent_id: (0, encodings_js_1.encodeSimple)("agent_id", payload.agent_id, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/agents/{agent_id}/versions")(pathParams);
      const query = (0, encodings_js_1.encodeFormQuery)({
        "page": payload.page,
        "page_size": payload.page_size
      });
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "agents_api_v1_agents_list_versions",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "GET",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        query,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.json(200, z3.array(components.Agent$inboundSchema)), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsUpdate.js
var require_betaAgentsUpdate = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsUpdate.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.betaAgentsUpdate = betaAgentsUpdate;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var errors = __importStar(require_errors2());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function betaAgentsUpdate(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1AgentsUpdateRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = (0, encodings_js_1.encodeJSON)("body", payload.AgentUpdateRequest, {
        explode: true
      });
      const pathParams = {
        agent_id: (0, encodings_js_1.encodeSimple)("agent_id", payload.agent_id, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/agents/{agent_id}")(pathParams);
      const headers = new Headers((0, primitives_js_1.compactMap)({
        "Content-Type": "application/json",
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "agents_api_v1_agents_update",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "PATCH",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.json(200, components.Agent$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsUpdateVersion.js
var require_betaAgentsUpdateVersion = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsUpdateVersion.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.betaAgentsUpdateVersion = betaAgentsUpdateVersion;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var errors = __importStar(require_errors2());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function betaAgentsUpdateVersion(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1AgentsUpdateVersionRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = null;
      const pathParams = {
        agent_id: (0, encodings_js_1.encodeSimple)("agent_id", payload.agent_id, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/agents/{agent_id}/version")(pathParams);
      const query = (0, encodings_js_1.encodeFormQuery)({
        "version": payload.version
      });
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "agents_api_v1_agents_update_version",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "PATCH",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        query,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.json(200, components.Agent$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/sdk/mistralagents.js
var require_mistralagents = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/sdk/mistralagents.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MistralAgents = void 0;
    var betaAgentsCreate_js_1 = require_betaAgentsCreate();
    var betaAgentsCreateVersionAlias_js_1 = require_betaAgentsCreateVersionAlias();
    var betaAgentsDelete_js_1 = require_betaAgentsDelete();
    var betaAgentsDeleteVersionAlias_js_1 = require_betaAgentsDeleteVersionAlias();
    var betaAgentsGet_js_1 = require_betaAgentsGet();
    var betaAgentsGetVersion_js_1 = require_betaAgentsGetVersion();
    var betaAgentsList_js_1 = require_betaAgentsList();
    var betaAgentsListVersionAliases_js_1 = require_betaAgentsListVersionAliases();
    var betaAgentsListVersions_js_1 = require_betaAgentsListVersions();
    var betaAgentsUpdate_js_1 = require_betaAgentsUpdate();
    var betaAgentsUpdateVersion_js_1 = require_betaAgentsUpdateVersion();
    var sdks_js_1 = require_sdks();
    var fp_js_1 = require_fp();
    var MistralAgents = class extends sdks_js_1.ClientSDK {
      /**
       * Create a agent that can be used within a conversation.
       *
       * @remarks
       * Create a new agent giving it instructions, tools, description. The agent is then available to be used as a regular assistant in a conversation or as part of an agent pool from which it can be used.
       */
      async create(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, betaAgentsCreate_js_1.betaAgentsCreate)(this, request, options));
      }
      /**
       * List agent entities.
       *
       * @remarks
       * Retrieve a list of agent entities sorted by creation time.
       */
      async list(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, betaAgentsList_js_1.betaAgentsList)(this, request, options));
      }
      /**
       * Retrieve an agent entity.
       *
       * @remarks
       * Given an agent, retrieve an agent entity with its attributes. The agent_version parameter can be an integer version number or a string alias.
       */
      async get(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, betaAgentsGet_js_1.betaAgentsGet)(this, request, options));
      }
      /**
       * Update an agent entity.
       *
       * @remarks
       * Update an agent attributes and create a new version.
       */
      async update(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, betaAgentsUpdate_js_1.betaAgentsUpdate)(this, request, options));
      }
      /**
       * Delete an agent entity.
       */
      async delete(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, betaAgentsDelete_js_1.betaAgentsDelete)(this, request, options));
      }
      /**
       * Update an agent version.
       *
       * @remarks
       * Switch the version of an agent.
       */
      async updateVersion(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, betaAgentsUpdateVersion_js_1.betaAgentsUpdateVersion)(this, request, options));
      }
      /**
       * List all versions of an agent.
       *
       * @remarks
       * Retrieve all versions for a specific agent with full agent context. Supports pagination.
       */
      async listVersions(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, betaAgentsListVersions_js_1.betaAgentsListVersions)(this, request, options));
      }
      /**
       * Retrieve a specific version of an agent.
       *
       * @remarks
       * Get a specific agent version by version number.
       */
      async getVersion(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, betaAgentsGetVersion_js_1.betaAgentsGetVersion)(this, request, options));
      }
      /**
       * Create or update an agent version alias.
       *
       * @remarks
       * Create a new alias or update an existing alias to point to a specific version. Aliases are unique per agent and can be reassigned to different versions.
       */
      async createVersionAlias(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, betaAgentsCreateVersionAlias_js_1.betaAgentsCreateVersionAlias)(this, request, options));
      }
      /**
       * List all aliases for an agent.
       *
       * @remarks
       * Retrieve all version aliases for a specific agent.
       */
      async listVersionAliases(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, betaAgentsListVersionAliases_js_1.betaAgentsListVersionAliases)(this, request, options));
      }
      /**
       * Delete an agent version alias.
       *
       * @remarks
       * Delete an existing alias for an agent.
       */
      async deleteVersionAlias(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, betaAgentsDeleteVersionAlias_js_1.betaAgentsDeleteVersionAlias)(this, request, options));
      }
    };
    exports.MistralAgents = MistralAgents;
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/sdk/beta.js
var require_beta = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/sdk/beta.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Beta = void 0;
    var sdks_js_1 = require_sdks();
    var conversations_js_1 = require_conversations();
    var libraries_js_1 = require_libraries();
    var mistralagents_js_1 = require_mistralagents();
    var Beta3 = class extends sdks_js_1.ClientSDK {
      get conversations() {
        return this._conversations ?? (this._conversations = new conversations_js_1.Conversations(this._options));
      }
      get agents() {
        return this._agents ?? (this._agents = new mistralagents_js_1.MistralAgents(this._options));
      }
      get libraries() {
        return this._libraries ?? (this._libraries = new libraries_js_1.Libraries(this._options));
      }
    };
    exports.Beta = Beta3;
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/chatComplete.js
var require_chatComplete = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/chatComplete.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.chatComplete = chatComplete;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var errors = __importStar(require_errors2());
    var async_js_1 = require_async();
    function chatComplete(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.ChatCompletionRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true });
      const path6 = (0, url_js_1.pathToFunc)("/v1/chat/completions")();
      const headers = new Headers((0, primitives_js_1.compactMap)({
        "Content-Type": "application/json",
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "chat_completion_v1_chat_completions_post",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "POST",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.json(200, components.ChatCompletionResponse$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/chatStream.js
var require_chatStream = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/chatStream.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.chatStream = chatStream;
    var z3 = __importStar(require_v3());
    var encodings_js_1 = require_encodings();
    var event_streams_js_1 = require_event_streams();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var errors = __importStar(require_errors2());
    var async_js_1 = require_async();
    function chatStream(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.ChatCompletionStreamRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true });
      const path6 = (0, url_js_1.pathToFunc)("/v1/chat/completions#stream")();
      const headers = new Headers((0, primitives_js_1.compactMap)({
        "Content-Type": "application/json",
        Accept: "text/event-stream"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "stream_chat",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "POST",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.sse(200, z3.instanceof(ReadableStream).transform((stream2) => {
        return new event_streams_js_1.EventStream(stream2, (rawEvent) => {
          if (rawEvent.data === "[DONE]")
            return { done: true };
          return {
            value: components.CompletionEvent$inboundSchema.parse(rawEvent)
          };
        });
      })), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/Options.js
var require_Options = __commonJS({
  "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/Options.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.getDefaultOptions = exports.defaultOptions = exports.jsonDescription = exports.ignoreOverride = void 0;
    exports.ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use");
    var jsonDescription = (jsonSchema, def) => {
      if (def.description) {
        try {
          return {
            ...jsonSchema,
            ...JSON.parse(def.description)
          };
        } catch {
        }
      }
      return jsonSchema;
    };
    exports.jsonDescription = jsonDescription;
    exports.defaultOptions = {
      name: void 0,
      $refStrategy: "root",
      basePath: ["#"],
      effectStrategy: "input",
      pipeStrategy: "all",
      dateStrategy: "format:date-time",
      mapStrategy: "entries",
      removeAdditionalStrategy: "passthrough",
      allowedAdditionalProperties: true,
      rejectedAdditionalProperties: false,
      definitionPath: "definitions",
      target: "jsonSchema7",
      strictUnions: false,
      definitions: {},
      errorMessages: false,
      markdownDescription: false,
      patternStrategy: "escape",
      applyRegexFlags: false,
      emailStrategy: "format:email",
      base64Strategy: "contentEncoding:base64",
      nameStrategy: "ref",
      openAiAnyTypeName: "OpenAiAnyType"
    };
    var getDefaultOptions2 = (options) => typeof options === "string" ? {
      ...exports.defaultOptions,
      name: options
    } : {
      ...exports.defaultOptions,
      ...options
    };
    exports.getDefaultOptions = getDefaultOptions2;
  }
});

// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/Refs.js
var require_Refs = __commonJS({
  "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/Refs.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.getRefs = void 0;
    var Options_js_1 = require_Options();
    var getRefs2 = (options) => {
      const _options = (0, Options_js_1.getDefaultOptions)(options);
      const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;
      return {
        ..._options,
        flags: { hasReferencedOpenAiAnyType: false },
        currentPath,
        propertyPath: void 0,
        seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [
          def._def,
          {
            def: def._def,
            path: [..._options.basePath, _options.definitionPath, name],
            // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
            jsonSchema: void 0
          }
        ]))
      };
    };
    exports.getRefs = getRefs2;
  }
});

// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/errorMessages.js
var require_errorMessages = __commonJS({
  "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/errorMessages.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.setResponseValueAndErrors = exports.addErrorMessage = void 0;
    function addErrorMessage2(res, key, errorMessage, refs) {
      if (!refs?.errorMessages)
        return;
      if (errorMessage) {
        res.errorMessage = {
          ...res.errorMessage,
          [key]: errorMessage
        };
      }
    }
    exports.addErrorMessage = addErrorMessage2;
    function setResponseValueAndErrors2(res, key, value, errorMessage, refs) {
      res[key] = value;
      addErrorMessage2(res, key, errorMessage, refs);
    }
    exports.setResponseValueAndErrors = setResponseValueAndErrors2;
  }
});

// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/getRelativePath.js
var require_getRelativePath = __commonJS({
  "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/getRelativePath.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.getRelativePath = void 0;
    var getRelativePath2 = (pathA, pathB) => {
      let i7 = 0;
      for (; i7 < pathA.length && i7 < pathB.length; i7++) {
        if (pathA[i7] !== pathB[i7])
          break;
      }
      return [(pathA.length - i7).toString(), ...pathB.slice(i7)].join("/");
    };
    exports.getRelativePath = getRelativePath2;
  }
});

// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/any.js
var require_any = __commonJS({
  "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/any.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.parseAnyDef = void 0;
    var getRelativePath_js_1 = require_getRelativePath();
    function parseAnyDef2(refs) {
      if (refs.target !== "openAi") {
        return {};
      }
      const anyDefinitionPath = [
        ...refs.basePath,
        refs.definitionPath,
        refs.openAiAnyTypeName
      ];
      refs.flags.hasReferencedOpenAiAnyType = true;
      return {
        $ref: refs.$refStrategy === "relative" ? (0, getRelativePath_js_1.getRelativePath)(anyDefinitionPath, refs.currentPath) : anyDefinitionPath.join("/")
      };
    }
    exports.parseAnyDef = parseAnyDef2;
  }
});

// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/array.js
var require_array = __commonJS({
  "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/array.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.parseArrayDef = void 0;
    var v3_1 = require_v3();
    var errorMessages_js_1 = require_errorMessages();
    var parseDef_js_1 = require_parseDef();
    function parseArrayDef2(def, refs) {
      const res = {
        type: "array"
      };
      if (def.type?._def && def.type?._def?.typeName !== v3_1.ZodFirstPartyTypeKind.ZodAny) {
        res.items = (0, parseDef_js_1.parseDef)(def.type._def, {
          ...refs,
          currentPath: [...refs.currentPath, "items"]
        });
      }
      if (def.minLength) {
        (0, errorMessages_js_1.setResponseValueAndErrors)(res, "minItems", def.minLength.value, def.minLength.message, refs);
      }
      if (def.maxLength) {
        (0, errorMessages_js_1.setResponseValueAndErrors)(res, "maxItems", def.maxLength.value, def.maxLength.message, refs);
      }
      if (def.exactLength) {
        (0, errorMessages_js_1.setResponseValueAndErrors)(res, "minItems", def.exactLength.value, def.exactLength.message, refs);
        (0, errorMessages_js_1.setResponseValueAndErrors)(res, "maxItems", def.exactLength.value, def.exactLength.message, refs);
      }
      return res;
    }
    exports.parseArrayDef = parseArrayDef2;
  }
});

// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/bigint.js
var require_bigint = __commonJS({
  "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/bigint.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.parseBigintDef = void 0;
    var errorMessages_js_1 = require_errorMessages();
    function parseBigintDef2(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) {
                (0, errorMessages_js_1.setResponseValueAndErrors)(res, "minimum", check.value, check.message, refs);
              } else {
                (0, errorMessages_js_1.setResponseValueAndErrors)(res, "exclusiveMinimum", check.value, check.message, refs);
              }
            } else {
              if (!check.inclusive) {
                res.exclusiveMinimum = true;
              }
              (0, errorMessages_js_1.setResponseValueAndErrors)(res, "minimum", check.value, check.message, refs);
            }
            break;
          case "max":
            if (refs.target === "jsonSchema7") {
              if (check.inclusive) {
                (0, errorMessages_js_1.setResponseValueAndErrors)(res, "maximum", check.value, check.message, refs);
              } else {
                (0, errorMessages_js_1.setResponseValueAndErrors)(res, "exclusiveMaximum", check.value, check.message, refs);
              }
            } else {
              if (!check.inclusive) {
                res.exclusiveMaximum = true;
              }
              (0, errorMessages_js_1.setResponseValueAndErrors)(res, "maximum", check.value, check.message, refs);
            }
            break;
          case "multipleOf":
            (0, errorMessages_js_1.setResponseValueAndErrors)(res, "multipleOf", check.value, check.message, refs);
            break;
        }
      }
      return res;
    }
    exports.parseBigintDef = parseBigintDef2;
  }
});

// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/boolean.js
var require_boolean = __commonJS({
  "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/boolean.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.parseBooleanDef = void 0;
    function parseBooleanDef2() {
      return {
        type: "boolean"
      };
    }
    exports.parseBooleanDef = parseBooleanDef2;
  }
});

// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/branded.js
var require_branded = __commonJS({
  "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/branded.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.parseBrandedDef = void 0;
    var parseDef_js_1 = require_parseDef();
    function parseBrandedDef2(_def, refs) {
      return (0, parseDef_js_1.parseDef)(_def.type._def, refs);
    }
    exports.parseBrandedDef = parseBrandedDef2;
  }
});

// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/catch.js
var require_catch = __commonJS({
  "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/catch.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.parseCatchDef = void 0;
    var parseDef_js_1 = require_parseDef();
    var parseCatchDef2 = (def, refs) => {
      return (0, parseDef_js_1.parseDef)(def.innerType._def, refs);
    };
    exports.parseCatchDef = parseCatchDef2;
  }
});

// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/date.js
var require_date = __commonJS({
  "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/date.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.parseDateDef = void 0;
    var errorMessages_js_1 = require_errorMessages();
    function parseDateDef2(def, refs, overrideDateStrategy) {
      const strategy = overrideDateStrategy ?? refs.dateStrategy;
      if (Array.isArray(strategy)) {
        return {
          anyOf: strategy.map((item, i7) => parseDateDef2(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 integerDateParser2(def, refs);
      }
    }
    exports.parseDateDef = parseDateDef2;
    var integerDateParser2 = (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":
            (0, errorMessages_js_1.setResponseValueAndErrors)(
              res,
              "minimum",
              check.value,
              // This is in milliseconds
              check.message,
              refs
            );
            break;
          case "max":
            (0, errorMessages_js_1.setResponseValueAndErrors)(
              res,
              "maximum",
              check.value,
              // This is in milliseconds
              check.message,
              refs
            );
            break;
        }
      }
      return res;
    };
  }
});

// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/default.js
var require_default = __commonJS({
  "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/default.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.parseDefaultDef = void 0;
    var parseDef_js_1 = require_parseDef();
    function parseDefaultDef2(_def, refs) {
      return {
        ...(0, parseDef_js_1.parseDef)(_def.innerType._def, refs),
        default: _def.defaultValue()
      };
    }
    exports.parseDefaultDef = parseDefaultDef2;
  }
});

// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/effects.js
var require_effects = __commonJS({
  "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/effects.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.parseEffectsDef = void 0;
    var parseDef_js_1 = require_parseDef();
    var any_js_1 = require_any();
    function parseEffectsDef2(_def, refs) {
      return refs.effectStrategy === "input" ? (0, parseDef_js_1.parseDef)(_def.schema._def, refs) : (0, any_js_1.parseAnyDef)(refs);
    }
    exports.parseEffectsDef = parseEffectsDef2;
  }
});

// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/enum.js
var require_enum = __commonJS({
  "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/enum.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.parseEnumDef = void 0;
    function parseEnumDef2(def) {
      return {
        type: "string",
        enum: Array.from(def.values)
      };
    }
    exports.parseEnumDef = parseEnumDef2;
  }
});

// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/intersection.js
var require_intersection = __commonJS({
  "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/intersection.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.parseIntersectionDef = void 0;
    var parseDef_js_1 = require_parseDef();
    var isJsonSchema7AllOfType2 = (type) => {
      if ("type" in type && type.type === "string")
        return false;
      return "allOf" in type;
    };
    function parseIntersectionDef2(def, refs) {
      const allOf = [
        (0, parseDef_js_1.parseDef)(def.left._def, {
          ...refs,
          currentPath: [...refs.currentPath, "allOf", "0"]
        }),
        (0, parseDef_js_1.parseDef)(def.right._def, {
          ...refs,
          currentPath: [...refs.currentPath, "allOf", "1"]
        })
      ].filter((x2) => !!x2);
      let unevaluatedProperties = refs.target === "jsonSchema2019-09" ? { unevaluatedProperties: false } : void 0;
      const mergedAllOf = [];
      allOf.forEach((schema) => {
        if (isJsonSchema7AllOfType2(schema)) {
          mergedAllOf.push(...schema.allOf);
          if (schema.unevaluatedProperties === void 0) {
            unevaluatedProperties = void 0;
          }
        } else {
          let nestedSchema = schema;
          if ("additionalProperties" in schema && schema.additionalProperties === false) {
            const { additionalProperties, ...rest } = schema;
            nestedSchema = rest;
          } else {
            unevaluatedProperties = void 0;
          }
          mergedAllOf.push(nestedSchema);
        }
      });
      return mergedAllOf.length ? {
        allOf: mergedAllOf,
        ...unevaluatedProperties
      } : void 0;
    }
    exports.parseIntersectionDef = parseIntersectionDef2;
  }
});

// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/literal.js
var require_literal = __commonJS({
  "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/literal.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.parseLiteralDef = void 0;
    function parseLiteralDef2(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
      };
    }
    exports.parseLiteralDef = parseLiteralDef2;
  }
});

// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/string.js
var require_string = __commonJS({
  "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/string.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.parseStringDef = exports.zodPatterns = void 0;
    var errorMessages_js_1 = require_errorMessages();
    var emojiRegex5 = void 0;
    exports.zodPatterns = {
      /**
       * `c` was changed to `[cC]` to replicate /i flag
       */
      cuid: /^[cC][^\s-]{8,}$/,
      cuid2: /^[0-9a-z]+$/,
      ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
      /**
       * `a-z` was added to replicate /i flag
       */
      email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
      /**
       * Constructed a valid Unicode RegExp
       *
       * Lazily instantiate since this type of regex isn't supported
       * in all envs (e.g. React Native).
       *
       * See:
       * https://github.com/colinhacks/zod/issues/2433
       * Fix in Zod:
       * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
       */
      emoji: () => {
        if (emojiRegex5 === void 0) {
          emojiRegex5 = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u");
        }
        return emojiRegex5;
      },
      /**
       * Unused
       */
      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}$/,
      /**
       * Unused
       */
      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])$/,
      /**
       * Unused
       */
      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 parseStringDef2(def, refs) {
      const res = {
        type: "string"
      };
      if (def.checks) {
        for (const check of def.checks) {
          switch (check.kind) {
            case "min":
              (0, errorMessages_js_1.setResponseValueAndErrors)(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs);
              break;
            case "max":
              (0, errorMessages_js_1.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":
                  addFormat2(res, "email", check.message, refs);
                  break;
                case "format:idn-email":
                  addFormat2(res, "idn-email", check.message, refs);
                  break;
                case "pattern:zod":
                  addPattern2(res, exports.zodPatterns.email, check.message, refs);
                  break;
              }
              break;
            case "url":
              addFormat2(res, "uri", check.message, refs);
              break;
            case "uuid":
              addFormat2(res, "uuid", check.message, refs);
              break;
            case "regex":
              addPattern2(res, check.regex, check.message, refs);
              break;
            case "cuid":
              addPattern2(res, exports.zodPatterns.cuid, check.message, refs);
              break;
            case "cuid2":
              addPattern2(res, exports.zodPatterns.cuid2, check.message, refs);
              break;
            case "startsWith":
              addPattern2(res, RegExp(`^${escapeLiteralCheckValue2(check.value, refs)}`), check.message, refs);
              break;
            case "endsWith":
              addPattern2(res, RegExp(`${escapeLiteralCheckValue2(check.value, refs)}$`), check.message, refs);
              break;
            case "datetime":
              addFormat2(res, "date-time", check.message, refs);
              break;
            case "date":
              addFormat2(res, "date", check.message, refs);
              break;
            case "time":
              addFormat2(res, "time", check.message, refs);
              break;
            case "duration":
              addFormat2(res, "duration", check.message, refs);
              break;
            case "length":
              (0, errorMessages_js_1.setResponseValueAndErrors)(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs);
              (0, errorMessages_js_1.setResponseValueAndErrors)(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);
              break;
            case "includes": {
              addPattern2(res, RegExp(escapeLiteralCheckValue2(check.value, refs)), check.message, refs);
              break;
            }
            case "ip": {
              if (check.version !== "v6") {
                addFormat2(res, "ipv4", check.message, refs);
              }
              if (check.version !== "v4") {
                addFormat2(res, "ipv6", check.message, refs);
              }
              break;
            }
            case "base64url":
              addPattern2(res, exports.zodPatterns.base64url, check.message, refs);
              break;
            case "jwt":
              addPattern2(res, exports.zodPatterns.jwt, check.message, refs);
              break;
            case "cidr": {
              if (check.version !== "v6") {
                addPattern2(res, exports.zodPatterns.ipv4Cidr, check.message, refs);
              }
              if (check.version !== "v4") {
                addPattern2(res, exports.zodPatterns.ipv6Cidr, check.message, refs);
              }
              break;
            }
            case "emoji":
              addPattern2(res, exports.zodPatterns.emoji(), check.message, refs);
              break;
            case "ulid": {
              addPattern2(res, exports.zodPatterns.ulid, check.message, refs);
              break;
            }
            case "base64": {
              switch (refs.base64Strategy) {
                case "format:binary": {
                  addFormat2(res, "binary", check.message, refs);
                  break;
                }
                case "contentEncoding:base64": {
                  (0, errorMessages_js_1.setResponseValueAndErrors)(res, "contentEncoding", "base64", check.message, refs);
                  break;
                }
                case "pattern:zod": {
                  addPattern2(res, exports.zodPatterns.base64, check.message, refs);
                  break;
                }
              }
              break;
            }
            case "nanoid": {
              addPattern2(res, exports.zodPatterns.nanoid, check.message, refs);
            }
            case "toLowerCase":
            case "toUpperCase":
            case "trim":
              break;
            default:
              /* @__PURE__ */ ((_3) => {
              })(check);
          }
        }
      }
      return res;
    }
    exports.parseStringDef = parseStringDef2;
    function escapeLiteralCheckValue2(literal, refs) {
      return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric2(literal) : literal;
    }
    var ALPHA_NUMERIC2 = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
    function escapeNonAlphaNumeric2(source) {
      let result = "";
      for (let i7 = 0; i7 < source.length; i7++) {
        if (!ALPHA_NUMERIC2.has(source[i7])) {
          result += "\\";
        }
        result += source[i7];
      }
      return result;
    }
    function addFormat2(schema, value, message, refs) {
      if (schema.format || schema.anyOf?.some((x2) => x2.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 {
        (0, errorMessages_js_1.setResponseValueAndErrors)(schema, "format", value, message, refs);
      }
    }
    function addPattern2(schema, regex, message, refs) {
      if (schema.pattern || schema.allOf?.some((x2) => x2.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: stringifyRegExpWithFlags2(regex, refs),
          ...message && refs.errorMessages && { errorMessage: { pattern: message } }
        });
      } else {
        (0, errorMessages_js_1.setResponseValueAndErrors)(schema, "pattern", stringifyRegExpWithFlags2(regex, refs), message, refs);
      }
    }
    function stringifyRegExpWithFlags2(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")
        // `.` matches newlines
      };
      const source = flags.i ? regex.source.toLowerCase() : regex.source;
      let pattern = "";
      let isEscaped = false;
      let inCharGroup = false;
      let inCharRange = false;
      for (let i7 = 0; i7 < source.length; i7++) {
        if (isEscaped) {
          pattern += source[i7];
          isEscaped = false;
          continue;
        }
        if (flags.i) {
          if (inCharGroup) {
            if (source[i7].match(/[a-z]/)) {
              if (inCharRange) {
                pattern += source[i7];
                pattern += `${source[i7 - 2]}-${source[i7]}`.toUpperCase();
                inCharRange = false;
              } else if (source[i7 + 1] === "-" && source[i7 + 2]?.match(/[a-z]/)) {
                pattern += source[i7];
                inCharRange = true;
              } else {
                pattern += `${source[i7]}${source[i7].toUpperCase()}`;
              }
              continue;
            }
          } else if (source[i7].match(/[a-z]/)) {
            pattern += `[${source[i7]}${source[i7].toUpperCase()}]`;
            continue;
          }
        }
        if (flags.m) {
          if (source[i7] === "^") {
            pattern += `(^|(?<=[\r
]))`;
            continue;
          } else if (source[i7] === "$") {
            pattern += `($|(?=[\r
]))`;
            continue;
          }
        }
        if (flags.s && source[i7] === ".") {
          pattern += inCharGroup ? `${source[i7]}\r
` : `[${source[i7]}\r
]`;
          continue;
        }
        pattern += source[i7];
        if (source[i7] === "\\") {
          isEscaped = true;
        } else if (inCharGroup && source[i7] === "]") {
          inCharGroup = false;
        } else if (!inCharGroup && source[i7] === "[") {
          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;
    }
  }
});

// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/record.js
var require_record = __commonJS({
  "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/record.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.parseRecordDef = void 0;
    var v3_1 = require_v3();
    var parseDef_js_1 = require_parseDef();
    var string_js_1 = require_string();
    var branded_js_1 = require_branded();
    var any_js_1 = require_any();
    function parseRecordDef2(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 === v3_1.ZodFirstPartyTypeKind.ZodEnum) {
        return {
          type: "object",
          required: def.keyType._def.values,
          properties: def.keyType._def.values.reduce((acc, key) => ({
            ...acc,
            [key]: (0, parseDef_js_1.parseDef)(def.valueType._def, {
              ...refs,
              currentPath: [...refs.currentPath, "properties", key]
            }) ?? (0, any_js_1.parseAnyDef)(refs)
          }), {}),
          additionalProperties: refs.rejectedAdditionalProperties
        };
      }
      const schema = {
        type: "object",
        additionalProperties: (0, parseDef_js_1.parseDef)(def.valueType._def, {
          ...refs,
          currentPath: [...refs.currentPath, "additionalProperties"]
        }) ?? refs.allowedAdditionalProperties
      };
      if (refs.target === "openApi3") {
        return schema;
      }
      if (def.keyType?._def.typeName === v3_1.ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) {
        const { type, ...keyType } = (0, string_js_1.parseStringDef)(def.keyType._def, refs);
        return {
          ...schema,
          propertyNames: keyType
        };
      } else if (def.keyType?._def.typeName === v3_1.ZodFirstPartyTypeKind.ZodEnum) {
        return {
          ...schema,
          propertyNames: {
            enum: def.keyType._def.values
          }
        };
      } else if (def.keyType?._def.typeName === v3_1.ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === v3_1.ZodFirstPartyTypeKind.ZodString && def.keyType._def.type._def.checks?.length) {
        const { type, ...keyType } = (0, branded_js_1.parseBrandedDef)(def.keyType._def, refs);
        return {
          ...schema,
          propertyNames: keyType
        };
      }
      return schema;
    }
    exports.parseRecordDef = parseRecordDef2;
  }
});

// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/map.js
var require_map = __commonJS({
  "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/map.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.parseMapDef = void 0;
    var parseDef_js_1 = require_parseDef();
    var record_js_1 = require_record();
    var any_js_1 = require_any();
    function parseMapDef2(def, refs) {
      if (refs.mapStrategy === "record") {
        return (0, record_js_1.parseRecordDef)(def, refs);
      }
      const keys2 = (0, parseDef_js_1.parseDef)(def.keyType._def, {
        ...refs,
        currentPath: [...refs.currentPath, "items", "items", "0"]
      }) || (0, any_js_1.parseAnyDef)(refs);
      const values2 = (0, parseDef_js_1.parseDef)(def.valueType._def, {
        ...refs,
        currentPath: [...refs.currentPath, "items", "items", "1"]
      }) || (0, any_js_1.parseAnyDef)(refs);
      return {
        type: "array",
        maxItems: 125,
        items: {
          type: "array",
          items: [keys2, values2],
          minItems: 2,
          maxItems: 2
        }
      };
    }
    exports.parseMapDef = parseMapDef2;
  }
});

// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/nativeEnum.js
var require_nativeEnum = __commonJS({
  "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/nativeEnum.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.parseNativeEnumDef = void 0;
    function parseNativeEnumDef2(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((values2) => typeof values2)));
      return {
        type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
        enum: actualValues
      };
    }
    exports.parseNativeEnumDef = parseNativeEnumDef2;
  }
});

// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/never.js
var require_never = __commonJS({
  "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/never.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.parseNeverDef = void 0;
    var any_js_1 = require_any();
    function parseNeverDef2(refs) {
      return refs.target === "openAi" ? void 0 : {
        not: (0, any_js_1.parseAnyDef)({
          ...refs,
          currentPath: [...refs.currentPath, "not"]
        })
      };
    }
    exports.parseNeverDef = parseNeverDef2;
  }
});

// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/null.js
var require_null = __commonJS({
  "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/null.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.parseNullDef = void 0;
    function parseNullDef2(refs) {
      return refs.target === "openApi3" ? {
        enum: ["null"],
        nullable: true
      } : {
        type: "null"
      };
    }
    exports.parseNullDef = parseNullDef2;
  }
});

// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/union.js
var require_union = __commonJS({
  "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/union.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.parseUnionDef = exports.primitiveMappings = void 0;
    var parseDef_js_1 = require_parseDef();
    exports.primitiveMappings = {
      ZodString: "string",
      ZodNumber: "number",
      ZodBigInt: "integer",
      ZodBoolean: "boolean",
      ZodNull: "null"
    };
    function parseUnionDef2(def, refs) {
      if (refs.target === "openApi3")
        return asAnyOf2(def, refs);
      const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
      if (options.every((x2) => x2._def.typeName in exports.primitiveMappings && (!x2._def.checks || !x2._def.checks.length))) {
        const types2 = options.reduce((types3, x2) => {
          const type = exports.primitiveMappings[x2._def.typeName];
          return type && !types3.includes(type) ? [...types3, type] : types3;
        }, []);
        return {
          type: types2.length > 1 ? types2 : types2[0]
        };
      } else if (options.every((x2) => x2._def.typeName === "ZodLiteral" && !x2.description)) {
        const types2 = options.reduce((acc, x2) => {
          const type = typeof x2._def.value;
          switch (type) {
            case "string":
            case "number":
            case "boolean":
              return [...acc, type];
            case "bigint":
              return [...acc, "integer"];
            case "object":
              if (x2._def.value === null)
                return [...acc, "null"];
            case "symbol":
            case "undefined":
            case "function":
            default:
              return acc;
          }
        }, []);
        if (types2.length === options.length) {
          const uniqueTypes = types2.filter((x2, i7, a3) => a3.indexOf(x2) === i7);
          return {
            type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
            enum: options.reduce((acc, x2) => {
              return acc.includes(x2._def.value) ? acc : [...acc, x2._def.value];
            }, [])
          };
        }
      } else if (options.every((x2) => x2._def.typeName === "ZodEnum")) {
        return {
          type: "string",
          enum: options.reduce((acc, x2) => [
            ...acc,
            ...x2._def.values.filter((x3) => !acc.includes(x3))
          ], [])
        };
      }
      return asAnyOf2(def, refs);
    }
    exports.parseUnionDef = parseUnionDef2;
    var asAnyOf2 = (def, refs) => {
      const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x2, i7) => (0, parseDef_js_1.parseDef)(x2._def, {
        ...refs,
        currentPath: [...refs.currentPath, "anyOf", `${i7}`]
      })).filter((x2) => !!x2 && (!refs.strictUnions || typeof x2 === "object" && Object.keys(x2).length > 0));
      return anyOf.length ? { anyOf } : void 0;
    };
  }
});

// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/nullable.js
var require_nullable = __commonJS({
  "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/nullable.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.parseNullableDef = void 0;
    var parseDef_js_1 = require_parseDef();
    var union_js_1 = require_union();
    function parseNullableDef2(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: union_js_1.primitiveMappings[def.innerType._def.typeName],
            nullable: true
          };
        }
        return {
          type: [
            union_js_1.primitiveMappings[def.innerType._def.typeName],
            "null"
          ]
        };
      }
      if (refs.target === "openApi3") {
        const base2 = (0, parseDef_js_1.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 = (0, parseDef_js_1.parseDef)(def.innerType._def, {
        ...refs,
        currentPath: [...refs.currentPath, "anyOf", "0"]
      });
      return base && { anyOf: [base, { type: "null" }] };
    }
    exports.parseNullableDef = parseNullableDef2;
  }
});

// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/number.js
var require_number = __commonJS({
  "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/number.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.parseNumberDef = void 0;
    var errorMessages_js_1 = require_errorMessages();
    function parseNumberDef2(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";
            (0, errorMessages_js_1.addErrorMessage)(res, "type", check.message, refs);
            break;
          case "min":
            if (refs.target === "jsonSchema7") {
              if (check.inclusive) {
                (0, errorMessages_js_1.setResponseValueAndErrors)(res, "minimum", check.value, check.message, refs);
              } else {
                (0, errorMessages_js_1.setResponseValueAndErrors)(res, "exclusiveMinimum", check.value, check.message, refs);
              }
            } else {
              if (!check.inclusive) {
                res.exclusiveMinimum = true;
              }
              (0, errorMessages_js_1.setResponseValueAndErrors)(res, "minimum", check.value, check.message, refs);
            }
            break;
          case "max":
            if (refs.target === "jsonSchema7") {
              if (check.inclusive) {
                (0, errorMessages_js_1.setResponseValueAndErrors)(res, "maximum", check.value, check.message, refs);
              } else {
                (0, errorMessages_js_1.setResponseValueAndErrors)(res, "exclusiveMaximum", check.value, check.message, refs);
              }
            } else {
              if (!check.inclusive) {
                res.exclusiveMaximum = true;
              }
              (0, errorMessages_js_1.setResponseValueAndErrors)(res, "maximum", check.value, check.message, refs);
            }
            break;
          case "multipleOf":
            (0, errorMessages_js_1.setResponseValueAndErrors)(res, "multipleOf", check.value, check.message, refs);
            break;
        }
      }
      return res;
    }
    exports.parseNumberDef = parseNumberDef2;
  }
});

// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/object.js
var require_object = __commonJS({
  "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/object.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.parseObjectDef = void 0;
    var parseDef_js_1 = require_parseDef();
    function parseObjectDef2(def, refs) {
      const forceOptionalIntoNullable = refs.target === "openAi";
      const result = {
        type: "object",
        properties: {}
      };
      const required = [];
      const shape = def.shape();
      for (const propName in shape) {
        let propDef = shape[propName];
        if (propDef === void 0 || propDef._def === void 0) {
          continue;
        }
        let propOptional = safeIsOptional2(propDef);
        if (propOptional && forceOptionalIntoNullable) {
          if (propDef._def.typeName === "ZodOptional") {
            propDef = propDef._def.innerType;
          }
          if (!propDef.isNullable()) {
            propDef = propDef.nullable();
          }
          propOptional = false;
        }
        const parsedDef = (0, parseDef_js_1.parseDef)(propDef._def, {
          ...refs,
          currentPath: [...refs.currentPath, "properties", propName],
          propertyPath: [...refs.currentPath, "properties", propName]
        });
        if (parsedDef === void 0) {
          continue;
        }
        result.properties[propName] = parsedDef;
        if (!propOptional) {
          required.push(propName);
        }
      }
      if (required.length) {
        result.required = required;
      }
      const additionalProperties = decideAdditionalProperties2(def, refs);
      if (additionalProperties !== void 0) {
        result.additionalProperties = additionalProperties;
      }
      return result;
    }
    exports.parseObjectDef = parseObjectDef2;
    function decideAdditionalProperties2(def, refs) {
      if (def.catchall._def.typeName !== "ZodNever") {
        return (0, parseDef_js_1.parseDef)(def.catchall._def, {
          ...refs,
          currentPath: [...refs.currentPath, "additionalProperties"]
        });
      }
      switch (def.unknownKeys) {
        case "passthrough":
          return refs.allowedAdditionalProperties;
        case "strict":
          return refs.rejectedAdditionalProperties;
        case "strip":
          return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
      }
    }
    function safeIsOptional2(schema) {
      try {
        return schema.isOptional();
      } catch {
        return true;
      }
    }
  }
});

// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/optional.js
var require_optional = __commonJS({
  "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/optional.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.parseOptionalDef = void 0;
    var parseDef_js_1 = require_parseDef();
    var any_js_1 = require_any();
    var parseOptionalDef2 = (def, refs) => {
      if (refs.currentPath.toString() === refs.propertyPath?.toString()) {
        return (0, parseDef_js_1.parseDef)(def.innerType._def, refs);
      }
      const innerSchema = (0, parseDef_js_1.parseDef)(def.innerType._def, {
        ...refs,
        currentPath: [...refs.currentPath, "anyOf", "1"]
      });
      return innerSchema ? {
        anyOf: [
          {
            not: (0, any_js_1.parseAnyDef)(refs)
          },
          innerSchema
        ]
      } : (0, any_js_1.parseAnyDef)(refs);
    };
    exports.parseOptionalDef = parseOptionalDef2;
  }
});

// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/pipeline.js
var require_pipeline = __commonJS({
  "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/pipeline.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.parsePipelineDef = void 0;
    var parseDef_js_1 = require_parseDef();
    var parsePipelineDef2 = (def, refs) => {
      if (refs.pipeStrategy === "input") {
        return (0, parseDef_js_1.parseDef)(def.in._def, refs);
      } else if (refs.pipeStrategy === "output") {
        return (0, parseDef_js_1.parseDef)(def.out._def, refs);
      }
      const a3 = (0, parseDef_js_1.parseDef)(def.in._def, {
        ...refs,
        currentPath: [...refs.currentPath, "allOf", "0"]
      });
      const b4 = (0, parseDef_js_1.parseDef)(def.out._def, {
        ...refs,
        currentPath: [...refs.currentPath, "allOf", a3 ? "1" : "0"]
      });
      return {
        allOf: [a3, b4].filter((x2) => x2 !== void 0)
      };
    };
    exports.parsePipelineDef = parsePipelineDef2;
  }
});

// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/promise.js
var require_promise = __commonJS({
  "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/promise.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.parsePromiseDef = void 0;
    var parseDef_js_1 = require_parseDef();
    function parsePromiseDef2(def, refs) {
      return (0, parseDef_js_1.parseDef)(def.type._def, refs);
    }
    exports.parsePromiseDef = parsePromiseDef2;
  }
});

// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/set.js
var require_set = __commonJS({
  "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/set.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.parseSetDef = void 0;
    var errorMessages_js_1 = require_errorMessages();
    var parseDef_js_1 = require_parseDef();
    function parseSetDef2(def, refs) {
      const items = (0, parseDef_js_1.parseDef)(def.valueType._def, {
        ...refs,
        currentPath: [...refs.currentPath, "items"]
      });
      const schema = {
        type: "array",
        uniqueItems: true,
        items
      };
      if (def.minSize) {
        (0, errorMessages_js_1.setResponseValueAndErrors)(schema, "minItems", def.minSize.value, def.minSize.message, refs);
      }
      if (def.maxSize) {
        (0, errorMessages_js_1.setResponseValueAndErrors)(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs);
      }
      return schema;
    }
    exports.parseSetDef = parseSetDef2;
  }
});

// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/tuple.js
var require_tuple = __commonJS({
  "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/tuple.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.parseTupleDef = void 0;
    var parseDef_js_1 = require_parseDef();
    function parseTupleDef2(def, refs) {
      if (def.rest) {
        return {
          type: "array",
          minItems: def.items.length,
          items: def.items.map((x2, i7) => (0, parseDef_js_1.parseDef)(x2._def, {
            ...refs,
            currentPath: [...refs.currentPath, "items", `${i7}`]
          })).reduce((acc, x2) => x2 === void 0 ? acc : [...acc, x2], []),
          additionalItems: (0, parseDef_js_1.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((x2, i7) => (0, parseDef_js_1.parseDef)(x2._def, {
            ...refs,
            currentPath: [...refs.currentPath, "items", `${i7}`]
          })).reduce((acc, x2) => x2 === void 0 ? acc : [...acc, x2], [])
        };
      }
    }
    exports.parseTupleDef = parseTupleDef2;
  }
});

// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/undefined.js
var require_undefined = __commonJS({
  "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/undefined.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.parseUndefinedDef = void 0;
    var any_js_1 = require_any();
    function parseUndefinedDef2(refs) {
      return {
        not: (0, any_js_1.parseAnyDef)(refs)
      };
    }
    exports.parseUndefinedDef = parseUndefinedDef2;
  }
});

// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/unknown.js
var require_unknown = __commonJS({
  "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/unknown.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.parseUnknownDef = void 0;
    var any_js_1 = require_any();
    function parseUnknownDef2(refs) {
      return (0, any_js_1.parseAnyDef)(refs);
    }
    exports.parseUnknownDef = parseUnknownDef2;
  }
});

// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/readonly.js
var require_readonly = __commonJS({
  "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/readonly.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.parseReadonlyDef = void 0;
    var parseDef_js_1 = require_parseDef();
    var parseReadonlyDef2 = (def, refs) => {
      return (0, parseDef_js_1.parseDef)(def.innerType._def, refs);
    };
    exports.parseReadonlyDef = parseReadonlyDef2;
  }
});

// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/selectParser.js
var require_selectParser = __commonJS({
  "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/selectParser.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.selectParser = void 0;
    var v3_1 = require_v3();
    var any_js_1 = require_any();
    var array_js_1 = require_array();
    var bigint_js_1 = require_bigint();
    var boolean_js_1 = require_boolean();
    var branded_js_1 = require_branded();
    var catch_js_1 = require_catch();
    var date_js_1 = require_date();
    var default_js_1 = require_default();
    var effects_js_1 = require_effects();
    var enum_js_1 = require_enum();
    var intersection_js_1 = require_intersection();
    var literal_js_1 = require_literal();
    var map_js_1 = require_map();
    var nativeEnum_js_1 = require_nativeEnum();
    var never_js_1 = require_never();
    var null_js_1 = require_null();
    var nullable_js_1 = require_nullable();
    var number_js_1 = require_number();
    var object_js_1 = require_object();
    var optional_js_1 = require_optional();
    var pipeline_js_1 = require_pipeline();
    var promise_js_1 = require_promise();
    var record_js_1 = require_record();
    var set_js_1 = require_set();
    var string_js_1 = require_string();
    var tuple_js_1 = require_tuple();
    var undefined_js_1 = require_undefined();
    var union_js_1 = require_union();
    var unknown_js_1 = require_unknown();
    var readonly_js_1 = require_readonly();
    var selectParser2 = (def, typeName, refs) => {
      switch (typeName) {
        case v3_1.ZodFirstPartyTypeKind.ZodString:
          return (0, string_js_1.parseStringDef)(def, refs);
        case v3_1.ZodFirstPartyTypeKind.ZodNumber:
          return (0, number_js_1.parseNumberDef)(def, refs);
        case v3_1.ZodFirstPartyTypeKind.ZodObject:
          return (0, object_js_1.parseObjectDef)(def, refs);
        case v3_1.ZodFirstPartyTypeKind.ZodBigInt:
          return (0, bigint_js_1.parseBigintDef)(def, refs);
        case v3_1.ZodFirstPartyTypeKind.ZodBoolean:
          return (0, boolean_js_1.parseBooleanDef)();
        case v3_1.ZodFirstPartyTypeKind.ZodDate:
          return (0, date_js_1.parseDateDef)(def, refs);
        case v3_1.ZodFirstPartyTypeKind.ZodUndefined:
          return (0, undefined_js_1.parseUndefinedDef)(refs);
        case v3_1.ZodFirstPartyTypeKind.ZodNull:
          return (0, null_js_1.parseNullDef)(refs);
        case v3_1.ZodFirstPartyTypeKind.ZodArray:
          return (0, array_js_1.parseArrayDef)(def, refs);
        case v3_1.ZodFirstPartyTypeKind.ZodUnion:
        case v3_1.ZodFirstPartyTypeKind.ZodDiscriminatedUnion:
          return (0, union_js_1.parseUnionDef)(def, refs);
        case v3_1.ZodFirstPartyTypeKind.ZodIntersection:
          return (0, intersection_js_1.parseIntersectionDef)(def, refs);
        case v3_1.ZodFirstPartyTypeKind.ZodTuple:
          return (0, tuple_js_1.parseTupleDef)(def, refs);
        case v3_1.ZodFirstPartyTypeKind.ZodRecord:
          return (0, record_js_1.parseRecordDef)(def, refs);
        case v3_1.ZodFirstPartyTypeKind.ZodLiteral:
          return (0, literal_js_1.parseLiteralDef)(def, refs);
        case v3_1.ZodFirstPartyTypeKind.ZodEnum:
          return (0, enum_js_1.parseEnumDef)(def);
        case v3_1.ZodFirstPartyTypeKind.ZodNativeEnum:
          return (0, nativeEnum_js_1.parseNativeEnumDef)(def);
        case v3_1.ZodFirstPartyTypeKind.ZodNullable:
          return (0, nullable_js_1.parseNullableDef)(def, refs);
        case v3_1.ZodFirstPartyTypeKind.ZodOptional:
          return (0, optional_js_1.parseOptionalDef)(def, refs);
        case v3_1.ZodFirstPartyTypeKind.ZodMap:
          return (0, map_js_1.parseMapDef)(def, refs);
        case v3_1.ZodFirstPartyTypeKind.ZodSet:
          return (0, set_js_1.parseSetDef)(def, refs);
        case v3_1.ZodFirstPartyTypeKind.ZodLazy:
          return () => def.getter()._def;
        case v3_1.ZodFirstPartyTypeKind.ZodPromise:
          return (0, promise_js_1.parsePromiseDef)(def, refs);
        case v3_1.ZodFirstPartyTypeKind.ZodNaN:
        case v3_1.ZodFirstPartyTypeKind.ZodNever:
          return (0, never_js_1.parseNeverDef)(refs);
        case v3_1.ZodFirstPartyTypeKind.ZodEffects:
          return (0, effects_js_1.parseEffectsDef)(def, refs);
        case v3_1.ZodFirstPartyTypeKind.ZodAny:
          return (0, any_js_1.parseAnyDef)(refs);
        case v3_1.ZodFirstPartyTypeKind.ZodUnknown:
          return (0, unknown_js_1.parseUnknownDef)(refs);
        case v3_1.ZodFirstPartyTypeKind.ZodDefault:
          return (0, default_js_1.parseDefaultDef)(def, refs);
        case v3_1.ZodFirstPartyTypeKind.ZodBranded:
          return (0, branded_js_1.parseBrandedDef)(def, refs);
        case v3_1.ZodFirstPartyTypeKind.ZodReadonly:
          return (0, readonly_js_1.parseReadonlyDef)(def, refs);
        case v3_1.ZodFirstPartyTypeKind.ZodCatch:
          return (0, catch_js_1.parseCatchDef)(def, refs);
        case v3_1.ZodFirstPartyTypeKind.ZodPipeline:
          return (0, pipeline_js_1.parsePipelineDef)(def, refs);
        case v3_1.ZodFirstPartyTypeKind.ZodFunction:
        case v3_1.ZodFirstPartyTypeKind.ZodVoid:
        case v3_1.ZodFirstPartyTypeKind.ZodSymbol:
          return void 0;
        default:
          return /* @__PURE__ */ ((_3) => void 0)(typeName);
      }
    };
    exports.selectParser = selectParser2;
  }
});

// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parseDef.js
var require_parseDef = __commonJS({
  "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parseDef.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.parseDef = void 0;
    var Options_js_1 = require_Options();
    var selectParser_js_1 = require_selectParser();
    var getRelativePath_js_1 = require_getRelativePath();
    var any_js_1 = require_any();
    function parseDef2(def, refs, forceResolution = false) {
      const seenItem = refs.seen.get(def);
      if (refs.override) {
        const overrideResult = refs.override?.(def, refs, seenItem, forceResolution);
        if (overrideResult !== Options_js_1.ignoreOverride) {
          return overrideResult;
        }
      }
      if (seenItem && !forceResolution) {
        const seenSchema = get$ref2(seenItem, refs);
        if (seenSchema !== void 0) {
          return seenSchema;
        }
      }
      const newItem = { def, path: refs.currentPath, jsonSchema: void 0 };
      refs.seen.set(def, newItem);
      const jsonSchemaOrGetter = (0, selectParser_js_1.selectParser)(def, def.typeName, refs);
      const jsonSchema = typeof jsonSchemaOrGetter === "function" ? parseDef2(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
      if (jsonSchema) {
        addMeta2(def, refs, jsonSchema);
      }
      if (refs.postProcess) {
        const postProcessResult = refs.postProcess(jsonSchema, def, refs);
        newItem.jsonSchema = jsonSchema;
        return postProcessResult;
      }
      newItem.jsonSchema = jsonSchema;
      return jsonSchema;
    }
    exports.parseDef = parseDef2;
    var get$ref2 = (item, refs) => {
      switch (refs.$refStrategy) {
        case "root":
          return { $ref: item.path.join("/") };
        case "relative":
          return { $ref: (0, getRelativePath_js_1.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 (0, any_js_1.parseAnyDef)(refs);
          }
          return refs.$refStrategy === "seen" ? (0, any_js_1.parseAnyDef)(refs) : void 0;
        }
      }
    };
    var addMeta2 = (def, refs, jsonSchema) => {
      if (def.description) {
        jsonSchema.description = def.description;
        if (refs.markdownDescription) {
          jsonSchema.markdownDescription = def.description;
        }
      }
      return jsonSchema;
    };
  }
});

// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parseTypes.js
var require_parseTypes = __commonJS({
  "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parseTypes.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/zodToJsonSchema.js
var require_zodToJsonSchema = __commonJS({
  "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/zodToJsonSchema.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.zodToJsonSchema = void 0;
    var parseDef_js_1 = require_parseDef();
    var Refs_js_1 = require_Refs();
    var any_js_1 = require_any();
    var zodToJsonSchema2 = (schema, options) => {
      const refs = (0, Refs_js_1.getRefs)(options);
      let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name2, schema2]) => ({
        ...acc,
        [name2]: (0, parseDef_js_1.parseDef)(schema2._def, {
          ...refs,
          currentPath: [...refs.basePath, refs.definitionPath, name2]
        }, true) ?? (0, any_js_1.parseAnyDef)(refs)
      }), {}) : void 0;
      const name = typeof options === "string" ? options : options?.nameStrategy === "title" ? void 0 : options?.name;
      const main2 = (0, parseDef_js_1.parseDef)(schema._def, name === void 0 ? refs : {
        ...refs,
        currentPath: [...refs.basePath, refs.definitionPath, name]
      }, false) ?? (0, any_js_1.parseAnyDef)(refs);
      const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
      if (title !== void 0) {
        main2.title = title;
      }
      if (refs.flags.hasReferencedOpenAiAnyType) {
        if (!definitions) {
          definitions = {};
        }
        if (!definitions[refs.openAiAnyTypeName]) {
          definitions[refs.openAiAnyTypeName] = {
            // Skipping "object" as no properties can be defined and additionalProperties must be "false"
            type: ["string", "number", "integer", "boolean", "array", "null"],
            items: {
              $ref: refs.$refStrategy === "relative" ? "1" : [
                ...refs.basePath,
                refs.definitionPath,
                refs.openAiAnyTypeName
              ].join("/")
            }
          };
        }
      }
      const combined = name === void 0 ? definitions ? {
        ...main2,
        [refs.definitionPath]: definitions
      } : main2 : {
        $ref: [
          ...refs.$refStrategy === "relative" ? [] : refs.basePath,
          refs.definitionPath,
          name
        ].join("/"),
        [refs.definitionPath]: {
          ...definitions,
          [name]: main2
        }
      };
      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;
    };
    exports.zodToJsonSchema = zodToJsonSchema2;
  }
});

// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/index.js
var require_cjs = __commonJS({
  "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/index.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __exportStar = exports && exports.__exportStar || function(m4, exports2) {
      for (var p4 in m4) if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4)) __createBinding(exports2, m4, p4);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar(require_Options(), exports);
    __exportStar(require_Refs(), exports);
    __exportStar(require_errorMessages(), exports);
    __exportStar(require_getRelativePath(), exports);
    __exportStar(require_parseDef(), exports);
    __exportStar(require_parseTypes(), exports);
    __exportStar(require_any(), exports);
    __exportStar(require_array(), exports);
    __exportStar(require_bigint(), exports);
    __exportStar(require_boolean(), exports);
    __exportStar(require_branded(), exports);
    __exportStar(require_catch(), exports);
    __exportStar(require_date(), exports);
    __exportStar(require_default(), exports);
    __exportStar(require_effects(), exports);
    __exportStar(require_enum(), exports);
    __exportStar(require_intersection(), exports);
    __exportStar(require_literal(), exports);
    __exportStar(require_map(), exports);
    __exportStar(require_nativeEnum(), exports);
    __exportStar(require_never(), exports);
    __exportStar(require_null(), exports);
    __exportStar(require_nullable(), exports);
    __exportStar(require_number(), exports);
    __exportStar(require_object(), exports);
    __exportStar(require_optional(), exports);
    __exportStar(require_pipeline(), exports);
    __exportStar(require_promise(), exports);
    __exportStar(require_readonly(), exports);
    __exportStar(require_record(), exports);
    __exportStar(require_set(), exports);
    __exportStar(require_string(), exports);
    __exportStar(require_tuple(), exports);
    __exportStar(require_undefined(), exports);
    __exportStar(require_union(), exports);
    __exportStar(require_unknown(), exports);
    __exportStar(require_selectParser(), exports);
    __exportStar(require_zodToJsonSchema(), exports);
    var zodToJsonSchema_js_1 = require_zodToJsonSchema();
    exports.default = zodToJsonSchema_js_1.zodToJsonSchema;
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/extra/structChat.js
var require_structChat = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/extra/structChat.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.transformToChatCompletionRequest = transformToChatCompletionRequest;
    exports.convertToParsedChatCompletionResponse = convertToParsedChatCompletionResponse;
    exports.responseFormatFromZodObject = responseFormatFromZodObject;
    var zod_to_json_schema_1 = require_cjs();
    function transformToChatCompletionRequest(parsedRequest) {
      const { responseFormat, ...rest } = parsedRequest;
      const transformedResponseFormat = responseFormatFromZodObject(responseFormat);
      return {
        ...rest,
        responseFormat: transformedResponseFormat
      };
    }
    function convertToParsedChatCompletionResponse(response, responseFormat) {
      if (response.choices === void 0 || response.choices.length === 0) {
        return {
          ...response,
          choices: response.choices === void 0 ? void 0 : []
        };
      }
      const parsedChoices = [];
      for (const _choice of response.choices) {
        if (_choice.message === null || typeof _choice.message === "undefined") {
          parsedChoices.push({ ..._choice, message: void 0 });
        } else {
          if (_choice.message.content !== null && typeof _choice.message.content !== "undefined" && !Array.isArray(_choice.message.content)) {
            parsedChoices.push({
              ..._choice,
              message: {
                ..._choice.message,
                parsed: responseFormat.safeParse(JSON.parse(_choice.message.content)).data
              }
            });
          }
        }
      }
      return {
        ...response,
        choices: parsedChoices
      };
    }
    function responseFormatFromZodObject(responseFormat) {
      const responseJsonSchema = (0, zod_to_json_schema_1.zodToJsonSchema)(responseFormat);
      const placeholderName = "placeholderName";
      return {
        type: "json_schema",
        jsonSchema: {
          name: placeholderName,
          schemaDefinition: responseJsonSchema,
          strict: true
        }
      };
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/sdk/chat.js
var require_chat = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/sdk/chat.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Chat = void 0;
    var chatComplete_js_1 = require_chatComplete();
    var chatStream_js_1 = require_chatStream();
    var sdks_js_1 = require_sdks();
    var fp_js_1 = require_fp();
    var structChat_js_1 = require_structChat();
    var Chat4 = class extends sdks_js_1.ClientSDK {
      // #region sdk-class-body
      /**
       * Chat Completion with the response parsed in the same format as the input requestFormat.
       *
       * @remarks
       * The response will be parsed back to the initial Zod object passed in the requestFormat field.
       */
      async parse(request, options) {
        const ccr_request = (0, structChat_js_1.transformToChatCompletionRequest)(request);
        const response = await (0, fp_js_1.unwrapAsync)((0, chatComplete_js_1.chatComplete)(this, ccr_request, options));
        const parsed_response = (0, structChat_js_1.convertToParsedChatCompletionResponse)(response, request.responseFormat);
        return parsed_response;
      }
      /**
       * Stream chat completion with a parsed request input.
       *
       * @remarks
       * Unlike the .parse method, this method will return a stream of events containing the JSON response. It will not be parsed back to the initial Zod object.
       * If you need to parse the stream, see the examples/src/async_structured_outputs.ts file.
       */
      async parseStream(request, options) {
        const ccr_request = (0, structChat_js_1.transformToChatCompletionRequest)(request);
        return (0, fp_js_1.unwrapAsync)((0, chatStream_js_1.chatStream)(this, ccr_request, options));
      }
      // #endregion sdk-class-body
      /**
       * Chat Completion
       */
      async complete(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, chatComplete_js_1.chatComplete)(this, request, options));
      }
      /**
       * Stream chat completion
       *
       * @remarks
       * Mistral AI provides the ability to stream responses back to a client in order to allow partial results for certain requests. Tokens will be sent as data-only server-sent events as they become available, with the stream terminated by a data: [DONE] message. Otherwise, the server will hold the request open until the timeout or until completion, with the response containing the full result as JSON.
       */
      async stream(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, chatStream_js_1.chatStream)(this, request, options));
      }
    };
    exports.Chat = Chat4;
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/classifiersClassify.js
var require_classifiersClassify = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/classifiersClassify.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.classifiersClassify = classifiersClassify;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var errors = __importStar(require_errors2());
    var async_js_1 = require_async();
    function classifiersClassify(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.ClassificationRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true });
      const path6 = (0, url_js_1.pathToFunc)("/v1/classifications")();
      const headers = new Headers((0, primitives_js_1.compactMap)({
        "Content-Type": "application/json",
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "classifications_v1_classifications_post",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "POST",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.json(200, components.ClassificationResponse$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/classifiersClassifyChat.js
var require_classifiersClassifyChat = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/classifiersClassifyChat.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.classifiersClassifyChat = classifiersClassifyChat;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var errors = __importStar(require_errors2());
    var async_js_1 = require_async();
    function classifiersClassifyChat(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.ChatClassificationRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true });
      const path6 = (0, url_js_1.pathToFunc)("/v1/chat/classifications")();
      const headers = new Headers((0, primitives_js_1.compactMap)({
        "Content-Type": "application/json",
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "chat_classifications_v1_chat_classifications_post",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "POST",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.json(200, components.ClassificationResponse$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/classifiersModerate.js
var require_classifiersModerate = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/classifiersModerate.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.classifiersModerate = classifiersModerate;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var errors = __importStar(require_errors2());
    var async_js_1 = require_async();
    function classifiersModerate(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.ClassificationRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true });
      const path6 = (0, url_js_1.pathToFunc)("/v1/moderations")();
      const headers = new Headers((0, primitives_js_1.compactMap)({
        "Content-Type": "application/json",
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "moderations_v1_moderations_post",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "POST",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.json(200, components.ModerationResponse$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/classifiersModerateChat.js
var require_classifiersModerateChat = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/classifiersModerateChat.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.classifiersModerateChat = classifiersModerateChat;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var errors = __importStar(require_errors2());
    var async_js_1 = require_async();
    function classifiersModerateChat(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.ChatModerationRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true });
      const path6 = (0, url_js_1.pathToFunc)("/v1/chat/moderations")();
      const headers = new Headers((0, primitives_js_1.compactMap)({
        "Content-Type": "application/json",
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "chat_moderations_v1_chat_moderations_post",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "POST",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.json(200, components.ModerationResponse$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/sdk/classifiers.js
var require_classifiers = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/sdk/classifiers.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Classifiers = void 0;
    var classifiersClassify_js_1 = require_classifiersClassify();
    var classifiersClassifyChat_js_1 = require_classifiersClassifyChat();
    var classifiersModerate_js_1 = require_classifiersModerate();
    var classifiersModerateChat_js_1 = require_classifiersModerateChat();
    var sdks_js_1 = require_sdks();
    var fp_js_1 = require_fp();
    var Classifiers = class extends sdks_js_1.ClientSDK {
      /**
       * Moderations
       */
      async moderate(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, classifiersModerate_js_1.classifiersModerate)(this, request, options));
      }
      /**
       * Chat Moderations
       */
      async moderateChat(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, classifiersModerateChat_js_1.classifiersModerateChat)(this, request, options));
      }
      /**
       * Classifications
       */
      async classify(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, classifiersClassify_js_1.classifiersClassify)(this, request, options));
      }
      /**
       * Chat Classifications
       */
      async classifyChat(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, classifiersClassifyChat_js_1.classifiersClassifyChat)(this, request, options));
      }
    };
    exports.Classifiers = Classifiers;
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/embeddingsCreate.js
var require_embeddingsCreate = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/embeddingsCreate.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.embeddingsCreate = embeddingsCreate;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var errors = __importStar(require_errors2());
    var async_js_1 = require_async();
    function embeddingsCreate(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.EmbeddingRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true });
      const path6 = (0, url_js_1.pathToFunc)("/v1/embeddings")();
      const headers = new Headers((0, primitives_js_1.compactMap)({
        "Content-Type": "application/json",
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "embeddings_v1_embeddings_post",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "POST",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.json(200, components.EmbeddingResponse$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/sdk/embeddings.js
var require_embeddings = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/sdk/embeddings.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Embeddings = void 0;
    var embeddingsCreate_js_1 = require_embeddingsCreate();
    var sdks_js_1 = require_sdks();
    var fp_js_1 = require_fp();
    var Embeddings2 = class extends sdks_js_1.ClientSDK {
      /**
       * Embeddings
       *
       * @remarks
       * Embeddings
       */
      async create(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, embeddingsCreate_js_1.embeddingsCreate)(this, request, options));
      }
    };
    exports.Embeddings = Embeddings2;
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/filesDelete.js
var require_filesDelete = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/filesDelete.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.filesDelete = filesDelete;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function filesDelete(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.FilesApiRoutesDeleteFileRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = null;
      const pathParams = {
        file_id: (0, encodings_js_1.encodeSimple)("file_id", payload.file_id, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/files/{file_id}")(pathParams);
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "files_api_routes_delete_file",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "DELETE",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const [result] = await M4.match(M4.json(200, components.DeleteFileOut$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req);
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/filesDownload.js
var require_filesDownload = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/filesDownload.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.filesDownload = filesDownload;
    var z3 = __importStar(require_v3());
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function filesDownload(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.FilesApiRoutesDownloadFileRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = null;
      const pathParams = {
        file_id: (0, encodings_js_1.encodeSimple)("file_id", payload.file_id, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/files/{file_id}/content")(pathParams);
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "application/octet-stream"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "files_api_routes_download_file",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "GET",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const [result] = await M4.match(M4.stream(200, z3.instanceof(ReadableStream)), M4.fail("4XX"), M4.fail("5XX"))(response, req);
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/filesGetSignedUrl.js
var require_filesGetSignedUrl = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/filesGetSignedUrl.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.filesGetSignedUrl = filesGetSignedUrl;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function filesGetSignedUrl(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.FilesApiRoutesGetSignedUrlRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = null;
      const pathParams = {
        file_id: (0, encodings_js_1.encodeSimple)("file_id", payload.file_id, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/files/{file_id}/url")(pathParams);
      const query = (0, encodings_js_1.encodeFormQuery)({
        "expiry": payload.expiry
      });
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "files_api_routes_get_signed_url",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "GET",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        query,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const [result] = await M4.match(M4.json(200, components.FileSignedURL$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req);
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/filesList.js
var require_filesList = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/filesList.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.filesList = filesList;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function filesList(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.FilesApiRoutesListFilesRequest$outboundSchema.optional().parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = null;
      const path6 = (0, url_js_1.pathToFunc)("/v1/files")();
      const query = (0, encodings_js_1.encodeFormQuery)({
        "include_total": payload?.include_total,
        "mimetypes": payload?.mimetypes,
        "page": payload?.page,
        "page_size": payload?.page_size,
        "purpose": payload?.purpose,
        "sample_type": payload?.sample_type,
        "search": payload?.search,
        "source": payload?.source
      });
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "files_api_routes_list_files",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "GET",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        query,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const [result] = await M4.match(M4.json(200, components.ListFilesOut$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req);
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/filesRetrieve.js
var require_filesRetrieve = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/filesRetrieve.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.filesRetrieve = filesRetrieve;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function filesRetrieve(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.FilesApiRoutesRetrieveFileRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = null;
      const pathParams = {
        file_id: (0, encodings_js_1.encodeSimple)("file_id", payload.file_id, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/files/{file_id}")(pathParams);
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "files_api_routes_retrieve_file",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "GET",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const [result] = await M4.match(M4.json(200, components.RetrieveFileOut$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req);
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/filesUpload.js
var require_filesUpload = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/filesUpload.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.filesUpload = filesUpload;
    var encodings_js_1 = require_encodings();
    var files_js_1 = require_files();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    var blobs_js_1 = require_blobs();
    var streams_js_1 = require_streams();
    function filesUpload(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.FilesApiRoutesUploadFileMultiPartBodyParams$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = new FormData();
      if ((0, blobs_js_1.isBlobLike)(payload.file)) {
        (0, encodings_js_1.appendForm)(body, "file", payload.file);
      } else if ((0, streams_js_1.isReadableStream)(payload.file.content)) {
        const buffer = await (0, files_js_1.readableStreamToArrayBuffer)(payload.file.content);
        const contentType = (0, files_js_1.getContentTypeFromFileName)(payload.file.fileName) || "application/octet-stream";
        const blob = new Blob([buffer], { type: contentType });
        (0, encodings_js_1.appendForm)(body, "file", blob, payload.file.fileName);
      } else {
        const contentType = (0, files_js_1.getContentTypeFromFileName)(payload.file.fileName) || "application/octet-stream";
        (0, encodings_js_1.appendForm)(body, "file", new Blob([payload.file.content], { type: contentType }), payload.file.fileName);
      }
      if (payload.purpose !== void 0) {
        (0, encodings_js_1.appendForm)(body, "purpose", payload.purpose);
      }
      const path6 = (0, url_js_1.pathToFunc)("/v1/files")();
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "files_api_routes_upload_file",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "POST",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const [result] = await M4.match(M4.json(200, components.UploadFileOut$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req);
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/sdk/files.js
var require_files2 = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/sdk/files.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Files = void 0;
    var filesDelete_js_1 = require_filesDelete();
    var filesDownload_js_1 = require_filesDownload();
    var filesGetSignedUrl_js_1 = require_filesGetSignedUrl();
    var filesList_js_1 = require_filesList();
    var filesRetrieve_js_1 = require_filesRetrieve();
    var filesUpload_js_1 = require_filesUpload();
    var sdks_js_1 = require_sdks();
    var fp_js_1 = require_fp();
    var Files6 = class extends sdks_js_1.ClientSDK {
      /**
       * Upload File
       *
       * @remarks
       * Upload a file that can be used across various endpoints.
       *
       * The size of individual files can be a maximum of 512 MB. The Fine-tuning API only supports .jsonl files.
       *
       * Please contact us if you need to increase these storage limits.
       */
      async upload(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, filesUpload_js_1.filesUpload)(this, request, options));
      }
      /**
       * List Files
       *
       * @remarks
       * Returns a list of files that belong to the user's organization.
       */
      async list(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, filesList_js_1.filesList)(this, request, options));
      }
      /**
       * Retrieve File
       *
       * @remarks
       * Returns information about a specific file.
       */
      async retrieve(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, filesRetrieve_js_1.filesRetrieve)(this, request, options));
      }
      /**
       * Delete File
       *
       * @remarks
       * Delete a file.
       */
      async delete(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, filesDelete_js_1.filesDelete)(this, request, options));
      }
      /**
       * Download File
       *
       * @remarks
       * Download a file
       */
      async download(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, filesDownload_js_1.filesDownload)(this, request, options));
      }
      /**
       * Get Signed Url
       */
      async getSignedUrl(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, filesGetSignedUrl_js_1.filesGetSignedUrl)(this, request, options));
      }
    };
    exports.Files = Files6;
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/fimComplete.js
var require_fimComplete = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/fimComplete.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.fimComplete = fimComplete;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var errors = __importStar(require_errors2());
    var async_js_1 = require_async();
    function fimComplete(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.FIMCompletionRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true });
      const path6 = (0, url_js_1.pathToFunc)("/v1/fim/completions")();
      const headers = new Headers((0, primitives_js_1.compactMap)({
        "Content-Type": "application/json",
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "fim_completion_v1_fim_completions_post",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "POST",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.json(200, components.FIMCompletionResponse$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/fimStream.js
var require_fimStream = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/fimStream.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.fimStream = fimStream;
    var z3 = __importStar(require_v3());
    var encodings_js_1 = require_encodings();
    var event_streams_js_1 = require_event_streams();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var errors = __importStar(require_errors2());
    var async_js_1 = require_async();
    function fimStream(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.FIMCompletionStreamRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true });
      const path6 = (0, url_js_1.pathToFunc)("/v1/fim/completions#stream")();
      const headers = new Headers((0, primitives_js_1.compactMap)({
        "Content-Type": "application/json",
        Accept: "text/event-stream"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "stream_fim",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "POST",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.sse(200, z3.instanceof(ReadableStream).transform((stream2) => {
        return new event_streams_js_1.EventStream(stream2, (rawEvent) => {
          if (rawEvent.data === "[DONE]")
            return { done: true };
          return {
            value: components.CompletionEvent$inboundSchema.parse(rawEvent)
          };
        });
      })), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/sdk/fim.js
var require_fim = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/sdk/fim.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Fim = void 0;
    var fimComplete_js_1 = require_fimComplete();
    var fimStream_js_1 = require_fimStream();
    var sdks_js_1 = require_sdks();
    var fp_js_1 = require_fp();
    var Fim = class extends sdks_js_1.ClientSDK {
      /**
       * Fim Completion
       *
       * @remarks
       * FIM completion.
       */
      async complete(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, fimComplete_js_1.fimComplete)(this, request, options));
      }
      /**
       * Stream fim completion
       *
       * @remarks
       * Mistral AI provides the ability to stream responses back to a client in order to allow partial results for certain requests. Tokens will be sent as data-only server-sent events as they become available, with the stream terminated by a data: [DONE] message. Otherwise, the server will hold the request open until the timeout or until completion, with the response containing the full result as JSON.
       */
      async stream(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, fimStream_js_1.fimStream)(this, request, options));
      }
    };
    exports.Fim = Fim;
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/fineTuningJobsCancel.js
var require_fineTuningJobsCancel = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/fineTuningJobsCancel.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.fineTuningJobsCancel = fineTuningJobsCancel;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function fineTuningJobsCancel(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.JobsApiRoutesFineTuningCancelFineTuningJobRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = null;
      const pathParams = {
        job_id: (0, encodings_js_1.encodeSimple)("job_id", payload.job_id, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/fine_tuning/jobs/{job_id}/cancel")(pathParams);
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "jobs_api_routes_fine_tuning_cancel_fine_tuning_job",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "POST",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const [result] = await M4.match(M4.json(200, operations.JobsApiRoutesFineTuningCancelFineTuningJobResponse$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req);
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/fineTuningJobsCreate.js
var require_fineTuningJobsCreate = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/fineTuningJobsCreate.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.fineTuningJobsCreate = fineTuningJobsCreate;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function fineTuningJobsCreate(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.JobIn$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true });
      const path6 = (0, url_js_1.pathToFunc)("/v1/fine_tuning/jobs")();
      const headers = new Headers((0, primitives_js_1.compactMap)({
        "Content-Type": "application/json",
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "jobs_api_routes_fine_tuning_create_fine_tuning_job",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "POST",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const [result] = await M4.match(M4.json(200, operations.JobsApiRoutesFineTuningCreateFineTuningJobResponse$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req);
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/fineTuningJobsGet.js
var require_fineTuningJobsGet = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/fineTuningJobsGet.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.fineTuningJobsGet = fineTuningJobsGet;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function fineTuningJobsGet(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.JobsApiRoutesFineTuningGetFineTuningJobRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = null;
      const pathParams = {
        job_id: (0, encodings_js_1.encodeSimple)("job_id", payload.job_id, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/fine_tuning/jobs/{job_id}")(pathParams);
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "jobs_api_routes_fine_tuning_get_fine_tuning_job",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "GET",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const [result] = await M4.match(M4.json(200, operations.JobsApiRoutesFineTuningGetFineTuningJobResponse$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req);
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/fineTuningJobsList.js
var require_fineTuningJobsList = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/fineTuningJobsList.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.fineTuningJobsList = fineTuningJobsList;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function fineTuningJobsList(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.JobsApiRoutesFineTuningGetFineTuningJobsRequest$outboundSchema.optional().parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = null;
      const path6 = (0, url_js_1.pathToFunc)("/v1/fine_tuning/jobs")();
      const query = (0, encodings_js_1.encodeFormQuery)({
        "created_after": payload?.created_after,
        "created_before": payload?.created_before,
        "created_by_me": payload?.created_by_me,
        "model": payload?.model,
        "page": payload?.page,
        "page_size": payload?.page_size,
        "status": payload?.status,
        "suffix": payload?.suffix,
        "wandb_name": payload?.wandb_name,
        "wandb_project": payload?.wandb_project
      });
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "jobs_api_routes_fine_tuning_get_fine_tuning_jobs",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "GET",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        query,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const [result] = await M4.match(M4.json(200, components.JobsOut$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req);
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/fineTuningJobsStart.js
var require_fineTuningJobsStart = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/fineTuningJobsStart.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.fineTuningJobsStart = fineTuningJobsStart;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function fineTuningJobsStart(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.JobsApiRoutesFineTuningStartFineTuningJobRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = null;
      const pathParams = {
        job_id: (0, encodings_js_1.encodeSimple)("job_id", payload.job_id, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/fine_tuning/jobs/{job_id}/start")(pathParams);
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "jobs_api_routes_fine_tuning_start_fine_tuning_job",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "POST",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const [result] = await M4.match(M4.json(200, operations.JobsApiRoutesFineTuningStartFineTuningJobResponse$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req);
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/sdk/jobs.js
var require_jobs = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/sdk/jobs.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Jobs = void 0;
    var fineTuningJobsCancel_js_1 = require_fineTuningJobsCancel();
    var fineTuningJobsCreate_js_1 = require_fineTuningJobsCreate();
    var fineTuningJobsGet_js_1 = require_fineTuningJobsGet();
    var fineTuningJobsList_js_1 = require_fineTuningJobsList();
    var fineTuningJobsStart_js_1 = require_fineTuningJobsStart();
    var sdks_js_1 = require_sdks();
    var fp_js_1 = require_fp();
    var Jobs2 = class extends sdks_js_1.ClientSDK {
      /**
       * Get Fine Tuning Jobs
       *
       * @remarks
       * Get a list of fine-tuning jobs for your organization and user.
       */
      async list(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, fineTuningJobsList_js_1.fineTuningJobsList)(this, request, options));
      }
      /**
       * Create Fine Tuning Job
       *
       * @remarks
       * Create a new fine-tuning job, it will be queued for processing.
       */
      async create(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, fineTuningJobsCreate_js_1.fineTuningJobsCreate)(this, request, options));
      }
      /**
       * Get Fine Tuning Job
       *
       * @remarks
       * Get a fine-tuned job details by its UUID.
       */
      async get(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, fineTuningJobsGet_js_1.fineTuningJobsGet)(this, request, options));
      }
      /**
       * Cancel Fine Tuning Job
       *
       * @remarks
       * Request the cancellation of a fine tuning job.
       */
      async cancel(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, fineTuningJobsCancel_js_1.fineTuningJobsCancel)(this, request, options));
      }
      /**
       * Start Fine Tuning Job
       *
       * @remarks
       * Request the start of a validated fine tuning job.
       */
      async start(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, fineTuningJobsStart_js_1.fineTuningJobsStart)(this, request, options));
      }
    };
    exports.Jobs = Jobs2;
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/sdk/finetuning.js
var require_finetuning = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/sdk/finetuning.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FineTuning = void 0;
    var sdks_js_1 = require_sdks();
    var jobs_js_1 = require_jobs();
    var FineTuning2 = class extends sdks_js_1.ClientSDK {
      get jobs() {
        return this._jobs ?? (this._jobs = new jobs_js_1.Jobs(this._options));
      }
    };
    exports.FineTuning = FineTuning2;
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/modelsArchive.js
var require_modelsArchive = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/modelsArchive.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.modelsArchive = modelsArchive;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function modelsArchive(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.JobsApiRoutesFineTuningArchiveFineTunedModelRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = null;
      const pathParams = {
        model_id: (0, encodings_js_1.encodeSimple)("model_id", payload.model_id, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/fine_tuning/models/{model_id}/archive")(pathParams);
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "jobs_api_routes_fine_tuning_archive_fine_tuned_model",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "POST",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const [result] = await M4.match(M4.json(200, components.ArchiveFTModelOut$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req);
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/modelsDelete.js
var require_modelsDelete = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/modelsDelete.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.modelsDelete = modelsDelete;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var errors = __importStar(require_errors2());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function modelsDelete(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.DeleteModelV1ModelsModelIdDeleteRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = null;
      const pathParams = {
        model_id: (0, encodings_js_1.encodeSimple)("model_id", payload.model_id, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/models/{model_id}")(pathParams);
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "delete_model_v1_models__model_id__delete",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "DELETE",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.json(200, components.DeleteModelOut$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/modelsList.js
var require_modelsList = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/modelsList.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.modelsList = modelsList;
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var async_js_1 = require_async();
    function modelsList(client, options) {
      return new async_js_1.APIPromise($do(client, options));
    }
    async function $do(client, options) {
      const path6 = (0, url_js_1.pathToFunc)("/v1/models")();
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "list_models_v1_models_get",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "GET",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const [result] = await M4.match(M4.json(200, components.ModelList$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req);
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/modelsRetrieve.js
var require_modelsRetrieve = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/modelsRetrieve.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.modelsRetrieve = modelsRetrieve;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var errors = __importStar(require_errors2());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function modelsRetrieve(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.RetrieveModelV1ModelsModelIdGetRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = null;
      const pathParams = {
        model_id: (0, encodings_js_1.encodeSimple)("model_id", payload.model_id, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/models/{model_id}")(pathParams);
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "retrieve_model_v1_models__model_id__get",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "GET",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.json(200, operations.RetrieveModelV1ModelsModelIdGetResponseRetrieveModelV1ModelsModelIdGet$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/modelsUnarchive.js
var require_modelsUnarchive = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/modelsUnarchive.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.modelsUnarchive = modelsUnarchive;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function modelsUnarchive(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.JobsApiRoutesFineTuningUnarchiveFineTunedModelRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = null;
      const pathParams = {
        model_id: (0, encodings_js_1.encodeSimple)("model_id", payload.model_id, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/fine_tuning/models/{model_id}/archive")(pathParams);
      const headers = new Headers((0, primitives_js_1.compactMap)({
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "jobs_api_routes_fine_tuning_unarchive_fine_tuned_model",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "DELETE",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const [result] = await M4.match(M4.json(200, components.UnarchiveFTModelOut$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req);
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/modelsUpdate.js
var require_modelsUpdate = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/modelsUpdate.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.modelsUpdate = modelsUpdate;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var operations = __importStar(require_operations());
    var async_js_1 = require_async();
    function modelsUpdate(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.JobsApiRoutesFineTuningUpdateFineTunedModelRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = (0, encodings_js_1.encodeJSON)("body", payload.UpdateFTModelIn, { explode: true });
      const pathParams = {
        model_id: (0, encodings_js_1.encodeSimple)("model_id", payload.model_id, {
          explode: false,
          charEncoding: "percent"
        })
      };
      const path6 = (0, url_js_1.pathToFunc)("/v1/fine_tuning/models/{model_id}")(pathParams);
      const headers = new Headers((0, primitives_js_1.compactMap)({
        "Content-Type": "application/json",
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "jobs_api_routes_fine_tuning_update_fine_tuned_model",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "PATCH",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const [result] = await M4.match(M4.json(200, operations.JobsApiRoutesFineTuningUpdateFineTunedModelResponse$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req);
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/sdk/models.js
var require_models = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/sdk/models.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Models = void 0;
    var modelsArchive_js_1 = require_modelsArchive();
    var modelsDelete_js_1 = require_modelsDelete();
    var modelsList_js_1 = require_modelsList();
    var modelsRetrieve_js_1 = require_modelsRetrieve();
    var modelsUnarchive_js_1 = require_modelsUnarchive();
    var modelsUpdate_js_1 = require_modelsUpdate();
    var sdks_js_1 = require_sdks();
    var fp_js_1 = require_fp();
    var Models5 = class extends sdks_js_1.ClientSDK {
      /**
       * List Models
       *
       * @remarks
       * List all models available to the user.
       */
      async list(options) {
        return (0, fp_js_1.unwrapAsync)((0, modelsList_js_1.modelsList)(this, options));
      }
      /**
       * Retrieve Model
       *
       * @remarks
       * Retrieve information about a model.
       */
      async retrieve(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, modelsRetrieve_js_1.modelsRetrieve)(this, request, options));
      }
      /**
       * Delete Model
       *
       * @remarks
       * Delete a fine-tuned model.
       */
      async delete(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, modelsDelete_js_1.modelsDelete)(this, request, options));
      }
      /**
       * Update Fine Tuned Model
       *
       * @remarks
       * Update a model name or description.
       */
      async update(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, modelsUpdate_js_1.modelsUpdate)(this, request, options));
      }
      /**
       * Archive Fine Tuned Model
       *
       * @remarks
       * Archive a fine-tuned model.
       */
      async archive(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, modelsArchive_js_1.modelsArchive)(this, request, options));
      }
      /**
       * Unarchive Fine Tuned Model
       *
       * @remarks
       * Un-archive a fine-tuned model.
       */
      async unarchive(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, modelsUnarchive_js_1.modelsUnarchive)(this, request, options));
      }
    };
    exports.Models = Models5;
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/funcs/ocrProcess.js
var require_ocrProcess = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/funcs/ocrProcess.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ocrProcess = ocrProcess;
    var encodings_js_1 = require_encodings();
    var M4 = __importStar(require_matchers());
    var primitives_js_1 = require_primitives();
    var schemas_js_1 = require_schemas();
    var security_js_1 = require_security();
    var url_js_1 = require_url();
    var components = __importStar(require_components());
    var errors = __importStar(require_errors2());
    var async_js_1 = require_async();
    function ocrProcess(client, request, options) {
      return new async_js_1.APIPromise($do(client, request, options));
    }
    async function $do(client, request, options) {
      const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.OCRRequest$outboundSchema.parse(value), "Input validation failed");
      if (!parsed.ok) {
        return [parsed, { status: "invalid" }];
      }
      const payload = parsed.value;
      const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true });
      const path6 = (0, url_js_1.pathToFunc)("/v1/ocr")();
      const headers = new Headers((0, primitives_js_1.compactMap)({
        "Content-Type": "application/json",
        Accept: "application/json"
      }));
      const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey);
      const securityInput = secConfig == null ? {} : { apiKey: secConfig };
      const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput);
      const context = {
        options: client._options,
        baseURL: options?.serverURL ?? client._baseURL ?? "",
        operationID: "ocr_v1_ocr_post",
        oAuth2Scopes: null,
        resolvedSecurity: requestSecurity,
        securitySource: client._options.apiKey,
        retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
        retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"]
      };
      const requestRes = client._createRequest(context, {
        security: requestSecurity,
        method: "POST",
        baseURL: options?.serverURL,
        path: path6,
        headers,
        body,
        userAgent: client._options.userAgent,
        timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1
      }, options);
      if (!requestRes.ok) {
        return [requestRes, { status: "invalid" }];
      }
      const req = requestRes.value;
      const doResult = await client._do(req, {
        context,
        errorCodes: ["422", "4XX", "5XX"],
        retryConfig: context.retryConfig,
        retryCodes: context.retryCodes
      });
      if (!doResult.ok) {
        return [doResult, { status: "request-error", request: req }];
      }
      const response = doResult.value;
      const responseFields = {
        HttpMeta: { Response: response, Request: req }
      };
      const [result] = await M4.match(M4.json(200, components.OCRResponse$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields });
      if (!result.ok) {
        return [result, { status: "complete", request: req, response }];
      }
      return [result, { status: "complete", request: req, response }];
    }
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/sdk/ocr.js
var require_ocr = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/sdk/ocr.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Ocr = void 0;
    var ocrProcess_js_1 = require_ocrProcess();
    var sdks_js_1 = require_sdks();
    var fp_js_1 = require_fp();
    var Ocr = class extends sdks_js_1.ClientSDK {
      /**
       * OCR
       */
      async process(request, options) {
        return (0, fp_js_1.unwrapAsync)((0, ocrProcess_js_1.ocrProcess)(this, request, options));
      }
    };
    exports.Ocr = Ocr;
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/sdk/sdk.js
var require_sdk = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/sdk/sdk.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Mistral = void 0;
    var sdks_js_1 = require_sdks();
    var agents_js_1 = require_agents();
    var audio_js_1 = require_audio();
    var batch_js_1 = require_batch();
    var beta_js_1 = require_beta();
    var chat_js_1 = require_chat();
    var classifiers_js_1 = require_classifiers();
    var embeddings_js_1 = require_embeddings();
    var files_js_1 = require_files2();
    var fim_js_1 = require_fim();
    var finetuning_js_1 = require_finetuning();
    var models_js_1 = require_models();
    var ocr_js_1 = require_ocr();
    var Mistral2 = class extends sdks_js_1.ClientSDK {
      get models() {
        return this._models ?? (this._models = new models_js_1.Models(this._options));
      }
      get beta() {
        return this._beta ?? (this._beta = new beta_js_1.Beta(this._options));
      }
      get files() {
        return this._files ?? (this._files = new files_js_1.Files(this._options));
      }
      get fineTuning() {
        return this._fineTuning ?? (this._fineTuning = new finetuning_js_1.FineTuning(this._options));
      }
      get batch() {
        return this._batch ?? (this._batch = new batch_js_1.Batch(this._options));
      }
      get chat() {
        return this._chat ?? (this._chat = new chat_js_1.Chat(this._options));
      }
      get fim() {
        return this._fim ?? (this._fim = new fim_js_1.Fim(this._options));
      }
      get agents() {
        return this._agents ?? (this._agents = new agents_js_1.Agents(this._options));
      }
      get embeddings() {
        return this._embeddings ?? (this._embeddings = new embeddings_js_1.Embeddings(this._options));
      }
      get classifiers() {
        return this._classifiers ?? (this._classifiers = new classifiers_js_1.Classifiers(this._options));
      }
      get ocr() {
        return this._ocr ?? (this._ocr = new ocr_js_1.Ocr(this._options));
      }
      get audio() {
        return this._audio ?? (this._audio = new audio_js_1.Audio(this._options));
      }
    };
    exports.Mistral = Mistral2;
  }
});

// ../pi-mono/node_modules/@mistralai/mistralai/index.js
var require_mistralai = __commonJS({
  "../pi-mono/node_modules/@mistralai/mistralai/index.js"(exports) {
    "use strict";
    init_process_shim();
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc = Object.getOwnPropertyDescriptor(m4, k2);
      if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m4[k2];
        } };
      }
      Object.defineProperty(o9, k22, desc);
    }) : (function(o9, m4, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o9[k22] = m4[k2];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) {
      Object.defineProperty(o9, "default", { enumerable: true, value: v4 });
    }) : function(o9, v4) {
      o9["default"] = v4;
    });
    var __exportStar = exports && exports.__exportStar || function(m4, exports2) {
      for (var p4 in m4) if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4)) __createBinding(exports2, m4, p4);
    };
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o9) {
        ownKeys = Object.getOwnPropertyNames || function(o10) {
          var ar = [];
          for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2;
          return ar;
        };
        return ownKeys(o9);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.HTTPClient = exports.files = void 0;
    __exportStar(require_config(), exports);
    exports.files = __importStar(require_files());
    var http_js_1 = require_http();
    Object.defineProperty(exports, "HTTPClient", { enumerable: true, get: function() {
      return http_js_1.HTTPClient;
    } });
    __exportStar(require_sdk(), exports);
  }
});

// ../pi-mono/node_modules/ajv/dist/compile/codegen/code.js
var require_code = __commonJS({
  "../pi-mono/node_modules/ajv/dist/compile/codegen/code.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0;
    var _CodeOrName = class {
    };
    exports._CodeOrName = _CodeOrName;
    exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
    var Name = class extends _CodeOrName {
      constructor(s6) {
        super();
        if (!exports.IDENTIFIER.test(s6))
          throw new Error("CodeGen: name must be a valid identifier");
        this.str = s6;
      }
      toString() {
        return this.str;
      }
      emptyStr() {
        return false;
      }
      get names() {
        return { [this.str]: 1 };
      }
    };
    exports.Name = Name;
    var _Code = class extends _CodeOrName {
      constructor(code) {
        super();
        this._items = typeof code === "string" ? [code] : code;
      }
      toString() {
        return this.str;
      }
      emptyStr() {
        if (this._items.length > 1)
          return false;
        const item = this._items[0];
        return item === "" || item === '""';
      }
      get str() {
        var _a7;
        return (_a7 = this._str) !== null && _a7 !== void 0 ? _a7 : this._str = this._items.reduce((s6, c6) => `${s6}${c6}`, "");
      }
      get names() {
        var _a7;
        return (_a7 = this._names) !== null && _a7 !== void 0 ? _a7 : this._names = this._items.reduce((names, c6) => {
          if (c6 instanceof Name)
            names[c6.str] = (names[c6.str] || 0) + 1;
          return names;
        }, {});
      }
    };
    exports._Code = _Code;
    exports.nil = new _Code("");
    function _3(strs2, ...args) {
      const code = [strs2[0]];
      let i7 = 0;
      while (i7 < args.length) {
        addCodeArg(code, args[i7]);
        code.push(strs2[++i7]);
      }
      return new _Code(code);
    }
    exports._ = _3;
    var plus = new _Code("+");
    function str2(strs2, ...args) {
      const expr = [safeStringify(strs2[0])];
      let i7 = 0;
      while (i7 < args.length) {
        expr.push(plus);
        addCodeArg(expr, args[i7]);
        expr.push(plus, safeStringify(strs2[++i7]));
      }
      optimize(expr);
      return new _Code(expr);
    }
    exports.str = str2;
    function addCodeArg(code, arg) {
      if (arg instanceof _Code)
        code.push(...arg._items);
      else if (arg instanceof Name)
        code.push(arg);
      else
        code.push(interpolate(arg));
    }
    exports.addCodeArg = addCodeArg;
    function optimize(expr) {
      let i7 = 1;
      while (i7 < expr.length - 1) {
        if (expr[i7] === plus) {
          const res = mergeExprItems(expr[i7 - 1], expr[i7 + 1]);
          if (res !== void 0) {
            expr.splice(i7 - 1, 3, res);
            continue;
          }
          expr[i7++] = "+";
        }
        i7++;
      }
    }
    function mergeExprItems(a3, b4) {
      if (b4 === '""')
        return a3;
      if (a3 === '""')
        return b4;
      if (typeof a3 == "string") {
        if (b4 instanceof Name || a3[a3.length - 1] !== '"')
          return;
        if (typeof b4 != "string")
          return `${a3.slice(0, -1)}${b4}"`;
        if (b4[0] === '"')
          return a3.slice(0, -1) + b4.slice(1);
        return;
      }
      if (typeof b4 == "string" && b4[0] === '"' && !(a3 instanceof Name))
        return `"${a3}${b4.slice(1)}`;
      return;
    }
    function strConcat(c1, c22) {
      return c22.emptyStr() ? c1 : c1.emptyStr() ? c22 : str2`${c1}${c22}`;
    }
    exports.strConcat = strConcat;
    function interpolate(x2) {
      return typeof x2 == "number" || typeof x2 == "boolean" || x2 === null ? x2 : safeStringify(Array.isArray(x2) ? x2.join(",") : x2);
    }
    function stringify2(x2) {
      return new _Code(safeStringify(x2));
    }
    exports.stringify = stringify2;
    function safeStringify(x2) {
      return JSON.stringify(x2).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
    }
    exports.safeStringify = safeStringify;
    function getProperty(key) {
      return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _3`[${key}]`;
    }
    exports.getProperty = getProperty;
    function getEsmExportName(key) {
      if (typeof key == "string" && exports.IDENTIFIER.test(key)) {
        return new _Code(`${key}`);
      }
      throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`);
    }
    exports.getEsmExportName = getEsmExportName;
    function regexpCode(rx) {
      return new _Code(rx.toString());
    }
    exports.regexpCode = regexpCode;
  }
});

// ../pi-mono/node_modules/ajv/dist/compile/codegen/scope.js
var require_scope = __commonJS({
  "../pi-mono/node_modules/ajv/dist/compile/codegen/scope.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0;
    var code_1 = require_code();
    var ValueError = class extends Error {
      constructor(name) {
        super(`CodeGen: "code" for ${name} not defined`);
        this.value = name.value;
      }
    };
    var UsedValueState;
    (function(UsedValueState2) {
      UsedValueState2[UsedValueState2["Started"] = 0] = "Started";
      UsedValueState2[UsedValueState2["Completed"] = 1] = "Completed";
    })(UsedValueState || (exports.UsedValueState = UsedValueState = {}));
    exports.varKinds = {
      const: new code_1.Name("const"),
      let: new code_1.Name("let"),
      var: new code_1.Name("var")
    };
    var Scope = class {
      constructor({ prefixes, parent } = {}) {
        this._names = {};
        this._prefixes = prefixes;
        this._parent = parent;
      }
      toName(nameOrPrefix) {
        return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix);
      }
      name(prefix) {
        return new code_1.Name(this._newName(prefix));
      }
      _newName(prefix) {
        const ng = this._names[prefix] || this._nameGroup(prefix);
        return `${prefix}${ng.index++}`;
      }
      _nameGroup(prefix) {
        var _a7, _b;
        if (((_b = (_a7 = this._parent) === null || _a7 === void 0 ? void 0 : _a7._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) {
          throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`);
        }
        return this._names[prefix] = { prefix, index: 0 };
      }
    };
    exports.Scope = Scope;
    var ValueScopeName = class extends code_1.Name {
      constructor(prefix, nameStr) {
        super(nameStr);
        this.prefix = prefix;
      }
      setValue(value, { property, itemIndex }) {
        this.value = value;
        this.scopePath = (0, code_1._)`.${new code_1.Name(property)}[${itemIndex}]`;
      }
    };
    exports.ValueScopeName = ValueScopeName;
    var line = (0, code_1._)`\n`;
    var ValueScope = class extends Scope {
      constructor(opts) {
        super(opts);
        this._values = {};
        this._scope = opts.scope;
        this.opts = { ...opts, _n: opts.lines ? line : code_1.nil };
      }
      get() {
        return this._scope;
      }
      name(prefix) {
        return new ValueScopeName(prefix, this._newName(prefix));
      }
      value(nameOrPrefix, value) {
        var _a7;
        if (value.ref === void 0)
          throw new Error("CodeGen: ref must be passed in value");
        const name = this.toName(nameOrPrefix);
        const { prefix } = name;
        const valueKey = (_a7 = value.key) !== null && _a7 !== void 0 ? _a7 : value.ref;
        let vs = this._values[prefix];
        if (vs) {
          const _name = vs.get(valueKey);
          if (_name)
            return _name;
        } else {
          vs = this._values[prefix] = /* @__PURE__ */ new Map();
        }
        vs.set(valueKey, name);
        const s6 = this._scope[prefix] || (this._scope[prefix] = []);
        const itemIndex = s6.length;
        s6[itemIndex] = value.ref;
        name.setValue(value, { property: prefix, itemIndex });
        return name;
      }
      getValue(prefix, keyOrRef) {
        const vs = this._values[prefix];
        if (!vs)
          return;
        return vs.get(keyOrRef);
      }
      scopeRefs(scopeName, values2 = this._values) {
        return this._reduceValues(values2, (name) => {
          if (name.scopePath === void 0)
            throw new Error(`CodeGen: name "${name}" has no value`);
          return (0, code_1._)`${scopeName}${name.scopePath}`;
        });
      }
      scopeCode(values2 = this._values, usedValues, getCode) {
        return this._reduceValues(values2, (name) => {
          if (name.value === void 0)
            throw new Error(`CodeGen: name "${name}" has no value`);
          return name.value.code;
        }, usedValues, getCode);
      }
      _reduceValues(values2, valueCode, usedValues = {}, getCode) {
        let code = code_1.nil;
        for (const prefix in values2) {
          const vs = values2[prefix];
          if (!vs)
            continue;
          const nameSet = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map();
          vs.forEach((name) => {
            if (nameSet.has(name))
              return;
            nameSet.set(name, UsedValueState.Started);
            let c6 = valueCode(name);
            if (c6) {
              const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const;
              code = (0, code_1._)`${code}${def} ${name} = ${c6};${this.opts._n}`;
            } else if (c6 = getCode === null || getCode === void 0 ? void 0 : getCode(name)) {
              code = (0, code_1._)`${code}${c6}${this.opts._n}`;
            } else {
              throw new ValueError(name);
            }
            nameSet.set(name, UsedValueState.Completed);
          });
        }
        return code;
      }
    };
    exports.ValueScope = ValueScope;
  }
});

// ../pi-mono/node_modules/ajv/dist/compile/codegen/index.js
var require_codegen = __commonJS({
  "../pi-mono/node_modules/ajv/dist/compile/codegen/index.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0;
    var code_1 = require_code();
    var scope_1 = require_scope();
    var code_2 = require_code();
    Object.defineProperty(exports, "_", { enumerable: true, get: function() {
      return code_2._;
    } });
    Object.defineProperty(exports, "str", { enumerable: true, get: function() {
      return code_2.str;
    } });
    Object.defineProperty(exports, "strConcat", { enumerable: true, get: function() {
      return code_2.strConcat;
    } });
    Object.defineProperty(exports, "nil", { enumerable: true, get: function() {
      return code_2.nil;
    } });
    Object.defineProperty(exports, "getProperty", { enumerable: true, get: function() {
      return code_2.getProperty;
    } });
    Object.defineProperty(exports, "stringify", { enumerable: true, get: function() {
      return code_2.stringify;
    } });
    Object.defineProperty(exports, "regexpCode", { enumerable: true, get: function() {
      return code_2.regexpCode;
    } });
    Object.defineProperty(exports, "Name", { enumerable: true, get: function() {
      return code_2.Name;
    } });
    var scope_2 = require_scope();
    Object.defineProperty(exports, "Scope", { enumerable: true, get: function() {
      return scope_2.Scope;
    } });
    Object.defineProperty(exports, "ValueScope", { enumerable: true, get: function() {
      return scope_2.ValueScope;
    } });
    Object.defineProperty(exports, "ValueScopeName", { enumerable: true, get: function() {
      return scope_2.ValueScopeName;
    } });
    Object.defineProperty(exports, "varKinds", { enumerable: true, get: function() {
      return scope_2.varKinds;
    } });
    exports.operators = {
      GT: new code_1._Code(">"),
      GTE: new code_1._Code(">="),
      LT: new code_1._Code("<"),
      LTE: new code_1._Code("<="),
      EQ: new code_1._Code("==="),
      NEQ: new code_1._Code("!=="),
      NOT: new code_1._Code("!"),
      OR: new code_1._Code("||"),
      AND: new code_1._Code("&&"),
      ADD: new code_1._Code("+")
    };
    var Node2 = class {
      optimizeNodes() {
        return this;
      }
      optimizeNames(_names, _constants) {
        return this;
      }
    };
    var Def = class extends Node2 {
      constructor(varKind, name, rhs) {
        super();
        this.varKind = varKind;
        this.name = name;
        this.rhs = rhs;
      }
      render({ es5, _n }) {
        const varKind = es5 ? scope_1.varKinds.var : this.varKind;
        const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`;
        return `${varKind} ${this.name}${rhs};` + _n;
      }
      optimizeNames(names, constants) {
        if (!names[this.name.str])
          return;
        if (this.rhs)
          this.rhs = optimizeExpr(this.rhs, names, constants);
        return this;
      }
      get names() {
        return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {};
      }
    };
    var Assign = class extends Node2 {
      constructor(lhs, rhs, sideEffects) {
        super();
        this.lhs = lhs;
        this.rhs = rhs;
        this.sideEffects = sideEffects;
      }
      render({ _n }) {
        return `${this.lhs} = ${this.rhs};` + _n;
      }
      optimizeNames(names, constants) {
        if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects)
          return;
        this.rhs = optimizeExpr(this.rhs, names, constants);
        return this;
      }
      get names() {
        const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names };
        return addExprNames(names, this.rhs);
      }
    };
    var AssignOp = class extends Assign {
      constructor(lhs, op2, rhs, sideEffects) {
        super(lhs, rhs, sideEffects);
        this.op = op2;
      }
      render({ _n }) {
        return `${this.lhs} ${this.op}= ${this.rhs};` + _n;
      }
    };
    var Label2 = class extends Node2 {
      constructor(label) {
        super();
        this.label = label;
        this.names = {};
      }
      render({ _n }) {
        return `${this.label}:` + _n;
      }
    };
    var Break = class extends Node2 {
      constructor(label) {
        super();
        this.label = label;
        this.names = {};
      }
      render({ _n }) {
        const label = this.label ? ` ${this.label}` : "";
        return `break${label};` + _n;
      }
    };
    var Throw3 = class extends Node2 {
      constructor(error) {
        super();
        this.error = error;
      }
      render({ _n }) {
        return `throw ${this.error};` + _n;
      }
      get names() {
        return this.error.names;
      }
    };
    var AnyCode = class extends Node2 {
      constructor(code) {
        super();
        this.code = code;
      }
      render({ _n }) {
        return `${this.code};` + _n;
      }
      optimizeNodes() {
        return `${this.code}` ? this : void 0;
      }
      optimizeNames(names, constants) {
        this.code = optimizeExpr(this.code, names, constants);
        return this;
      }
      get names() {
        return this.code instanceof code_1._CodeOrName ? this.code.names : {};
      }
    };
    var ParentNode = class extends Node2 {
      constructor(nodes = []) {
        super();
        this.nodes = nodes;
      }
      render(opts) {
        return this.nodes.reduce((code, n7) => code + n7.render(opts), "");
      }
      optimizeNodes() {
        const { nodes } = this;
        let i7 = nodes.length;
        while (i7--) {
          const n7 = nodes[i7].optimizeNodes();
          if (Array.isArray(n7))
            nodes.splice(i7, 1, ...n7);
          else if (n7)
            nodes[i7] = n7;
          else
            nodes.splice(i7, 1);
        }
        return nodes.length > 0 ? this : void 0;
      }
      optimizeNames(names, constants) {
        const { nodes } = this;
        let i7 = nodes.length;
        while (i7--) {
          const n7 = nodes[i7];
          if (n7.optimizeNames(names, constants))
            continue;
          subtractNames(names, n7.names);
          nodes.splice(i7, 1);
        }
        return nodes.length > 0 ? this : void 0;
      }
      get names() {
        return this.nodes.reduce((names, n7) => addNames(names, n7.names), {});
      }
    };
    var BlockNode = class extends ParentNode {
      render(opts) {
        return "{" + opts._n + super.render(opts) + "}" + opts._n;
      }
    };
    var Root = class extends ParentNode {
    };
    var Else = class extends BlockNode {
    };
    Else.kind = "else";
    var If = class _If extends BlockNode {
      constructor(condition, nodes) {
        super(nodes);
        this.condition = condition;
      }
      render(opts) {
        let code = `if(${this.condition})` + super.render(opts);
        if (this.else)
          code += "else " + this.else.render(opts);
        return code;
      }
      optimizeNodes() {
        super.optimizeNodes();
        const cond = this.condition;
        if (cond === true)
          return this.nodes;
        let e9 = this.else;
        if (e9) {
          const ns2 = e9.optimizeNodes();
          e9 = this.else = Array.isArray(ns2) ? new Else(ns2) : ns2;
        }
        if (e9) {
          if (cond === false)
            return e9 instanceof _If ? e9 : e9.nodes;
          if (this.nodes.length)
            return this;
          return new _If(not(cond), e9 instanceof _If ? [e9] : e9.nodes);
        }
        if (cond === false || !this.nodes.length)
          return void 0;
        return this;
      }
      optimizeNames(names, constants) {
        var _a7;
        this.else = (_a7 = this.else) === null || _a7 === void 0 ? void 0 : _a7.optimizeNames(names, constants);
        if (!(super.optimizeNames(names, constants) || this.else))
          return;
        this.condition = optimizeExpr(this.condition, names, constants);
        return this;
      }
      get names() {
        const names = super.names;
        addExprNames(names, this.condition);
        if (this.else)
          addNames(names, this.else.names);
        return names;
      }
    };
    If.kind = "if";
    var For = class extends BlockNode {
    };
    For.kind = "for";
    var ForLoop = class extends For {
      constructor(iteration) {
        super();
        this.iteration = iteration;
      }
      render(opts) {
        return `for(${this.iteration})` + super.render(opts);
      }
      optimizeNames(names, constants) {
        if (!super.optimizeNames(names, constants))
          return;
        this.iteration = optimizeExpr(this.iteration, names, constants);
        return this;
      }
      get names() {
        return addNames(super.names, this.iteration.names);
      }
    };
    var ForRange = class extends For {
      constructor(varKind, name, from, to) {
        super();
        this.varKind = varKind;
        this.name = name;
        this.from = from;
        this.to = to;
      }
      render(opts) {
        const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind;
        const { name, from, to } = this;
        return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts);
      }
      get names() {
        const names = addExprNames(super.names, this.from);
        return addExprNames(names, this.to);
      }
    };
    var ForIter = class extends For {
      constructor(loop, varKind, name, iterable) {
        super();
        this.loop = loop;
        this.varKind = varKind;
        this.name = name;
        this.iterable = iterable;
      }
      render(opts) {
        return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);
      }
      optimizeNames(names, constants) {
        if (!super.optimizeNames(names, constants))
          return;
        this.iterable = optimizeExpr(this.iterable, names, constants);
        return this;
      }
      get names() {
        return addNames(super.names, this.iterable.names);
      }
    };
    var Func = class extends BlockNode {
      constructor(name, args, async) {
        super();
        this.name = name;
        this.args = args;
        this.async = async;
      }
      render(opts) {
        const _async = this.async ? "async " : "";
        return `${_async}function ${this.name}(${this.args})` + super.render(opts);
      }
    };
    Func.kind = "func";
    var Return = class extends ParentNode {
      render(opts) {
        return "return " + super.render(opts);
      }
    };
    Return.kind = "return";
    var Try = class extends BlockNode {
      render(opts) {
        let code = "try" + super.render(opts);
        if (this.catch)
          code += this.catch.render(opts);
        if (this.finally)
          code += this.finally.render(opts);
        return code;
      }
      optimizeNodes() {
        var _a7, _b;
        super.optimizeNodes();
        (_a7 = this.catch) === null || _a7 === void 0 ? void 0 : _a7.optimizeNodes();
        (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes();
        return this;
      }
      optimizeNames(names, constants) {
        var _a7, _b;
        super.optimizeNames(names, constants);
        (_a7 = this.catch) === null || _a7 === void 0 ? void 0 : _a7.optimizeNames(names, constants);
        (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants);
        return this;
      }
      get names() {
        const names = super.names;
        if (this.catch)
          addNames(names, this.catch.names);
        if (this.finally)
          addNames(names, this.finally.names);
        return names;
      }
    };
    var Catch = class extends BlockNode {
      constructor(error) {
        super();
        this.error = error;
      }
      render(opts) {
        return `catch(${this.error})` + super.render(opts);
      }
    };
    Catch.kind = "catch";
    var Finally = class extends BlockNode {
      render(opts) {
        return "finally" + super.render(opts);
      }
    };
    Finally.kind = "finally";
    var CodeGen = class {
      constructor(extScope, opts = {}) {
        this._values = {};
        this._blockStarts = [];
        this._constants = {};
        this.opts = { ...opts, _n: opts.lines ? "\n" : "" };
        this._extScope = extScope;
        this._scope = new scope_1.Scope({ parent: extScope });
        this._nodes = [new Root()];
      }
      toString() {
        return this._root.render(this.opts);
      }
      // returns unique name in the internal scope
      name(prefix) {
        return this._scope.name(prefix);
      }
      // reserves unique name in the external scope
      scopeName(prefix) {
        return this._extScope.name(prefix);
      }
      // reserves unique name in the external scope and assigns value to it
      scopeValue(prefixOrName, value) {
        const name = this._extScope.value(prefixOrName, value);
        const vs = this._values[name.prefix] || (this._values[name.prefix] = /* @__PURE__ */ new Set());
        vs.add(name);
        return name;
      }
      getScopeValue(prefix, keyOrRef) {
        return this._extScope.getValue(prefix, keyOrRef);
      }
      // return code that assigns values in the external scope to the names that are used internally
      // (same names that were returned by gen.scopeName or gen.scopeValue)
      scopeRefs(scopeName) {
        return this._extScope.scopeRefs(scopeName, this._values);
      }
      scopeCode() {
        return this._extScope.scopeCode(this._values);
      }
      _def(varKind, nameOrPrefix, rhs, constant) {
        const name = this._scope.toName(nameOrPrefix);
        if (rhs !== void 0 && constant)
          this._constants[name.str] = rhs;
        this._leafNode(new Def(varKind, name, rhs));
        return name;
      }
      // `const` declaration (`var` in es5 mode)
      const(nameOrPrefix, rhs, _constant) {
        return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant);
      }
      // `let` declaration with optional assignment (`var` in es5 mode)
      let(nameOrPrefix, rhs, _constant) {
        return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant);
      }
      // `var` declaration with optional assignment
      var(nameOrPrefix, rhs, _constant) {
        return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant);
      }
      // assignment code
      assign(lhs, rhs, sideEffects) {
        return this._leafNode(new Assign(lhs, rhs, sideEffects));
      }
      // `+=` code
      add(lhs, rhs) {
        return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs));
      }
      // appends passed SafeExpr to code or executes Block
      code(c6) {
        if (typeof c6 == "function")
          c6();
        else if (c6 !== code_1.nil)
          this._leafNode(new AnyCode(c6));
        return this;
      }
      // returns code for object literal for the passed argument list of key-value pairs
      object(...keyValues) {
        const code = ["{"];
        for (const [key, value] of keyValues) {
          if (code.length > 1)
            code.push(",");
          code.push(key);
          if (key !== value || this.opts.es5) {
            code.push(":");
            (0, code_1.addCodeArg)(code, value);
          }
        }
        code.push("}");
        return new code_1._Code(code);
      }
      // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed)
      if(condition, thenBody, elseBody) {
        this._blockNode(new If(condition));
        if (thenBody && elseBody) {
          this.code(thenBody).else().code(elseBody).endIf();
        } else if (thenBody) {
          this.code(thenBody).endIf();
        } else if (elseBody) {
          throw new Error('CodeGen: "else" body without "then" body');
        }
        return this;
      }
      // `else if` clause - invalid without `if` or after `else` clauses
      elseIf(condition) {
        return this._elseNode(new If(condition));
      }
      // `else` clause - only valid after `if` or `else if` clauses
      else() {
        return this._elseNode(new Else());
      }
      // end `if` statement (needed if gen.if was used only with condition)
      endIf() {
        return this._endBlockNode(If, Else);
      }
      _for(node, forBody) {
        this._blockNode(node);
        if (forBody)
          this.code(forBody).endFor();
        return this;
      }
      // a generic `for` clause (or statement if `forBody` is passed)
      for(iteration, forBody) {
        return this._for(new ForLoop(iteration), forBody);
      }
      // `for` statement for a range of values
      forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) {
        const name = this._scope.toName(nameOrPrefix);
        return this._for(new ForRange(varKind, name, from, to), () => forBody(name));
      }
      // `for-of` statement (in es5 mode replace with a normal for loop)
      forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) {
        const name = this._scope.toName(nameOrPrefix);
        if (this.opts.es5) {
          const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable);
          return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (i7) => {
            this.var(name, (0, code_1._)`${arr}[${i7}]`);
            forBody(name);
          });
        }
        return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name));
      }
      // `for-in` statement.
      // With option `ownProperties` replaced with a `for-of` loop for object keys
      forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) {
        if (this.opts.ownProperties) {
          return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj})`, forBody);
        }
        const name = this._scope.toName(nameOrPrefix);
        return this._for(new ForIter("in", varKind, name, obj), () => forBody(name));
      }
      // end `for` loop
      endFor() {
        return this._endBlockNode(For);
      }
      // `label` statement
      label(label) {
        return this._leafNode(new Label2(label));
      }
      // `break` statement
      break(label) {
        return this._leafNode(new Break(label));
      }
      // `return` statement
      return(value) {
        const node = new Return();
        this._blockNode(node);
        this.code(value);
        if (node.nodes.length !== 1)
          throw new Error('CodeGen: "return" should have one node');
        return this._endBlockNode(Return);
      }
      // `try` statement
      try(tryBody, catchCode, finallyCode) {
        if (!catchCode && !finallyCode)
          throw new Error('CodeGen: "try" without "catch" and "finally"');
        const node = new Try();
        this._blockNode(node);
        this.code(tryBody);
        if (catchCode) {
          const error = this.name("e");
          this._currNode = node.catch = new Catch(error);
          catchCode(error);
        }
        if (finallyCode) {
          this._currNode = node.finally = new Finally();
          this.code(finallyCode);
        }
        return this._endBlockNode(Catch, Finally);
      }
      // `throw` statement
      throw(error) {
        return this._leafNode(new Throw3(error));
      }
      // start self-balancing block
      block(body, nodeCount) {
        this._blockStarts.push(this._nodes.length);
        if (body)
          this.code(body).endBlock(nodeCount);
        return this;
      }
      // end the current self-balancing block
      endBlock(nodeCount) {
        const len = this._blockStarts.pop();
        if (len === void 0)
          throw new Error("CodeGen: not in self-balancing block");
        const toClose = this._nodes.length - len;
        if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) {
          throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`);
        }
        this._nodes.length = len;
        return this;
      }
      // `function` heading (or definition if funcBody is passed)
      func(name, args = code_1.nil, async, funcBody) {
        this._blockNode(new Func(name, args, async));
        if (funcBody)
          this.code(funcBody).endFunc();
        return this;
      }
      // end function definition
      endFunc() {
        return this._endBlockNode(Func);
      }
      optimize(n7 = 1) {
        while (n7-- > 0) {
          this._root.optimizeNodes();
          this._root.optimizeNames(this._root.names, this._constants);
        }
      }
      _leafNode(node) {
        this._currNode.nodes.push(node);
        return this;
      }
      _blockNode(node) {
        this._currNode.nodes.push(node);
        this._nodes.push(node);
      }
      _endBlockNode(N1, N22) {
        const n7 = this._currNode;
        if (n7 instanceof N1 || N22 && n7 instanceof N22) {
          this._nodes.pop();
          return this;
        }
        throw new Error(`CodeGen: not in block "${N22 ? `${N1.kind}/${N22.kind}` : N1.kind}"`);
      }
      _elseNode(node) {
        const n7 = this._currNode;
        if (!(n7 instanceof If)) {
          throw new Error('CodeGen: "else" without "if"');
        }
        this._currNode = n7.else = node;
        return this;
      }
      get _root() {
        return this._nodes[0];
      }
      get _currNode() {
        const ns2 = this._nodes;
        return ns2[ns2.length - 1];
      }
      set _currNode(node) {
        const ns2 = this._nodes;
        ns2[ns2.length - 1] = node;
      }
    };
    exports.CodeGen = CodeGen;
    function addNames(names, from) {
      for (const n7 in from)
        names[n7] = (names[n7] || 0) + (from[n7] || 0);
      return names;
    }
    function addExprNames(names, from) {
      return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names;
    }
    function optimizeExpr(expr, names, constants) {
      if (expr instanceof code_1.Name)
        return replaceName(expr);
      if (!canOptimize(expr))
        return expr;
      return new code_1._Code(expr._items.reduce((items, c6) => {
        if (c6 instanceof code_1.Name)
          c6 = replaceName(c6);
        if (c6 instanceof code_1._Code)
          items.push(...c6._items);
        else
          items.push(c6);
        return items;
      }, []));
      function replaceName(n7) {
        const c6 = constants[n7.str];
        if (c6 === void 0 || names[n7.str] !== 1)
          return n7;
        delete names[n7.str];
        return c6;
      }
      function canOptimize(e9) {
        return e9 instanceof code_1._Code && e9._items.some((c6) => c6 instanceof code_1.Name && names[c6.str] === 1 && constants[c6.str] !== void 0);
      }
    }
    function subtractNames(names, from) {
      for (const n7 in from)
        names[n7] = (names[n7] || 0) - (from[n7] || 0);
    }
    function not(x2) {
      return typeof x2 == "boolean" || typeof x2 == "number" || x2 === null ? !x2 : (0, code_1._)`!${par(x2)}`;
    }
    exports.not = not;
    var andCode = mappend(exports.operators.AND);
    function and(...args) {
      return args.reduce(andCode);
    }
    exports.and = and;
    var orCode = mappend(exports.operators.OR);
    function or(...args) {
      return args.reduce(orCode);
    }
    exports.or = or;
    function mappend(op2) {
      return (x2, y4) => x2 === code_1.nil ? y4 : y4 === code_1.nil ? x2 : (0, code_1._)`${par(x2)} ${op2} ${par(y4)}`;
    }
    function par(x2) {
      return x2 instanceof code_1.Name ? x2 : (0, code_1._)`(${x2})`;
    }
  }
});

// ../pi-mono/node_modules/ajv/dist/compile/util.js
var require_util2 = __commonJS({
  "../pi-mono/node_modules/ajv/dist/compile/util.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0;
    var codegen_1 = require_codegen();
    var code_1 = require_code();
    function toHash(arr) {
      const hash = {};
      for (const item of arr)
        hash[item] = true;
      return hash;
    }
    exports.toHash = toHash;
    function alwaysValidSchema(it, schema) {
      if (typeof schema == "boolean")
        return schema;
      if (Object.keys(schema).length === 0)
        return true;
      checkUnknownRules(it, schema);
      return !schemaHasRules(schema, it.self.RULES.all);
    }
    exports.alwaysValidSchema = alwaysValidSchema;
    function checkUnknownRules(it, schema = it.schema) {
      const { opts, self: self2 } = it;
      if (!opts.strictSchema)
        return;
      if (typeof schema === "boolean")
        return;
      const rules = self2.RULES.keywords;
      for (const key in schema) {
        if (!rules[key])
          checkStrictMode(it, `unknown keyword: "${key}"`);
      }
    }
    exports.checkUnknownRules = checkUnknownRules;
    function schemaHasRules(schema, rules) {
      if (typeof schema == "boolean")
        return !schema;
      for (const key in schema)
        if (rules[key])
          return true;
      return false;
    }
    exports.schemaHasRules = schemaHasRules;
    function schemaHasRulesButRef(schema, RULES) {
      if (typeof schema == "boolean")
        return !schema;
      for (const key in schema)
        if (key !== "$ref" && RULES.all[key])
          return true;
      return false;
    }
    exports.schemaHasRulesButRef = schemaHasRulesButRef;
    function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) {
      if (!$data) {
        if (typeof schema == "number" || typeof schema == "boolean")
          return schema;
        if (typeof schema == "string")
          return (0, codegen_1._)`${schema}`;
      }
      return (0, codegen_1._)`${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`;
    }
    exports.schemaRefOrVal = schemaRefOrVal;
    function unescapeFragment(str2) {
      return unescapeJsonPointer(decodeURIComponent(str2));
    }
    exports.unescapeFragment = unescapeFragment;
    function escapeFragment(str2) {
      return encodeURIComponent(escapeJsonPointer(str2));
    }
    exports.escapeFragment = escapeFragment;
    function escapeJsonPointer(str2) {
      if (typeof str2 == "number")
        return `${str2}`;
      return str2.replace(/~/g, "~0").replace(/\//g, "~1");
    }
    exports.escapeJsonPointer = escapeJsonPointer;
    function unescapeJsonPointer(str2) {
      return str2.replace(/~1/g, "/").replace(/~0/g, "~");
    }
    exports.unescapeJsonPointer = unescapeJsonPointer;
    function eachItem(xs, f4) {
      if (Array.isArray(xs)) {
        for (const x2 of xs)
          f4(x2);
      } else {
        f4(xs);
      }
    }
    exports.eachItem = eachItem;
    function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues: mergeValues3, resultToName }) {
      return (gen, from, to, toName) => {
        const res = to === void 0 ? from : to instanceof codegen_1.Name ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) : from instanceof codegen_1.Name ? (mergeToName(gen, to, from), from) : mergeValues3(from, to);
        return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res;
      };
    }
    exports.mergeEvaluated = {
      props: makeMergeEvaluated({
        mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => {
          gen.if((0, codegen_1._)`${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._)`${to} || {}`).code((0, codegen_1._)`Object.assign(${to}, ${from})`));
        }),
        mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => {
          if (from === true) {
            gen.assign(to, true);
          } else {
            gen.assign(to, (0, codegen_1._)`${to} || {}`);
            setEvaluated(gen, to, from);
          }
        }),
        mergeValues: (from, to) => from === true ? true : { ...from, ...to },
        resultToName: evaluatedPropsToName
      }),
      items: makeMergeEvaluated({
        mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._)`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)),
        mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._)`${to} > ${from} ? ${to} : ${from}`)),
        mergeValues: (from, to) => from === true ? true : Math.max(from, to),
        resultToName: (gen, items) => gen.var("items", items)
      })
    };
    function evaluatedPropsToName(gen, ps) {
      if (ps === true)
        return gen.var("props", true);
      const props = gen.var("props", (0, codegen_1._)`{}`);
      if (ps !== void 0)
        setEvaluated(gen, props, ps);
      return props;
    }
    exports.evaluatedPropsToName = evaluatedPropsToName;
    function setEvaluated(gen, props, ps) {
      Object.keys(ps).forEach((p4) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p4)}`, true));
    }
    exports.setEvaluated = setEvaluated;
    var snippets = {};
    function useFunc(gen, f4) {
      return gen.scopeValue("func", {
        ref: f4,
        code: snippets[f4.code] || (snippets[f4.code] = new code_1._Code(f4.code))
      });
    }
    exports.useFunc = useFunc;
    var Type4;
    (function(Type5) {
      Type5[Type5["Num"] = 0] = "Num";
      Type5[Type5["Str"] = 1] = "Str";
    })(Type4 || (exports.Type = Type4 = {}));
    function getErrorPath(dataProp, dataPropType, jsPropertySyntax) {
      if (dataProp instanceof codegen_1.Name) {
        const isNumber2 = dataPropType === Type4.Num;
        return jsPropertySyntax ? isNumber2 ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber2 ? (0, codegen_1._)`"/" + ${dataProp}` : (0, codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`;
      }
      return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp);
    }
    exports.getErrorPath = getErrorPath;
    function checkStrictMode(it, msg, mode = it.opts.strictSchema) {
      if (!mode)
        return;
      msg = `strict mode: ${msg}`;
      if (mode === true)
        throw new Error(msg);
      it.self.logger.warn(msg);
    }
    exports.checkStrictMode = checkStrictMode;
  }
});

// ../pi-mono/node_modules/ajv/dist/compile/names.js
var require_names = __commonJS({
  "../pi-mono/node_modules/ajv/dist/compile/names.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var names = {
      // validation function arguments
      data: new codegen_1.Name("data"),
      // data passed to validation function
      // args passed from referencing schema
      valCxt: new codegen_1.Name("valCxt"),
      // validation/data context - should not be used directly, it is destructured to the names below
      instancePath: new codegen_1.Name("instancePath"),
      parentData: new codegen_1.Name("parentData"),
      parentDataProperty: new codegen_1.Name("parentDataProperty"),
      rootData: new codegen_1.Name("rootData"),
      // root data - same as the data passed to the first/top validation function
      dynamicAnchors: new codegen_1.Name("dynamicAnchors"),
      // used to support recursiveRef and dynamicRef
      // function scoped variables
      vErrors: new codegen_1.Name("vErrors"),
      // null or array of validation errors
      errors: new codegen_1.Name("errors"),
      // counter of validation errors
      this: new codegen_1.Name("this"),
      // "globals"
      self: new codegen_1.Name("self"),
      scope: new codegen_1.Name("scope"),
      // JTD serialize/parse name for JSON string and position
      json: new codegen_1.Name("json"),
      jsonPos: new codegen_1.Name("jsonPos"),
      jsonLen: new codegen_1.Name("jsonLen"),
      jsonPart: new codegen_1.Name("jsonPart")
    };
    exports.default = names;
  }
});

// ../pi-mono/node_modules/ajv/dist/compile/errors.js
var require_errors3 = __commonJS({
  "../pi-mono/node_modules/ajv/dist/compile/errors.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0;
    var codegen_1 = require_codegen();
    var util_1 = require_util2();
    var names_1 = require_names();
    exports.keywordError = {
      message: ({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation`
    };
    exports.keyword$DataError = {
      message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)`
    };
    function reportError(cxt, error = exports.keywordError, errorPaths, overrideAllErrors) {
      const { it } = cxt;
      const { gen, compositeRule, allErrors } = it;
      const errObj = errorObjectCode(cxt, error, errorPaths);
      if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) {
        addError(gen, errObj);
      } else {
        returnErrors(it, (0, codegen_1._)`[${errObj}]`);
      }
    }
    exports.reportError = reportError;
    function reportExtraError(cxt, error = exports.keywordError, errorPaths) {
      const { it } = cxt;
      const { gen, compositeRule, allErrors } = it;
      const errObj = errorObjectCode(cxt, error, errorPaths);
      addError(gen, errObj);
      if (!(compositeRule || allErrors)) {
        returnErrors(it, names_1.default.vErrors);
      }
    }
    exports.reportExtraError = reportExtraError;
    function resetErrorsCount(gen, errsCount) {
      gen.assign(names_1.default.errors, errsCount);
      gen.if((0, codegen_1._)`${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._)`${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null)));
    }
    exports.resetErrorsCount = resetErrorsCount;
    function extendErrors({ gen, keyword, schemaValue, data, errsCount, it }) {
      if (errsCount === void 0)
        throw new Error("ajv implementation error");
      const err = gen.name("err");
      gen.forRange("i", errsCount, names_1.default.errors, (i7) => {
        gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i7}]`);
        gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath)));
        gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`);
        if (it.opts.verbose) {
          gen.assign((0, codegen_1._)`${err}.schema`, schemaValue);
          gen.assign((0, codegen_1._)`${err}.data`, data);
        }
      });
    }
    exports.extendErrors = extendErrors;
    function addError(gen, errObj) {
      const err = gen.const("err", errObj);
      gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err})`);
      gen.code((0, codegen_1._)`${names_1.default.errors}++`);
    }
    function returnErrors(it, errs) {
      const { gen, validateName, schemaEnv } = it;
      if (schemaEnv.$async) {
        gen.throw((0, codegen_1._)`new ${it.ValidationError}(${errs})`);
      } else {
        gen.assign((0, codegen_1._)`${validateName}.errors`, errs);
        gen.return(false);
      }
    }
    var E3 = {
      keyword: new codegen_1.Name("keyword"),
      schemaPath: new codegen_1.Name("schemaPath"),
      // also used in JTD errors
      params: new codegen_1.Name("params"),
      propertyName: new codegen_1.Name("propertyName"),
      message: new codegen_1.Name("message"),
      schema: new codegen_1.Name("schema"),
      parentSchema: new codegen_1.Name("parentSchema")
    };
    function errorObjectCode(cxt, error, errorPaths) {
      const { createErrors } = cxt.it;
      if (createErrors === false)
        return (0, codegen_1._)`{}`;
      return errorObject(cxt, error, errorPaths);
    }
    function errorObject(cxt, error, errorPaths = {}) {
      const { gen, it } = cxt;
      const keyValues = [
        errorInstancePath(it, errorPaths),
        errorSchemaPath(cxt, errorPaths)
      ];
      extraErrorProps(cxt, error, keyValues);
      return gen.object(...keyValues);
    }
    function errorInstancePath({ errorPath }, { instancePath }) {
      const instPath = instancePath ? (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` : errorPath;
      return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)];
    }
    function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) {
      let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str)`${errSchemaPath}/${keyword}`;
      if (schemaPath) {
        schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`;
      }
      return [E3.schemaPath, schPath];
    }
    function extraErrorProps(cxt, { params, message }, keyValues) {
      const { keyword, data, schemaValue, it } = cxt;
      const { opts, propertyName, topSchemaRef, schemaPath } = it;
      keyValues.push([E3.keyword, keyword], [E3.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]);
      if (opts.messages) {
        keyValues.push([E3.message, typeof message == "function" ? message(cxt) : message]);
      }
      if (opts.verbose) {
        keyValues.push([E3.schema, schemaValue], [E3.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]);
      }
      if (propertyName)
        keyValues.push([E3.propertyName, propertyName]);
    }
  }
});

// ../pi-mono/node_modules/ajv/dist/compile/validate/boolSchema.js
var require_boolSchema = __commonJS({
  "../pi-mono/node_modules/ajv/dist/compile/validate/boolSchema.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0;
    var errors_1 = require_errors3();
    var codegen_1 = require_codegen();
    var names_1 = require_names();
    var boolError = {
      message: "boolean schema is false"
    };
    function topBoolOrEmptySchema(it) {
      const { gen, schema, validateName } = it;
      if (schema === false) {
        falseSchemaError(it, false);
      } else if (typeof schema == "object" && schema.$async === true) {
        gen.return(names_1.default.data);
      } else {
        gen.assign((0, codegen_1._)`${validateName}.errors`, null);
        gen.return(true);
      }
    }
    exports.topBoolOrEmptySchema = topBoolOrEmptySchema;
    function boolOrEmptySchema(it, valid) {
      const { gen, schema } = it;
      if (schema === false) {
        gen.var(valid, false);
        falseSchemaError(it);
      } else {
        gen.var(valid, true);
      }
    }
    exports.boolOrEmptySchema = boolOrEmptySchema;
    function falseSchemaError(it, overrideAllErrors) {
      const { gen, data } = it;
      const cxt = {
        gen,
        keyword: "false schema",
        data,
        schema: false,
        schemaCode: false,
        schemaValue: false,
        params: {},
        it
      };
      (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors);
    }
  }
});

// ../pi-mono/node_modules/ajv/dist/compile/rules.js
var require_rules = __commonJS({
  "../pi-mono/node_modules/ajv/dist/compile/rules.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.getRules = exports.isJSONType = void 0;
    var _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"];
    var jsonTypes = new Set(_jsonTypes);
    function isJSONType(x2) {
      return typeof x2 == "string" && jsonTypes.has(x2);
    }
    exports.isJSONType = isJSONType;
    function getRules() {
      const groups = {
        number: { type: "number", rules: [] },
        string: { type: "string", rules: [] },
        array: { type: "array", rules: [] },
        object: { type: "object", rules: [] }
      };
      return {
        types: { ...groups, integer: true, boolean: true, null: true },
        rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object],
        post: { rules: [] },
        all: {},
        keywords: {}
      };
    }
    exports.getRules = getRules;
  }
});

// ../pi-mono/node_modules/ajv/dist/compile/validate/applicability.js
var require_applicability = __commonJS({
  "../pi-mono/node_modules/ajv/dist/compile/validate/applicability.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0;
    function schemaHasRulesForType({ schema, self: self2 }, type) {
      const group = self2.RULES.types[type];
      return group && group !== true && shouldUseGroup(schema, group);
    }
    exports.schemaHasRulesForType = schemaHasRulesForType;
    function shouldUseGroup(schema, group) {
      return group.rules.some((rule) => shouldUseRule(schema, rule));
    }
    exports.shouldUseGroup = shouldUseGroup;
    function shouldUseRule(schema, rule) {
      var _a7;
      return schema[rule.keyword] !== void 0 || ((_a7 = rule.definition.implements) === null || _a7 === void 0 ? void 0 : _a7.some((kwd) => schema[kwd] !== void 0));
    }
    exports.shouldUseRule = shouldUseRule;
  }
});

// ../pi-mono/node_modules/ajv/dist/compile/validate/dataType.js
var require_dataType = __commonJS({
  "../pi-mono/node_modules/ajv/dist/compile/validate/dataType.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0;
    var rules_1 = require_rules();
    var applicability_1 = require_applicability();
    var errors_1 = require_errors3();
    var codegen_1 = require_codegen();
    var util_1 = require_util2();
    var DataType;
    (function(DataType2) {
      DataType2[DataType2["Correct"] = 0] = "Correct";
      DataType2[DataType2["Wrong"] = 1] = "Wrong";
    })(DataType || (exports.DataType = DataType = {}));
    function getSchemaTypes(schema) {
      const types2 = getJSONTypes(schema.type);
      const hasNull = types2.includes("null");
      if (hasNull) {
        if (schema.nullable === false)
          throw new Error("type: null contradicts nullable: false");
      } else {
        if (!types2.length && schema.nullable !== void 0) {
          throw new Error('"nullable" cannot be used without "type"');
        }
        if (schema.nullable === true)
          types2.push("null");
      }
      return types2;
    }
    exports.getSchemaTypes = getSchemaTypes;
    function getJSONTypes(ts) {
      const types2 = Array.isArray(ts) ? ts : ts ? [ts] : [];
      if (types2.every(rules_1.isJSONType))
        return types2;
      throw new Error("type must be JSONType or JSONType[]: " + types2.join(","));
    }
    exports.getJSONTypes = getJSONTypes;
    function coerceAndCheckDataType(it, types2) {
      const { gen, data, opts } = it;
      const coerceTo = coerceToTypes(types2, opts.coerceTypes);
      const checkTypes = types2.length > 0 && !(coerceTo.length === 0 && types2.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types2[0]));
      if (checkTypes) {
        const wrongType = checkDataTypes(types2, data, opts.strictNumbers, DataType.Wrong);
        gen.if(wrongType, () => {
          if (coerceTo.length)
            coerceData(it, types2, coerceTo);
          else
            reportTypeError(it);
        });
      }
      return checkTypes;
    }
    exports.coerceAndCheckDataType = coerceAndCheckDataType;
    var COERCIBLE = /* @__PURE__ */ new Set(["string", "number", "integer", "boolean", "null"]);
    function coerceToTypes(types2, coerceTypes) {
      return coerceTypes ? types2.filter((t6) => COERCIBLE.has(t6) || coerceTypes === "array" && t6 === "array") : [];
    }
    function coerceData(it, types2, coerceTo) {
      const { gen, data, opts } = it;
      const dataType = gen.let("dataType", (0, codegen_1._)`typeof ${data}`);
      const coerced = gen.let("coerced", (0, codegen_1._)`undefined`);
      if (opts.coerceTypes === "array") {
        gen.if((0, codegen_1._)`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen.assign(data, (0, codegen_1._)`${data}[0]`).assign(dataType, (0, codegen_1._)`typeof ${data}`).if(checkDataTypes(types2, data, opts.strictNumbers), () => gen.assign(coerced, data)));
      }
      gen.if((0, codegen_1._)`${coerced} !== undefined`);
      for (const t6 of coerceTo) {
        if (COERCIBLE.has(t6) || t6 === "array" && opts.coerceTypes === "array") {
          coerceSpecificType(t6);
        }
      }
      gen.else();
      reportTypeError(it);
      gen.endIf();
      gen.if((0, codegen_1._)`${coerced} !== undefined`, () => {
        gen.assign(data, coerced);
        assignParentData(it, coerced);
      });
      function coerceSpecificType(t6) {
        switch (t6) {
          case "string":
            gen.elseIf((0, codegen_1._)`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced, (0, codegen_1._)`"" + ${data}`).elseIf((0, codegen_1._)`${data} === null`).assign(coerced, (0, codegen_1._)`""`);
            return;
          case "number":
            gen.elseIf((0, codegen_1._)`${dataType} == "boolean" || ${data} === null
              || (${dataType} == "string" && ${data} && ${data} == +${data})`).assign(coerced, (0, codegen_1._)`+${data}`);
            return;
          case "integer":
            gen.elseIf((0, codegen_1._)`${dataType} === "boolean" || ${data} === null
              || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`).assign(coerced, (0, codegen_1._)`+${data}`);
            return;
          case "boolean":
            gen.elseIf((0, codegen_1._)`${data} === "false" || ${data} === 0 || ${data} === null`).assign(coerced, false).elseIf((0, codegen_1._)`${data} === "true" || ${data} === 1`).assign(coerced, true);
            return;
          case "null":
            gen.elseIf((0, codegen_1._)`${data} === "" || ${data} === 0 || ${data} === false`);
            gen.assign(coerced, null);
            return;
          case "array":
            gen.elseIf((0, codegen_1._)`${dataType} === "string" || ${dataType} === "number"
              || ${dataType} === "boolean" || ${data} === null`).assign(coerced, (0, codegen_1._)`[${data}]`);
        }
      }
    }
    function assignParentData({ gen, parentData, parentDataProperty }, expr) {
      gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr));
    }
    function checkDataType(dataType, data, strictNums, correct = DataType.Correct) {
      const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ;
      let cond;
      switch (dataType) {
        case "null":
          return (0, codegen_1._)`${data} ${EQ} null`;
        case "array":
          cond = (0, codegen_1._)`Array.isArray(${data})`;
          break;
        case "object":
          cond = (0, codegen_1._)`${data} && typeof ${data} == "object" && !Array.isArray(${data})`;
          break;
        case "integer":
          cond = numCond((0, codegen_1._)`!(${data} % 1) && !isNaN(${data})`);
          break;
        case "number":
          cond = numCond();
          break;
        default:
          return (0, codegen_1._)`typeof ${data} ${EQ} ${dataType}`;
      }
      return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond);
      function numCond(_cond = codegen_1.nil) {
        return (0, codegen_1.and)((0, codegen_1._)`typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._)`isFinite(${data})` : codegen_1.nil);
      }
    }
    exports.checkDataType = checkDataType;
    function checkDataTypes(dataTypes, data, strictNums, correct) {
      if (dataTypes.length === 1) {
        return checkDataType(dataTypes[0], data, strictNums, correct);
      }
      let cond;
      const types2 = (0, util_1.toHash)(dataTypes);
      if (types2.array && types2.object) {
        const notObj = (0, codegen_1._)`typeof ${data} != "object"`;
        cond = types2.null ? notObj : (0, codegen_1._)`!${data} || ${notObj}`;
        delete types2.null;
        delete types2.array;
        delete types2.object;
      } else {
        cond = codegen_1.nil;
      }
      if (types2.number)
        delete types2.integer;
      for (const t6 in types2)
        cond = (0, codegen_1.and)(cond, checkDataType(t6, data, strictNums, correct));
      return cond;
    }
    exports.checkDataTypes = checkDataTypes;
    var typeError = {
      message: ({ schema }) => `must be ${schema}`,
      params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._)`{type: ${schema}}` : (0, codegen_1._)`{type: ${schemaValue}}`
    };
    function reportTypeError(it) {
      const cxt = getTypeErrorContext(it);
      (0, errors_1.reportError)(cxt, typeError);
    }
    exports.reportTypeError = reportTypeError;
    function getTypeErrorContext(it) {
      const { gen, data, schema } = it;
      const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type");
      return {
        gen,
        keyword: "type",
        data,
        schema: schema.type,
        schemaCode,
        schemaValue: schemaCode,
        parentSchema: schema,
        params: {},
        it
      };
    }
  }
});

// ../pi-mono/node_modules/ajv/dist/compile/validate/defaults.js
var require_defaults = __commonJS({
  "../pi-mono/node_modules/ajv/dist/compile/validate/defaults.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.assignDefaults = void 0;
    var codegen_1 = require_codegen();
    var util_1 = require_util2();
    function assignDefaults(it, ty) {
      const { properties, items } = it.schema;
      if (ty === "object" && properties) {
        for (const key in properties) {
          assignDefault(it, key, properties[key].default);
        }
      } else if (ty === "array" && Array.isArray(items)) {
        items.forEach((sch, i7) => assignDefault(it, i7, sch.default));
      }
    }
    exports.assignDefaults = assignDefaults;
    function assignDefault(it, prop, defaultValue) {
      const { gen, compositeRule, data, opts } = it;
      if (defaultValue === void 0)
        return;
      const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`;
      if (compositeRule) {
        (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`);
        return;
      }
      let condition = (0, codegen_1._)`${childData} === undefined`;
      if (opts.useDefaults === "empty") {
        condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`;
      }
      gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`);
    }
  }
});

// ../pi-mono/node_modules/ajv/dist/vocabularies/code.js
var require_code2 = __commonJS({
  "../pi-mono/node_modules/ajv/dist/vocabularies/code.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0;
    var codegen_1 = require_codegen();
    var util_1 = require_util2();
    var names_1 = require_names();
    var util_2 = require_util2();
    function checkReportMissingProp(cxt, prop) {
      const { gen, data, it } = cxt;
      gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => {
        cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true);
        cxt.error();
      });
    }
    exports.checkReportMissingProp = checkReportMissingProp;
    function checkMissingProp({ gen, data, it: { opts } }, properties, missing) {
      return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`)));
    }
    exports.checkMissingProp = checkMissingProp;
    function reportMissingProp(cxt, missing) {
      cxt.setParams({ missingProperty: missing }, true);
      cxt.error();
    }
    exports.reportMissingProp = reportMissingProp;
    function hasPropFunc(gen) {
      return gen.scopeValue("func", {
        // eslint-disable-next-line @typescript-eslint/unbound-method
        ref: Object.prototype.hasOwnProperty,
        code: (0, codegen_1._)`Object.prototype.hasOwnProperty`
      });
    }
    exports.hasPropFunc = hasPropFunc;
    function isOwnProperty(gen, data, property) {
      return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`;
    }
    exports.isOwnProperty = isOwnProperty;
    function propertyInData(gen, data, property, ownProperties) {
      const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} !== undefined`;
      return ownProperties ? (0, codegen_1._)`${cond} && ${isOwnProperty(gen, data, property)}` : cond;
    }
    exports.propertyInData = propertyInData;
    function noPropertyInData(gen, data, property, ownProperties) {
      const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} === undefined`;
      return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond;
    }
    exports.noPropertyInData = noPropertyInData;
    function allSchemaProperties(schemaMap) {
      return schemaMap ? Object.keys(schemaMap).filter((p4) => p4 !== "__proto__") : [];
    }
    exports.allSchemaProperties = allSchemaProperties;
    function schemaProperties(it, schemaMap) {
      return allSchemaProperties(schemaMap).filter((p4) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p4]));
    }
    exports.schemaProperties = schemaProperties;
    function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) {
      const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data;
      const valCxt = [
        [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)],
        [names_1.default.parentData, it.parentData],
        [names_1.default.parentDataProperty, it.parentDataProperty],
        [names_1.default.rootData, names_1.default.rootData]
      ];
      if (it.opts.dynamicRef)
        valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]);
      const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`;
      return context !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context}, ${args})` : (0, codegen_1._)`${func}(${args})`;
    }
    exports.callValidateCode = callValidateCode;
    var newRegExp = (0, codegen_1._)`new RegExp`;
    function usePattern({ gen, it: { opts } }, pattern) {
      const u5 = opts.unicodeRegExp ? "u" : "";
      const { regExp } = opts.code;
      const rx = regExp(pattern, u5);
      return gen.scopeValue("pattern", {
        key: rx.toString(),
        ref: rx,
        code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u5})`
      });
    }
    exports.usePattern = usePattern;
    function validateArray(cxt) {
      const { gen, data, keyword, it } = cxt;
      const valid = gen.name("valid");
      if (it.allErrors) {
        const validArr = gen.let("valid", true);
        validateItems(() => gen.assign(validArr, false));
        return validArr;
      }
      gen.var(valid, true);
      validateItems(() => gen.break());
      return valid;
      function validateItems(notValid) {
        const len = gen.const("len", (0, codegen_1._)`${data}.length`);
        gen.forRange("i", 0, len, (i7) => {
          cxt.subschema({
            keyword,
            dataProp: i7,
            dataPropType: util_1.Type.Num
          }, valid);
          gen.if((0, codegen_1.not)(valid), notValid);
        });
      }
    }
    exports.validateArray = validateArray;
    function validateUnion(cxt) {
      const { gen, schema, keyword, it } = cxt;
      if (!Array.isArray(schema))
        throw new Error("ajv implementation error");
      const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch));
      if (alwaysValid && !it.opts.unevaluated)
        return;
      const valid = gen.let("valid", false);
      const schValid = gen.name("_valid");
      gen.block(() => schema.forEach((_sch, i7) => {
        const schCxt = cxt.subschema({
          keyword,
          schemaProp: i7,
          compositeRule: true
        }, schValid);
        gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`);
        const merged = cxt.mergeValidEvaluated(schCxt, schValid);
        if (!merged)
          gen.if((0, codegen_1.not)(valid));
      }));
      cxt.result(valid, () => cxt.reset(), () => cxt.error(true));
    }
    exports.validateUnion = validateUnion;
  }
});

// ../pi-mono/node_modules/ajv/dist/compile/validate/keyword.js
var require_keyword = __commonJS({
  "../pi-mono/node_modules/ajv/dist/compile/validate/keyword.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0;
    var codegen_1 = require_codegen();
    var names_1 = require_names();
    var code_1 = require_code2();
    var errors_1 = require_errors3();
    function macroKeywordCode(cxt, def) {
      const { gen, keyword, schema, parentSchema, it } = cxt;
      const macroSchema = def.macro.call(it.self, schema, parentSchema, it);
      const schemaRef = useKeyword(gen, keyword, macroSchema);
      if (it.opts.validateSchema !== false)
        it.self.validateSchema(macroSchema, true);
      const valid = gen.name("valid");
      cxt.subschema({
        schema: macroSchema,
        schemaPath: codegen_1.nil,
        errSchemaPath: `${it.errSchemaPath}/${keyword}`,
        topSchemaRef: schemaRef,
        compositeRule: true
      }, valid);
      cxt.pass(valid, () => cxt.error(true));
    }
    exports.macroKeywordCode = macroKeywordCode;
    function funcKeywordCode(cxt, def) {
      var _a7;
      const { gen, keyword, schema, parentSchema, $data, it } = cxt;
      checkAsyncKeyword(it, def);
      const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate;
      const validateRef = useKeyword(gen, keyword, validate);
      const valid = gen.let("valid");
      cxt.block$data(valid, validateKeyword);
      cxt.ok((_a7 = def.valid) !== null && _a7 !== void 0 ? _a7 : valid);
      function validateKeyword() {
        if (def.errors === false) {
          assignValid();
          if (def.modifying)
            modifyData(cxt);
          reportErrs(() => cxt.error());
        } else {
          const ruleErrs = def.async ? validateAsync() : validateSync();
          if (def.modifying)
            modifyData(cxt);
          reportErrs(() => addErrs(cxt, ruleErrs));
        }
      }
      function validateAsync() {
        const ruleErrs = gen.let("ruleErrs", null);
        gen.try(() => assignValid((0, codegen_1._)`await `), (e9) => gen.assign(valid, false).if((0, codegen_1._)`${e9} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e9}.errors`), () => gen.throw(e9)));
        return ruleErrs;
      }
      function validateSync() {
        const validateErrs = (0, codegen_1._)`${validateRef}.errors`;
        gen.assign(validateErrs, null);
        assignValid(codegen_1.nil);
        return validateErrs;
      }
      function assignValid(_await = def.async ? (0, codegen_1._)`await ` : codegen_1.nil) {
        const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self;
        const passSchema = !("compile" in def && !$data || def.schema === false);
        gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying);
      }
      function reportErrs(errors) {
        var _a8;
        gen.if((0, codegen_1.not)((_a8 = def.valid) !== null && _a8 !== void 0 ? _a8 : valid), errors);
      }
    }
    exports.funcKeywordCode = funcKeywordCode;
    function modifyData(cxt) {
      const { gen, data, it } = cxt;
      gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._)`${it.parentData}[${it.parentDataProperty}]`));
    }
    function addErrs(cxt, errs) {
      const { gen } = cxt;
      gen.if((0, codegen_1._)`Array.isArray(${errs})`, () => {
        gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`);
        (0, errors_1.extendErrors)(cxt);
      }, () => cxt.error());
    }
    function checkAsyncKeyword({ schemaEnv }, def) {
      if (def.async && !schemaEnv.$async)
        throw new Error("async keyword in sync schema");
    }
    function useKeyword(gen, keyword, result) {
      if (result === void 0)
        throw new Error(`keyword "${keyword}" failed to compile`);
      return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) });
    }
    function validSchemaType(schema, schemaType, allowUndefined = false) {
      return !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || allowUndefined && typeof schema == "undefined");
    }
    exports.validSchemaType = validSchemaType;
    function validateKeywordUsage({ schema, opts, self: self2, errSchemaPath }, def, keyword) {
      if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) {
        throw new Error("ajv implementation error");
      }
      const deps = def.dependencies;
      if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) {
        throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`);
      }
      if (def.validateSchema) {
        const valid = def.validateSchema(schema[keyword]);
        if (!valid) {
          const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self2.errorsText(def.validateSchema.errors);
          if (opts.validateSchema === "log")
            self2.logger.error(msg);
          else
            throw new Error(msg);
        }
      }
    }
    exports.validateKeywordUsage = validateKeywordUsage;
  }
});

// ../pi-mono/node_modules/ajv/dist/compile/validate/subschema.js
var require_subschema = __commonJS({
  "../pi-mono/node_modules/ajv/dist/compile/validate/subschema.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0;
    var codegen_1 = require_codegen();
    var util_1 = require_util2();
    function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) {
      if (keyword !== void 0 && schema !== void 0) {
        throw new Error('both "keyword" and "schema" passed, only one allowed');
      }
      if (keyword !== void 0) {
        const sch = it.schema[keyword];
        return schemaProp === void 0 ? {
          schema: sch,
          schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`,
          errSchemaPath: `${it.errSchemaPath}/${keyword}`
        } : {
          schema: sch[schemaProp],
          schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`,
          errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}`
        };
      }
      if (schema !== void 0) {
        if (schemaPath === void 0 || errSchemaPath === void 0 || topSchemaRef === void 0) {
          throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');
        }
        return {
          schema,
          schemaPath,
          topSchemaRef,
          errSchemaPath
        };
      }
      throw new Error('either "keyword" or "schema" must be passed');
    }
    exports.getSubschema = getSubschema;
    function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) {
      if (data !== void 0 && dataProp !== void 0) {
        throw new Error('both "data" and "dataProp" passed, only one allowed');
      }
      const { gen } = it;
      if (dataProp !== void 0) {
        const { errorPath, dataPathArr, opts } = it;
        const nextData = gen.let("data", (0, codegen_1._)`${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true);
        dataContextProps(nextData);
        subschema.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`;
        subschema.parentDataProperty = (0, codegen_1._)`${dataProp}`;
        subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty];
      }
      if (data !== void 0) {
        const nextData = data instanceof codegen_1.Name ? data : gen.let("data", data, true);
        dataContextProps(nextData);
        if (propertyName !== void 0)
          subschema.propertyName = propertyName;
      }
      if (dataTypes)
        subschema.dataTypes = dataTypes;
      function dataContextProps(_nextData) {
        subschema.data = _nextData;
        subschema.dataLevel = it.dataLevel + 1;
        subschema.dataTypes = [];
        it.definedProperties = /* @__PURE__ */ new Set();
        subschema.parentData = it.data;
        subschema.dataNames = [...it.dataNames, _nextData];
      }
    }
    exports.extendSubschemaData = extendSubschemaData;
    function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) {
      if (compositeRule !== void 0)
        subschema.compositeRule = compositeRule;
      if (createErrors !== void 0)
        subschema.createErrors = createErrors;
      if (allErrors !== void 0)
        subschema.allErrors = allErrors;
      subschema.jtdDiscriminator = jtdDiscriminator;
      subschema.jtdMetadata = jtdMetadata;
    }
    exports.extendSubschemaMode = extendSubschemaMode;
  }
});

// ../pi-mono/node_modules/fast-deep-equal/index.js
var require_fast_deep_equal = __commonJS({
  "../pi-mono/node_modules/fast-deep-equal/index.js"(exports, module) {
    "use strict";
    init_process_shim();
    module.exports = function equal(a3, b4) {
      if (a3 === b4) return true;
      if (a3 && b4 && typeof a3 == "object" && typeof b4 == "object") {
        if (a3.constructor !== b4.constructor) return false;
        var length, i7, keys2;
        if (Array.isArray(a3)) {
          length = a3.length;
          if (length != b4.length) return false;
          for (i7 = length; i7-- !== 0; )
            if (!equal(a3[i7], b4[i7])) return false;
          return true;
        }
        if (a3.constructor === RegExp) return a3.source === b4.source && a3.flags === b4.flags;
        if (a3.valueOf !== Object.prototype.valueOf) return a3.valueOf() === b4.valueOf();
        if (a3.toString !== Object.prototype.toString) return a3.toString() === b4.toString();
        keys2 = Object.keys(a3);
        length = keys2.length;
        if (length !== Object.keys(b4).length) return false;
        for (i7 = length; i7-- !== 0; )
          if (!Object.prototype.hasOwnProperty.call(b4, keys2[i7])) return false;
        for (i7 = length; i7-- !== 0; ) {
          var key = keys2[i7];
          if (!equal(a3[key], b4[key])) return false;
        }
        return true;
      }
      return a3 !== a3 && b4 !== b4;
    };
  }
});

// ../pi-mono/node_modules/json-schema-traverse/index.js
var require_json_schema_traverse = __commonJS({
  "../pi-mono/node_modules/json-schema-traverse/index.js"(exports, module) {
    "use strict";
    init_process_shim();
    var traverse2 = module.exports = function(schema, opts, cb) {
      if (typeof opts == "function") {
        cb = opts;
        opts = {};
      }
      cb = opts.cb || cb;
      var pre = typeof cb == "function" ? cb : cb.pre || function() {
      };
      var post2 = cb.post || function() {
      };
      _traverse(opts, pre, post2, schema, "", schema);
    };
    traverse2.keywords = {
      additionalItems: true,
      items: true,
      contains: true,
      additionalProperties: true,
      propertyNames: true,
      not: true,
      if: true,
      then: true,
      else: true
    };
    traverse2.arrayKeywords = {
      items: true,
      allOf: true,
      anyOf: true,
      oneOf: true
    };
    traverse2.propsKeywords = {
      $defs: true,
      definitions: true,
      properties: true,
      patternProperties: true,
      dependencies: true
    };
    traverse2.skipKeywords = {
      default: true,
      enum: true,
      const: true,
      required: true,
      maximum: true,
      minimum: true,
      exclusiveMaximum: true,
      exclusiveMinimum: true,
      multipleOf: true,
      maxLength: true,
      minLength: true,
      pattern: true,
      format: true,
      maxItems: true,
      minItems: true,
      uniqueItems: true,
      maxProperties: true,
      minProperties: true
    };
    function _traverse(opts, pre, post2, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
      if (schema && typeof schema == "object" && !Array.isArray(schema)) {
        pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
        for (var key in schema) {
          var sch = schema[key];
          if (Array.isArray(sch)) {
            if (key in traverse2.arrayKeywords) {
              for (var i7 = 0; i7 < sch.length; i7++)
                _traverse(opts, pre, post2, sch[i7], jsonPtr + "/" + key + "/" + i7, rootSchema, jsonPtr, key, schema, i7);
            }
          } else if (key in traverse2.propsKeywords) {
            if (sch && typeof sch == "object") {
              for (var prop in sch)
                _traverse(opts, pre, post2, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);
            }
          } else if (key in traverse2.keywords || opts.allKeys && !(key in traverse2.skipKeywords)) {
            _traverse(opts, pre, post2, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema);
          }
        }
        post2(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
      }
    }
    function escapeJsonPtr(str2) {
      return str2.replace(/~/g, "~0").replace(/\//g, "~1");
    }
  }
});

// ../pi-mono/node_modules/ajv/dist/compile/resolve.js
var require_resolve = __commonJS({
  "../pi-mono/node_modules/ajv/dist/compile/resolve.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0;
    var util_1 = require_util2();
    var equal = require_fast_deep_equal();
    var traverse2 = require_json_schema_traverse();
    var SIMPLE_INLINED = /* @__PURE__ */ new Set([
      "type",
      "format",
      "pattern",
      "maxLength",
      "minLength",
      "maxProperties",
      "minProperties",
      "maxItems",
      "minItems",
      "maximum",
      "minimum",
      "uniqueItems",
      "multipleOf",
      "required",
      "enum",
      "const"
    ]);
    function inlineRef(schema, limit2 = true) {
      if (typeof schema == "boolean")
        return true;
      if (limit2 === true)
        return !hasRef(schema);
      if (!limit2)
        return false;
      return countKeys(schema) <= limit2;
    }
    exports.inlineRef = inlineRef;
    var REF_KEYWORDS = /* @__PURE__ */ new Set([
      "$ref",
      "$recursiveRef",
      "$recursiveAnchor",
      "$dynamicRef",
      "$dynamicAnchor"
    ]);
    function hasRef(schema) {
      for (const key in schema) {
        if (REF_KEYWORDS.has(key))
          return true;
        const sch = schema[key];
        if (Array.isArray(sch) && sch.some(hasRef))
          return true;
        if (typeof sch == "object" && hasRef(sch))
          return true;
      }
      return false;
    }
    function countKeys(schema) {
      let count = 0;
      for (const key in schema) {
        if (key === "$ref")
          return Infinity;
        count++;
        if (SIMPLE_INLINED.has(key))
          continue;
        if (typeof schema[key] == "object") {
          (0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch));
        }
        if (count === Infinity)
          return Infinity;
      }
      return count;
    }
    function getFullPath(resolver, id = "", normalize) {
      if (normalize !== false)
        id = normalizeId(id);
      const p4 = resolver.parse(id);
      return _getFullPath(resolver, p4);
    }
    exports.getFullPath = getFullPath;
    function _getFullPath(resolver, p4) {
      const serialized = resolver.serialize(p4);
      return serialized.split("#")[0] + "#";
    }
    exports._getFullPath = _getFullPath;
    var TRAILING_SLASH_HASH = /#\/?$/;
    function normalizeId(id) {
      return id ? id.replace(TRAILING_SLASH_HASH, "") : "";
    }
    exports.normalizeId = normalizeId;
    function resolveUrl(resolver, baseId, id) {
      id = normalizeId(id);
      return resolver.resolve(baseId, id);
    }
    exports.resolveUrl = resolveUrl;
    var ANCHOR = /^[a-z_][-a-z0-9._]*$/i;
    function getSchemaRefs(schema, baseId) {
      if (typeof schema == "boolean")
        return {};
      const { schemaId, uriResolver } = this.opts;
      const schId = normalizeId(schema[schemaId] || baseId);
      const baseIds = { "": schId };
      const pathPrefix = getFullPath(uriResolver, schId, false);
      const localRefs = {};
      const schemaRefs = /* @__PURE__ */ new Set();
      traverse2(schema, { allKeys: true }, (sch, jsonPtr, _3, parentJsonPtr) => {
        if (parentJsonPtr === void 0)
          return;
        const fullPath = pathPrefix + jsonPtr;
        let innerBaseId = baseIds[parentJsonPtr];
        if (typeof sch[schemaId] == "string")
          innerBaseId = addRef.call(this, sch[schemaId]);
        addAnchor.call(this, sch.$anchor);
        addAnchor.call(this, sch.$dynamicAnchor);
        baseIds[jsonPtr] = innerBaseId;
        function addRef(ref) {
          const _resolve = this.opts.uriResolver.resolve;
          ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref);
          if (schemaRefs.has(ref))
            throw ambiguos(ref);
          schemaRefs.add(ref);
          let schOrRef = this.refs[ref];
          if (typeof schOrRef == "string")
            schOrRef = this.refs[schOrRef];
          if (typeof schOrRef == "object") {
            checkAmbiguosRef(sch, schOrRef.schema, ref);
          } else if (ref !== normalizeId(fullPath)) {
            if (ref[0] === "#") {
              checkAmbiguosRef(sch, localRefs[ref], ref);
              localRefs[ref] = sch;
            } else {
              this.refs[ref] = fullPath;
            }
          }
          return ref;
        }
        function addAnchor(anchor) {
          if (typeof anchor == "string") {
            if (!ANCHOR.test(anchor))
              throw new Error(`invalid anchor "${anchor}"`);
            addRef.call(this, `#${anchor}`);
          }
        }
      });
      return localRefs;
      function checkAmbiguosRef(sch1, sch2, ref) {
        if (sch2 !== void 0 && !equal(sch1, sch2))
          throw ambiguos(ref);
      }
      function ambiguos(ref) {
        return new Error(`reference "${ref}" resolves to more than one schema`);
      }
    }
    exports.getSchemaRefs = getSchemaRefs;
  }
});

// ../pi-mono/node_modules/ajv/dist/compile/validate/index.js
var require_validate = __commonJS({
  "../pi-mono/node_modules/ajv/dist/compile/validate/index.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0;
    var boolSchema_1 = require_boolSchema();
    var dataType_1 = require_dataType();
    var applicability_1 = require_applicability();
    var dataType_2 = require_dataType();
    var defaults_1 = require_defaults();
    var keyword_1 = require_keyword();
    var subschema_1 = require_subschema();
    var codegen_1 = require_codegen();
    var names_1 = require_names();
    var resolve_1 = require_resolve();
    var util_1 = require_util2();
    var errors_1 = require_errors3();
    function validateFunctionCode(it) {
      if (isSchemaObj(it)) {
        checkKeywords(it);
        if (schemaCxtHasRules(it)) {
          topSchemaObjCode(it);
          return;
        }
      }
      validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it));
    }
    exports.validateFunctionCode = validateFunctionCode;
    function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) {
      if (opts.code.es5) {
        gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => {
          gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema, opts)}`);
          destructureValCxtES5(gen, opts);
          gen.code(body);
        });
      } else {
        gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body));
      }
    }
    function destructureValCxt(opts) {
      return (0, codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._)`, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`;
    }
    function destructureValCxtES5(gen, opts) {
      gen.if(names_1.default.valCxt, () => {
        gen.var(names_1.default.instancePath, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`);
        gen.var(names_1.default.parentData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`);
        gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`);
        gen.var(names_1.default.rootData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`);
        if (opts.dynamicRef)
          gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`);
      }, () => {
        gen.var(names_1.default.instancePath, (0, codegen_1._)`""`);
        gen.var(names_1.default.parentData, (0, codegen_1._)`undefined`);
        gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`undefined`);
        gen.var(names_1.default.rootData, names_1.default.data);
        if (opts.dynamicRef)
          gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`{}`);
      });
    }
    function topSchemaObjCode(it) {
      const { schema, opts, gen } = it;
      validateFunction(it, () => {
        if (opts.$comment && schema.$comment)
          commentKeyword(it);
        checkNoDefault(it);
        gen.let(names_1.default.vErrors, null);
        gen.let(names_1.default.errors, 0);
        if (opts.unevaluated)
          resetEvaluated(it);
        typeAndKeywords(it);
        returnResults(it);
      });
      return;
    }
    function resetEvaluated(it) {
      const { gen, validateName } = it;
      it.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName}.evaluated`);
      gen.if((0, codegen_1._)`${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it.evaluated}.props`, (0, codegen_1._)`undefined`));
      gen.if((0, codegen_1._)`${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it.evaluated}.items`, (0, codegen_1._)`undefined`));
    }
    function funcSourceUrl(schema, opts) {
      const schId = typeof schema == "object" && schema[opts.schemaId];
      return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._)`/*# sourceURL=${schId} */` : codegen_1.nil;
    }
    function subschemaCode(it, valid) {
      if (isSchemaObj(it)) {
        checkKeywords(it);
        if (schemaCxtHasRules(it)) {
          subSchemaObjCode(it, valid);
          return;
        }
      }
      (0, boolSchema_1.boolOrEmptySchema)(it, valid);
    }
    function schemaCxtHasRules({ schema, self: self2 }) {
      if (typeof schema == "boolean")
        return !schema;
      for (const key in schema)
        if (self2.RULES.all[key])
          return true;
      return false;
    }
    function isSchemaObj(it) {
      return typeof it.schema != "boolean";
    }
    function subSchemaObjCode(it, valid) {
      const { schema, gen, opts } = it;
      if (opts.$comment && schema.$comment)
        commentKeyword(it);
      updateContext(it);
      checkAsyncSchema(it);
      const errsCount = gen.const("_errs", names_1.default.errors);
      typeAndKeywords(it, errsCount);
      gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`);
    }
    function checkKeywords(it) {
      (0, util_1.checkUnknownRules)(it);
      checkRefsAndKeywords(it);
    }
    function typeAndKeywords(it, errsCount) {
      if (it.opts.jtd)
        return schemaKeywords(it, [], false, errsCount);
      const types2 = (0, dataType_1.getSchemaTypes)(it.schema);
      const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types2);
      schemaKeywords(it, types2, !checkedTypes, errsCount);
    }
    function checkRefsAndKeywords(it) {
      const { schema, errSchemaPath, opts, self: self2 } = it;
      if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self2.RULES)) {
        self2.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`);
      }
    }
    function checkNoDefault(it) {
      const { schema, opts } = it;
      if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) {
        (0, util_1.checkStrictMode)(it, "default is ignored in the schema root");
      }
    }
    function updateContext(it) {
      const schId = it.schema[it.opts.schemaId];
      if (schId)
        it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId);
    }
    function checkAsyncSchema(it) {
      if (it.schema.$async && !it.schemaEnv.$async)
        throw new Error("async schema in sync schema");
    }
    function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) {
      const msg = schema.$comment;
      if (opts.$comment === true) {
        gen.code((0, codegen_1._)`${names_1.default.self}.logger.log(${msg})`);
      } else if (typeof opts.$comment == "function") {
        const schemaPath = (0, codegen_1.str)`${errSchemaPath}/$comment`;
        const rootName = gen.scopeValue("root", { ref: schemaEnv.root });
        gen.code((0, codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`);
      }
    }
    function returnResults(it) {
      const { gen, schemaEnv, validateName, ValidationError, opts } = it;
      if (schemaEnv.$async) {
        gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`));
      } else {
        gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors);
        if (opts.unevaluated)
          assignEvaluated(it);
        gen.return((0, codegen_1._)`${names_1.default.errors} === 0`);
      }
    }
    function assignEvaluated({ gen, evaluated, props, items }) {
      if (props instanceof codegen_1.Name)
        gen.assign((0, codegen_1._)`${evaluated}.props`, props);
      if (items instanceof codegen_1.Name)
        gen.assign((0, codegen_1._)`${evaluated}.items`, items);
    }
    function schemaKeywords(it, types2, typeErrors, errsCount) {
      const { gen, schema, data, allErrors, opts, self: self2 } = it;
      const { RULES } = self2;
      if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) {
        gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition));
        return;
      }
      if (!opts.jtd)
        checkStrictTypes(it, types2);
      gen.block(() => {
        for (const group of RULES.rules)
          groupKeywords(group);
        groupKeywords(RULES.post);
      });
      function groupKeywords(group) {
        if (!(0, applicability_1.shouldUseGroup)(schema, group))
          return;
        if (group.type) {
          gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers));
          iterateKeywords(it, group);
          if (types2.length === 1 && types2[0] === group.type && typeErrors) {
            gen.else();
            (0, dataType_2.reportTypeError)(it);
          }
          gen.endIf();
        } else {
          iterateKeywords(it, group);
        }
        if (!allErrors)
          gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`);
      }
    }
    function iterateKeywords(it, group) {
      const { gen, schema, opts: { useDefaults } } = it;
      if (useDefaults)
        (0, defaults_1.assignDefaults)(it, group.type);
      gen.block(() => {
        for (const rule of group.rules) {
          if ((0, applicability_1.shouldUseRule)(schema, rule)) {
            keywordCode(it, rule.keyword, rule.definition, group.type);
          }
        }
      });
    }
    function checkStrictTypes(it, types2) {
      if (it.schemaEnv.meta || !it.opts.strictTypes)
        return;
      checkContextTypes(it, types2);
      if (!it.opts.allowUnionTypes)
        checkMultipleTypes(it, types2);
      checkKeywordTypes(it, it.dataTypes);
    }
    function checkContextTypes(it, types2) {
      if (!types2.length)
        return;
      if (!it.dataTypes.length) {
        it.dataTypes = types2;
        return;
      }
      types2.forEach((t6) => {
        if (!includesType(it.dataTypes, t6)) {
          strictTypesError(it, `type "${t6}" not allowed by context "${it.dataTypes.join(",")}"`);
        }
      });
      narrowSchemaTypes(it, types2);
    }
    function checkMultipleTypes(it, ts) {
      if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) {
        strictTypesError(it, "use allowUnionTypes to allow union type keyword");
      }
    }
    function checkKeywordTypes(it, ts) {
      const rules = it.self.RULES.all;
      for (const keyword in rules) {
        const rule = rules[keyword];
        if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) {
          const { type } = rule.definition;
          if (type.length && !type.some((t6) => hasApplicableType(ts, t6))) {
            strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`);
          }
        }
      }
    }
    function hasApplicableType(schTs, kwdT) {
      return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer");
    }
    function includesType(ts, t6) {
      return ts.includes(t6) || t6 === "integer" && ts.includes("number");
    }
    function narrowSchemaTypes(it, withTypes) {
      const ts = [];
      for (const t6 of it.dataTypes) {
        if (includesType(withTypes, t6))
          ts.push(t6);
        else if (withTypes.includes("integer") && t6 === "number")
          ts.push("integer");
      }
      it.dataTypes = ts;
    }
    function strictTypesError(it, msg) {
      const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;
      msg += ` at "${schemaPath}" (strictTypes)`;
      (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes);
    }
    var KeywordCxt = class {
      constructor(it, def, keyword) {
        (0, keyword_1.validateKeywordUsage)(it, def, keyword);
        this.gen = it.gen;
        this.allErrors = it.allErrors;
        this.keyword = keyword;
        this.data = it.data;
        this.schema = it.schema[keyword];
        this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data;
        this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data);
        this.schemaType = def.schemaType;
        this.parentSchema = it.schema;
        this.params = {};
        this.it = it;
        this.def = def;
        if (this.$data) {
          this.schemaCode = it.gen.const("vSchema", getData(this.$data, it));
        } else {
          this.schemaCode = this.schemaValue;
          if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) {
            throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`);
          }
        }
        if ("code" in def ? def.trackErrors : def.errors !== false) {
          this.errsCount = it.gen.const("_errs", names_1.default.errors);
        }
      }
      result(condition, successAction, failAction) {
        this.failResult((0, codegen_1.not)(condition), successAction, failAction);
      }
      failResult(condition, successAction, failAction) {
        this.gen.if(condition);
        if (failAction)
          failAction();
        else
          this.error();
        if (successAction) {
          this.gen.else();
          successAction();
          if (this.allErrors)
            this.gen.endIf();
        } else {
          if (this.allErrors)
            this.gen.endIf();
          else
            this.gen.else();
        }
      }
      pass(condition, failAction) {
        this.failResult((0, codegen_1.not)(condition), void 0, failAction);
      }
      fail(condition) {
        if (condition === void 0) {
          this.error();
          if (!this.allErrors)
            this.gen.if(false);
          return;
        }
        this.gen.if(condition);
        this.error();
        if (this.allErrors)
          this.gen.endIf();
        else
          this.gen.else();
      }
      fail$data(condition) {
        if (!this.$data)
          return this.fail(condition);
        const { schemaCode } = this;
        this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`);
      }
      error(append, errorParams, errorPaths) {
        if (errorParams) {
          this.setParams(errorParams);
          this._error(append, errorPaths);
          this.setParams({});
          return;
        }
        this._error(append, errorPaths);
      }
      _error(append, errorPaths) {
        ;
        (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths);
      }
      $dataError() {
        (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError);
      }
      reset() {
        if (this.errsCount === void 0)
          throw new Error('add "trackErrors" to keyword definition');
        (0, errors_1.resetErrorsCount)(this.gen, this.errsCount);
      }
      ok(cond) {
        if (!this.allErrors)
          this.gen.if(cond);
      }
      setParams(obj, assign) {
        if (assign)
          Object.assign(this.params, obj);
        else
          this.params = obj;
      }
      block$data(valid, codeBlock, $dataValid = codegen_1.nil) {
        this.gen.block(() => {
          this.check$data(valid, $dataValid);
          codeBlock();
        });
      }
      check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) {
        if (!this.$data)
          return;
        const { gen, schemaCode, schemaType, def } = this;
        gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid));
        if (valid !== codegen_1.nil)
          gen.assign(valid, true);
        if (schemaType.length || def.validateSchema) {
          gen.elseIf(this.invalid$data());
          this.$dataError();
          if (valid !== codegen_1.nil)
            gen.assign(valid, false);
        }
        gen.else();
      }
      invalid$data() {
        const { gen, schemaCode, schemaType, def, it } = this;
        return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema());
        function wrong$DataType() {
          if (schemaType.length) {
            if (!(schemaCode instanceof codegen_1.Name))
              throw new Error("ajv implementation error");
            const st = Array.isArray(schemaType) ? schemaType : [schemaType];
            return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`;
          }
          return codegen_1.nil;
        }
        function invalid$DataSchema() {
          if (def.validateSchema) {
            const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema });
            return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`;
          }
          return codegen_1.nil;
        }
      }
      subschema(appl, valid) {
        const subschema = (0, subschema_1.getSubschema)(this.it, appl);
        (0, subschema_1.extendSubschemaData)(subschema, this.it, appl);
        (0, subschema_1.extendSubschemaMode)(subschema, appl);
        const nextContext = { ...this.it, ...subschema, items: void 0, props: void 0 };
        subschemaCode(nextContext, valid);
        return nextContext;
      }
      mergeEvaluated(schemaCxt, toName) {
        const { it, gen } = this;
        if (!it.opts.unevaluated)
          return;
        if (it.props !== true && schemaCxt.props !== void 0) {
          it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName);
        }
        if (it.items !== true && schemaCxt.items !== void 0) {
          it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName);
        }
      }
      mergeValidEvaluated(schemaCxt, valid) {
        const { it, gen } = this;
        if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {
          gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name));
          return true;
        }
      }
    };
    exports.KeywordCxt = KeywordCxt;
    function keywordCode(it, keyword, def, ruleType) {
      const cxt = new KeywordCxt(it, def, keyword);
      if ("code" in def) {
        def.code(cxt, ruleType);
      } else if (cxt.$data && def.validate) {
        (0, keyword_1.funcKeywordCode)(cxt, def);
      } else if ("macro" in def) {
        (0, keyword_1.macroKeywordCode)(cxt, def);
      } else if (def.compile || def.validate) {
        (0, keyword_1.funcKeywordCode)(cxt, def);
      }
    }
    var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
    var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
    function getData($data, { dataLevel, dataNames, dataPathArr }) {
      let jsonPointer;
      let data;
      if ($data === "")
        return names_1.default.rootData;
      if ($data[0] === "/") {
        if (!JSON_POINTER.test($data))
          throw new Error(`Invalid JSON-pointer: ${$data}`);
        jsonPointer = $data;
        data = names_1.default.rootData;
      } else {
        const matches = RELATIVE_JSON_POINTER.exec($data);
        if (!matches)
          throw new Error(`Invalid JSON-pointer: ${$data}`);
        const up = +matches[1];
        jsonPointer = matches[2];
        if (jsonPointer === "#") {
          if (up >= dataLevel)
            throw new Error(errorMsg("property/index", up));
          return dataPathArr[dataLevel - up];
        }
        if (up > dataLevel)
          throw new Error(errorMsg("data", up));
        data = dataNames[dataLevel - up];
        if (!jsonPointer)
          return data;
      }
      let expr = data;
      const segments = jsonPointer.split("/");
      for (const segment of segments) {
        if (segment) {
          data = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`;
          expr = (0, codegen_1._)`${expr} && ${data}`;
        }
      }
      return expr;
      function errorMsg(pointerType, up) {
        return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`;
      }
    }
    exports.getData = getData;
  }
});

// ../pi-mono/node_modules/ajv/dist/runtime/validation_error.js
var require_validation_error = __commonJS({
  "../pi-mono/node_modules/ajv/dist/runtime/validation_error.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    var ValidationError = class extends Error {
      constructor(errors) {
        super("validation failed");
        this.errors = errors;
        this.ajv = this.validation = true;
      }
    };
    exports.default = ValidationError;
  }
});

// ../pi-mono/node_modules/ajv/dist/compile/ref_error.js
var require_ref_error = __commonJS({
  "../pi-mono/node_modules/ajv/dist/compile/ref_error.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    var resolve_1 = require_resolve();
    var MissingRefError = class extends Error {
      constructor(resolver, baseId, ref, msg) {
        super(msg || `can't resolve reference ${ref} from id ${baseId}`);
        this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref);
        this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef));
      }
    };
    exports.default = MissingRefError;
  }
});

// ../pi-mono/node_modules/ajv/dist/compile/index.js
var require_compile = __commonJS({
  "../pi-mono/node_modules/ajv/dist/compile/index.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0;
    var codegen_1 = require_codegen();
    var validation_error_1 = require_validation_error();
    var names_1 = require_names();
    var resolve_1 = require_resolve();
    var util_1 = require_util2();
    var validate_1 = require_validate();
    var SchemaEnv = class {
      constructor(env) {
        var _a7;
        this.refs = {};
        this.dynamicAnchors = {};
        let schema;
        if (typeof env.schema == "object")
          schema = env.schema;
        this.schema = env.schema;
        this.schemaId = env.schemaId;
        this.root = env.root || this;
        this.baseId = (_a7 = env.baseId) !== null && _a7 !== void 0 ? _a7 : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]);
        this.schemaPath = env.schemaPath;
        this.localRefs = env.localRefs;
        this.meta = env.meta;
        this.$async = schema === null || schema === void 0 ? void 0 : schema.$async;
        this.refs = {};
      }
    };
    exports.SchemaEnv = SchemaEnv;
    function compileSchema(sch) {
      const _sch = getCompilingSchema.call(this, sch);
      if (_sch)
        return _sch;
      const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId);
      const { es5, lines } = this.opts.code;
      const { ownProperties } = this.opts;
      const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties });
      let _ValidationError;
      if (sch.$async) {
        _ValidationError = gen.scopeValue("Error", {
          ref: validation_error_1.default,
          code: (0, codegen_1._)`require("ajv/dist/runtime/validation_error").default`
        });
      }
      const validateName = gen.scopeName("validate");
      sch.validateName = validateName;
      const schemaCxt = {
        gen,
        allErrors: this.opts.allErrors,
        data: names_1.default.data,
        parentData: names_1.default.parentData,
        parentDataProperty: names_1.default.parentDataProperty,
        dataNames: [names_1.default.data],
        dataPathArr: [codegen_1.nil],
        // TODO can its length be used as dataLevel if nil is removed?
        dataLevel: 0,
        dataTypes: [],
        definedProperties: /* @__PURE__ */ new Set(),
        topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) } : { ref: sch.schema }),
        validateName,
        ValidationError: _ValidationError,
        schema: sch.schema,
        schemaEnv: sch,
        rootId,
        baseId: sch.baseId || rootId,
        schemaPath: codegen_1.nil,
        errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"),
        errorPath: (0, codegen_1._)`""`,
        opts: this.opts,
        self: this
      };
      let sourceCode;
      try {
        this._compilations.add(sch);
        (0, validate_1.validateFunctionCode)(schemaCxt);
        gen.optimize(this.opts.code.optimize);
        const validateCode = gen.toString();
        sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`;
        if (this.opts.code.process)
          sourceCode = this.opts.code.process(sourceCode, sch);
        const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode);
        const validate = makeValidate(this, this.scope.get());
        this.scope.value(validateName, { ref: validate });
        validate.errors = null;
        validate.schema = sch.schema;
        validate.schemaEnv = sch;
        if (sch.$async)
          validate.$async = true;
        if (this.opts.code.source === true) {
          validate.source = { validateName, validateCode, scopeValues: gen._values };
        }
        if (this.opts.unevaluated) {
          const { props, items } = schemaCxt;
          validate.evaluated = {
            props: props instanceof codegen_1.Name ? void 0 : props,
            items: items instanceof codegen_1.Name ? void 0 : items,
            dynamicProps: props instanceof codegen_1.Name,
            dynamicItems: items instanceof codegen_1.Name
          };
          if (validate.source)
            validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated);
        }
        sch.validate = validate;
        return sch;
      } catch (e9) {
        delete sch.validate;
        delete sch.validateName;
        if (sourceCode)
          this.logger.error("Error compiling schema, function code:", sourceCode);
        throw e9;
      } finally {
        this._compilations.delete(sch);
      }
    }
    exports.compileSchema = compileSchema;
    function resolveRef(root, baseId, ref) {
      var _a7;
      ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref);
      const schOrFunc = root.refs[ref];
      if (schOrFunc)
        return schOrFunc;
      let _sch = resolve.call(this, root, ref);
      if (_sch === void 0) {
        const schema = (_a7 = root.localRefs) === null || _a7 === void 0 ? void 0 : _a7[ref];
        const { schemaId } = this.opts;
        if (schema)
          _sch = new SchemaEnv({ schema, schemaId, root, baseId });
      }
      if (_sch === void 0)
        return;
      return root.refs[ref] = inlineOrCompile.call(this, _sch);
    }
    exports.resolveRef = resolveRef;
    function inlineOrCompile(sch) {
      if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs))
        return sch.schema;
      return sch.validate ? sch : compileSchema.call(this, sch);
    }
    function getCompilingSchema(schEnv) {
      for (const sch of this._compilations) {
        if (sameSchemaEnv(sch, schEnv))
          return sch;
      }
    }
    exports.getCompilingSchema = getCompilingSchema;
    function sameSchemaEnv(s1, s22) {
      return s1.schema === s22.schema && s1.root === s22.root && s1.baseId === s22.baseId;
    }
    function resolve(root, ref) {
      let sch;
      while (typeof (sch = this.refs[ref]) == "string")
        ref = sch;
      return sch || this.schemas[ref] || resolveSchema.call(this, root, ref);
    }
    function resolveSchema(root, ref) {
      const p4 = this.opts.uriResolver.parse(ref);
      const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p4);
      let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, void 0);
      if (Object.keys(root.schema).length > 0 && refPath === baseId) {
        return getJsonPointer.call(this, p4, root);
      }
      const id = (0, resolve_1.normalizeId)(refPath);
      const schOrRef = this.refs[id] || this.schemas[id];
      if (typeof schOrRef == "string") {
        const sch = resolveSchema.call(this, root, schOrRef);
        if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object")
          return;
        return getJsonPointer.call(this, p4, sch);
      }
      if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object")
        return;
      if (!schOrRef.validate)
        compileSchema.call(this, schOrRef);
      if (id === (0, resolve_1.normalizeId)(ref)) {
        const { schema } = schOrRef;
        const { schemaId } = this.opts;
        const schId = schema[schemaId];
        if (schId)
          baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);
        return new SchemaEnv({ schema, schemaId, root, baseId });
      }
      return getJsonPointer.call(this, p4, schOrRef);
    }
    exports.resolveSchema = resolveSchema;
    var PREVENT_SCOPE_CHANGE = /* @__PURE__ */ new Set([
      "properties",
      "patternProperties",
      "enum",
      "dependencies",
      "definitions"
    ]);
    function getJsonPointer(parsedRef, { baseId, schema, root }) {
      var _a7;
      if (((_a7 = parsedRef.fragment) === null || _a7 === void 0 ? void 0 : _a7[0]) !== "/")
        return;
      for (const part of parsedRef.fragment.slice(1).split("/")) {
        if (typeof schema === "boolean")
          return;
        const partSchema = schema[(0, util_1.unescapeFragment)(part)];
        if (partSchema === void 0)
          return;
        schema = partSchema;
        const schId = typeof schema === "object" && schema[this.opts.schemaId];
        if (!PREVENT_SCOPE_CHANGE.has(part) && schId) {
          baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);
        }
      }
      let env;
      if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) {
        const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref);
        env = resolveSchema.call(this, root, $ref);
      }
      const { schemaId } = this.opts;
      env = env || new SchemaEnv({ schema, schemaId, root, baseId });
      if (env.schema !== env.root.schema)
        return env;
      return void 0;
    }
  }
});

// ../pi-mono/node_modules/ajv/dist/refs/data.json
var require_data = __commonJS({
  "../pi-mono/node_modules/ajv/dist/refs/data.json"(exports, module) {
    module.exports = {
      $id: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
      description: "Meta-schema for $data reference (JSON AnySchema extension proposal)",
      type: "object",
      required: ["$data"],
      properties: {
        $data: {
          type: "string",
          anyOf: [{ format: "relative-json-pointer" }, { format: "json-pointer" }]
        }
      },
      additionalProperties: false
    };
  }
});

// ../pi-mono/node_modules/fast-uri/lib/utils.js
var require_utils = __commonJS({
  "../pi-mono/node_modules/fast-uri/lib/utils.js"(exports, module) {
    "use strict";
    init_process_shim();
    var isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu);
    var isIPv4 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);
    function stringArrayToHexStripped(input) {
      let acc = "";
      let code = 0;
      let i7 = 0;
      for (i7 = 0; i7 < input.length; i7++) {
        code = input[i7].charCodeAt(0);
        if (code === 48) {
          continue;
        }
        if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) {
          return "";
        }
        acc += input[i7];
        break;
      }
      for (i7 += 1; i7 < input.length; i7++) {
        code = input[i7].charCodeAt(0);
        if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) {
          return "";
        }
        acc += input[i7];
      }
      return acc;
    }
    var nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);
    function consumeIsZone(buffer) {
      buffer.length = 0;
      return true;
    }
    function consumeHextets(buffer, address, output) {
      if (buffer.length) {
        const hex = stringArrayToHexStripped(buffer);
        if (hex !== "") {
          address.push(hex);
        } else {
          output.error = true;
          return false;
        }
        buffer.length = 0;
      }
      return true;
    }
    function getIPV6(input) {
      let tokenCount = 0;
      const output = { error: false, address: "", zone: "" };
      const address = [];
      const buffer = [];
      let endipv6Encountered = false;
      let endIpv6 = false;
      let consume = consumeHextets;
      for (let i7 = 0; i7 < input.length; i7++) {
        const cursor = input[i7];
        if (cursor === "[" || cursor === "]") {
          continue;
        }
        if (cursor === ":") {
          if (endipv6Encountered === true) {
            endIpv6 = true;
          }
          if (!consume(buffer, address, output)) {
            break;
          }
          if (++tokenCount > 7) {
            output.error = true;
            break;
          }
          if (i7 > 0 && input[i7 - 1] === ":") {
            endipv6Encountered = true;
          }
          address.push(":");
          continue;
        } else if (cursor === "%") {
          if (!consume(buffer, address, output)) {
            break;
          }
          consume = consumeIsZone;
        } else {
          buffer.push(cursor);
          continue;
        }
      }
      if (buffer.length) {
        if (consume === consumeIsZone) {
          output.zone = buffer.join("");
        } else if (endIpv6) {
          address.push(buffer.join(""));
        } else {
          address.push(stringArrayToHexStripped(buffer));
        }
      }
      output.address = address.join("");
      return output;
    }
    function normalizeIPv6(host) {
      if (findToken(host, ":") < 2) {
        return { host, isIPV6: false };
      }
      const ipv6 = getIPV6(host);
      if (!ipv6.error) {
        let newHost = ipv6.address;
        let escapedHost = ipv6.address;
        if (ipv6.zone) {
          newHost += "%" + ipv6.zone;
          escapedHost += "%25" + ipv6.zone;
        }
        return { host: newHost, isIPV6: true, escapedHost };
      } else {
        return { host, isIPV6: false };
      }
    }
    function findToken(str2, token) {
      let ind = 0;
      for (let i7 = 0; i7 < str2.length; i7++) {
        if (str2[i7] === token) ind++;
      }
      return ind;
    }
    function removeDotSegments(path6) {
      let input = path6;
      const output = [];
      let nextSlash = -1;
      let len = 0;
      while (len = input.length) {
        if (len === 1) {
          if (input === ".") {
            break;
          } else if (input === "/") {
            output.push("/");
            break;
          } else {
            output.push(input);
            break;
          }
        } else if (len === 2) {
          if (input[0] === ".") {
            if (input[1] === ".") {
              break;
            } else if (input[1] === "/") {
              input = input.slice(2);
              continue;
            }
          } else if (input[0] === "/") {
            if (input[1] === "." || input[1] === "/") {
              output.push("/");
              break;
            }
          }
        } else if (len === 3) {
          if (input === "/..") {
            if (output.length !== 0) {
              output.pop();
            }
            output.push("/");
            break;
          }
        }
        if (input[0] === ".") {
          if (input[1] === ".") {
            if (input[2] === "/") {
              input = input.slice(3);
              continue;
            }
          } else if (input[1] === "/") {
            input = input.slice(2);
            continue;
          }
        } else if (input[0] === "/") {
          if (input[1] === ".") {
            if (input[2] === "/") {
              input = input.slice(2);
              continue;
            } else if (input[2] === ".") {
              if (input[3] === "/") {
                input = input.slice(3);
                if (output.length !== 0) {
                  output.pop();
                }
                continue;
              }
            }
          }
        }
        if ((nextSlash = input.indexOf("/", 1)) === -1) {
          output.push(input);
          break;
        } else {
          output.push(input.slice(0, nextSlash));
          input = input.slice(nextSlash);
        }
      }
      return output.join("");
    }
    function normalizeComponentEncoding(component, esc) {
      const func = esc !== true ? escape : unescape;
      if (component.scheme !== void 0) {
        component.scheme = func(component.scheme);
      }
      if (component.userinfo !== void 0) {
        component.userinfo = func(component.userinfo);
      }
      if (component.host !== void 0) {
        component.host = func(component.host);
      }
      if (component.path !== void 0) {
        component.path = func(component.path);
      }
      if (component.query !== void 0) {
        component.query = func(component.query);
      }
      if (component.fragment !== void 0) {
        component.fragment = func(component.fragment);
      }
      return component;
    }
    function recomposeAuthority(component) {
      const uriTokens = [];
      if (component.userinfo !== void 0) {
        uriTokens.push(component.userinfo);
        uriTokens.push("@");
      }
      if (component.host !== void 0) {
        let host = unescape(component.host);
        if (!isIPv4(host)) {
          const ipV6res = normalizeIPv6(host);
          if (ipV6res.isIPV6 === true) {
            host = `[${ipV6res.escapedHost}]`;
          } else {
            host = component.host;
          }
        }
        uriTokens.push(host);
      }
      if (typeof component.port === "number" || typeof component.port === "string") {
        uriTokens.push(":");
        uriTokens.push(String(component.port));
      }
      return uriTokens.length ? uriTokens.join("") : void 0;
    }
    module.exports = {
      nonSimpleDomain,
      recomposeAuthority,
      normalizeComponentEncoding,
      removeDotSegments,
      isIPv4,
      isUUID,
      normalizeIPv6,
      stringArrayToHexStripped
    };
  }
});

// ../pi-mono/node_modules/fast-uri/lib/schemes.js
var require_schemes = __commonJS({
  "../pi-mono/node_modules/fast-uri/lib/schemes.js"(exports, module) {
    "use strict";
    init_process_shim();
    var { isUUID } = require_utils();
    var URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;
    var supportedSchemeNames = (
      /** @type {const} */
      [
        "http",
        "https",
        "ws",
        "wss",
        "urn",
        "urn:uuid"
      ]
    );
    function isValidSchemeName(name) {
      return supportedSchemeNames.indexOf(
        /** @type {*} */
        name
      ) !== -1;
    }
    function wsIsSecure(wsComponent) {
      if (wsComponent.secure === true) {
        return true;
      } else if (wsComponent.secure === false) {
        return false;
      } else if (wsComponent.scheme) {
        return wsComponent.scheme.length === 3 && (wsComponent.scheme[0] === "w" || wsComponent.scheme[0] === "W") && (wsComponent.scheme[1] === "s" || wsComponent.scheme[1] === "S") && (wsComponent.scheme[2] === "s" || wsComponent.scheme[2] === "S");
      } else {
        return false;
      }
    }
    function httpParse(component) {
      if (!component.host) {
        component.error = component.error || "HTTP URIs must have a host.";
      }
      return component;
    }
    function httpSerialize(component) {
      const secure = String(component.scheme).toLowerCase() === "https";
      if (component.port === (secure ? 443 : 80) || component.port === "") {
        component.port = void 0;
      }
      if (!component.path) {
        component.path = "/";
      }
      return component;
    }
    function wsParse(wsComponent) {
      wsComponent.secure = wsIsSecure(wsComponent);
      wsComponent.resourceName = (wsComponent.path || "/") + (wsComponent.query ? "?" + wsComponent.query : "");
      wsComponent.path = void 0;
      wsComponent.query = void 0;
      return wsComponent;
    }
    function wsSerialize(wsComponent) {
      if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === "") {
        wsComponent.port = void 0;
      }
      if (typeof wsComponent.secure === "boolean") {
        wsComponent.scheme = wsComponent.secure ? "wss" : "ws";
        wsComponent.secure = void 0;
      }
      if (wsComponent.resourceName) {
        const [path6, query] = wsComponent.resourceName.split("?");
        wsComponent.path = path6 && path6 !== "/" ? path6 : void 0;
        wsComponent.query = query;
        wsComponent.resourceName = void 0;
      }
      wsComponent.fragment = void 0;
      return wsComponent;
    }
    function urnParse(urnComponent, options) {
      if (!urnComponent.path) {
        urnComponent.error = "URN can not be parsed";
        return urnComponent;
      }
      const matches = urnComponent.path.match(URN_REG);
      if (matches) {
        const scheme = options.scheme || urnComponent.scheme || "urn";
        urnComponent.nid = matches[1].toLowerCase();
        urnComponent.nss = matches[2];
        const urnScheme = `${scheme}:${options.nid || urnComponent.nid}`;
        const schemeHandler = getSchemeHandler(urnScheme);
        urnComponent.path = void 0;
        if (schemeHandler) {
          urnComponent = schemeHandler.parse(urnComponent, options);
        }
      } else {
        urnComponent.error = urnComponent.error || "URN can not be parsed.";
      }
      return urnComponent;
    }
    function urnSerialize(urnComponent, options) {
      if (urnComponent.nid === void 0) {
        throw new Error("URN without nid cannot be serialized");
      }
      const scheme = options.scheme || urnComponent.scheme || "urn";
      const nid = urnComponent.nid.toLowerCase();
      const urnScheme = `${scheme}:${options.nid || nid}`;
      const schemeHandler = getSchemeHandler(urnScheme);
      if (schemeHandler) {
        urnComponent = schemeHandler.serialize(urnComponent, options);
      }
      const uriComponent = urnComponent;
      const nss = urnComponent.nss;
      uriComponent.path = `${nid || options.nid}:${nss}`;
      options.skipEscape = true;
      return uriComponent;
    }
    function urnuuidParse(urnComponent, options) {
      const uuidComponent = urnComponent;
      uuidComponent.uuid = uuidComponent.nss;
      uuidComponent.nss = void 0;
      if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) {
        uuidComponent.error = uuidComponent.error || "UUID is not valid.";
      }
      return uuidComponent;
    }
    function urnuuidSerialize(uuidComponent) {
      const urnComponent = uuidComponent;
      urnComponent.nss = (uuidComponent.uuid || "").toLowerCase();
      return urnComponent;
    }
    var http = (
      /** @type {SchemeHandler} */
      {
        scheme: "http",
        domainHost: true,
        parse: httpParse,
        serialize: httpSerialize
      }
    );
    var https = (
      /** @type {SchemeHandler} */
      {
        scheme: "https",
        domainHost: http.domainHost,
        parse: httpParse,
        serialize: httpSerialize
      }
    );
    var ws = (
      /** @type {SchemeHandler} */
      {
        scheme: "ws",
        domainHost: true,
        parse: wsParse,
        serialize: wsSerialize
      }
    );
    var wss = (
      /** @type {SchemeHandler} */
      {
        scheme: "wss",
        domainHost: ws.domainHost,
        parse: ws.parse,
        serialize: ws.serialize
      }
    );
    var urn = (
      /** @type {SchemeHandler} */
      {
        scheme: "urn",
        parse: urnParse,
        serialize: urnSerialize,
        skipNormalize: true
      }
    );
    var urnuuid = (
      /** @type {SchemeHandler} */
      {
        scheme: "urn:uuid",
        parse: urnuuidParse,
        serialize: urnuuidSerialize,
        skipNormalize: true
      }
    );
    var SCHEMES = (
      /** @type {Record<SchemeName, SchemeHandler>} */
      {
        http,
        https,
        ws,
        wss,
        urn,
        "urn:uuid": urnuuid
      }
    );
    Object.setPrototypeOf(SCHEMES, null);
    function getSchemeHandler(scheme) {
      return scheme && (SCHEMES[
        /** @type {SchemeName} */
        scheme
      ] || SCHEMES[
        /** @type {SchemeName} */
        scheme.toLowerCase()
      ]) || void 0;
    }
    module.exports = {
      wsIsSecure,
      SCHEMES,
      isValidSchemeName,
      getSchemeHandler
    };
  }
});

// ../pi-mono/node_modules/fast-uri/index.js
var require_fast_uri = __commonJS({
  "../pi-mono/node_modules/fast-uri/index.js"(exports, module) {
    "use strict";
    init_process_shim();
    var { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = require_utils();
    var { SCHEMES, getSchemeHandler } = require_schemes();
    function normalize(uri, options) {
      if (typeof uri === "string") {
        uri = /** @type {T} */
        serialize2(parse(uri, options), options);
      } else if (typeof uri === "object") {
        uri = /** @type {T} */
        parse(serialize2(uri, options), options);
      }
      return uri;
    }
    function resolve(baseURI, relativeURI, options) {
      const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" };
      const resolved = resolveComponent(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true);
      schemelessOptions.skipEscape = true;
      return serialize2(resolved, schemelessOptions);
    }
    function resolveComponent(base, relative, options, skipNormalization) {
      const target = {};
      if (!skipNormalization) {
        base = parse(serialize2(base, options), options);
        relative = parse(serialize2(relative, options), options);
      }
      options = options || {};
      if (!options.tolerant && relative.scheme) {
        target.scheme = relative.scheme;
        target.userinfo = relative.userinfo;
        target.host = relative.host;
        target.port = relative.port;
        target.path = removeDotSegments(relative.path || "");
        target.query = relative.query;
      } else {
        if (relative.userinfo !== void 0 || relative.host !== void 0 || relative.port !== void 0) {
          target.userinfo = relative.userinfo;
          target.host = relative.host;
          target.port = relative.port;
          target.path = removeDotSegments(relative.path || "");
          target.query = relative.query;
        } else {
          if (!relative.path) {
            target.path = base.path;
            if (relative.query !== void 0) {
              target.query = relative.query;
            } else {
              target.query = base.query;
            }
          } else {
            if (relative.path[0] === "/") {
              target.path = removeDotSegments(relative.path);
            } else {
              if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) {
                target.path = "/" + relative.path;
              } else if (!base.path) {
                target.path = relative.path;
              } else {
                target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path;
              }
              target.path = removeDotSegments(target.path);
            }
            target.query = relative.query;
          }
          target.userinfo = base.userinfo;
          target.host = base.host;
          target.port = base.port;
        }
        target.scheme = base.scheme;
      }
      target.fragment = relative.fragment;
      return target;
    }
    function equal(uriA, uriB, options) {
      if (typeof uriA === "string") {
        uriA = unescape(uriA);
        uriA = serialize2(normalizeComponentEncoding(parse(uriA, options), true), { ...options, skipEscape: true });
      } else if (typeof uriA === "object") {
        uriA = serialize2(normalizeComponentEncoding(uriA, true), { ...options, skipEscape: true });
      }
      if (typeof uriB === "string") {
        uriB = unescape(uriB);
        uriB = serialize2(normalizeComponentEncoding(parse(uriB, options), true), { ...options, skipEscape: true });
      } else if (typeof uriB === "object") {
        uriB = serialize2(normalizeComponentEncoding(uriB, true), { ...options, skipEscape: true });
      }
      return uriA.toLowerCase() === uriB.toLowerCase();
    }
    function serialize2(cmpts, opts) {
      const component = {
        host: cmpts.host,
        scheme: cmpts.scheme,
        userinfo: cmpts.userinfo,
        port: cmpts.port,
        path: cmpts.path,
        query: cmpts.query,
        nid: cmpts.nid,
        nss: cmpts.nss,
        uuid: cmpts.uuid,
        fragment: cmpts.fragment,
        reference: cmpts.reference,
        resourceName: cmpts.resourceName,
        secure: cmpts.secure,
        error: ""
      };
      const options = Object.assign({}, opts);
      const uriTokens = [];
      const schemeHandler = getSchemeHandler(options.scheme || component.scheme);
      if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options);
      if (component.path !== void 0) {
        if (!options.skipEscape) {
          component.path = escape(component.path);
          if (component.scheme !== void 0) {
            component.path = component.path.split("%3A").join(":");
          }
        } else {
          component.path = unescape(component.path);
        }
      }
      if (options.reference !== "suffix" && component.scheme) {
        uriTokens.push(component.scheme, ":");
      }
      const authority = recomposeAuthority(component);
      if (authority !== void 0) {
        if (options.reference !== "suffix") {
          uriTokens.push("//");
        }
        uriTokens.push(authority);
        if (component.path && component.path[0] !== "/") {
          uriTokens.push("/");
        }
      }
      if (component.path !== void 0) {
        let s6 = component.path;
        if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {
          s6 = removeDotSegments(s6);
        }
        if (authority === void 0 && s6[0] === "/" && s6[1] === "/") {
          s6 = "/%2F" + s6.slice(2);
        }
        uriTokens.push(s6);
      }
      if (component.query !== void 0) {
        uriTokens.push("?", component.query);
      }
      if (component.fragment !== void 0) {
        uriTokens.push("#", component.fragment);
      }
      return uriTokens.join("");
    }
    var URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;
    function parse(uri, opts) {
      const options = Object.assign({}, opts);
      const parsed = {
        scheme: void 0,
        userinfo: void 0,
        host: "",
        port: void 0,
        path: "",
        query: void 0,
        fragment: void 0
      };
      let isIP = false;
      if (options.reference === "suffix") {
        if (options.scheme) {
          uri = options.scheme + ":" + uri;
        } else {
          uri = "//" + uri;
        }
      }
      const matches = uri.match(URI_PARSE);
      if (matches) {
        parsed.scheme = matches[1];
        parsed.userinfo = matches[3];
        parsed.host = matches[4];
        parsed.port = parseInt(matches[5], 10);
        parsed.path = matches[6] || "";
        parsed.query = matches[7];
        parsed.fragment = matches[8];
        if (isNaN(parsed.port)) {
          parsed.port = matches[5];
        }
        if (parsed.host) {
          const ipv4result = isIPv4(parsed.host);
          if (ipv4result === false) {
            const ipv6result = normalizeIPv6(parsed.host);
            parsed.host = ipv6result.host.toLowerCase();
            isIP = ipv6result.isIPV6;
          } else {
            isIP = true;
          }
        }
        if (parsed.scheme === void 0 && parsed.userinfo === void 0 && parsed.host === void 0 && parsed.port === void 0 && parsed.query === void 0 && !parsed.path) {
          parsed.reference = "same-document";
        } else if (parsed.scheme === void 0) {
          parsed.reference = "relative";
        } else if (parsed.fragment === void 0) {
          parsed.reference = "absolute";
        } else {
          parsed.reference = "uri";
        }
        if (options.reference && options.reference !== "suffix" && options.reference !== parsed.reference) {
          parsed.error = parsed.error || "URI is not a " + options.reference + " reference.";
        }
        const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme);
        if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {
          if (parsed.host && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) {
            try {
              parsed.host = URL.domainToASCII(parsed.host.toLowerCase());
            } catch (e9) {
              parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e9;
            }
          }
        }
        if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) {
          if (uri.indexOf("%") !== -1) {
            if (parsed.scheme !== void 0) {
              parsed.scheme = unescape(parsed.scheme);
            }
            if (parsed.host !== void 0) {
              parsed.host = unescape(parsed.host);
            }
          }
          if (parsed.path) {
            parsed.path = escape(unescape(parsed.path));
          }
          if (parsed.fragment) {
            parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment));
          }
        }
        if (schemeHandler && schemeHandler.parse) {
          schemeHandler.parse(parsed, options);
        }
      } else {
        parsed.error = parsed.error || "URI can not be parsed.";
      }
      return parsed;
    }
    var fastUri = {
      SCHEMES,
      normalize,
      resolve,
      resolveComponent,
      equal,
      serialize: serialize2,
      parse
    };
    module.exports = fastUri;
    module.exports.default = fastUri;
    module.exports.fastUri = fastUri;
  }
});

// ../pi-mono/node_modules/ajv/dist/runtime/uri.js
var require_uri = __commonJS({
  "../pi-mono/node_modules/ajv/dist/runtime/uri.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    var uri = require_fast_uri();
    uri.code = 'require("ajv/dist/runtime/uri").default';
    exports.default = uri;
  }
});

// ../pi-mono/node_modules/ajv/dist/core.js
var require_core = __commonJS({
  "../pi-mono/node_modules/ajv/dist/core.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0;
    var validate_1 = require_validate();
    Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() {
      return validate_1.KeywordCxt;
    } });
    var codegen_1 = require_codegen();
    Object.defineProperty(exports, "_", { enumerable: true, get: function() {
      return codegen_1._;
    } });
    Object.defineProperty(exports, "str", { enumerable: true, get: function() {
      return codegen_1.str;
    } });
    Object.defineProperty(exports, "stringify", { enumerable: true, get: function() {
      return codegen_1.stringify;
    } });
    Object.defineProperty(exports, "nil", { enumerable: true, get: function() {
      return codegen_1.nil;
    } });
    Object.defineProperty(exports, "Name", { enumerable: true, get: function() {
      return codegen_1.Name;
    } });
    Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() {
      return codegen_1.CodeGen;
    } });
    var validation_error_1 = require_validation_error();
    var ref_error_1 = require_ref_error();
    var rules_1 = require_rules();
    var compile_1 = require_compile();
    var codegen_2 = require_codegen();
    var resolve_1 = require_resolve();
    var dataType_1 = require_dataType();
    var util_1 = require_util2();
    var $dataRefSchema = require_data();
    var uri_1 = require_uri();
    var defaultRegExp = (str2, flags) => new RegExp(str2, flags);
    defaultRegExp.code = "new RegExp";
    var META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"];
    var EXT_SCOPE_NAMES = /* @__PURE__ */ new Set([
      "validate",
      "serialize",
      "parse",
      "wrapper",
      "root",
      "schema",
      "keyword",
      "pattern",
      "formats",
      "validate$data",
      "func",
      "obj",
      "Error"
    ]);
    var removedOptions = {
      errorDataPath: "",
      format: "`validateFormats: false` can be used instead.",
      nullable: '"nullable" keyword is supported by default.',
      jsonPointers: "Deprecated jsPropertySyntax can be used instead.",
      extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.",
      missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.",
      processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`",
      sourceCode: "Use option `code: {source: true}`",
      strictDefaults: "It is default now, see option `strict`.",
      strictKeywords: "It is default now, see option `strict`.",
      uniqueItems: '"uniqueItems" keyword is always validated.',
      unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",
      cache: "Map is used as cache, schema object as key.",
      serialize: "Map is used as cache, schema object as key.",
      ajvErrors: "It is default now."
    };
    var deprecatedOptions = {
      ignoreKeywordsWithRef: "",
      jsPropertySyntax: "",
      unicode: '"minLength"/"maxLength" account for unicode characters by default.'
    };
    var MAX_EXPRESSION = 200;
    function requiredOptions(o9) {
      var _a7, _b, _c, _d, _e2, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0;
      const s6 = o9.strict;
      const _optz = (_a7 = o9.code) === null || _a7 === void 0 ? void 0 : _a7.optimize;
      const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0;
      const regExp = (_c = (_b = o9.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp;
      const uriResolver = (_d = o9.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default;
      return {
        strictSchema: (_f = (_e2 = o9.strictSchema) !== null && _e2 !== void 0 ? _e2 : s6) !== null && _f !== void 0 ? _f : true,
        strictNumbers: (_h = (_g = o9.strictNumbers) !== null && _g !== void 0 ? _g : s6) !== null && _h !== void 0 ? _h : true,
        strictTypes: (_k = (_j = o9.strictTypes) !== null && _j !== void 0 ? _j : s6) !== null && _k !== void 0 ? _k : "log",
        strictTuples: (_m = (_l = o9.strictTuples) !== null && _l !== void 0 ? _l : s6) !== null && _m !== void 0 ? _m : "log",
        strictRequired: (_p = (_o = o9.strictRequired) !== null && _o !== void 0 ? _o : s6) !== null && _p !== void 0 ? _p : false,
        code: o9.code ? { ...o9.code, optimize, regExp } : { optimize, regExp },
        loopRequired: (_q = o9.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION,
        loopEnum: (_r = o9.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION,
        meta: (_s = o9.meta) !== null && _s !== void 0 ? _s : true,
        messages: (_t = o9.messages) !== null && _t !== void 0 ? _t : true,
        inlineRefs: (_u = o9.inlineRefs) !== null && _u !== void 0 ? _u : true,
        schemaId: (_v = o9.schemaId) !== null && _v !== void 0 ? _v : "$id",
        addUsedSchema: (_w = o9.addUsedSchema) !== null && _w !== void 0 ? _w : true,
        validateSchema: (_x = o9.validateSchema) !== null && _x !== void 0 ? _x : true,
        validateFormats: (_y = o9.validateFormats) !== null && _y !== void 0 ? _y : true,
        unicodeRegExp: (_z = o9.unicodeRegExp) !== null && _z !== void 0 ? _z : true,
        int32range: (_0 = o9.int32range) !== null && _0 !== void 0 ? _0 : true,
        uriResolver
      };
    }
    var Ajv2 = class {
      constructor(opts = {}) {
        this.schemas = {};
        this.refs = {};
        this.formats = {};
        this._compilations = /* @__PURE__ */ new Set();
        this._loading = {};
        this._cache = /* @__PURE__ */ new Map();
        opts = this.opts = { ...opts, ...requiredOptions(opts) };
        const { es5, lines } = this.opts.code;
        this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines });
        this.logger = getLogger(opts.logger);
        const formatOpt = opts.validateFormats;
        opts.validateFormats = false;
        this.RULES = (0, rules_1.getRules)();
        checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED");
        checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn");
        this._metaOpts = getMetaSchemaOptions.call(this);
        if (opts.formats)
          addInitialFormats.call(this);
        this._addVocabularies();
        this._addDefaultMetaSchema();
        if (opts.keywords)
          addInitialKeywords.call(this, opts.keywords);
        if (typeof opts.meta == "object")
          this.addMetaSchema(opts.meta);
        addInitialSchemas.call(this);
        opts.validateFormats = formatOpt;
      }
      _addVocabularies() {
        this.addKeyword("$async");
      }
      _addDefaultMetaSchema() {
        const { $data, meta, schemaId } = this.opts;
        let _dataRefSchema = $dataRefSchema;
        if (schemaId === "id") {
          _dataRefSchema = { ...$dataRefSchema };
          _dataRefSchema.id = _dataRefSchema.$id;
          delete _dataRefSchema.$id;
        }
        if (meta && $data)
          this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false);
      }
      defaultMeta() {
        const { meta, schemaId } = this.opts;
        return this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : void 0;
      }
      validate(schemaKeyRef, data) {
        let v4;
        if (typeof schemaKeyRef == "string") {
          v4 = this.getSchema(schemaKeyRef);
          if (!v4)
            throw new Error(`no schema with key or ref "${schemaKeyRef}"`);
        } else {
          v4 = this.compile(schemaKeyRef);
        }
        const valid = v4(data);
        if (!("$async" in v4))
          this.errors = v4.errors;
        return valid;
      }
      compile(schema, _meta) {
        const sch = this._addSchema(schema, _meta);
        return sch.validate || this._compileSchemaEnv(sch);
      }
      compileAsync(schema, meta) {
        if (typeof this.opts.loadSchema != "function") {
          throw new Error("options.loadSchema should be a function");
        }
        const { loadSchema } = this.opts;
        return runCompileAsync.call(this, schema, meta);
        async function runCompileAsync(_schema, _meta) {
          await loadMetaSchema.call(this, _schema.$schema);
          const sch = this._addSchema(_schema, _meta);
          return sch.validate || _compileAsync.call(this, sch);
        }
        async function loadMetaSchema($ref) {
          if ($ref && !this.getSchema($ref)) {
            await runCompileAsync.call(this, { $ref }, true);
          }
        }
        async function _compileAsync(sch) {
          try {
            return this._compileSchemaEnv(sch);
          } catch (e9) {
            if (!(e9 instanceof ref_error_1.default))
              throw e9;
            checkLoaded.call(this, e9);
            await loadMissingSchema.call(this, e9.missingSchema);
            return _compileAsync.call(this, sch);
          }
        }
        function checkLoaded({ missingSchema: ref, missingRef }) {
          if (this.refs[ref]) {
            throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`);
          }
        }
        async function loadMissingSchema(ref) {
          const _schema = await _loadSchema.call(this, ref);
          if (!this.refs[ref])
            await loadMetaSchema.call(this, _schema.$schema);
          if (!this.refs[ref])
            this.addSchema(_schema, ref, meta);
        }
        async function _loadSchema(ref) {
          const p4 = this._loading[ref];
          if (p4)
            return p4;
          try {
            return await (this._loading[ref] = loadSchema(ref));
          } finally {
            delete this._loading[ref];
          }
        }
      }
      // Adds schema to the instance
      addSchema(schema, key, _meta, _validateSchema = this.opts.validateSchema) {
        if (Array.isArray(schema)) {
          for (const sch of schema)
            this.addSchema(sch, void 0, _meta, _validateSchema);
          return this;
        }
        let id;
        if (typeof schema === "object") {
          const { schemaId } = this.opts;
          id = schema[schemaId];
          if (id !== void 0 && typeof id != "string") {
            throw new Error(`schema ${schemaId} must be string`);
          }
        }
        key = (0, resolve_1.normalizeId)(key || id);
        this._checkUnique(key);
        this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true);
        return this;
      }
      // Add schema that will be used to validate other schemas
      // options in META_IGNORE_OPTIONS are alway set to false
      addMetaSchema(schema, key, _validateSchema = this.opts.validateSchema) {
        this.addSchema(schema, key, true, _validateSchema);
        return this;
      }
      //  Validate schema against its meta-schema
      validateSchema(schema, throwOrLogError) {
        if (typeof schema == "boolean")
          return true;
        let $schema;
        $schema = schema.$schema;
        if ($schema !== void 0 && typeof $schema != "string") {
          throw new Error("$schema must be a string");
        }
        $schema = $schema || this.opts.defaultMeta || this.defaultMeta();
        if (!$schema) {
          this.logger.warn("meta-schema not available");
          this.errors = null;
          return true;
        }
        const valid = this.validate($schema, schema);
        if (!valid && throwOrLogError) {
          const message = "schema is invalid: " + this.errorsText();
          if (this.opts.validateSchema === "log")
            this.logger.error(message);
          else
            throw new Error(message);
        }
        return valid;
      }
      // Get compiled schema by `key` or `ref`.
      // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id)
      getSchema(keyRef) {
        let sch;
        while (typeof (sch = getSchEnv.call(this, keyRef)) == "string")
          keyRef = sch;
        if (sch === void 0) {
          const { schemaId } = this.opts;
          const root = new compile_1.SchemaEnv({ schema: {}, schemaId });
          sch = compile_1.resolveSchema.call(this, root, keyRef);
          if (!sch)
            return;
          this.refs[keyRef] = sch;
        }
        return sch.validate || this._compileSchemaEnv(sch);
      }
      // Remove cached schema(s).
      // If no parameter is passed all schemas but meta-schemas are removed.
      // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
      // Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
      removeSchema(schemaKeyRef) {
        if (schemaKeyRef instanceof RegExp) {
          this._removeAllSchemas(this.schemas, schemaKeyRef);
          this._removeAllSchemas(this.refs, schemaKeyRef);
          return this;
        }
        switch (typeof schemaKeyRef) {
          case "undefined":
            this._removeAllSchemas(this.schemas);
            this._removeAllSchemas(this.refs);
            this._cache.clear();
            return this;
          case "string": {
            const sch = getSchEnv.call(this, schemaKeyRef);
            if (typeof sch == "object")
              this._cache.delete(sch.schema);
            delete this.schemas[schemaKeyRef];
            delete this.refs[schemaKeyRef];
            return this;
          }
          case "object": {
            const cacheKey = schemaKeyRef;
            this._cache.delete(cacheKey);
            let id = schemaKeyRef[this.opts.schemaId];
            if (id) {
              id = (0, resolve_1.normalizeId)(id);
              delete this.schemas[id];
              delete this.refs[id];
            }
            return this;
          }
          default:
            throw new Error("ajv.removeSchema: invalid parameter");
        }
      }
      // add "vocabulary" - a collection of keywords
      addVocabulary(definitions) {
        for (const def of definitions)
          this.addKeyword(def);
        return this;
      }
      addKeyword(kwdOrDef, def) {
        let keyword;
        if (typeof kwdOrDef == "string") {
          keyword = kwdOrDef;
          if (typeof def == "object") {
            this.logger.warn("these parameters are deprecated, see docs for addKeyword");
            def.keyword = keyword;
          }
        } else if (typeof kwdOrDef == "object" && def === void 0) {
          def = kwdOrDef;
          keyword = def.keyword;
          if (Array.isArray(keyword) && !keyword.length) {
            throw new Error("addKeywords: keyword must be string or non-empty array");
          }
        } else {
          throw new Error("invalid addKeywords parameters");
        }
        checkKeyword.call(this, keyword, def);
        if (!def) {
          (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd));
          return this;
        }
        keywordMetaschema.call(this, def);
        const definition = {
          ...def,
          type: (0, dataType_1.getJSONTypes)(def.type),
          schemaType: (0, dataType_1.getJSONTypes)(def.schemaType)
        };
        (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k2) => addRule.call(this, k2, definition) : (k2) => definition.type.forEach((t6) => addRule.call(this, k2, definition, t6)));
        return this;
      }
      getKeyword(keyword) {
        const rule = this.RULES.all[keyword];
        return typeof rule == "object" ? rule.definition : !!rule;
      }
      // Remove keyword
      removeKeyword(keyword) {
        const { RULES } = this;
        delete RULES.keywords[keyword];
        delete RULES.all[keyword];
        for (const group of RULES.rules) {
          const i7 = group.rules.findIndex((rule) => rule.keyword === keyword);
          if (i7 >= 0)
            group.rules.splice(i7, 1);
        }
        return this;
      }
      // Add format
      addFormat(name, format) {
        if (typeof format == "string")
          format = new RegExp(format);
        this.formats[name] = format;
        return this;
      }
      errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) {
        if (!errors || errors.length === 0)
          return "No errors";
        return errors.map((e9) => `${dataVar}${e9.instancePath} ${e9.message}`).reduce((text3, msg) => text3 + separator + msg);
      }
      $dataMetaSchema(metaSchema, keywordsJsonPointers) {
        const rules = this.RULES.all;
        metaSchema = JSON.parse(JSON.stringify(metaSchema));
        for (const jsonPointer of keywordsJsonPointers) {
          const segments = jsonPointer.split("/").slice(1);
          let keywords = metaSchema;
          for (const seg of segments)
            keywords = keywords[seg];
          for (const key in rules) {
            const rule = rules[key];
            if (typeof rule != "object")
              continue;
            const { $data } = rule.definition;
            const schema = keywords[key];
            if ($data && schema)
              keywords[key] = schemaOrData(schema);
          }
        }
        return metaSchema;
      }
      _removeAllSchemas(schemas, regex) {
        for (const keyRef in schemas) {
          const sch = schemas[keyRef];
          if (!regex || regex.test(keyRef)) {
            if (typeof sch == "string") {
              delete schemas[keyRef];
            } else if (sch && !sch.meta) {
              this._cache.delete(sch.schema);
              delete schemas[keyRef];
            }
          }
        }
      }
      _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) {
        let id;
        const { schemaId } = this.opts;
        if (typeof schema == "object") {
          id = schema[schemaId];
        } else {
          if (this.opts.jtd)
            throw new Error("schema must be object");
          else if (typeof schema != "boolean")
            throw new Error("schema must be object or boolean");
        }
        let sch = this._cache.get(schema);
        if (sch !== void 0)
          return sch;
        baseId = (0, resolve_1.normalizeId)(id || baseId);
        const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId);
        sch = new compile_1.SchemaEnv({ schema, schemaId, meta, baseId, localRefs });
        this._cache.set(sch.schema, sch);
        if (addSchema && !baseId.startsWith("#")) {
          if (baseId)
            this._checkUnique(baseId);
          this.refs[baseId] = sch;
        }
        if (validateSchema)
          this.validateSchema(schema, true);
        return sch;
      }
      _checkUnique(id) {
        if (this.schemas[id] || this.refs[id]) {
          throw new Error(`schema with key or id "${id}" already exists`);
        }
      }
      _compileSchemaEnv(sch) {
        if (sch.meta)
          this._compileMetaSchema(sch);
        else
          compile_1.compileSchema.call(this, sch);
        if (!sch.validate)
          throw new Error("ajv implementation error");
        return sch.validate;
      }
      _compileMetaSchema(sch) {
        const currentOpts = this.opts;
        this.opts = this._metaOpts;
        try {
          compile_1.compileSchema.call(this, sch);
        } finally {
          this.opts = currentOpts;
        }
      }
    };
    Ajv2.ValidationError = validation_error_1.default;
    Ajv2.MissingRefError = ref_error_1.default;
    exports.default = Ajv2;
    function checkOptions(checkOpts, options, msg, log = "error") {
      for (const key in checkOpts) {
        const opt = key;
        if (opt in options)
          this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`);
      }
    }
    function getSchEnv(keyRef) {
      keyRef = (0, resolve_1.normalizeId)(keyRef);
      return this.schemas[keyRef] || this.refs[keyRef];
    }
    function addInitialSchemas() {
      const optsSchemas = this.opts.schemas;
      if (!optsSchemas)
        return;
      if (Array.isArray(optsSchemas))
        this.addSchema(optsSchemas);
      else
        for (const key in optsSchemas)
          this.addSchema(optsSchemas[key], key);
    }
    function addInitialFormats() {
      for (const name in this.opts.formats) {
        const format = this.opts.formats[name];
        if (format)
          this.addFormat(name, format);
      }
    }
    function addInitialKeywords(defs) {
      if (Array.isArray(defs)) {
        this.addVocabulary(defs);
        return;
      }
      this.logger.warn("keywords option as map is deprecated, pass array");
      for (const keyword in defs) {
        const def = defs[keyword];
        if (!def.keyword)
          def.keyword = keyword;
        this.addKeyword(def);
      }
    }
    function getMetaSchemaOptions() {
      const metaOpts = { ...this.opts };
      for (const opt of META_IGNORE_OPTIONS)
        delete metaOpts[opt];
      return metaOpts;
    }
    var noLogs = { log() {
    }, warn() {
    }, error() {
    } };
    function getLogger(logger2) {
      if (logger2 === false)
        return noLogs;
      if (logger2 === void 0)
        return console;
      if (logger2.log && logger2.warn && logger2.error)
        return logger2;
      throw new Error("logger must implement log, warn and error methods");
    }
    var KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i;
    function checkKeyword(keyword, def) {
      const { RULES } = this;
      (0, util_1.eachItem)(keyword, (kwd) => {
        if (RULES.keywords[kwd])
          throw new Error(`Keyword ${kwd} is already defined`);
        if (!KEYWORD_NAME.test(kwd))
          throw new Error(`Keyword ${kwd} has invalid name`);
      });
      if (!def)
        return;
      if (def.$data && !("code" in def || "validate" in def)) {
        throw new Error('$data keyword must have "code" or "validate" function');
      }
    }
    function addRule(keyword, definition, dataType) {
      var _a7;
      const post2 = definition === null || definition === void 0 ? void 0 : definition.post;
      if (dataType && post2)
        throw new Error('keyword with "post" flag cannot have "type"');
      const { RULES } = this;
      let ruleGroup = post2 ? RULES.post : RULES.rules.find(({ type: t6 }) => t6 === dataType);
      if (!ruleGroup) {
        ruleGroup = { type: dataType, rules: [] };
        RULES.rules.push(ruleGroup);
      }
      RULES.keywords[keyword] = true;
      if (!definition)
        return;
      const rule = {
        keyword,
        definition: {
          ...definition,
          type: (0, dataType_1.getJSONTypes)(definition.type),
          schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType)
        }
      };
      if (definition.before)
        addBeforeRule.call(this, ruleGroup, rule, definition.before);
      else
        ruleGroup.rules.push(rule);
      RULES.all[keyword] = rule;
      (_a7 = definition.implements) === null || _a7 === void 0 ? void 0 : _a7.forEach((kwd) => this.addKeyword(kwd));
    }
    function addBeforeRule(ruleGroup, rule, before) {
      const i7 = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);
      if (i7 >= 0) {
        ruleGroup.rules.splice(i7, 0, rule);
      } else {
        ruleGroup.rules.push(rule);
        this.logger.warn(`rule ${before} is not defined`);
      }
    }
    function keywordMetaschema(def) {
      let { metaSchema } = def;
      if (metaSchema === void 0)
        return;
      if (def.$data && this.opts.$data)
        metaSchema = schemaOrData(metaSchema);
      def.validateSchema = this.compile(metaSchema, true);
    }
    var $dataRef = {
      $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"
    };
    function schemaOrData(schema) {
      return { anyOf: [schema, $dataRef] };
    }
  }
});

// ../pi-mono/node_modules/ajv/dist/vocabularies/core/id.js
var require_id = __commonJS({
  "../pi-mono/node_modules/ajv/dist/vocabularies/core/id.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    var def = {
      keyword: "id",
      code() {
        throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID');
      }
    };
    exports.default = def;
  }
});

// ../pi-mono/node_modules/ajv/dist/vocabularies/core/ref.js
var require_ref = __commonJS({
  "../pi-mono/node_modules/ajv/dist/vocabularies/core/ref.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.callRef = exports.getValidate = void 0;
    var ref_error_1 = require_ref_error();
    var code_1 = require_code2();
    var codegen_1 = require_codegen();
    var names_1 = require_names();
    var compile_1 = require_compile();
    var util_1 = require_util2();
    var def = {
      keyword: "$ref",
      schemaType: "string",
      code(cxt) {
        const { gen, schema: $ref, it } = cxt;
        const { baseId, schemaEnv: env, validateName, opts, self: self2 } = it;
        const { root } = env;
        if (($ref === "#" || $ref === "#/") && baseId === root.baseId)
          return callRootRef();
        const schOrEnv = compile_1.resolveRef.call(self2, root, baseId, $ref);
        if (schOrEnv === void 0)
          throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref);
        if (schOrEnv instanceof compile_1.SchemaEnv)
          return callValidate(schOrEnv);
        return inlineRefSchema(schOrEnv);
        function callRootRef() {
          if (env === root)
            return callRef(cxt, validateName, env, env.$async);
          const rootName = gen.scopeValue("root", { ref: root });
          return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async);
        }
        function callValidate(sch) {
          const v4 = getValidate(cxt, sch);
          callRef(cxt, v4, sch, sch.$async);
        }
        function inlineRefSchema(sch) {
          const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch });
          const valid = gen.name("valid");
          const schCxt = cxt.subschema({
            schema: sch,
            dataTypes: [],
            schemaPath: codegen_1.nil,
            topSchemaRef: schName,
            errSchemaPath: $ref
          }, valid);
          cxt.mergeEvaluated(schCxt);
          cxt.ok(valid);
        }
      }
    };
    function getValidate(cxt, sch) {
      const { gen } = cxt;
      return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`;
    }
    exports.getValidate = getValidate;
    function callRef(cxt, v4, sch, $async) {
      const { gen, it } = cxt;
      const { allErrors, schemaEnv: env, opts } = it;
      const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil;
      if ($async)
        callAsyncRef();
      else
        callSyncRef();
      function callAsyncRef() {
        if (!env.$async)
          throw new Error("async schema referenced by sync schema");
        const valid = gen.let("valid");
        gen.try(() => {
          gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v4, passCxt)}`);
          addEvaluatedFrom(v4);
          if (!allErrors)
            gen.assign(valid, true);
        }, (e9) => {
          gen.if((0, codegen_1._)`!(${e9} instanceof ${it.ValidationError})`, () => gen.throw(e9));
          addErrorsFrom(e9);
          if (!allErrors)
            gen.assign(valid, false);
        });
        cxt.ok(valid);
      }
      function callSyncRef() {
        cxt.result((0, code_1.callValidateCode)(cxt, v4, passCxt), () => addEvaluatedFrom(v4), () => addErrorsFrom(v4));
      }
      function addErrorsFrom(source) {
        const errs = (0, codegen_1._)`${source}.errors`;
        gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`);
        gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`);
      }
      function addEvaluatedFrom(source) {
        var _a7;
        if (!it.opts.unevaluated)
          return;
        const schEvaluated = (_a7 = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a7 === void 0 ? void 0 : _a7.evaluated;
        if (it.props !== true) {
          if (schEvaluated && !schEvaluated.dynamicProps) {
            if (schEvaluated.props !== void 0) {
              it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props);
            }
          } else {
            const props = gen.var("props", (0, codegen_1._)`${source}.evaluated.props`);
            it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name);
          }
        }
        if (it.items !== true) {
          if (schEvaluated && !schEvaluated.dynamicItems) {
            if (schEvaluated.items !== void 0) {
              it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items);
            }
          } else {
            const items = gen.var("items", (0, codegen_1._)`${source}.evaluated.items`);
            it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name);
          }
        }
      }
    }
    exports.callRef = callRef;
    exports.default = def;
  }
});

// ../pi-mono/node_modules/ajv/dist/vocabularies/core/index.js
var require_core2 = __commonJS({
  "../pi-mono/node_modules/ajv/dist/vocabularies/core/index.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    var id_1 = require_id();
    var ref_1 = require_ref();
    var core = [
      "$schema",
      "$id",
      "$defs",
      "$vocabulary",
      { keyword: "$comment" },
      "definitions",
      id_1.default,
      ref_1.default
    ];
    exports.default = core;
  }
});

// ../pi-mono/node_modules/ajv/dist/vocabularies/validation/limitNumber.js
var require_limitNumber = __commonJS({
  "../pi-mono/node_modules/ajv/dist/vocabularies/validation/limitNumber.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var ops = codegen_1.operators;
    var KWDs = {
      maximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT },
      minimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT },
      exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE },
      exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE }
    };
    var error = {
      message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`,
      params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`
    };
    var def = {
      keyword: Object.keys(KWDs),
      type: "number",
      schemaType: "number",
      $data: true,
      error,
      code(cxt) {
        const { keyword, data, schemaCode } = cxt;
        cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`);
      }
    };
    exports.default = def;
  }
});

// ../pi-mono/node_modules/ajv/dist/vocabularies/validation/multipleOf.js
var require_multipleOf = __commonJS({
  "../pi-mono/node_modules/ajv/dist/vocabularies/validation/multipleOf.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var error = {
      message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`,
      params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}`
    };
    var def = {
      keyword: "multipleOf",
      type: "number",
      schemaType: "number",
      $data: true,
      error,
      code(cxt) {
        const { gen, data, schemaCode, it } = cxt;
        const prec = it.opts.multipleOfPrecision;
        const res = gen.let("res");
        const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`;
        cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`);
      }
    };
    exports.default = def;
  }
});

// ../pi-mono/node_modules/ajv/dist/runtime/ucs2length.js
var require_ucs2length = __commonJS({
  "../pi-mono/node_modules/ajv/dist/runtime/ucs2length.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    function ucs2length(str2) {
      const len = str2.length;
      let length = 0;
      let pos = 0;
      let value;
      while (pos < len) {
        length++;
        value = str2.charCodeAt(pos++);
        if (value >= 55296 && value <= 56319 && pos < len) {
          value = str2.charCodeAt(pos);
          if ((value & 64512) === 56320)
            pos++;
        }
      }
      return length;
    }
    exports.default = ucs2length;
    ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default';
  }
});

// ../pi-mono/node_modules/ajv/dist/vocabularies/validation/limitLength.js
var require_limitLength = __commonJS({
  "../pi-mono/node_modules/ajv/dist/vocabularies/validation/limitLength.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var util_1 = require_util2();
    var ucs2length_1 = require_ucs2length();
    var error = {
      message({ keyword, schemaCode }) {
        const comp = keyword === "maxLength" ? "more" : "fewer";
        return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`;
      },
      params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}`
    };
    var def = {
      keyword: ["maxLength", "minLength"],
      type: "string",
      schemaType: "number",
      $data: true,
      error,
      code(cxt) {
        const { keyword, data, schemaCode, it } = cxt;
        const op2 = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT;
        const len = it.opts.unicode === false ? (0, codegen_1._)`${data}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`;
        cxt.fail$data((0, codegen_1._)`${len} ${op2} ${schemaCode}`);
      }
    };
    exports.default = def;
  }
});

// ../pi-mono/node_modules/ajv/dist/vocabularies/validation/pattern.js
var require_pattern = __commonJS({
  "../pi-mono/node_modules/ajv/dist/vocabularies/validation/pattern.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    var code_1 = require_code2();
    var util_1 = require_util2();
    var codegen_1 = require_codegen();
    var error = {
      message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`,
      params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}`
    };
    var def = {
      keyword: "pattern",
      type: "string",
      schemaType: "string",
      $data: true,
      error,
      code(cxt) {
        const { gen, data, $data, schema, schemaCode, it } = cxt;
        const u5 = it.opts.unicodeRegExp ? "u" : "";
        if ($data) {
          const { regExp } = it.opts.code;
          const regExpCode = regExp.code === "new RegExp" ? (0, codegen_1._)`new RegExp` : (0, util_1.useFunc)(gen, regExp);
          const valid = gen.let("valid");
          gen.try(() => gen.assign(valid, (0, codegen_1._)`${regExpCode}(${schemaCode}, ${u5}).test(${data})`), () => gen.assign(valid, false));
          cxt.fail$data((0, codegen_1._)`!${valid}`);
        } else {
          const regExp = (0, code_1.usePattern)(cxt, schema);
          cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`);
        }
      }
    };
    exports.default = def;
  }
});

// ../pi-mono/node_modules/ajv/dist/vocabularies/validation/limitProperties.js
var require_limitProperties = __commonJS({
  "../pi-mono/node_modules/ajv/dist/vocabularies/validation/limitProperties.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var error = {
      message({ keyword, schemaCode }) {
        const comp = keyword === "maxProperties" ? "more" : "fewer";
        return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`;
      },
      params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}`
    };
    var def = {
      keyword: ["maxProperties", "minProperties"],
      type: "object",
      schemaType: "number",
      $data: true,
      error,
      code(cxt) {
        const { keyword, data, schemaCode } = cxt;
        const op2 = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT;
        cxt.fail$data((0, codegen_1._)`Object.keys(${data}).length ${op2} ${schemaCode}`);
      }
    };
    exports.default = def;
  }
});

// ../pi-mono/node_modules/ajv/dist/vocabularies/validation/required.js
var require_required = __commonJS({
  "../pi-mono/node_modules/ajv/dist/vocabularies/validation/required.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    var code_1 = require_code2();
    var codegen_1 = require_codegen();
    var util_1 = require_util2();
    var error = {
      message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`,
      params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}`
    };
    var def = {
      keyword: "required",
      type: "object",
      schemaType: "array",
      $data: true,
      error,
      code(cxt) {
        const { gen, schema, schemaCode, data, $data, it } = cxt;
        const { opts } = it;
        if (!$data && schema.length === 0)
          return;
        const useLoop = schema.length >= opts.loopRequired;
        if (it.allErrors)
          allErrorsMode();
        else
          exitOnErrorMode();
        if (opts.strictRequired) {
          const props = cxt.parentSchema.properties;
          const { definedProperties } = cxt.it;
          for (const requiredKey of schema) {
            if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) {
              const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;
              const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`;
              (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired);
            }
          }
        }
        function allErrorsMode() {
          if (useLoop || $data) {
            cxt.block$data(codegen_1.nil, loopAllRequired);
          } else {
            for (const prop of schema) {
              (0, code_1.checkReportMissingProp)(cxt, prop);
            }
          }
        }
        function exitOnErrorMode() {
          const missing = gen.let("missing");
          if (useLoop || $data) {
            const valid = gen.let("valid", true);
            cxt.block$data(valid, () => loopUntilMissing(missing, valid));
            cxt.ok(valid);
          } else {
            gen.if((0, code_1.checkMissingProp)(cxt, schema, missing));
            (0, code_1.reportMissingProp)(cxt, missing);
            gen.else();
          }
        }
        function loopAllRequired() {
          gen.forOf("prop", schemaCode, (prop) => {
            cxt.setParams({ missingProperty: prop });
            gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error());
          });
        }
        function loopUntilMissing(missing, valid) {
          cxt.setParams({ missingProperty: missing });
          gen.forOf(missing, schemaCode, () => {
            gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties));
            gen.if((0, codegen_1.not)(valid), () => {
              cxt.error();
              gen.break();
            });
          }, codegen_1.nil);
        }
      }
    };
    exports.default = def;
  }
});

// ../pi-mono/node_modules/ajv/dist/vocabularies/validation/limitItems.js
var require_limitItems = __commonJS({
  "../pi-mono/node_modules/ajv/dist/vocabularies/validation/limitItems.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var error = {
      message({ keyword, schemaCode }) {
        const comp = keyword === "maxItems" ? "more" : "fewer";
        return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`;
      },
      params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}`
    };
    var def = {
      keyword: ["maxItems", "minItems"],
      type: "array",
      schemaType: "number",
      $data: true,
      error,
      code(cxt) {
        const { keyword, data, schemaCode } = cxt;
        const op2 = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT;
        cxt.fail$data((0, codegen_1._)`${data}.length ${op2} ${schemaCode}`);
      }
    };
    exports.default = def;
  }
});

// ../pi-mono/node_modules/ajv/dist/runtime/equal.js
var require_equal = __commonJS({
  "../pi-mono/node_modules/ajv/dist/runtime/equal.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    var equal = require_fast_deep_equal();
    equal.code = 'require("ajv/dist/runtime/equal").default';
    exports.default = equal;
  }
});

// ../pi-mono/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js
var require_uniqueItems = __commonJS({
  "../pi-mono/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    var dataType_1 = require_dataType();
    var codegen_1 = require_codegen();
    var util_1 = require_util2();
    var equal_1 = require_equal();
    var error = {
      message: ({ params: { i: i7, j: j3 } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j3} and ${i7} are identical)`,
      params: ({ params: { i: i7, j: j3 } }) => (0, codegen_1._)`{i: ${i7}, j: ${j3}}`
    };
    var def = {
      keyword: "uniqueItems",
      type: "array",
      schemaType: "boolean",
      $data: true,
      error,
      code(cxt) {
        const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt;
        if (!$data && !schema)
          return;
        const valid = gen.let("valid");
        const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : [];
        cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`);
        cxt.ok(valid);
        function validateUniqueItems() {
          const i7 = gen.let("i", (0, codegen_1._)`${data}.length`);
          const j3 = gen.let("j");
          cxt.setParams({ i: i7, j: j3 });
          gen.assign(valid, true);
          gen.if((0, codegen_1._)`${i7} > 1`, () => (canOptimize() ? loopN : loopN2)(i7, j3));
        }
        function canOptimize() {
          return itemTypes.length > 0 && !itemTypes.some((t6) => t6 === "object" || t6 === "array");
        }
        function loopN(i7, j3) {
          const item = gen.name("item");
          const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong);
          const indices = gen.const("indices", (0, codegen_1._)`{}`);
          gen.for((0, codegen_1._)`;${i7}--;`, () => {
            gen.let(item, (0, codegen_1._)`${data}[${i7}]`);
            gen.if(wrongType, (0, codegen_1._)`continue`);
            if (itemTypes.length > 1)
              gen.if((0, codegen_1._)`typeof ${item} == "string"`, (0, codegen_1._)`${item} += "_"`);
            gen.if((0, codegen_1._)`typeof ${indices}[${item}] == "number"`, () => {
              gen.assign(j3, (0, codegen_1._)`${indices}[${item}]`);
              cxt.error();
              gen.assign(valid, false).break();
            }).code((0, codegen_1._)`${indices}[${item}] = ${i7}`);
          });
        }
        function loopN2(i7, j3) {
          const eql = (0, util_1.useFunc)(gen, equal_1.default);
          const outer = gen.name("outer");
          gen.label(outer).for((0, codegen_1._)`;${i7}--;`, () => gen.for((0, codegen_1._)`${j3} = ${i7}; ${j3}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i7}], ${data}[${j3}])`, () => {
            cxt.error();
            gen.assign(valid, false).break(outer);
          })));
        }
      }
    };
    exports.default = def;
  }
});

// ../pi-mono/node_modules/ajv/dist/vocabularies/validation/const.js
var require_const = __commonJS({
  "../pi-mono/node_modules/ajv/dist/vocabularies/validation/const.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var util_1 = require_util2();
    var equal_1 = require_equal();
    var error = {
      message: "must be equal to constant",
      params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}`
    };
    var def = {
      keyword: "const",
      $data: true,
      error,
      code(cxt) {
        const { gen, data, $data, schemaCode, schema } = cxt;
        if ($data || schema && typeof schema == "object") {
          cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`);
        } else {
          cxt.fail((0, codegen_1._)`${schema} !== ${data}`);
        }
      }
    };
    exports.default = def;
  }
});

// ../pi-mono/node_modules/ajv/dist/vocabularies/validation/enum.js
var require_enum2 = __commonJS({
  "../pi-mono/node_modules/ajv/dist/vocabularies/validation/enum.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var util_1 = require_util2();
    var equal_1 = require_equal();
    var error = {
      message: "must be equal to one of the allowed values",
      params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}`
    };
    var def = {
      keyword: "enum",
      schemaType: "array",
      $data: true,
      error,
      code(cxt) {
        const { gen, data, $data, schema, schemaCode, it } = cxt;
        if (!$data && schema.length === 0)
          throw new Error("enum must have non-empty array");
        const useLoop = schema.length >= it.opts.loopEnum;
        let eql;
        const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default);
        let valid;
        if (useLoop || $data) {
          valid = gen.let("valid");
          cxt.block$data(valid, loopEnum);
        } else {
          if (!Array.isArray(schema))
            throw new Error("ajv implementation error");
          const vSchema = gen.const("vSchema", schemaCode);
          valid = (0, codegen_1.or)(...schema.map((_x, i7) => equalCode(vSchema, i7)));
        }
        cxt.pass(valid);
        function loopEnum() {
          gen.assign(valid, false);
          gen.forOf("v", schemaCode, (v4) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v4})`, () => gen.assign(valid, true).break()));
        }
        function equalCode(vSchema, i7) {
          const sch = schema[i7];
          return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i7}])` : (0, codegen_1._)`${data} === ${sch}`;
        }
      }
    };
    exports.default = def;
  }
});

// ../pi-mono/node_modules/ajv/dist/vocabularies/validation/index.js
var require_validation = __commonJS({
  "../pi-mono/node_modules/ajv/dist/vocabularies/validation/index.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    var limitNumber_1 = require_limitNumber();
    var multipleOf_1 = require_multipleOf();
    var limitLength_1 = require_limitLength();
    var pattern_1 = require_pattern();
    var limitProperties_1 = require_limitProperties();
    var required_1 = require_required();
    var limitItems_1 = require_limitItems();
    var uniqueItems_1 = require_uniqueItems();
    var const_1 = require_const();
    var enum_1 = require_enum2();
    var validation = [
      // number
      limitNumber_1.default,
      multipleOf_1.default,
      // string
      limitLength_1.default,
      pattern_1.default,
      // object
      limitProperties_1.default,
      required_1.default,
      // array
      limitItems_1.default,
      uniqueItems_1.default,
      // any
      { keyword: "type", schemaType: ["string", "array"] },
      { keyword: "nullable", schemaType: "boolean" },
      const_1.default,
      enum_1.default
    ];
    exports.default = validation;
  }
});

// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js
var require_additionalItems = __commonJS({
  "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.validateAdditionalItems = void 0;
    var codegen_1 = require_codegen();
    var util_1 = require_util2();
    var error = {
      message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`,
      params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}`
    };
    var def = {
      keyword: "additionalItems",
      type: "array",
      schemaType: ["boolean", "object"],
      before: "uniqueItems",
      error,
      code(cxt) {
        const { parentSchema, it } = cxt;
        const { items } = parentSchema;
        if (!Array.isArray(items)) {
          (0, util_1.checkStrictMode)(it, '"additionalItems" is ignored when "items" is not an array of schemas');
          return;
        }
        validateAdditionalItems(cxt, items);
      }
    };
    function validateAdditionalItems(cxt, items) {
      const { gen, schema, data, keyword, it } = cxt;
      it.items = true;
      const len = gen.const("len", (0, codegen_1._)`${data}.length`);
      if (schema === false) {
        cxt.setParams({ len: items.length });
        cxt.pass((0, codegen_1._)`${len} <= ${items.length}`);
      } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
        const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items.length}`);
        gen.if((0, codegen_1.not)(valid), () => validateItems(valid));
        cxt.ok(valid);
      }
      function validateItems(valid) {
        gen.forRange("i", items.length, len, (i7) => {
          cxt.subschema({ keyword, dataProp: i7, dataPropType: util_1.Type.Num }, valid);
          if (!it.allErrors)
            gen.if((0, codegen_1.not)(valid), () => gen.break());
        });
      }
    }
    exports.validateAdditionalItems = validateAdditionalItems;
    exports.default = def;
  }
});

// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/items.js
var require_items = __commonJS({
  "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/items.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.validateTuple = void 0;
    var codegen_1 = require_codegen();
    var util_1 = require_util2();
    var code_1 = require_code2();
    var def = {
      keyword: "items",
      type: "array",
      schemaType: ["object", "array", "boolean"],
      before: "uniqueItems",
      code(cxt) {
        const { schema, it } = cxt;
        if (Array.isArray(schema))
          return validateTuple(cxt, "additionalItems", schema);
        it.items = true;
        if ((0, util_1.alwaysValidSchema)(it, schema))
          return;
        cxt.ok((0, code_1.validateArray)(cxt));
      }
    };
    function validateTuple(cxt, extraItems, schArr = cxt.schema) {
      const { gen, parentSchema, data, keyword, it } = cxt;
      checkStrictTuple(parentSchema);
      if (it.opts.unevaluated && schArr.length && it.items !== true) {
        it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items);
      }
      const valid = gen.name("valid");
      const len = gen.const("len", (0, codegen_1._)`${data}.length`);
      schArr.forEach((sch, i7) => {
        if ((0, util_1.alwaysValidSchema)(it, sch))
          return;
        gen.if((0, codegen_1._)`${len} > ${i7}`, () => cxt.subschema({
          keyword,
          schemaProp: i7,
          dataProp: i7
        }, valid));
        cxt.ok(valid);
      });
      function checkStrictTuple(sch) {
        const { opts, errSchemaPath } = it;
        const l5 = schArr.length;
        const fullTuple = l5 === sch.minItems && (l5 === sch.maxItems || sch[extraItems] === false);
        if (opts.strictTuples && !fullTuple) {
          const msg = `"${keyword}" is ${l5}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`;
          (0, util_1.checkStrictMode)(it, msg, opts.strictTuples);
        }
      }
    }
    exports.validateTuple = validateTuple;
    exports.default = def;
  }
});

// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js
var require_prefixItems = __commonJS({
  "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    var items_1 = require_items();
    var def = {
      keyword: "prefixItems",
      type: "array",
      schemaType: ["array"],
      before: "uniqueItems",
      code: (cxt) => (0, items_1.validateTuple)(cxt, "items")
    };
    exports.default = def;
  }
});

// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/items2020.js
var require_items2020 = __commonJS({
  "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/items2020.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var util_1 = require_util2();
    var code_1 = require_code2();
    var additionalItems_1 = require_additionalItems();
    var error = {
      message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`,
      params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}`
    };
    var def = {
      keyword: "items",
      type: "array",
      schemaType: ["object", "boolean"],
      before: "uniqueItems",
      error,
      code(cxt) {
        const { schema, parentSchema, it } = cxt;
        const { prefixItems } = parentSchema;
        it.items = true;
        if ((0, util_1.alwaysValidSchema)(it, schema))
          return;
        if (prefixItems)
          (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems);
        else
          cxt.ok((0, code_1.validateArray)(cxt));
      }
    };
    exports.default = def;
  }
});

// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/contains.js
var require_contains = __commonJS({
  "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/contains.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var util_1 = require_util2();
    var error = {
      message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`,
      params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}`
    };
    var def = {
      keyword: "contains",
      type: "array",
      schemaType: ["object", "boolean"],
      before: "uniqueItems",
      trackErrors: true,
      error,
      code(cxt) {
        const { gen, schema, parentSchema, data, it } = cxt;
        let min;
        let max;
        const { minContains, maxContains } = parentSchema;
        if (it.opts.next) {
          min = minContains === void 0 ? 1 : minContains;
          max = maxContains;
        } else {
          min = 1;
        }
        const len = gen.const("len", (0, codegen_1._)`${data}.length`);
        cxt.setParams({ min, max });
        if (max === void 0 && min === 0) {
          (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`);
          return;
        }
        if (max !== void 0 && min > max) {
          (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`);
          cxt.fail();
          return;
        }
        if ((0, util_1.alwaysValidSchema)(it, schema)) {
          let cond = (0, codegen_1._)`${len} >= ${min}`;
          if (max !== void 0)
            cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`;
          cxt.pass(cond);
          return;
        }
        it.items = true;
        const valid = gen.name("valid");
        if (max === void 0 && min === 1) {
          validateItems(valid, () => gen.if(valid, () => gen.break()));
        } else if (min === 0) {
          gen.let(valid, true);
          if (max !== void 0)
            gen.if((0, codegen_1._)`${data}.length > 0`, validateItemsWithCount);
        } else {
          gen.let(valid, false);
          validateItemsWithCount();
        }
        cxt.result(valid, () => cxt.reset());
        function validateItemsWithCount() {
          const schValid = gen.name("_valid");
          const count = gen.let("count", 0);
          validateItems(schValid, () => gen.if(schValid, () => checkLimits(count)));
        }
        function validateItems(_valid, block) {
          gen.forRange("i", 0, len, (i7) => {
            cxt.subschema({
              keyword: "contains",
              dataProp: i7,
              dataPropType: util_1.Type.Num,
              compositeRule: true
            }, _valid);
            block();
          });
        }
        function checkLimits(count) {
          gen.code((0, codegen_1._)`${count}++`);
          if (max === void 0) {
            gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break());
          } else {
            gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break());
            if (min === 1)
              gen.assign(valid, true);
            else
              gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true));
          }
        }
      }
    };
    exports.default = def;
  }
});

// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/dependencies.js
var require_dependencies = __commonJS({
  "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/dependencies.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0;
    var codegen_1 = require_codegen();
    var util_1 = require_util2();
    var code_1 = require_code2();
    exports.error = {
      message: ({ params: { property, depsCount, deps } }) => {
        const property_ies = depsCount === 1 ? "property" : "properties";
        return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`;
      },
      params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property},
    missingProperty: ${missingProperty},
    depsCount: ${depsCount},
    deps: ${deps}}`
      // TODO change to reference
    };
    var def = {
      keyword: "dependencies",
      type: "object",
      schemaType: "object",
      error: exports.error,
      code(cxt) {
        const [propDeps, schDeps] = splitDependencies(cxt);
        validatePropertyDeps(cxt, propDeps);
        validateSchemaDeps(cxt, schDeps);
      }
    };
    function splitDependencies({ schema }) {
      const propertyDeps = {};
      const schemaDeps = {};
      for (const key in schema) {
        if (key === "__proto__")
          continue;
        const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps;
        deps[key] = schema[key];
      }
      return [propertyDeps, schemaDeps];
    }
    function validatePropertyDeps(cxt, propertyDeps = cxt.schema) {
      const { gen, data, it } = cxt;
      if (Object.keys(propertyDeps).length === 0)
        return;
      const missing = gen.let("missing");
      for (const prop in propertyDeps) {
        const deps = propertyDeps[prop];
        if (deps.length === 0)
          continue;
        const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties);
        cxt.setParams({
          property: prop,
          depsCount: deps.length,
          deps: deps.join(", ")
        });
        if (it.allErrors) {
          gen.if(hasProperty, () => {
            for (const depProp of deps) {
              (0, code_1.checkReportMissingProp)(cxt, depProp);
            }
          });
        } else {
          gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`);
          (0, code_1.reportMissingProp)(cxt, missing);
          gen.else();
        }
      }
    }
    exports.validatePropertyDeps = validatePropertyDeps;
    function validateSchemaDeps(cxt, schemaDeps = cxt.schema) {
      const { gen, data, keyword, it } = cxt;
      const valid = gen.name("valid");
      for (const prop in schemaDeps) {
        if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop]))
          continue;
        gen.if(
          (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties),
          () => {
            const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid);
            cxt.mergeValidEvaluated(schCxt, valid);
          },
          () => gen.var(valid, true)
          // TODO var
        );
        cxt.ok(valid);
      }
    }
    exports.validateSchemaDeps = validateSchemaDeps;
    exports.default = def;
  }
});

// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js
var require_propertyNames = __commonJS({
  "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var util_1 = require_util2();
    var error = {
      message: "property name must be valid",
      params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}`
    };
    var def = {
      keyword: "propertyNames",
      type: "object",
      schemaType: ["object", "boolean"],
      error,
      code(cxt) {
        const { gen, schema, data, it } = cxt;
        if ((0, util_1.alwaysValidSchema)(it, schema))
          return;
        const valid = gen.name("valid");
        gen.forIn("key", data, (key) => {
          cxt.setParams({ propertyName: key });
          cxt.subschema({
            keyword: "propertyNames",
            data: key,
            dataTypes: ["string"],
            propertyName: key,
            compositeRule: true
          }, valid);
          gen.if((0, codegen_1.not)(valid), () => {
            cxt.error(true);
            if (!it.allErrors)
              gen.break();
          });
        });
        cxt.ok(valid);
      }
    };
    exports.default = def;
  }
});

// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js
var require_additionalProperties = __commonJS({
  "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    var code_1 = require_code2();
    var codegen_1 = require_codegen();
    var names_1 = require_names();
    var util_1 = require_util2();
    var error = {
      message: "must NOT have additional properties",
      params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}`
    };
    var def = {
      keyword: "additionalProperties",
      type: ["object"],
      schemaType: ["boolean", "object"],
      allowUndefined: true,
      trackErrors: true,
      error,
      code(cxt) {
        const { gen, schema, parentSchema, data, errsCount, it } = cxt;
        if (!errsCount)
          throw new Error("ajv implementation error");
        const { allErrors, opts } = it;
        it.props = true;
        if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema))
          return;
        const props = (0, code_1.allSchemaProperties)(parentSchema.properties);
        const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties);
        checkAdditionalProperties();
        cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`);
        function checkAdditionalProperties() {
          gen.forIn("key", data, (key) => {
            if (!props.length && !patProps.length)
              additionalPropertyCode(key);
            else
              gen.if(isAdditional(key), () => additionalPropertyCode(key));
          });
        }
        function isAdditional(key) {
          let definedProp;
          if (props.length > 8) {
            const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties");
            definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key);
          } else if (props.length) {
            definedProp = (0, codegen_1.or)(...props.map((p4) => (0, codegen_1._)`${key} === ${p4}`));
          } else {
            definedProp = codegen_1.nil;
          }
          if (patProps.length) {
            definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p4) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p4)}.test(${key})`));
          }
          return (0, codegen_1.not)(definedProp);
        }
        function deleteAdditional(key) {
          gen.code((0, codegen_1._)`delete ${data}[${key}]`);
        }
        function additionalPropertyCode(key) {
          if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) {
            deleteAdditional(key);
            return;
          }
          if (schema === false) {
            cxt.setParams({ additionalProperty: key });
            cxt.error();
            if (!allErrors)
              gen.break();
            return;
          }
          if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
            const valid = gen.name("valid");
            if (opts.removeAdditional === "failing") {
              applyAdditionalSchema(key, valid, false);
              gen.if((0, codegen_1.not)(valid), () => {
                cxt.reset();
                deleteAdditional(key);
              });
            } else {
              applyAdditionalSchema(key, valid);
              if (!allErrors)
                gen.if((0, codegen_1.not)(valid), () => gen.break());
            }
          }
        }
        function applyAdditionalSchema(key, valid, errors) {
          const subschema = {
            keyword: "additionalProperties",
            dataProp: key,
            dataPropType: util_1.Type.Str
          };
          if (errors === false) {
            Object.assign(subschema, {
              compositeRule: true,
              createErrors: false,
              allErrors: false
            });
          }
          cxt.subschema(subschema, valid);
        }
      }
    };
    exports.default = def;
  }
});

// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/properties.js
var require_properties = __commonJS({
  "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/properties.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    var validate_1 = require_validate();
    var code_1 = require_code2();
    var util_1 = require_util2();
    var additionalProperties_1 = require_additionalProperties();
    var def = {
      keyword: "properties",
      type: "object",
      schemaType: "object",
      code(cxt) {
        const { gen, schema, parentSchema, data, it } = cxt;
        if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) {
          additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties"));
        }
        const allProps = (0, code_1.allSchemaProperties)(schema);
        for (const prop of allProps) {
          it.definedProperties.add(prop);
        }
        if (it.opts.unevaluated && allProps.length && it.props !== true) {
          it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props);
        }
        const properties = allProps.filter((p4) => !(0, util_1.alwaysValidSchema)(it, schema[p4]));
        if (properties.length === 0)
          return;
        const valid = gen.name("valid");
        for (const prop of properties) {
          if (hasDefault(prop)) {
            applyPropertySchema(prop);
          } else {
            gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties));
            applyPropertySchema(prop);
            if (!it.allErrors)
              gen.else().var(valid, true);
            gen.endIf();
          }
          cxt.it.definedProperties.add(prop);
          cxt.ok(valid);
        }
        function hasDefault(prop) {
          return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== void 0;
        }
        function applyPropertySchema(prop) {
          cxt.subschema({
            keyword: "properties",
            schemaProp: prop,
            dataProp: prop
          }, valid);
        }
      }
    };
    exports.default = def;
  }
});

// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js
var require_patternProperties = __commonJS({
  "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    var code_1 = require_code2();
    var codegen_1 = require_codegen();
    var util_1 = require_util2();
    var util_2 = require_util2();
    var def = {
      keyword: "patternProperties",
      type: "object",
      schemaType: "object",
      code(cxt) {
        const { gen, schema, data, parentSchema, it } = cxt;
        const { opts } = it;
        const patterns = (0, code_1.allSchemaProperties)(schema);
        const alwaysValidPatterns = patterns.filter((p4) => (0, util_1.alwaysValidSchema)(it, schema[p4]));
        if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) {
          return;
        }
        const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties;
        const valid = gen.name("valid");
        if (it.props !== true && !(it.props instanceof codegen_1.Name)) {
          it.props = (0, util_2.evaluatedPropsToName)(gen, it.props);
        }
        const { props } = it;
        validatePatternProperties();
        function validatePatternProperties() {
          for (const pat of patterns) {
            if (checkProperties)
              checkMatchingProperties(pat);
            if (it.allErrors) {
              validateProperties(pat);
            } else {
              gen.var(valid, true);
              validateProperties(pat);
              gen.if(valid);
            }
          }
        }
        function checkMatchingProperties(pat) {
          for (const prop in checkProperties) {
            if (new RegExp(pat).test(prop)) {
              (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`);
            }
          }
        }
        function validateProperties(pat) {
          gen.forIn("key", data, (key) => {
            gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => {
              const alwaysValid = alwaysValidPatterns.includes(pat);
              if (!alwaysValid) {
                cxt.subschema({
                  keyword: "patternProperties",
                  schemaProp: pat,
                  dataProp: key,
                  dataPropType: util_2.Type.Str
                }, valid);
              }
              if (it.opts.unevaluated && props !== true) {
                gen.assign((0, codegen_1._)`${props}[${key}]`, true);
              } else if (!alwaysValid && !it.allErrors) {
                gen.if((0, codegen_1.not)(valid), () => gen.break());
              }
            });
          });
        }
      }
    };
    exports.default = def;
  }
});

// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/not.js
var require_not = __commonJS({
  "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/not.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    var util_1 = require_util2();
    var def = {
      keyword: "not",
      schemaType: ["object", "boolean"],
      trackErrors: true,
      code(cxt) {
        const { gen, schema, it } = cxt;
        if ((0, util_1.alwaysValidSchema)(it, schema)) {
          cxt.fail();
          return;
        }
        const valid = gen.name("valid");
        cxt.subschema({
          keyword: "not",
          compositeRule: true,
          createErrors: false,
          allErrors: false
        }, valid);
        cxt.failResult(valid, () => cxt.reset(), () => cxt.error());
      },
      error: { message: "must NOT be valid" }
    };
    exports.default = def;
  }
});

// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/anyOf.js
var require_anyOf = __commonJS({
  "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/anyOf.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    var code_1 = require_code2();
    var def = {
      keyword: "anyOf",
      schemaType: "array",
      trackErrors: true,
      code: code_1.validateUnion,
      error: { message: "must match a schema in anyOf" }
    };
    exports.default = def;
  }
});

// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/oneOf.js
var require_oneOf = __commonJS({
  "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/oneOf.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var util_1 = require_util2();
    var error = {
      message: "must match exactly one schema in oneOf",
      params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}`
    };
    var def = {
      keyword: "oneOf",
      schemaType: "array",
      trackErrors: true,
      error,
      code(cxt) {
        const { gen, schema, parentSchema, it } = cxt;
        if (!Array.isArray(schema))
          throw new Error("ajv implementation error");
        if (it.opts.discriminator && parentSchema.discriminator)
          return;
        const schArr = schema;
        const valid = gen.let("valid", false);
        const passing = gen.let("passing", null);
        const schValid = gen.name("_valid");
        cxt.setParams({ passing });
        gen.block(validateOneOf);
        cxt.result(valid, () => cxt.reset(), () => cxt.error(true));
        function validateOneOf() {
          schArr.forEach((sch, i7) => {
            let schCxt;
            if ((0, util_1.alwaysValidSchema)(it, sch)) {
              gen.var(schValid, true);
            } else {
              schCxt = cxt.subschema({
                keyword: "oneOf",
                schemaProp: i7,
                compositeRule: true
              }, schValid);
            }
            if (i7 > 0) {
              gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i7}]`).else();
            }
            gen.if(schValid, () => {
              gen.assign(valid, true);
              gen.assign(passing, i7);
              if (schCxt)
                cxt.mergeEvaluated(schCxt, codegen_1.Name);
            });
          });
        }
      }
    };
    exports.default = def;
  }
});

// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/allOf.js
var require_allOf = __commonJS({
  "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/allOf.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    var util_1 = require_util2();
    var def = {
      keyword: "allOf",
      schemaType: "array",
      code(cxt) {
        const { gen, schema, it } = cxt;
        if (!Array.isArray(schema))
          throw new Error("ajv implementation error");
        const valid = gen.name("valid");
        schema.forEach((sch, i7) => {
          if ((0, util_1.alwaysValidSchema)(it, sch))
            return;
          const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i7 }, valid);
          cxt.ok(valid);
          cxt.mergeEvaluated(schCxt);
        });
      }
    };
    exports.default = def;
  }
});

// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/if.js
var require_if = __commonJS({
  "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/if.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var util_1 = require_util2();
    var error = {
      message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`,
      params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}`
    };
    var def = {
      keyword: "if",
      schemaType: ["object", "boolean"],
      trackErrors: true,
      error,
      code(cxt) {
        const { gen, parentSchema, it } = cxt;
        if (parentSchema.then === void 0 && parentSchema.else === void 0) {
          (0, util_1.checkStrictMode)(it, '"if" without "then" and "else" is ignored');
        }
        const hasThen = hasSchema(it, "then");
        const hasElse = hasSchema(it, "else");
        if (!hasThen && !hasElse)
          return;
        const valid = gen.let("valid", true);
        const schValid = gen.name("_valid");
        validateIf();
        cxt.reset();
        if (hasThen && hasElse) {
          const ifClause = gen.let("ifClause");
          cxt.setParams({ ifClause });
          gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause));
        } else if (hasThen) {
          gen.if(schValid, validateClause("then"));
        } else {
          gen.if((0, codegen_1.not)(schValid), validateClause("else"));
        }
        cxt.pass(valid, () => cxt.error(true));
        function validateIf() {
          const schCxt = cxt.subschema({
            keyword: "if",
            compositeRule: true,
            createErrors: false,
            allErrors: false
          }, schValid);
          cxt.mergeEvaluated(schCxt);
        }
        function validateClause(keyword, ifClause) {
          return () => {
            const schCxt = cxt.subschema({ keyword }, schValid);
            gen.assign(valid, schValid);
            cxt.mergeValidEvaluated(schCxt, valid);
            if (ifClause)
              gen.assign(ifClause, (0, codegen_1._)`${keyword}`);
            else
              cxt.setParams({ ifClause: keyword });
          };
        }
      }
    };
    function hasSchema(it, keyword) {
      const schema = it.schema[keyword];
      return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it, schema);
    }
    exports.default = def;
  }
});

// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/thenElse.js
var require_thenElse = __commonJS({
  "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/thenElse.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    var util_1 = require_util2();
    var def = {
      keyword: ["then", "else"],
      schemaType: ["object", "boolean"],
      code({ keyword, parentSchema, it }) {
        if (parentSchema.if === void 0)
          (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`);
      }
    };
    exports.default = def;
  }
});

// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/index.js
var require_applicator = __commonJS({
  "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/index.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    var additionalItems_1 = require_additionalItems();
    var prefixItems_1 = require_prefixItems();
    var items_1 = require_items();
    var items2020_1 = require_items2020();
    var contains_1 = require_contains();
    var dependencies_1 = require_dependencies();
    var propertyNames_1 = require_propertyNames();
    var additionalProperties_1 = require_additionalProperties();
    var properties_1 = require_properties();
    var patternProperties_1 = require_patternProperties();
    var not_1 = require_not();
    var anyOf_1 = require_anyOf();
    var oneOf_1 = require_oneOf();
    var allOf_1 = require_allOf();
    var if_1 = require_if();
    var thenElse_1 = require_thenElse();
    function getApplicator(draft2020 = false) {
      const applicator = [
        // any
        not_1.default,
        anyOf_1.default,
        oneOf_1.default,
        allOf_1.default,
        if_1.default,
        thenElse_1.default,
        // object
        propertyNames_1.default,
        additionalProperties_1.default,
        dependencies_1.default,
        properties_1.default,
        patternProperties_1.default
      ];
      if (draft2020)
        applicator.push(prefixItems_1.default, items2020_1.default);
      else
        applicator.push(additionalItems_1.default, items_1.default);
      applicator.push(contains_1.default);
      return applicator;
    }
    exports.default = getApplicator;
  }
});

// ../pi-mono/node_modules/ajv/dist/vocabularies/format/format.js
var require_format = __commonJS({
  "../pi-mono/node_modules/ajv/dist/vocabularies/format/format.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var error = {
      message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`,
      params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}`
    };
    var def = {
      keyword: "format",
      type: ["number", "string"],
      schemaType: "string",
      $data: true,
      error,
      code(cxt, ruleType) {
        const { gen, data, $data, schema, schemaCode, it } = cxt;
        const { opts, errSchemaPath, schemaEnv, self: self2 } = it;
        if (!opts.validateFormats)
          return;
        if ($data)
          validate$DataFormat();
        else
          validateFormat();
        function validate$DataFormat() {
          const fmts = gen.scopeValue("formats", {
            ref: self2.formats,
            code: opts.code.formats
          });
          const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`);
          const fType = gen.let("fType");
          const format = gen.let("format");
          gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format, fDef));
          cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt()));
          function unknownFmt() {
            if (opts.strictSchema === false)
              return codegen_1.nil;
            return (0, codegen_1._)`${schemaCode} && !${format}`;
          }
          function invalidFmt() {
            const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` : (0, codegen_1._)`${format}(${data})`;
            const validData = (0, codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`;
            return (0, codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`;
          }
        }
        function validateFormat() {
          const formatDef = self2.formats[schema];
          if (!formatDef) {
            unknownFormat();
            return;
          }
          if (formatDef === true)
            return;
          const [fmtType, format, fmtRef] = getFormat(formatDef);
          if (fmtType === ruleType)
            cxt.pass(validCondition());
          function unknownFormat() {
            if (opts.strictSchema === false) {
              self2.logger.warn(unknownMsg());
              return;
            }
            throw new Error(unknownMsg());
            function unknownMsg() {
              return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`;
            }
          }
          function getFormat(fmtDef) {
            const code = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` : void 0;
            const fmt = gen.scopeValue("formats", { key: schema, ref: fmtDef, code });
            if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) {
              return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1._)`${fmt}.validate`];
            }
            return ["string", fmtDef, fmt];
          }
          function validCondition() {
            if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) {
              if (!schemaEnv.$async)
                throw new Error("async format in sync schema");
              return (0, codegen_1._)`await ${fmtRef}(${data})`;
            }
            return typeof format == "function" ? (0, codegen_1._)`${fmtRef}(${data})` : (0, codegen_1._)`${fmtRef}.test(${data})`;
          }
        }
      }
    };
    exports.default = def;
  }
});

// ../pi-mono/node_modules/ajv/dist/vocabularies/format/index.js
var require_format2 = __commonJS({
  "../pi-mono/node_modules/ajv/dist/vocabularies/format/index.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    var format_1 = require_format();
    var format = [format_1.default];
    exports.default = format;
  }
});

// ../pi-mono/node_modules/ajv/dist/vocabularies/metadata.js
var require_metadata = __commonJS({
  "../pi-mono/node_modules/ajv/dist/vocabularies/metadata.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.contentVocabulary = exports.metadataVocabulary = void 0;
    exports.metadataVocabulary = [
      "title",
      "description",
      "default",
      "deprecated",
      "readOnly",
      "writeOnly",
      "examples"
    ];
    exports.contentVocabulary = [
      "contentMediaType",
      "contentEncoding",
      "contentSchema"
    ];
  }
});

// ../pi-mono/node_modules/ajv/dist/vocabularies/draft7.js
var require_draft7 = __commonJS({
  "../pi-mono/node_modules/ajv/dist/vocabularies/draft7.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    var core_1 = require_core2();
    var validation_1 = require_validation();
    var applicator_1 = require_applicator();
    var format_1 = require_format2();
    var metadata_1 = require_metadata();
    var draft7Vocabularies = [
      core_1.default,
      validation_1.default,
      (0, applicator_1.default)(),
      format_1.default,
      metadata_1.metadataVocabulary,
      metadata_1.contentVocabulary
    ];
    exports.default = draft7Vocabularies;
  }
});

// ../pi-mono/node_modules/ajv/dist/vocabularies/discriminator/types.js
var require_types2 = __commonJS({
  "../pi-mono/node_modules/ajv/dist/vocabularies/discriminator/types.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DiscrError = void 0;
    var DiscrError;
    (function(DiscrError2) {
      DiscrError2["Tag"] = "tag";
      DiscrError2["Mapping"] = "mapping";
    })(DiscrError || (exports.DiscrError = DiscrError = {}));
  }
});

// ../pi-mono/node_modules/ajv/dist/vocabularies/discriminator/index.js
var require_discriminator = __commonJS({
  "../pi-mono/node_modules/ajv/dist/vocabularies/discriminator/index.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var types_1 = require_types2();
    var compile_1 = require_compile();
    var ref_error_1 = require_ref_error();
    var util_1 = require_util2();
    var error = {
      message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`,
      params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`
    };
    var def = {
      keyword: "discriminator",
      type: "object",
      schemaType: "object",
      error,
      code(cxt) {
        const { gen, data, schema, parentSchema, it } = cxt;
        const { oneOf } = parentSchema;
        if (!it.opts.discriminator) {
          throw new Error("discriminator: requires discriminator option");
        }
        const tagName = schema.propertyName;
        if (typeof tagName != "string")
          throw new Error("discriminator: requires propertyName");
        if (schema.mapping)
          throw new Error("discriminator: mapping is not supported");
        if (!oneOf)
          throw new Error("discriminator: requires oneOf keyword");
        const valid = gen.let("valid", false);
        const tag = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`);
        gen.if((0, codegen_1._)`typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag, tagName }));
        cxt.ok(valid);
        function validateMapping() {
          const mapping = getMapping();
          gen.if(false);
          for (const tagValue in mapping) {
            gen.elseIf((0, codegen_1._)`${tag} === ${tagValue}`);
            gen.assign(valid, applyTagSchema(mapping[tagValue]));
          }
          gen.else();
          cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag, tagName });
          gen.endIf();
        }
        function applyTagSchema(schemaProp) {
          const _valid = gen.name("valid");
          const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid);
          cxt.mergeEvaluated(schCxt, codegen_1.Name);
          return _valid;
        }
        function getMapping() {
          var _a7;
          const oneOfMapping = {};
          const topRequired = hasRequired(parentSchema);
          let tagRequired = true;
          for (let i7 = 0; i7 < oneOf.length; i7++) {
            let sch = oneOf[i7];
            if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) {
              const ref = sch.$ref;
              sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref);
              if (sch instanceof compile_1.SchemaEnv)
                sch = sch.schema;
              if (sch === void 0)
                throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref);
            }
            const propSch = (_a7 = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a7 === void 0 ? void 0 : _a7[tagName];
            if (typeof propSch != "object") {
              throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`);
            }
            tagRequired = tagRequired && (topRequired || hasRequired(sch));
            addMappings(propSch, i7);
          }
          if (!tagRequired)
            throw new Error(`discriminator: "${tagName}" must be required`);
          return oneOfMapping;
          function hasRequired({ required }) {
            return Array.isArray(required) && required.includes(tagName);
          }
          function addMappings(sch, i7) {
            if (sch.const) {
              addMapping(sch.const, i7);
            } else if (sch.enum) {
              for (const tagValue of sch.enum) {
                addMapping(tagValue, i7);
              }
            } else {
              throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`);
            }
          }
          function addMapping(tagValue, i7) {
            if (typeof tagValue != "string" || tagValue in oneOfMapping) {
              throw new Error(`discriminator: "${tagName}" values must be unique strings`);
            }
            oneOfMapping[tagValue] = i7;
          }
        }
      }
    };
    exports.default = def;
  }
});

// ../pi-mono/node_modules/ajv/dist/refs/json-schema-draft-07.json
var require_json_schema_draft_07 = __commonJS({
  "../pi-mono/node_modules/ajv/dist/refs/json-schema-draft-07.json"(exports, module) {
    module.exports = {
      $schema: "http://json-schema.org/draft-07/schema#",
      $id: "http://json-schema.org/draft-07/schema#",
      title: "Core schema meta-schema",
      definitions: {
        schemaArray: {
          type: "array",
          minItems: 1,
          items: { $ref: "#" }
        },
        nonNegativeInteger: {
          type: "integer",
          minimum: 0
        },
        nonNegativeIntegerDefault0: {
          allOf: [{ $ref: "#/definitions/nonNegativeInteger" }, { default: 0 }]
        },
        simpleTypes: {
          enum: ["array", "boolean", "integer", "null", "number", "object", "string"]
        },
        stringArray: {
          type: "array",
          items: { type: "string" },
          uniqueItems: true,
          default: []
        }
      },
      type: ["object", "boolean"],
      properties: {
        $id: {
          type: "string",
          format: "uri-reference"
        },
        $schema: {
          type: "string",
          format: "uri"
        },
        $ref: {
          type: "string",
          format: "uri-reference"
        },
        $comment: {
          type: "string"
        },
        title: {
          type: "string"
        },
        description: {
          type: "string"
        },
        default: true,
        readOnly: {
          type: "boolean",
          default: false
        },
        examples: {
          type: "array",
          items: true
        },
        multipleOf: {
          type: "number",
          exclusiveMinimum: 0
        },
        maximum: {
          type: "number"
        },
        exclusiveMaximum: {
          type: "number"
        },
        minimum: {
          type: "number"
        },
        exclusiveMinimum: {
          type: "number"
        },
        maxLength: { $ref: "#/definitions/nonNegativeInteger" },
        minLength: { $ref: "#/definitions/nonNegativeIntegerDefault0" },
        pattern: {
          type: "string",
          format: "regex"
        },
        additionalItems: { $ref: "#" },
        items: {
          anyOf: [{ $ref: "#" }, { $ref: "#/definitions/schemaArray" }],
          default: true
        },
        maxItems: { $ref: "#/definitions/nonNegativeInteger" },
        minItems: { $ref: "#/definitions/nonNegativeIntegerDefault0" },
        uniqueItems: {
          type: "boolean",
          default: false
        },
        contains: { $ref: "#" },
        maxProperties: { $ref: "#/definitions/nonNegativeInteger" },
        minProperties: { $ref: "#/definitions/nonNegativeIntegerDefault0" },
        required: { $ref: "#/definitions/stringArray" },
        additionalProperties: { $ref: "#" },
        definitions: {
          type: "object",
          additionalProperties: { $ref: "#" },
          default: {}
        },
        properties: {
          type: "object",
          additionalProperties: { $ref: "#" },
          default: {}
        },
        patternProperties: {
          type: "object",
          additionalProperties: { $ref: "#" },
          propertyNames: { format: "regex" },
          default: {}
        },
        dependencies: {
          type: "object",
          additionalProperties: {
            anyOf: [{ $ref: "#" }, { $ref: "#/definitions/stringArray" }]
          }
        },
        propertyNames: { $ref: "#" },
        const: true,
        enum: {
          type: "array",
          items: true,
          minItems: 1,
          uniqueItems: true
        },
        type: {
          anyOf: [
            { $ref: "#/definitions/simpleTypes" },
            {
              type: "array",
              items: { $ref: "#/definitions/simpleTypes" },
              minItems: 1,
              uniqueItems: true
            }
          ]
        },
        format: { type: "string" },
        contentMediaType: { type: "string" },
        contentEncoding: { type: "string" },
        if: { $ref: "#" },
        then: { $ref: "#" },
        else: { $ref: "#" },
        allOf: { $ref: "#/definitions/schemaArray" },
        anyOf: { $ref: "#/definitions/schemaArray" },
        oneOf: { $ref: "#/definitions/schemaArray" },
        not: { $ref: "#" }
      },
      default: true
    };
  }
});

// ../pi-mono/node_modules/ajv/dist/ajv.js
var require_ajv = __commonJS({
  "../pi-mono/node_modules/ajv/dist/ajv.js"(exports, module) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0;
    var core_1 = require_core();
    var draft7_1 = require_draft7();
    var discriminator_1 = require_discriminator();
    var draft7MetaSchema = require_json_schema_draft_07();
    var META_SUPPORT_DATA = ["/properties"];
    var META_SCHEMA_ID = "http://json-schema.org/draft-07/schema";
    var Ajv2 = class extends core_1.default {
      _addVocabularies() {
        super._addVocabularies();
        draft7_1.default.forEach((v4) => this.addVocabulary(v4));
        if (this.opts.discriminator)
          this.addKeyword(discriminator_1.default);
      }
      _addDefaultMetaSchema() {
        super._addDefaultMetaSchema();
        if (!this.opts.meta)
          return;
        const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema;
        this.addMetaSchema(metaSchema, META_SCHEMA_ID, false);
        this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID;
      }
      defaultMeta() {
        return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0);
      }
    };
    exports.Ajv = Ajv2;
    module.exports = exports = Ajv2;
    module.exports.Ajv = Ajv2;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.default = Ajv2;
    var validate_1 = require_validate();
    Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() {
      return validate_1.KeywordCxt;
    } });
    var codegen_1 = require_codegen();
    Object.defineProperty(exports, "_", { enumerable: true, get: function() {
      return codegen_1._;
    } });
    Object.defineProperty(exports, "str", { enumerable: true, get: function() {
      return codegen_1.str;
    } });
    Object.defineProperty(exports, "stringify", { enumerable: true, get: function() {
      return codegen_1.stringify;
    } });
    Object.defineProperty(exports, "nil", { enumerable: true, get: function() {
      return codegen_1.nil;
    } });
    Object.defineProperty(exports, "Name", { enumerable: true, get: function() {
      return codegen_1.Name;
    } });
    Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() {
      return codegen_1.CodeGen;
    } });
    var validation_error_1 = require_validation_error();
    Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function() {
      return validation_error_1.default;
    } });
    var ref_error_1 = require_ref_error();
    Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function() {
      return ref_error_1.default;
    } });
  }
});

// ../pi-mono/node_modules/ajv-formats/dist/formats.js
var require_formats = __commonJS({
  "../pi-mono/node_modules/ajv-formats/dist/formats.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.formatNames = exports.fastFormats = exports.fullFormats = void 0;
    function fmtDef(validate, compare) {
      return { validate, compare };
    }
    exports.fullFormats = {
      // date: http://tools.ietf.org/html/rfc3339#section-5.6
      date: fmtDef(date, compareDate),
      // date-time: http://tools.ietf.org/html/rfc3339#section-5.6
      time: fmtDef(getTime(true), compareTime),
      "date-time": fmtDef(getDateTime(true), compareDateTime),
      "iso-time": fmtDef(getTime(), compareIsoTime),
      "iso-date-time": fmtDef(getDateTime(), compareIsoDateTime),
      // duration: https://tools.ietf.org/html/rfc3339#appendix-A
      duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,
      uri,
      "uri-reference": /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,
      // uri-template: https://tools.ietf.org/html/rfc6570
      "uri-template": /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,
      // For the source: https://gist.github.com/dperini/729294
      // For test cases: https://mathiasbynens.be/demo/url-regex
      url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,
      email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,
      hostname: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,
      // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html
      ipv4: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,
      ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,
      regex,
      // uuid: http://tools.ietf.org/html/rfc4122
      uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,
      // JSON-pointer: https://tools.ietf.org/html/rfc6901
      // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A
      "json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/,
      "json-pointer-uri-fragment": /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,
      // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00
      "relative-json-pointer": /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,
      // the following formats are used by the openapi specification: https://spec.openapis.org/oas/v3.0.0#data-types
      // byte: https://github.com/miguelmota/is-base64
      byte,
      // signed 32 bit integer
      int32: { type: "number", validate: validateInt32 },
      // signed 64 bit integer
      int64: { type: "number", validate: validateInt64 },
      // C-type float
      float: { type: "number", validate: validateNumber },
      // C-type double
      double: { type: "number", validate: validateNumber },
      // hint to the UI to hide input strings
      password: true,
      // unchecked string payload
      binary: true
    };
    exports.fastFormats = {
      ...exports.fullFormats,
      date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate),
      time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareTime),
      "date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareDateTime),
      "iso-time": fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoTime),
      "iso-date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoDateTime),
      // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js
      uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,
      "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,
      // email (sources from jsen validator):
      // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363
      // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'wilful violation')
      email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i
    };
    exports.formatNames = Object.keys(exports.fullFormats);
    function isLeapYear(year) {
      return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
    }
    var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
    var DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    function date(str2) {
      const matches = DATE.exec(str2);
      if (!matches)
        return false;
      const year = +matches[1];
      const month = +matches[2];
      const day = +matches[3];
      return month >= 1 && month <= 12 && day >= 1 && day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]);
    }
    function compareDate(d1, d22) {
      if (!(d1 && d22))
        return void 0;
      if (d1 > d22)
        return 1;
      if (d1 < d22)
        return -1;
      return 0;
    }
    var TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;
    function getTime(strictTimeZone) {
      return function time(str2) {
        const matches = TIME.exec(str2);
        if (!matches)
          return false;
        const hr = +matches[1];
        const min = +matches[2];
        const sec = +matches[3];
        const tz = matches[4];
        const tzSign = matches[5] === "-" ? -1 : 1;
        const tzH = +(matches[6] || 0);
        const tzM = +(matches[7] || 0);
        if (tzH > 23 || tzM > 59 || strictTimeZone && !tz)
          return false;
        if (hr <= 23 && min <= 59 && sec < 60)
          return true;
        const utcMin = min - tzM * tzSign;
        const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0);
        return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61;
      };
    }
    function compareTime(s1, s22) {
      if (!(s1 && s22))
        return void 0;
      const t1 = (/* @__PURE__ */ new Date("2020-01-01T" + s1)).valueOf();
      const t22 = (/* @__PURE__ */ new Date("2020-01-01T" + s22)).valueOf();
      if (!(t1 && t22))
        return void 0;
      return t1 - t22;
    }
    function compareIsoTime(t1, t22) {
      if (!(t1 && t22))
        return void 0;
      const a1 = TIME.exec(t1);
      const a22 = TIME.exec(t22);
      if (!(a1 && a22))
        return void 0;
      t1 = a1[1] + a1[2] + a1[3];
      t22 = a22[1] + a22[2] + a22[3];
      if (t1 > t22)
        return 1;
      if (t1 < t22)
        return -1;
      return 0;
    }
    var DATE_TIME_SEPARATOR = /t|\s/i;
    function getDateTime(strictTimeZone) {
      const time = getTime(strictTimeZone);
      return function date_time(str2) {
        const dateTime = str2.split(DATE_TIME_SEPARATOR);
        return dateTime.length === 2 && date(dateTime[0]) && time(dateTime[1]);
      };
    }
    function compareDateTime(dt1, dt2) {
      if (!(dt1 && dt2))
        return void 0;
      const d1 = new Date(dt1).valueOf();
      const d22 = new Date(dt2).valueOf();
      if (!(d1 && d22))
        return void 0;
      return d1 - d22;
    }
    function compareIsoDateTime(dt1, dt2) {
      if (!(dt1 && dt2))
        return void 0;
      const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR);
      const [d22, t22] = dt2.split(DATE_TIME_SEPARATOR);
      const res = compareDate(d1, d22);
      if (res === void 0)
        return void 0;
      return res || compareTime(t1, t22);
    }
    var NOT_URI_FRAGMENT = /\/|:/;
    var URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
    function uri(str2) {
      return NOT_URI_FRAGMENT.test(str2) && URI.test(str2);
    }
    var BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;
    function byte(str2) {
      BYTE.lastIndex = 0;
      return BYTE.test(str2);
    }
    var MIN_INT32 = -(2 ** 31);
    var MAX_INT32 = 2 ** 31 - 1;
    function validateInt32(value) {
      return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32;
    }
    function validateInt64(value) {
      return Number.isInteger(value);
    }
    function validateNumber() {
      return true;
    }
    var Z_ANCHOR = /[^\\]\\Z/;
    function regex(str2) {
      if (Z_ANCHOR.test(str2))
        return false;
      try {
        new RegExp(str2);
        return true;
      } catch (e9) {
        return false;
      }
    }
  }
});

// ../pi-mono/node_modules/ajv-formats/dist/limit.js
var require_limit = __commonJS({
  "../pi-mono/node_modules/ajv-formats/dist/limit.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.formatLimitDefinition = void 0;
    var ajv_1 = require_ajv();
    var codegen_1 = require_codegen();
    var ops = codegen_1.operators;
    var KWDs = {
      formatMaximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT },
      formatMinimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT },
      formatExclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE },
      formatExclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE }
    };
    var error = {
      message: ({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`,
      params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`
    };
    exports.formatLimitDefinition = {
      keyword: Object.keys(KWDs),
      type: "string",
      schemaType: "string",
      $data: true,
      error,
      code(cxt) {
        const { gen, data, schemaCode, keyword, it } = cxt;
        const { opts, self: self2 } = it;
        if (!opts.validateFormats)
          return;
        const fCxt = new ajv_1.KeywordCxt(it, self2.RULES.all.format.definition, "format");
        if (fCxt.$data)
          validate$DataFormat();
        else
          validateFormat();
        function validate$DataFormat() {
          const fmts = gen.scopeValue("formats", {
            ref: self2.formats,
            code: opts.code.formats
          });
          const fmt = gen.const("fmt", (0, codegen_1._)`${fmts}[${fCxt.schemaCode}]`);
          cxt.fail$data((0, codegen_1.or)((0, codegen_1._)`typeof ${fmt} != "object"`, (0, codegen_1._)`${fmt} instanceof RegExp`, (0, codegen_1._)`typeof ${fmt}.compare != "function"`, compareCode(fmt)));
        }
        function validateFormat() {
          const format = fCxt.schema;
          const fmtDef = self2.formats[format];
          if (!fmtDef || fmtDef === true)
            return;
          if (typeof fmtDef != "object" || fmtDef instanceof RegExp || typeof fmtDef.compare != "function") {
            throw new Error(`"${keyword}": format "${format}" does not define "compare" function`);
          }
          const fmt = gen.scopeValue("formats", {
            key: format,
            ref: fmtDef,
            code: opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(format)}` : void 0
          });
          cxt.fail$data(compareCode(fmt));
        }
        function compareCode(fmt) {
          return (0, codegen_1._)`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`;
        }
      },
      dependencies: ["format"]
    };
    var formatLimitPlugin = (ajv2) => {
      ajv2.addKeyword(exports.formatLimitDefinition);
      return ajv2;
    };
    exports.default = formatLimitPlugin;
  }
});

// ../pi-mono/node_modules/ajv-formats/dist/index.js
var require_dist2 = __commonJS({
  "../pi-mono/node_modules/ajv-formats/dist/index.js"(exports, module) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    var formats_1 = require_formats();
    var limit_1 = require_limit();
    var codegen_1 = require_codegen();
    var fullName = new codegen_1.Name("fullFormats");
    var fastName = new codegen_1.Name("fastFormats");
    var formatsPlugin = (ajv2, opts = { keywords: true }) => {
      if (Array.isArray(opts)) {
        addFormats2(ajv2, opts, formats_1.fullFormats, fullName);
        return ajv2;
      }
      const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName];
      const list = opts.formats || formats_1.formatNames;
      addFormats2(ajv2, list, formats, exportName);
      if (opts.keywords)
        (0, limit_1.default)(ajv2);
      return ajv2;
    };
    formatsPlugin.get = (name, mode = "full") => {
      const formats = mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats;
      const f4 = formats[name];
      if (!f4)
        throw new Error(`Unknown format "${name}"`);
      return f4;
    };
    function addFormats2(ajv2, list, fs, exportName) {
      var _a7;
      var _b;
      (_a7 = (_b = ajv2.opts.code).formats) !== null && _a7 !== void 0 ? _a7 : _b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`;
      for (const f4 of list)
        ajv2.addFormat(f4, fs[f4]);
    }
    module.exports = exports = formatsPlugin;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.default = formatsPlugin;
  }
});

// ../pi-mono/node_modules/color-name/index.js
var require_color_name = __commonJS({
  "../pi-mono/node_modules/color-name/index.js"(exports, module) {
    "use strict";
    init_process_shim();
    module.exports = {
      "aliceblue": [240, 248, 255],
      "antiquewhite": [250, 235, 215],
      "aqua": [0, 255, 255],
      "aquamarine": [127, 255, 212],
      "azure": [240, 255, 255],
      "beige": [245, 245, 220],
      "bisque": [255, 228, 196],
      "black": [0, 0, 0],
      "blanchedalmond": [255, 235, 205],
      "blue": [0, 0, 255],
      "blueviolet": [138, 43, 226],
      "brown": [165, 42, 42],
      "burlywood": [222, 184, 135],
      "cadetblue": [95, 158, 160],
      "chartreuse": [127, 255, 0],
      "chocolate": [210, 105, 30],
      "coral": [255, 127, 80],
      "cornflowerblue": [100, 149, 237],
      "cornsilk": [255, 248, 220],
      "crimson": [220, 20, 60],
      "cyan": [0, 255, 255],
      "darkblue": [0, 0, 139],
      "darkcyan": [0, 139, 139],
      "darkgoldenrod": [184, 134, 11],
      "darkgray": [169, 169, 169],
      "darkgreen": [0, 100, 0],
      "darkgrey": [169, 169, 169],
      "darkkhaki": [189, 183, 107],
      "darkmagenta": [139, 0, 139],
      "darkolivegreen": [85, 107, 47],
      "darkorange": [255, 140, 0],
      "darkorchid": [153, 50, 204],
      "darkred": [139, 0, 0],
      "darksalmon": [233, 150, 122],
      "darkseagreen": [143, 188, 143],
      "darkslateblue": [72, 61, 139],
      "darkslategray": [47, 79, 79],
      "darkslategrey": [47, 79, 79],
      "darkturquoise": [0, 206, 209],
      "darkviolet": [148, 0, 211],
      "deeppink": [255, 20, 147],
      "deepskyblue": [0, 191, 255],
      "dimgray": [105, 105, 105],
      "dimgrey": [105, 105, 105],
      "dodgerblue": [30, 144, 255],
      "firebrick": [178, 34, 34],
      "floralwhite": [255, 250, 240],
      "forestgreen": [34, 139, 34],
      "fuchsia": [255, 0, 255],
      "gainsboro": [220, 220, 220],
      "ghostwhite": [248, 248, 255],
      "gold": [255, 215, 0],
      "goldenrod": [218, 165, 32],
      "gray": [128, 128, 128],
      "green": [0, 128, 0],
      "greenyellow": [173, 255, 47],
      "grey": [128, 128, 128],
      "honeydew": [240, 255, 240],
      "hotpink": [255, 105, 180],
      "indianred": [205, 92, 92],
      "indigo": [75, 0, 130],
      "ivory": [255, 255, 240],
      "khaki": [240, 230, 140],
      "lavender": [230, 230, 250],
      "lavenderblush": [255, 240, 245],
      "lawngreen": [124, 252, 0],
      "lemonchiffon": [255, 250, 205],
      "lightblue": [173, 216, 230],
      "lightcoral": [240, 128, 128],
      "lightcyan": [224, 255, 255],
      "lightgoldenrodyellow": [250, 250, 210],
      "lightgray": [211, 211, 211],
      "lightgreen": [144, 238, 144],
      "lightgrey": [211, 211, 211],
      "lightpink": [255, 182, 193],
      "lightsalmon": [255, 160, 122],
      "lightseagreen": [32, 178, 170],
      "lightskyblue": [135, 206, 250],
      "lightslategray": [119, 136, 153],
      "lightslategrey": [119, 136, 153],
      "lightsteelblue": [176, 196, 222],
      "lightyellow": [255, 255, 224],
      "lime": [0, 255, 0],
      "limegreen": [50, 205, 50],
      "linen": [250, 240, 230],
      "magenta": [255, 0, 255],
      "maroon": [128, 0, 0],
      "mediumaquamarine": [102, 205, 170],
      "mediumblue": [0, 0, 205],
      "mediumorchid": [186, 85, 211],
      "mediumpurple": [147, 112, 219],
      "mediumseagreen": [60, 179, 113],
      "mediumslateblue": [123, 104, 238],
      "mediumspringgreen": [0, 250, 154],
      "mediumturquoise": [72, 209, 204],
      "mediumvioletred": [199, 21, 133],
      "midnightblue": [25, 25, 112],
      "mintcream": [245, 255, 250],
      "mistyrose": [255, 228, 225],
      "moccasin": [255, 228, 181],
      "navajowhite": [255, 222, 173],
      "navy": [0, 0, 128],
      "oldlace": [253, 245, 230],
      "olive": [128, 128, 0],
      "olivedrab": [107, 142, 35],
      "orange": [255, 165, 0],
      "orangered": [255, 69, 0],
      "orchid": [218, 112, 214],
      "palegoldenrod": [238, 232, 170],
      "palegreen": [152, 251, 152],
      "paleturquoise": [175, 238, 238],
      "palevioletred": [219, 112, 147],
      "papayawhip": [255, 239, 213],
      "peachpuff": [255, 218, 185],
      "peru": [205, 133, 63],
      "pink": [255, 192, 203],
      "plum": [221, 160, 221],
      "powderblue": [176, 224, 230],
      "purple": [128, 0, 128],
      "rebeccapurple": [102, 51, 153],
      "red": [255, 0, 0],
      "rosybrown": [188, 143, 143],
      "royalblue": [65, 105, 225],
      "saddlebrown": [139, 69, 19],
      "salmon": [250, 128, 114],
      "sandybrown": [244, 164, 96],
      "seagreen": [46, 139, 87],
      "seashell": [255, 245, 238],
      "sienna": [160, 82, 45],
      "silver": [192, 192, 192],
      "skyblue": [135, 206, 235],
      "slateblue": [106, 90, 205],
      "slategray": [112, 128, 144],
      "slategrey": [112, 128, 144],
      "snow": [255, 250, 250],
      "springgreen": [0, 255, 127],
      "steelblue": [70, 130, 180],
      "tan": [210, 180, 140],
      "teal": [0, 128, 128],
      "thistle": [216, 191, 216],
      "tomato": [255, 99, 71],
      "turquoise": [64, 224, 208],
      "violet": [238, 130, 238],
      "wheat": [245, 222, 179],
      "white": [255, 255, 255],
      "whitesmoke": [245, 245, 245],
      "yellow": [255, 255, 0],
      "yellowgreen": [154, 205, 50]
    };
  }
});

// ../pi-mono/node_modules/color-convert/conversions.js
var require_conversions = __commonJS({
  "../pi-mono/node_modules/color-convert/conversions.js"(exports, module) {
    init_process_shim();
    var cssKeywords = require_color_name();
    var reverseKeywords = {};
    for (const key of Object.keys(cssKeywords)) {
      reverseKeywords[cssKeywords[key]] = key;
    }
    var convert = {
      rgb: { channels: 3, labels: "rgb" },
      hsl: { channels: 3, labels: "hsl" },
      hsv: { channels: 3, labels: "hsv" },
      hwb: { channels: 3, labels: "hwb" },
      cmyk: { channels: 4, labels: "cmyk" },
      xyz: { channels: 3, labels: "xyz" },
      lab: { channels: 3, labels: "lab" },
      lch: { channels: 3, labels: "lch" },
      hex: { channels: 1, labels: ["hex"] },
      keyword: { channels: 1, labels: ["keyword"] },
      ansi16: { channels: 1, labels: ["ansi16"] },
      ansi256: { channels: 1, labels: ["ansi256"] },
      hcg: { channels: 3, labels: ["h", "c", "g"] },
      apple: { channels: 3, labels: ["r16", "g16", "b16"] },
      gray: { channels: 1, labels: ["gray"] }
    };
    module.exports = convert;
    for (const model of Object.keys(convert)) {
      if (!("channels" in convert[model])) {
        throw new Error("missing channels property: " + model);
      }
      if (!("labels" in convert[model])) {
        throw new Error("missing channel labels property: " + model);
      }
      if (convert[model].labels.length !== convert[model].channels) {
        throw new Error("channel and label counts mismatch: " + model);
      }
      const { channels, labels } = convert[model];
      delete convert[model].channels;
      delete convert[model].labels;
      Object.defineProperty(convert[model], "channels", { value: channels });
      Object.defineProperty(convert[model], "labels", { value: labels });
    }
    convert.rgb.hsl = function(rgb) {
      const r8 = rgb[0] / 255;
      const g3 = rgb[1] / 255;
      const b4 = rgb[2] / 255;
      const min = Math.min(r8, g3, b4);
      const max = Math.max(r8, g3, b4);
      const delta = max - min;
      let h7;
      let s6;
      if (max === min) {
        h7 = 0;
      } else if (r8 === max) {
        h7 = (g3 - b4) / delta;
      } else if (g3 === max) {
        h7 = 2 + (b4 - r8) / delta;
      } else if (b4 === max) {
        h7 = 4 + (r8 - g3) / delta;
      }
      h7 = Math.min(h7 * 60, 360);
      if (h7 < 0) {
        h7 += 360;
      }
      const l5 = (min + max) / 2;
      if (max === min) {
        s6 = 0;
      } else if (l5 <= 0.5) {
        s6 = delta / (max + min);
      } else {
        s6 = delta / (2 - max - min);
      }
      return [h7, s6 * 100, l5 * 100];
    };
    convert.rgb.hsv = function(rgb) {
      let rdif;
      let gdif;
      let bdif;
      let h7;
      let s6;
      const r8 = rgb[0] / 255;
      const g3 = rgb[1] / 255;
      const b4 = rgb[2] / 255;
      const v4 = Math.max(r8, g3, b4);
      const diff = v4 - Math.min(r8, g3, b4);
      const diffc = function(c6) {
        return (v4 - c6) / 6 / diff + 1 / 2;
      };
      if (diff === 0) {
        h7 = 0;
        s6 = 0;
      } else {
        s6 = diff / v4;
        rdif = diffc(r8);
        gdif = diffc(g3);
        bdif = diffc(b4);
        if (r8 === v4) {
          h7 = bdif - gdif;
        } else if (g3 === v4) {
          h7 = 1 / 3 + rdif - bdif;
        } else if (b4 === v4) {
          h7 = 2 / 3 + gdif - rdif;
        }
        if (h7 < 0) {
          h7 += 1;
        } else if (h7 > 1) {
          h7 -= 1;
        }
      }
      return [
        h7 * 360,
        s6 * 100,
        v4 * 100
      ];
    };
    convert.rgb.hwb = function(rgb) {
      const r8 = rgb[0];
      const g3 = rgb[1];
      let b4 = rgb[2];
      const h7 = convert.rgb.hsl(rgb)[0];
      const w3 = 1 / 255 * Math.min(r8, Math.min(g3, b4));
      b4 = 1 - 1 / 255 * Math.max(r8, Math.max(g3, b4));
      return [h7, w3 * 100, b4 * 100];
    };
    convert.rgb.cmyk = function(rgb) {
      const r8 = rgb[0] / 255;
      const g3 = rgb[1] / 255;
      const b4 = rgb[2] / 255;
      const k2 = Math.min(1 - r8, 1 - g3, 1 - b4);
      const c6 = (1 - r8 - k2) / (1 - k2) || 0;
      const m4 = (1 - g3 - k2) / (1 - k2) || 0;
      const y4 = (1 - b4 - k2) / (1 - k2) || 0;
      return [c6 * 100, m4 * 100, y4 * 100, k2 * 100];
    };
    function comparativeDistance(x2, y4) {
      return (x2[0] - y4[0]) ** 2 + (x2[1] - y4[1]) ** 2 + (x2[2] - y4[2]) ** 2;
    }
    convert.rgb.keyword = function(rgb) {
      const reversed = reverseKeywords[rgb];
      if (reversed) {
        return reversed;
      }
      let currentClosestDistance = Infinity;
      let currentClosestKeyword;
      for (const keyword of Object.keys(cssKeywords)) {
        const value = cssKeywords[keyword];
        const distance = comparativeDistance(rgb, value);
        if (distance < currentClosestDistance) {
          currentClosestDistance = distance;
          currentClosestKeyword = keyword;
        }
      }
      return currentClosestKeyword;
    };
    convert.keyword.rgb = function(keyword) {
      return cssKeywords[keyword];
    };
    convert.rgb.xyz = function(rgb) {
      let r8 = rgb[0] / 255;
      let g3 = rgb[1] / 255;
      let b4 = rgb[2] / 255;
      r8 = r8 > 0.04045 ? ((r8 + 0.055) / 1.055) ** 2.4 : r8 / 12.92;
      g3 = g3 > 0.04045 ? ((g3 + 0.055) / 1.055) ** 2.4 : g3 / 12.92;
      b4 = b4 > 0.04045 ? ((b4 + 0.055) / 1.055) ** 2.4 : b4 / 12.92;
      const x2 = r8 * 0.4124 + g3 * 0.3576 + b4 * 0.1805;
      const y4 = r8 * 0.2126 + g3 * 0.7152 + b4 * 0.0722;
      const z3 = r8 * 0.0193 + g3 * 0.1192 + b4 * 0.9505;
      return [x2 * 100, y4 * 100, z3 * 100];
    };
    convert.rgb.lab = function(rgb) {
      const xyz = convert.rgb.xyz(rgb);
      let x2 = xyz[0];
      let y4 = xyz[1];
      let z3 = xyz[2];
      x2 /= 95.047;
      y4 /= 100;
      z3 /= 108.883;
      x2 = x2 > 8856e-6 ? x2 ** (1 / 3) : 7.787 * x2 + 16 / 116;
      y4 = y4 > 8856e-6 ? y4 ** (1 / 3) : 7.787 * y4 + 16 / 116;
      z3 = z3 > 8856e-6 ? z3 ** (1 / 3) : 7.787 * z3 + 16 / 116;
      const l5 = 116 * y4 - 16;
      const a3 = 500 * (x2 - y4);
      const b4 = 200 * (y4 - z3);
      return [l5, a3, b4];
    };
    convert.hsl.rgb = function(hsl) {
      const h7 = hsl[0] / 360;
      const s6 = hsl[1] / 100;
      const l5 = hsl[2] / 100;
      let t22;
      let t32;
      let val2;
      if (s6 === 0) {
        val2 = l5 * 255;
        return [val2, val2, val2];
      }
      if (l5 < 0.5) {
        t22 = l5 * (1 + s6);
      } else {
        t22 = l5 + s6 - l5 * s6;
      }
      const t1 = 2 * l5 - t22;
      const rgb = [0, 0, 0];
      for (let i7 = 0; i7 < 3; i7++) {
        t32 = h7 + 1 / 3 * -(i7 - 1);
        if (t32 < 0) {
          t32++;
        }
        if (t32 > 1) {
          t32--;
        }
        if (6 * t32 < 1) {
          val2 = t1 + (t22 - t1) * 6 * t32;
        } else if (2 * t32 < 1) {
          val2 = t22;
        } else if (3 * t32 < 2) {
          val2 = t1 + (t22 - t1) * (2 / 3 - t32) * 6;
        } else {
          val2 = t1;
        }
        rgb[i7] = val2 * 255;
      }
      return rgb;
    };
    convert.hsl.hsv = function(hsl) {
      const h7 = hsl[0];
      let s6 = hsl[1] / 100;
      let l5 = hsl[2] / 100;
      let smin = s6;
      const lmin = Math.max(l5, 0.01);
      l5 *= 2;
      s6 *= l5 <= 1 ? l5 : 2 - l5;
      smin *= lmin <= 1 ? lmin : 2 - lmin;
      const v4 = (l5 + s6) / 2;
      const sv = l5 === 0 ? 2 * smin / (lmin + smin) : 2 * s6 / (l5 + s6);
      return [h7, sv * 100, v4 * 100];
    };
    convert.hsv.rgb = function(hsv) {
      const h7 = hsv[0] / 60;
      const s6 = hsv[1] / 100;
      let v4 = hsv[2] / 100;
      const hi = Math.floor(h7) % 6;
      const f4 = h7 - Math.floor(h7);
      const p4 = 255 * v4 * (1 - s6);
      const q2 = 255 * v4 * (1 - s6 * f4);
      const t6 = 255 * v4 * (1 - s6 * (1 - f4));
      v4 *= 255;
      switch (hi) {
        case 0:
          return [v4, t6, p4];
        case 1:
          return [q2, v4, p4];
        case 2:
          return [p4, v4, t6];
        case 3:
          return [p4, q2, v4];
        case 4:
          return [t6, p4, v4];
        case 5:
          return [v4, p4, q2];
      }
    };
    convert.hsv.hsl = function(hsv) {
      const h7 = hsv[0];
      const s6 = hsv[1] / 100;
      const v4 = hsv[2] / 100;
      const vmin = Math.max(v4, 0.01);
      let sl;
      let l5;
      l5 = (2 - s6) * v4;
      const lmin = (2 - s6) * vmin;
      sl = s6 * vmin;
      sl /= lmin <= 1 ? lmin : 2 - lmin;
      sl = sl || 0;
      l5 /= 2;
      return [h7, sl * 100, l5 * 100];
    };
    convert.hwb.rgb = function(hwb) {
      const h7 = hwb[0] / 360;
      let wh = hwb[1] / 100;
      let bl = hwb[2] / 100;
      const ratio = wh + bl;
      let f4;
      if (ratio > 1) {
        wh /= ratio;
        bl /= ratio;
      }
      const i7 = Math.floor(6 * h7);
      const v4 = 1 - bl;
      f4 = 6 * h7 - i7;
      if ((i7 & 1) !== 0) {
        f4 = 1 - f4;
      }
      const n7 = wh + f4 * (v4 - wh);
      let r8;
      let g3;
      let b4;
      switch (i7) {
        default:
        case 6:
        case 0:
          r8 = v4;
          g3 = n7;
          b4 = wh;
          break;
        case 1:
          r8 = n7;
          g3 = v4;
          b4 = wh;
          break;
        case 2:
          r8 = wh;
          g3 = v4;
          b4 = n7;
          break;
        case 3:
          r8 = wh;
          g3 = n7;
          b4 = v4;
          break;
        case 4:
          r8 = n7;
          g3 = wh;
          b4 = v4;
          break;
        case 5:
          r8 = v4;
          g3 = wh;
          b4 = n7;
          break;
      }
      return [r8 * 255, g3 * 255, b4 * 255];
    };
    convert.cmyk.rgb = function(cmyk) {
      const c6 = cmyk[0] / 100;
      const m4 = cmyk[1] / 100;
      const y4 = cmyk[2] / 100;
      const k2 = cmyk[3] / 100;
      const r8 = 1 - Math.min(1, c6 * (1 - k2) + k2);
      const g3 = 1 - Math.min(1, m4 * (1 - k2) + k2);
      const b4 = 1 - Math.min(1, y4 * (1 - k2) + k2);
      return [r8 * 255, g3 * 255, b4 * 255];
    };
    convert.xyz.rgb = function(xyz) {
      const x2 = xyz[0] / 100;
      const y4 = xyz[1] / 100;
      const z3 = xyz[2] / 100;
      let r8;
      let g3;
      let b4;
      r8 = x2 * 3.2406 + y4 * -1.5372 + z3 * -0.4986;
      g3 = x2 * -0.9689 + y4 * 1.8758 + z3 * 0.0415;
      b4 = x2 * 0.0557 + y4 * -0.204 + z3 * 1.057;
      r8 = r8 > 31308e-7 ? 1.055 * r8 ** (1 / 2.4) - 0.055 : r8 * 12.92;
      g3 = g3 > 31308e-7 ? 1.055 * g3 ** (1 / 2.4) - 0.055 : g3 * 12.92;
      b4 = b4 > 31308e-7 ? 1.055 * b4 ** (1 / 2.4) - 0.055 : b4 * 12.92;
      r8 = Math.min(Math.max(0, r8), 1);
      g3 = Math.min(Math.max(0, g3), 1);
      b4 = Math.min(Math.max(0, b4), 1);
      return [r8 * 255, g3 * 255, b4 * 255];
    };
    convert.xyz.lab = function(xyz) {
      let x2 = xyz[0];
      let y4 = xyz[1];
      let z3 = xyz[2];
      x2 /= 95.047;
      y4 /= 100;
      z3 /= 108.883;
      x2 = x2 > 8856e-6 ? x2 ** (1 / 3) : 7.787 * x2 + 16 / 116;
      y4 = y4 > 8856e-6 ? y4 ** (1 / 3) : 7.787 * y4 + 16 / 116;
      z3 = z3 > 8856e-6 ? z3 ** (1 / 3) : 7.787 * z3 + 16 / 116;
      const l5 = 116 * y4 - 16;
      const a3 = 500 * (x2 - y4);
      const b4 = 200 * (y4 - z3);
      return [l5, a3, b4];
    };
    convert.lab.xyz = function(lab) {
      const l5 = lab[0];
      const a3 = lab[1];
      const b4 = lab[2];
      let x2;
      let y4;
      let z3;
      y4 = (l5 + 16) / 116;
      x2 = a3 / 500 + y4;
      z3 = y4 - b4 / 200;
      const y22 = y4 ** 3;
      const x22 = x2 ** 3;
      const z22 = z3 ** 3;
      y4 = y22 > 8856e-6 ? y22 : (y4 - 16 / 116) / 7.787;
      x2 = x22 > 8856e-6 ? x22 : (x2 - 16 / 116) / 7.787;
      z3 = z22 > 8856e-6 ? z22 : (z3 - 16 / 116) / 7.787;
      x2 *= 95.047;
      y4 *= 100;
      z3 *= 108.883;
      return [x2, y4, z3];
    };
    convert.lab.lch = function(lab) {
      const l5 = lab[0];
      const a3 = lab[1];
      const b4 = lab[2];
      let h7;
      const hr = Math.atan2(b4, a3);
      h7 = hr * 360 / 2 / Math.PI;
      if (h7 < 0) {
        h7 += 360;
      }
      const c6 = Math.sqrt(a3 * a3 + b4 * b4);
      return [l5, c6, h7];
    };
    convert.lch.lab = function(lch) {
      const l5 = lch[0];
      const c6 = lch[1];
      const h7 = lch[2];
      const hr = h7 / 360 * 2 * Math.PI;
      const a3 = c6 * Math.cos(hr);
      const b4 = c6 * Math.sin(hr);
      return [l5, a3, b4];
    };
    convert.rgb.ansi16 = function(args, saturation = null) {
      const [r8, g3, b4] = args;
      let value = saturation === null ? convert.rgb.hsv(args)[2] : saturation;
      value = Math.round(value / 50);
      if (value === 0) {
        return 30;
      }
      let ansi = 30 + (Math.round(b4 / 255) << 2 | Math.round(g3 / 255) << 1 | Math.round(r8 / 255));
      if (value === 2) {
        ansi += 60;
      }
      return ansi;
    };
    convert.hsv.ansi16 = function(args) {
      return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
    };
    convert.rgb.ansi256 = function(args) {
      const r8 = args[0];
      const g3 = args[1];
      const b4 = args[2];
      if (r8 === g3 && g3 === b4) {
        if (r8 < 8) {
          return 16;
        }
        if (r8 > 248) {
          return 231;
        }
        return Math.round((r8 - 8) / 247 * 24) + 232;
      }
      const ansi = 16 + 36 * Math.round(r8 / 255 * 5) + 6 * Math.round(g3 / 255 * 5) + Math.round(b4 / 255 * 5);
      return ansi;
    };
    convert.ansi16.rgb = function(args) {
      let color = args % 10;
      if (color === 0 || color === 7) {
        if (args > 50) {
          color += 3.5;
        }
        color = color / 10.5 * 255;
        return [color, color, color];
      }
      const mult = (~~(args > 50) + 1) * 0.5;
      const r8 = (color & 1) * mult * 255;
      const g3 = (color >> 1 & 1) * mult * 255;
      const b4 = (color >> 2 & 1) * mult * 255;
      return [r8, g3, b4];
    };
    convert.ansi256.rgb = function(args) {
      if (args >= 232) {
        const c6 = (args - 232) * 10 + 8;
        return [c6, c6, c6];
      }
      args -= 16;
      let rem;
      const r8 = Math.floor(args / 36) / 5 * 255;
      const g3 = Math.floor((rem = args % 36) / 6) / 5 * 255;
      const b4 = rem % 6 / 5 * 255;
      return [r8, g3, b4];
    };
    convert.rgb.hex = function(args) {
      const integer = ((Math.round(args[0]) & 255) << 16) + ((Math.round(args[1]) & 255) << 8) + (Math.round(args[2]) & 255);
      const string = integer.toString(16).toUpperCase();
      return "000000".substring(string.length) + string;
    };
    convert.hex.rgb = function(args) {
      const match2 = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
      if (!match2) {
        return [0, 0, 0];
      }
      let colorString = match2[0];
      if (match2[0].length === 3) {
        colorString = colorString.split("").map((char) => {
          return char + char;
        }).join("");
      }
      const integer = parseInt(colorString, 16);
      const r8 = integer >> 16 & 255;
      const g3 = integer >> 8 & 255;
      const b4 = integer & 255;
      return [r8, g3, b4];
    };
    convert.rgb.hcg = function(rgb) {
      const r8 = rgb[0] / 255;
      const g3 = rgb[1] / 255;
      const b4 = rgb[2] / 255;
      const max = Math.max(Math.max(r8, g3), b4);
      const min = Math.min(Math.min(r8, g3), b4);
      const chroma = max - min;
      let grayscale;
      let hue;
      if (chroma < 1) {
        grayscale = min / (1 - chroma);
      } else {
        grayscale = 0;
      }
      if (chroma <= 0) {
        hue = 0;
      } else if (max === r8) {
        hue = (g3 - b4) / chroma % 6;
      } else if (max === g3) {
        hue = 2 + (b4 - r8) / chroma;
      } else {
        hue = 4 + (r8 - g3) / chroma;
      }
      hue /= 6;
      hue %= 1;
      return [hue * 360, chroma * 100, grayscale * 100];
    };
    convert.hsl.hcg = function(hsl) {
      const s6 = hsl[1] / 100;
      const l5 = hsl[2] / 100;
      const c6 = l5 < 0.5 ? 2 * s6 * l5 : 2 * s6 * (1 - l5);
      let f4 = 0;
      if (c6 < 1) {
        f4 = (l5 - 0.5 * c6) / (1 - c6);
      }
      return [hsl[0], c6 * 100, f4 * 100];
    };
    convert.hsv.hcg = function(hsv) {
      const s6 = hsv[1] / 100;
      const v4 = hsv[2] / 100;
      const c6 = s6 * v4;
      let f4 = 0;
      if (c6 < 1) {
        f4 = (v4 - c6) / (1 - c6);
      }
      return [hsv[0], c6 * 100, f4 * 100];
    };
    convert.hcg.rgb = function(hcg) {
      const h7 = hcg[0] / 360;
      const c6 = hcg[1] / 100;
      const g3 = hcg[2] / 100;
      if (c6 === 0) {
        return [g3 * 255, g3 * 255, g3 * 255];
      }
      const pure = [0, 0, 0];
      const hi = h7 % 1 * 6;
      const v4 = hi % 1;
      const w3 = 1 - v4;
      let mg = 0;
      switch (Math.floor(hi)) {
        case 0:
          pure[0] = 1;
          pure[1] = v4;
          pure[2] = 0;
          break;
        case 1:
          pure[0] = w3;
          pure[1] = 1;
          pure[2] = 0;
          break;
        case 2:
          pure[0] = 0;
          pure[1] = 1;
          pure[2] = v4;
          break;
        case 3:
          pure[0] = 0;
          pure[1] = w3;
          pure[2] = 1;
          break;
        case 4:
          pure[0] = v4;
          pure[1] = 0;
          pure[2] = 1;
          break;
        default:
          pure[0] = 1;
          pure[1] = 0;
          pure[2] = w3;
      }
      mg = (1 - c6) * g3;
      return [
        (c6 * pure[0] + mg) * 255,
        (c6 * pure[1] + mg) * 255,
        (c6 * pure[2] + mg) * 255
      ];
    };
    convert.hcg.hsv = function(hcg) {
      const c6 = hcg[1] / 100;
      const g3 = hcg[2] / 100;
      const v4 = c6 + g3 * (1 - c6);
      let f4 = 0;
      if (v4 > 0) {
        f4 = c6 / v4;
      }
      return [hcg[0], f4 * 100, v4 * 100];
    };
    convert.hcg.hsl = function(hcg) {
      const c6 = hcg[1] / 100;
      const g3 = hcg[2] / 100;
      const l5 = g3 * (1 - c6) + 0.5 * c6;
      let s6 = 0;
      if (l5 > 0 && l5 < 0.5) {
        s6 = c6 / (2 * l5);
      } else if (l5 >= 0.5 && l5 < 1) {
        s6 = c6 / (2 * (1 - l5));
      }
      return [hcg[0], s6 * 100, l5 * 100];
    };
    convert.hcg.hwb = function(hcg) {
      const c6 = hcg[1] / 100;
      const g3 = hcg[2] / 100;
      const v4 = c6 + g3 * (1 - c6);
      return [hcg[0], (v4 - c6) * 100, (1 - v4) * 100];
    };
    convert.hwb.hcg = function(hwb) {
      const w3 = hwb[1] / 100;
      const b4 = hwb[2] / 100;
      const v4 = 1 - b4;
      const c6 = v4 - w3;
      let g3 = 0;
      if (c6 < 1) {
        g3 = (v4 - c6) / (1 - c6);
      }
      return [hwb[0], c6 * 100, g3 * 100];
    };
    convert.apple.rgb = function(apple) {
      return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255];
    };
    convert.rgb.apple = function(rgb) {
      return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535];
    };
    convert.gray.rgb = function(args) {
      return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
    };
    convert.gray.hsl = function(args) {
      return [0, 0, args[0]];
    };
    convert.gray.hsv = convert.gray.hsl;
    convert.gray.hwb = function(gray) {
      return [0, 100, gray[0]];
    };
    convert.gray.cmyk = function(gray) {
      return [0, 0, 0, gray[0]];
    };
    convert.gray.lab = function(gray) {
      return [gray[0], 0, 0];
    };
    convert.gray.hex = function(gray) {
      const val2 = Math.round(gray[0] / 100 * 255) & 255;
      const integer = (val2 << 16) + (val2 << 8) + val2;
      const string = integer.toString(16).toUpperCase();
      return "000000".substring(string.length) + string;
    };
    convert.rgb.gray = function(rgb) {
      const val2 = (rgb[0] + rgb[1] + rgb[2]) / 3;
      return [val2 / 255 * 100];
    };
  }
});

// ../pi-mono/node_modules/color-convert/route.js
var require_route = __commonJS({
  "../pi-mono/node_modules/color-convert/route.js"(exports, module) {
    init_process_shim();
    var conversions2 = require_conversions();
    function buildGraph() {
      const graph = {};
      const models2 = Object.keys(conversions2);
      for (let len = models2.length, i7 = 0; i7 < len; i7++) {
        graph[models2[i7]] = {
          // http://jsperf.com/1-vs-infinity
          // micro-opt, but this is simple.
          distance: -1,
          parent: null
        };
      }
      return graph;
    }
    function deriveBFS(fromModel) {
      const graph = buildGraph();
      const queue = [fromModel];
      graph[fromModel].distance = 0;
      while (queue.length) {
        const current2 = queue.pop();
        const adjacents = Object.keys(conversions2[current2]);
        for (let len = adjacents.length, i7 = 0; i7 < len; i7++) {
          const adjacent = adjacents[i7];
          const node = graph[adjacent];
          if (node.distance === -1) {
            node.distance = graph[current2].distance + 1;
            node.parent = current2;
            queue.unshift(adjacent);
          }
        }
      }
      return graph;
    }
    function link(from, to) {
      return function(args) {
        return to(from(args));
      };
    }
    function wrapConversion(toModel, graph) {
      const path6 = [graph[toModel].parent, toModel];
      let fn = conversions2[graph[toModel].parent][toModel];
      let cur = graph[toModel].parent;
      while (graph[cur].parent) {
        path6.unshift(graph[cur].parent);
        fn = link(conversions2[graph[cur].parent][cur], fn);
        cur = graph[cur].parent;
      }
      fn.conversion = path6;
      return fn;
    }
    module.exports = function(fromModel) {
      const graph = deriveBFS(fromModel);
      const conversion = {};
      const models2 = Object.keys(graph);
      for (let len = models2.length, i7 = 0; i7 < len; i7++) {
        const toModel = models2[i7];
        const node = graph[toModel];
        if (node.parent === null) {
          continue;
        }
        conversion[toModel] = wrapConversion(toModel, graph);
      }
      return conversion;
    };
  }
});

// ../pi-mono/node_modules/color-convert/index.js
var require_color_convert = __commonJS({
  "../pi-mono/node_modules/color-convert/index.js"(exports, module) {
    init_process_shim();
    var conversions2 = require_conversions();
    var route2 = require_route();
    var convert = {};
    var models2 = Object.keys(conversions2);
    function wrapRaw(fn) {
      const wrappedFn = function(...args) {
        const arg0 = args[0];
        if (arg0 === void 0 || arg0 === null) {
          return arg0;
        }
        if (arg0.length > 1) {
          args = arg0;
        }
        return fn(args);
      };
      if ("conversion" in fn) {
        wrappedFn.conversion = fn.conversion;
      }
      return wrappedFn;
    }
    function wrapRounded(fn) {
      const wrappedFn = function(...args) {
        const arg0 = args[0];
        if (arg0 === void 0 || arg0 === null) {
          return arg0;
        }
        if (arg0.length > 1) {
          args = arg0;
        }
        const result = fn(args);
        if (typeof result === "object") {
          for (let len = result.length, i7 = 0; i7 < len; i7++) {
            result[i7] = Math.round(result[i7]);
          }
        }
        return result;
      };
      if ("conversion" in fn) {
        wrappedFn.conversion = fn.conversion;
      }
      return wrappedFn;
    }
    models2.forEach((fromModel) => {
      convert[fromModel] = {};
      Object.defineProperty(convert[fromModel], "channels", { value: conversions2[fromModel].channels });
      Object.defineProperty(convert[fromModel], "labels", { value: conversions2[fromModel].labels });
      const routes = route2(fromModel);
      const routeModels = Object.keys(routes);
      routeModels.forEach((toModel) => {
        const fn = routes[toModel];
        convert[fromModel][toModel] = wrapRounded(fn);
        convert[fromModel][toModel].raw = wrapRaw(fn);
      });
    });
    module.exports = convert;
  }
});

// ../pi-mono/node_modules/ansi-styles/index.js
var require_ansi_styles = __commonJS({
  "../pi-mono/node_modules/ansi-styles/index.js"(exports, module) {
    "use strict";
    init_process_shim();
    var wrapAnsi16 = (fn, offset) => (...args) => {
      const code = fn(...args);
      return `\x1B[${code + offset}m`;
    };
    var wrapAnsi256 = (fn, offset) => (...args) => {
      const code = fn(...args);
      return `\x1B[${38 + offset};5;${code}m`;
    };
    var wrapAnsi16m = (fn, offset) => (...args) => {
      const rgb = fn(...args);
      return `\x1B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
    };
    var ansi2ansi = (n7) => n7;
    var rgb2rgb = (r8, g3, b4) => [r8, g3, b4];
    var setLazyProperty = (object, property, get3) => {
      Object.defineProperty(object, property, {
        get: () => {
          const value = get3();
          Object.defineProperty(object, property, {
            value,
            enumerable: true,
            configurable: true
          });
          return value;
        },
        enumerable: true,
        configurable: true
      });
    };
    var colorConvert2;
    var makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => {
      if (colorConvert2 === void 0) {
        colorConvert2 = require_color_convert();
      }
      const offset = isBackground ? 10 : 0;
      const styles2 = {};
      for (const [sourceSpace, suite] of Object.entries(colorConvert2)) {
        const name = sourceSpace === "ansi16" ? "ansi" : sourceSpace;
        if (sourceSpace === targetSpace) {
          styles2[name] = wrap(identity, offset);
        } else if (typeof suite === "object") {
          styles2[name] = wrap(suite[targetSpace], offset);
        }
      }
      return styles2;
    };
    function assembleStyles() {
      const codes = /* @__PURE__ */ new Map();
      const styles2 = {
        modifier: {
          reset: [0, 0],
          // 21 isn't widely supported and 22 does the same thing
          bold: [1, 22],
          dim: [2, 22],
          italic: [3, 23],
          underline: [4, 24],
          inverse: [7, 27],
          hidden: [8, 28],
          strikethrough: [9, 29]
        },
        color: {
          black: [30, 39],
          red: [31, 39],
          green: [32, 39],
          yellow: [33, 39],
          blue: [34, 39],
          magenta: [35, 39],
          cyan: [36, 39],
          white: [37, 39],
          // Bright color
          blackBright: [90, 39],
          redBright: [91, 39],
          greenBright: [92, 39],
          yellowBright: [93, 39],
          blueBright: [94, 39],
          magentaBright: [95, 39],
          cyanBright: [96, 39],
          whiteBright: [97, 39]
        },
        bgColor: {
          bgBlack: [40, 49],
          bgRed: [41, 49],
          bgGreen: [42, 49],
          bgYellow: [43, 49],
          bgBlue: [44, 49],
          bgMagenta: [45, 49],
          bgCyan: [46, 49],
          bgWhite: [47, 49],
          // Bright color
          bgBlackBright: [100, 49],
          bgRedBright: [101, 49],
          bgGreenBright: [102, 49],
          bgYellowBright: [103, 49],
          bgBlueBright: [104, 49],
          bgMagentaBright: [105, 49],
          bgCyanBright: [106, 49],
          bgWhiteBright: [107, 49]
        }
      };
      styles2.color.gray = styles2.color.blackBright;
      styles2.bgColor.bgGray = styles2.bgColor.bgBlackBright;
      styles2.color.grey = styles2.color.blackBright;
      styles2.bgColor.bgGrey = styles2.bgColor.bgBlackBright;
      for (const [groupName, group] of Object.entries(styles2)) {
        for (const [styleName, style] of Object.entries(group)) {
          styles2[styleName] = {
            open: `\x1B[${style[0]}m`,
            close: `\x1B[${style[1]}m`
          };
          group[styleName] = styles2[styleName];
          codes.set(style[0], style[1]);
        }
        Object.defineProperty(styles2, groupName, {
          value: group,
          enumerable: false
        });
      }
      Object.defineProperty(styles2, "codes", {
        value: codes,
        enumerable: false
      });
      styles2.color.close = "\x1B[39m";
      styles2.bgColor.close = "\x1B[49m";
      setLazyProperty(styles2.color, "ansi", () => makeDynamicStyles(wrapAnsi16, "ansi16", ansi2ansi, false));
      setLazyProperty(styles2.color, "ansi256", () => makeDynamicStyles(wrapAnsi256, "ansi256", ansi2ansi, false));
      setLazyProperty(styles2.color, "ansi16m", () => makeDynamicStyles(wrapAnsi16m, "rgb", rgb2rgb, false));
      setLazyProperty(styles2.bgColor, "ansi", () => makeDynamicStyles(wrapAnsi16, "ansi16", ansi2ansi, true));
      setLazyProperty(styles2.bgColor, "ansi256", () => makeDynamicStyles(wrapAnsi256, "ansi256", ansi2ansi, true));
      setLazyProperty(styles2.bgColor, "ansi16m", () => makeDynamicStyles(wrapAnsi16m, "rgb", rgb2rgb, true));
      return styles2;
    }
    Object.defineProperty(module, "exports", {
      enumerable: true,
      get: assembleStyles
    });
  }
});

// ../pi-mono/node_modules/@lmstudio/sdk/node_modules/supports-color/browser.js
var require_browser = __commonJS({
  "../pi-mono/node_modules/@lmstudio/sdk/node_modules/supports-color/browser.js"(exports, module) {
    "use strict";
    init_process_shim();
    module.exports = {
      stdout: false,
      stderr: false
    };
  }
});

// ../pi-mono/node_modules/@lmstudio/sdk/node_modules/chalk/source/util.js
var require_util3 = __commonJS({
  "../pi-mono/node_modules/@lmstudio/sdk/node_modules/chalk/source/util.js"(exports, module) {
    "use strict";
    init_process_shim();
    var stringReplaceAll = (string, substring, replacer) => {
      let index = string.indexOf(substring);
      if (index === -1) {
        return string;
      }
      const substringLength = substring.length;
      let endIndex = 0;
      let returnValue = "";
      do {
        returnValue += string.substr(endIndex, index - endIndex) + substring + replacer;
        endIndex = index + substringLength;
        index = string.indexOf(substring, endIndex);
      } while (index !== -1);
      returnValue += string.substr(endIndex);
      return returnValue;
    };
    var stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index) => {
      let endIndex = 0;
      let returnValue = "";
      do {
        const gotCR = string[index - 1] === "\r";
        returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? "\r\n" : "\n") + postfix;
        endIndex = index + 1;
        index = string.indexOf("\n", endIndex);
      } while (index !== -1);
      returnValue += string.substr(endIndex);
      return returnValue;
    };
    module.exports = {
      stringReplaceAll,
      stringEncaseCRLFWithFirstIndex
    };
  }
});

// ../pi-mono/node_modules/@lmstudio/sdk/node_modules/chalk/source/templates.js
var require_templates = __commonJS({
  "../pi-mono/node_modules/@lmstudio/sdk/node_modules/chalk/source/templates.js"(exports, module) {
    "use strict";
    init_process_shim();
    var TEMPLATE_REGEX = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
    var STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
    var STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
    var ESCAPE_REGEX2 = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi;
    var ESCAPES = /* @__PURE__ */ new Map([
      ["n", "\n"],
      ["r", "\r"],
      ["t", "	"],
      ["b", "\b"],
      ["f", "\f"],
      ["v", "\v"],
      ["0", "\0"],
      ["\\", "\\"],
      ["e", "\x1B"],
      ["a", "\x07"]
    ]);
    function unescape3(c6) {
      const u5 = c6[0] === "u";
      const bracket = c6[1] === "{";
      if (u5 && !bracket && c6.length === 5 || c6[0] === "x" && c6.length === 3) {
        return String.fromCharCode(parseInt(c6.slice(1), 16));
      }
      if (u5 && bracket) {
        return String.fromCodePoint(parseInt(c6.slice(2, -1), 16));
      }
      return ESCAPES.get(c6) || c6;
    }
    function parseArguments(name, arguments_) {
      const results = [];
      const chunks = arguments_.trim().split(/\s*,\s*/g);
      let matches;
      for (const chunk of chunks) {
        const number = Number(chunk);
        if (!Number.isNaN(number)) {
          results.push(number);
        } else if (matches = chunk.match(STRING_REGEX)) {
          results.push(matches[2].replace(ESCAPE_REGEX2, (m4, escape4, character) => escape4 ? unescape3(escape4) : character));
        } else {
          throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
        }
      }
      return results;
    }
    function parseStyle(style) {
      STYLE_REGEX.lastIndex = 0;
      const results = [];
      let matches;
      while ((matches = STYLE_REGEX.exec(style)) !== null) {
        const name = matches[1];
        if (matches[2]) {
          const args = parseArguments(name, matches[2]);
          results.push([name].concat(args));
        } else {
          results.push([name]);
        }
      }
      return results;
    }
    function buildStyle(chalk2, styles2) {
      const enabled = {};
      for (const layer of styles2) {
        for (const style of layer.styles) {
          enabled[style[0]] = layer.inverse ? null : style.slice(1);
        }
      }
      let current2 = chalk2;
      for (const [styleName, styles3] of Object.entries(enabled)) {
        if (!Array.isArray(styles3)) {
          continue;
        }
        if (!(styleName in current2)) {
          throw new Error(`Unknown Chalk style: ${styleName}`);
        }
        current2 = styles3.length > 0 ? current2[styleName](...styles3) : current2[styleName];
      }
      return current2;
    }
    module.exports = (chalk2, temporary) => {
      const styles2 = [];
      const chunks = [];
      let chunk = [];
      temporary.replace(TEMPLATE_REGEX, (m4, escapeCharacter, inverse, style, close2, character) => {
        if (escapeCharacter) {
          chunk.push(unescape3(escapeCharacter));
        } else if (style) {
          const string = chunk.join("");
          chunk = [];
          chunks.push(styles2.length === 0 ? string : buildStyle(chalk2, styles2)(string));
          styles2.push({ inverse, styles: parseStyle(style) });
        } else if (close2) {
          if (styles2.length === 0) {
            throw new Error("Found extraneous } in Chalk template literal");
          }
          chunks.push(buildStyle(chalk2, styles2)(chunk.join("")));
          chunk = [];
          styles2.pop();
        } else {
          chunk.push(character);
        }
      });
      chunks.push(chunk.join(""));
      if (styles2.length > 0) {
        const errMessage = `Chalk template literal is missing ${styles2.length} closing bracket${styles2.length === 1 ? "" : "s"} (\`}\`)`;
        throw new Error(errMessage);
      }
      return chunks.join("");
    };
  }
});

// ../pi-mono/node_modules/@lmstudio/sdk/node_modules/chalk/source/index.js
var require_source2 = __commonJS({
  "../pi-mono/node_modules/@lmstudio/sdk/node_modules/chalk/source/index.js"(exports, module) {
    "use strict";
    init_process_shim();
    var ansiStyles2 = require_ansi_styles();
    var { stdout: stdoutColor, stderr: stderrColor } = require_browser();
    var {
      stringReplaceAll,
      stringEncaseCRLFWithFirstIndex
    } = require_util3();
    var { isArray: isArray5 } = Array;
    var levelMapping = [
      "ansi",
      "ansi",
      "ansi256",
      "ansi16m"
    ];
    var styles2 = /* @__PURE__ */ Object.create(null);
    var applyOptions = (object, options = {}) => {
      if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
        throw new Error("The `level` option should be an integer from 0 to 3");
      }
      const colorLevel = stdoutColor ? stdoutColor.level : 0;
      object.level = options.level === void 0 ? colorLevel : options.level;
    };
    var ChalkClass = class {
      constructor(options) {
        return chalkFactory(options);
      }
    };
    var chalkFactory = (options) => {
      const chalk3 = {};
      applyOptions(chalk3, options);
      chalk3.template = (...arguments_) => chalkTag(chalk3.template, ...arguments_);
      Object.setPrototypeOf(chalk3, Chalk.prototype);
      Object.setPrototypeOf(chalk3.template, chalk3);
      chalk3.template.constructor = () => {
        throw new Error("`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.");
      };
      chalk3.template.Instance = ChalkClass;
      return chalk3.template;
    };
    function Chalk(options) {
      return chalkFactory(options);
    }
    for (const [styleName, style] of Object.entries(ansiStyles2)) {
      styles2[styleName] = {
        get() {
          const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty);
          Object.defineProperty(this, styleName, { value: builder });
          return builder;
        }
      };
    }
    styles2.visible = {
      get() {
        const builder = createBuilder(this, this._styler, true);
        Object.defineProperty(this, "visible", { value: builder });
        return builder;
      }
    };
    var usedModels = ["rgb", "hex", "keyword", "hsl", "hsv", "hwb", "ansi", "ansi256"];
    for (const model of usedModels) {
      styles2[model] = {
        get() {
          const { level } = this;
          return function(...arguments_) {
            const styler = createStyler(ansiStyles2.color[levelMapping[level]][model](...arguments_), ansiStyles2.color.close, this._styler);
            return createBuilder(this, styler, this._isEmpty);
          };
        }
      };
    }
    for (const model of usedModels) {
      const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
      styles2[bgModel] = {
        get() {
          const { level } = this;
          return function(...arguments_) {
            const styler = createStyler(ansiStyles2.bgColor[levelMapping[level]][model](...arguments_), ansiStyles2.bgColor.close, this._styler);
            return createBuilder(this, styler, this._isEmpty);
          };
        }
      };
    }
    var proto = Object.defineProperties(() => {
    }, {
      ...styles2,
      level: {
        enumerable: true,
        get() {
          return this._generator.level;
        },
        set(level) {
          this._generator.level = level;
        }
      }
    });
    var createStyler = (open2, close2, parent) => {
      let openAll;
      let closeAll;
      if (parent === void 0) {
        openAll = open2;
        closeAll = close2;
      } else {
        openAll = parent.openAll + open2;
        closeAll = close2 + parent.closeAll;
      }
      return {
        open: open2,
        close: close2,
        openAll,
        closeAll,
        parent
      };
    };
    var createBuilder = (self2, _styler, _isEmpty) => {
      const builder = (...arguments_) => {
        if (isArray5(arguments_[0]) && isArray5(arguments_[0].raw)) {
          return applyStyle(builder, chalkTag(builder, ...arguments_));
        }
        return applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" "));
      };
      Object.setPrototypeOf(builder, proto);
      builder._generator = self2;
      builder._styler = _styler;
      builder._isEmpty = _isEmpty;
      return builder;
    };
    var applyStyle = (self2, string) => {
      if (self2.level <= 0 || !string) {
        return self2._isEmpty ? "" : string;
      }
      let styler = self2._styler;
      if (styler === void 0) {
        return string;
      }
      const { openAll, closeAll } = styler;
      if (string.indexOf("\x1B") !== -1) {
        while (styler !== void 0) {
          string = stringReplaceAll(string, styler.close, styler.open);
          styler = styler.parent;
        }
      }
      const lfIndex = string.indexOf("\n");
      if (lfIndex !== -1) {
        string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
      }
      return openAll + string + closeAll;
    };
    var template;
    var chalkTag = (chalk3, ...strings) => {
      const [firstString] = strings;
      if (!isArray5(firstString) || !isArray5(firstString.raw)) {
        return strings.join(" ");
      }
      const arguments_ = strings.slice(1);
      const parts = [firstString.raw[0]];
      for (let i7 = 1; i7 < firstString.length; i7++) {
        parts.push(
          String(arguments_[i7 - 1]).replace(/[{}\\]/g, "\\$&"),
          String(firstString.raw[i7])
        );
      }
      if (template === void 0) {
        template = require_templates();
      }
      return template(chalk3, parts.join(""));
    };
    Object.defineProperties(Chalk.prototype, styles2);
    var chalk2 = Chalk();
    chalk2.supportsColor = stdoutColor;
    chalk2.stderr = Chalk({ level: stderrColor ? stderrColor.level : 0 });
    chalk2.stderr.supportsColor = stderrColor;
    module.exports = chalk2;
  }
});

// ../pi-mono/node_modules/@lmstudio/lms-isomorphic/dist/cjs/browser/generateRandomBase64.js
var require_generateRandomBase64 = __commonJS({
  "../pi-mono/node_modules/@lmstudio/lms-isomorphic/dist/cjs/browser/generateRandomBase64.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.generateRandomBase64 = generateRandomBase642;
    function generateRandomBase642(bytesOfRandomness = 18) {
      const randomBytes = new Uint8Array(bytesOfRandomness);
      globalThis.crypto.getRandomValues(randomBytes);
      return btoa(String.fromCharCode(...randomBytes));
    }
  }
});

// ../pi-mono/node_modules/@lmstudio/lms-isomorphic/dist/cjs/browser/readFileAsBase64.js
var require_readFileAsBase64 = __commonJS({
  "../pi-mono/node_modules/@lmstudio/lms-isomorphic/dist/cjs/browser/readFileAsBase64.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.readFileAsBase64 = readFileAsBase642;
    async function readFileAsBase642(_path) {
      return { success: false };
    }
  }
});

// ../pi-mono/node_modules/@lmstudio/lms-isomorphic/dist/cjs/browser/terminalSize.js
var require_terminalSize = __commonJS({
  "../pi-mono/node_modules/@lmstudio/lms-isomorphic/dist/cjs/browser/terminalSize.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.terminalSize = terminalSize2;
    function terminalSize2() {
      return { columns: 80, rows: 24 };
    }
  }
});

// ../pi-mono/node_modules/@lmstudio/lms-isomorphic/dist/cjs/browser/WebSocket.js
var require_WebSocket = __commonJS({
  "../pi-mono/node_modules/@lmstudio/lms-isomorphic/dist/cjs/browser/WebSocket.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.WebSocket = void 0;
    exports.WebSocket = globalThis.WebSocket;
  }
});

// ../pi-mono/node_modules/@lmstudio/lms-isomorphic/dist/cjs/browser.js
var require_browser2 = __commonJS({
  "../pi-mono/node_modules/@lmstudio/lms-isomorphic/dist/cjs/browser.js"(exports) {
    "use strict";
    init_process_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.WebSocket = exports.terminalSize = exports.readFileAsBase64 = exports.generateRandomBase64 = void 0;
    var generateRandomBase64_js_1 = require_generateRandomBase64();
    Object.defineProperty(exports, "generateRandomBase64", { enumerable: true, get: function() {
      return generateRandomBase64_js_1.generateRandomBase64;
    } });
    var readFileAsBase64_js_1 = require_readFileAsBase64();
    Object.defineProperty(exports, "readFileAsBase64", { enumerable: true, get: function() {
      return readFileAsBase64_js_1.readFileAsBase64;
    } });
    var terminalSize_js_1 = require_terminalSize();
    Object.defineProperty(exports, "terminalSize", { enumerable: true, get: function() {
      return terminalSize_js_1.terminalSize;
    } });
    var WebSocket_js_1 = require_WebSocket();
    Object.defineProperty(exports, "WebSocket", { enumerable: true, get: function() {
      return WebSocket_js_1.WebSocket;
    } });
  }
});

// ../pi-mono/node_modules/jszip/dist/jszip.min.js
var require_jszip_min = __commonJS({
  "../pi-mono/node_modules/jszip/dist/jszip.min.js"(exports, module) {
    init_process_shim();
    !(function(e9) {
      if ("object" == typeof exports && "undefined" != typeof module) module.exports = e9();
      else if ("function" == typeof define && define.amd) define([], e9);
      else {
        ("undefined" != typeof window ? window : "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : this).JSZip = e9();
      }
    })(function() {
      return (function s6(a3, o9, h7) {
        function u5(r8, e10) {
          if (!o9[r8]) {
            if (!a3[r8]) {
              var t6 = "function" == typeof __require && __require;
              if (!e10 && t6) return t6(r8, true);
              if (l5) return l5(r8, true);
              var n7 = new Error("Cannot find module '" + r8 + "'");
              throw n7.code = "MODULE_NOT_FOUND", n7;
            }
            var i7 = o9[r8] = { exports: {} };
            a3[r8][0].call(i7.exports, function(e11) {
              var t7 = a3[r8][1][e11];
              return u5(t7 || e11);
            }, i7, i7.exports, s6, a3, o9, h7);
          }
          return o9[r8].exports;
        }
        for (var l5 = "function" == typeof __require && __require, e9 = 0; e9 < h7.length; e9++) u5(h7[e9]);
        return u5;
      })({ 1: [function(e9, t6, r8) {
        "use strict";
        var d4 = e9("./utils"), c6 = e9("./support"), p4 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
        r8.encode = function(e10) {
          for (var t7, r9, n7, i7, s6, a3, o9, h7 = [], u5 = 0, l5 = e10.length, f4 = l5, c7 = "string" !== d4.getTypeOf(e10); u5 < e10.length; ) f4 = l5 - u5, n7 = c7 ? (t7 = e10[u5++], r9 = u5 < l5 ? e10[u5++] : 0, u5 < l5 ? e10[u5++] : 0) : (t7 = e10.charCodeAt(u5++), r9 = u5 < l5 ? e10.charCodeAt(u5++) : 0, u5 < l5 ? e10.charCodeAt(u5++) : 0), i7 = t7 >> 2, s6 = (3 & t7) << 4 | r9 >> 4, a3 = 1 < f4 ? (15 & r9) << 2 | n7 >> 6 : 64, o9 = 2 < f4 ? 63 & n7 : 64, h7.push(p4.charAt(i7) + p4.charAt(s6) + p4.charAt(a3) + p4.charAt(o9));
          return h7.join("");
        }, r8.decode = function(e10) {
          var t7, r9, n7, i7, s6, a3, o9 = 0, h7 = 0, u5 = "data:";
          if (e10.substr(0, u5.length) === u5) throw new Error("Invalid base64 input, it looks like a data url.");
          var l5, f4 = 3 * (e10 = e10.replace(/[^A-Za-z0-9+/=]/g, "")).length / 4;
          if (e10.charAt(e10.length - 1) === p4.charAt(64) && f4--, e10.charAt(e10.length - 2) === p4.charAt(64) && f4--, f4 % 1 != 0) throw new Error("Invalid base64 input, bad content length.");
          for (l5 = c6.uint8array ? new Uint8Array(0 | f4) : new Array(0 | f4); o9 < e10.length; ) t7 = p4.indexOf(e10.charAt(o9++)) << 2 | (i7 = p4.indexOf(e10.charAt(o9++))) >> 4, r9 = (15 & i7) << 4 | (s6 = p4.indexOf(e10.charAt(o9++))) >> 2, n7 = (3 & s6) << 6 | (a3 = p4.indexOf(e10.charAt(o9++))), l5[h7++] = t7, 64 !== s6 && (l5[h7++] = r9), 64 !== a3 && (l5[h7++] = n7);
          return l5;
        };
      }, { "./support": 30, "./utils": 32 }], 2: [function(e9, t6, r8) {
        "use strict";
        var n7 = e9("./external"), i7 = e9("./stream/DataWorker"), s6 = e9("./stream/Crc32Probe"), a3 = e9("./stream/DataLengthProbe");
        function o9(e10, t7, r9, n8, i8) {
          this.compressedSize = e10, this.uncompressedSize = t7, this.crc32 = r9, this.compression = n8, this.compressedContent = i8;
        }
        o9.prototype = { getContentWorker: function() {
          var e10 = new i7(n7.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new a3("data_length")), t7 = this;
          return e10.on("end", function() {
            if (this.streamInfo.data_length !== t7.uncompressedSize) throw new Error("Bug : uncompressed data size mismatch");
          }), e10;
        }, getCompressedWorker: function() {
          return new i7(n7.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize", this.compressedSize).withStreamInfo("uncompressedSize", this.uncompressedSize).withStreamInfo("crc32", this.crc32).withStreamInfo("compression", this.compression);
        } }, o9.createWorkerFrom = function(e10, t7, r9) {
          return e10.pipe(new s6()).pipe(new a3("uncompressedSize")).pipe(t7.compressWorker(r9)).pipe(new a3("compressedSize")).withStreamInfo("compression", t7);
        }, t6.exports = o9;
      }, { "./external": 6, "./stream/Crc32Probe": 25, "./stream/DataLengthProbe": 26, "./stream/DataWorker": 27 }], 3: [function(e9, t6, r8) {
        "use strict";
        var n7 = e9("./stream/GenericWorker");
        r8.STORE = { magic: "\0\0", compressWorker: function() {
          return new n7("STORE compression");
        }, uncompressWorker: function() {
          return new n7("STORE decompression");
        } }, r8.DEFLATE = e9("./flate");
      }, { "./flate": 7, "./stream/GenericWorker": 28 }], 4: [function(e9, t6, r8) {
        "use strict";
        var n7 = e9("./utils");
        var o9 = (function() {
          for (var e10, t7 = [], r9 = 0; r9 < 256; r9++) {
            e10 = r9;
            for (var n8 = 0; n8 < 8; n8++) e10 = 1 & e10 ? 3988292384 ^ e10 >>> 1 : e10 >>> 1;
            t7[r9] = e10;
          }
          return t7;
        })();
        t6.exports = function(e10, t7) {
          return void 0 !== e10 && e10.length ? "string" !== n7.getTypeOf(e10) ? (function(e11, t8, r9, n8) {
            var i7 = o9, s6 = n8 + r9;
            e11 ^= -1;
            for (var a3 = n8; a3 < s6; a3++) e11 = e11 >>> 8 ^ i7[255 & (e11 ^ t8[a3])];
            return -1 ^ e11;
          })(0 | t7, e10, e10.length, 0) : (function(e11, t8, r9, n8) {
            var i7 = o9, s6 = n8 + r9;
            e11 ^= -1;
            for (var a3 = n8; a3 < s6; a3++) e11 = e11 >>> 8 ^ i7[255 & (e11 ^ t8.charCodeAt(a3))];
            return -1 ^ e11;
          })(0 | t7, e10, e10.length, 0) : 0;
        };
      }, { "./utils": 32 }], 5: [function(e9, t6, r8) {
        "use strict";
        r8.base64 = false, r8.binary = false, r8.dir = false, r8.createFolders = true, r8.date = null, r8.compression = null, r8.compressionOptions = null, r8.comment = null, r8.unixPermissions = null, r8.dosPermissions = null;
      }, {}], 6: [function(e9, t6, r8) {
        "use strict";
        var n7 = null;
        n7 = "undefined" != typeof Promise ? Promise : e9("lie"), t6.exports = { Promise: n7 };
      }, { lie: 37 }], 7: [function(e9, t6, r8) {
        "use strict";
        var n7 = "undefined" != typeof Uint8Array && "undefined" != typeof Uint16Array && "undefined" != typeof Uint32Array, i7 = e9("pako"), s6 = e9("./utils"), a3 = e9("./stream/GenericWorker"), o9 = n7 ? "uint8array" : "array";
        function h7(e10, t7) {
          a3.call(this, "FlateWorker/" + e10), this._pako = null, this._pakoAction = e10, this._pakoOptions = t7, this.meta = {};
        }
        r8.magic = "\b\0", s6.inherits(h7, a3), h7.prototype.processChunk = function(e10) {
          this.meta = e10.meta, null === this._pako && this._createPako(), this._pako.push(s6.transformTo(o9, e10.data), false);
        }, h7.prototype.flush = function() {
          a3.prototype.flush.call(this), null === this._pako && this._createPako(), this._pako.push([], true);
        }, h7.prototype.cleanUp = function() {
          a3.prototype.cleanUp.call(this), this._pako = null;
        }, h7.prototype._createPako = function() {
          this._pako = new i7[this._pakoAction]({ raw: true, level: this._pakoOptions.level || -1 });
          var t7 = this;
          this._pako.onData = function(e10) {
            t7.push({ data: e10, meta: t7.meta });
          };
        }, r8.compressWorker = function(e10) {
          return new h7("Deflate", e10);
        }, r8.uncompressWorker = function() {
          return new h7("Inflate", {});
        };
      }, { "./stream/GenericWorker": 28, "./utils": 32, pako: 38 }], 8: [function(e9, t6, r8) {
        "use strict";
        function A2(e10, t7) {
          var r9, n8 = "";
          for (r9 = 0; r9 < t7; r9++) n8 += String.fromCharCode(255 & e10), e10 >>>= 8;
          return n8;
        }
        function n7(e10, t7, r9, n8, i8, s7) {
          var a3, o9, h7 = e10.file, u5 = e10.compression, l5 = s7 !== O2.utf8encode, f4 = I3.transformTo("string", s7(h7.name)), c6 = I3.transformTo("string", O2.utf8encode(h7.name)), d4 = h7.comment, p4 = I3.transformTo("string", s7(d4)), m4 = I3.transformTo("string", O2.utf8encode(d4)), _3 = c6.length !== h7.name.length, g3 = m4.length !== d4.length, b4 = "", v4 = "", y4 = "", w3 = h7.dir, k2 = h7.date, x2 = { crc32: 0, compressedSize: 0, uncompressedSize: 0 };
          t7 && !r9 || (x2.crc32 = e10.crc32, x2.compressedSize = e10.compressedSize, x2.uncompressedSize = e10.uncompressedSize);
          var S5 = 0;
          t7 && (S5 |= 8), l5 || !_3 && !g3 || (S5 |= 2048);
          var z3 = 0, C3 = 0;
          w3 && (z3 |= 16), "UNIX" === i8 ? (C3 = 798, z3 |= (function(e11, t8) {
            var r10 = e11;
            return e11 || (r10 = t8 ? 16893 : 33204), (65535 & r10) << 16;
          })(h7.unixPermissions, w3)) : (C3 = 20, z3 |= (function(e11) {
            return 63 & (e11 || 0);
          })(h7.dosPermissions)), a3 = k2.getUTCHours(), a3 <<= 6, a3 |= k2.getUTCMinutes(), a3 <<= 5, a3 |= k2.getUTCSeconds() / 2, o9 = k2.getUTCFullYear() - 1980, o9 <<= 4, o9 |= k2.getUTCMonth() + 1, o9 <<= 5, o9 |= k2.getUTCDate(), _3 && (v4 = A2(1, 1) + A2(B3(f4), 4) + c6, b4 += "up" + A2(v4.length, 2) + v4), g3 && (y4 = A2(1, 1) + A2(B3(p4), 4) + m4, b4 += "uc" + A2(y4.length, 2) + y4);
          var E3 = "";
          return E3 += "\n\0", E3 += A2(S5, 2), E3 += u5.magic, E3 += A2(a3, 2), E3 += A2(o9, 2), E3 += A2(x2.crc32, 4), E3 += A2(x2.compressedSize, 4), E3 += A2(x2.uncompressedSize, 4), E3 += A2(f4.length, 2), E3 += A2(b4.length, 2), { fileRecord: R3.LOCAL_FILE_HEADER + E3 + f4 + b4, dirRecord: R3.CENTRAL_FILE_HEADER + A2(C3, 2) + E3 + A2(p4.length, 2) + "\0\0\0\0" + A2(z3, 4) + A2(n8, 4) + f4 + b4 + p4 };
        }
        var I3 = e9("../utils"), i7 = e9("../stream/GenericWorker"), O2 = e9("../utf8"), B3 = e9("../crc32"), R3 = e9("../signature");
        function s6(e10, t7, r9, n8) {
          i7.call(this, "ZipFileWorker"), this.bytesWritten = 0, this.zipComment = t7, this.zipPlatform = r9, this.encodeFileName = n8, this.streamFiles = e10, this.accumulate = false, this.contentBuffer = [], this.dirRecords = [], this.currentSourceOffset = 0, this.entriesCount = 0, this.currentFile = null, this._sources = [];
        }
        I3.inherits(s6, i7), s6.prototype.push = function(e10) {
          var t7 = e10.meta.percent || 0, r9 = this.entriesCount, n8 = this._sources.length;
          this.accumulate ? this.contentBuffer.push(e10) : (this.bytesWritten += e10.data.length, i7.prototype.push.call(this, { data: e10.data, meta: { currentFile: this.currentFile, percent: r9 ? (t7 + 100 * (r9 - n8 - 1)) / r9 : 100 } }));
        }, s6.prototype.openedSource = function(e10) {
          this.currentSourceOffset = this.bytesWritten, this.currentFile = e10.file.name;
          var t7 = this.streamFiles && !e10.file.dir;
          if (t7) {
            var r9 = n7(e10, t7, false, this.currentSourceOffset, this.zipPlatform, this.encodeFileName);
            this.push({ data: r9.fileRecord, meta: { percent: 0 } });
          } else this.accumulate = true;
        }, s6.prototype.closedSource = function(e10) {
          this.accumulate = false;
          var t7 = this.streamFiles && !e10.file.dir, r9 = n7(e10, t7, true, this.currentSourceOffset, this.zipPlatform, this.encodeFileName);
          if (this.dirRecords.push(r9.dirRecord), t7) this.push({ data: (function(e11) {
            return R3.DATA_DESCRIPTOR + A2(e11.crc32, 4) + A2(e11.compressedSize, 4) + A2(e11.uncompressedSize, 4);
          })(e10), meta: { percent: 100 } });
          else for (this.push({ data: r9.fileRecord, meta: { percent: 0 } }); this.contentBuffer.length; ) this.push(this.contentBuffer.shift());
          this.currentFile = null;
        }, s6.prototype.flush = function() {
          for (var e10 = this.bytesWritten, t7 = 0; t7 < this.dirRecords.length; t7++) this.push({ data: this.dirRecords[t7], meta: { percent: 100 } });
          var r9 = this.bytesWritten - e10, n8 = (function(e11, t8, r10, n9, i8) {
            var s7 = I3.transformTo("string", i8(n9));
            return R3.CENTRAL_DIRECTORY_END + "\0\0\0\0" + A2(e11, 2) + A2(e11, 2) + A2(t8, 4) + A2(r10, 4) + A2(s7.length, 2) + s7;
          })(this.dirRecords.length, r9, e10, this.zipComment, this.encodeFileName);
          this.push({ data: n8, meta: { percent: 100 } });
        }, s6.prototype.prepareNextSource = function() {
          this.previous = this._sources.shift(), this.openedSource(this.previous.streamInfo), this.isPaused ? this.previous.pause() : this.previous.resume();
        }, s6.prototype.registerPrevious = function(e10) {
          this._sources.push(e10);
          var t7 = this;
          return e10.on("data", function(e11) {
            t7.processChunk(e11);
          }), e10.on("end", function() {
            t7.closedSource(t7.previous.streamInfo), t7._sources.length ? t7.prepareNextSource() : t7.end();
          }), e10.on("error", function(e11) {
            t7.error(e11);
          }), this;
        }, s6.prototype.resume = function() {
          return !!i7.prototype.resume.call(this) && (!this.previous && this._sources.length ? (this.prepareNextSource(), true) : this.previous || this._sources.length || this.generatedError ? void 0 : (this.end(), true));
        }, s6.prototype.error = function(e10) {
          var t7 = this._sources;
          if (!i7.prototype.error.call(this, e10)) return false;
          for (var r9 = 0; r9 < t7.length; r9++) try {
            t7[r9].error(e10);
          } catch (e11) {
          }
          return true;
        }, s6.prototype.lock = function() {
          i7.prototype.lock.call(this);
          for (var e10 = this._sources, t7 = 0; t7 < e10.length; t7++) e10[t7].lock();
        }, t6.exports = s6;
      }, { "../crc32": 4, "../signature": 23, "../stream/GenericWorker": 28, "../utf8": 31, "../utils": 32 }], 9: [function(e9, t6, r8) {
        "use strict";
        var u5 = e9("../compressions"), n7 = e9("./ZipFileWorker");
        r8.generateWorker = function(e10, a3, t7) {
          var o9 = new n7(a3.streamFiles, t7, a3.platform, a3.encodeFileName), h7 = 0;
          try {
            e10.forEach(function(e11, t8) {
              h7++;
              var r9 = (function(e12, t9) {
                var r10 = e12 || t9, n9 = u5[r10];
                if (!n9) throw new Error(r10 + " is not a valid compression method !");
                return n9;
              })(t8.options.compression, a3.compression), n8 = t8.options.compressionOptions || a3.compressionOptions || {}, i7 = t8.dir, s6 = t8.date;
              t8._compressWorker(r9, n8).withStreamInfo("file", { name: e11, dir: i7, date: s6, comment: t8.comment || "", unixPermissions: t8.unixPermissions, dosPermissions: t8.dosPermissions }).pipe(o9);
            }), o9.entriesCount = h7;
          } catch (e11) {
            o9.error(e11);
          }
          return o9;
        };
      }, { "../compressions": 3, "./ZipFileWorker": 8 }], 10: [function(e9, t6, r8) {
        "use strict";
        function n7() {
          if (!(this instanceof n7)) return new n7();
          if (arguments.length) throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");
          this.files = /* @__PURE__ */ Object.create(null), this.comment = null, this.root = "", this.clone = function() {
            var e10 = new n7();
            for (var t7 in this) "function" != typeof this[t7] && (e10[t7] = this[t7]);
            return e10;
          };
        }
        (n7.prototype = e9("./object")).loadAsync = e9("./load"), n7.support = e9("./support"), n7.defaults = e9("./defaults"), n7.version = "3.10.1", n7.loadAsync = function(e10, t7) {
          return new n7().loadAsync(e10, t7);
        }, n7.external = e9("./external"), t6.exports = n7;
      }, { "./defaults": 5, "./external": 6, "./load": 11, "./object": 15, "./support": 30 }], 11: [function(e9, t6, r8) {
        "use strict";
        var u5 = e9("./utils"), i7 = e9("./external"), n7 = e9("./utf8"), s6 = e9("./zipEntries"), a3 = e9("./stream/Crc32Probe"), l5 = e9("./nodejsUtils");
        function f4(n8) {
          return new i7.Promise(function(e10, t7) {
            var r9 = n8.decompressed.getContentWorker().pipe(new a3());
            r9.on("error", function(e11) {
              t7(e11);
            }).on("end", function() {
              r9.streamInfo.crc32 !== n8.decompressed.crc32 ? t7(new Error("Corrupted zip : CRC32 mismatch")) : e10();
            }).resume();
          });
        }
        t6.exports = function(e10, o9) {
          var h7 = this;
          return o9 = u5.extend(o9 || {}, { base64: false, checkCRC32: false, optimizedBinaryString: false, createFolders: false, decodeFileName: n7.utf8decode }), l5.isNode && l5.isStream(e10) ? i7.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")) : u5.prepareContent("the loaded zip file", e10, true, o9.optimizedBinaryString, o9.base64).then(function(e11) {
            var t7 = new s6(o9);
            return t7.load(e11), t7;
          }).then(function(e11) {
            var t7 = [i7.Promise.resolve(e11)], r9 = e11.files;
            if (o9.checkCRC32) for (var n8 = 0; n8 < r9.length; n8++) t7.push(f4(r9[n8]));
            return i7.Promise.all(t7);
          }).then(function(e11) {
            for (var t7 = e11.shift(), r9 = t7.files, n8 = 0; n8 < r9.length; n8++) {
              var i8 = r9[n8], s7 = i8.fileNameStr, a4 = u5.resolve(i8.fileNameStr);
              h7.file(a4, i8.decompressed, { binary: true, optimizedBinaryString: true, date: i8.date, dir: i8.dir, comment: i8.fileCommentStr.length ? i8.fileCommentStr : null, unixPermissions: i8.unixPermissions, dosPermissions: i8.dosPermissions, createFolders: o9.createFolders }), i8.dir || (h7.file(a4).unsafeOriginalName = s7);
            }
            return t7.zipComment.length && (h7.comment = t7.zipComment), h7;
          });
        };
      }, { "./external": 6, "./nodejsUtils": 14, "./stream/Crc32Probe": 25, "./utf8": 31, "./utils": 32, "./zipEntries": 33 }], 12: [function(e9, t6, r8) {
        "use strict";
        var n7 = e9("../utils"), i7 = e9("../stream/GenericWorker");
        function s6(e10, t7) {
          i7.call(this, "Nodejs stream input adapter for " + e10), this._upstreamEnded = false, this._bindStream(t7);
        }
        n7.inherits(s6, i7), s6.prototype._bindStream = function(e10) {
          var t7 = this;
          (this._stream = e10).pause(), e10.on("data", function(e11) {
            t7.push({ data: e11, meta: { percent: 0 } });
          }).on("error", function(e11) {
            t7.isPaused ? this.generatedError = e11 : t7.error(e11);
          }).on("end", function() {
            t7.isPaused ? t7._upstreamEnded = true : t7.end();
          });
        }, s6.prototype.pause = function() {
          return !!i7.prototype.pause.call(this) && (this._stream.pause(), true);
        }, s6.prototype.resume = function() {
          return !!i7.prototype.resume.call(this) && (this._upstreamEnded ? this.end() : this._stream.resume(), true);
        }, t6.exports = s6;
      }, { "../stream/GenericWorker": 28, "../utils": 32 }], 13: [function(e9, t6, r8) {
        "use strict";
        var i7 = e9("readable-stream").Readable;
        function n7(e10, t7, r9) {
          i7.call(this, t7), this._helper = e10;
          var n8 = this;
          e10.on("data", function(e11, t8) {
            n8.push(e11) || n8._helper.pause(), r9 && r9(t8);
          }).on("error", function(e11) {
            n8.emit("error", e11);
          }).on("end", function() {
            n8.push(null);
          });
        }
        e9("../utils").inherits(n7, i7), n7.prototype._read = function() {
          this._helper.resume();
        }, t6.exports = n7;
      }, { "../utils": 32, "readable-stream": 16 }], 14: [function(e9, t6, r8) {
        "use strict";
        t6.exports = { isNode: "undefined" != typeof Buffer, newBufferFrom: function(e10, t7) {
          if (Buffer.from && Buffer.from !== Uint8Array.from) return Buffer.from(e10, t7);
          if ("number" == typeof e10) throw new Error('The "data" argument must not be a number');
          return new Buffer(e10, t7);
        }, allocBuffer: function(e10) {
          if (Buffer.alloc) return Buffer.alloc(e10);
          var t7 = new Buffer(e10);
          return t7.fill(0), t7;
        }, isBuffer: function(e10) {
          return Buffer.isBuffer(e10);
        }, isStream: function(e10) {
          return e10 && "function" == typeof e10.on && "function" == typeof e10.pause && "function" == typeof e10.resume;
        } };
      }, {}], 15: [function(e9, t6, r8) {
        "use strict";
        function s6(e10, t7, r9) {
          var n8, i8 = u5.getTypeOf(t7), s7 = u5.extend(r9 || {}, f4);
          s7.date = s7.date || /* @__PURE__ */ new Date(), null !== s7.compression && (s7.compression = s7.compression.toUpperCase()), "string" == typeof s7.unixPermissions && (s7.unixPermissions = parseInt(s7.unixPermissions, 8)), s7.unixPermissions && 16384 & s7.unixPermissions && (s7.dir = true), s7.dosPermissions && 16 & s7.dosPermissions && (s7.dir = true), s7.dir && (e10 = g3(e10)), s7.createFolders && (n8 = _3(e10)) && b4.call(this, n8, true);
          var a4 = "string" === i8 && false === s7.binary && false === s7.base64;
          r9 && void 0 !== r9.binary || (s7.binary = !a4), (t7 instanceof c6 && 0 === t7.uncompressedSize || s7.dir || !t7 || 0 === t7.length) && (s7.base64 = false, s7.binary = true, t7 = "", s7.compression = "STORE", i8 = "string");
          var o10 = null;
          o10 = t7 instanceof c6 || t7 instanceof l5 ? t7 : p4.isNode && p4.isStream(t7) ? new m4(e10, t7) : u5.prepareContent(e10, t7, s7.binary, s7.optimizedBinaryString, s7.base64);
          var h8 = new d4(e10, o10, s7);
          this.files[e10] = h8;
        }
        var i7 = e9("./utf8"), u5 = e9("./utils"), l5 = e9("./stream/GenericWorker"), a3 = e9("./stream/StreamHelper"), f4 = e9("./defaults"), c6 = e9("./compressedObject"), d4 = e9("./zipObject"), o9 = e9("./generate"), p4 = e9("./nodejsUtils"), m4 = e9("./nodejs/NodejsStreamInputAdapter"), _3 = function(e10) {
          "/" === e10.slice(-1) && (e10 = e10.substring(0, e10.length - 1));
          var t7 = e10.lastIndexOf("/");
          return 0 < t7 ? e10.substring(0, t7) : "";
        }, g3 = function(e10) {
          return "/" !== e10.slice(-1) && (e10 += "/"), e10;
        }, b4 = function(e10, t7) {
          return t7 = void 0 !== t7 ? t7 : f4.createFolders, e10 = g3(e10), this.files[e10] || s6.call(this, e10, null, { dir: true, createFolders: t7 }), this.files[e10];
        };
        function h7(e10) {
          return "[object RegExp]" === Object.prototype.toString.call(e10);
        }
        var n7 = { load: function() {
          throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
        }, forEach: function(e10) {
          var t7, r9, n8;
          for (t7 in this.files) n8 = this.files[t7], (r9 = t7.slice(this.root.length, t7.length)) && t7.slice(0, this.root.length) === this.root && e10(r9, n8);
        }, filter: function(r9) {
          var n8 = [];
          return this.forEach(function(e10, t7) {
            r9(e10, t7) && n8.push(t7);
          }), n8;
        }, file: function(e10, t7, r9) {
          if (1 !== arguments.length) return e10 = this.root + e10, s6.call(this, e10, t7, r9), this;
          if (h7(e10)) {
            var n8 = e10;
            return this.filter(function(e11, t8) {
              return !t8.dir && n8.test(e11);
            });
          }
          var i8 = this.files[this.root + e10];
          return i8 && !i8.dir ? i8 : null;
        }, folder: function(r9) {
          if (!r9) return this;
          if (h7(r9)) return this.filter(function(e11, t8) {
            return t8.dir && r9.test(e11);
          });
          var e10 = this.root + r9, t7 = b4.call(this, e10), n8 = this.clone();
          return n8.root = t7.name, n8;
        }, remove: function(r9) {
          r9 = this.root + r9;
          var e10 = this.files[r9];
          if (e10 || ("/" !== r9.slice(-1) && (r9 += "/"), e10 = this.files[r9]), e10 && !e10.dir) delete this.files[r9];
          else for (var t7 = this.filter(function(e11, t8) {
            return t8.name.slice(0, r9.length) === r9;
          }), n8 = 0; n8 < t7.length; n8++) delete this.files[t7[n8].name];
          return this;
        }, generate: function() {
          throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
        }, generateInternalStream: function(e10) {
          var t7, r9 = {};
          try {
            if ((r9 = u5.extend(e10 || {}, { streamFiles: false, compression: "STORE", compressionOptions: null, type: "", platform: "DOS", comment: null, mimeType: "application/zip", encodeFileName: i7.utf8encode })).type = r9.type.toLowerCase(), r9.compression = r9.compression.toUpperCase(), "binarystring" === r9.type && (r9.type = "string"), !r9.type) throw new Error("No output type specified.");
            u5.checkSupport(r9.type), "darwin" !== r9.platform && "freebsd" !== r9.platform && "linux" !== r9.platform && "sunos" !== r9.platform || (r9.platform = "UNIX"), "win32" === r9.platform && (r9.platform = "DOS");
            var n8 = r9.comment || this.comment || "";
            t7 = o9.generateWorker(this, r9, n8);
          } catch (e11) {
            (t7 = new l5("error")).error(e11);
          }
          return new a3(t7, r9.type || "string", r9.mimeType);
        }, generateAsync: function(e10, t7) {
          return this.generateInternalStream(e10).accumulate(t7);
        }, generateNodeStream: function(e10, t7) {
          return (e10 = e10 || {}).type || (e10.type = "nodebuffer"), this.generateInternalStream(e10).toNodejsStream(t7);
        } };
        t6.exports = n7;
      }, { "./compressedObject": 2, "./defaults": 5, "./generate": 9, "./nodejs/NodejsStreamInputAdapter": 12, "./nodejsUtils": 14, "./stream/GenericWorker": 28, "./stream/StreamHelper": 29, "./utf8": 31, "./utils": 32, "./zipObject": 35 }], 16: [function(e9, t6, r8) {
        "use strict";
        t6.exports = e9("stream");
      }, { stream: void 0 }], 17: [function(e9, t6, r8) {
        "use strict";
        var n7 = e9("./DataReader");
        function i7(e10) {
          n7.call(this, e10);
          for (var t7 = 0; t7 < this.data.length; t7++) e10[t7] = 255 & e10[t7];
        }
        e9("../utils").inherits(i7, n7), i7.prototype.byteAt = function(e10) {
          return this.data[this.zero + e10];
        }, i7.prototype.lastIndexOfSignature = function(e10) {
          for (var t7 = e10.charCodeAt(0), r9 = e10.charCodeAt(1), n8 = e10.charCodeAt(2), i8 = e10.charCodeAt(3), s6 = this.length - 4; 0 <= s6; --s6) if (this.data[s6] === t7 && this.data[s6 + 1] === r9 && this.data[s6 + 2] === n8 && this.data[s6 + 3] === i8) return s6 - this.zero;
          return -1;
        }, i7.prototype.readAndCheckSignature = function(e10) {
          var t7 = e10.charCodeAt(0), r9 = e10.charCodeAt(1), n8 = e10.charCodeAt(2), i8 = e10.charCodeAt(3), s6 = this.readData(4);
          return t7 === s6[0] && r9 === s6[1] && n8 === s6[2] && i8 === s6[3];
        }, i7.prototype.readData = function(e10) {
          if (this.checkOffset(e10), 0 === e10) return [];
          var t7 = this.data.slice(this.zero + this.index, this.zero + this.index + e10);
          return this.index += e10, t7;
        }, t6.exports = i7;
      }, { "../utils": 32, "./DataReader": 18 }], 18: [function(e9, t6, r8) {
        "use strict";
        var n7 = e9("../utils");
        function i7(e10) {
          this.data = e10, this.length = e10.length, this.index = 0, this.zero = 0;
        }
        i7.prototype = { checkOffset: function(e10) {
          this.checkIndex(this.index + e10);
        }, checkIndex: function(e10) {
          if (this.length < this.zero + e10 || e10 < 0) throw new Error("End of data reached (data length = " + this.length + ", asked index = " + e10 + "). Corrupted zip ?");
        }, setIndex: function(e10) {
          this.checkIndex(e10), this.index = e10;
        }, skip: function(e10) {
          this.setIndex(this.index + e10);
        }, byteAt: function() {
        }, readInt: function(e10) {
          var t7, r9 = 0;
          for (this.checkOffset(e10), t7 = this.index + e10 - 1; t7 >= this.index; t7--) r9 = (r9 << 8) + this.byteAt(t7);
          return this.index += e10, r9;
        }, readString: function(e10) {
          return n7.transformTo("string", this.readData(e10));
        }, readData: function() {
        }, lastIndexOfSignature: function() {
        }, readAndCheckSignature: function() {
        }, readDate: function() {
          var e10 = this.readInt(4);
          return new Date(Date.UTC(1980 + (e10 >> 25 & 127), (e10 >> 21 & 15) - 1, e10 >> 16 & 31, e10 >> 11 & 31, e10 >> 5 & 63, (31 & e10) << 1));
        } }, t6.exports = i7;
      }, { "../utils": 32 }], 19: [function(e9, t6, r8) {
        "use strict";
        var n7 = e9("./Uint8ArrayReader");
        function i7(e10) {
          n7.call(this, e10);
        }
        e9("../utils").inherits(i7, n7), i7.prototype.readData = function(e10) {
          this.checkOffset(e10);
          var t7 = this.data.slice(this.zero + this.index, this.zero + this.index + e10);
          return this.index += e10, t7;
        }, t6.exports = i7;
      }, { "../utils": 32, "./Uint8ArrayReader": 21 }], 20: [function(e9, t6, r8) {
        "use strict";
        var n7 = e9("./DataReader");
        function i7(e10) {
          n7.call(this, e10);
        }
        e9("../utils").inherits(i7, n7), i7.prototype.byteAt = function(e10) {
          return this.data.charCodeAt(this.zero + e10);
        }, i7.prototype.lastIndexOfSignature = function(e10) {
          return this.data.lastIndexOf(e10) - this.zero;
        }, i7.prototype.readAndCheckSignature = function(e10) {
          return e10 === this.readData(4);
        }, i7.prototype.readData = function(e10) {
          this.checkOffset(e10);
          var t7 = this.data.slice(this.zero + this.index, this.zero + this.index + e10);
          return this.index += e10, t7;
        }, t6.exports = i7;
      }, { "../utils": 32, "./DataReader": 18 }], 21: [function(e9, t6, r8) {
        "use strict";
        var n7 = e9("./ArrayReader");
        function i7(e10) {
          n7.call(this, e10);
        }
        e9("../utils").inherits(i7, n7), i7.prototype.readData = function(e10) {
          if (this.checkOffset(e10), 0 === e10) return new Uint8Array(0);
          var t7 = this.data.subarray(this.zero + this.index, this.zero + this.index + e10);
          return this.index += e10, t7;
        }, t6.exports = i7;
      }, { "../utils": 32, "./ArrayReader": 17 }], 22: [function(e9, t6, r8) {
        "use strict";
        var n7 = e9("../utils"), i7 = e9("../support"), s6 = e9("./ArrayReader"), a3 = e9("./StringReader"), o9 = e9("./NodeBufferReader"), h7 = e9("./Uint8ArrayReader");
        t6.exports = function(e10) {
          var t7 = n7.getTypeOf(e10);
          return n7.checkSupport(t7), "string" !== t7 || i7.uint8array ? "nodebuffer" === t7 ? new o9(e10) : i7.uint8array ? new h7(n7.transformTo("uint8array", e10)) : new s6(n7.transformTo("array", e10)) : new a3(e10);
        };
      }, { "../support": 30, "../utils": 32, "./ArrayReader": 17, "./NodeBufferReader": 19, "./StringReader": 20, "./Uint8ArrayReader": 21 }], 23: [function(e9, t6, r8) {
        "use strict";
        r8.LOCAL_FILE_HEADER = "PK", r8.CENTRAL_FILE_HEADER = "PK", r8.CENTRAL_DIRECTORY_END = "PK", r8.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x07", r8.ZIP64_CENTRAL_DIRECTORY_END = "PK", r8.DATA_DESCRIPTOR = "PK\x07\b";
      }, {}], 24: [function(e9, t6, r8) {
        "use strict";
        var n7 = e9("./GenericWorker"), i7 = e9("../utils");
        function s6(e10) {
          n7.call(this, "ConvertWorker to " + e10), this.destType = e10;
        }
        i7.inherits(s6, n7), s6.prototype.processChunk = function(e10) {
          this.push({ data: i7.transformTo(this.destType, e10.data), meta: e10.meta });
        }, t6.exports = s6;
      }, { "../utils": 32, "./GenericWorker": 28 }], 25: [function(e9, t6, r8) {
        "use strict";
        var n7 = e9("./GenericWorker"), i7 = e9("../crc32");
        function s6() {
          n7.call(this, "Crc32Probe"), this.withStreamInfo("crc32", 0);
        }
        e9("../utils").inherits(s6, n7), s6.prototype.processChunk = function(e10) {
          this.streamInfo.crc32 = i7(e10.data, this.streamInfo.crc32 || 0), this.push(e10);
        }, t6.exports = s6;
      }, { "../crc32": 4, "../utils": 32, "./GenericWorker": 28 }], 26: [function(e9, t6, r8) {
        "use strict";
        var n7 = e9("../utils"), i7 = e9("./GenericWorker");
        function s6(e10) {
          i7.call(this, "DataLengthProbe for " + e10), this.propName = e10, this.withStreamInfo(e10, 0);
        }
        n7.inherits(s6, i7), s6.prototype.processChunk = function(e10) {
          if (e10) {
            var t7 = this.streamInfo[this.propName] || 0;
            this.streamInfo[this.propName] = t7 + e10.data.length;
          }
          i7.prototype.processChunk.call(this, e10);
        }, t6.exports = s6;
      }, { "../utils": 32, "./GenericWorker": 28 }], 27: [function(e9, t6, r8) {
        "use strict";
        var n7 = e9("../utils"), i7 = e9("./GenericWorker");
        function s6(e10) {
          i7.call(this, "DataWorker");
          var t7 = this;
          this.dataIsReady = false, this.index = 0, this.max = 0, this.data = null, this.type = "", this._tickScheduled = false, e10.then(function(e11) {
            t7.dataIsReady = true, t7.data = e11, t7.max = e11 && e11.length || 0, t7.type = n7.getTypeOf(e11), t7.isPaused || t7._tickAndRepeat();
          }, function(e11) {
            t7.error(e11);
          });
        }
        n7.inherits(s6, i7), s6.prototype.cleanUp = function() {
          i7.prototype.cleanUp.call(this), this.data = null;
        }, s6.prototype.resume = function() {
          return !!i7.prototype.resume.call(this) && (!this._tickScheduled && this.dataIsReady && (this._tickScheduled = true, n7.delay(this._tickAndRepeat, [], this)), true);
        }, s6.prototype._tickAndRepeat = function() {
          this._tickScheduled = false, this.isPaused || this.isFinished || (this._tick(), this.isFinished || (n7.delay(this._tickAndRepeat, [], this), this._tickScheduled = true));
        }, s6.prototype._tick = function() {
          if (this.isPaused || this.isFinished) return false;
          var e10 = null, t7 = Math.min(this.max, this.index + 16384);
          if (this.index >= this.max) return this.end();
          switch (this.type) {
            case "string":
              e10 = this.data.substring(this.index, t7);
              break;
            case "uint8array":
              e10 = this.data.subarray(this.index, t7);
              break;
            case "array":
            case "nodebuffer":
              e10 = this.data.slice(this.index, t7);
          }
          return this.index = t7, this.push({ data: e10, meta: { percent: this.max ? this.index / this.max * 100 : 0 } });
        }, t6.exports = s6;
      }, { "../utils": 32, "./GenericWorker": 28 }], 28: [function(e9, t6, r8) {
        "use strict";
        function n7(e10) {
          this.name = e10 || "default", this.streamInfo = {}, this.generatedError = null, this.extraStreamInfo = {}, this.isPaused = true, this.isFinished = false, this.isLocked = false, this._listeners = { data: [], end: [], error: [] }, this.previous = null;
        }
        n7.prototype = { push: function(e10) {
          this.emit("data", e10);
        }, end: function() {
          if (this.isFinished) return false;
          this.flush();
          try {
            this.emit("end"), this.cleanUp(), this.isFinished = true;
          } catch (e10) {
            this.emit("error", e10);
          }
          return true;
        }, error: function(e10) {
          return !this.isFinished && (this.isPaused ? this.generatedError = e10 : (this.isFinished = true, this.emit("error", e10), this.previous && this.previous.error(e10), this.cleanUp()), true);
        }, on: function(e10, t7) {
          return this._listeners[e10].push(t7), this;
        }, cleanUp: function() {
          this.streamInfo = this.generatedError = this.extraStreamInfo = null, this._listeners = [];
        }, emit: function(e10, t7) {
          if (this._listeners[e10]) for (var r9 = 0; r9 < this._listeners[e10].length; r9++) this._listeners[e10][r9].call(this, t7);
        }, pipe: function(e10) {
          return e10.registerPrevious(this);
        }, registerPrevious: function(e10) {
          if (this.isLocked) throw new Error("The stream '" + this + "' has already been used.");
          this.streamInfo = e10.streamInfo, this.mergeStreamInfo(), this.previous = e10;
          var t7 = this;
          return e10.on("data", function(e11) {
            t7.processChunk(e11);
          }), e10.on("end", function() {
            t7.end();
          }), e10.on("error", function(e11) {
            t7.error(e11);
          }), this;
        }, pause: function() {
          return !this.isPaused && !this.isFinished && (this.isPaused = true, this.previous && this.previous.pause(), true);
        }, resume: function() {
          if (!this.isPaused || this.isFinished) return false;
          var e10 = this.isPaused = false;
          return this.generatedError && (this.error(this.generatedError), e10 = true), this.previous && this.previous.resume(), !e10;
        }, flush: function() {
        }, processChunk: function(e10) {
          this.push(e10);
        }, withStreamInfo: function(e10, t7) {
          return this.extraStreamInfo[e10] = t7, this.mergeStreamInfo(), this;
        }, mergeStreamInfo: function() {
          for (var e10 in this.extraStreamInfo) Object.prototype.hasOwnProperty.call(this.extraStreamInfo, e10) && (this.streamInfo[e10] = this.extraStreamInfo[e10]);
        }, lock: function() {
          if (this.isLocked) throw new Error("The stream '" + this + "' has already been used.");
          this.isLocked = true, this.previous && this.previous.lock();
        }, toString: function() {
          var e10 = "Worker " + this.name;
          return this.previous ? this.previous + " -> " + e10 : e10;
        } }, t6.exports = n7;
      }, {}], 29: [function(e9, t6, r8) {
        "use strict";
        var h7 = e9("../utils"), i7 = e9("./ConvertWorker"), s6 = e9("./GenericWorker"), u5 = e9("../base64"), n7 = e9("../support"), a3 = e9("../external"), o9 = null;
        if (n7.nodestream) try {
          o9 = e9("../nodejs/NodejsStreamOutputAdapter");
        } catch (e10) {
        }
        function l5(e10, o10) {
          return new a3.Promise(function(t7, r9) {
            var n8 = [], i8 = e10._internalType, s7 = e10._outputType, a4 = e10._mimeType;
            e10.on("data", function(e11, t8) {
              n8.push(e11), o10 && o10(t8);
            }).on("error", function(e11) {
              n8 = [], r9(e11);
            }).on("end", function() {
              try {
                var e11 = (function(e12, t8, r10) {
                  switch (e12) {
                    case "blob":
                      return h7.newBlob(h7.transformTo("arraybuffer", t8), r10);
                    case "base64":
                      return u5.encode(t8);
                    default:
                      return h7.transformTo(e12, t8);
                  }
                })(s7, (function(e12, t8) {
                  var r10, n9 = 0, i9 = null, s8 = 0;
                  for (r10 = 0; r10 < t8.length; r10++) s8 += t8[r10].length;
                  switch (e12) {
                    case "string":
                      return t8.join("");
                    case "array":
                      return Array.prototype.concat.apply([], t8);
                    case "uint8array":
                      for (i9 = new Uint8Array(s8), r10 = 0; r10 < t8.length; r10++) i9.set(t8[r10], n9), n9 += t8[r10].length;
                      return i9;
                    case "nodebuffer":
                      return Buffer.concat(t8);
                    default:
                      throw new Error("concat : unsupported type '" + e12 + "'");
                  }
                })(i8, n8), a4);
                t7(e11);
              } catch (e12) {
                r9(e12);
              }
              n8 = [];
            }).resume();
          });
        }
        function f4(e10, t7, r9) {
          var n8 = t7;
          switch (t7) {
            case "blob":
            case "arraybuffer":
              n8 = "uint8array";
              break;
            case "base64":
              n8 = "string";
          }
          try {
            this._internalType = n8, this._outputType = t7, this._mimeType = r9, h7.checkSupport(n8), this._worker = e10.pipe(new i7(n8)), e10.lock();
          } catch (e11) {
            this._worker = new s6("error"), this._worker.error(e11);
          }
        }
        f4.prototype = { accumulate: function(e10) {
          return l5(this, e10);
        }, on: function(e10, t7) {
          var r9 = this;
          return "data" === e10 ? this._worker.on(e10, function(e11) {
            t7.call(r9, e11.data, e11.meta);
          }) : this._worker.on(e10, function() {
            h7.delay(t7, arguments, r9);
          }), this;
        }, resume: function() {
          return h7.delay(this._worker.resume, [], this._worker), this;
        }, pause: function() {
          return this._worker.pause(), this;
        }, toNodejsStream: function(e10) {
          if (h7.checkSupport("nodestream"), "nodebuffer" !== this._outputType) throw new Error(this._outputType + " is not supported by this method");
          return new o9(this, { objectMode: "nodebuffer" !== this._outputType }, e10);
        } }, t6.exports = f4;
      }, { "../base64": 1, "../external": 6, "../nodejs/NodejsStreamOutputAdapter": 13, "../support": 30, "../utils": 32, "./ConvertWorker": 24, "./GenericWorker": 28 }], 30: [function(e9, t6, r8) {
        "use strict";
        if (r8.base64 = true, r8.array = true, r8.string = true, r8.arraybuffer = "undefined" != typeof ArrayBuffer && "undefined" != typeof Uint8Array, r8.nodebuffer = "undefined" != typeof Buffer, r8.uint8array = "undefined" != typeof Uint8Array, "undefined" == typeof ArrayBuffer) r8.blob = false;
        else {
          var n7 = new ArrayBuffer(0);
          try {
            r8.blob = 0 === new Blob([n7], { type: "application/zip" }).size;
          } catch (e10) {
            try {
              var i7 = new (self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder)();
              i7.append(n7), r8.blob = 0 === i7.getBlob("application/zip").size;
            } catch (e11) {
              r8.blob = false;
            }
          }
        }
        try {
          r8.nodestream = !!e9("readable-stream").Readable;
        } catch (e10) {
          r8.nodestream = false;
        }
      }, { "readable-stream": 16 }], 31: [function(e9, t6, s6) {
        "use strict";
        for (var o9 = e9("./utils"), h7 = e9("./support"), r8 = e9("./nodejsUtils"), n7 = e9("./stream/GenericWorker"), u5 = new Array(256), i7 = 0; i7 < 256; i7++) u5[i7] = 252 <= i7 ? 6 : 248 <= i7 ? 5 : 240 <= i7 ? 4 : 224 <= i7 ? 3 : 192 <= i7 ? 2 : 1;
        u5[254] = u5[254] = 1;
        function a3() {
          n7.call(this, "utf-8 decode"), this.leftOver = null;
        }
        function l5() {
          n7.call(this, "utf-8 encode");
        }
        s6.utf8encode = function(e10) {
          return h7.nodebuffer ? r8.newBufferFrom(e10, "utf-8") : (function(e11) {
            var t7, r9, n8, i8, s7, a4 = e11.length, o10 = 0;
            for (i8 = 0; i8 < a4; i8++) 55296 == (64512 & (r9 = e11.charCodeAt(i8))) && i8 + 1 < a4 && 56320 == (64512 & (n8 = e11.charCodeAt(i8 + 1))) && (r9 = 65536 + (r9 - 55296 << 10) + (n8 - 56320), i8++), o10 += r9 < 128 ? 1 : r9 < 2048 ? 2 : r9 < 65536 ? 3 : 4;
            for (t7 = h7.uint8array ? new Uint8Array(o10) : new Array(o10), i8 = s7 = 0; s7 < o10; i8++) 55296 == (64512 & (r9 = e11.charCodeAt(i8))) && i8 + 1 < a4 && 56320 == (64512 & (n8 = e11.charCodeAt(i8 + 1))) && (r9 = 65536 + (r9 - 55296 << 10) + (n8 - 56320), i8++), r9 < 128 ? t7[s7++] = r9 : (r9 < 2048 ? t7[s7++] = 192 | r9 >>> 6 : (r9 < 65536 ? t7[s7++] = 224 | r9 >>> 12 : (t7[s7++] = 240 | r9 >>> 18, t7[s7++] = 128 | r9 >>> 12 & 63), t7[s7++] = 128 | r9 >>> 6 & 63), t7[s7++] = 128 | 63 & r9);
            return t7;
          })(e10);
        }, s6.utf8decode = function(e10) {
          return h7.nodebuffer ? o9.transformTo("nodebuffer", e10).toString("utf-8") : (function(e11) {
            var t7, r9, n8, i8, s7 = e11.length, a4 = new Array(2 * s7);
            for (t7 = r9 = 0; t7 < s7; ) if ((n8 = e11[t7++]) < 128) a4[r9++] = n8;
            else if (4 < (i8 = u5[n8])) a4[r9++] = 65533, t7 += i8 - 1;
            else {
              for (n8 &= 2 === i8 ? 31 : 3 === i8 ? 15 : 7; 1 < i8 && t7 < s7; ) n8 = n8 << 6 | 63 & e11[t7++], i8--;
              1 < i8 ? a4[r9++] = 65533 : n8 < 65536 ? a4[r9++] = n8 : (n8 -= 65536, a4[r9++] = 55296 | n8 >> 10 & 1023, a4[r9++] = 56320 | 1023 & n8);
            }
            return a4.length !== r9 && (a4.subarray ? a4 = a4.subarray(0, r9) : a4.length = r9), o9.applyFromCharCode(a4);
          })(e10 = o9.transformTo(h7.uint8array ? "uint8array" : "array", e10));
        }, o9.inherits(a3, n7), a3.prototype.processChunk = function(e10) {
          var t7 = o9.transformTo(h7.uint8array ? "uint8array" : "array", e10.data);
          if (this.leftOver && this.leftOver.length) {
            if (h7.uint8array) {
              var r9 = t7;
              (t7 = new Uint8Array(r9.length + this.leftOver.length)).set(this.leftOver, 0), t7.set(r9, this.leftOver.length);
            } else t7 = this.leftOver.concat(t7);
            this.leftOver = null;
          }
          var n8 = (function(e11, t8) {
            var r10;
            for ((t8 = t8 || e11.length) > e11.length && (t8 = e11.length), r10 = t8 - 1; 0 <= r10 && 128 == (192 & e11[r10]); ) r10--;
            return r10 < 0 ? t8 : 0 === r10 ? t8 : r10 + u5[e11[r10]] > t8 ? r10 : t8;
          })(t7), i8 = t7;
          n8 !== t7.length && (h7.uint8array ? (i8 = t7.subarray(0, n8), this.leftOver = t7.subarray(n8, t7.length)) : (i8 = t7.slice(0, n8), this.leftOver = t7.slice(n8, t7.length))), this.push({ data: s6.utf8decode(i8), meta: e10.meta });
        }, a3.prototype.flush = function() {
          this.leftOver && this.leftOver.length && (this.push({ data: s6.utf8decode(this.leftOver), meta: {} }), this.leftOver = null);
        }, s6.Utf8DecodeWorker = a3, o9.inherits(l5, n7), l5.prototype.processChunk = function(e10) {
          this.push({ data: s6.utf8encode(e10.data), meta: e10.meta });
        }, s6.Utf8EncodeWorker = l5;
      }, { "./nodejsUtils": 14, "./stream/GenericWorker": 28, "./support": 30, "./utils": 32 }], 32: [function(e9, t6, a3) {
        "use strict";
        var o9 = e9("./support"), h7 = e9("./base64"), r8 = e9("./nodejsUtils"), u5 = e9("./external");
        function n7(e10) {
          return e10;
        }
        function l5(e10, t7) {
          for (var r9 = 0; r9 < e10.length; ++r9) t7[r9] = 255 & e10.charCodeAt(r9);
          return t7;
        }
        e9("setimmediate"), a3.newBlob = function(t7, r9) {
          a3.checkSupport("blob");
          try {
            return new Blob([t7], { type: r9 });
          } catch (e10) {
            try {
              var n8 = new (self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder)();
              return n8.append(t7), n8.getBlob(r9);
            } catch (e11) {
              throw new Error("Bug : can't construct the Blob.");
            }
          }
        };
        var i7 = { stringifyByChunk: function(e10, t7, r9) {
          var n8 = [], i8 = 0, s7 = e10.length;
          if (s7 <= r9) return String.fromCharCode.apply(null, e10);
          for (; i8 < s7; ) "array" === t7 || "nodebuffer" === t7 ? n8.push(String.fromCharCode.apply(null, e10.slice(i8, Math.min(i8 + r9, s7)))) : n8.push(String.fromCharCode.apply(null, e10.subarray(i8, Math.min(i8 + r9, s7)))), i8 += r9;
          return n8.join("");
        }, stringifyByChar: function(e10) {
          for (var t7 = "", r9 = 0; r9 < e10.length; r9++) t7 += String.fromCharCode(e10[r9]);
          return t7;
        }, applyCanBeUsed: { uint8array: (function() {
          try {
            return o9.uint8array && 1 === String.fromCharCode.apply(null, new Uint8Array(1)).length;
          } catch (e10) {
            return false;
          }
        })(), nodebuffer: (function() {
          try {
            return o9.nodebuffer && 1 === String.fromCharCode.apply(null, r8.allocBuffer(1)).length;
          } catch (e10) {
            return false;
          }
        })() } };
        function s6(e10) {
          var t7 = 65536, r9 = a3.getTypeOf(e10), n8 = true;
          if ("uint8array" === r9 ? n8 = i7.applyCanBeUsed.uint8array : "nodebuffer" === r9 && (n8 = i7.applyCanBeUsed.nodebuffer), n8) for (; 1 < t7; ) try {
            return i7.stringifyByChunk(e10, r9, t7);
          } catch (e11) {
            t7 = Math.floor(t7 / 2);
          }
          return i7.stringifyByChar(e10);
        }
        function f4(e10, t7) {
          for (var r9 = 0; r9 < e10.length; r9++) t7[r9] = e10[r9];
          return t7;
        }
        a3.applyFromCharCode = s6;
        var c6 = {};
        c6.string = { string: n7, array: function(e10) {
          return l5(e10, new Array(e10.length));
        }, arraybuffer: function(e10) {
          return c6.string.uint8array(e10).buffer;
        }, uint8array: function(e10) {
          return l5(e10, new Uint8Array(e10.length));
        }, nodebuffer: function(e10) {
          return l5(e10, r8.allocBuffer(e10.length));
        } }, c6.array = { string: s6, array: n7, arraybuffer: function(e10) {
          return new Uint8Array(e10).buffer;
        }, uint8array: function(e10) {
          return new Uint8Array(e10);
        }, nodebuffer: function(e10) {
          return r8.newBufferFrom(e10);
        } }, c6.arraybuffer = { string: function(e10) {
          return s6(new Uint8Array(e10));
        }, array: function(e10) {
          return f4(new Uint8Array(e10), new Array(e10.byteLength));
        }, arraybuffer: n7, uint8array: function(e10) {
          return new Uint8Array(e10);
        }, nodebuffer: function(e10) {
          return r8.newBufferFrom(new Uint8Array(e10));
        } }, c6.uint8array = { string: s6, array: function(e10) {
          return f4(e10, new Array(e10.length));
        }, arraybuffer: function(e10) {
          return e10.buffer;
        }, uint8array: n7, nodebuffer: function(e10) {
          return r8.newBufferFrom(e10);
        } }, c6.nodebuffer = { string: s6, array: function(e10) {
          return f4(e10, new Array(e10.length));
        }, arraybuffer: function(e10) {
          return c6.nodebuffer.uint8array(e10).buffer;
        }, uint8array: function(e10) {
          return f4(e10, new Uint8Array(e10.length));
        }, nodebuffer: n7 }, a3.transformTo = function(e10, t7) {
          if (t7 = t7 || "", !e10) return t7;
          a3.checkSupport(e10);
          var r9 = a3.getTypeOf(t7);
          return c6[r9][e10](t7);
        }, a3.resolve = function(e10) {
          for (var t7 = e10.split("/"), r9 = [], n8 = 0; n8 < t7.length; n8++) {
            var i8 = t7[n8];
            "." === i8 || "" === i8 && 0 !== n8 && n8 !== t7.length - 1 || (".." === i8 ? r9.pop() : r9.push(i8));
          }
          return r9.join("/");
        }, a3.getTypeOf = function(e10) {
          return "string" == typeof e10 ? "string" : "[object Array]" === Object.prototype.toString.call(e10) ? "array" : o9.nodebuffer && r8.isBuffer(e10) ? "nodebuffer" : o9.uint8array && e10 instanceof Uint8Array ? "uint8array" : o9.arraybuffer && e10 instanceof ArrayBuffer ? "arraybuffer" : void 0;
        }, a3.checkSupport = function(e10) {
          if (!o9[e10.toLowerCase()]) throw new Error(e10 + " is not supported by this platform");
        }, a3.MAX_VALUE_16BITS = 65535, a3.MAX_VALUE_32BITS = -1, a3.pretty = function(e10) {
          var t7, r9, n8 = "";
          for (r9 = 0; r9 < (e10 || "").length; r9++) n8 += "\\x" + ((t7 = e10.charCodeAt(r9)) < 16 ? "0" : "") + t7.toString(16).toUpperCase();
          return n8;
        }, a3.delay = function(e10, t7, r9) {
          setImmediate(function() {
            e10.apply(r9 || null, t7 || []);
          });
        }, a3.inherits = function(e10, t7) {
          function r9() {
          }
          r9.prototype = t7.prototype, e10.prototype = new r9();
        }, a3.extend = function() {
          var e10, t7, r9 = {};
          for (e10 = 0; e10 < arguments.length; e10++) for (t7 in arguments[e10]) Object.prototype.hasOwnProperty.call(arguments[e10], t7) && void 0 === r9[t7] && (r9[t7] = arguments[e10][t7]);
          return r9;
        }, a3.prepareContent = function(r9, e10, n8, i8, s7) {
          return u5.Promise.resolve(e10).then(function(n9) {
            return o9.blob && (n9 instanceof Blob || -1 !== ["[object File]", "[object Blob]"].indexOf(Object.prototype.toString.call(n9))) && "undefined" != typeof FileReader ? new u5.Promise(function(t7, r10) {
              var e11 = new FileReader();
              e11.onload = function(e12) {
                t7(e12.target.result);
              }, e11.onerror = function(e12) {
                r10(e12.target.error);
              }, e11.readAsArrayBuffer(n9);
            }) : n9;
          }).then(function(e11) {
            var t7 = a3.getTypeOf(e11);
            return t7 ? ("arraybuffer" === t7 ? e11 = a3.transformTo("uint8array", e11) : "string" === t7 && (s7 ? e11 = h7.decode(e11) : n8 && true !== i8 && (e11 = (function(e12) {
              return l5(e12, o9.uint8array ? new Uint8Array(e12.length) : new Array(e12.length));
            })(e11))), e11) : u5.Promise.reject(new Error("Can't read the data of '" + r9 + "'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?"));
          });
        };
      }, { "./base64": 1, "./external": 6, "./nodejsUtils": 14, "./support": 30, setimmediate: 54 }], 33: [function(e9, t6, r8) {
        "use strict";
        var n7 = e9("./reader/readerFor"), i7 = e9("./utils"), s6 = e9("./signature"), a3 = e9("./zipEntry"), o9 = e9("./support");
        function h7(e10) {
          this.files = [], this.loadOptions = e10;
        }
        h7.prototype = { checkSignature: function(e10) {
          if (!this.reader.readAndCheckSignature(e10)) {
            this.reader.index -= 4;
            var t7 = this.reader.readString(4);
            throw new Error("Corrupted zip or bug: unexpected signature (" + i7.pretty(t7) + ", expected " + i7.pretty(e10) + ")");
          }
        }, isSignature: function(e10, t7) {
          var r9 = this.reader.index;
          this.reader.setIndex(e10);
          var n8 = this.reader.readString(4) === t7;
          return this.reader.setIndex(r9), n8;
        }, readBlockEndOfCentral: function() {
          this.diskNumber = this.reader.readInt(2), this.diskWithCentralDirStart = this.reader.readInt(2), this.centralDirRecordsOnThisDisk = this.reader.readInt(2), this.centralDirRecords = this.reader.readInt(2), this.centralDirSize = this.reader.readInt(4), this.centralDirOffset = this.reader.readInt(4), this.zipCommentLength = this.reader.readInt(2);
          var e10 = this.reader.readData(this.zipCommentLength), t7 = o9.uint8array ? "uint8array" : "array", r9 = i7.transformTo(t7, e10);
          this.zipComment = this.loadOptions.decodeFileName(r9);
        }, readBlockZip64EndOfCentral: function() {
          this.zip64EndOfCentralSize = this.reader.readInt(8), this.reader.skip(4), this.diskNumber = this.reader.readInt(4), this.diskWithCentralDirStart = this.reader.readInt(4), this.centralDirRecordsOnThisDisk = this.reader.readInt(8), this.centralDirRecords = this.reader.readInt(8), this.centralDirSize = this.reader.readInt(8), this.centralDirOffset = this.reader.readInt(8), this.zip64ExtensibleData = {};
          for (var e10, t7, r9, n8 = this.zip64EndOfCentralSize - 44; 0 < n8; ) e10 = this.reader.readInt(2), t7 = this.reader.readInt(4), r9 = this.reader.readData(t7), this.zip64ExtensibleData[e10] = { id: e10, length: t7, value: r9 };
        }, readBlockZip64EndOfCentralLocator: function() {
          if (this.diskWithZip64CentralDirStart = this.reader.readInt(4), this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8), this.disksCount = this.reader.readInt(4), 1 < this.disksCount) throw new Error("Multi-volumes zip are not supported");
        }, readLocalFiles: function() {
          var e10, t7;
          for (e10 = 0; e10 < this.files.length; e10++) t7 = this.files[e10], this.reader.setIndex(t7.localHeaderOffset), this.checkSignature(s6.LOCAL_FILE_HEADER), t7.readLocalPart(this.reader), t7.handleUTF8(), t7.processAttributes();
        }, readCentralDir: function() {
          var e10;
          for (this.reader.setIndex(this.centralDirOffset); this.reader.readAndCheckSignature(s6.CENTRAL_FILE_HEADER); ) (e10 = new a3({ zip64: this.zip64 }, this.loadOptions)).readCentralPart(this.reader), this.files.push(e10);
          if (this.centralDirRecords !== this.files.length && 0 !== this.centralDirRecords && 0 === this.files.length) throw new Error("Corrupted zip or bug: expected " + this.centralDirRecords + " records in central dir, got " + this.files.length);
        }, readEndOfCentral: function() {
          var e10 = this.reader.lastIndexOfSignature(s6.CENTRAL_DIRECTORY_END);
          if (e10 < 0) throw !this.isSignature(0, s6.LOCAL_FILE_HEADER) ? new Error("Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html") : new Error("Corrupted zip: can't find end of central directory");
          this.reader.setIndex(e10);
          var t7 = e10;
          if (this.checkSignature(s6.CENTRAL_DIRECTORY_END), this.readBlockEndOfCentral(), this.diskNumber === i7.MAX_VALUE_16BITS || this.diskWithCentralDirStart === i7.MAX_VALUE_16BITS || this.centralDirRecordsOnThisDisk === i7.MAX_VALUE_16BITS || this.centralDirRecords === i7.MAX_VALUE_16BITS || this.centralDirSize === i7.MAX_VALUE_32BITS || this.centralDirOffset === i7.MAX_VALUE_32BITS) {
            if (this.zip64 = true, (e10 = this.reader.lastIndexOfSignature(s6.ZIP64_CENTRAL_DIRECTORY_LOCATOR)) < 0) throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");
            if (this.reader.setIndex(e10), this.checkSignature(s6.ZIP64_CENTRAL_DIRECTORY_LOCATOR), this.readBlockZip64EndOfCentralLocator(), !this.isSignature(this.relativeOffsetEndOfZip64CentralDir, s6.ZIP64_CENTRAL_DIRECTORY_END) && (this.relativeOffsetEndOfZip64CentralDir = this.reader.lastIndexOfSignature(s6.ZIP64_CENTRAL_DIRECTORY_END), this.relativeOffsetEndOfZip64CentralDir < 0)) throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");
            this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir), this.checkSignature(s6.ZIP64_CENTRAL_DIRECTORY_END), this.readBlockZip64EndOfCentral();
          }
          var r9 = this.centralDirOffset + this.centralDirSize;
          this.zip64 && (r9 += 20, r9 += 12 + this.zip64EndOfCentralSize);
          var n8 = t7 - r9;
          if (0 < n8) this.isSignature(t7, s6.CENTRAL_FILE_HEADER) || (this.reader.zero = n8);
          else if (n8 < 0) throw new Error("Corrupted zip: missing " + Math.abs(n8) + " bytes.");
        }, prepareReader: function(e10) {
          this.reader = n7(e10);
        }, load: function(e10) {
          this.prepareReader(e10), this.readEndOfCentral(), this.readCentralDir(), this.readLocalFiles();
        } }, t6.exports = h7;
      }, { "./reader/readerFor": 22, "./signature": 23, "./support": 30, "./utils": 32, "./zipEntry": 34 }], 34: [function(e9, t6, r8) {
        "use strict";
        var n7 = e9("./reader/readerFor"), s6 = e9("./utils"), i7 = e9("./compressedObject"), a3 = e9("./crc32"), o9 = e9("./utf8"), h7 = e9("./compressions"), u5 = e9("./support");
        function l5(e10, t7) {
          this.options = e10, this.loadOptions = t7;
        }
        l5.prototype = { isEncrypted: function() {
          return 1 == (1 & this.bitFlag);
        }, useUTF8: function() {
          return 2048 == (2048 & this.bitFlag);
        }, readLocalPart: function(e10) {
          var t7, r9;
          if (e10.skip(22), this.fileNameLength = e10.readInt(2), r9 = e10.readInt(2), this.fileName = e10.readData(this.fileNameLength), e10.skip(r9), -1 === this.compressedSize || -1 === this.uncompressedSize) throw new Error("Bug or corrupted zip : didn't get enough information from the central directory (compressedSize === -1 || uncompressedSize === -1)");
          if (null === (t7 = (function(e11) {
            for (var t8 in h7) if (Object.prototype.hasOwnProperty.call(h7, t8) && h7[t8].magic === e11) return h7[t8];
            return null;
          })(this.compressionMethod))) throw new Error("Corrupted zip : compression " + s6.pretty(this.compressionMethod) + " unknown (inner file : " + s6.transformTo("string", this.fileName) + ")");
          this.decompressed = new i7(this.compressedSize, this.uncompressedSize, this.crc32, t7, e10.readData(this.compressedSize));
        }, readCentralPart: function(e10) {
          this.versionMadeBy = e10.readInt(2), e10.skip(2), this.bitFlag = e10.readInt(2), this.compressionMethod = e10.readString(2), this.date = e10.readDate(), this.crc32 = e10.readInt(4), this.compressedSize = e10.readInt(4), this.uncompressedSize = e10.readInt(4);
          var t7 = e10.readInt(2);
          if (this.extraFieldsLength = e10.readInt(2), this.fileCommentLength = e10.readInt(2), this.diskNumberStart = e10.readInt(2), this.internalFileAttributes = e10.readInt(2), this.externalFileAttributes = e10.readInt(4), this.localHeaderOffset = e10.readInt(4), this.isEncrypted()) throw new Error("Encrypted zip are not supported");
          e10.skip(t7), this.readExtraFields(e10), this.parseZIP64ExtraField(e10), this.fileComment = e10.readData(this.fileCommentLength);
        }, processAttributes: function() {
          this.unixPermissions = null, this.dosPermissions = null;
          var e10 = this.versionMadeBy >> 8;
          this.dir = !!(16 & this.externalFileAttributes), 0 == e10 && (this.dosPermissions = 63 & this.externalFileAttributes), 3 == e10 && (this.unixPermissions = this.externalFileAttributes >> 16 & 65535), this.dir || "/" !== this.fileNameStr.slice(-1) || (this.dir = true);
        }, parseZIP64ExtraField: function() {
          if (this.extraFields[1]) {
            var e10 = n7(this.extraFields[1].value);
            this.uncompressedSize === s6.MAX_VALUE_32BITS && (this.uncompressedSize = e10.readInt(8)), this.compressedSize === s6.MAX_VALUE_32BITS && (this.compressedSize = e10.readInt(8)), this.localHeaderOffset === s6.MAX_VALUE_32BITS && (this.localHeaderOffset = e10.readInt(8)), this.diskNumberStart === s6.MAX_VALUE_32BITS && (this.diskNumberStart = e10.readInt(4));
          }
        }, readExtraFields: function(e10) {
          var t7, r9, n8, i8 = e10.index + this.extraFieldsLength;
          for (this.extraFields || (this.extraFields = {}); e10.index + 4 < i8; ) t7 = e10.readInt(2), r9 = e10.readInt(2), n8 = e10.readData(r9), this.extraFields[t7] = { id: t7, length: r9, value: n8 };
          e10.setIndex(i8);
        }, handleUTF8: function() {
          var e10 = u5.uint8array ? "uint8array" : "array";
          if (this.useUTF8()) this.fileNameStr = o9.utf8decode(this.fileName), this.fileCommentStr = o9.utf8decode(this.fileComment);
          else {
            var t7 = this.findExtraFieldUnicodePath();
            if (null !== t7) this.fileNameStr = t7;
            else {
              var r9 = s6.transformTo(e10, this.fileName);
              this.fileNameStr = this.loadOptions.decodeFileName(r9);
            }
            var n8 = this.findExtraFieldUnicodeComment();
            if (null !== n8) this.fileCommentStr = n8;
            else {
              var i8 = s6.transformTo(e10, this.fileComment);
              this.fileCommentStr = this.loadOptions.decodeFileName(i8);
            }
          }
        }, findExtraFieldUnicodePath: function() {
          var e10 = this.extraFields[28789];
          if (e10) {
            var t7 = n7(e10.value);
            return 1 !== t7.readInt(1) ? null : a3(this.fileName) !== t7.readInt(4) ? null : o9.utf8decode(t7.readData(e10.length - 5));
          }
          return null;
        }, findExtraFieldUnicodeComment: function() {
          var e10 = this.extraFields[25461];
          if (e10) {
            var t7 = n7(e10.value);
            return 1 !== t7.readInt(1) ? null : a3(this.fileComment) !== t7.readInt(4) ? null : o9.utf8decode(t7.readData(e10.length - 5));
          }
          return null;
        } }, t6.exports = l5;
      }, { "./compressedObject": 2, "./compressions": 3, "./crc32": 4, "./reader/readerFor": 22, "./support": 30, "./utf8": 31, "./utils": 32 }], 35: [function(e9, t6, r8) {
        "use strict";
        function n7(e10, t7, r9) {
          this.name = e10, this.dir = r9.dir, this.date = r9.date, this.comment = r9.comment, this.unixPermissions = r9.unixPermissions, this.dosPermissions = r9.dosPermissions, this._data = t7, this._dataBinary = r9.binary, this.options = { compression: r9.compression, compressionOptions: r9.compressionOptions };
        }
        var s6 = e9("./stream/StreamHelper"), i7 = e9("./stream/DataWorker"), a3 = e9("./utf8"), o9 = e9("./compressedObject"), h7 = e9("./stream/GenericWorker");
        n7.prototype = { internalStream: function(e10) {
          var t7 = null, r9 = "string";
          try {
            if (!e10) throw new Error("No output type specified.");
            var n8 = "string" === (r9 = e10.toLowerCase()) || "text" === r9;
            "binarystring" !== r9 && "text" !== r9 || (r9 = "string"), t7 = this._decompressWorker();
            var i8 = !this._dataBinary;
            i8 && !n8 && (t7 = t7.pipe(new a3.Utf8EncodeWorker())), !i8 && n8 && (t7 = t7.pipe(new a3.Utf8DecodeWorker()));
          } catch (e11) {
            (t7 = new h7("error")).error(e11);
          }
          return new s6(t7, r9, "");
        }, async: function(e10, t7) {
          return this.internalStream(e10).accumulate(t7);
        }, nodeStream: function(e10, t7) {
          return this.internalStream(e10 || "nodebuffer").toNodejsStream(t7);
        }, _compressWorker: function(e10, t7) {
          if (this._data instanceof o9 && this._data.compression.magic === e10.magic) return this._data.getCompressedWorker();
          var r9 = this._decompressWorker();
          return this._dataBinary || (r9 = r9.pipe(new a3.Utf8EncodeWorker())), o9.createWorkerFrom(r9, e10, t7);
        }, _decompressWorker: function() {
          return this._data instanceof o9 ? this._data.getContentWorker() : this._data instanceof h7 ? this._data : new i7(this._data);
        } };
        for (var u5 = ["asText", "asBinary", "asNodeBuffer", "asUint8Array", "asArrayBuffer"], l5 = function() {
          throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
        }, f4 = 0; f4 < u5.length; f4++) n7.prototype[u5[f4]] = l5;
        t6.exports = n7;
      }, { "./compressedObject": 2, "./stream/DataWorker": 27, "./stream/GenericWorker": 28, "./stream/StreamHelper": 29, "./utf8": 31 }], 36: [function(e9, l5, t6) {
        (function(t7) {
          "use strict";
          var r8, n7, e10 = t7.MutationObserver || t7.WebKitMutationObserver;
          if (e10) {
            var i7 = 0, s6 = new e10(u5), a3 = t7.document.createTextNode("");
            s6.observe(a3, { characterData: true }), r8 = function() {
              a3.data = i7 = ++i7 % 2;
            };
          } else if (t7.setImmediate || void 0 === t7.MessageChannel) r8 = "document" in t7 && "onreadystatechange" in t7.document.createElement("script") ? function() {
            var e11 = t7.document.createElement("script");
            e11.onreadystatechange = function() {
              u5(), e11.onreadystatechange = null, e11.parentNode.removeChild(e11), e11 = null;
            }, t7.document.documentElement.appendChild(e11);
          } : function() {
            setTimeout(u5, 0);
          };
          else {
            var o9 = new t7.MessageChannel();
            o9.port1.onmessage = u5, r8 = function() {
              o9.port2.postMessage(0);
            };
          }
          var h7 = [];
          function u5() {
            var e11, t8;
            n7 = true;
            for (var r9 = h7.length; r9; ) {
              for (t8 = h7, h7 = [], e11 = -1; ++e11 < r9; ) t8[e11]();
              r9 = h7.length;
            }
            n7 = false;
          }
          l5.exports = function(e11) {
            1 !== h7.push(e11) || n7 || r8();
          };
        }).call(this, "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : "undefined" != typeof window ? window : {});
      }, {}], 37: [function(e9, t6, r8) {
        "use strict";
        var i7 = e9("immediate");
        function u5() {
        }
        var l5 = {}, s6 = ["REJECTED"], a3 = ["FULFILLED"], n7 = ["PENDING"];
        function o9(e10) {
          if ("function" != typeof e10) throw new TypeError("resolver must be a function");
          this.state = n7, this.queue = [], this.outcome = void 0, e10 !== u5 && d4(this, e10);
        }
        function h7(e10, t7, r9) {
          this.promise = e10, "function" == typeof t7 && (this.onFulfilled = t7, this.callFulfilled = this.otherCallFulfilled), "function" == typeof r9 && (this.onRejected = r9, this.callRejected = this.otherCallRejected);
        }
        function f4(t7, r9, n8) {
          i7(function() {
            var e10;
            try {
              e10 = r9(n8);
            } catch (e11) {
              return l5.reject(t7, e11);
            }
            e10 === t7 ? l5.reject(t7, new TypeError("Cannot resolve promise with itself")) : l5.resolve(t7, e10);
          });
        }
        function c6(e10) {
          var t7 = e10 && e10.then;
          if (e10 && ("object" == typeof e10 || "function" == typeof e10) && "function" == typeof t7) return function() {
            t7.apply(e10, arguments);
          };
        }
        function d4(t7, e10) {
          var r9 = false;
          function n8(e11) {
            r9 || (r9 = true, l5.reject(t7, e11));
          }
          function i8(e11) {
            r9 || (r9 = true, l5.resolve(t7, e11));
          }
          var s7 = p4(function() {
            e10(i8, n8);
          });
          "error" === s7.status && n8(s7.value);
        }
        function p4(e10, t7) {
          var r9 = {};
          try {
            r9.value = e10(t7), r9.status = "success";
          } catch (e11) {
            r9.status = "error", r9.value = e11;
          }
          return r9;
        }
        (t6.exports = o9).prototype.finally = function(t7) {
          if ("function" != typeof t7) return this;
          var r9 = this.constructor;
          return this.then(function(e10) {
            return r9.resolve(t7()).then(function() {
              return e10;
            });
          }, function(e10) {
            return r9.resolve(t7()).then(function() {
              throw e10;
            });
          });
        }, o9.prototype.catch = function(e10) {
          return this.then(null, e10);
        }, o9.prototype.then = function(e10, t7) {
          if ("function" != typeof e10 && this.state === a3 || "function" != typeof t7 && this.state === s6) return this;
          var r9 = new this.constructor(u5);
          this.state !== n7 ? f4(r9, this.state === a3 ? e10 : t7, this.outcome) : this.queue.push(new h7(r9, e10, t7));
          return r9;
        }, h7.prototype.callFulfilled = function(e10) {
          l5.resolve(this.promise, e10);
        }, h7.prototype.otherCallFulfilled = function(e10) {
          f4(this.promise, this.onFulfilled, e10);
        }, h7.prototype.callRejected = function(e10) {
          l5.reject(this.promise, e10);
        }, h7.prototype.otherCallRejected = function(e10) {
          f4(this.promise, this.onRejected, e10);
        }, l5.resolve = function(e10, t7) {
          var r9 = p4(c6, t7);
          if ("error" === r9.status) return l5.reject(e10, r9.value);
          var n8 = r9.value;
          if (n8) d4(e10, n8);
          else {
            e10.state = a3, e10.outcome = t7;
            for (var i8 = -1, s7 = e10.queue.length; ++i8 < s7; ) e10.queue[i8].callFulfilled(t7);
          }
          return e10;
        }, l5.reject = function(e10, t7) {
          e10.state = s6, e10.outcome = t7;
          for (var r9 = -1, n8 = e10.queue.length; ++r9 < n8; ) e10.queue[r9].callRejected(t7);
          return e10;
        }, o9.resolve = function(e10) {
          if (e10 instanceof this) return e10;
          return l5.resolve(new this(u5), e10);
        }, o9.reject = function(e10) {
          var t7 = new this(u5);
          return l5.reject(t7, e10);
        }, o9.all = function(e10) {
          var r9 = this;
          if ("[object Array]" !== Object.prototype.toString.call(e10)) return this.reject(new TypeError("must be an array"));
          var n8 = e10.length, i8 = false;
          if (!n8) return this.resolve([]);
          var s7 = new Array(n8), a4 = 0, t7 = -1, o10 = new this(u5);
          for (; ++t7 < n8; ) h8(e10[t7], t7);
          return o10;
          function h8(e11, t8) {
            r9.resolve(e11).then(function(e12) {
              s7[t8] = e12, ++a4 !== n8 || i8 || (i8 = true, l5.resolve(o10, s7));
            }, function(e12) {
              i8 || (i8 = true, l5.reject(o10, e12));
            });
          }
        }, o9.race = function(e10) {
          var t7 = this;
          if ("[object Array]" !== Object.prototype.toString.call(e10)) return this.reject(new TypeError("must be an array"));
          var r9 = e10.length, n8 = false;
          if (!r9) return this.resolve([]);
          var i8 = -1, s7 = new this(u5);
          for (; ++i8 < r9; ) a4 = e10[i8], t7.resolve(a4).then(function(e11) {
            n8 || (n8 = true, l5.resolve(s7, e11));
          }, function(e11) {
            n8 || (n8 = true, l5.reject(s7, e11));
          });
          var a4;
          return s7;
        };
      }, { immediate: 36 }], 38: [function(e9, t6, r8) {
        "use strict";
        var n7 = {};
        (0, e9("./lib/utils/common").assign)(n7, e9("./lib/deflate"), e9("./lib/inflate"), e9("./lib/zlib/constants")), t6.exports = n7;
      }, { "./lib/deflate": 39, "./lib/inflate": 40, "./lib/utils/common": 41, "./lib/zlib/constants": 44 }], 39: [function(e9, t6, r8) {
        "use strict";
        var a3 = e9("./zlib/deflate"), o9 = e9("./utils/common"), h7 = e9("./utils/strings"), i7 = e9("./zlib/messages"), s6 = e9("./zlib/zstream"), u5 = Object.prototype.toString, l5 = 0, f4 = -1, c6 = 0, d4 = 8;
        function p4(e10) {
          if (!(this instanceof p4)) return new p4(e10);
          this.options = o9.assign({ level: f4, method: d4, chunkSize: 16384, windowBits: 15, memLevel: 8, strategy: c6, to: "" }, e10 || {});
          var t7 = this.options;
          t7.raw && 0 < t7.windowBits ? t7.windowBits = -t7.windowBits : t7.gzip && 0 < t7.windowBits && t7.windowBits < 16 && (t7.windowBits += 16), this.err = 0, this.msg = "", this.ended = false, this.chunks = [], this.strm = new s6(), this.strm.avail_out = 0;
          var r9 = a3.deflateInit2(this.strm, t7.level, t7.method, t7.windowBits, t7.memLevel, t7.strategy);
          if (r9 !== l5) throw new Error(i7[r9]);
          if (t7.header && a3.deflateSetHeader(this.strm, t7.header), t7.dictionary) {
            var n8;
            if (n8 = "string" == typeof t7.dictionary ? h7.string2buf(t7.dictionary) : "[object ArrayBuffer]" === u5.call(t7.dictionary) ? new Uint8Array(t7.dictionary) : t7.dictionary, (r9 = a3.deflateSetDictionary(this.strm, n8)) !== l5) throw new Error(i7[r9]);
            this._dict_set = true;
          }
        }
        function n7(e10, t7) {
          var r9 = new p4(t7);
          if (r9.push(e10, true), r9.err) throw r9.msg || i7[r9.err];
          return r9.result;
        }
        p4.prototype.push = function(e10, t7) {
          var r9, n8, i8 = this.strm, s7 = this.options.chunkSize;
          if (this.ended) return false;
          n8 = t7 === ~~t7 ? t7 : true === t7 ? 4 : 0, "string" == typeof e10 ? i8.input = h7.string2buf(e10) : "[object ArrayBuffer]" === u5.call(e10) ? i8.input = new Uint8Array(e10) : i8.input = e10, i8.next_in = 0, i8.avail_in = i8.input.length;
          do {
            if (0 === i8.avail_out && (i8.output = new o9.Buf8(s7), i8.next_out = 0, i8.avail_out = s7), 1 !== (r9 = a3.deflate(i8, n8)) && r9 !== l5) return this.onEnd(r9), !(this.ended = true);
            0 !== i8.avail_out && (0 !== i8.avail_in || 4 !== n8 && 2 !== n8) || ("string" === this.options.to ? this.onData(h7.buf2binstring(o9.shrinkBuf(i8.output, i8.next_out))) : this.onData(o9.shrinkBuf(i8.output, i8.next_out)));
          } while ((0 < i8.avail_in || 0 === i8.avail_out) && 1 !== r9);
          return 4 === n8 ? (r9 = a3.deflateEnd(this.strm), this.onEnd(r9), this.ended = true, r9 === l5) : 2 !== n8 || (this.onEnd(l5), !(i8.avail_out = 0));
        }, p4.prototype.onData = function(e10) {
          this.chunks.push(e10);
        }, p4.prototype.onEnd = function(e10) {
          e10 === l5 && ("string" === this.options.to ? this.result = this.chunks.join("") : this.result = o9.flattenChunks(this.chunks)), this.chunks = [], this.err = e10, this.msg = this.strm.msg;
        }, r8.Deflate = p4, r8.deflate = n7, r8.deflateRaw = function(e10, t7) {
          return (t7 = t7 || {}).raw = true, n7(e10, t7);
        }, r8.gzip = function(e10, t7) {
          return (t7 = t7 || {}).gzip = true, n7(e10, t7);
        };
      }, { "./utils/common": 41, "./utils/strings": 42, "./zlib/deflate": 46, "./zlib/messages": 51, "./zlib/zstream": 53 }], 40: [function(e9, t6, r8) {
        "use strict";
        var c6 = e9("./zlib/inflate"), d4 = e9("./utils/common"), p4 = e9("./utils/strings"), m4 = e9("./zlib/constants"), n7 = e9("./zlib/messages"), i7 = e9("./zlib/zstream"), s6 = e9("./zlib/gzheader"), _3 = Object.prototype.toString;
        function a3(e10) {
          if (!(this instanceof a3)) return new a3(e10);
          this.options = d4.assign({ chunkSize: 16384, windowBits: 0, to: "" }, e10 || {});
          var t7 = this.options;
          t7.raw && 0 <= t7.windowBits && t7.windowBits < 16 && (t7.windowBits = -t7.windowBits, 0 === t7.windowBits && (t7.windowBits = -15)), !(0 <= t7.windowBits && t7.windowBits < 16) || e10 && e10.windowBits || (t7.windowBits += 32), 15 < t7.windowBits && t7.windowBits < 48 && 0 == (15 & t7.windowBits) && (t7.windowBits |= 15), this.err = 0, this.msg = "", this.ended = false, this.chunks = [], this.strm = new i7(), this.strm.avail_out = 0;
          var r9 = c6.inflateInit2(this.strm, t7.windowBits);
          if (r9 !== m4.Z_OK) throw new Error(n7[r9]);
          this.header = new s6(), c6.inflateGetHeader(this.strm, this.header);
        }
        function o9(e10, t7) {
          var r9 = new a3(t7);
          if (r9.push(e10, true), r9.err) throw r9.msg || n7[r9.err];
          return r9.result;
        }
        a3.prototype.push = function(e10, t7) {
          var r9, n8, i8, s7, a4, o10, h7 = this.strm, u5 = this.options.chunkSize, l5 = this.options.dictionary, f4 = false;
          if (this.ended) return false;
          n8 = t7 === ~~t7 ? t7 : true === t7 ? m4.Z_FINISH : m4.Z_NO_FLUSH, "string" == typeof e10 ? h7.input = p4.binstring2buf(e10) : "[object ArrayBuffer]" === _3.call(e10) ? h7.input = new Uint8Array(e10) : h7.input = e10, h7.next_in = 0, h7.avail_in = h7.input.length;
          do {
            if (0 === h7.avail_out && (h7.output = new d4.Buf8(u5), h7.next_out = 0, h7.avail_out = u5), (r9 = c6.inflate(h7, m4.Z_NO_FLUSH)) === m4.Z_NEED_DICT && l5 && (o10 = "string" == typeof l5 ? p4.string2buf(l5) : "[object ArrayBuffer]" === _3.call(l5) ? new Uint8Array(l5) : l5, r9 = c6.inflateSetDictionary(this.strm, o10)), r9 === m4.Z_BUF_ERROR && true === f4 && (r9 = m4.Z_OK, f4 = false), r9 !== m4.Z_STREAM_END && r9 !== m4.Z_OK) return this.onEnd(r9), !(this.ended = true);
            h7.next_out && (0 !== h7.avail_out && r9 !== m4.Z_STREAM_END && (0 !== h7.avail_in || n8 !== m4.Z_FINISH && n8 !== m4.Z_SYNC_FLUSH) || ("string" === this.options.to ? (i8 = p4.utf8border(h7.output, h7.next_out), s7 = h7.next_out - i8, a4 = p4.buf2string(h7.output, i8), h7.next_out = s7, h7.avail_out = u5 - s7, s7 && d4.arraySet(h7.output, h7.output, i8, s7, 0), this.onData(a4)) : this.onData(d4.shrinkBuf(h7.output, h7.next_out)))), 0 === h7.avail_in && 0 === h7.avail_out && (f4 = true);
          } while ((0 < h7.avail_in || 0 === h7.avail_out) && r9 !== m4.Z_STREAM_END);
          return r9 === m4.Z_STREAM_END && (n8 = m4.Z_FINISH), n8 === m4.Z_FINISH ? (r9 = c6.inflateEnd(this.strm), this.onEnd(r9), this.ended = true, r9 === m4.Z_OK) : n8 !== m4.Z_SYNC_FLUSH || (this.onEnd(m4.Z_OK), !(h7.avail_out = 0));
        }, a3.prototype.onData = function(e10) {
          this.chunks.push(e10);
        }, a3.prototype.onEnd = function(e10) {
          e10 === m4.Z_OK && ("string" === this.options.to ? this.result = this.chunks.join("") : this.result = d4.flattenChunks(this.chunks)), this.chunks = [], this.err = e10, this.msg = this.strm.msg;
        }, r8.Inflate = a3, r8.inflate = o9, r8.inflateRaw = function(e10, t7) {
          return (t7 = t7 || {}).raw = true, o9(e10, t7);
        }, r8.ungzip = o9;
      }, { "./utils/common": 41, "./utils/strings": 42, "./zlib/constants": 44, "./zlib/gzheader": 47, "./zlib/inflate": 49, "./zlib/messages": 51, "./zlib/zstream": 53 }], 41: [function(e9, t6, r8) {
        "use strict";
        var n7 = "undefined" != typeof Uint8Array && "undefined" != typeof Uint16Array && "undefined" != typeof Int32Array;
        r8.assign = function(e10) {
          for (var t7 = Array.prototype.slice.call(arguments, 1); t7.length; ) {
            var r9 = t7.shift();
            if (r9) {
              if ("object" != typeof r9) throw new TypeError(r9 + "must be non-object");
              for (var n8 in r9) r9.hasOwnProperty(n8) && (e10[n8] = r9[n8]);
            }
          }
          return e10;
        }, r8.shrinkBuf = function(e10, t7) {
          return e10.length === t7 ? e10 : e10.subarray ? e10.subarray(0, t7) : (e10.length = t7, e10);
        };
        var i7 = { arraySet: function(e10, t7, r9, n8, i8) {
          if (t7.subarray && e10.subarray) e10.set(t7.subarray(r9, r9 + n8), i8);
          else for (var s7 = 0; s7 < n8; s7++) e10[i8 + s7] = t7[r9 + s7];
        }, flattenChunks: function(e10) {
          var t7, r9, n8, i8, s7, a3;
          for (t7 = n8 = 0, r9 = e10.length; t7 < r9; t7++) n8 += e10[t7].length;
          for (a3 = new Uint8Array(n8), t7 = i8 = 0, r9 = e10.length; t7 < r9; t7++) s7 = e10[t7], a3.set(s7, i8), i8 += s7.length;
          return a3;
        } }, s6 = { arraySet: function(e10, t7, r9, n8, i8) {
          for (var s7 = 0; s7 < n8; s7++) e10[i8 + s7] = t7[r9 + s7];
        }, flattenChunks: function(e10) {
          return [].concat.apply([], e10);
        } };
        r8.setTyped = function(e10) {
          e10 ? (r8.Buf8 = Uint8Array, r8.Buf16 = Uint16Array, r8.Buf32 = Int32Array, r8.assign(r8, i7)) : (r8.Buf8 = Array, r8.Buf16 = Array, r8.Buf32 = Array, r8.assign(r8, s6));
        }, r8.setTyped(n7);
      }, {}], 42: [function(e9, t6, r8) {
        "use strict";
        var h7 = e9("./common"), i7 = true, s6 = true;
        try {
          String.fromCharCode.apply(null, [0]);
        } catch (e10) {
          i7 = false;
        }
        try {
          String.fromCharCode.apply(null, new Uint8Array(1));
        } catch (e10) {
          s6 = false;
        }
        for (var u5 = new h7.Buf8(256), n7 = 0; n7 < 256; n7++) u5[n7] = 252 <= n7 ? 6 : 248 <= n7 ? 5 : 240 <= n7 ? 4 : 224 <= n7 ? 3 : 192 <= n7 ? 2 : 1;
        function l5(e10, t7) {
          if (t7 < 65537 && (e10.subarray && s6 || !e10.subarray && i7)) return String.fromCharCode.apply(null, h7.shrinkBuf(e10, t7));
          for (var r9 = "", n8 = 0; n8 < t7; n8++) r9 += String.fromCharCode(e10[n8]);
          return r9;
        }
        u5[254] = u5[254] = 1, r8.string2buf = function(e10) {
          var t7, r9, n8, i8, s7, a3 = e10.length, o9 = 0;
          for (i8 = 0; i8 < a3; i8++) 55296 == (64512 & (r9 = e10.charCodeAt(i8))) && i8 + 1 < a3 && 56320 == (64512 & (n8 = e10.charCodeAt(i8 + 1))) && (r9 = 65536 + (r9 - 55296 << 10) + (n8 - 56320), i8++), o9 += r9 < 128 ? 1 : r9 < 2048 ? 2 : r9 < 65536 ? 3 : 4;
          for (t7 = new h7.Buf8(o9), i8 = s7 = 0; s7 < o9; i8++) 55296 == (64512 & (r9 = e10.charCodeAt(i8))) && i8 + 1 < a3 && 56320 == (64512 & (n8 = e10.charCodeAt(i8 + 1))) && (r9 = 65536 + (r9 - 55296 << 10) + (n8 - 56320), i8++), r9 < 128 ? t7[s7++] = r9 : (r9 < 2048 ? t7[s7++] = 192 | r9 >>> 6 : (r9 < 65536 ? t7[s7++] = 224 | r9 >>> 12 : (t7[s7++] = 240 | r9 >>> 18, t7[s7++] = 128 | r9 >>> 12 & 63), t7[s7++] = 128 | r9 >>> 6 & 63), t7[s7++] = 128 | 63 & r9);
          return t7;
        }, r8.buf2binstring = function(e10) {
          return l5(e10, e10.length);
        }, r8.binstring2buf = function(e10) {
          for (var t7 = new h7.Buf8(e10.length), r9 = 0, n8 = t7.length; r9 < n8; r9++) t7[r9] = e10.charCodeAt(r9);
          return t7;
        }, r8.buf2string = function(e10, t7) {
          var r9, n8, i8, s7, a3 = t7 || e10.length, o9 = new Array(2 * a3);
          for (r9 = n8 = 0; r9 < a3; ) if ((i8 = e10[r9++]) < 128) o9[n8++] = i8;
          else if (4 < (s7 = u5[i8])) o9[n8++] = 65533, r9 += s7 - 1;
          else {
            for (i8 &= 2 === s7 ? 31 : 3 === s7 ? 15 : 7; 1 < s7 && r9 < a3; ) i8 = i8 << 6 | 63 & e10[r9++], s7--;
            1 < s7 ? o9[n8++] = 65533 : i8 < 65536 ? o9[n8++] = i8 : (i8 -= 65536, o9[n8++] = 55296 | i8 >> 10 & 1023, o9[n8++] = 56320 | 1023 & i8);
          }
          return l5(o9, n8);
        }, r8.utf8border = function(e10, t7) {
          var r9;
          for ((t7 = t7 || e10.length) > e10.length && (t7 = e10.length), r9 = t7 - 1; 0 <= r9 && 128 == (192 & e10[r9]); ) r9--;
          return r9 < 0 ? t7 : 0 === r9 ? t7 : r9 + u5[e10[r9]] > t7 ? r9 : t7;
        };
      }, { "./common": 41 }], 43: [function(e9, t6, r8) {
        "use strict";
        t6.exports = function(e10, t7, r9, n7) {
          for (var i7 = 65535 & e10 | 0, s6 = e10 >>> 16 & 65535 | 0, a3 = 0; 0 !== r9; ) {
            for (r9 -= a3 = 2e3 < r9 ? 2e3 : r9; s6 = s6 + (i7 = i7 + t7[n7++] | 0) | 0, --a3; ) ;
            i7 %= 65521, s6 %= 65521;
          }
          return i7 | s6 << 16 | 0;
        };
      }, {}], 44: [function(e9, t6, r8) {
        "use strict";
        t6.exports = { Z_NO_FLUSH: 0, Z_PARTIAL_FLUSH: 1, Z_SYNC_FLUSH: 2, Z_FULL_FLUSH: 3, Z_FINISH: 4, Z_BLOCK: 5, Z_TREES: 6, Z_OK: 0, Z_STREAM_END: 1, Z_NEED_DICT: 2, Z_ERRNO: -1, Z_STREAM_ERROR: -2, Z_DATA_ERROR: -3, Z_BUF_ERROR: -5, Z_NO_COMPRESSION: 0, Z_BEST_SPEED: 1, Z_BEST_COMPRESSION: 9, Z_DEFAULT_COMPRESSION: -1, Z_FILTERED: 1, Z_HUFFMAN_ONLY: 2, Z_RLE: 3, Z_FIXED: 4, Z_DEFAULT_STRATEGY: 0, Z_BINARY: 0, Z_TEXT: 1, Z_UNKNOWN: 2, Z_DEFLATED: 8 };
      }, {}], 45: [function(e9, t6, r8) {
        "use strict";
        var o9 = (function() {
          for (var e10, t7 = [], r9 = 0; r9 < 256; r9++) {
            e10 = r9;
            for (var n7 = 0; n7 < 8; n7++) e10 = 1 & e10 ? 3988292384 ^ e10 >>> 1 : e10 >>> 1;
            t7[r9] = e10;
          }
          return t7;
        })();
        t6.exports = function(e10, t7, r9, n7) {
          var i7 = o9, s6 = n7 + r9;
          e10 ^= -1;
          for (var a3 = n7; a3 < s6; a3++) e10 = e10 >>> 8 ^ i7[255 & (e10 ^ t7[a3])];
          return -1 ^ e10;
        };
      }, {}], 46: [function(e9, t6, r8) {
        "use strict";
        var h7, c6 = e9("../utils/common"), u5 = e9("./trees"), d4 = e9("./adler32"), p4 = e9("./crc32"), n7 = e9("./messages"), l5 = 0, f4 = 4, m4 = 0, _3 = -2, g3 = -1, b4 = 4, i7 = 2, v4 = 8, y4 = 9, s6 = 286, a3 = 30, o9 = 19, w3 = 2 * s6 + 1, k2 = 15, x2 = 3, S5 = 258, z3 = S5 + x2 + 1, C3 = 42, E3 = 113, A2 = 1, I3 = 2, O2 = 3, B3 = 4;
        function R3(e10, t7) {
          return e10.msg = n7[t7], t7;
        }
        function T3(e10) {
          return (e10 << 1) - (4 < e10 ? 9 : 0);
        }
        function D4(e10) {
          for (var t7 = e10.length; 0 <= --t7; ) e10[t7] = 0;
        }
        function F2(e10) {
          var t7 = e10.state, r9 = t7.pending;
          r9 > e10.avail_out && (r9 = e10.avail_out), 0 !== r9 && (c6.arraySet(e10.output, t7.pending_buf, t7.pending_out, r9, e10.next_out), e10.next_out += r9, t7.pending_out += r9, e10.total_out += r9, e10.avail_out -= r9, t7.pending -= r9, 0 === t7.pending && (t7.pending_out = 0));
        }
        function N3(e10, t7) {
          u5._tr_flush_block(e10, 0 <= e10.block_start ? e10.block_start : -1, e10.strstart - e10.block_start, t7), e10.block_start = e10.strstart, F2(e10.strm);
        }
        function U2(e10, t7) {
          e10.pending_buf[e10.pending++] = t7;
        }
        function P3(e10, t7) {
          e10.pending_buf[e10.pending++] = t7 >>> 8 & 255, e10.pending_buf[e10.pending++] = 255 & t7;
        }
        function L3(e10, t7) {
          var r9, n8, i8 = e10.max_chain_length, s7 = e10.strstart, a4 = e10.prev_length, o10 = e10.nice_match, h8 = e10.strstart > e10.w_size - z3 ? e10.strstart - (e10.w_size - z3) : 0, u6 = e10.window, l6 = e10.w_mask, f5 = e10.prev, c7 = e10.strstart + S5, d5 = u6[s7 + a4 - 1], p5 = u6[s7 + a4];
          e10.prev_length >= e10.good_match && (i8 >>= 2), o10 > e10.lookahead && (o10 = e10.lookahead);
          do {
            if (u6[(r9 = t7) + a4] === p5 && u6[r9 + a4 - 1] === d5 && u6[r9] === u6[s7] && u6[++r9] === u6[s7 + 1]) {
              s7 += 2, r9++;
              do {
              } while (u6[++s7] === u6[++r9] && u6[++s7] === u6[++r9] && u6[++s7] === u6[++r9] && u6[++s7] === u6[++r9] && u6[++s7] === u6[++r9] && u6[++s7] === u6[++r9] && u6[++s7] === u6[++r9] && u6[++s7] === u6[++r9] && s7 < c7);
              if (n8 = S5 - (c7 - s7), s7 = c7 - S5, a4 < n8) {
                if (e10.match_start = t7, o10 <= (a4 = n8)) break;
                d5 = u6[s7 + a4 - 1], p5 = u6[s7 + a4];
              }
            }
          } while ((t7 = f5[t7 & l6]) > h8 && 0 != --i8);
          return a4 <= e10.lookahead ? a4 : e10.lookahead;
        }
        function j3(e10) {
          var t7, r9, n8, i8, s7, a4, o10, h8, u6, l6, f5 = e10.w_size;
          do {
            if (i8 = e10.window_size - e10.lookahead - e10.strstart, e10.strstart >= f5 + (f5 - z3)) {
              for (c6.arraySet(e10.window, e10.window, f5, f5, 0), e10.match_start -= f5, e10.strstart -= f5, e10.block_start -= f5, t7 = r9 = e10.hash_size; n8 = e10.head[--t7], e10.head[t7] = f5 <= n8 ? n8 - f5 : 0, --r9; ) ;
              for (t7 = r9 = f5; n8 = e10.prev[--t7], e10.prev[t7] = f5 <= n8 ? n8 - f5 : 0, --r9; ) ;
              i8 += f5;
            }
            if (0 === e10.strm.avail_in) break;
            if (a4 = e10.strm, o10 = e10.window, h8 = e10.strstart + e10.lookahead, u6 = i8, l6 = void 0, l6 = a4.avail_in, u6 < l6 && (l6 = u6), r9 = 0 === l6 ? 0 : (a4.avail_in -= l6, c6.arraySet(o10, a4.input, a4.next_in, l6, h8), 1 === a4.state.wrap ? a4.adler = d4(a4.adler, o10, l6, h8) : 2 === a4.state.wrap && (a4.adler = p4(a4.adler, o10, l6, h8)), a4.next_in += l6, a4.total_in += l6, l6), e10.lookahead += r9, e10.lookahead + e10.insert >= x2) for (s7 = e10.strstart - e10.insert, e10.ins_h = e10.window[s7], e10.ins_h = (e10.ins_h << e10.hash_shift ^ e10.window[s7 + 1]) & e10.hash_mask; e10.insert && (e10.ins_h = (e10.ins_h << e10.hash_shift ^ e10.window[s7 + x2 - 1]) & e10.hash_mask, e10.prev[s7 & e10.w_mask] = e10.head[e10.ins_h], e10.head[e10.ins_h] = s7, s7++, e10.insert--, !(e10.lookahead + e10.insert < x2)); ) ;
          } while (e10.lookahead < z3 && 0 !== e10.strm.avail_in);
        }
        function Z2(e10, t7) {
          for (var r9, n8; ; ) {
            if (e10.lookahead < z3) {
              if (j3(e10), e10.lookahead < z3 && t7 === l5) return A2;
              if (0 === e10.lookahead) break;
            }
            if (r9 = 0, e10.lookahead >= x2 && (e10.ins_h = (e10.ins_h << e10.hash_shift ^ e10.window[e10.strstart + x2 - 1]) & e10.hash_mask, r9 = e10.prev[e10.strstart & e10.w_mask] = e10.head[e10.ins_h], e10.head[e10.ins_h] = e10.strstart), 0 !== r9 && e10.strstart - r9 <= e10.w_size - z3 && (e10.match_length = L3(e10, r9)), e10.match_length >= x2) if (n8 = u5._tr_tally(e10, e10.strstart - e10.match_start, e10.match_length - x2), e10.lookahead -= e10.match_length, e10.match_length <= e10.max_lazy_match && e10.lookahead >= x2) {
              for (e10.match_length--; e10.strstart++, e10.ins_h = (e10.ins_h << e10.hash_shift ^ e10.window[e10.strstart + x2 - 1]) & e10.hash_mask, r9 = e10.prev[e10.strstart & e10.w_mask] = e10.head[e10.ins_h], e10.head[e10.ins_h] = e10.strstart, 0 != --e10.match_length; ) ;
              e10.strstart++;
            } else e10.strstart += e10.match_length, e10.match_length = 0, e10.ins_h = e10.window[e10.strstart], e10.ins_h = (e10.ins_h << e10.hash_shift ^ e10.window[e10.strstart + 1]) & e10.hash_mask;
            else n8 = u5._tr_tally(e10, 0, e10.window[e10.strstart]), e10.lookahead--, e10.strstart++;
            if (n8 && (N3(e10, false), 0 === e10.strm.avail_out)) return A2;
          }
          return e10.insert = e10.strstart < x2 - 1 ? e10.strstart : x2 - 1, t7 === f4 ? (N3(e10, true), 0 === e10.strm.avail_out ? O2 : B3) : e10.last_lit && (N3(e10, false), 0 === e10.strm.avail_out) ? A2 : I3;
        }
        function W2(e10, t7) {
          for (var r9, n8, i8; ; ) {
            if (e10.lookahead < z3) {
              if (j3(e10), e10.lookahead < z3 && t7 === l5) return A2;
              if (0 === e10.lookahead) break;
            }
            if (r9 = 0, e10.lookahead >= x2 && (e10.ins_h = (e10.ins_h << e10.hash_shift ^ e10.window[e10.strstart + x2 - 1]) & e10.hash_mask, r9 = e10.prev[e10.strstart & e10.w_mask] = e10.head[e10.ins_h], e10.head[e10.ins_h] = e10.strstart), e10.prev_length = e10.match_length, e10.prev_match = e10.match_start, e10.match_length = x2 - 1, 0 !== r9 && e10.prev_length < e10.max_lazy_match && e10.strstart - r9 <= e10.w_size - z3 && (e10.match_length = L3(e10, r9), e10.match_length <= 5 && (1 === e10.strategy || e10.match_length === x2 && 4096 < e10.strstart - e10.match_start) && (e10.match_length = x2 - 1)), e10.prev_length >= x2 && e10.match_length <= e10.prev_length) {
              for (i8 = e10.strstart + e10.lookahead - x2, n8 = u5._tr_tally(e10, e10.strstart - 1 - e10.prev_match, e10.prev_length - x2), e10.lookahead -= e10.prev_length - 1, e10.prev_length -= 2; ++e10.strstart <= i8 && (e10.ins_h = (e10.ins_h << e10.hash_shift ^ e10.window[e10.strstart + x2 - 1]) & e10.hash_mask, r9 = e10.prev[e10.strstart & e10.w_mask] = e10.head[e10.ins_h], e10.head[e10.ins_h] = e10.strstart), 0 != --e10.prev_length; ) ;
              if (e10.match_available = 0, e10.match_length = x2 - 1, e10.strstart++, n8 && (N3(e10, false), 0 === e10.strm.avail_out)) return A2;
            } else if (e10.match_available) {
              if ((n8 = u5._tr_tally(e10, 0, e10.window[e10.strstart - 1])) && N3(e10, false), e10.strstart++, e10.lookahead--, 0 === e10.strm.avail_out) return A2;
            } else e10.match_available = 1, e10.strstart++, e10.lookahead--;
          }
          return e10.match_available && (n8 = u5._tr_tally(e10, 0, e10.window[e10.strstart - 1]), e10.match_available = 0), e10.insert = e10.strstart < x2 - 1 ? e10.strstart : x2 - 1, t7 === f4 ? (N3(e10, true), 0 === e10.strm.avail_out ? O2 : B3) : e10.last_lit && (N3(e10, false), 0 === e10.strm.avail_out) ? A2 : I3;
        }
        function M4(e10, t7, r9, n8, i8) {
          this.good_length = e10, this.max_lazy = t7, this.nice_length = r9, this.max_chain = n8, this.func = i8;
        }
        function H2() {
          this.strm = null, this.status = 0, this.pending_buf = null, this.pending_buf_size = 0, this.pending_out = 0, this.pending = 0, this.wrap = 0, this.gzhead = null, this.gzindex = 0, this.method = v4, this.last_flush = -1, this.w_size = 0, this.w_bits = 0, this.w_mask = 0, this.window = null, this.window_size = 0, this.prev = null, this.head = null, this.ins_h = 0, this.hash_size = 0, this.hash_bits = 0, this.hash_mask = 0, this.hash_shift = 0, this.block_start = 0, this.match_length = 0, this.prev_match = 0, this.match_available = 0, this.strstart = 0, this.match_start = 0, this.lookahead = 0, this.prev_length = 0, this.max_chain_length = 0, this.max_lazy_match = 0, this.level = 0, this.strategy = 0, this.good_match = 0, this.nice_match = 0, this.dyn_ltree = new c6.Buf16(2 * w3), this.dyn_dtree = new c6.Buf16(2 * (2 * a3 + 1)), this.bl_tree = new c6.Buf16(2 * (2 * o9 + 1)), D4(this.dyn_ltree), D4(this.dyn_dtree), D4(this.bl_tree), this.l_desc = null, this.d_desc = null, this.bl_desc = null, this.bl_count = new c6.Buf16(k2 + 1), this.heap = new c6.Buf16(2 * s6 + 1), D4(this.heap), this.heap_len = 0, this.heap_max = 0, this.depth = new c6.Buf16(2 * s6 + 1), D4(this.depth), this.l_buf = 0, this.lit_bufsize = 0, this.last_lit = 0, this.d_buf = 0, this.opt_len = 0, this.static_len = 0, this.matches = 0, this.insert = 0, this.bi_buf = 0, this.bi_valid = 0;
        }
        function G2(e10) {
          var t7;
          return e10 && e10.state ? (e10.total_in = e10.total_out = 0, e10.data_type = i7, (t7 = e10.state).pending = 0, t7.pending_out = 0, t7.wrap < 0 && (t7.wrap = -t7.wrap), t7.status = t7.wrap ? C3 : E3, e10.adler = 2 === t7.wrap ? 0 : 1, t7.last_flush = l5, u5._tr_init(t7), m4) : R3(e10, _3);
        }
        function K2(e10) {
          var t7 = G2(e10);
          return t7 === m4 && (function(e11) {
            e11.window_size = 2 * e11.w_size, D4(e11.head), e11.max_lazy_match = h7[e11.level].max_lazy, e11.good_match = h7[e11.level].good_length, e11.nice_match = h7[e11.level].nice_length, e11.max_chain_length = h7[e11.level].max_chain, e11.strstart = 0, e11.block_start = 0, e11.lookahead = 0, e11.insert = 0, e11.match_length = e11.prev_length = x2 - 1, e11.match_available = 0, e11.ins_h = 0;
          })(e10.state), t7;
        }
        function Y(e10, t7, r9, n8, i8, s7) {
          if (!e10) return _3;
          var a4 = 1;
          if (t7 === g3 && (t7 = 6), n8 < 0 ? (a4 = 0, n8 = -n8) : 15 < n8 && (a4 = 2, n8 -= 16), i8 < 1 || y4 < i8 || r9 !== v4 || n8 < 8 || 15 < n8 || t7 < 0 || 9 < t7 || s7 < 0 || b4 < s7) return R3(e10, _3);
          8 === n8 && (n8 = 9);
          var o10 = new H2();
          return (e10.state = o10).strm = e10, o10.wrap = a4, o10.gzhead = null, o10.w_bits = n8, o10.w_size = 1 << o10.w_bits, o10.w_mask = o10.w_size - 1, o10.hash_bits = i8 + 7, o10.hash_size = 1 << o10.hash_bits, o10.hash_mask = o10.hash_size - 1, o10.hash_shift = ~~((o10.hash_bits + x2 - 1) / x2), o10.window = new c6.Buf8(2 * o10.w_size), o10.head = new c6.Buf16(o10.hash_size), o10.prev = new c6.Buf16(o10.w_size), o10.lit_bufsize = 1 << i8 + 6, o10.pending_buf_size = 4 * o10.lit_bufsize, o10.pending_buf = new c6.Buf8(o10.pending_buf_size), o10.d_buf = 1 * o10.lit_bufsize, o10.l_buf = 3 * o10.lit_bufsize, o10.level = t7, o10.strategy = s7, o10.method = r9, K2(e10);
        }
        h7 = [new M4(0, 0, 0, 0, function(e10, t7) {
          var r9 = 65535;
          for (r9 > e10.pending_buf_size - 5 && (r9 = e10.pending_buf_size - 5); ; ) {
            if (e10.lookahead <= 1) {
              if (j3(e10), 0 === e10.lookahead && t7 === l5) return A2;
              if (0 === e10.lookahead) break;
            }
            e10.strstart += e10.lookahead, e10.lookahead = 0;
            var n8 = e10.block_start + r9;
            if ((0 === e10.strstart || e10.strstart >= n8) && (e10.lookahead = e10.strstart - n8, e10.strstart = n8, N3(e10, false), 0 === e10.strm.avail_out)) return A2;
            if (e10.strstart - e10.block_start >= e10.w_size - z3 && (N3(e10, false), 0 === e10.strm.avail_out)) return A2;
          }
          return e10.insert = 0, t7 === f4 ? (N3(e10, true), 0 === e10.strm.avail_out ? O2 : B3) : (e10.strstart > e10.block_start && (N3(e10, false), e10.strm.avail_out), A2);
        }), new M4(4, 4, 8, 4, Z2), new M4(4, 5, 16, 8, Z2), new M4(4, 6, 32, 32, Z2), new M4(4, 4, 16, 16, W2), new M4(8, 16, 32, 32, W2), new M4(8, 16, 128, 128, W2), new M4(8, 32, 128, 256, W2), new M4(32, 128, 258, 1024, W2), new M4(32, 258, 258, 4096, W2)], r8.deflateInit = function(e10, t7) {
          return Y(e10, t7, v4, 15, 8, 0);
        }, r8.deflateInit2 = Y, r8.deflateReset = K2, r8.deflateResetKeep = G2, r8.deflateSetHeader = function(e10, t7) {
          return e10 && e10.state ? 2 !== e10.state.wrap ? _3 : (e10.state.gzhead = t7, m4) : _3;
        }, r8.deflate = function(e10, t7) {
          var r9, n8, i8, s7;
          if (!e10 || !e10.state || 5 < t7 || t7 < 0) return e10 ? R3(e10, _3) : _3;
          if (n8 = e10.state, !e10.output || !e10.input && 0 !== e10.avail_in || 666 === n8.status && t7 !== f4) return R3(e10, 0 === e10.avail_out ? -5 : _3);
          if (n8.strm = e10, r9 = n8.last_flush, n8.last_flush = t7, n8.status === C3) if (2 === n8.wrap) e10.adler = 0, U2(n8, 31), U2(n8, 139), U2(n8, 8), n8.gzhead ? (U2(n8, (n8.gzhead.text ? 1 : 0) + (n8.gzhead.hcrc ? 2 : 0) + (n8.gzhead.extra ? 4 : 0) + (n8.gzhead.name ? 8 : 0) + (n8.gzhead.comment ? 16 : 0)), U2(n8, 255 & n8.gzhead.time), U2(n8, n8.gzhead.time >> 8 & 255), U2(n8, n8.gzhead.time >> 16 & 255), U2(n8, n8.gzhead.time >> 24 & 255), U2(n8, 9 === n8.level ? 2 : 2 <= n8.strategy || n8.level < 2 ? 4 : 0), U2(n8, 255 & n8.gzhead.os), n8.gzhead.extra && n8.gzhead.extra.length && (U2(n8, 255 & n8.gzhead.extra.length), U2(n8, n8.gzhead.extra.length >> 8 & 255)), n8.gzhead.hcrc && (e10.adler = p4(e10.adler, n8.pending_buf, n8.pending, 0)), n8.gzindex = 0, n8.status = 69) : (U2(n8, 0), U2(n8, 0), U2(n8, 0), U2(n8, 0), U2(n8, 0), U2(n8, 9 === n8.level ? 2 : 2 <= n8.strategy || n8.level < 2 ? 4 : 0), U2(n8, 3), n8.status = E3);
          else {
            var a4 = v4 + (n8.w_bits - 8 << 4) << 8;
            a4 |= (2 <= n8.strategy || n8.level < 2 ? 0 : n8.level < 6 ? 1 : 6 === n8.level ? 2 : 3) << 6, 0 !== n8.strstart && (a4 |= 32), a4 += 31 - a4 % 31, n8.status = E3, P3(n8, a4), 0 !== n8.strstart && (P3(n8, e10.adler >>> 16), P3(n8, 65535 & e10.adler)), e10.adler = 1;
          }
          if (69 === n8.status) if (n8.gzhead.extra) {
            for (i8 = n8.pending; n8.gzindex < (65535 & n8.gzhead.extra.length) && (n8.pending !== n8.pending_buf_size || (n8.gzhead.hcrc && n8.pending > i8 && (e10.adler = p4(e10.adler, n8.pending_buf, n8.pending - i8, i8)), F2(e10), i8 = n8.pending, n8.pending !== n8.pending_buf_size)); ) U2(n8, 255 & n8.gzhead.extra[n8.gzindex]), n8.gzindex++;
            n8.gzhead.hcrc && n8.pending > i8 && (e10.adler = p4(e10.adler, n8.pending_buf, n8.pending - i8, i8)), n8.gzindex === n8.gzhead.extra.length && (n8.gzindex = 0, n8.status = 73);
          } else n8.status = 73;
          if (73 === n8.status) if (n8.gzhead.name) {
            i8 = n8.pending;
            do {
              if (n8.pending === n8.pending_buf_size && (n8.gzhead.hcrc && n8.pending > i8 && (e10.adler = p4(e10.adler, n8.pending_buf, n8.pending - i8, i8)), F2(e10), i8 = n8.pending, n8.pending === n8.pending_buf_size)) {
                s7 = 1;
                break;
              }
              s7 = n8.gzindex < n8.gzhead.name.length ? 255 & n8.gzhead.name.charCodeAt(n8.gzindex++) : 0, U2(n8, s7);
            } while (0 !== s7);
            n8.gzhead.hcrc && n8.pending > i8 && (e10.adler = p4(e10.adler, n8.pending_buf, n8.pending - i8, i8)), 0 === s7 && (n8.gzindex = 0, n8.status = 91);
          } else n8.status = 91;
          if (91 === n8.status) if (n8.gzhead.comment) {
            i8 = n8.pending;
            do {
              if (n8.pending === n8.pending_buf_size && (n8.gzhead.hcrc && n8.pending > i8 && (e10.adler = p4(e10.adler, n8.pending_buf, n8.pending - i8, i8)), F2(e10), i8 = n8.pending, n8.pending === n8.pending_buf_size)) {
                s7 = 1;
                break;
              }
              s7 = n8.gzindex < n8.gzhead.comment.length ? 255 & n8.gzhead.comment.charCodeAt(n8.gzindex++) : 0, U2(n8, s7);
            } while (0 !== s7);
            n8.gzhead.hcrc && n8.pending > i8 && (e10.adler = p4(e10.adler, n8.pending_buf, n8.pending - i8, i8)), 0 === s7 && (n8.status = 103);
          } else n8.status = 103;
          if (103 === n8.status && (n8.gzhead.hcrc ? (n8.pending + 2 > n8.pending_buf_size && F2(e10), n8.pending + 2 <= n8.pending_buf_size && (U2(n8, 255 & e10.adler), U2(n8, e10.adler >> 8 & 255), e10.adler = 0, n8.status = E3)) : n8.status = E3), 0 !== n8.pending) {
            if (F2(e10), 0 === e10.avail_out) return n8.last_flush = -1, m4;
          } else if (0 === e10.avail_in && T3(t7) <= T3(r9) && t7 !== f4) return R3(e10, -5);
          if (666 === n8.status && 0 !== e10.avail_in) return R3(e10, -5);
          if (0 !== e10.avail_in || 0 !== n8.lookahead || t7 !== l5 && 666 !== n8.status) {
            var o10 = 2 === n8.strategy ? (function(e11, t8) {
              for (var r10; ; ) {
                if (0 === e11.lookahead && (j3(e11), 0 === e11.lookahead)) {
                  if (t8 === l5) return A2;
                  break;
                }
                if (e11.match_length = 0, r10 = u5._tr_tally(e11, 0, e11.window[e11.strstart]), e11.lookahead--, e11.strstart++, r10 && (N3(e11, false), 0 === e11.strm.avail_out)) return A2;
              }
              return e11.insert = 0, t8 === f4 ? (N3(e11, true), 0 === e11.strm.avail_out ? O2 : B3) : e11.last_lit && (N3(e11, false), 0 === e11.strm.avail_out) ? A2 : I3;
            })(n8, t7) : 3 === n8.strategy ? (function(e11, t8) {
              for (var r10, n9, i9, s8, a5 = e11.window; ; ) {
                if (e11.lookahead <= S5) {
                  if (j3(e11), e11.lookahead <= S5 && t8 === l5) return A2;
                  if (0 === e11.lookahead) break;
                }
                if (e11.match_length = 0, e11.lookahead >= x2 && 0 < e11.strstart && (n9 = a5[i9 = e11.strstart - 1]) === a5[++i9] && n9 === a5[++i9] && n9 === a5[++i9]) {
                  s8 = e11.strstart + S5;
                  do {
                  } while (n9 === a5[++i9] && n9 === a5[++i9] && n9 === a5[++i9] && n9 === a5[++i9] && n9 === a5[++i9] && n9 === a5[++i9] && n9 === a5[++i9] && n9 === a5[++i9] && i9 < s8);
                  e11.match_length = S5 - (s8 - i9), e11.match_length > e11.lookahead && (e11.match_length = e11.lookahead);
                }
                if (e11.match_length >= x2 ? (r10 = u5._tr_tally(e11, 1, e11.match_length - x2), e11.lookahead -= e11.match_length, e11.strstart += e11.match_length, e11.match_length = 0) : (r10 = u5._tr_tally(e11, 0, e11.window[e11.strstart]), e11.lookahead--, e11.strstart++), r10 && (N3(e11, false), 0 === e11.strm.avail_out)) return A2;
              }
              return e11.insert = 0, t8 === f4 ? (N3(e11, true), 0 === e11.strm.avail_out ? O2 : B3) : e11.last_lit && (N3(e11, false), 0 === e11.strm.avail_out) ? A2 : I3;
            })(n8, t7) : h7[n8.level].func(n8, t7);
            if (o10 !== O2 && o10 !== B3 || (n8.status = 666), o10 === A2 || o10 === O2) return 0 === e10.avail_out && (n8.last_flush = -1), m4;
            if (o10 === I3 && (1 === t7 ? u5._tr_align(n8) : 5 !== t7 && (u5._tr_stored_block(n8, 0, 0, false), 3 === t7 && (D4(n8.head), 0 === n8.lookahead && (n8.strstart = 0, n8.block_start = 0, n8.insert = 0))), F2(e10), 0 === e10.avail_out)) return n8.last_flush = -1, m4;
          }
          return t7 !== f4 ? m4 : n8.wrap <= 0 ? 1 : (2 === n8.wrap ? (U2(n8, 255 & e10.adler), U2(n8, e10.adler >> 8 & 255), U2(n8, e10.adler >> 16 & 255), U2(n8, e10.adler >> 24 & 255), U2(n8, 255 & e10.total_in), U2(n8, e10.total_in >> 8 & 255), U2(n8, e10.total_in >> 16 & 255), U2(n8, e10.total_in >> 24 & 255)) : (P3(n8, e10.adler >>> 16), P3(n8, 65535 & e10.adler)), F2(e10), 0 < n8.wrap && (n8.wrap = -n8.wrap), 0 !== n8.pending ? m4 : 1);
        }, r8.deflateEnd = function(e10) {
          var t7;
          return e10 && e10.state ? (t7 = e10.state.status) !== C3 && 69 !== t7 && 73 !== t7 && 91 !== t7 && 103 !== t7 && t7 !== E3 && 666 !== t7 ? R3(e10, _3) : (e10.state = null, t7 === E3 ? R3(e10, -3) : m4) : _3;
        }, r8.deflateSetDictionary = function(e10, t7) {
          var r9, n8, i8, s7, a4, o10, h8, u6, l6 = t7.length;
          if (!e10 || !e10.state) return _3;
          if (2 === (s7 = (r9 = e10.state).wrap) || 1 === s7 && r9.status !== C3 || r9.lookahead) return _3;
          for (1 === s7 && (e10.adler = d4(e10.adler, t7, l6, 0)), r9.wrap = 0, l6 >= r9.w_size && (0 === s7 && (D4(r9.head), r9.strstart = 0, r9.block_start = 0, r9.insert = 0), u6 = new c6.Buf8(r9.w_size), c6.arraySet(u6, t7, l6 - r9.w_size, r9.w_size, 0), t7 = u6, l6 = r9.w_size), a4 = e10.avail_in, o10 = e10.next_in, h8 = e10.input, e10.avail_in = l6, e10.next_in = 0, e10.input = t7, j3(r9); r9.lookahead >= x2; ) {
            for (n8 = r9.strstart, i8 = r9.lookahead - (x2 - 1); r9.ins_h = (r9.ins_h << r9.hash_shift ^ r9.window[n8 + x2 - 1]) & r9.hash_mask, r9.prev[n8 & r9.w_mask] = r9.head[r9.ins_h], r9.head[r9.ins_h] = n8, n8++, --i8; ) ;
            r9.strstart = n8, r9.lookahead = x2 - 1, j3(r9);
          }
          return r9.strstart += r9.lookahead, r9.block_start = r9.strstart, r9.insert = r9.lookahead, r9.lookahead = 0, r9.match_length = r9.prev_length = x2 - 1, r9.match_available = 0, e10.next_in = o10, e10.input = h8, e10.avail_in = a4, r9.wrap = s7, m4;
        }, r8.deflateInfo = "pako deflate (from Nodeca project)";
      }, { "../utils/common": 41, "./adler32": 43, "./crc32": 45, "./messages": 51, "./trees": 52 }], 47: [function(e9, t6, r8) {
        "use strict";
        t6.exports = function() {
          this.text = 0, this.time = 0, this.xflags = 0, this.os = 0, this.extra = null, this.extra_len = 0, this.name = "", this.comment = "", this.hcrc = 0, this.done = false;
        };
      }, {}], 48: [function(e9, t6, r8) {
        "use strict";
        t6.exports = function(e10, t7) {
          var r9, n7, i7, s6, a3, o9, h7, u5, l5, f4, c6, d4, p4, m4, _3, g3, b4, v4, y4, w3, k2, x2, S5, z3, C3;
          r9 = e10.state, n7 = e10.next_in, z3 = e10.input, i7 = n7 + (e10.avail_in - 5), s6 = e10.next_out, C3 = e10.output, a3 = s6 - (t7 - e10.avail_out), o9 = s6 + (e10.avail_out - 257), h7 = r9.dmax, u5 = r9.wsize, l5 = r9.whave, f4 = r9.wnext, c6 = r9.window, d4 = r9.hold, p4 = r9.bits, m4 = r9.lencode, _3 = r9.distcode, g3 = (1 << r9.lenbits) - 1, b4 = (1 << r9.distbits) - 1;
          e: do {
            p4 < 15 && (d4 += z3[n7++] << p4, p4 += 8, d4 += z3[n7++] << p4, p4 += 8), v4 = m4[d4 & g3];
            t: for (; ; ) {
              if (d4 >>>= y4 = v4 >>> 24, p4 -= y4, 0 === (y4 = v4 >>> 16 & 255)) C3[s6++] = 65535 & v4;
              else {
                if (!(16 & y4)) {
                  if (0 == (64 & y4)) {
                    v4 = m4[(65535 & v4) + (d4 & (1 << y4) - 1)];
                    continue t;
                  }
                  if (32 & y4) {
                    r9.mode = 12;
                    break e;
                  }
                  e10.msg = "invalid literal/length code", r9.mode = 30;
                  break e;
                }
                w3 = 65535 & v4, (y4 &= 15) && (p4 < y4 && (d4 += z3[n7++] << p4, p4 += 8), w3 += d4 & (1 << y4) - 1, d4 >>>= y4, p4 -= y4), p4 < 15 && (d4 += z3[n7++] << p4, p4 += 8, d4 += z3[n7++] << p4, p4 += 8), v4 = _3[d4 & b4];
                r: for (; ; ) {
                  if (d4 >>>= y4 = v4 >>> 24, p4 -= y4, !(16 & (y4 = v4 >>> 16 & 255))) {
                    if (0 == (64 & y4)) {
                      v4 = _3[(65535 & v4) + (d4 & (1 << y4) - 1)];
                      continue r;
                    }
                    e10.msg = "invalid distance code", r9.mode = 30;
                    break e;
                  }
                  if (k2 = 65535 & v4, p4 < (y4 &= 15) && (d4 += z3[n7++] << p4, (p4 += 8) < y4 && (d4 += z3[n7++] << p4, p4 += 8)), h7 < (k2 += d4 & (1 << y4) - 1)) {
                    e10.msg = "invalid distance too far back", r9.mode = 30;
                    break e;
                  }
                  if (d4 >>>= y4, p4 -= y4, (y4 = s6 - a3) < k2) {
                    if (l5 < (y4 = k2 - y4) && r9.sane) {
                      e10.msg = "invalid distance too far back", r9.mode = 30;
                      break e;
                    }
                    if (S5 = c6, (x2 = 0) === f4) {
                      if (x2 += u5 - y4, y4 < w3) {
                        for (w3 -= y4; C3[s6++] = c6[x2++], --y4; ) ;
                        x2 = s6 - k2, S5 = C3;
                      }
                    } else if (f4 < y4) {
                      if (x2 += u5 + f4 - y4, (y4 -= f4) < w3) {
                        for (w3 -= y4; C3[s6++] = c6[x2++], --y4; ) ;
                        if (x2 = 0, f4 < w3) {
                          for (w3 -= y4 = f4; C3[s6++] = c6[x2++], --y4; ) ;
                          x2 = s6 - k2, S5 = C3;
                        }
                      }
                    } else if (x2 += f4 - y4, y4 < w3) {
                      for (w3 -= y4; C3[s6++] = c6[x2++], --y4; ) ;
                      x2 = s6 - k2, S5 = C3;
                    }
                    for (; 2 < w3; ) C3[s6++] = S5[x2++], C3[s6++] = S5[x2++], C3[s6++] = S5[x2++], w3 -= 3;
                    w3 && (C3[s6++] = S5[x2++], 1 < w3 && (C3[s6++] = S5[x2++]));
                  } else {
                    for (x2 = s6 - k2; C3[s6++] = C3[x2++], C3[s6++] = C3[x2++], C3[s6++] = C3[x2++], 2 < (w3 -= 3); ) ;
                    w3 && (C3[s6++] = C3[x2++], 1 < w3 && (C3[s6++] = C3[x2++]));
                  }
                  break;
                }
              }
              break;
            }
          } while (n7 < i7 && s6 < o9);
          n7 -= w3 = p4 >> 3, d4 &= (1 << (p4 -= w3 << 3)) - 1, e10.next_in = n7, e10.next_out = s6, e10.avail_in = n7 < i7 ? i7 - n7 + 5 : 5 - (n7 - i7), e10.avail_out = s6 < o9 ? o9 - s6 + 257 : 257 - (s6 - o9), r9.hold = d4, r9.bits = p4;
        };
      }, {}], 49: [function(e9, t6, r8) {
        "use strict";
        var I3 = e9("../utils/common"), O2 = e9("./adler32"), B3 = e9("./crc32"), R3 = e9("./inffast"), T3 = e9("./inftrees"), D4 = 1, F2 = 2, N3 = 0, U2 = -2, P3 = 1, n7 = 852, i7 = 592;
        function L3(e10) {
          return (e10 >>> 24 & 255) + (e10 >>> 8 & 65280) + ((65280 & e10) << 8) + ((255 & e10) << 24);
        }
        function s6() {
          this.mode = 0, this.last = false, this.wrap = 0, this.havedict = false, this.flags = 0, this.dmax = 0, this.check = 0, this.total = 0, this.head = null, this.wbits = 0, this.wsize = 0, this.whave = 0, this.wnext = 0, this.window = null, this.hold = 0, this.bits = 0, this.length = 0, this.offset = 0, this.extra = 0, this.lencode = null, this.distcode = null, this.lenbits = 0, this.distbits = 0, this.ncode = 0, this.nlen = 0, this.ndist = 0, this.have = 0, this.next = null, this.lens = new I3.Buf16(320), this.work = new I3.Buf16(288), this.lendyn = null, this.distdyn = null, this.sane = 0, this.back = 0, this.was = 0;
        }
        function a3(e10) {
          var t7;
          return e10 && e10.state ? (t7 = e10.state, e10.total_in = e10.total_out = t7.total = 0, e10.msg = "", t7.wrap && (e10.adler = 1 & t7.wrap), t7.mode = P3, t7.last = 0, t7.havedict = 0, t7.dmax = 32768, t7.head = null, t7.hold = 0, t7.bits = 0, t7.lencode = t7.lendyn = new I3.Buf32(n7), t7.distcode = t7.distdyn = new I3.Buf32(i7), t7.sane = 1, t7.back = -1, N3) : U2;
        }
        function o9(e10) {
          var t7;
          return e10 && e10.state ? ((t7 = e10.state).wsize = 0, t7.whave = 0, t7.wnext = 0, a3(e10)) : U2;
        }
        function h7(e10, t7) {
          var r9, n8;
          return e10 && e10.state ? (n8 = e10.state, t7 < 0 ? (r9 = 0, t7 = -t7) : (r9 = 1 + (t7 >> 4), t7 < 48 && (t7 &= 15)), t7 && (t7 < 8 || 15 < t7) ? U2 : (null !== n8.window && n8.wbits !== t7 && (n8.window = null), n8.wrap = r9, n8.wbits = t7, o9(e10))) : U2;
        }
        function u5(e10, t7) {
          var r9, n8;
          return e10 ? (n8 = new s6(), (e10.state = n8).window = null, (r9 = h7(e10, t7)) !== N3 && (e10.state = null), r9) : U2;
        }
        var l5, f4, c6 = true;
        function j3(e10) {
          if (c6) {
            var t7;
            for (l5 = new I3.Buf32(512), f4 = new I3.Buf32(32), t7 = 0; t7 < 144; ) e10.lens[t7++] = 8;
            for (; t7 < 256; ) e10.lens[t7++] = 9;
            for (; t7 < 280; ) e10.lens[t7++] = 7;
            for (; t7 < 288; ) e10.lens[t7++] = 8;
            for (T3(D4, e10.lens, 0, 288, l5, 0, e10.work, { bits: 9 }), t7 = 0; t7 < 32; ) e10.lens[t7++] = 5;
            T3(F2, e10.lens, 0, 32, f4, 0, e10.work, { bits: 5 }), c6 = false;
          }
          e10.lencode = l5, e10.lenbits = 9, e10.distcode = f4, e10.distbits = 5;
        }
        function Z2(e10, t7, r9, n8) {
          var i8, s7 = e10.state;
          return null === s7.window && (s7.wsize = 1 << s7.wbits, s7.wnext = 0, s7.whave = 0, s7.window = new I3.Buf8(s7.wsize)), n8 >= s7.wsize ? (I3.arraySet(s7.window, t7, r9 - s7.wsize, s7.wsize, 0), s7.wnext = 0, s7.whave = s7.wsize) : (n8 < (i8 = s7.wsize - s7.wnext) && (i8 = n8), I3.arraySet(s7.window, t7, r9 - n8, i8, s7.wnext), (n8 -= i8) ? (I3.arraySet(s7.window, t7, r9 - n8, n8, 0), s7.wnext = n8, s7.whave = s7.wsize) : (s7.wnext += i8, s7.wnext === s7.wsize && (s7.wnext = 0), s7.whave < s7.wsize && (s7.whave += i8))), 0;
        }
        r8.inflateReset = o9, r8.inflateReset2 = h7, r8.inflateResetKeep = a3, r8.inflateInit = function(e10) {
          return u5(e10, 15);
        }, r8.inflateInit2 = u5, r8.inflate = function(e10, t7) {
          var r9, n8, i8, s7, a4, o10, h8, u6, l6, f5, c7, d4, p4, m4, _3, g3, b4, v4, y4, w3, k2, x2, S5, z3, C3 = 0, E3 = new I3.Buf8(4), A2 = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
          if (!e10 || !e10.state || !e10.output || !e10.input && 0 !== e10.avail_in) return U2;
          12 === (r9 = e10.state).mode && (r9.mode = 13), a4 = e10.next_out, i8 = e10.output, h8 = e10.avail_out, s7 = e10.next_in, n8 = e10.input, o10 = e10.avail_in, u6 = r9.hold, l6 = r9.bits, f5 = o10, c7 = h8, x2 = N3;
          e: for (; ; ) switch (r9.mode) {
            case P3:
              if (0 === r9.wrap) {
                r9.mode = 13;
                break;
              }
              for (; l6 < 16; ) {
                if (0 === o10) break e;
                o10--, u6 += n8[s7++] << l6, l6 += 8;
              }
              if (2 & r9.wrap && 35615 === u6) {
                E3[r9.check = 0] = 255 & u6, E3[1] = u6 >>> 8 & 255, r9.check = B3(r9.check, E3, 2, 0), l6 = u6 = 0, r9.mode = 2;
                break;
              }
              if (r9.flags = 0, r9.head && (r9.head.done = false), !(1 & r9.wrap) || (((255 & u6) << 8) + (u6 >> 8)) % 31) {
                e10.msg = "incorrect header check", r9.mode = 30;
                break;
              }
              if (8 != (15 & u6)) {
                e10.msg = "unknown compression method", r9.mode = 30;
                break;
              }
              if (l6 -= 4, k2 = 8 + (15 & (u6 >>>= 4)), 0 === r9.wbits) r9.wbits = k2;
              else if (k2 > r9.wbits) {
                e10.msg = "invalid window size", r9.mode = 30;
                break;
              }
              r9.dmax = 1 << k2, e10.adler = r9.check = 1, r9.mode = 512 & u6 ? 10 : 12, l6 = u6 = 0;
              break;
            case 2:
              for (; l6 < 16; ) {
                if (0 === o10) break e;
                o10--, u6 += n8[s7++] << l6, l6 += 8;
              }
              if (r9.flags = u6, 8 != (255 & r9.flags)) {
                e10.msg = "unknown compression method", r9.mode = 30;
                break;
              }
              if (57344 & r9.flags) {
                e10.msg = "unknown header flags set", r9.mode = 30;
                break;
              }
              r9.head && (r9.head.text = u6 >> 8 & 1), 512 & r9.flags && (E3[0] = 255 & u6, E3[1] = u6 >>> 8 & 255, r9.check = B3(r9.check, E3, 2, 0)), l6 = u6 = 0, r9.mode = 3;
            case 3:
              for (; l6 < 32; ) {
                if (0 === o10) break e;
                o10--, u6 += n8[s7++] << l6, l6 += 8;
              }
              r9.head && (r9.head.time = u6), 512 & r9.flags && (E3[0] = 255 & u6, E3[1] = u6 >>> 8 & 255, E3[2] = u6 >>> 16 & 255, E3[3] = u6 >>> 24 & 255, r9.check = B3(r9.check, E3, 4, 0)), l6 = u6 = 0, r9.mode = 4;
            case 4:
              for (; l6 < 16; ) {
                if (0 === o10) break e;
                o10--, u6 += n8[s7++] << l6, l6 += 8;
              }
              r9.head && (r9.head.xflags = 255 & u6, r9.head.os = u6 >> 8), 512 & r9.flags && (E3[0] = 255 & u6, E3[1] = u6 >>> 8 & 255, r9.check = B3(r9.check, E3, 2, 0)), l6 = u6 = 0, r9.mode = 5;
            case 5:
              if (1024 & r9.flags) {
                for (; l6 < 16; ) {
                  if (0 === o10) break e;
                  o10--, u6 += n8[s7++] << l6, l6 += 8;
                }
                r9.length = u6, r9.head && (r9.head.extra_len = u6), 512 & r9.flags && (E3[0] = 255 & u6, E3[1] = u6 >>> 8 & 255, r9.check = B3(r9.check, E3, 2, 0)), l6 = u6 = 0;
              } else r9.head && (r9.head.extra = null);
              r9.mode = 6;
            case 6:
              if (1024 & r9.flags && (o10 < (d4 = r9.length) && (d4 = o10), d4 && (r9.head && (k2 = r9.head.extra_len - r9.length, r9.head.extra || (r9.head.extra = new Array(r9.head.extra_len)), I3.arraySet(r9.head.extra, n8, s7, d4, k2)), 512 & r9.flags && (r9.check = B3(r9.check, n8, d4, s7)), o10 -= d4, s7 += d4, r9.length -= d4), r9.length)) break e;
              r9.length = 0, r9.mode = 7;
            case 7:
              if (2048 & r9.flags) {
                if (0 === o10) break e;
                for (d4 = 0; k2 = n8[s7 + d4++], r9.head && k2 && r9.length < 65536 && (r9.head.name += String.fromCharCode(k2)), k2 && d4 < o10; ) ;
                if (512 & r9.flags && (r9.check = B3(r9.check, n8, d4, s7)), o10 -= d4, s7 += d4, k2) break e;
              } else r9.head && (r9.head.name = null);
              r9.length = 0, r9.mode = 8;
            case 8:
              if (4096 & r9.flags) {
                if (0 === o10) break e;
                for (d4 = 0; k2 = n8[s7 + d4++], r9.head && k2 && r9.length < 65536 && (r9.head.comment += String.fromCharCode(k2)), k2 && d4 < o10; ) ;
                if (512 & r9.flags && (r9.check = B3(r9.check, n8, d4, s7)), o10 -= d4, s7 += d4, k2) break e;
              } else r9.head && (r9.head.comment = null);
              r9.mode = 9;
            case 9:
              if (512 & r9.flags) {
                for (; l6 < 16; ) {
                  if (0 === o10) break e;
                  o10--, u6 += n8[s7++] << l6, l6 += 8;
                }
                if (u6 !== (65535 & r9.check)) {
                  e10.msg = "header crc mismatch", r9.mode = 30;
                  break;
                }
                l6 = u6 = 0;
              }
              r9.head && (r9.head.hcrc = r9.flags >> 9 & 1, r9.head.done = true), e10.adler = r9.check = 0, r9.mode = 12;
              break;
            case 10:
              for (; l6 < 32; ) {
                if (0 === o10) break e;
                o10--, u6 += n8[s7++] << l6, l6 += 8;
              }
              e10.adler = r9.check = L3(u6), l6 = u6 = 0, r9.mode = 11;
            case 11:
              if (0 === r9.havedict) return e10.next_out = a4, e10.avail_out = h8, e10.next_in = s7, e10.avail_in = o10, r9.hold = u6, r9.bits = l6, 2;
              e10.adler = r9.check = 1, r9.mode = 12;
            case 12:
              if (5 === t7 || 6 === t7) break e;
            case 13:
              if (r9.last) {
                u6 >>>= 7 & l6, l6 -= 7 & l6, r9.mode = 27;
                break;
              }
              for (; l6 < 3; ) {
                if (0 === o10) break e;
                o10--, u6 += n8[s7++] << l6, l6 += 8;
              }
              switch (r9.last = 1 & u6, l6 -= 1, 3 & (u6 >>>= 1)) {
                case 0:
                  r9.mode = 14;
                  break;
                case 1:
                  if (j3(r9), r9.mode = 20, 6 !== t7) break;
                  u6 >>>= 2, l6 -= 2;
                  break e;
                case 2:
                  r9.mode = 17;
                  break;
                case 3:
                  e10.msg = "invalid block type", r9.mode = 30;
              }
              u6 >>>= 2, l6 -= 2;
              break;
            case 14:
              for (u6 >>>= 7 & l6, l6 -= 7 & l6; l6 < 32; ) {
                if (0 === o10) break e;
                o10--, u6 += n8[s7++] << l6, l6 += 8;
              }
              if ((65535 & u6) != (u6 >>> 16 ^ 65535)) {
                e10.msg = "invalid stored block lengths", r9.mode = 30;
                break;
              }
              if (r9.length = 65535 & u6, l6 = u6 = 0, r9.mode = 15, 6 === t7) break e;
            case 15:
              r9.mode = 16;
            case 16:
              if (d4 = r9.length) {
                if (o10 < d4 && (d4 = o10), h8 < d4 && (d4 = h8), 0 === d4) break e;
                I3.arraySet(i8, n8, s7, d4, a4), o10 -= d4, s7 += d4, h8 -= d4, a4 += d4, r9.length -= d4;
                break;
              }
              r9.mode = 12;
              break;
            case 17:
              for (; l6 < 14; ) {
                if (0 === o10) break e;
                o10--, u6 += n8[s7++] << l6, l6 += 8;
              }
              if (r9.nlen = 257 + (31 & u6), u6 >>>= 5, l6 -= 5, r9.ndist = 1 + (31 & u6), u6 >>>= 5, l6 -= 5, r9.ncode = 4 + (15 & u6), u6 >>>= 4, l6 -= 4, 286 < r9.nlen || 30 < r9.ndist) {
                e10.msg = "too many length or distance symbols", r9.mode = 30;
                break;
              }
              r9.have = 0, r9.mode = 18;
            case 18:
              for (; r9.have < r9.ncode; ) {
                for (; l6 < 3; ) {
                  if (0 === o10) break e;
                  o10--, u6 += n8[s7++] << l6, l6 += 8;
                }
                r9.lens[A2[r9.have++]] = 7 & u6, u6 >>>= 3, l6 -= 3;
              }
              for (; r9.have < 19; ) r9.lens[A2[r9.have++]] = 0;
              if (r9.lencode = r9.lendyn, r9.lenbits = 7, S5 = { bits: r9.lenbits }, x2 = T3(0, r9.lens, 0, 19, r9.lencode, 0, r9.work, S5), r9.lenbits = S5.bits, x2) {
                e10.msg = "invalid code lengths set", r9.mode = 30;
                break;
              }
              r9.have = 0, r9.mode = 19;
            case 19:
              for (; r9.have < r9.nlen + r9.ndist; ) {
                for (; g3 = (C3 = r9.lencode[u6 & (1 << r9.lenbits) - 1]) >>> 16 & 255, b4 = 65535 & C3, !((_3 = C3 >>> 24) <= l6); ) {
                  if (0 === o10) break e;
                  o10--, u6 += n8[s7++] << l6, l6 += 8;
                }
                if (b4 < 16) u6 >>>= _3, l6 -= _3, r9.lens[r9.have++] = b4;
                else {
                  if (16 === b4) {
                    for (z3 = _3 + 2; l6 < z3; ) {
                      if (0 === o10) break e;
                      o10--, u6 += n8[s7++] << l6, l6 += 8;
                    }
                    if (u6 >>>= _3, l6 -= _3, 0 === r9.have) {
                      e10.msg = "invalid bit length repeat", r9.mode = 30;
                      break;
                    }
                    k2 = r9.lens[r9.have - 1], d4 = 3 + (3 & u6), u6 >>>= 2, l6 -= 2;
                  } else if (17 === b4) {
                    for (z3 = _3 + 3; l6 < z3; ) {
                      if (0 === o10) break e;
                      o10--, u6 += n8[s7++] << l6, l6 += 8;
                    }
                    l6 -= _3, k2 = 0, d4 = 3 + (7 & (u6 >>>= _3)), u6 >>>= 3, l6 -= 3;
                  } else {
                    for (z3 = _3 + 7; l6 < z3; ) {
                      if (0 === o10) break e;
                      o10--, u6 += n8[s7++] << l6, l6 += 8;
                    }
                    l6 -= _3, k2 = 0, d4 = 11 + (127 & (u6 >>>= _3)), u6 >>>= 7, l6 -= 7;
                  }
                  if (r9.have + d4 > r9.nlen + r9.ndist) {
                    e10.msg = "invalid bit length repeat", r9.mode = 30;
                    break;
                  }
                  for (; d4--; ) r9.lens[r9.have++] = k2;
                }
              }
              if (30 === r9.mode) break;
              if (0 === r9.lens[256]) {
                e10.msg = "invalid code -- missing end-of-block", r9.mode = 30;
                break;
              }
              if (r9.lenbits = 9, S5 = { bits: r9.lenbits }, x2 = T3(D4, r9.lens, 0, r9.nlen, r9.lencode, 0, r9.work, S5), r9.lenbits = S5.bits, x2) {
                e10.msg = "invalid literal/lengths set", r9.mode = 30;
                break;
              }
              if (r9.distbits = 6, r9.distcode = r9.distdyn, S5 = { bits: r9.distbits }, x2 = T3(F2, r9.lens, r9.nlen, r9.ndist, r9.distcode, 0, r9.work, S5), r9.distbits = S5.bits, x2) {
                e10.msg = "invalid distances set", r9.mode = 30;
                break;
              }
              if (r9.mode = 20, 6 === t7) break e;
            case 20:
              r9.mode = 21;
            case 21:
              if (6 <= o10 && 258 <= h8) {
                e10.next_out = a4, e10.avail_out = h8, e10.next_in = s7, e10.avail_in = o10, r9.hold = u6, r9.bits = l6, R3(e10, c7), a4 = e10.next_out, i8 = e10.output, h8 = e10.avail_out, s7 = e10.next_in, n8 = e10.input, o10 = e10.avail_in, u6 = r9.hold, l6 = r9.bits, 12 === r9.mode && (r9.back = -1);
                break;
              }
              for (r9.back = 0; g3 = (C3 = r9.lencode[u6 & (1 << r9.lenbits) - 1]) >>> 16 & 255, b4 = 65535 & C3, !((_3 = C3 >>> 24) <= l6); ) {
                if (0 === o10) break e;
                o10--, u6 += n8[s7++] << l6, l6 += 8;
              }
              if (g3 && 0 == (240 & g3)) {
                for (v4 = _3, y4 = g3, w3 = b4; g3 = (C3 = r9.lencode[w3 + ((u6 & (1 << v4 + y4) - 1) >> v4)]) >>> 16 & 255, b4 = 65535 & C3, !(v4 + (_3 = C3 >>> 24) <= l6); ) {
                  if (0 === o10) break e;
                  o10--, u6 += n8[s7++] << l6, l6 += 8;
                }
                u6 >>>= v4, l6 -= v4, r9.back += v4;
              }
              if (u6 >>>= _3, l6 -= _3, r9.back += _3, r9.length = b4, 0 === g3) {
                r9.mode = 26;
                break;
              }
              if (32 & g3) {
                r9.back = -1, r9.mode = 12;
                break;
              }
              if (64 & g3) {
                e10.msg = "invalid literal/length code", r9.mode = 30;
                break;
              }
              r9.extra = 15 & g3, r9.mode = 22;
            case 22:
              if (r9.extra) {
                for (z3 = r9.extra; l6 < z3; ) {
                  if (0 === o10) break e;
                  o10--, u6 += n8[s7++] << l6, l6 += 8;
                }
                r9.length += u6 & (1 << r9.extra) - 1, u6 >>>= r9.extra, l6 -= r9.extra, r9.back += r9.extra;
              }
              r9.was = r9.length, r9.mode = 23;
            case 23:
              for (; g3 = (C3 = r9.distcode[u6 & (1 << r9.distbits) - 1]) >>> 16 & 255, b4 = 65535 & C3, !((_3 = C3 >>> 24) <= l6); ) {
                if (0 === o10) break e;
                o10--, u6 += n8[s7++] << l6, l6 += 8;
              }
              if (0 == (240 & g3)) {
                for (v4 = _3, y4 = g3, w3 = b4; g3 = (C3 = r9.distcode[w3 + ((u6 & (1 << v4 + y4) - 1) >> v4)]) >>> 16 & 255, b4 = 65535 & C3, !(v4 + (_3 = C3 >>> 24) <= l6); ) {
                  if (0 === o10) break e;
                  o10--, u6 += n8[s7++] << l6, l6 += 8;
                }
                u6 >>>= v4, l6 -= v4, r9.back += v4;
              }
              if (u6 >>>= _3, l6 -= _3, r9.back += _3, 64 & g3) {
                e10.msg = "invalid distance code", r9.mode = 30;
                break;
              }
              r9.offset = b4, r9.extra = 15 & g3, r9.mode = 24;
            case 24:
              if (r9.extra) {
                for (z3 = r9.extra; l6 < z3; ) {
                  if (0 === o10) break e;
                  o10--, u6 += n8[s7++] << l6, l6 += 8;
                }
                r9.offset += u6 & (1 << r9.extra) - 1, u6 >>>= r9.extra, l6 -= r9.extra, r9.back += r9.extra;
              }
              if (r9.offset > r9.dmax) {
                e10.msg = "invalid distance too far back", r9.mode = 30;
                break;
              }
              r9.mode = 25;
            case 25:
              if (0 === h8) break e;
              if (d4 = c7 - h8, r9.offset > d4) {
                if ((d4 = r9.offset - d4) > r9.whave && r9.sane) {
                  e10.msg = "invalid distance too far back", r9.mode = 30;
                  break;
                }
                p4 = d4 > r9.wnext ? (d4 -= r9.wnext, r9.wsize - d4) : r9.wnext - d4, d4 > r9.length && (d4 = r9.length), m4 = r9.window;
              } else m4 = i8, p4 = a4 - r9.offset, d4 = r9.length;
              for (h8 < d4 && (d4 = h8), h8 -= d4, r9.length -= d4; i8[a4++] = m4[p4++], --d4; ) ;
              0 === r9.length && (r9.mode = 21);
              break;
            case 26:
              if (0 === h8) break e;
              i8[a4++] = r9.length, h8--, r9.mode = 21;
              break;
            case 27:
              if (r9.wrap) {
                for (; l6 < 32; ) {
                  if (0 === o10) break e;
                  o10--, u6 |= n8[s7++] << l6, l6 += 8;
                }
                if (c7 -= h8, e10.total_out += c7, r9.total += c7, c7 && (e10.adler = r9.check = r9.flags ? B3(r9.check, i8, c7, a4 - c7) : O2(r9.check, i8, c7, a4 - c7)), c7 = h8, (r9.flags ? u6 : L3(u6)) !== r9.check) {
                  e10.msg = "incorrect data check", r9.mode = 30;
                  break;
                }
                l6 = u6 = 0;
              }
              r9.mode = 28;
            case 28:
              if (r9.wrap && r9.flags) {
                for (; l6 < 32; ) {
                  if (0 === o10) break e;
                  o10--, u6 += n8[s7++] << l6, l6 += 8;
                }
                if (u6 !== (4294967295 & r9.total)) {
                  e10.msg = "incorrect length check", r9.mode = 30;
                  break;
                }
                l6 = u6 = 0;
              }
              r9.mode = 29;
            case 29:
              x2 = 1;
              break e;
            case 30:
              x2 = -3;
              break e;
            case 31:
              return -4;
            case 32:
            default:
              return U2;
          }
          return e10.next_out = a4, e10.avail_out = h8, e10.next_in = s7, e10.avail_in = o10, r9.hold = u6, r9.bits = l6, (r9.wsize || c7 !== e10.avail_out && r9.mode < 30 && (r9.mode < 27 || 4 !== t7)) && Z2(e10, e10.output, e10.next_out, c7 - e10.avail_out) ? (r9.mode = 31, -4) : (f5 -= e10.avail_in, c7 -= e10.avail_out, e10.total_in += f5, e10.total_out += c7, r9.total += c7, r9.wrap && c7 && (e10.adler = r9.check = r9.flags ? B3(r9.check, i8, c7, e10.next_out - c7) : O2(r9.check, i8, c7, e10.next_out - c7)), e10.data_type = r9.bits + (r9.last ? 64 : 0) + (12 === r9.mode ? 128 : 0) + (20 === r9.mode || 15 === r9.mode ? 256 : 0), (0 == f5 && 0 === c7 || 4 === t7) && x2 === N3 && (x2 = -5), x2);
        }, r8.inflateEnd = function(e10) {
          if (!e10 || !e10.state) return U2;
          var t7 = e10.state;
          return t7.window && (t7.window = null), e10.state = null, N3;
        }, r8.inflateGetHeader = function(e10, t7) {
          var r9;
          return e10 && e10.state ? 0 == (2 & (r9 = e10.state).wrap) ? U2 : ((r9.head = t7).done = false, N3) : U2;
        }, r8.inflateSetDictionary = function(e10, t7) {
          var r9, n8 = t7.length;
          return e10 && e10.state ? 0 !== (r9 = e10.state).wrap && 11 !== r9.mode ? U2 : 11 === r9.mode && O2(1, t7, n8, 0) !== r9.check ? -3 : Z2(e10, t7, n8, n8) ? (r9.mode = 31, -4) : (r9.havedict = 1, N3) : U2;
        }, r8.inflateInfo = "pako inflate (from Nodeca project)";
      }, { "../utils/common": 41, "./adler32": 43, "./crc32": 45, "./inffast": 48, "./inftrees": 50 }], 50: [function(e9, t6, r8) {
        "use strict";
        var D4 = e9("../utils/common"), F2 = [3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0], N3 = [16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78], U2 = [1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0], P3 = [16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 28, 28, 29, 29, 64, 64];
        t6.exports = function(e10, t7, r9, n7, i7, s6, a3, o9) {
          var h7, u5, l5, f4, c6, d4, p4, m4, _3, g3 = o9.bits, b4 = 0, v4 = 0, y4 = 0, w3 = 0, k2 = 0, x2 = 0, S5 = 0, z3 = 0, C3 = 0, E3 = 0, A2 = null, I3 = 0, O2 = new D4.Buf16(16), B3 = new D4.Buf16(16), R3 = null, T3 = 0;
          for (b4 = 0; b4 <= 15; b4++) O2[b4] = 0;
          for (v4 = 0; v4 < n7; v4++) O2[t7[r9 + v4]]++;
          for (k2 = g3, w3 = 15; 1 <= w3 && 0 === O2[w3]; w3--) ;
          if (w3 < k2 && (k2 = w3), 0 === w3) return i7[s6++] = 20971520, i7[s6++] = 20971520, o9.bits = 1, 0;
          for (y4 = 1; y4 < w3 && 0 === O2[y4]; y4++) ;
          for (k2 < y4 && (k2 = y4), b4 = z3 = 1; b4 <= 15; b4++) if (z3 <<= 1, (z3 -= O2[b4]) < 0) return -1;
          if (0 < z3 && (0 === e10 || 1 !== w3)) return -1;
          for (B3[1] = 0, b4 = 1; b4 < 15; b4++) B3[b4 + 1] = B3[b4] + O2[b4];
          for (v4 = 0; v4 < n7; v4++) 0 !== t7[r9 + v4] && (a3[B3[t7[r9 + v4]]++] = v4);
          if (d4 = 0 === e10 ? (A2 = R3 = a3, 19) : 1 === e10 ? (A2 = F2, I3 -= 257, R3 = N3, T3 -= 257, 256) : (A2 = U2, R3 = P3, -1), b4 = y4, c6 = s6, S5 = v4 = E3 = 0, l5 = -1, f4 = (C3 = 1 << (x2 = k2)) - 1, 1 === e10 && 852 < C3 || 2 === e10 && 592 < C3) return 1;
          for (; ; ) {
            for (p4 = b4 - S5, _3 = a3[v4] < d4 ? (m4 = 0, a3[v4]) : a3[v4] > d4 ? (m4 = R3[T3 + a3[v4]], A2[I3 + a3[v4]]) : (m4 = 96, 0), h7 = 1 << b4 - S5, y4 = u5 = 1 << x2; i7[c6 + (E3 >> S5) + (u5 -= h7)] = p4 << 24 | m4 << 16 | _3 | 0, 0 !== u5; ) ;
            for (h7 = 1 << b4 - 1; E3 & h7; ) h7 >>= 1;
            if (0 !== h7 ? (E3 &= h7 - 1, E3 += h7) : E3 = 0, v4++, 0 == --O2[b4]) {
              if (b4 === w3) break;
              b4 = t7[r9 + a3[v4]];
            }
            if (k2 < b4 && (E3 & f4) !== l5) {
              for (0 === S5 && (S5 = k2), c6 += y4, z3 = 1 << (x2 = b4 - S5); x2 + S5 < w3 && !((z3 -= O2[x2 + S5]) <= 0); ) x2++, z3 <<= 1;
              if (C3 += 1 << x2, 1 === e10 && 852 < C3 || 2 === e10 && 592 < C3) return 1;
              i7[l5 = E3 & f4] = k2 << 24 | x2 << 16 | c6 - s6 | 0;
            }
          }
          return 0 !== E3 && (i7[c6 + E3] = b4 - S5 << 24 | 64 << 16 | 0), o9.bits = k2, 0;
        };
      }, { "../utils/common": 41 }], 51: [function(e9, t6, r8) {
        "use strict";
        t6.exports = { 2: "need dictionary", 1: "stream end", 0: "", "-1": "file error", "-2": "stream error", "-3": "data error", "-4": "insufficient memory", "-5": "buffer error", "-6": "incompatible version" };
      }, {}], 52: [function(e9, t6, r8) {
        "use strict";
        var i7 = e9("../utils/common"), o9 = 0, h7 = 1;
        function n7(e10) {
          for (var t7 = e10.length; 0 <= --t7; ) e10[t7] = 0;
        }
        var s6 = 0, a3 = 29, u5 = 256, l5 = u5 + 1 + a3, f4 = 30, c6 = 19, _3 = 2 * l5 + 1, g3 = 15, d4 = 16, p4 = 7, m4 = 256, b4 = 16, v4 = 17, y4 = 18, w3 = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0], k2 = [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13], x2 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7], S5 = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15], z3 = new Array(2 * (l5 + 2));
        n7(z3);
        var C3 = new Array(2 * f4);
        n7(C3);
        var E3 = new Array(512);
        n7(E3);
        var A2 = new Array(256);
        n7(A2);
        var I3 = new Array(a3);
        n7(I3);
        var O2, B3, R3, T3 = new Array(f4);
        function D4(e10, t7, r9, n8, i8) {
          this.static_tree = e10, this.extra_bits = t7, this.extra_base = r9, this.elems = n8, this.max_length = i8, this.has_stree = e10 && e10.length;
        }
        function F2(e10, t7) {
          this.dyn_tree = e10, this.max_code = 0, this.stat_desc = t7;
        }
        function N3(e10) {
          return e10 < 256 ? E3[e10] : E3[256 + (e10 >>> 7)];
        }
        function U2(e10, t7) {
          e10.pending_buf[e10.pending++] = 255 & t7, e10.pending_buf[e10.pending++] = t7 >>> 8 & 255;
        }
        function P3(e10, t7, r9) {
          e10.bi_valid > d4 - r9 ? (e10.bi_buf |= t7 << e10.bi_valid & 65535, U2(e10, e10.bi_buf), e10.bi_buf = t7 >> d4 - e10.bi_valid, e10.bi_valid += r9 - d4) : (e10.bi_buf |= t7 << e10.bi_valid & 65535, e10.bi_valid += r9);
        }
        function L3(e10, t7, r9) {
          P3(e10, r9[2 * t7], r9[2 * t7 + 1]);
        }
        function j3(e10, t7) {
          for (var r9 = 0; r9 |= 1 & e10, e10 >>>= 1, r9 <<= 1, 0 < --t7; ) ;
          return r9 >>> 1;
        }
        function Z2(e10, t7, r9) {
          var n8, i8, s7 = new Array(g3 + 1), a4 = 0;
          for (n8 = 1; n8 <= g3; n8++) s7[n8] = a4 = a4 + r9[n8 - 1] << 1;
          for (i8 = 0; i8 <= t7; i8++) {
            var o10 = e10[2 * i8 + 1];
            0 !== o10 && (e10[2 * i8] = j3(s7[o10]++, o10));
          }
        }
        function W2(e10) {
          var t7;
          for (t7 = 0; t7 < l5; t7++) e10.dyn_ltree[2 * t7] = 0;
          for (t7 = 0; t7 < f4; t7++) e10.dyn_dtree[2 * t7] = 0;
          for (t7 = 0; t7 < c6; t7++) e10.bl_tree[2 * t7] = 0;
          e10.dyn_ltree[2 * m4] = 1, e10.opt_len = e10.static_len = 0, e10.last_lit = e10.matches = 0;
        }
        function M4(e10) {
          8 < e10.bi_valid ? U2(e10, e10.bi_buf) : 0 < e10.bi_valid && (e10.pending_buf[e10.pending++] = e10.bi_buf), e10.bi_buf = 0, e10.bi_valid = 0;
        }
        function H2(e10, t7, r9, n8) {
          var i8 = 2 * t7, s7 = 2 * r9;
          return e10[i8] < e10[s7] || e10[i8] === e10[s7] && n8[t7] <= n8[r9];
        }
        function G2(e10, t7, r9) {
          for (var n8 = e10.heap[r9], i8 = r9 << 1; i8 <= e10.heap_len && (i8 < e10.heap_len && H2(t7, e10.heap[i8 + 1], e10.heap[i8], e10.depth) && i8++, !H2(t7, n8, e10.heap[i8], e10.depth)); ) e10.heap[r9] = e10.heap[i8], r9 = i8, i8 <<= 1;
          e10.heap[r9] = n8;
        }
        function K2(e10, t7, r9) {
          var n8, i8, s7, a4, o10 = 0;
          if (0 !== e10.last_lit) for (; n8 = e10.pending_buf[e10.d_buf + 2 * o10] << 8 | e10.pending_buf[e10.d_buf + 2 * o10 + 1], i8 = e10.pending_buf[e10.l_buf + o10], o10++, 0 === n8 ? L3(e10, i8, t7) : (L3(e10, (s7 = A2[i8]) + u5 + 1, t7), 0 !== (a4 = w3[s7]) && P3(e10, i8 -= I3[s7], a4), L3(e10, s7 = N3(--n8), r9), 0 !== (a4 = k2[s7]) && P3(e10, n8 -= T3[s7], a4)), o10 < e10.last_lit; ) ;
          L3(e10, m4, t7);
        }
        function Y(e10, t7) {
          var r9, n8, i8, s7 = t7.dyn_tree, a4 = t7.stat_desc.static_tree, o10 = t7.stat_desc.has_stree, h8 = t7.stat_desc.elems, u6 = -1;
          for (e10.heap_len = 0, e10.heap_max = _3, r9 = 0; r9 < h8; r9++) 0 !== s7[2 * r9] ? (e10.heap[++e10.heap_len] = u6 = r9, e10.depth[r9] = 0) : s7[2 * r9 + 1] = 0;
          for (; e10.heap_len < 2; ) s7[2 * (i8 = e10.heap[++e10.heap_len] = u6 < 2 ? ++u6 : 0)] = 1, e10.depth[i8] = 0, e10.opt_len--, o10 && (e10.static_len -= a4[2 * i8 + 1]);
          for (t7.max_code = u6, r9 = e10.heap_len >> 1; 1 <= r9; r9--) G2(e10, s7, r9);
          for (i8 = h8; r9 = e10.heap[1], e10.heap[1] = e10.heap[e10.heap_len--], G2(e10, s7, 1), n8 = e10.heap[1], e10.heap[--e10.heap_max] = r9, e10.heap[--e10.heap_max] = n8, s7[2 * i8] = s7[2 * r9] + s7[2 * n8], e10.depth[i8] = (e10.depth[r9] >= e10.depth[n8] ? e10.depth[r9] : e10.depth[n8]) + 1, s7[2 * r9 + 1] = s7[2 * n8 + 1] = i8, e10.heap[1] = i8++, G2(e10, s7, 1), 2 <= e10.heap_len; ) ;
          e10.heap[--e10.heap_max] = e10.heap[1], (function(e11, t8) {
            var r10, n9, i9, s8, a5, o11, h9 = t8.dyn_tree, u7 = t8.max_code, l6 = t8.stat_desc.static_tree, f5 = t8.stat_desc.has_stree, c7 = t8.stat_desc.extra_bits, d5 = t8.stat_desc.extra_base, p5 = t8.stat_desc.max_length, m5 = 0;
            for (s8 = 0; s8 <= g3; s8++) e11.bl_count[s8] = 0;
            for (h9[2 * e11.heap[e11.heap_max] + 1] = 0, r10 = e11.heap_max + 1; r10 < _3; r10++) p5 < (s8 = h9[2 * h9[2 * (n9 = e11.heap[r10]) + 1] + 1] + 1) && (s8 = p5, m5++), h9[2 * n9 + 1] = s8, u7 < n9 || (e11.bl_count[s8]++, a5 = 0, d5 <= n9 && (a5 = c7[n9 - d5]), o11 = h9[2 * n9], e11.opt_len += o11 * (s8 + a5), f5 && (e11.static_len += o11 * (l6[2 * n9 + 1] + a5)));
            if (0 !== m5) {
              do {
                for (s8 = p5 - 1; 0 === e11.bl_count[s8]; ) s8--;
                e11.bl_count[s8]--, e11.bl_count[s8 + 1] += 2, e11.bl_count[p5]--, m5 -= 2;
              } while (0 < m5);
              for (s8 = p5; 0 !== s8; s8--) for (n9 = e11.bl_count[s8]; 0 !== n9; ) u7 < (i9 = e11.heap[--r10]) || (h9[2 * i9 + 1] !== s8 && (e11.opt_len += (s8 - h9[2 * i9 + 1]) * h9[2 * i9], h9[2 * i9 + 1] = s8), n9--);
            }
          })(e10, t7), Z2(s7, u6, e10.bl_count);
        }
        function X3(e10, t7, r9) {
          var n8, i8, s7 = -1, a4 = t7[1], o10 = 0, h8 = 7, u6 = 4;
          for (0 === a4 && (h8 = 138, u6 = 3), t7[2 * (r9 + 1) + 1] = 65535, n8 = 0; n8 <= r9; n8++) i8 = a4, a4 = t7[2 * (n8 + 1) + 1], ++o10 < h8 && i8 === a4 || (o10 < u6 ? e10.bl_tree[2 * i8] += o10 : 0 !== i8 ? (i8 !== s7 && e10.bl_tree[2 * i8]++, e10.bl_tree[2 * b4]++) : o10 <= 10 ? e10.bl_tree[2 * v4]++ : e10.bl_tree[2 * y4]++, s7 = i8, u6 = (o10 = 0) === a4 ? (h8 = 138, 3) : i8 === a4 ? (h8 = 6, 3) : (h8 = 7, 4));
        }
        function V3(e10, t7, r9) {
          var n8, i8, s7 = -1, a4 = t7[1], o10 = 0, h8 = 7, u6 = 4;
          for (0 === a4 && (h8 = 138, u6 = 3), n8 = 0; n8 <= r9; n8++) if (i8 = a4, a4 = t7[2 * (n8 + 1) + 1], !(++o10 < h8 && i8 === a4)) {
            if (o10 < u6) for (; L3(e10, i8, e10.bl_tree), 0 != --o10; ) ;
            else 0 !== i8 ? (i8 !== s7 && (L3(e10, i8, e10.bl_tree), o10--), L3(e10, b4, e10.bl_tree), P3(e10, o10 - 3, 2)) : o10 <= 10 ? (L3(e10, v4, e10.bl_tree), P3(e10, o10 - 3, 3)) : (L3(e10, y4, e10.bl_tree), P3(e10, o10 - 11, 7));
            s7 = i8, u6 = (o10 = 0) === a4 ? (h8 = 138, 3) : i8 === a4 ? (h8 = 6, 3) : (h8 = 7, 4);
          }
        }
        n7(T3);
        var q2 = false;
        function J2(e10, t7, r9, n8) {
          P3(e10, (s6 << 1) + (n8 ? 1 : 0), 3), (function(e11, t8, r10, n9) {
            M4(e11), n9 && (U2(e11, r10), U2(e11, ~r10)), i7.arraySet(e11.pending_buf, e11.window, t8, r10, e11.pending), e11.pending += r10;
          })(e10, t7, r9, true);
        }
        r8._tr_init = function(e10) {
          q2 || ((function() {
            var e11, t7, r9, n8, i8, s7 = new Array(g3 + 1);
            for (n8 = r9 = 0; n8 < a3 - 1; n8++) for (I3[n8] = r9, e11 = 0; e11 < 1 << w3[n8]; e11++) A2[r9++] = n8;
            for (A2[r9 - 1] = n8, n8 = i8 = 0; n8 < 16; n8++) for (T3[n8] = i8, e11 = 0; e11 < 1 << k2[n8]; e11++) E3[i8++] = n8;
            for (i8 >>= 7; n8 < f4; n8++) for (T3[n8] = i8 << 7, e11 = 0; e11 < 1 << k2[n8] - 7; e11++) E3[256 + i8++] = n8;
            for (t7 = 0; t7 <= g3; t7++) s7[t7] = 0;
            for (e11 = 0; e11 <= 143; ) z3[2 * e11 + 1] = 8, e11++, s7[8]++;
            for (; e11 <= 255; ) z3[2 * e11 + 1] = 9, e11++, s7[9]++;
            for (; e11 <= 279; ) z3[2 * e11 + 1] = 7, e11++, s7[7]++;
            for (; e11 <= 287; ) z3[2 * e11 + 1] = 8, e11++, s7[8]++;
            for (Z2(z3, l5 + 1, s7), e11 = 0; e11 < f4; e11++) C3[2 * e11 + 1] = 5, C3[2 * e11] = j3(e11, 5);
            O2 = new D4(z3, w3, u5 + 1, l5, g3), B3 = new D4(C3, k2, 0, f4, g3), R3 = new D4(new Array(0), x2, 0, c6, p4);
          })(), q2 = true), e10.l_desc = new F2(e10.dyn_ltree, O2), e10.d_desc = new F2(e10.dyn_dtree, B3), e10.bl_desc = new F2(e10.bl_tree, R3), e10.bi_buf = 0, e10.bi_valid = 0, W2(e10);
        }, r8._tr_stored_block = J2, r8._tr_flush_block = function(e10, t7, r9, n8) {
          var i8, s7, a4 = 0;
          0 < e10.level ? (2 === e10.strm.data_type && (e10.strm.data_type = (function(e11) {
            var t8, r10 = 4093624447;
            for (t8 = 0; t8 <= 31; t8++, r10 >>>= 1) if (1 & r10 && 0 !== e11.dyn_ltree[2 * t8]) return o9;
            if (0 !== e11.dyn_ltree[18] || 0 !== e11.dyn_ltree[20] || 0 !== e11.dyn_ltree[26]) return h7;
            for (t8 = 32; t8 < u5; t8++) if (0 !== e11.dyn_ltree[2 * t8]) return h7;
            return o9;
          })(e10)), Y(e10, e10.l_desc), Y(e10, e10.d_desc), a4 = (function(e11) {
            var t8;
            for (X3(e11, e11.dyn_ltree, e11.l_desc.max_code), X3(e11, e11.dyn_dtree, e11.d_desc.max_code), Y(e11, e11.bl_desc), t8 = c6 - 1; 3 <= t8 && 0 === e11.bl_tree[2 * S5[t8] + 1]; t8--) ;
            return e11.opt_len += 3 * (t8 + 1) + 5 + 5 + 4, t8;
          })(e10), i8 = e10.opt_len + 3 + 7 >>> 3, (s7 = e10.static_len + 3 + 7 >>> 3) <= i8 && (i8 = s7)) : i8 = s7 = r9 + 5, r9 + 4 <= i8 && -1 !== t7 ? J2(e10, t7, r9, n8) : 4 === e10.strategy || s7 === i8 ? (P3(e10, 2 + (n8 ? 1 : 0), 3), K2(e10, z3, C3)) : (P3(e10, 4 + (n8 ? 1 : 0), 3), (function(e11, t8, r10, n9) {
            var i9;
            for (P3(e11, t8 - 257, 5), P3(e11, r10 - 1, 5), P3(e11, n9 - 4, 4), i9 = 0; i9 < n9; i9++) P3(e11, e11.bl_tree[2 * S5[i9] + 1], 3);
            V3(e11, e11.dyn_ltree, t8 - 1), V3(e11, e11.dyn_dtree, r10 - 1);
          })(e10, e10.l_desc.max_code + 1, e10.d_desc.max_code + 1, a4 + 1), K2(e10, e10.dyn_ltree, e10.dyn_dtree)), W2(e10), n8 && M4(e10);
        }, r8._tr_tally = function(e10, t7, r9) {
          return e10.pending_buf[e10.d_buf + 2 * e10.last_lit] = t7 >>> 8 & 255, e10.pending_buf[e10.d_buf + 2 * e10.last_lit + 1] = 255 & t7, e10.pending_buf[e10.l_buf + e10.last_lit] = 255 & r9, e10.last_lit++, 0 === t7 ? e10.dyn_ltree[2 * r9]++ : (e10.matches++, t7--, e10.dyn_ltree[2 * (A2[r9] + u5 + 1)]++, e10.dyn_dtree[2 * N3(t7)]++), e10.last_lit === e10.lit_bufsize - 1;
        }, r8._tr_align = function(e10) {
          P3(e10, 2, 3), L3(e10, m4, z3), (function(e11) {
            16 === e11.bi_valid ? (U2(e11, e11.bi_buf), e11.bi_buf = 0, e11.bi_valid = 0) : 8 <= e11.bi_valid && (e11.pending_buf[e11.pending++] = 255 & e11.bi_buf, e11.bi_buf >>= 8, e11.bi_valid -= 8);
          })(e10);
        };
      }, { "../utils/common": 41 }], 53: [function(e9, t6, r8) {
        "use strict";
        t6.exports = function() {
          this.input = null, this.next_in = 0, this.avail_in = 0, this.total_in = 0, this.output = null, this.next_out = 0, this.avail_out = 0, this.total_out = 0, this.msg = "", this.state = null, this.data_type = 2, this.adler = 0;
        };
      }, {}], 54: [function(e9, t6, r8) {
        (function(e10) {
          !(function(r9, n7) {
            "use strict";
            if (!r9.setImmediate) {
              var i7, s6, t7, a3, o9 = 1, h7 = {}, u5 = false, l5 = r9.document, e11 = Object.getPrototypeOf && Object.getPrototypeOf(r9);
              e11 = e11 && e11.setTimeout ? e11 : r9, i7 = "[object process]" === {}.toString.call(r9.process) ? function(e12) {
                process.nextTick(function() {
                  c6(e12);
                });
              } : (function() {
                if (r9.postMessage && !r9.importScripts) {
                  var e12 = true, t8 = r9.onmessage;
                  return r9.onmessage = function() {
                    e12 = false;
                  }, r9.postMessage("", "*"), r9.onmessage = t8, e12;
                }
              })() ? (a3 = "setImmediate$" + Math.random() + "$", r9.addEventListener ? r9.addEventListener("message", d4, false) : r9.attachEvent("onmessage", d4), function(e12) {
                r9.postMessage(a3 + e12, "*");
              }) : r9.MessageChannel ? ((t7 = new MessageChannel()).port1.onmessage = function(e12) {
                c6(e12.data);
              }, function(e12) {
                t7.port2.postMessage(e12);
              }) : l5 && "onreadystatechange" in l5.createElement("script") ? (s6 = l5.documentElement, function(e12) {
                var t8 = l5.createElement("script");
                t8.onreadystatechange = function() {
                  c6(e12), t8.onreadystatechange = null, s6.removeChild(t8), t8 = null;
                }, s6.appendChild(t8);
              }) : function(e12) {
                setTimeout(c6, 0, e12);
              }, e11.setImmediate = function(e12) {
                "function" != typeof e12 && (e12 = new Function("" + e12));
                for (var t8 = new Array(arguments.length - 1), r10 = 0; r10 < t8.length; r10++) t8[r10] = arguments[r10 + 1];
                var n8 = { callback: e12, args: t8 };
                return h7[o9] = n8, i7(o9), o9++;
              }, e11.clearImmediate = f4;
            }
            function f4(e12) {
              delete h7[e12];
            }
            function c6(e12) {
              if (u5) setTimeout(c6, 0, e12);
              else {
                var t8 = h7[e12];
                if (t8) {
                  u5 = true;
                  try {
                    !(function(e13) {
                      var t9 = e13.callback, r10 = e13.args;
                      switch (r10.length) {
                        case 0:
                          t9();
                          break;
                        case 1:
                          t9(r10[0]);
                          break;
                        case 2:
                          t9(r10[0], r10[1]);
                          break;
                        case 3:
                          t9(r10[0], r10[1], r10[2]);
                          break;
                        default:
                          t9.apply(n7, r10);
                      }
                    })(t8);
                  } finally {
                    f4(e12), u5 = false;
                  }
                }
              }
            }
            function d4(e12) {
              e12.source === r9 && "string" == typeof e12.data && 0 === e12.data.indexOf(a3) && c6(+e12.data.slice(a3.length));
            }
          })("undefined" == typeof self ? void 0 === e10 ? this : e10 : self);
        }).call(this, "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : "undefined" != typeof window ? window : {});
      }, {}] }, {}, [10])(10);
    });
  }
});

// ../pi-mono/node_modules/highlight.js/lib/core.js
var require_core3 = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/core.js"(exports, module) {
    init_process_shim();
    function deepFreeze(obj) {
      if (obj instanceof Map) {
        obj.clear = obj.delete = obj.set = function() {
          throw new Error("map is read-only");
        };
      } else if (obj instanceof Set) {
        obj.add = obj.clear = obj.delete = function() {
          throw new Error("set is read-only");
        };
      }
      Object.freeze(obj);
      Object.getOwnPropertyNames(obj).forEach(function(name) {
        var prop = obj[name];
        if (typeof prop == "object" && !Object.isFrozen(prop)) {
          deepFreeze(prop);
        }
      });
      return obj;
    }
    var deepFreezeEs6 = deepFreeze;
    var _default = deepFreeze;
    deepFreezeEs6.default = _default;
    var Response3 = class {
      /**
       * @param {CompiledMode} mode
       */
      constructor(mode) {
        if (mode.data === void 0) mode.data = {};
        this.data = mode.data;
        this.isMatchIgnored = false;
      }
      ignoreMatch() {
        this.isMatchIgnored = true;
      }
    };
    function escapeHTML(value) {
      return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#x27;");
    }
    function inherit(original, ...objects) {
      const result = /* @__PURE__ */ Object.create(null);
      for (const key in original) {
        result[key] = original[key];
      }
      objects.forEach(function(obj) {
        for (const key in obj) {
          result[key] = obj[key];
        }
      });
      return (
        /** @type {T} */
        result
      );
    }
    var SPAN_CLOSE = "</span>";
    var emitsWrappingTags = (node) => {
      return !!node.kind;
    };
    var HTMLRenderer = class {
      /**
       * Creates a new HTMLRenderer
       *
       * @param {Tree} parseTree - the parse tree (must support `walk` API)
       * @param {{classPrefix: string}} options
       */
      constructor(parseTree3, options) {
        this.buffer = "";
        this.classPrefix = options.classPrefix;
        parseTree3.walk(this);
      }
      /**
       * Adds texts to the output stream
       *
       * @param {string} text */
      addText(text3) {
        this.buffer += escapeHTML(text3);
      }
      /**
       * Adds a node open to the output stream (if needed)
       *
       * @param {Node} node */
      openNode(node) {
        if (!emitsWrappingTags(node)) return;
        let className = node.kind;
        if (!node.sublanguage) {
          className = `${this.classPrefix}${className}`;
        }
        this.span(className);
      }
      /**
       * Adds a node close to the output stream (if needed)
       *
       * @param {Node} node */
      closeNode(node) {
        if (!emitsWrappingTags(node)) return;
        this.buffer += SPAN_CLOSE;
      }
      /**
       * returns the accumulated buffer
      */
      value() {
        return this.buffer;
      }
      // helpers
      /**
       * Builds a span element
       *
       * @param {string} className */
      span(className) {
        this.buffer += `<span class="${className}">`;
      }
    };
    var TokenTree = class _TokenTree {
      constructor() {
        this.rootNode = { children: [] };
        this.stack = [this.rootNode];
      }
      get top() {
        return this.stack[this.stack.length - 1];
      }
      get root() {
        return this.rootNode;
      }
      /** @param {Node} node */
      add(node) {
        this.top.children.push(node);
      }
      /** @param {string} kind */
      openNode(kind) {
        const node = { kind, children: [] };
        this.add(node);
        this.stack.push(node);
      }
      closeNode() {
        if (this.stack.length > 1) {
          return this.stack.pop();
        }
        return void 0;
      }
      closeAllNodes() {
        while (this.closeNode()) ;
      }
      toJSON() {
        return JSON.stringify(this.rootNode, null, 4);
      }
      /**
       * @typedef { import("./html_renderer").Renderer } Renderer
       * @param {Renderer} builder
       */
      walk(builder) {
        return this.constructor._walk(builder, this.rootNode);
      }
      /**
       * @param {Renderer} builder
       * @param {Node} node
       */
      static _walk(builder, node) {
        if (typeof node === "string") {
          builder.addText(node);
        } else if (node.children) {
          builder.openNode(node);
          node.children.forEach((child) => this._walk(builder, child));
          builder.closeNode(node);
        }
        return builder;
      }
      /**
       * @param {Node} node
       */
      static _collapse(node) {
        if (typeof node === "string") return;
        if (!node.children) return;
        if (node.children.every((el) => typeof el === "string")) {
          node.children = [node.children.join("")];
        } else {
          node.children.forEach((child) => {
            _TokenTree._collapse(child);
          });
        }
      }
    };
    var TokenTreeEmitter = class extends TokenTree {
      /**
       * @param {*} options
       */
      constructor(options) {
        super();
        this.options = options;
      }
      /**
       * @param {string} text
       * @param {string} kind
       */
      addKeyword(text3, kind) {
        if (text3 === "") {
          return;
        }
        this.openNode(kind);
        this.addText(text3);
        this.closeNode();
      }
      /**
       * @param {string} text
       */
      addText(text3) {
        if (text3 === "") {
          return;
        }
        this.add(text3);
      }
      /**
       * @param {Emitter & {root: DataNode}} emitter
       * @param {string} name
       */
      addSublanguage(emitter, name) {
        const node = emitter.root;
        node.kind = name;
        node.sublanguage = true;
        this.add(node);
      }
      toHTML() {
        const renderer = new HTMLRenderer(this, this.options);
        return renderer.value();
      }
      finalize() {
        return true;
      }
    };
    function escape4(value) {
      return new RegExp(value.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&"), "m");
    }
    function source(re2) {
      if (!re2) return null;
      if (typeof re2 === "string") return re2;
      return re2.source;
    }
    function concat(...args) {
      const joined = args.map((x2) => source(x2)).join("");
      return joined;
    }
    function either(...args) {
      const joined = "(" + args.map((x2) => source(x2)).join("|") + ")";
      return joined;
    }
    function countMatchGroups(re2) {
      return new RegExp(re2.toString() + "|").exec("").length - 1;
    }
    function startsWith(re2, lexeme) {
      const match2 = re2 && re2.exec(lexeme);
      return match2 && match2.index === 0;
    }
    var BACKREF_RE = /\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./;
    function join(regexps, separator = "|") {
      let numCaptures = 0;
      return regexps.map((regex) => {
        numCaptures += 1;
        const offset = numCaptures;
        let re2 = source(regex);
        let out = "";
        while (re2.length > 0) {
          const match2 = BACKREF_RE.exec(re2);
          if (!match2) {
            out += re2;
            break;
          }
          out += re2.substring(0, match2.index);
          re2 = re2.substring(match2.index + match2[0].length);
          if (match2[0][0] === "\\" && match2[1]) {
            out += "\\" + String(Number(match2[1]) + offset);
          } else {
            out += match2[0];
            if (match2[0] === "(") {
              numCaptures++;
            }
          }
        }
        return out;
      }).map((re2) => `(${re2})`).join(separator);
    }
    var MATCH_NOTHING_RE = /\b\B/;
    var IDENT_RE3 = "[a-zA-Z]\\w*";
    var UNDERSCORE_IDENT_RE = "[a-zA-Z_]\\w*";
    var NUMBER_RE = "\\b\\d+(\\.\\d+)?";
    var C_NUMBER_RE = "(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)";
    var BINARY_NUMBER_RE = "\\b(0b[01]+)";
    var RE_STARTERS_RE = "!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~";
    var SHEBANG = (opts = {}) => {
      const beginShebang = /^#![ ]*\//;
      if (opts.binary) {
        opts.begin = concat(
          beginShebang,
          /.*\b/,
          opts.binary,
          /\b.*/
        );
      }
      return inherit({
        className: "meta",
        begin: beginShebang,
        end: /$/,
        relevance: 0,
        /** @type {ModeCallback} */
        "on:begin": (m4, resp) => {
          if (m4.index !== 0) resp.ignoreMatch();
        }
      }, opts);
    };
    var BACKSLASH_ESCAPE = {
      begin: "\\\\[\\s\\S]",
      relevance: 0
    };
    var APOS_STRING_MODE = {
      className: "string",
      begin: "'",
      end: "'",
      illegal: "\\n",
      contains: [BACKSLASH_ESCAPE]
    };
    var QUOTE_STRING_MODE = {
      className: "string",
      begin: '"',
      end: '"',
      illegal: "\\n",
      contains: [BACKSLASH_ESCAPE]
    };
    var PHRASAL_WORDS_MODE = {
      begin: /\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/
    };
    var COMMENT = function(begin, end, modeOptions = {}) {
      const mode = inherit(
        {
          className: "comment",
          begin,
          end,
          contains: []
        },
        modeOptions
      );
      mode.contains.push(PHRASAL_WORDS_MODE);
      mode.contains.push({
        className: "doctag",
        begin: "(?:TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):",
        relevance: 0
      });
      return mode;
    };
    var C_LINE_COMMENT_MODE = COMMENT("//", "$");
    var C_BLOCK_COMMENT_MODE = COMMENT("/\\*", "\\*/");
    var HASH_COMMENT_MODE = COMMENT("#", "$");
    var NUMBER_MODE = {
      className: "number",
      begin: NUMBER_RE,
      relevance: 0
    };
    var C_NUMBER_MODE = {
      className: "number",
      begin: C_NUMBER_RE,
      relevance: 0
    };
    var BINARY_NUMBER_MODE = {
      className: "number",
      begin: BINARY_NUMBER_RE,
      relevance: 0
    };
    var CSS_NUMBER_MODE = {
      className: "number",
      begin: NUMBER_RE + "(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",
      relevance: 0
    };
    var REGEXP_MODE = {
      // this outer rule makes sure we actually have a WHOLE regex and not simply
      // an expression such as:
      //
      //     3 / something
      //
      // (which will then blow up when regex's `illegal` sees the newline)
      begin: /(?=\/[^/\n]*\/)/,
      contains: [{
        className: "regexp",
        begin: /\//,
        end: /\/[gimuy]*/,
        illegal: /\n/,
        contains: [
          BACKSLASH_ESCAPE,
          {
            begin: /\[/,
            end: /\]/,
            relevance: 0,
            contains: [BACKSLASH_ESCAPE]
          }
        ]
      }]
    };
    var TITLE_MODE = {
      className: "title",
      begin: IDENT_RE3,
      relevance: 0
    };
    var UNDERSCORE_TITLE_MODE = {
      className: "title",
      begin: UNDERSCORE_IDENT_RE,
      relevance: 0
    };
    var METHOD_GUARD = {
      // excludes method names from keyword processing
      begin: "\\.\\s*" + UNDERSCORE_IDENT_RE,
      relevance: 0
    };
    var END_SAME_AS_BEGIN = function(mode) {
      return Object.assign(
        mode,
        {
          /** @type {ModeCallback} */
          "on:begin": (m4, resp) => {
            resp.data._beginMatch = m4[1];
          },
          /** @type {ModeCallback} */
          "on:end": (m4, resp) => {
            if (resp.data._beginMatch !== m4[1]) resp.ignoreMatch();
          }
        }
      );
    };
    var MODES2 = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      MATCH_NOTHING_RE,
      IDENT_RE: IDENT_RE3,
      UNDERSCORE_IDENT_RE,
      NUMBER_RE,
      C_NUMBER_RE,
      BINARY_NUMBER_RE,
      RE_STARTERS_RE,
      SHEBANG,
      BACKSLASH_ESCAPE,
      APOS_STRING_MODE,
      QUOTE_STRING_MODE,
      PHRASAL_WORDS_MODE,
      COMMENT,
      C_LINE_COMMENT_MODE,
      C_BLOCK_COMMENT_MODE,
      HASH_COMMENT_MODE,
      NUMBER_MODE,
      C_NUMBER_MODE,
      BINARY_NUMBER_MODE,
      CSS_NUMBER_MODE,
      REGEXP_MODE,
      TITLE_MODE,
      UNDERSCORE_TITLE_MODE,
      METHOD_GUARD,
      END_SAME_AS_BEGIN
    });
    function skipIfhasPrecedingDot(match2, response) {
      const before = match2.input[match2.index - 1];
      if (before === ".") {
        response.ignoreMatch();
      }
    }
    function beginKeywords(mode, parent) {
      if (!parent) return;
      if (!mode.beginKeywords) return;
      mode.begin = "\\b(" + mode.beginKeywords.split(" ").join("|") + ")(?!\\.)(?=\\b|\\s)";
      mode.__beforeBegin = skipIfhasPrecedingDot;
      mode.keywords = mode.keywords || mode.beginKeywords;
      delete mode.beginKeywords;
      if (mode.relevance === void 0) mode.relevance = 0;
    }
    function compileIllegal(mode, _parent) {
      if (!Array.isArray(mode.illegal)) return;
      mode.illegal = either(...mode.illegal);
    }
    function compileMatch(mode, _parent) {
      if (!mode.match) return;
      if (mode.begin || mode.end) throw new Error("begin & end are not supported with match");
      mode.begin = mode.match;
      delete mode.match;
    }
    function compileRelevance(mode, _parent) {
      if (mode.relevance === void 0) mode.relevance = 1;
    }
    var COMMON_KEYWORDS = [
      "of",
      "and",
      "for",
      "in",
      "not",
      "or",
      "if",
      "then",
      "parent",
      // common variable name
      "list",
      // common variable name
      "value"
      // common variable name
    ];
    var DEFAULT_KEYWORD_CLASSNAME = "keyword";
    function compileKeywords(rawKeywords, caseInsensitive, className = DEFAULT_KEYWORD_CLASSNAME) {
      const compiledKeywords = {};
      if (typeof rawKeywords === "string") {
        compileList(className, rawKeywords.split(" "));
      } else if (Array.isArray(rawKeywords)) {
        compileList(className, rawKeywords);
      } else {
        Object.keys(rawKeywords).forEach(function(className2) {
          Object.assign(
            compiledKeywords,
            compileKeywords(rawKeywords[className2], caseInsensitive, className2)
          );
        });
      }
      return compiledKeywords;
      function compileList(className2, keywordList) {
        if (caseInsensitive) {
          keywordList = keywordList.map((x2) => x2.toLowerCase());
        }
        keywordList.forEach(function(keyword) {
          const pair = keyword.split("|");
          compiledKeywords[pair[0]] = [className2, scoreForKeyword(pair[0], pair[1])];
        });
      }
    }
    function scoreForKeyword(keyword, providedScore) {
      if (providedScore) {
        return Number(providedScore);
      }
      return commonKeyword(keyword) ? 0 : 1;
    }
    function commonKeyword(keyword) {
      return COMMON_KEYWORDS.includes(keyword.toLowerCase());
    }
    function compileLanguage(language, { plugins: plugins2 }) {
      function langRe(value, global2) {
        return new RegExp(
          source(value),
          "m" + (language.case_insensitive ? "i" : "") + (global2 ? "g" : "")
        );
      }
      class MultiRegex {
        constructor() {
          this.matchIndexes = {};
          this.regexes = [];
          this.matchAt = 1;
          this.position = 0;
        }
        // @ts-ignore
        addRule(re2, opts) {
          opts.position = this.position++;
          this.matchIndexes[this.matchAt] = opts;
          this.regexes.push([opts, re2]);
          this.matchAt += countMatchGroups(re2) + 1;
        }
        compile() {
          if (this.regexes.length === 0) {
            this.exec = () => null;
          }
          const terminators = this.regexes.map((el) => el[1]);
          this.matcherRe = langRe(join(terminators), true);
          this.lastIndex = 0;
        }
        /** @param {string} s */
        exec(s6) {
          this.matcherRe.lastIndex = this.lastIndex;
          const match2 = this.matcherRe.exec(s6);
          if (!match2) {
            return null;
          }
          const i7 = match2.findIndex((el, i8) => i8 > 0 && el !== void 0);
          const matchData = this.matchIndexes[i7];
          match2.splice(0, i7);
          return Object.assign(match2, matchData);
        }
      }
      class ResumableMultiRegex {
        constructor() {
          this.rules = [];
          this.multiRegexes = [];
          this.count = 0;
          this.lastIndex = 0;
          this.regexIndex = 0;
        }
        // @ts-ignore
        getMatcher(index) {
          if (this.multiRegexes[index]) return this.multiRegexes[index];
          const matcher = new MultiRegex();
          this.rules.slice(index).forEach(([re2, opts]) => matcher.addRule(re2, opts));
          matcher.compile();
          this.multiRegexes[index] = matcher;
          return matcher;
        }
        resumingScanAtSamePosition() {
          return this.regexIndex !== 0;
        }
        considerAll() {
          this.regexIndex = 0;
        }
        // @ts-ignore
        addRule(re2, opts) {
          this.rules.push([re2, opts]);
          if (opts.type === "begin") this.count++;
        }
        /** @param {string} s */
        exec(s6) {
          const m4 = this.getMatcher(this.regexIndex);
          m4.lastIndex = this.lastIndex;
          let result = m4.exec(s6);
          if (this.resumingScanAtSamePosition()) {
            if (result && result.index === this.lastIndex) ;
            else {
              const m22 = this.getMatcher(0);
              m22.lastIndex = this.lastIndex + 1;
              result = m22.exec(s6);
            }
          }
          if (result) {
            this.regexIndex += result.position + 1;
            if (this.regexIndex === this.count) {
              this.considerAll();
            }
          }
          return result;
        }
      }
      function buildModeRegex(mode) {
        const mm = new ResumableMultiRegex();
        mode.contains.forEach((term) => mm.addRule(term.begin, { rule: term, type: "begin" }));
        if (mode.terminatorEnd) {
          mm.addRule(mode.terminatorEnd, { type: "end" });
        }
        if (mode.illegal) {
          mm.addRule(mode.illegal, { type: "illegal" });
        }
        return mm;
      }
      function compileMode(mode, parent) {
        const cmode = (
          /** @type CompiledMode */
          mode
        );
        if (mode.isCompiled) return cmode;
        [
          // do this early so compiler extensions generally don't have to worry about
          // the distinction between match/begin
          compileMatch
        ].forEach((ext2) => ext2(mode, parent));
        language.compilerExtensions.forEach((ext2) => ext2(mode, parent));
        mode.__beforeBegin = null;
        [
          beginKeywords,
          // do this later so compiler extensions that come earlier have access to the
          // raw array if they wanted to perhaps manipulate it, etc.
          compileIllegal,
          // default to 1 relevance if not specified
          compileRelevance
        ].forEach((ext2) => ext2(mode, parent));
        mode.isCompiled = true;
        let keywordPattern = null;
        if (typeof mode.keywords === "object") {
          keywordPattern = mode.keywords.$pattern;
          delete mode.keywords.$pattern;
        }
        if (mode.keywords) {
          mode.keywords = compileKeywords(mode.keywords, language.case_insensitive);
        }
        if (mode.lexemes && keywordPattern) {
          throw new Error("ERR: Prefer `keywords.$pattern` to `mode.lexemes`, BOTH are not allowed. (see mode reference) ");
        }
        keywordPattern = keywordPattern || mode.lexemes || /\w+/;
        cmode.keywordPatternRe = langRe(keywordPattern, true);
        if (parent) {
          if (!mode.begin) mode.begin = /\B|\b/;
          cmode.beginRe = langRe(mode.begin);
          if (mode.endSameAsBegin) mode.end = mode.begin;
          if (!mode.end && !mode.endsWithParent) mode.end = /\B|\b/;
          if (mode.end) cmode.endRe = langRe(mode.end);
          cmode.terminatorEnd = source(mode.end) || "";
          if (mode.endsWithParent && parent.terminatorEnd) {
            cmode.terminatorEnd += (mode.end ? "|" : "") + parent.terminatorEnd;
          }
        }
        if (mode.illegal) cmode.illegalRe = langRe(
          /** @type {RegExp | string} */
          mode.illegal
        );
        if (!mode.contains) mode.contains = [];
        mode.contains = [].concat(...mode.contains.map(function(c6) {
          return expandOrCloneMode(c6 === "self" ? mode : c6);
        }));
        mode.contains.forEach(function(c6) {
          compileMode(
            /** @type Mode */
            c6,
            cmode
          );
        });
        if (mode.starts) {
          compileMode(mode.starts, parent);
        }
        cmode.matcher = buildModeRegex(cmode);
        return cmode;
      }
      if (!language.compilerExtensions) language.compilerExtensions = [];
      if (language.contains && language.contains.includes("self")) {
        throw new Error("ERR: contains `self` is not supported at the top-level of a language.  See documentation.");
      }
      language.classNameAliases = inherit(language.classNameAliases || {});
      return compileMode(
        /** @type Mode */
        language
      );
    }
    function dependencyOnParent(mode) {
      if (!mode) return false;
      return mode.endsWithParent || dependencyOnParent(mode.starts);
    }
    function expandOrCloneMode(mode) {
      if (mode.variants && !mode.cachedVariants) {
        mode.cachedVariants = mode.variants.map(function(variant) {
          return inherit(mode, { variants: null }, variant);
        });
      }
      if (mode.cachedVariants) {
        return mode.cachedVariants;
      }
      if (dependencyOnParent(mode)) {
        return inherit(mode, { starts: mode.starts ? inherit(mode.starts) : null });
      }
      if (Object.isFrozen(mode)) {
        return inherit(mode);
      }
      return mode;
    }
    var version5 = "10.7.3";
    function hasValueOrEmptyAttribute(value) {
      return Boolean(value || value === "");
    }
    function BuildVuePlugin(hljs5) {
      const Component = {
        props: ["language", "code", "autodetect"],
        data: function() {
          return {
            detectedLanguage: "",
            unknownLanguage: false
          };
        },
        computed: {
          className() {
            if (this.unknownLanguage) return "";
            return "hljs " + this.detectedLanguage;
          },
          highlighted() {
            if (!this.autoDetect && !hljs5.getLanguage(this.language)) {
              console.warn(`The language "${this.language}" you specified could not be found.`);
              this.unknownLanguage = true;
              return escapeHTML(this.code);
            }
            let result = {};
            if (this.autoDetect) {
              result = hljs5.highlightAuto(this.code);
              this.detectedLanguage = result.language;
            } else {
              result = hljs5.highlight(this.language, this.code, this.ignoreIllegals);
              this.detectedLanguage = this.language;
            }
            return result.value;
          },
          autoDetect() {
            return !this.language || hasValueOrEmptyAttribute(this.autodetect);
          },
          ignoreIllegals() {
            return true;
          }
        },
        // this avoids needing to use a whole Vue compilation pipeline just
        // to build Highlight.js
        render(createElement2) {
          return createElement2("pre", {}, [
            createElement2("code", {
              class: this.className,
              domProps: { innerHTML: this.highlighted }
            })
          ]);
        }
        // template: `<pre><code :class="className" v-html="highlighted"></code></pre>`
      };
      const VuePlugin = {
        install(Vue) {
          Vue.component("highlightjs", Component);
        }
      };
      return { Component, VuePlugin };
    }
    var mergeHTMLPlugin = {
      "after:highlightElement": ({ el, result, text: text3 }) => {
        const originalStream = nodeStream(el);
        if (!originalStream.length) return;
        const resultNode = document.createElement("div");
        resultNode.innerHTML = result.value;
        result.value = mergeStreams(originalStream, nodeStream(resultNode), text3);
      }
    };
    function tag(node) {
      return node.nodeName.toLowerCase();
    }
    function nodeStream(node) {
      const result = [];
      (function _nodeStream(node2, offset) {
        for (let child = node2.firstChild; child; child = child.nextSibling) {
          if (child.nodeType === 3) {
            offset += child.nodeValue.length;
          } else if (child.nodeType === 1) {
            result.push({
              event: "start",
              offset,
              node: child
            });
            offset = _nodeStream(child, offset);
            if (!tag(child).match(/br|hr|img|input/)) {
              result.push({
                event: "stop",
                offset,
                node: child
              });
            }
          }
        }
        return offset;
      })(node, 0);
      return result;
    }
    function mergeStreams(original, highlighted, value) {
      let processed = 0;
      let result = "";
      const nodeStack = [];
      function selectStream() {
        if (!original.length || !highlighted.length) {
          return original.length ? original : highlighted;
        }
        if (original[0].offset !== highlighted[0].offset) {
          return original[0].offset < highlighted[0].offset ? original : highlighted;
        }
        return highlighted[0].event === "start" ? original : highlighted;
      }
      function open2(node) {
        function attributeString(attr) {
          return " " + attr.nodeName + '="' + escapeHTML(attr.value) + '"';
        }
        result += "<" + tag(node) + [].map.call(node.attributes, attributeString).join("") + ">";
      }
      function close2(node) {
        result += "</" + tag(node) + ">";
      }
      function render3(event) {
        (event.event === "start" ? open2 : close2)(event.node);
      }
      while (original.length || highlighted.length) {
        let stream2 = selectStream();
        result += escapeHTML(value.substring(processed, stream2[0].offset));
        processed = stream2[0].offset;
        if (stream2 === original) {
          nodeStack.reverse().forEach(close2);
          do {
            render3(stream2.splice(0, 1)[0]);
            stream2 = selectStream();
          } while (stream2 === original && stream2.length && stream2[0].offset === processed);
          nodeStack.reverse().forEach(open2);
        } else {
          if (stream2[0].event === "start") {
            nodeStack.push(stream2[0].node);
          } else {
            nodeStack.pop();
          }
          render3(stream2.splice(0, 1)[0]);
        }
      }
      return result + escapeHTML(value.substr(processed));
    }
    var seenDeprecations = {};
    var error = (message) => {
      console.error(message);
    };
    var warn2 = (message, ...args) => {
      console.log(`WARN: ${message}`, ...args);
    };
    var deprecated2 = (version6, message) => {
      if (seenDeprecations[`${version6}/${message}`]) return;
      console.log(`Deprecated as of ${version6}. ${message}`);
      seenDeprecations[`${version6}/${message}`] = true;
    };
    var escape$1 = escapeHTML;
    var inherit$1 = inherit;
    var NO_MATCH = Symbol("nomatch");
    var HLJS = function(hljs5) {
      const languages = /* @__PURE__ */ Object.create(null);
      const aliases = /* @__PURE__ */ Object.create(null);
      const plugins2 = [];
      let SAFE_MODE = true;
      const fixMarkupRe = /(^(<[^>]+>|\t|)+|\n)/gm;
      const LANGUAGE_NOT_FOUND = "Could not find the language '{}', did you forget to load/include a language module?";
      const PLAINTEXT_LANGUAGE = { disableAutodetect: true, name: "Plain text", contains: [] };
      let options = {
        noHighlightRe: /^(no-?highlight)$/i,
        languageDetectRe: /\blang(?:uage)?-([\w-]+)\b/i,
        classPrefix: "hljs-",
        tabReplace: null,
        useBR: false,
        languages: null,
        // beta configuration options, subject to change, welcome to discuss
        // https://github.com/highlightjs/highlight.js/issues/1086
        __emitter: TokenTreeEmitter
      };
      function shouldNotHighlight(languageName) {
        return options.noHighlightRe.test(languageName);
      }
      function blockLanguage(block) {
        let classes = block.className + " ";
        classes += block.parentNode ? block.parentNode.className : "";
        const match2 = options.languageDetectRe.exec(classes);
        if (match2) {
          const language = getLanguage(match2[1]);
          if (!language) {
            warn2(LANGUAGE_NOT_FOUND.replace("{}", match2[1]));
            warn2("Falling back to no-highlight mode for this block.", block);
          }
          return language ? match2[1] : "no-highlight";
        }
        return classes.split(/\s+/).find((_class) => shouldNotHighlight(_class) || getLanguage(_class));
      }
      function highlight2(codeOrlanguageName, optionsOrCode, ignoreIllegals, continuation) {
        let code = "";
        let languageName = "";
        if (typeof optionsOrCode === "object") {
          code = codeOrlanguageName;
          ignoreIllegals = optionsOrCode.ignoreIllegals;
          languageName = optionsOrCode.language;
          continuation = void 0;
        } else {
          deprecated2("10.7.0", "highlight(lang, code, ...args) has been deprecated.");
          deprecated2("10.7.0", "Please use highlight(code, options) instead.\nhttps://github.com/highlightjs/highlight.js/issues/2277");
          languageName = codeOrlanguageName;
          code = optionsOrCode;
        }
        const context = {
          code,
          language: languageName
        };
        fire("before:highlight", context);
        const result = context.result ? context.result : _highlight(context.language, context.code, ignoreIllegals, continuation);
        result.code = context.code;
        fire("after:highlight", result);
        return result;
      }
      function _highlight(languageName, codeToHighlight, ignoreIllegals, continuation) {
        function keywordData(mode, match2) {
          const matchText = language.case_insensitive ? match2[0].toLowerCase() : match2[0];
          return Object.prototype.hasOwnProperty.call(mode.keywords, matchText) && mode.keywords[matchText];
        }
        function processKeywords() {
          if (!top.keywords) {
            emitter.addText(modeBuffer);
            return;
          }
          let lastIndex = 0;
          top.keywordPatternRe.lastIndex = 0;
          let match2 = top.keywordPatternRe.exec(modeBuffer);
          let buf = "";
          while (match2) {
            buf += modeBuffer.substring(lastIndex, match2.index);
            const data = keywordData(top, match2);
            if (data) {
              const [kind, keywordRelevance] = data;
              emitter.addText(buf);
              buf = "";
              relevance += keywordRelevance;
              if (kind.startsWith("_")) {
                buf += match2[0];
              } else {
                const cssClass = language.classNameAliases[kind] || kind;
                emitter.addKeyword(match2[0], cssClass);
              }
            } else {
              buf += match2[0];
            }
            lastIndex = top.keywordPatternRe.lastIndex;
            match2 = top.keywordPatternRe.exec(modeBuffer);
          }
          buf += modeBuffer.substr(lastIndex);
          emitter.addText(buf);
        }
        function processSubLanguage() {
          if (modeBuffer === "") return;
          let result2 = null;
          if (typeof top.subLanguage === "string") {
            if (!languages[top.subLanguage]) {
              emitter.addText(modeBuffer);
              return;
            }
            result2 = _highlight(top.subLanguage, modeBuffer, true, continuations[top.subLanguage]);
            continuations[top.subLanguage] = /** @type {CompiledMode} */
            result2.top;
          } else {
            result2 = highlightAuto(modeBuffer, top.subLanguage.length ? top.subLanguage : null);
          }
          if (top.relevance > 0) {
            relevance += result2.relevance;
          }
          emitter.addSublanguage(result2.emitter, result2.language);
        }
        function processBuffer() {
          if (top.subLanguage != null) {
            processSubLanguage();
          } else {
            processKeywords();
          }
          modeBuffer = "";
        }
        function startNewMode(mode) {
          if (mode.className) {
            emitter.openNode(language.classNameAliases[mode.className] || mode.className);
          }
          top = Object.create(mode, { parent: { value: top } });
          return top;
        }
        function endOfMode(mode, match2, matchPlusRemainder) {
          let matched = startsWith(mode.endRe, matchPlusRemainder);
          if (matched) {
            if (mode["on:end"]) {
              const resp = new Response3(mode);
              mode["on:end"](match2, resp);
              if (resp.isMatchIgnored) matched = false;
            }
            if (matched) {
              while (mode.endsParent && mode.parent) {
                mode = mode.parent;
              }
              return mode;
            }
          }
          if (mode.endsWithParent) {
            return endOfMode(mode.parent, match2, matchPlusRemainder);
          }
        }
        function doIgnore(lexeme) {
          if (top.matcher.regexIndex === 0) {
            modeBuffer += lexeme[0];
            return 1;
          } else {
            resumeScanAtSamePosition = true;
            return 0;
          }
        }
        function doBeginMatch(match2) {
          const lexeme = match2[0];
          const newMode = match2.rule;
          const resp = new Response3(newMode);
          const beforeCallbacks = [newMode.__beforeBegin, newMode["on:begin"]];
          for (const cb of beforeCallbacks) {
            if (!cb) continue;
            cb(match2, resp);
            if (resp.isMatchIgnored) return doIgnore(lexeme);
          }
          if (newMode && newMode.endSameAsBegin) {
            newMode.endRe = escape4(lexeme);
          }
          if (newMode.skip) {
            modeBuffer += lexeme;
          } else {
            if (newMode.excludeBegin) {
              modeBuffer += lexeme;
            }
            processBuffer();
            if (!newMode.returnBegin && !newMode.excludeBegin) {
              modeBuffer = lexeme;
            }
          }
          startNewMode(newMode);
          return newMode.returnBegin ? 0 : lexeme.length;
        }
        function doEndMatch(match2) {
          const lexeme = match2[0];
          const matchPlusRemainder = codeToHighlight.substr(match2.index);
          const endMode = endOfMode(top, match2, matchPlusRemainder);
          if (!endMode) {
            return NO_MATCH;
          }
          const origin = top;
          if (origin.skip) {
            modeBuffer += lexeme;
          } else {
            if (!(origin.returnEnd || origin.excludeEnd)) {
              modeBuffer += lexeme;
            }
            processBuffer();
            if (origin.excludeEnd) {
              modeBuffer = lexeme;
            }
          }
          do {
            if (top.className) {
              emitter.closeNode();
            }
            if (!top.skip && !top.subLanguage) {
              relevance += top.relevance;
            }
            top = top.parent;
          } while (top !== endMode.parent);
          if (endMode.starts) {
            if (endMode.endSameAsBegin) {
              endMode.starts.endRe = endMode.endRe;
            }
            startNewMode(endMode.starts);
          }
          return origin.returnEnd ? 0 : lexeme.length;
        }
        function processContinuations() {
          const list = [];
          for (let current2 = top; current2 !== language; current2 = current2.parent) {
            if (current2.className) {
              list.unshift(current2.className);
            }
          }
          list.forEach((item) => emitter.openNode(item));
        }
        let lastMatch = {};
        function processLexeme(textBeforeMatch, match2) {
          const lexeme = match2 && match2[0];
          modeBuffer += textBeforeMatch;
          if (lexeme == null) {
            processBuffer();
            return 0;
          }
          if (lastMatch.type === "begin" && match2.type === "end" && lastMatch.index === match2.index && lexeme === "") {
            modeBuffer += codeToHighlight.slice(match2.index, match2.index + 1);
            if (!SAFE_MODE) {
              const err = new Error("0 width match regex");
              err.languageName = languageName;
              err.badRule = lastMatch.rule;
              throw err;
            }
            return 1;
          }
          lastMatch = match2;
          if (match2.type === "begin") {
            return doBeginMatch(match2);
          } else if (match2.type === "illegal" && !ignoreIllegals) {
            const err = new Error('Illegal lexeme "' + lexeme + '" for mode "' + (top.className || "<unnamed>") + '"');
            err.mode = top;
            throw err;
          } else if (match2.type === "end") {
            const processed = doEndMatch(match2);
            if (processed !== NO_MATCH) {
              return processed;
            }
          }
          if (match2.type === "illegal" && lexeme === "") {
            return 1;
          }
          if (iterations > 1e5 && iterations > match2.index * 3) {
            const err = new Error("potential infinite loop, way more iterations than matches");
            throw err;
          }
          modeBuffer += lexeme;
          return lexeme.length;
        }
        const language = getLanguage(languageName);
        if (!language) {
          error(LANGUAGE_NOT_FOUND.replace("{}", languageName));
          throw new Error('Unknown language: "' + languageName + '"');
        }
        const md = compileLanguage(language, { plugins: plugins2 });
        let result = "";
        let top = continuation || md;
        const continuations = {};
        const emitter = new options.__emitter(options);
        processContinuations();
        let modeBuffer = "";
        let relevance = 0;
        let index = 0;
        let iterations = 0;
        let resumeScanAtSamePosition = false;
        try {
          top.matcher.considerAll();
          for (; ; ) {
            iterations++;
            if (resumeScanAtSamePosition) {
              resumeScanAtSamePosition = false;
            } else {
              top.matcher.considerAll();
            }
            top.matcher.lastIndex = index;
            const match2 = top.matcher.exec(codeToHighlight);
            if (!match2) break;
            const beforeMatch = codeToHighlight.substring(index, match2.index);
            const processedCount = processLexeme(beforeMatch, match2);
            index = match2.index + processedCount;
          }
          processLexeme(codeToHighlight.substr(index));
          emitter.closeAllNodes();
          emitter.finalize();
          result = emitter.toHTML();
          return {
            // avoid possible breakage with v10 clients expecting
            // this to always be an integer
            relevance: Math.floor(relevance),
            value: result,
            language: languageName,
            illegal: false,
            emitter,
            top
          };
        } catch (err) {
          if (err.message && err.message.includes("Illegal")) {
            return {
              illegal: true,
              illegalBy: {
                msg: err.message,
                context: codeToHighlight.slice(index - 100, index + 100),
                mode: err.mode
              },
              sofar: result,
              relevance: 0,
              value: escape$1(codeToHighlight),
              emitter
            };
          } else if (SAFE_MODE) {
            return {
              illegal: false,
              relevance: 0,
              value: escape$1(codeToHighlight),
              emitter,
              language: languageName,
              top,
              errorRaised: err
            };
          } else {
            throw err;
          }
        }
      }
      function justTextHighlightResult(code) {
        const result = {
          relevance: 0,
          emitter: new options.__emitter(options),
          value: escape$1(code),
          illegal: false,
          top: PLAINTEXT_LANGUAGE
        };
        result.emitter.addText(code);
        return result;
      }
      function highlightAuto(code, languageSubset) {
        languageSubset = languageSubset || options.languages || Object.keys(languages);
        const plaintext = justTextHighlightResult(code);
        const results = languageSubset.filter(getLanguage).filter(autoDetection).map(
          (name) => _highlight(name, code, false)
        );
        results.unshift(plaintext);
        const sorted = results.sort((a3, b4) => {
          if (a3.relevance !== b4.relevance) return b4.relevance - a3.relevance;
          if (a3.language && b4.language) {
            if (getLanguage(a3.language).supersetOf === b4.language) {
              return 1;
            } else if (getLanguage(b4.language).supersetOf === a3.language) {
              return -1;
            }
          }
          return 0;
        });
        const [best, secondBest] = sorted;
        const result = best;
        result.second_best = secondBest;
        return result;
      }
      function fixMarkup(html) {
        if (!(options.tabReplace || options.useBR)) {
          return html;
        }
        return html.replace(fixMarkupRe, (match2) => {
          if (match2 === "\n") {
            return options.useBR ? "<br>" : match2;
          } else if (options.tabReplace) {
            return match2.replace(/\t/g, options.tabReplace);
          }
          return match2;
        });
      }
      function updateClassName(element, currentLang, resultLang) {
        const language = currentLang ? aliases[currentLang] : resultLang;
        element.classList.add("hljs");
        if (language) element.classList.add(language);
      }
      const brPlugin = {
        "before:highlightElement": ({ el }) => {
          if (options.useBR) {
            el.innerHTML = el.innerHTML.replace(/\n/g, "").replace(/<br[ /]*>/g, "\n");
          }
        },
        "after:highlightElement": ({ result }) => {
          if (options.useBR) {
            result.value = result.value.replace(/\n/g, "<br>");
          }
        }
      };
      const TAB_REPLACE_RE = /^(<[^>]+>|\t)+/gm;
      const tabReplacePlugin = {
        "after:highlightElement": ({ result }) => {
          if (options.tabReplace) {
            result.value = result.value.replace(
              TAB_REPLACE_RE,
              (m4) => m4.replace(/\t/g, options.tabReplace)
            );
          }
        }
      };
      function highlightElement(element) {
        let node = null;
        const language = blockLanguage(element);
        if (shouldNotHighlight(language)) return;
        fire(
          "before:highlightElement",
          { el: element, language }
        );
        node = element;
        const text3 = node.textContent;
        const result = language ? highlight2(text3, { language, ignoreIllegals: true }) : highlightAuto(text3);
        fire("after:highlightElement", { el: element, result, text: text3 });
        element.innerHTML = result.value;
        updateClassName(element, language, result.language);
        element.result = {
          language: result.language,
          // TODO: remove with version 11.0
          re: result.relevance,
          relavance: result.relevance
        };
        if (result.second_best) {
          element.second_best = {
            language: result.second_best.language,
            // TODO: remove with version 11.0
            re: result.second_best.relevance,
            relavance: result.second_best.relevance
          };
        }
      }
      function configure(userOptions) {
        if (userOptions.useBR) {
          deprecated2("10.3.0", "'useBR' will be removed entirely in v11.0");
          deprecated2("10.3.0", "Please see https://github.com/highlightjs/highlight.js/issues/2559");
        }
        options = inherit$1(options, userOptions);
      }
      const initHighlighting = () => {
        if (initHighlighting.called) return;
        initHighlighting.called = true;
        deprecated2("10.6.0", "initHighlighting() is deprecated.  Use highlightAll() instead.");
        const blocks = document.querySelectorAll("pre code");
        blocks.forEach(highlightElement);
      };
      function initHighlightingOnLoad() {
        deprecated2("10.6.0", "initHighlightingOnLoad() is deprecated.  Use highlightAll() instead.");
        wantsHighlight = true;
      }
      let wantsHighlight = false;
      function highlightAll() {
        if (document.readyState === "loading") {
          wantsHighlight = true;
          return;
        }
        const blocks = document.querySelectorAll("pre code");
        blocks.forEach(highlightElement);
      }
      function boot() {
        if (wantsHighlight) highlightAll();
      }
      if (typeof window !== "undefined" && window.addEventListener) {
        window.addEventListener("DOMContentLoaded", boot, false);
      }
      function registerLanguage(languageName, languageDefinition) {
        let lang = null;
        try {
          lang = languageDefinition(hljs5);
        } catch (error$1) {
          error("Language definition for '{}' could not be registered.".replace("{}", languageName));
          if (!SAFE_MODE) {
            throw error$1;
          } else {
            error(error$1);
          }
          lang = PLAINTEXT_LANGUAGE;
        }
        if (!lang.name) lang.name = languageName;
        languages[languageName] = lang;
        lang.rawDefinition = languageDefinition.bind(null, hljs5);
        if (lang.aliases) {
          registerAliases(lang.aliases, { languageName });
        }
      }
      function unregisterLanguage(languageName) {
        delete languages[languageName];
        for (const alias of Object.keys(aliases)) {
          if (aliases[alias] === languageName) {
            delete aliases[alias];
          }
        }
      }
      function listLanguages() {
        return Object.keys(languages);
      }
      function requireLanguage(name) {
        deprecated2("10.4.0", "requireLanguage will be removed entirely in v11.");
        deprecated2("10.4.0", "Please see https://github.com/highlightjs/highlight.js/pull/2844");
        const lang = getLanguage(name);
        if (lang) {
          return lang;
        }
        const err = new Error("The '{}' language is required, but not loaded.".replace("{}", name));
        throw err;
      }
      function getLanguage(name) {
        name = (name || "").toLowerCase();
        return languages[name] || languages[aliases[name]];
      }
      function registerAliases(aliasList, { languageName }) {
        if (typeof aliasList === "string") {
          aliasList = [aliasList];
        }
        aliasList.forEach((alias) => {
          aliases[alias.toLowerCase()] = languageName;
        });
      }
      function autoDetection(name) {
        const lang = getLanguage(name);
        return lang && !lang.disableAutodetect;
      }
      function upgradePluginAPI(plugin) {
        if (plugin["before:highlightBlock"] && !plugin["before:highlightElement"]) {
          plugin["before:highlightElement"] = (data) => {
            plugin["before:highlightBlock"](
              Object.assign({ block: data.el }, data)
            );
          };
        }
        if (plugin["after:highlightBlock"] && !plugin["after:highlightElement"]) {
          plugin["after:highlightElement"] = (data) => {
            plugin["after:highlightBlock"](
              Object.assign({ block: data.el }, data)
            );
          };
        }
      }
      function addPlugin(plugin) {
        upgradePluginAPI(plugin);
        plugins2.push(plugin);
      }
      function fire(event, args) {
        const cb = event;
        plugins2.forEach(function(plugin) {
          if (plugin[cb]) {
            plugin[cb](args);
          }
        });
      }
      function deprecateFixMarkup(arg) {
        deprecated2("10.2.0", "fixMarkup will be removed entirely in v11.0");
        deprecated2("10.2.0", "Please see https://github.com/highlightjs/highlight.js/issues/2534");
        return fixMarkup(arg);
      }
      function deprecateHighlightBlock(el) {
        deprecated2("10.7.0", "highlightBlock will be removed entirely in v12.0");
        deprecated2("10.7.0", "Please use highlightElement now.");
        return highlightElement(el);
      }
      Object.assign(hljs5, {
        highlight: highlight2,
        highlightAuto,
        highlightAll,
        fixMarkup: deprecateFixMarkup,
        highlightElement,
        // TODO: Remove with v12 API
        highlightBlock: deprecateHighlightBlock,
        configure,
        initHighlighting,
        initHighlightingOnLoad,
        registerLanguage,
        unregisterLanguage,
        listLanguages,
        getLanguage,
        registerAliases,
        requireLanguage,
        autoDetection,
        inherit: inherit$1,
        addPlugin,
        // plugins for frameworks
        vuePlugin: BuildVuePlugin(hljs5).VuePlugin
      });
      hljs5.debugMode = function() {
        SAFE_MODE = false;
      };
      hljs5.safeMode = function() {
        SAFE_MODE = true;
      };
      hljs5.versionString = version5;
      for (const key in MODES2) {
        if (typeof MODES2[key] === "object") {
          deepFreezeEs6(MODES2[key]);
        }
      }
      Object.assign(hljs5, MODES2);
      hljs5.addPlugin(brPlugin);
      hljs5.addPlugin(mergeHTMLPlugin);
      hljs5.addPlugin(tabReplacePlugin);
      return hljs5;
    };
    var highlight = HLJS({});
    module.exports = highlight;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/1c.js
var require_c = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/1c.js"(exports, module) {
    init_process_shim();
    function _1c(hljs5) {
      var UNDERSCORE_IDENT_RE = "[A-Za-z\u0410-\u042F\u0430-\u044F\u0451\u0401_][A-Za-z\u0410-\u042F\u0430-\u044F\u0451\u0401_0-9]+";
      var v7_keywords = "\u0434\u0430\u043B\u0435\u0435 ";
      var v8_keywords = "\u0432\u043E\u0437\u0432\u0440\u0430\u0442 \u0432\u044B\u0437\u0432\u0430\u0442\u044C\u0438\u0441\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u0435 \u0432\u044B\u043F\u043E\u043B\u043D\u0438\u0442\u044C \u0434\u043B\u044F \u0435\u0441\u043B\u0438 \u0438 \u0438\u0437 \u0438\u043B\u0438 \u0438\u043D\u0430\u0447\u0435 \u0438\u043D\u0430\u0447\u0435\u0435\u0441\u043B\u0438 \u0438\u0441\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u0435 \u043A\u0430\u0436\u0434\u043E\u0433\u043E \u043A\u043E\u043D\u0435\u0446\u0435\u0441\u043B\u0438 \u043A\u043E\u043D\u0435\u0446\u043F\u043E\u043F\u044B\u0442\u043A\u0438 \u043A\u043E\u043D\u0435\u0446\u0446\u0438\u043A\u043B\u0430 \u043D\u0435 \u043D\u043E\u0432\u044B\u0439 \u043F\u0435\u0440\u0435\u0439\u0442\u0438 \u043F\u0435\u0440\u0435\u043C \u043F\u043E \u043F\u043E\u043A\u0430 \u043F\u043E\u043F\u044B\u0442\u043A\u0430 \u043F\u0440\u0435\u0440\u0432\u0430\u0442\u044C \u043F\u0440\u043E\u0434\u043E\u043B\u0436\u0438\u0442\u044C \u0442\u043E\u0433\u0434\u0430 \u0446\u0438\u043A\u043B \u044D\u043A\u0441\u043F\u043E\u0440\u0442 ";
      var KEYWORD = v7_keywords + v8_keywords;
      var v7_meta_keywords = "\u0437\u0430\u0433\u0440\u0443\u0437\u0438\u0442\u044C\u0438\u0437\u0444\u0430\u0439\u043B\u0430 ";
      var v8_meta_keywords = "\u0432\u0435\u0431\u043A\u043B\u0438\u0435\u043D\u0442 \u0432\u043C\u0435\u0441\u0442\u043E \u0432\u043D\u0435\u0448\u043D\u0435\u0435\u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0435 \u043A\u043B\u0438\u0435\u043D\u0442 \u043A\u043E\u043D\u0435\u0446\u043E\u0431\u043B\u0430\u0441\u0442\u0438 \u043C\u043E\u0431\u0438\u043B\u044C\u043D\u043E\u0435\u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u043A\u043B\u0438\u0435\u043D\u0442 \u043C\u043E\u0431\u0438\u043B\u044C\u043D\u043E\u0435\u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u0441\u0435\u0440\u0432\u0435\u0440 \u043D\u0430\u043A\u043B\u0438\u0435\u043D\u0442\u0435 \u043D\u0430\u043A\u043B\u0438\u0435\u043D\u0442\u0435\u043D\u0430\u0441\u0435\u0440\u0432\u0435\u0440\u0435 \u043D\u0430\u043A\u043B\u0438\u0435\u043D\u0442\u0435\u043D\u0430\u0441\u0435\u0440\u0432\u0435\u0440\u0435\u0431\u0435\u0437\u043A\u043E\u043D\u0442\u0435\u043A\u0441\u0442\u0430 \u043D\u0430\u0441\u0435\u0440\u0432\u0435\u0440\u0435 \u043D\u0430\u0441\u0435\u0440\u0432\u0435\u0440\u0435\u0431\u0435\u0437\u043A\u043E\u043D\u0442\u0435\u043A\u0441\u0442\u0430 \u043E\u0431\u043B\u0430\u0441\u0442\u044C \u043F\u0435\u0440\u0435\u0434 \u043F\u043E\u0441\u043B\u0435 \u0441\u0435\u0440\u0432\u0435\u0440 \u0442\u043E\u043B\u0441\u0442\u044B\u0439\u043A\u043B\u0438\u0435\u043D\u0442\u043E\u0431\u044B\u0447\u043D\u043E\u0435\u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u0435 \u0442\u043E\u043B\u0441\u0442\u044B\u0439\u043A\u043B\u0438\u0435\u043D\u0442\u0443\u043F\u0440\u0430\u0432\u043B\u044F\u0435\u043C\u043E\u0435\u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u0435 \u0442\u043E\u043D\u043A\u0438\u0439\u043A\u043B\u0438\u0435\u043D\u0442 ";
      var METAKEYWORD = v7_meta_keywords + v8_meta_keywords;
      var v7_system_constants = "\u0440\u0430\u0437\u0434\u0435\u043B\u0438\u0442\u0435\u043B\u044C\u0441\u0442\u0440\u0430\u043D\u0438\u0446 \u0440\u0430\u0437\u0434\u0435\u043B\u0438\u0442\u0435\u043B\u044C\u0441\u0442\u0440\u043E\u043A \u0441\u0438\u043C\u0432\u043E\u043B\u0442\u0430\u0431\u0443\u043B\u044F\u0446\u0438\u0438 ";
      var v7_global_context_methods = "ansitooem oemtoansi \u0432\u0432\u0435\u0441\u0442\u0438\u0432\u0438\u0434\u0441\u0443\u0431\u043A\u043E\u043D\u0442\u043E \u0432\u0432\u0435\u0441\u0442\u0438\u043F\u0435\u0440\u0435\u0447\u0438\u0441\u043B\u0435\u043D\u0438\u0435 \u0432\u0432\u0435\u0441\u0442\u0438\u043F\u0435\u0440\u0438\u043E\u0434 \u0432\u0432\u0435\u0441\u0442\u0438\u043F\u043B\u0430\u043D\u0441\u0447\u0435\u0442\u043E\u0432 \u0432\u044B\u0431\u0440\u0430\u043D\u043D\u044B\u0439\u043F\u043B\u0430\u043D\u0441\u0447\u0435\u0442\u043E\u0432 \u0434\u0430\u0442\u0430\u0433\u043E\u0434 \u0434\u0430\u0442\u0430\u043C\u0435\u0441\u044F\u0446 \u0434\u0430\u0442\u0430\u0447\u0438\u0441\u043B\u043E \u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A\u0441\u0438\u0441\u0442\u0435\u043C\u044B \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435\u0432\u0441\u0442\u0440\u043E\u043A\u0443 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435\u0438\u0437\u0441\u0442\u0440\u043E\u043A\u0438 \u043A\u0430\u0442\u0430\u043B\u043E\u0433\u0438\u0431 \u043A\u0430\u0442\u0430\u043B\u043E\u0433\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F \u043A\u043E\u0434\u0441\u0438\u043C\u0432 \u043A\u043E\u043D\u0433\u043E\u0434\u0430 \u043A\u043E\u043D\u0435\u0446\u043F\u0435\u0440\u0438\u043E\u0434\u0430\u0431\u0438 \u043A\u043E\u043D\u0435\u0446\u0440\u0430\u0441\u0441\u0447\u0438\u0442\u0430\u043D\u043D\u043E\u0433\u043E\u043F\u0435\u0440\u0438\u043E\u0434\u0430\u0431\u0438 \u043A\u043E\u043D\u0435\u0446\u0441\u0442\u0430\u043D\u0434\u0430\u0440\u0442\u043D\u043E\u0433\u043E\u0438\u043D\u0442\u0435\u0440\u0432\u0430\u043B\u0430 \u043A\u043E\u043D\u043A\u0432\u0430\u0440\u0442\u0430\u043B\u0430 \u043A\u043E\u043D\u043C\u0435\u0441\u044F\u0446\u0430 \u043A\u043E\u043D\u043D\u0435\u0434\u0435\u043B\u0438 \u043B\u043E\u0433 \u043B\u043E\u043310 \u043C\u0430\u043A\u0441\u0438\u043C\u0430\u043B\u044C\u043D\u043E\u0435\u043A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u043E\u0441\u0443\u0431\u043A\u043E\u043D\u0442\u043E \u043D\u0430\u0437\u0432\u0430\u043D\u0438\u0435\u0438\u043D\u0442\u0435\u0440\u0444\u0435\u0439\u0441\u0430 \u043D\u0430\u0437\u0432\u0430\u043D\u0438\u0435\u043D\u0430\u0431\u043E\u0440\u0430\u043F\u0440\u0430\u0432 \u043D\u0430\u0437\u043D\u0430\u0447\u0438\u0442\u044C\u0432\u0438\u0434 \u043D\u0430\u0437\u043D\u0430\u0447\u0438\u0442\u044C\u0441\u0447\u0435\u0442 \u043D\u0430\u0439\u0442\u0438\u0441\u0441\u044B\u043B\u043A\u0438 \u043D\u0430\u0447\u0430\u043B\u043E\u043F\u0435\u0440\u0438\u043E\u0434\u0430\u0431\u0438 \u043D\u0430\u0447\u0430\u043B\u043E\u0441\u0442\u0430\u043D\u0434\u0430\u0440\u0442\u043D\u043E\u0433\u043E\u0438\u043D\u0442\u0435\u0440\u0432\u0430\u043B\u0430 \u043D\u0430\u0447\u0433\u043E\u0434\u0430 \u043D\u0430\u0447\u043A\u0432\u0430\u0440\u0442\u0430\u043B\u0430 \u043D\u0430\u0447\u043C\u0435\u0441\u044F\u0446\u0430 \u043D\u0430\u0447\u043D\u0435\u0434\u0435\u043B\u0438 \u043D\u043E\u043C\u0435\u0440\u0434\u043D\u044F\u0433\u043E\u0434\u0430 \u043D\u043E\u043C\u0435\u0440\u0434\u043D\u044F\u043D\u0435\u0434\u0435\u043B\u0438 \u043D\u043E\u043C\u0435\u0440\u043D\u0435\u0434\u0435\u043B\u0438\u0433\u043E\u0434\u0430 \u043E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0430\u043E\u0436\u0438\u0434\u0430\u043D\u0438\u044F \u043E\u0441\u043D\u043E\u0432\u043D\u043E\u0439\u0436\u0443\u0440\u043D\u0430\u043B\u0440\u0430\u0441\u0447\u0435\u0442\u043E\u0432 \u043E\u0441\u043D\u043E\u0432\u043D\u043E\u0439\u043F\u043B\u0430\u043D\u0441\u0447\u0435\u0442\u043E\u0432 \u043E\u0441\u043D\u043E\u0432\u043D\u043E\u0439\u044F\u0437\u044B\u043A \u043E\u0447\u0438\u0441\u0442\u0438\u0442\u044C\u043E\u043A\u043D\u043E\u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0439 \u043F\u0435\u0440\u0438\u043E\u0434\u0441\u0442\u0440 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0432\u0440\u0435\u043C\u044F\u0442\u0430 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0434\u0430\u0442\u0443\u0442\u0430 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0442\u0430 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044F\u043E\u0442\u0431\u043E\u0440\u0430 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u043F\u043E\u0437\u0438\u0446\u0438\u044E\u0442\u0430 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u043F\u0443\u0441\u0442\u043E\u0435\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0442\u0430 \u043F\u0440\u0435\u0444\u0438\u043A\u0441\u0430\u0432\u0442\u043E\u043D\u0443\u043C\u0435\u0440\u0430\u0446\u0438\u0438 \u043F\u0440\u043E\u043F\u0438\u0441\u044C \u043F\u0443\u0441\u0442\u043E\u0435\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0440\u0430\u0437\u043C \u0440\u0430\u0437\u043E\u0431\u0440\u0430\u0442\u044C\u043F\u043E\u0437\u0438\u0446\u0438\u044E\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430 \u0440\u0430\u0441\u0441\u0447\u0438\u0442\u0430\u0442\u044C\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u044B\u043D\u0430 \u0440\u0430\u0441\u0441\u0447\u0438\u0442\u0430\u0442\u044C\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u044B\u043F\u043E \u0441\u0438\u043C\u0432 \u0441\u043E\u0437\u0434\u0430\u0442\u044C\u043E\u0431\u044A\u0435\u043A\u0442 \u0441\u0442\u0430\u0442\u0443\u0441\u0432\u043E\u0437\u0432\u0440\u0430\u0442\u0430 \u0441\u0442\u0440\u043A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u043E\u0441\u0442\u0440\u043E\u043A \u0441\u0444\u043E\u0440\u043C\u0438\u0440\u043E\u0432\u0430\u0442\u044C\u043F\u043E\u0437\u0438\u0446\u0438\u044E\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430 \u0441\u0447\u0435\u0442\u043F\u043E\u043A\u043E\u0434\u0443 \u0442\u0435\u043A\u0443\u0449\u0435\u0435\u0432\u0440\u0435\u043C\u044F \u0442\u0438\u043F\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044F \u0442\u0438\u043F\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044F\u0441\u0442\u0440 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u0442\u0430\u043D\u0430 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u0442\u0430\u043F\u043E \u0444\u0438\u043A\u0441\u0448\u0430\u0431\u043B\u043E\u043D \u0448\u0430\u0431\u043B\u043E\u043D ";
      var v8_global_context_methods = "acos asin atan base64\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 base64\u0441\u0442\u0440\u043E\u043A\u0430 cos exp log log10 pow sin sqrt tan xml\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 xml\u0441\u0442\u0440\u043E\u043A\u0430 xml\u0442\u0438\u043F xml\u0442\u0438\u043F\u0437\u043D\u0447 \u0430\u043A\u0442\u0438\u0432\u043D\u043E\u0435\u043E\u043A\u043D\u043E \u0431\u0435\u0437\u043E\u043F\u0430\u0441\u043D\u044B\u0439\u0440\u0435\u0436\u0438\u043C \u0431\u0435\u0437\u043E\u043F\u0430\u0441\u043D\u044B\u0439\u0440\u0435\u0436\u0438\u043C\u0440\u0430\u0437\u0434\u0435\u043B\u0435\u043D\u0438\u044F\u0434\u0430\u043D\u043D\u044B\u0445 \u0431\u0443\u043B\u0435\u0432\u043E \u0432\u0432\u0435\u0441\u0442\u0438\u0434\u0430\u0442\u0443 \u0432\u0432\u0435\u0441\u0442\u0438\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432\u0432\u0435\u0441\u0442\u0438\u0441\u0442\u0440\u043E\u043A\u0443 \u0432\u0432\u0435\u0441\u0442\u0438\u0447\u0438\u0441\u043B\u043E \u0432\u043E\u0437\u043C\u043E\u0436\u043D\u043E\u0441\u0442\u044C\u0447\u0442\u0435\u043D\u0438\u044Fxml \u0432\u043E\u043F\u0440\u043E\u0441 \u0432\u043E\u0441\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432\u0440\u0435\u0433 \u0432\u044B\u0433\u0440\u0443\u0437\u0438\u0442\u044C\u0436\u0443\u0440\u043D\u0430\u043B\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0446\u0438\u0438 \u0432\u044B\u043F\u043E\u043B\u043D\u0438\u0442\u044C\u043E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0443\u043E\u043F\u043E\u0432\u0435\u0449\u0435\u043D\u0438\u044F \u0432\u044B\u043F\u043E\u043B\u043D\u0438\u0442\u044C\u043F\u0440\u043E\u0432\u0435\u0440\u043A\u0443\u043F\u0440\u0430\u0432\u0434\u043E\u0441\u0442\u0443\u043F\u0430 \u0432\u044B\u0447\u0438\u0441\u043B\u0438\u0442\u044C \u0433\u043E\u0434 \u0434\u0430\u043D\u043D\u044B\u0435\u0444\u043E\u0440\u043C\u044B\u0432\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0434\u0430\u0442\u0430 \u0434\u0435\u043D\u044C \u0434\u0435\u043D\u044C\u0433\u043E\u0434\u0430 \u0434\u0435\u043D\u044C\u043D\u0435\u0434\u0435\u043B\u0438 \u0434\u043E\u0431\u0430\u0432\u0438\u0442\u044C\u043C\u0435\u0441\u044F\u0446 \u0437\u0430\u0431\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u0430\u0442\u044C\u0434\u0430\u043D\u043D\u044B\u0435\u0434\u043B\u044F\u0440\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F \u0437\u0430\u0431\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u0430\u0442\u044C\u0440\u0430\u0431\u043E\u0442\u0443\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F \u0437\u0430\u0432\u0435\u0440\u0448\u0438\u0442\u044C\u0440\u0430\u0431\u043E\u0442\u0443\u0441\u0438\u0441\u0442\u0435\u043C\u044B \u0437\u0430\u0433\u0440\u0443\u0437\u0438\u0442\u044C\u0432\u043D\u0435\u0448\u043D\u044E\u044E\u043A\u043E\u043C\u043F\u043E\u043D\u0435\u043D\u0442\u0443 \u0437\u0430\u043A\u0440\u044B\u0442\u044C\u0441\u043F\u0440\u0430\u0432\u043A\u0443 \u0437\u0430\u043F\u0438\u0441\u0430\u0442\u044Cjson \u0437\u0430\u043F\u0438\u0441\u0430\u0442\u044Cxml \u0437\u0430\u043F\u0438\u0441\u0430\u0442\u044C\u0434\u0430\u0442\u0443json \u0437\u0430\u043F\u0438\u0441\u044C\u0436\u0443\u0440\u043D\u0430\u043B\u0430\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0446\u0438\u0438 \u0437\u0430\u043F\u043E\u043B\u043D\u0438\u0442\u044C\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044F\u0441\u0432\u043E\u0439\u0441\u0442\u0432 \u0437\u0430\u043F\u0440\u043E\u0441\u0438\u0442\u044C\u0440\u0430\u0437\u0440\u0435\u0448\u0435\u043D\u0438\u0435\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F \u0437\u0430\u043F\u0443\u0441\u0442\u0438\u0442\u044C\u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u0435 \u0437\u0430\u043F\u0443\u0441\u0442\u0438\u0442\u044C\u0441\u0438\u0441\u0442\u0435\u043C\u0443 \u0437\u0430\u0444\u0438\u043A\u0441\u0438\u0440\u043E\u0432\u0430\u0442\u044C\u0442\u0440\u0430\u043D\u0437\u0430\u043A\u0446\u0438\u044E \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435\u0432\u0434\u0430\u043D\u043D\u044B\u0435\u0444\u043E\u0440\u043C\u044B \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435\u0432\u0441\u0442\u0440\u043E\u043A\u0443\u0432\u043D\u0443\u0442\u0440 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435\u0432\u0444\u0430\u0439\u043B \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435\u0437\u0430\u043F\u043E\u043B\u043D\u0435\u043D\u043E \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435\u0438\u0437\u0441\u0442\u0440\u043E\u043A\u0438\u0432\u043D\u0443\u0442\u0440 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435\u0438\u0437\u0444\u0430\u0439\u043B\u0430 \u0438\u0437xml\u0442\u0438\u043F\u0430 \u0438\u043C\u043F\u043E\u0440\u0442\u043C\u043E\u0434\u0435\u043B\u0438xdto \u0438\u043C\u044F\u043A\u043E\u043C\u043F\u044C\u044E\u0442\u0435\u0440\u0430 \u0438\u043C\u044F\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F \u0438\u043D\u0438\u0446\u0438\u0430\u043B\u0438\u0437\u0438\u0440\u043E\u0432\u0430\u0442\u044C\u043F\u0440\u0435\u0434\u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u043D\u044B\u0435\u0434\u0430\u043D\u043D\u044B\u0435 \u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u044F\u043E\u0431\u043E\u0448\u0438\u0431\u043A\u0435 \u043A\u0430\u0442\u0430\u043B\u043E\u0433\u0431\u0438\u0431\u043B\u0438\u043E\u0442\u0435\u043A\u0438\u043C\u043E\u0431\u0438\u043B\u044C\u043D\u043E\u0433\u043E\u0443\u0441\u0442\u0440\u043E\u0439\u0441\u0442\u0432\u0430 \u043A\u0430\u0442\u0430\u043B\u043E\u0433\u0432\u0440\u0435\u043C\u0435\u043D\u043D\u044B\u0445\u0444\u0430\u0439\u043B\u043E\u0432 \u043A\u0430\u0442\u0430\u043B\u043E\u0433\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u043E\u0432 \u043A\u0430\u0442\u0430\u043B\u043E\u0433\u043F\u0440\u043E\u0433\u0440\u0430\u043C\u043C\u044B \u043A\u043E\u0434\u0438\u0440\u043E\u0432\u0430\u0442\u044C\u0441\u0442\u0440\u043E\u043A\u0443 \u043A\u043E\u0434\u043B\u043E\u043A\u0430\u043B\u0438\u0437\u0430\u0446\u0438\u0438\u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u043E\u043D\u043D\u043E\u0439\u0431\u0430\u0437\u044B \u043A\u043E\u0434\u0441\u0438\u043C\u0432\u043E\u043B\u0430 \u043A\u043E\u043C\u0430\u043D\u0434\u0430\u0441\u0438\u0441\u0442\u0435\u043C\u044B \u043A\u043E\u043D\u0435\u0446\u0433\u043E\u0434\u0430 \u043A\u043E\u043D\u0435\u0446\u0434\u043D\u044F \u043A\u043E\u043D\u0435\u0446\u043A\u0432\u0430\u0440\u0442\u0430\u043B\u0430 \u043A\u043E\u043D\u0435\u0446\u043C\u0435\u0441\u044F\u0446\u0430 \u043A\u043E\u043D\u0435\u0446\u043C\u0438\u043D\u0443\u0442\u044B \u043A\u043E\u043D\u0435\u0446\u043D\u0435\u0434\u0435\u043B\u0438 \u043A\u043E\u043D\u0435\u0446\u0447\u0430\u0441\u0430 \u043A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u044F\u0431\u0430\u0437\u044B\u0434\u0430\u043D\u043D\u044B\u0445\u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0430\u0434\u0438\u043D\u0430\u043C\u0438\u0447\u0435\u0441\u043A\u0438 \u043A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u044F\u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0430 \u043A\u043E\u043F\u0438\u0440\u043E\u0432\u0430\u0442\u044C\u0434\u0430\u043D\u043D\u044B\u0435\u0444\u043E\u0440\u043C\u044B \u043A\u043E\u043F\u0438\u0440\u043E\u0432\u0430\u0442\u044C\u0444\u0430\u0439\u043B \u043A\u0440\u0430\u0442\u043A\u043E\u0435\u043F\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043B\u0435\u043D\u0438\u0435\u043E\u0448\u0438\u0431\u043A\u0438 \u043B\u0435\u0432 \u043C\u0430\u043A\u0441 \u043C\u0435\u0441\u0442\u043D\u043E\u0435\u0432\u0440\u0435\u043C\u044F \u043C\u0435\u0441\u044F\u0446 \u043C\u0438\u043D \u043C\u0438\u043D\u0443\u0442\u0430 \u043C\u043E\u043D\u043E\u043F\u043E\u043B\u044C\u043D\u044B\u0439\u0440\u0435\u0436\u0438\u043C \u043D\u0430\u0439\u0442\u0438 \u043D\u0430\u0439\u0442\u0438\u043D\u0435\u0434\u043E\u043F\u0443\u0441\u0442\u0438\u043C\u044B\u0435\u0441\u0438\u043C\u0432\u043E\u043B\u044Bxml \u043D\u0430\u0439\u0442\u0438\u043E\u043A\u043D\u043E\u043F\u043E\u043D\u0430\u0432\u0438\u0433\u0430\u0446\u0438\u043E\u043D\u043D\u043E\u0439\u0441\u0441\u044B\u043B\u043A\u0435 \u043D\u0430\u0439\u0442\u0438\u043F\u043E\u043C\u0435\u0447\u0435\u043D\u043D\u044B\u0435\u043D\u0430\u0443\u0434\u0430\u043B\u0435\u043D\u0438\u0435 \u043D\u0430\u0439\u0442\u0438\u043F\u043E\u0441\u0441\u044B\u043B\u043A\u0430\u043C \u043D\u0430\u0439\u0442\u0438\u0444\u0430\u0439\u043B\u044B \u043D\u0430\u0447\u0430\u043B\u043E\u0433\u043E\u0434\u0430 \u043D\u0430\u0447\u0430\u043B\u043E\u0434\u043D\u044F \u043D\u0430\u0447\u0430\u043B\u043E\u043A\u0432\u0430\u0440\u0442\u0430\u043B\u0430 \u043D\u0430\u0447\u0430\u043B\u043E\u043C\u0435\u0441\u044F\u0446\u0430 \u043D\u0430\u0447\u0430\u043B\u043E\u043C\u0438\u043D\u0443\u0442\u044B \u043D\u0430\u0447\u0430\u043B\u043E\u043D\u0435\u0434\u0435\u043B\u0438 \u043D\u0430\u0447\u0430\u043B\u043E\u0447\u0430\u0441\u0430 \u043D\u0430\u0447\u0430\u0442\u044C\u0437\u0430\u043F\u0440\u043E\u0441\u0440\u0430\u0437\u0440\u0435\u0448\u0435\u043D\u0438\u044F\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F \u043D\u0430\u0447\u0430\u0442\u044C\u0437\u0430\u043F\u0443\u0441\u043A\u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u044F \u043D\u0430\u0447\u0430\u0442\u044C\u043A\u043E\u043F\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435\u0444\u0430\u0439\u043B\u0430 \u043D\u0430\u0447\u0430\u0442\u044C\u043F\u0435\u0440\u0435\u043C\u0435\u0449\u0435\u043D\u0438\u0435\u0444\u0430\u0439\u043B\u0430 \u043D\u0430\u0447\u0430\u0442\u044C\u043F\u043E\u0434\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u0435\u0432\u043D\u0435\u0448\u043D\u0435\u0439\u043A\u043E\u043C\u043F\u043E\u043D\u0435\u043D\u0442\u044B \u043D\u0430\u0447\u0430\u0442\u044C\u043F\u043E\u0434\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u0435\u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F\u0440\u0430\u0431\u043E\u0442\u044B\u0441\u043A\u0440\u0438\u043F\u0442\u043E\u0433\u0440\u0430\u0444\u0438\u0435\u0439 \u043D\u0430\u0447\u0430\u0442\u044C\u043F\u043E\u0434\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u0435\u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F\u0440\u0430\u0431\u043E\u0442\u044B\u0441\u0444\u0430\u0439\u043B\u0430\u043C\u0438 \u043D\u0430\u0447\u0430\u0442\u044C\u043F\u043E\u0438\u0441\u043A\u0444\u0430\u0439\u043B\u043E\u0432 \u043D\u0430\u0447\u0430\u0442\u044C\u043F\u043E\u043B\u0443\u0447\u0435\u043D\u0438\u0435\u043A\u0430\u0442\u0430\u043B\u043E\u0433\u0430\u0432\u0440\u0435\u043C\u0435\u043D\u043D\u044B\u0445\u0444\u0430\u0439\u043B\u043E\u0432 \u043D\u0430\u0447\u0430\u0442\u044C\u043F\u043E\u043B\u0443\u0447\u0435\u043D\u0438\u0435\u043A\u0430\u0442\u0430\u043B\u043E\u0433\u0430\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u043E\u0432 \u043D\u0430\u0447\u0430\u0442\u044C\u043F\u043E\u043B\u0443\u0447\u0435\u043D\u0438\u0435\u0440\u0430\u0431\u043E\u0447\u0435\u0433\u043E\u043A\u0430\u0442\u0430\u043B\u043E\u0433\u0430\u0434\u0430\u043D\u043D\u044B\u0445\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F \u043D\u0430\u0447\u0430\u0442\u044C\u043F\u043E\u043B\u0443\u0447\u0435\u043D\u0438\u0435\u0444\u0430\u0439\u043B\u043E\u0432 \u043D\u0430\u0447\u0430\u0442\u044C\u043F\u043E\u043C\u0435\u0449\u0435\u043D\u0438\u0435\u0444\u0430\u0439\u043B\u0430 \u043D\u0430\u0447\u0430\u0442\u044C\u043F\u043E\u043C\u0435\u0449\u0435\u043D\u0438\u0435\u0444\u0430\u0439\u043B\u043E\u0432 \u043D\u0430\u0447\u0430\u0442\u044C\u0441\u043E\u0437\u0434\u0430\u043D\u0438\u0435\u0434\u0432\u043E\u0438\u0447\u043D\u044B\u0445\u0434\u0430\u043D\u043D\u044B\u0445\u0438\u0437\u0444\u0430\u0439\u043B\u0430 \u043D\u0430\u0447\u0430\u0442\u044C\u0441\u043E\u0437\u0434\u0430\u043D\u0438\u0435\u043A\u0430\u0442\u0430\u043B\u043E\u0433\u0430 \u043D\u0430\u0447\u0430\u0442\u044C\u0442\u0440\u0430\u043D\u0437\u0430\u043A\u0446\u0438\u044E \u043D\u0430\u0447\u0430\u0442\u044C\u0443\u0434\u0430\u043B\u0435\u043D\u0438\u0435\u0444\u0430\u0439\u043B\u043E\u0432 \u043D\u0430\u0447\u0430\u0442\u044C\u0443\u0441\u0442\u0430\u043D\u043E\u0432\u043A\u0443\u0432\u043D\u0435\u0448\u043D\u0435\u0439\u043A\u043E\u043C\u043F\u043E\u043D\u0435\u043D\u0442\u044B \u043D\u0430\u0447\u0430\u0442\u044C\u0443\u0441\u0442\u0430\u043D\u043E\u0432\u043A\u0443\u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F\u0440\u0430\u0431\u043E\u0442\u044B\u0441\u043A\u0440\u0438\u043F\u0442\u043E\u0433\u0440\u0430\u0444\u0438\u0435\u0439 \u043D\u0430\u0447\u0430\u0442\u044C\u0443\u0441\u0442\u0430\u043D\u043E\u0432\u043A\u0443\u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F\u0440\u0430\u0431\u043E\u0442\u044B\u0441\u0444\u0430\u0439\u043B\u0430\u043C\u0438 \u043D\u0435\u0434\u0435\u043B\u044F\u0433\u043E\u0434\u0430 \u043D\u0435\u043E\u0431\u0445\u043E\u0434\u0438\u043C\u043E\u0441\u0442\u044C\u0437\u0430\u0432\u0435\u0440\u0448\u0435\u043D\u0438\u044F\u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u044F \u043D\u043E\u043C\u0435\u0440\u0441\u0435\u0430\u043D\u0441\u0430\u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u043E\u043D\u043D\u043E\u0439\u0431\u0430\u0437\u044B \u043D\u043E\u043C\u0435\u0440\u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u044F\u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u043E\u043D\u043D\u043E\u0439\u0431\u0430\u0437\u044B \u043D\u0440\u0435\u0433 \u043D\u0441\u0442\u0440 \u043E\u0431\u043D\u043E\u0432\u0438\u0442\u044C\u0438\u043D\u0442\u0435\u0440\u0444\u0435\u0439\u0441 \u043E\u0431\u043D\u043E\u0432\u0438\u0442\u044C\u043D\u0443\u043C\u0435\u0440\u0430\u0446\u0438\u044E\u043E\u0431\u044A\u0435\u043A\u0442\u043E\u0432 \u043E\u0431\u043D\u043E\u0432\u0438\u0442\u044C\u043F\u043E\u0432\u0442\u043E\u0440\u043D\u043E\u0438\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0435\u043C\u044B\u0435\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044F \u043E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0430\u043F\u0440\u0435\u0440\u044B\u0432\u0430\u043D\u0438\u044F\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F \u043E\u0431\u044A\u0435\u0434\u0438\u043D\u0438\u0442\u044C\u0444\u0430\u0439\u043B\u044B \u043E\u043A\u0440 \u043E\u043F\u0438\u0441\u0430\u043D\u0438\u0435\u043E\u0448\u0438\u0431\u043A\u0438 \u043E\u043F\u043E\u0432\u0435\u0441\u0442\u0438\u0442\u044C \u043E\u043F\u043E\u0432\u0435\u0441\u0442\u0438\u0442\u044C\u043E\u0431\u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u0438 \u043E\u0442\u043A\u043B\u044E\u0447\u0438\u0442\u044C\u043E\u0431\u0440\u0430\u0431\u043E\u0442\u0447\u0438\u043A\u0437\u0430\u043F\u0440\u043E\u0441\u0430\u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043A\u043A\u043B\u0438\u0435\u043D\u0442\u0430\u043B\u0438\u0446\u0435\u043D\u0437\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F \u043E\u0442\u043A\u043B\u044E\u0447\u0438\u0442\u044C\u043E\u0431\u0440\u0430\u0431\u043E\u0442\u0447\u0438\u043A\u043E\u0436\u0438\u0434\u0430\u043D\u0438\u044F \u043E\u0442\u043A\u043B\u044E\u0447\u0438\u0442\u044C\u043E\u0431\u0440\u0430\u0431\u043E\u0442\u0447\u0438\u043A\u043E\u043F\u043E\u0432\u0435\u0449\u0435\u043D\u0438\u044F \u043E\u0442\u043A\u0440\u044B\u0442\u044C\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u043E\u0442\u043A\u0440\u044B\u0442\u044C\u0438\u043D\u0434\u0435\u043A\u0441\u0441\u043F\u0440\u0430\u0432\u043A\u0438 \u043E\u0442\u043A\u0440\u044B\u0442\u044C\u0441\u043E\u0434\u0435\u0440\u0436\u0430\u043D\u0438\u0435\u0441\u043F\u0440\u0430\u0432\u043A\u0438 \u043E\u0442\u043A\u0440\u044B\u0442\u044C\u0441\u043F\u0440\u0430\u0432\u043A\u0443 \u043E\u0442\u043A\u0440\u044B\u0442\u044C\u0444\u043E\u0440\u043C\u0443 \u043E\u0442\u043A\u0440\u044B\u0442\u044C\u0444\u043E\u0440\u043C\u0443\u043C\u043E\u0434\u0430\u043B\u044C\u043D\u043E \u043E\u0442\u043C\u0435\u043D\u0438\u0442\u044C\u0442\u0440\u0430\u043D\u0437\u0430\u043A\u0446\u0438\u044E \u043E\u0447\u0438\u0441\u0442\u0438\u0442\u044C\u0436\u0443\u0440\u043D\u0430\u043B\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0446\u0438\u0438 \u043E\u0447\u0438\u0441\u0442\u0438\u0442\u044C\u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F \u043E\u0447\u0438\u0441\u0442\u0438\u0442\u044C\u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u044F \u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u044B\u0434\u043E\u0441\u0442\u0443\u043F\u0430 \u043F\u0435\u0440\u0435\u0439\u0442\u0438\u043F\u043E\u043D\u0430\u0432\u0438\u0433\u0430\u0446\u0438\u043E\u043D\u043D\u043E\u0439\u0441\u0441\u044B\u043B\u043A\u0435 \u043F\u0435\u0440\u0435\u043C\u0435\u0441\u0442\u0438\u0442\u044C\u0444\u0430\u0439\u043B \u043F\u043E\u0434\u043A\u043B\u044E\u0447\u0438\u0442\u044C\u0432\u043D\u0435\u0448\u043D\u044E\u044E\u043A\u043E\u043C\u043F\u043E\u043D\u0435\u043D\u0442\u0443 \u043F\u043E\u0434\u043A\u043B\u044E\u0447\u0438\u0442\u044C\u043E\u0431\u0440\u0430\u0431\u043E\u0442\u0447\u0438\u043A\u0437\u0430\u043F\u0440\u043E\u0441\u0430\u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043A\u043A\u043B\u0438\u0435\u043D\u0442\u0430\u043B\u0438\u0446\u0435\u043D\u0437\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F \u043F\u043E\u0434\u043A\u043B\u044E\u0447\u0438\u0442\u044C\u043E\u0431\u0440\u0430\u0431\u043E\u0442\u0447\u0438\u043A\u043E\u0436\u0438\u0434\u0430\u043D\u0438\u044F \u043F\u043E\u0434\u043A\u043B\u044E\u0447\u0438\u0442\u044C\u043E\u0431\u0440\u0430\u0431\u043E\u0442\u0447\u0438\u043A\u043E\u043F\u043E\u0432\u0435\u0449\u0435\u043D\u0438\u044F \u043F\u043E\u0434\u043A\u043B\u044E\u0447\u0438\u0442\u044C\u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435\u0440\u0430\u0431\u043E\u0442\u044B\u0441\u043A\u0440\u0438\u043F\u0442\u043E\u0433\u0440\u0430\u0444\u0438\u0435\u0439 \u043F\u043E\u0434\u043A\u043B\u044E\u0447\u0438\u0442\u044C\u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435\u0440\u0430\u0431\u043E\u0442\u044B\u0441\u0444\u0430\u0439\u043B\u0430\u043C\u0438 \u043F\u043E\u0434\u0440\u043E\u0431\u043D\u043E\u0435\u043F\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043B\u0435\u043D\u0438\u0435\u043E\u0448\u0438\u0431\u043A\u0438 \u043F\u043E\u043A\u0430\u0437\u0430\u0442\u044C\u0432\u0432\u043E\u0434\u0434\u0430\u0442\u044B \u043F\u043E\u043A\u0430\u0437\u0430\u0442\u044C\u0432\u0432\u043E\u0434\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044F \u043F\u043E\u043A\u0430\u0437\u0430\u0442\u044C\u0432\u0432\u043E\u0434\u0441\u0442\u0440\u043E\u043A\u0438 \u043F\u043E\u043A\u0430\u0437\u0430\u0442\u044C\u0432\u0432\u043E\u0434\u0447\u0438\u0441\u043B\u0430 \u043F\u043E\u043A\u0430\u0437\u0430\u0442\u044C\u0432\u043E\u043F\u0440\u043E\u0441 \u043F\u043E\u043A\u0430\u0437\u0430\u0442\u044C\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u043F\u043E\u043A\u0430\u0437\u0430\u0442\u044C\u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u044E\u043E\u0431\u043E\u0448\u0438\u0431\u043A\u0435 \u043F\u043E\u043A\u0430\u0437\u0430\u0442\u044C\u043D\u0430\u043A\u0430\u0440\u0442\u0435 \u043F\u043E\u043A\u0430\u0437\u0430\u0442\u044C\u043E\u043F\u043E\u0432\u0435\u0449\u0435\u043D\u0438\u0435\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F \u043F\u043E\u043A\u0430\u0437\u0430\u0442\u044C\u043F\u0440\u0435\u0434\u0443\u043F\u0440\u0435\u0436\u0434\u0435\u043D\u0438\u0435 \u043F\u043E\u043B\u043D\u043E\u0435\u0438\u043C\u044F\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044Ccom\u043E\u0431\u044A\u0435\u043A\u0442 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044Cxml\u0442\u0438\u043F \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0430\u0434\u0440\u0435\u0441\u043F\u043E\u043C\u0435\u0441\u0442\u043E\u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u044E \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0431\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u043A\u0443\u0441\u0435\u0430\u043D\u0441\u043E\u0432 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0432\u0440\u0435\u043C\u044F\u0437\u0430\u0432\u0435\u0440\u0448\u0435\u043D\u0438\u044F\u0441\u043F\u044F\u0449\u0435\u0433\u043E\u0441\u0435\u0430\u043D\u0441\u0430 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0432\u0440\u0435\u043C\u044F\u0437\u0430\u0441\u044B\u043F\u0430\u043D\u0438\u044F\u043F\u0430\u0441\u0441\u0438\u0432\u043D\u043E\u0433\u043E\u0441\u0435\u0430\u043D\u0441\u0430 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0432\u0440\u0435\u043C\u044F\u043E\u0436\u0438\u0434\u0430\u043D\u0438\u044F\u0431\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0434\u0430\u043D\u043D\u044B\u0435\u0432\u044B\u0431\u043E\u0440\u0430 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0434\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u044B\u0439\u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u043A\u043B\u0438\u0435\u043D\u0442\u0430\u043B\u0438\u0446\u0435\u043D\u0437\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0434\u043E\u043F\u0443\u0441\u0442\u0438\u043C\u044B\u0435\u043A\u043E\u0434\u044B\u043B\u043E\u043A\u0430\u043B\u0438\u0437\u0430\u0446\u0438\u0438 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0434\u043E\u043F\u0443\u0441\u0442\u0438\u043C\u044B\u0435\u0447\u0430\u0441\u043E\u0432\u044B\u0435\u043F\u043E\u044F\u0441\u0430 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A\u043A\u043B\u0438\u0435\u043D\u0442\u0441\u043A\u043E\u0433\u043E\u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u044F \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A\u0441\u0438\u0441\u0442\u0435\u043C\u044B \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044F\u043E\u0442\u0431\u043E\u0440\u0430\u0436\u0443\u0440\u043D\u0430\u043B\u0430\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0446\u0438\u0438 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0438\u0434\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0442\u043E\u0440\u043A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u0438 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0438\u0437\u0432\u0440\u0435\u043C\u0435\u043D\u043D\u043E\u0433\u043E\u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0438\u043C\u044F\u0432\u0440\u0435\u043C\u0435\u043D\u043D\u043E\u0433\u043E\u0444\u0430\u0439\u043B\u0430 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0438\u043C\u044F\u043A\u043B\u0438\u0435\u043D\u0442\u0430\u043B\u0438\u0446\u0435\u043D\u0437\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u044E\u044D\u043A\u0440\u0430\u043D\u043E\u0432\u043A\u043B\u0438\u0435\u043D\u0442\u0430 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u0436\u0443\u0440\u043D\u0430\u043B\u0430\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0446\u0438\u0438 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u0441\u043E\u0431\u044B\u0442\u0438\u044F\u0436\u0443\u0440\u043D\u0430\u043B\u0430\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0446\u0438\u0438 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u043A\u0440\u0430\u0442\u043A\u0438\u0439\u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A\u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u044F \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u043C\u0430\u043A\u0435\u0442\u043E\u0444\u043E\u0440\u043C\u043B\u0435\u043D\u0438\u044F \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u043C\u0430\u0441\u043A\u0443\u0432\u0441\u0435\u0444\u0430\u0439\u043B\u044B \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u043C\u0430\u0441\u043A\u0443\u0432\u0441\u0435\u0444\u0430\u0439\u043B\u044B\u043A\u043B\u0438\u0435\u043D\u0442\u0430 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u043C\u0430\u0441\u043A\u0443\u0432\u0441\u0435\u0444\u0430\u0439\u043B\u044B\u0441\u0435\u0440\u0432\u0435\u0440\u0430 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u043C\u0435\u0441\u0442\u043E\u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u043F\u043E\u0430\u0434\u0440\u0435\u0441\u0443 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u043C\u0438\u043D\u0438\u043C\u0430\u043B\u044C\u043D\u0443\u044E\u0434\u043B\u0438\u043D\u0443\u043F\u0430\u0440\u043E\u043B\u0435\u0439\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u0435\u0439 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u043D\u0430\u0432\u0438\u0433\u0430\u0446\u0438\u043E\u043D\u043D\u0443\u044E\u0441\u0441\u044B\u043B\u043A\u0443 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u043D\u0430\u0432\u0438\u0433\u0430\u0446\u0438\u043E\u043D\u043D\u0443\u044E\u0441\u0441\u044B\u043B\u043A\u0443\u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u043E\u043D\u043D\u043E\u0439\u0431\u0430\u0437\u044B \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u0435\u043A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u0438\u0431\u0430\u0437\u044B\u0434\u0430\u043D\u043D\u044B\u0445 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u0435\u043F\u0440\u0435\u0434\u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u043D\u044B\u0445\u0434\u0430\u043D\u043D\u044B\u0445\u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u043E\u043D\u043D\u043E\u0439\u0431\u0430\u0437\u044B \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u043E\u0431\u0449\u0438\u0439\u043C\u0430\u043A\u0435\u0442 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u043E\u0431\u0449\u0443\u044E\u0444\u043E\u0440\u043C\u0443 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u043E\u043A\u043D\u0430 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u043E\u043F\u0435\u0440\u0430\u0442\u0438\u0432\u043D\u0443\u044E\u043E\u0442\u043C\u0435\u0442\u043A\u0443\u0432\u0440\u0435\u043C\u0435\u043D\u0438 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u043E\u0442\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u0435\u0431\u0435\u0437\u043E\u043F\u0430\u0441\u043D\u043E\u0433\u043E\u0440\u0435\u0436\u0438\u043C\u0430 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u044B\u0444\u0443\u043D\u043A\u0446\u0438\u043E\u043D\u0430\u043B\u044C\u043D\u044B\u0445\u043E\u043F\u0446\u0438\u0439\u0438\u043D\u0442\u0435\u0440\u0444\u0435\u0439\u0441\u0430 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u043F\u043E\u043B\u043D\u043E\u0435\u0438\u043C\u044F\u043F\u0440\u0435\u0434\u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u043D\u043E\u0433\u043E\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044F \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u043F\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043B\u0435\u043D\u0438\u044F\u043D\u0430\u0432\u0438\u0433\u0430\u0446\u0438\u043E\u043D\u043D\u044B\u0445\u0441\u0441\u044B\u043B\u043E\u043A \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u043F\u0440\u043E\u0432\u0435\u0440\u043A\u0443\u0441\u043B\u043E\u0436\u043D\u043E\u0441\u0442\u0438\u043F\u0430\u0440\u043E\u043B\u0435\u0439\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u0435\u0439 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0440\u0430\u0437\u0434\u0435\u043B\u0438\u0442\u0435\u043B\u044C\u043F\u0443\u0442\u0438 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0440\u0430\u0437\u0434\u0435\u043B\u0438\u0442\u0435\u043B\u044C\u043F\u0443\u0442\u0438\u043A\u043B\u0438\u0435\u043D\u0442\u0430 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0440\u0430\u0437\u0434\u0435\u043B\u0438\u0442\u0435\u043B\u044C\u043F\u0443\u0442\u0438\u0441\u0435\u0440\u0432\u0435\u0440\u0430 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0441\u0435\u0430\u043D\u0441\u044B\u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u043E\u043D\u043D\u043E\u0439\u0431\u0430\u0437\u044B \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0441\u043A\u043E\u0440\u043E\u0441\u0442\u044C\u043A\u043B\u0438\u0435\u043D\u0442\u0441\u043A\u043E\u0433\u043E\u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u044F \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u044F\u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u043E\u043D\u043D\u043E\u0439\u0431\u0430\u0437\u044B \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u044F\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044E \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0438\u0435\u043E\u0431\u044A\u0435\u043A\u0442\u0430\u0438\u0444\u043E\u0440\u043C\u044B \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0441\u043E\u0441\u0442\u0430\u0432\u0441\u0442\u0430\u043D\u0434\u0430\u0440\u0442\u043D\u043E\u0433\u043E\u0438\u043D\u0442\u0435\u0440\u0444\u0435\u0439\u0441\u0430odata \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0441\u0442\u0440\u0443\u043A\u0442\u0443\u0440\u0443\u0445\u0440\u0430\u043D\u0435\u043D\u0438\u044F\u0431\u0430\u0437\u044B\u0434\u0430\u043D\u043D\u044B\u0445 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0442\u0435\u043A\u0443\u0449\u0438\u0439\u0441\u0435\u0430\u043D\u0441\u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u043E\u043D\u043D\u043E\u0439\u0431\u0430\u0437\u044B \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0444\u0430\u0439\u043B \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0444\u0430\u0439\u043B\u044B \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0444\u043E\u0440\u043C\u0443 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0444\u0443\u043D\u043A\u0446\u0438\u043E\u043D\u0430\u043B\u044C\u043D\u0443\u044E\u043E\u043F\u0446\u0438\u044E \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0444\u0443\u043D\u043A\u0446\u0438\u043E\u043D\u0430\u043B\u044C\u043D\u0443\u044E\u043E\u043F\u0446\u0438\u044E\u0438\u043D\u0442\u0435\u0440\u0444\u0435\u0439\u0441\u0430 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0447\u0430\u0441\u043E\u0432\u043E\u0439\u043F\u043E\u044F\u0441\u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u043E\u043D\u043D\u043E\u0439\u0431\u0430\u0437\u044B \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u0438\u043E\u0441 \u043F\u043E\u043C\u0435\u0441\u0442\u0438\u0442\u044C\u0432\u043E\u0432\u0440\u0435\u043C\u0435\u043D\u043D\u043E\u0435\u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0435 \u043F\u043E\u043C\u0435\u0441\u0442\u0438\u0442\u044C\u0444\u0430\u0439\u043B \u043F\u043E\u043C\u0435\u0441\u0442\u0438\u0442\u044C\u0444\u0430\u0439\u043B\u044B \u043F\u0440\u0430\u0432 \u043F\u0440\u0430\u0432\u043E\u0434\u043E\u0441\u0442\u0443\u043F\u0430 \u043F\u0440\u0435\u0434\u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u043D\u043E\u0435\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u043F\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043B\u0435\u043D\u0438\u0435\u043A\u043E\u0434\u0430\u043B\u043E\u043A\u0430\u043B\u0438\u0437\u0430\u0446\u0438\u0438 \u043F\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043B\u0435\u043D\u0438\u0435\u043F\u0435\u0440\u0438\u043E\u0434\u0430 \u043F\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043B\u0435\u043D\u0438\u0435\u043F\u0440\u0430\u0432\u0430 \u043F\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043B\u0435\u043D\u0438\u0435\u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u044F \u043F\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043B\u0435\u043D\u0438\u0435\u0441\u043E\u0431\u044B\u0442\u0438\u044F\u0436\u0443\u0440\u043D\u0430\u043B\u0430\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0446\u0438\u0438 \u043F\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043B\u0435\u043D\u0438\u0435\u0447\u0430\u0441\u043E\u0432\u043E\u0433\u043E\u043F\u043E\u044F\u0441\u0430 \u043F\u0440\u0435\u0434\u0443\u043F\u0440\u0435\u0436\u0434\u0435\u043D\u0438\u0435 \u043F\u0440\u0435\u043A\u0440\u0430\u0442\u0438\u0442\u044C\u0440\u0430\u0431\u043E\u0442\u0443\u0441\u0438\u0441\u0442\u0435\u043C\u044B \u043F\u0440\u0438\u0432\u0438\u043B\u0435\u0433\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u044B\u0439\u0440\u0435\u0436\u0438\u043C \u043F\u0440\u043E\u0434\u043E\u043B\u0436\u0438\u0442\u044C\u0432\u044B\u0437\u043E\u0432 \u043F\u0440\u043E\u0447\u0438\u0442\u0430\u0442\u044Cjson \u043F\u0440\u043E\u0447\u0438\u0442\u0430\u0442\u044Cxml \u043F\u0440\u043E\u0447\u0438\u0442\u0430\u0442\u044C\u0434\u0430\u0442\u0443json \u043F\u0443\u0441\u0442\u0430\u044F\u0441\u0442\u0440\u043E\u043A\u0430 \u0440\u0430\u0431\u043E\u0447\u0438\u0439\u043A\u0430\u0442\u0430\u043B\u043E\u0433\u0434\u0430\u043D\u043D\u044B\u0445\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F \u0440\u0430\u0437\u0431\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u0430\u0442\u044C\u0434\u0430\u043D\u043D\u044B\u0435\u0434\u043B\u044F\u0440\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F \u0440\u0430\u0437\u0434\u0435\u043B\u0438\u0442\u044C\u0444\u0430\u0439\u043B \u0440\u0430\u0437\u043E\u0440\u0432\u0430\u0442\u044C\u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0435\u0441\u0432\u043D\u0435\u0448\u043D\u0438\u043C\u0438\u0441\u0442\u043E\u0447\u043D\u0438\u043A\u043E\u043C\u0434\u0430\u043D\u043D\u044B\u0445 \u0440\u0430\u0441\u043A\u043E\u0434\u0438\u0440\u043E\u0432\u0430\u0442\u044C\u0441\u0442\u0440\u043E\u043A\u0443 \u0440\u043E\u043B\u044C\u0434\u043E\u0441\u0442\u0443\u043F\u043D\u0430 \u0441\u0435\u043A\u0443\u043D\u0434\u0430 \u0441\u0438\u0433\u043D\u0430\u043B \u0441\u0438\u043C\u0432\u043E\u043B \u0441\u043A\u043E\u043F\u0438\u0440\u043E\u0432\u0430\u0442\u044C\u0436\u0443\u0440\u043D\u0430\u043B\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0446\u0438\u0438 \u0441\u043C\u0435\u0449\u0435\u043D\u0438\u0435\u043B\u0435\u0442\u043D\u0435\u0433\u043E\u0432\u0440\u0435\u043C\u0435\u043D\u0438 \u0441\u043C\u0435\u0449\u0435\u043D\u0438\u0435\u0441\u0442\u0430\u043D\u0434\u0430\u0440\u0442\u043D\u043E\u0433\u043E\u0432\u0440\u0435\u043C\u0435\u043D\u0438 \u0441\u043E\u0435\u0434\u0438\u043D\u0438\u0442\u044C\u0431\u0443\u0444\u0435\u0440\u044B\u0434\u0432\u043E\u0438\u0447\u043D\u044B\u0445\u0434\u0430\u043D\u043D\u044B\u0445 \u0441\u043E\u0437\u0434\u0430\u0442\u044C\u043A\u0430\u0442\u0430\u043B\u043E\u0433 \u0441\u043E\u0437\u0434\u0430\u0442\u044C\u0444\u0430\u0431\u0440\u0438\u043A\u0443xdto \u0441\u043E\u043A\u0440\u043B \u0441\u043E\u043A\u0440\u043B\u043F \u0441\u043E\u043A\u0440\u043F \u0441\u043E\u043E\u0431\u0449\u0438\u0442\u044C \u0441\u043E\u0441\u0442\u043E\u044F\u043D\u0438\u0435 \u0441\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u044C\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0441\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u044C\u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F \u0441\u0440\u0435\u0434 \u0441\u0442\u0440\u0434\u043B\u0438\u043D\u0430 \u0441\u0442\u0440\u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0435\u0442\u0441\u044F\u043D\u0430 \u0441\u0442\u0440\u0437\u0430\u043C\u0435\u043D\u0438\u0442\u044C \u0441\u0442\u0440\u043D\u0430\u0439\u0442\u0438 \u0441\u0442\u0440\u043D\u0430\u0447\u0438\u043D\u0430\u0435\u0442\u0441\u044F\u0441 \u0441\u0442\u0440\u043E\u043A\u0430 \u0441\u0442\u0440\u043E\u043A\u0430\u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u044F\u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u043E\u043D\u043D\u043E\u0439\u0431\u0430\u0437\u044B \u0441\u0442\u0440\u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0441\u0442\u0440\u043E\u043A\u0443 \u0441\u0442\u0440\u0440\u0430\u0437\u0434\u0435\u043B\u0438\u0442\u044C \u0441\u0442\u0440\u0441\u043E\u0435\u0434\u0438\u043D\u0438\u0442\u044C \u0441\u0442\u0440\u0441\u0440\u0430\u0432\u043D\u0438\u0442\u044C \u0441\u0442\u0440\u0447\u0438\u0441\u043B\u043E\u0432\u0445\u043E\u0436\u0434\u0435\u043D\u0438\u0439 \u0441\u0442\u0440\u0447\u0438\u0441\u043B\u043E\u0441\u0442\u0440\u043E\u043A \u0441\u0442\u0440\u0448\u0430\u0431\u043B\u043E\u043D \u0442\u0435\u043A\u0443\u0449\u0430\u044F\u0434\u0430\u0442\u0430 \u0442\u0435\u043A\u0443\u0449\u0430\u044F\u0434\u0430\u0442\u0430\u0441\u0435\u0430\u043D\u0441\u0430 \u0442\u0435\u043A\u0443\u0449\u0430\u044F\u0443\u043D\u0438\u0432\u0435\u0440\u0441\u0430\u043B\u044C\u043D\u0430\u044F\u0434\u0430\u0442\u0430 \u0442\u0435\u043A\u0443\u0449\u0430\u044F\u0443\u043D\u0438\u0432\u0435\u0440\u0441\u0430\u043B\u044C\u043D\u0430\u044F\u0434\u0430\u0442\u0430\u0432\u043C\u0438\u043B\u043B\u0438\u0441\u0435\u043A\u0443\u043D\u0434\u0430\u0445 \u0442\u0435\u043A\u0443\u0449\u0438\u0439\u0432\u0430\u0440\u0438\u0430\u043D\u0442\u0438\u043D\u0442\u0435\u0440\u0444\u0435\u0439\u0441\u0430\u043A\u043B\u0438\u0435\u043D\u0442\u0441\u043A\u043E\u0433\u043E\u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u044F \u0442\u0435\u043A\u0443\u0449\u0438\u0439\u0432\u0430\u0440\u0438\u0430\u043D\u0442\u043E\u0441\u043D\u043E\u0432\u043D\u043E\u0433\u043E\u0448\u0440\u0438\u0444\u0442\u0430\u043A\u043B\u0438\u0435\u043D\u0442\u0441\u043A\u043E\u0433\u043E\u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u044F \u0442\u0435\u043A\u0443\u0449\u0438\u0439\u043A\u043E\u0434\u043B\u043E\u043A\u0430\u043B\u0438\u0437\u0430\u0446\u0438\u0438 \u0442\u0435\u043A\u0443\u0449\u0438\u0439\u0440\u0435\u0436\u0438\u043C\u0437\u0430\u043F\u0443\u0441\u043A\u0430 \u0442\u0435\u043A\u0443\u0449\u0438\u0439\u044F\u0437\u044B\u043A \u0442\u0435\u043A\u0443\u0449\u0438\u0439\u044F\u0437\u044B\u043A\u0441\u0438\u0441\u0442\u0435\u043C\u044B \u0442\u0438\u043F \u0442\u0438\u043F\u0437\u043D\u0447 \u0442\u0440\u0430\u043D\u0437\u0430\u043A\u0446\u0438\u044F\u0430\u043A\u0442\u0438\u0432\u043D\u0430 \u0442\u0440\u0435\u0433 \u0443\u0434\u0430\u043B\u0438\u0442\u044C\u0434\u0430\u043D\u043D\u044B\u0435\u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u043E\u043D\u043D\u043E\u0439\u0431\u0430\u0437\u044B \u0443\u0434\u0430\u043B\u0438\u0442\u044C\u0438\u0437\u0432\u0440\u0435\u043C\u0435\u043D\u043D\u043E\u0433\u043E\u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430 \u0443\u0434\u0430\u043B\u0438\u0442\u044C\u043E\u0431\u044A\u0435\u043A\u0442\u044B \u0443\u0434\u0430\u043B\u0438\u0442\u044C\u0444\u0430\u0439\u043B\u044B \u0443\u043D\u0438\u0432\u0435\u0440\u0441\u0430\u043B\u044C\u043D\u043E\u0435\u0432\u0440\u0435\u043C\u044F \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u0431\u0435\u0437\u043E\u043F\u0430\u0441\u043D\u044B\u0439\u0440\u0435\u0436\u0438\u043C \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u0431\u0435\u0437\u043E\u043F\u0430\u0441\u043D\u044B\u0439\u0440\u0435\u0436\u0438\u043C\u0440\u0430\u0437\u0434\u0435\u043B\u0435\u043D\u0438\u044F\u0434\u0430\u043D\u043D\u044B\u0445 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u0431\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u043A\u0443\u0441\u0435\u0430\u043D\u0441\u043E\u0432 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u0432\u043D\u0435\u0448\u043D\u044E\u044E\u043A\u043E\u043C\u043F\u043E\u043D\u0435\u043D\u0442\u0443 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u0432\u0440\u0435\u043C\u044F\u0437\u0430\u0432\u0435\u0440\u0448\u0435\u043D\u0438\u044F\u0441\u043F\u044F\u0449\u0435\u0433\u043E\u0441\u0435\u0430\u043D\u0441\u0430 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u0432\u0440\u0435\u043C\u044F\u0437\u0430\u0441\u044B\u043F\u0430\u043D\u0438\u044F\u043F\u0430\u0441\u0441\u0438\u0432\u043D\u043E\u0433\u043E\u0441\u0435\u0430\u043D\u0441\u0430 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u0432\u0440\u0435\u043C\u044F\u043E\u0436\u0438\u0434\u0430\u043D\u0438\u044F\u0431\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A\u043A\u043B\u0438\u0435\u043D\u0442\u0441\u043A\u043E\u0433\u043E\u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u044F \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A\u0441\u0438\u0441\u0442\u0435\u043C\u044B \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u0436\u0443\u0440\u043D\u0430\u043B\u0430\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0446\u0438\u0438 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u0441\u043E\u0431\u044B\u0442\u0438\u044F\u0436\u0443\u0440\u043D\u0430\u043B\u0430\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0446\u0438\u0438 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u043A\u0440\u0430\u0442\u043A\u0438\u0439\u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A\u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u044F \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u043C\u0438\u043D\u0438\u043C\u0430\u043B\u044C\u043D\u0443\u044E\u0434\u043B\u0438\u043D\u0443\u043F\u0430\u0440\u043E\u043B\u0435\u0439\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u0435\u0439 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u043C\u043E\u043D\u043E\u043F\u043E\u043B\u044C\u043D\u044B\u0439\u0440\u0435\u0436\u0438\u043C \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438\u043A\u043B\u0438\u0435\u043D\u0442\u0430\u043B\u0438\u0446\u0435\u043D\u0437\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u0435\u043F\u0440\u0435\u0434\u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u043D\u044B\u0445\u0434\u0430\u043D\u043D\u044B\u0445\u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u043E\u043D\u043D\u043E\u0439\u0431\u0430\u0437\u044B \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u043E\u0442\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u0435\u0431\u0435\u0437\u043E\u043F\u0430\u0441\u043D\u043E\u0433\u043E\u0440\u0435\u0436\u0438\u043C\u0430 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u044B\u0444\u0443\u043D\u043A\u0446\u0438\u043E\u043D\u0430\u043B\u044C\u043D\u044B\u0445\u043E\u043F\u0446\u0438\u0439\u0438\u043D\u0442\u0435\u0440\u0444\u0435\u0439\u0441\u0430 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u043F\u0440\u0438\u0432\u0438\u043B\u0435\u0433\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u044B\u0439\u0440\u0435\u0436\u0438\u043C \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u043F\u0440\u043E\u0432\u0435\u0440\u043A\u0443\u0441\u043B\u043E\u0436\u043D\u043E\u0441\u0442\u0438\u043F\u0430\u0440\u043E\u043B\u0435\u0439\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u0435\u0439 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435\u0440\u0430\u0431\u043E\u0442\u044B\u0441\u043A\u0440\u0438\u043F\u0442\u043E\u0433\u0440\u0430\u0444\u0438\u0435\u0439 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435\u0440\u0430\u0431\u043E\u0442\u044B\u0441\u0444\u0430\u0439\u043B\u0430\u043C\u0438 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0435\u0441\u0432\u043D\u0435\u0448\u043D\u0438\u043C\u0438\u0441\u0442\u043E\u0447\u043D\u0438\u043A\u043E\u043C\u0434\u0430\u043D\u043D\u044B\u0445 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0438\u0435\u043E\u0431\u044A\u0435\u043A\u0442\u0430\u0438\u0444\u043E\u0440\u043C\u044B \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u0441\u043E\u0441\u0442\u0430\u0432\u0441\u0442\u0430\u043D\u0434\u0430\u0440\u0442\u043D\u043E\u0433\u043E\u0438\u043D\u0442\u0435\u0440\u0444\u0435\u0439\u0441\u0430odata \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u0447\u0430\u0441\u043E\u0432\u043E\u0439\u043F\u043E\u044F\u0441\u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u043E\u043D\u043D\u043E\u0439\u0431\u0430\u0437\u044B \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u0447\u0430\u0441\u043E\u0432\u043E\u0439\u043F\u043E\u044F\u0441\u0441\u0435\u0430\u043D\u0441\u0430 \u0444\u043E\u0440\u043C\u0430\u0442 \u0446\u0435\u043B \u0447\u0430\u0441 \u0447\u0430\u0441\u043E\u0432\u043E\u0439\u043F\u043E\u044F\u0441 \u0447\u0430\u0441\u043E\u0432\u043E\u0439\u043F\u043E\u044F\u0441\u0441\u0435\u0430\u043D\u0441\u0430 \u0447\u0438\u0441\u043B\u043E \u0447\u0438\u0441\u043B\u043E\u043F\u0440\u043E\u043F\u0438\u0441\u044C\u044E \u044D\u0442\u043E\u0430\u0434\u0440\u0435\u0441\u0432\u0440\u0435\u043C\u0435\u043D\u043D\u043E\u0433\u043E\u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430 ";
      var v8_global_context_property = "ws\u0441\u0441\u044B\u043B\u043A\u0438 \u0431\u0438\u0431\u043B\u0438\u043E\u0442\u0435\u043A\u0430\u043A\u0430\u0440\u0442\u0438\u043D\u043E\u043A \u0431\u0438\u0431\u043B\u0438\u043E\u0442\u0435\u043A\u0430\u043C\u0430\u043A\u0435\u0442\u043E\u0432\u043E\u0444\u043E\u0440\u043C\u043B\u0435\u043D\u0438\u044F\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0431\u0438\u0431\u043B\u0438\u043E\u0442\u0435\u043A\u0430\u0441\u0442\u0438\u043B\u0435\u0439 \u0431\u0438\u0437\u043D\u0435\u0441\u043F\u0440\u043E\u0446\u0435\u0441\u0441\u044B \u0432\u043D\u0435\u0448\u043D\u0438\u0435\u0438\u0441\u0442\u043E\u0447\u043D\u0438\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0432\u043D\u0435\u0448\u043D\u0438\u0435\u043E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0438 \u0432\u043D\u0435\u0448\u043D\u0438\u0435\u043E\u0442\u0447\u0435\u0442\u044B \u0432\u0441\u0442\u0440\u043E\u0435\u043D\u043D\u044B\u0435\u043F\u043E\u043A\u0443\u043F\u043A\u0438 \u0433\u043B\u0430\u0432\u043D\u044B\u0439\u0438\u043D\u0442\u0435\u0440\u0444\u0435\u0439\u0441 \u0433\u043B\u0430\u0432\u043D\u044B\u0439\u0441\u0442\u0438\u043B\u044C \u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u044B \u0434\u043E\u0441\u0442\u0430\u0432\u043B\u044F\u0435\u043C\u044B\u0435\u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u044F \u0436\u0443\u0440\u043D\u0430\u043B\u044B\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u043E\u0432 \u0437\u0430\u0434\u0430\u0447\u0438 \u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u044F\u043E\u0431\u0438\u043D\u0442\u0435\u0440\u043D\u0435\u0442\u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0438 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u0440\u0430\u0431\u043E\u0447\u0435\u0439\u0434\u0430\u0442\u044B \u0438\u0441\u0442\u043E\u0440\u0438\u044F\u0440\u0430\u0431\u043E\u0442\u044B\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F \u043A\u043E\u043D\u0441\u0442\u0430\u043D\u0442\u044B \u043A\u0440\u0438\u0442\u0435\u0440\u0438\u0438\u043E\u0442\u0431\u043E\u0440\u0430 \u043C\u0435\u0442\u0430\u0434\u0430\u043D\u043D\u044B\u0435 \u043E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0438 \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u0440\u0435\u043A\u043B\u0430\u043C\u044B \u043E\u0442\u043F\u0440\u0430\u0432\u043A\u0430\u0434\u043E\u0441\u0442\u0430\u0432\u043B\u044F\u0435\u043C\u044B\u0445\u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0439 \u043E\u0442\u0447\u0435\u0442\u044B \u043F\u0430\u043D\u0435\u043B\u044C\u0437\u0430\u0434\u0430\u0447\u043E\u0441 \u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u0437\u0430\u043F\u0443\u0441\u043A\u0430 \u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u044B\u0441\u0435\u0430\u043D\u0441\u0430 \u043F\u0435\u0440\u0435\u0447\u0438\u0441\u043B\u0435\u043D\u0438\u044F \u043F\u043B\u0430\u043D\u044B\u0432\u0438\u0434\u043E\u0432\u0440\u0430\u0441\u0447\u0435\u0442\u0430 \u043F\u043B\u0430\u043D\u044B\u0432\u0438\u0434\u043E\u0432\u0445\u0430\u0440\u0430\u043A\u0442\u0435\u0440\u0438\u0441\u0442\u0438\u043A \u043F\u043B\u0430\u043D\u044B\u043E\u0431\u043C\u0435\u043D\u0430 \u043F\u043B\u0430\u043D\u044B\u0441\u0447\u0435\u0442\u043E\u0432 \u043F\u043E\u043B\u043D\u043E\u0442\u0435\u043A\u0441\u0442\u043E\u0432\u044B\u0439\u043F\u043E\u0438\u0441\u043A \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u0438\u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u043E\u043D\u043D\u043E\u0439\u0431\u0430\u0437\u044B \u043F\u043E\u0441\u043B\u0435\u0434\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u0438 \u043F\u0440\u043E\u0432\u0435\u0440\u043A\u0430\u0432\u0441\u0442\u0440\u043E\u0435\u043D\u043D\u044B\u0445\u043F\u043E\u043A\u0443\u043F\u043E\u043A \u0440\u0430\u0431\u043E\u0447\u0430\u044F\u0434\u0430\u0442\u0430 \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F\u043A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u0438 \u0440\u0435\u0433\u0438\u0441\u0442\u0440\u044B\u0431\u0443\u0445\u0433\u0430\u043B\u0442\u0435\u0440\u0438\u0438 \u0440\u0435\u0433\u0438\u0441\u0442\u0440\u044B\u043D\u0430\u043A\u043E\u043F\u043B\u0435\u043D\u0438\u044F \u0440\u0435\u0433\u0438\u0441\u0442\u0440\u044B\u0440\u0430\u0441\u0447\u0435\u0442\u0430 \u0440\u0435\u0433\u0438\u0441\u0442\u0440\u044B\u0441\u0432\u0435\u0434\u0435\u043D\u0438\u0439 \u0440\u0435\u0433\u043B\u0430\u043C\u0435\u043D\u0442\u043D\u044B\u0435\u0437\u0430\u0434\u0430\u043D\u0438\u044F \u0441\u0435\u0440\u0438\u0430\u043B\u0438\u0437\u0430\u0442\u043E\u0440xdto \u0441\u043F\u0440\u0430\u0432\u043E\u0447\u043D\u0438\u043A\u0438 \u0441\u0440\u0435\u0434\u0441\u0442\u0432\u0430\u0433\u0435\u043E\u043F\u043E\u0437\u0438\u0446\u0438\u043E\u043D\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F \u0441\u0440\u0435\u0434\u0441\u0442\u0432\u0430\u043A\u0440\u0438\u043F\u0442\u043E\u0433\u0440\u0430\u0444\u0438\u0438 \u0441\u0440\u0435\u0434\u0441\u0442\u0432\u0430\u043C\u0443\u043B\u044C\u0442\u0438\u043C\u0435\u0434\u0438\u0430 \u0441\u0440\u0435\u0434\u0441\u0442\u0432\u0430\u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u044F\u0440\u0435\u043A\u043B\u0430\u043C\u044B \u0441\u0440\u0435\u0434\u0441\u0442\u0432\u0430\u043F\u043E\u0447\u0442\u044B \u0441\u0440\u0435\u0434\u0441\u0442\u0432\u0430\u0442\u0435\u043B\u0435\u0444\u043E\u043D\u0438\u0438 \u0444\u0430\u0431\u0440\u0438\u043A\u0430xdto \u0444\u0430\u0439\u043B\u043E\u0432\u044B\u0435\u043F\u043E\u0442\u043E\u043A\u0438 \u0444\u043E\u043D\u043E\u0432\u044B\u0435\u0437\u0430\u0434\u0430\u043D\u0438\u044F \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430\u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043A \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0435\u0432\u0430\u0440\u0438\u0430\u043D\u0442\u043E\u0432\u043E\u0442\u0447\u0435\u0442\u043E\u0432 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0435\u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043A\u0434\u0430\u043D\u043D\u044B\u0445\u0444\u043E\u0440\u043C \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0435\u043E\u0431\u0449\u0438\u0445\u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043A \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0435\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u0441\u043A\u0438\u0445\u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043A\u0434\u0438\u043D\u0430\u043C\u0438\u0447\u0435\u0441\u043A\u0438\u0445\u0441\u043F\u0438\u0441\u043A\u043E\u0432 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0435\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u0441\u043A\u0438\u0445\u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043A\u043E\u0442\u0447\u0435\u0442\u043E\u0432 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0435\u0441\u0438\u0441\u0442\u0435\u043C\u043D\u044B\u0445\u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043A ";
      var BUILTIN = v7_system_constants + v7_global_context_methods + v8_global_context_methods + v8_global_context_property;
      var v8_system_sets_of_values = "web\u0446\u0432\u0435\u0442\u0430 windows\u0446\u0432\u0435\u0442\u0430 windows\u0448\u0440\u0438\u0444\u0442\u044B \u0431\u0438\u0431\u043B\u0438\u043E\u0442\u0435\u043A\u0430\u043A\u0430\u0440\u0442\u0438\u043D\u043E\u043A \u0440\u0430\u043C\u043A\u0438\u0441\u0442\u0438\u043B\u044F \u0441\u0438\u043C\u0432\u043E\u043B\u044B \u0446\u0432\u0435\u0442\u0430\u0441\u0442\u0438\u043B\u044F \u0448\u0440\u0438\u0444\u0442\u044B\u0441\u0442\u0438\u043B\u044F ";
      var v8_system_enums_interface = "\u0430\u0432\u0442\u043E\u043C\u0430\u0442\u0438\u0447\u0435\u0441\u043A\u043E\u0435\u0441\u043E\u0445\u0440\u0430\u043D\u0435\u043D\u0438\u0435\u0434\u0430\u043D\u043D\u044B\u0445\u0444\u043E\u0440\u043C\u044B\u0432\u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0430\u0445 \u0430\u0432\u0442\u043E\u043D\u0443\u043C\u0435\u0440\u0430\u0446\u0438\u044F\u0432\u0444\u043E\u0440\u043C\u0435 \u0430\u0432\u0442\u043E\u0440\u0430\u0437\u0434\u0432\u0438\u0436\u0435\u043D\u0438\u0435\u0441\u0435\u0440\u0438\u0439 \u0430\u043D\u0438\u043C\u0430\u0446\u0438\u044F\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u0432\u0430\u0440\u0438\u0430\u043D\u0442\u0432\u044B\u0440\u0430\u0432\u043D\u0438\u0432\u0430\u043D\u0438\u044F\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432\u0438\u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043A\u043E\u0432 \u0432\u0430\u0440\u0438\u0430\u043D\u0442\u0443\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u044F\u0432\u044B\u0441\u043E\u0442\u043E\u0439\u0442\u0430\u0431\u043B\u0438\u0446\u044B \u0432\u0435\u0440\u0442\u0438\u043A\u0430\u043B\u044C\u043D\u0430\u044F\u043F\u0440\u043E\u043A\u0440\u0443\u0442\u043A\u0430\u0444\u043E\u0440\u043C\u044B \u0432\u0435\u0440\u0442\u0438\u043A\u0430\u043B\u044C\u043D\u043E\u0435\u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435 \u0432\u0435\u0440\u0442\u0438\u043A\u0430\u043B\u044C\u043D\u043E\u0435\u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430 \u0432\u0438\u0434\u0433\u0440\u0443\u043F\u043F\u044B\u0444\u043E\u0440\u043C\u044B \u0432\u0438\u0434\u0434\u0435\u043A\u043E\u0440\u0430\u0446\u0438\u0438\u0444\u043E\u0440\u043C\u044B \u0432\u0438\u0434\u0434\u043E\u043F\u043E\u043B\u043D\u0435\u043D\u0438\u044F\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u0444\u043E\u0440\u043C\u044B \u0432\u0438\u0434\u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u044F\u0434\u0430\u043D\u043D\u044B\u0445 \u0432\u0438\u0434\u043A\u043D\u043E\u043F\u043A\u0438\u0444\u043E\u0440\u043C\u044B \u0432\u0438\u0434\u043F\u0435\u0440\u0435\u043A\u043B\u044E\u0447\u0430\u0442\u0435\u043B\u044F \u0432\u0438\u0434\u043F\u043E\u0434\u043F\u0438\u0441\u0435\u0439\u043A\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u0435 \u0432\u0438\u0434\u043F\u043E\u043B\u044F\u0444\u043E\u0440\u043C\u044B \u0432\u0438\u0434\u0444\u043B\u0430\u0436\u043A\u0430 \u0432\u043B\u0438\u044F\u043D\u0438\u0435\u0440\u0430\u0437\u043C\u0435\u0440\u0430\u043D\u0430\u043F\u0443\u0437\u044B\u0440\u0435\u043A\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u0433\u043E\u0440\u0438\u0437\u043E\u043D\u0442\u0430\u043B\u044C\u043D\u043E\u0435\u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435 \u0433\u043E\u0440\u0438\u0437\u043E\u043D\u0442\u0430\u043B\u044C\u043D\u043E\u0435\u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430 \u0433\u0440\u0443\u043F\u043F\u0438\u0440\u043E\u0432\u043A\u0430\u043A\u043E\u043B\u043E\u043D\u043E\u043A \u0433\u0440\u0443\u043F\u043F\u0438\u0440\u043E\u0432\u043A\u0430\u043F\u043E\u0434\u0447\u0438\u043D\u0435\u043D\u043D\u044B\u0445\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432\u0444\u043E\u0440\u043C\u044B \u0433\u0440\u0443\u043F\u043F\u044B\u0438\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B \u0434\u0435\u0439\u0441\u0442\u0432\u0438\u0435\u043F\u0435\u0440\u0435\u0442\u0430\u0441\u043A\u0438\u0432\u0430\u043D\u0438\u044F \u0434\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u044B\u0439\u0440\u0435\u0436\u0438\u043C\u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u044F \u0434\u043E\u043F\u0443\u0441\u0442\u0438\u043C\u044B\u0435\u0434\u0435\u0439\u0441\u0442\u0432\u0438\u044F\u043F\u0435\u0440\u0435\u0442\u0430\u0441\u043A\u0438\u0432\u0430\u043D\u0438\u044F \u0438\u043D\u0442\u0435\u0440\u0432\u0430\u043B\u043C\u0435\u0436\u0434\u0443\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u043C\u0438\u0444\u043E\u0440\u043C\u044B \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u0432\u044B\u0432\u043E\u0434\u0430 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u043F\u043E\u043B\u043E\u0441\u044B\u043F\u0440\u043E\u043A\u0440\u0443\u0442\u043A\u0438 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0435\u043C\u043E\u0435\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435\u0442\u043E\u0447\u043A\u0438\u0431\u0438\u0440\u0436\u0435\u0432\u043E\u0439\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u0438\u0441\u0442\u043E\u0440\u0438\u044F\u0432\u044B\u0431\u043E\u0440\u0430\u043F\u0440\u0438\u0432\u0432\u043E\u0434\u0435 \u0438\u0441\u0442\u043E\u0447\u043D\u0438\u043A\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0439\u043E\u0441\u0438\u0442\u043E\u0447\u0435\u043A\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u0438\u0441\u0442\u043E\u0447\u043D\u0438\u043A\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044F\u0440\u0430\u0437\u043C\u0435\u0440\u0430\u043F\u0443\u0437\u044B\u0440\u044C\u043A\u0430\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u043A\u0430\u0442\u0435\u0433\u043E\u0440\u0438\u044F\u0433\u0440\u0443\u043F\u043F\u044B\u043A\u043E\u043C\u0430\u043D\u0434 \u043C\u0430\u043A\u0441\u0438\u043C\u0443\u043C\u0441\u0435\u0440\u0438\u0439 \u043D\u0430\u0447\u0430\u043B\u044C\u043D\u043E\u0435\u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u0434\u0435\u0440\u0435\u0432\u0430 \u043D\u0430\u0447\u0430\u043B\u044C\u043D\u043E\u0435\u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u0441\u043F\u0438\u0441\u043A\u0430 \u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u0435\u0442\u0435\u043A\u0441\u0442\u0430\u0440\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F \u043E\u0440\u0438\u0435\u043D\u0442\u0430\u0446\u0438\u044F\u0434\u0435\u043D\u0434\u0440\u043E\u0433\u0440\u0430\u043C\u043C\u044B \u043E\u0440\u0438\u0435\u043D\u0442\u0430\u0446\u0438\u044F\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u043E\u0440\u0438\u0435\u043D\u0442\u0430\u0446\u0438\u044F\u043C\u0435\u0442\u043E\u043A\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u043E\u0440\u0438\u0435\u043D\u0442\u0430\u0446\u0438\u044F\u043C\u0435\u0442\u043E\u043A\u0441\u0432\u043E\u0434\u043D\u043E\u0439\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u043E\u0440\u0438\u0435\u043D\u0442\u0430\u0446\u0438\u044F\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u0444\u043E\u0440\u043C\u044B \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u0432\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u0435 \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u0432\u043B\u0435\u0433\u0435\u043D\u0434\u0435\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u0433\u0440\u0443\u043F\u043F\u044B\u043A\u043D\u043E\u043F\u043E\u043A \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043A\u0430\u0448\u043A\u0430\u043B\u044B\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0439\u0441\u0432\u043E\u0434\u043D\u043E\u0439\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044F\u0438\u0437\u043C\u0435\u0440\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0439\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u0438\u043D\u0442\u0435\u0440\u0432\u0430\u043B\u0430\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B\u0433\u0430\u043D\u0442\u0430 \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u043A\u043D\u043E\u043F\u043A\u0438 \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u043A\u043D\u043E\u043F\u043A\u0438\u0432\u044B\u0431\u043E\u0440\u0430 \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u043E\u0431\u0441\u0443\u0436\u0434\u0435\u043D\u0438\u0439\u0444\u043E\u0440\u043C\u044B \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u043E\u0431\u044B\u0447\u043D\u043E\u0439\u0433\u0440\u0443\u043F\u043F\u044B \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u043E\u0442\u0440\u0438\u0446\u0430\u0442\u0435\u043B\u044C\u043D\u044B\u0445\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0439\u043F\u0443\u0437\u044B\u0440\u044C\u043A\u043E\u0432\u043E\u0439\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u043F\u0430\u043D\u0435\u043B\u0438\u043F\u043E\u0438\u0441\u043A\u0430 \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u043F\u043E\u0434\u0441\u043A\u0430\u0437\u043A\u0438 \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u043F\u0440\u0435\u0434\u0443\u043F\u0440\u0435\u0436\u0434\u0435\u043D\u0438\u044F\u043F\u0440\u0438\u0440\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0438 \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u0440\u0430\u0437\u043C\u0435\u0442\u043A\u0438\u043F\u043E\u043B\u043E\u0441\u044B\u0440\u0435\u0433\u0443\u043B\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u0441\u0442\u0440\u0430\u043D\u0438\u0446\u0444\u043E\u0440\u043C\u044B \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u0442\u0430\u0431\u043B\u0438\u0446\u044B \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u0442\u0435\u043A\u0441\u0442\u0430\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044F\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B\u0433\u0430\u043D\u0442\u0430 \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u0443\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u044F\u043E\u0431\u044B\u0447\u043D\u043E\u0439\u0433\u0440\u0443\u043F\u043F\u044B \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u0444\u0438\u0433\u0443\u0440\u044B\u043A\u043D\u043E\u043F\u043A\u0438 \u043F\u0430\u043B\u0438\u0442\u0440\u0430\u0446\u0432\u0435\u0442\u043E\u0432\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u043F\u043E\u0432\u0435\u0434\u0435\u043D\u0438\u0435\u043E\u0431\u044B\u0447\u043D\u043E\u0439\u0433\u0440\u0443\u043F\u043F\u044B \u043F\u043E\u0434\u0434\u0435\u0440\u0436\u043A\u0430\u043C\u0430\u0441\u0448\u0442\u0430\u0431\u0430\u0434\u0435\u043D\u0434\u0440\u043E\u0433\u0440\u0430\u043C\u043C\u044B \u043F\u043E\u0434\u0434\u0435\u0440\u0436\u043A\u0430\u043C\u0430\u0441\u0448\u0442\u0430\u0431\u0430\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B\u0433\u0430\u043D\u0442\u0430 \u043F\u043E\u0434\u0434\u0435\u0440\u0436\u043A\u0430\u043C\u0430\u0441\u0448\u0442\u0430\u0431\u0430\u0441\u0432\u043E\u0434\u043D\u043E\u0439\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u043F\u043E\u0438\u0441\u043A\u0432\u0442\u0430\u0431\u043B\u0438\u0446\u0435\u043F\u0440\u0438\u0432\u0432\u043E\u0434\u0435 \u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043A\u0430\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u0444\u043E\u0440\u043C\u044B \u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u043A\u0430\u0440\u0442\u0438\u043D\u043A\u0438\u043A\u043D\u043E\u043F\u043A\u0438\u0444\u043E\u0440\u043C\u044B \u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u043A\u0430\u0440\u0442\u0438\u043D\u043A\u0438\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u0433\u0440\u0430\u0444\u0438\u0447\u0435\u0441\u043A\u043E\u0439\u0441\u0445\u0435\u043C\u044B \u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u043A\u043E\u043C\u0430\u043D\u0434\u043D\u043E\u0439\u043F\u0430\u043D\u0435\u043B\u0438\u0444\u043E\u0440\u043C\u044B \u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u043A\u043E\u043C\u0430\u043D\u0434\u043D\u043E\u0439\u043F\u0430\u043D\u0435\u043B\u0438\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u0444\u043E\u0440\u043C\u044B \u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u043E\u043F\u043E\u0440\u043D\u043E\u0439\u0442\u043E\u0447\u043A\u0438\u043E\u0442\u0440\u0438\u0441\u043E\u0432\u043A\u0438 \u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u043F\u043E\u0434\u043F\u0438\u0441\u0435\u0439\u043A\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u0435 \u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u043F\u043E\u0434\u043F\u0438\u0441\u0435\u0439\u0448\u043A\u0430\u043B\u044B\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0439\u0438\u0437\u043C\u0435\u0440\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0439\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u0441\u043E\u0441\u0442\u043E\u044F\u043D\u0438\u044F\u043F\u0440\u043E\u0441\u043C\u043E\u0442\u0440\u0430 \u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u0441\u0442\u0440\u043E\u043A\u0438\u043F\u043E\u0438\u0441\u043A\u0430 \u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u0442\u0435\u043A\u0441\u0442\u0430\u0441\u043E\u0435\u0434\u0438\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0439\u043B\u0438\u043D\u0438\u0438 \u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u0443\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u044F\u043F\u043E\u0438\u0441\u043A\u043E\u043C \u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u0448\u043A\u0430\u043B\u044B\u0432\u0440\u0435\u043C\u0435\u043D\u0438 \u043F\u043E\u0440\u044F\u0434\u043E\u043A\u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u044F\u0442\u043E\u0447\u0435\u043A\u0433\u043E\u0440\u0438\u0437\u043E\u043D\u0442\u0430\u043B\u044C\u043D\u043E\u0439\u0433\u0438\u0441\u0442\u043E\u0433\u0440\u0430\u043C\u043C\u044B \u043F\u043E\u0440\u044F\u0434\u043E\u043A\u0441\u0435\u0440\u0438\u0439\u0432\u043B\u0435\u0433\u0435\u043D\u0434\u0435\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u0440\u0430\u0437\u043C\u0435\u0440\u043A\u0430\u0440\u0442\u0438\u043D\u043A\u0438 \u0440\u0430\u0441\u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043A\u0430\u0448\u043A\u0430\u043B\u044B\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u0440\u0430\u0441\u0442\u044F\u0433\u0438\u0432\u0430\u043D\u0438\u0435\u043F\u043E\u0432\u0435\u0440\u0442\u0438\u043A\u0430\u043B\u0438\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B\u0433\u0430\u043D\u0442\u0430 \u0440\u0435\u0436\u0438\u043C\u0430\u0432\u0442\u043E\u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u044F\u0441\u043E\u0441\u0442\u043E\u044F\u043D\u0438\u044F \u0440\u0435\u0436\u0438\u043C\u0432\u0432\u043E\u0434\u0430\u0441\u0442\u0440\u043E\u043A\u0442\u0430\u0431\u043B\u0438\u0446\u044B \u0440\u0435\u0436\u0438\u043C\u0432\u044B\u0431\u043E\u0440\u0430\u043D\u0435\u0437\u0430\u043F\u043E\u043B\u043D\u0435\u043D\u043D\u043E\u0433\u043E \u0440\u0435\u0436\u0438\u043C\u0432\u044B\u0434\u0435\u043B\u0435\u043D\u0438\u044F\u0434\u0430\u0442\u044B \u0440\u0435\u0436\u0438\u043C\u0432\u044B\u0434\u0435\u043B\u0435\u043D\u0438\u044F\u0441\u0442\u0440\u043E\u043A\u0438\u0442\u0430\u0431\u043B\u0438\u0446\u044B \u0440\u0435\u0436\u0438\u043C\u0432\u044B\u0434\u0435\u043B\u0435\u043D\u0438\u044F\u0442\u0430\u0431\u043B\u0438\u0446\u044B \u0440\u0435\u0436\u0438\u043C\u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u044F\u0440\u0430\u0437\u043C\u0435\u0440\u0430 \u0440\u0435\u0436\u0438\u043C\u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u044F\u0441\u0432\u044F\u0437\u0430\u043D\u043D\u043E\u0433\u043E\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044F \u0440\u0435\u0436\u0438\u043C\u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u044F\u0434\u0438\u0430\u043B\u043E\u0433\u0430\u043F\u0435\u0447\u0430\u0442\u0438 \u0440\u0435\u0436\u0438\u043C\u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u044F\u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u0430\u043A\u043E\u043C\u0430\u043D\u0434\u044B \u0440\u0435\u0436\u0438\u043C\u043C\u0430\u0441\u0448\u0442\u0430\u0431\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F\u043F\u0440\u043E\u0441\u043C\u043E\u0442\u0440\u0430 \u0440\u0435\u0436\u0438\u043C\u043E\u0441\u043D\u043E\u0432\u043D\u043E\u0433\u043E\u043E\u043A\u043D\u0430\u043A\u043B\u0438\u0435\u043D\u0442\u0441\u043A\u043E\u0433\u043E\u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u044F \u0440\u0435\u0436\u0438\u043C\u043E\u0442\u043A\u0440\u044B\u0442\u0438\u044F\u043E\u043A\u043D\u0430\u0444\u043E\u0440\u043C\u044B \u0440\u0435\u0436\u0438\u043C\u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u044F\u0432\u044B\u0434\u0435\u043B\u0435\u043D\u0438\u044F \u0440\u0435\u0436\u0438\u043C\u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u044F\u0433\u0435\u043E\u0433\u0440\u0430\u0444\u0438\u0447\u0435\u0441\u043A\u043E\u0439\u0441\u0445\u0435\u043C\u044B \u0440\u0435\u0436\u0438\u043C\u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u044F\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0439\u0441\u0435\u0440\u0438\u0438 \u0440\u0435\u0436\u0438\u043C\u043E\u0442\u0440\u0438\u0441\u043E\u0432\u043A\u0438\u0441\u0435\u0442\u043A\u0438\u0433\u0440\u0430\u0444\u0438\u0447\u0435\u0441\u043A\u043E\u0439\u0441\u0445\u0435\u043C\u044B \u0440\u0435\u0436\u0438\u043C\u043F\u043E\u043B\u0443\u043F\u0440\u043E\u0437\u0440\u0430\u0447\u043D\u043E\u0441\u0442\u0438\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u0440\u0435\u0436\u0438\u043C\u043F\u0440\u043E\u0431\u0435\u043B\u043E\u0432\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u0440\u0435\u0436\u0438\u043C\u0440\u0430\u0437\u043C\u0435\u0449\u0435\u043D\u0438\u044F\u043D\u0430\u0441\u0442\u0440\u0430\u043D\u0438\u0446\u0435 \u0440\u0435\u0436\u0438\u043C\u0440\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F\u043A\u043E\u043B\u043E\u043D\u043A\u0438 \u0440\u0435\u0436\u0438\u043C\u0441\u0433\u043B\u0430\u0436\u0438\u0432\u0430\u043D\u0438\u044F\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u0440\u0435\u0436\u0438\u043C\u0441\u0433\u043B\u0430\u0436\u0438\u0432\u0430\u043D\u0438\u044F\u0438\u043D\u0434\u0438\u043A\u0430\u0442\u043E\u0440\u0430 \u0440\u0435\u0436\u0438\u043C\u0441\u043F\u0438\u0441\u043A\u0430\u0437\u0430\u0434\u0430\u0447 \u0441\u043A\u0432\u043E\u0437\u043D\u043E\u0435\u0432\u044B\u0440\u0430\u0432\u043D\u0438\u0432\u0430\u043D\u0438\u0435 \u0441\u043E\u0445\u0440\u0430\u043D\u0435\u043D\u0438\u0435\u0434\u0430\u043D\u043D\u044B\u0445\u0444\u043E\u0440\u043C\u044B\u0432\u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0430\u0445 \u0441\u043F\u043E\u0441\u043E\u0431\u0437\u0430\u043F\u043E\u043B\u043D\u0435\u043D\u0438\u044F\u0442\u0435\u043A\u0441\u0442\u0430\u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043A\u0430\u0448\u043A\u0430\u043B\u044B\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u0441\u043F\u043E\u0441\u043E\u0431\u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u0438\u044F\u043E\u0433\u0440\u0430\u043D\u0438\u0447\u0438\u0432\u0430\u044E\u0449\u0435\u0433\u043E\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044F\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u0441\u0442\u0430\u043D\u0434\u0430\u0440\u0442\u043D\u0430\u044F\u0433\u0440\u0443\u043F\u043F\u0430\u043A\u043E\u043C\u0430\u043D\u0434 \u0441\u0442\u0430\u043D\u0434\u0430\u0440\u0442\u043D\u043E\u0435\u043E\u0444\u043E\u0440\u043C\u043B\u0435\u043D\u0438\u0435 \u0441\u0442\u0430\u0442\u0443\u0441\u043E\u043F\u043E\u0432\u0435\u0449\u0435\u043D\u0438\u044F\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F \u0441\u0442\u0438\u043B\u044C\u0441\u0442\u0440\u0435\u043B\u043A\u0438 \u0442\u0438\u043F\u0430\u043F\u043F\u0440\u043E\u043A\u0441\u0438\u043C\u0430\u0446\u0438\u0438\u043B\u0438\u043D\u0438\u0438\u0442\u0440\u0435\u043D\u0434\u0430\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u0442\u0438\u043F\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u0442\u0438\u043F\u0435\u0434\u0438\u043D\u0438\u0446\u044B\u0448\u043A\u0430\u043B\u044B\u0432\u0440\u0435\u043C\u0435\u043D\u0438 \u0442\u0438\u043F\u0438\u043C\u043F\u043E\u0440\u0442\u0430\u0441\u0435\u0440\u0438\u0439\u0441\u043B\u043E\u044F\u0433\u0435\u043E\u0433\u0440\u0430\u0444\u0438\u0447\u0435\u0441\u043A\u043E\u0439\u0441\u0445\u0435\u043C\u044B \u0442\u0438\u043F\u043B\u0438\u043D\u0438\u0438\u0433\u0435\u043E\u0433\u0440\u0430\u0444\u0438\u0447\u0435\u0441\u043A\u043E\u0439\u0441\u0445\u0435\u043C\u044B \u0442\u0438\u043F\u043B\u0438\u043D\u0438\u0438\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u0442\u0438\u043F\u043C\u0430\u0440\u043A\u0435\u0440\u0430\u0433\u0435\u043E\u0433\u0440\u0430\u0444\u0438\u0447\u0435\u0441\u043A\u043E\u0439\u0441\u0445\u0435\u043C\u044B \u0442\u0438\u043F\u043C\u0430\u0440\u043A\u0435\u0440\u0430\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u0442\u0438\u043F\u043E\u0431\u043B\u0430\u0441\u0442\u0438\u043E\u0444\u043E\u0440\u043C\u043B\u0435\u043D\u0438\u044F \u0442\u0438\u043F\u043E\u0440\u0433\u0430\u043D\u0438\u0437\u0430\u0446\u0438\u0438\u0438\u0441\u0442\u043E\u0447\u043D\u0438\u043A\u0430\u0434\u0430\u043D\u043D\u044B\u0445\u0433\u0435\u043E\u0433\u0440\u0430\u0444\u0438\u0447\u0435\u0441\u043A\u043E\u0439\u0441\u0445\u0435\u043C\u044B \u0442\u0438\u043F\u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u044F\u0441\u0435\u0440\u0438\u0438\u0441\u043B\u043E\u044F\u0433\u0435\u043E\u0433\u0440\u0430\u0444\u0438\u0447\u0435\u0441\u043A\u043E\u0439\u0441\u0445\u0435\u043C\u044B \u0442\u0438\u043F\u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u044F\u0442\u043E\u0447\u0435\u0447\u043D\u043E\u0433\u043E\u043E\u0431\u044A\u0435\u043A\u0442\u0430\u0433\u0435\u043E\u0433\u0440\u0430\u0444\u0438\u0447\u0435\u0441\u043A\u043E\u0439\u0441\u0445\u0435\u043C\u044B \u0442\u0438\u043F\u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u044F\u0448\u043A\u0430\u043B\u044B\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u043B\u0435\u0433\u0435\u043D\u0434\u044B\u0433\u0435\u043E\u0433\u0440\u0430\u0444\u0438\u0447\u0435\u0441\u043A\u043E\u0439\u0441\u0445\u0435\u043C\u044B \u0442\u0438\u043F\u043F\u043E\u0438\u0441\u043A\u0430\u043E\u0431\u044A\u0435\u043A\u0442\u043E\u0432\u0433\u0435\u043E\u0433\u0440\u0430\u0444\u0438\u0447\u0435\u0441\u043A\u043E\u0439\u0441\u0445\u0435\u043C\u044B \u0442\u0438\u043F\u043F\u0440\u043E\u0435\u043A\u0446\u0438\u0438\u0433\u0435\u043E\u0433\u0440\u0430\u0444\u0438\u0447\u0435\u0441\u043A\u043E\u0439\u0441\u0445\u0435\u043C\u044B \u0442\u0438\u043F\u0440\u0430\u0437\u043C\u0435\u0449\u0435\u043D\u0438\u044F\u0438\u0437\u043C\u0435\u0440\u0435\u043D\u0438\u0439 \u0442\u0438\u043F\u0440\u0430\u0437\u043C\u0435\u0449\u0435\u043D\u0438\u044F\u0440\u0435\u043A\u0432\u0438\u0437\u0438\u0442\u043E\u0432\u0438\u0437\u043C\u0435\u0440\u0435\u043D\u0438\u0439 \u0442\u0438\u043F\u0440\u0430\u043C\u043A\u0438\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u0443\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u044F \u0442\u0438\u043F\u0441\u0432\u043E\u0434\u043D\u043E\u0439\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u0442\u0438\u043F\u0441\u0432\u044F\u0437\u0438\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B\u0433\u0430\u043D\u0442\u0430 \u0442\u0438\u043F\u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u044F\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0439\u043F\u043E\u0441\u0435\u0440\u0438\u044F\u043C\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u0442\u0438\u043F\u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u044F\u0442\u043E\u0447\u0435\u043A\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u0442\u0438\u043F\u0441\u043E\u0435\u0434\u0438\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0439\u043B\u0438\u043D\u0438\u0438 \u0442\u0438\u043F\u0441\u0442\u043E\u0440\u043E\u043D\u044B\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u0433\u0440\u0430\u0444\u0438\u0447\u0435\u0441\u043A\u043E\u0439\u0441\u0445\u0435\u043C\u044B \u0442\u0438\u043F\u0444\u043E\u0440\u043C\u044B\u043E\u0442\u0447\u0435\u0442\u0430 \u0442\u0438\u043F\u0448\u043A\u0430\u043B\u044B\u0440\u0430\u0434\u0430\u0440\u043D\u043E\u0439\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u0444\u0430\u043A\u0442\u043E\u0440\u043B\u0438\u043D\u0438\u0438\u0442\u0440\u0435\u043D\u0434\u0430\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u0444\u0438\u0433\u0443\u0440\u0430\u043A\u043D\u043E\u043F\u043A\u0438 \u0444\u0438\u0433\u0443\u0440\u044B\u0433\u0440\u0430\u0444\u0438\u0447\u0435\u0441\u043A\u043E\u0439\u0441\u0445\u0435\u043C\u044B \u0444\u0438\u043A\u0441\u0430\u0446\u0438\u044F\u0432\u0442\u0430\u0431\u043B\u0438\u0446\u0435 \u0444\u043E\u0440\u043C\u0430\u0442\u0434\u043D\u044F\u0448\u043A\u0430\u043B\u044B\u0432\u0440\u0435\u043C\u0435\u043D\u0438 \u0444\u043E\u0440\u043C\u0430\u0442\u043A\u0430\u0440\u0442\u0438\u043D\u043A\u0438 \u0448\u0438\u0440\u0438\u043D\u0430\u043F\u043E\u0434\u0447\u0438\u043D\u0435\u043D\u043D\u044B\u0445\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432\u0444\u043E\u0440\u043C\u044B ";
      var v8_system_enums_objects_properties = "\u0432\u0438\u0434\u0434\u0432\u0438\u0436\u0435\u043D\u0438\u044F\u0431\u0443\u0445\u0433\u0430\u043B\u0442\u0435\u0440\u0438\u0438 \u0432\u0438\u0434\u0434\u0432\u0438\u0436\u0435\u043D\u0438\u044F\u043D\u0430\u043A\u043E\u043F\u043B\u0435\u043D\u0438\u044F \u0432\u0438\u0434\u043F\u0435\u0440\u0438\u043E\u0434\u0430\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0440\u0430\u0441\u0447\u0435\u0442\u0430 \u0432\u0438\u0434\u0441\u0447\u0435\u0442\u0430 \u0432\u0438\u0434\u0442\u043E\u0447\u043A\u0438\u043C\u0430\u0440\u0448\u0440\u0443\u0442\u0430\u0431\u0438\u0437\u043D\u0435\u0441\u043F\u0440\u043E\u0446\u0435\u0441\u0441\u0430 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u0430\u0433\u0440\u0435\u0433\u0430\u0442\u0430\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u043D\u0430\u043A\u043E\u043F\u043B\u0435\u043D\u0438\u044F \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u0433\u0440\u0443\u043F\u043F\u0438\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u0440\u0435\u0436\u0438\u043C\u0430\u043F\u0440\u043E\u0432\u0435\u0434\u0435\u043D\u0438\u044F \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u0441\u0440\u0435\u0437\u0430 \u043F\u0435\u0440\u0438\u043E\u0434\u0438\u0447\u043D\u043E\u0441\u0442\u044C\u0430\u0433\u0440\u0435\u0433\u0430\u0442\u0430\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u043D\u0430\u043A\u043E\u043F\u043B\u0435\u043D\u0438\u044F \u0440\u0435\u0436\u0438\u043C\u0430\u0432\u0442\u043E\u0432\u0440\u0435\u043C\u044F \u0440\u0435\u0436\u0438\u043C\u0437\u0430\u043F\u0438\u0441\u0438\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430 \u0440\u0435\u0436\u0438\u043C\u043F\u0440\u043E\u0432\u0435\u0434\u0435\u043D\u0438\u044F\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430 ";
      var v8_system_enums_exchange_plans = "\u0430\u0432\u0442\u043E\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0446\u0438\u044F\u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u0439 \u0434\u043E\u043F\u0443\u0441\u0442\u0438\u043C\u044B\u0439\u043D\u043E\u043C\u0435\u0440\u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u044F \u043E\u0442\u043F\u0440\u0430\u0432\u043A\u0430\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u0434\u0430\u043D\u043D\u044B\u0445 \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u0438\u0435\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u0434\u0430\u043D\u043D\u044B\u0445 ";
      var v8_system_enums_tabular_document = "\u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u0440\u0430\u0441\u0448\u0438\u0444\u0440\u043E\u0432\u043A\u0438\u0442\u0430\u0431\u043B\u0438\u0447\u043D\u043E\u0433\u043E\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430 \u043E\u0440\u0438\u0435\u043D\u0442\u0430\u0446\u0438\u044F\u0441\u0442\u0440\u0430\u043D\u0438\u0446\u044B \u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u0438\u0442\u043E\u0433\u043E\u0432\u043A\u043E\u043B\u043E\u043D\u043E\u043A\u0441\u0432\u043E\u0434\u043D\u043E\u0439\u0442\u0430\u0431\u043B\u0438\u0446\u044B \u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u0438\u0442\u043E\u0433\u043E\u0432\u0441\u0442\u0440\u043E\u043A\u0441\u0432\u043E\u0434\u043D\u043E\u0439\u0442\u0430\u0431\u043B\u0438\u0446\u044B \u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u0442\u0435\u043A\u0441\u0442\u0430\u043E\u0442\u043D\u043E\u0441\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u043A\u0430\u0440\u0442\u0438\u043D\u043A\u0438 \u0440\u0430\u0441\u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043A\u0430\u0433\u0440\u0443\u043F\u043F\u0438\u0440\u043E\u0432\u043A\u0438\u0442\u0430\u0431\u043B\u0438\u0447\u043D\u043E\u0433\u043E\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430 \u0441\u043F\u043E\u0441\u043E\u0431\u0447\u0442\u0435\u043D\u0438\u044F\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0439\u0442\u0430\u0431\u043B\u0438\u0447\u043D\u043E\u0433\u043E\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430 \u0442\u0438\u043F\u0434\u0432\u0443\u0441\u0442\u043E\u0440\u043E\u043D\u043D\u0435\u0439\u043F\u0435\u0447\u0430\u0442\u0438 \u0442\u0438\u043F\u0437\u0430\u043F\u043E\u043B\u043D\u0435\u043D\u0438\u044F\u043E\u0431\u043B\u0430\u0441\u0442\u0438\u0442\u0430\u0431\u043B\u0438\u0447\u043D\u043E\u0433\u043E\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430 \u0442\u0438\u043F\u043A\u0443\u0440\u0441\u043E\u0440\u043E\u0432\u0442\u0430\u0431\u043B\u0438\u0447\u043D\u043E\u0433\u043E\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430 \u0442\u0438\u043F\u043B\u0438\u043D\u0438\u0438\u0440\u0438\u0441\u0443\u043D\u043A\u0430\u0442\u0430\u0431\u043B\u0438\u0447\u043D\u043E\u0433\u043E\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430 \u0442\u0438\u043F\u043B\u0438\u043D\u0438\u0438\u044F\u0447\u0435\u0439\u043A\u0438\u0442\u0430\u0431\u043B\u0438\u0447\u043D\u043E\u0433\u043E\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430 \u0442\u0438\u043F\u043D\u0430\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u044F\u043F\u0435\u0440\u0435\u0445\u043E\u0434\u0430\u0442\u0430\u0431\u043B\u0438\u0447\u043D\u043E\u0433\u043E\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430 \u0442\u0438\u043F\u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u044F\u0432\u044B\u0434\u0435\u043B\u0435\u043D\u0438\u044F\u0442\u0430\u0431\u043B\u0438\u0447\u043D\u043E\u0433\u043E\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430 \u0442\u0438\u043F\u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u044F\u043B\u0438\u043D\u0438\u0439\u0441\u0432\u043E\u0434\u043D\u043E\u0439\u0442\u0430\u0431\u043B\u0438\u0446\u044B \u0442\u0438\u043F\u0440\u0430\u0437\u043C\u0435\u0449\u0435\u043D\u0438\u044F\u0442\u0435\u043A\u0441\u0442\u0430\u0442\u0430\u0431\u043B\u0438\u0447\u043D\u043E\u0433\u043E\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430 \u0442\u0438\u043F\u0440\u0438\u0441\u0443\u043D\u043A\u0430\u0442\u0430\u0431\u043B\u0438\u0447\u043D\u043E\u0433\u043E\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430 \u0442\u0438\u043F\u0441\u043C\u0435\u0449\u0435\u043D\u0438\u044F\u0442\u0430\u0431\u043B\u0438\u0447\u043D\u043E\u0433\u043E\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430 \u0442\u0438\u043F\u0443\u0437\u043E\u0440\u0430\u0442\u0430\u0431\u043B\u0438\u0447\u043D\u043E\u0433\u043E\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430 \u0442\u0438\u043F\u0444\u0430\u0439\u043B\u0430\u0442\u0430\u0431\u043B\u0438\u0447\u043D\u043E\u0433\u043E\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430 \u0442\u043E\u0447\u043D\u043E\u0441\u0442\u044C\u043F\u0435\u0447\u0430\u0442\u0438 \u0447\u0435\u0440\u0435\u0434\u043E\u0432\u0430\u043D\u0438\u0435\u0440\u0430\u0441\u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u044F\u0441\u0442\u0440\u0430\u043D\u0438\u0446 ";
      var v8_system_enums_sheduler = "\u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u0432\u0440\u0435\u043C\u0435\u043D\u0438\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432\u043F\u043B\u0430\u043D\u0438\u0440\u043E\u0432\u0449\u0438\u043A\u0430 ";
      var v8_system_enums_formatted_document = "\u0442\u0438\u043F\u0444\u0430\u0439\u043B\u0430\u0444\u043E\u0440\u043C\u0430\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u043E\u0433\u043E\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430 ";
      var v8_system_enums_query = "\u043E\u0431\u0445\u043E\u0434\u0440\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442\u0430\u0437\u0430\u043F\u0440\u043E\u0441\u0430 \u0442\u0438\u043F\u0437\u0430\u043F\u0438\u0441\u0438\u0437\u0430\u043F\u0440\u043E\u0441\u0430 ";
      var v8_system_enums_report_builder = "\u0432\u0438\u0434\u0437\u0430\u043F\u043E\u043B\u043D\u0435\u043D\u0438\u044F\u0440\u0430\u0441\u0448\u0438\u0444\u0440\u043E\u0432\u043A\u0438\u043F\u043E\u0441\u0442\u0440\u043E\u0438\u0442\u0435\u043B\u044F\u043E\u0442\u0447\u0435\u0442\u0430 \u0442\u0438\u043F\u0434\u043E\u0431\u0430\u0432\u043B\u0435\u043D\u0438\u044F\u043F\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043B\u0435\u043D\u0438\u0439 \u0442\u0438\u043F\u0438\u0437\u043C\u0435\u0440\u0435\u043D\u0438\u044F\u043F\u043E\u0441\u0442\u0440\u043E\u0438\u0442\u0435\u043B\u044F\u043E\u0442\u0447\u0435\u0442\u0430 \u0442\u0438\u043F\u0440\u0430\u0437\u043C\u0435\u0449\u0435\u043D\u0438\u044F\u0438\u0442\u043E\u0433\u043E\u0432 ";
      var v8_system_enums_files = "\u0434\u043E\u0441\u0442\u0443\u043F\u043A\u0444\u0430\u0439\u043B\u0443 \u0440\u0435\u0436\u0438\u043C\u0434\u0438\u0430\u043B\u043E\u0433\u0430\u0432\u044B\u0431\u043E\u0440\u0430\u0444\u0430\u0439\u043B\u0430 \u0440\u0435\u0436\u0438\u043C\u043E\u0442\u043A\u0440\u044B\u0442\u0438\u044F\u0444\u0430\u0439\u043B\u0430 ";
      var v8_system_enums_query_builder = "\u0442\u0438\u043F\u0438\u0437\u043C\u0435\u0440\u0435\u043D\u0438\u044F\u043F\u043E\u0441\u0442\u0440\u043E\u0438\u0442\u0435\u043B\u044F\u0437\u0430\u043F\u0440\u043E\u0441\u0430 ";
      var v8_system_enums_data_analysis = "\u0432\u0438\u0434\u0434\u0430\u043D\u043D\u044B\u0445\u0430\u043D\u0430\u043B\u0438\u0437\u0430 \u043C\u0435\u0442\u043E\u0434\u043A\u043B\u0430\u0441\u0442\u0435\u0440\u0438\u0437\u0430\u0446\u0438\u0438 \u0442\u0438\u043F\u0435\u0434\u0438\u043D\u0438\u0446\u044B\u0438\u043D\u0442\u0435\u0440\u0432\u0430\u043B\u0430\u0432\u0440\u0435\u043C\u0435\u043D\u0438\u0430\u043D\u0430\u043B\u0438\u0437\u0430\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0438\u043F\u0437\u0430\u043F\u043E\u043B\u043D\u0435\u043D\u0438\u044F\u0442\u0430\u0431\u043B\u0438\u0446\u044B\u0440\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442\u0430\u0430\u043D\u0430\u043B\u0438\u0437\u0430\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0438\u043F\u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u044F\u0447\u0438\u0441\u043B\u043E\u0432\u044B\u0445\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0439\u0430\u043D\u0430\u043B\u0438\u0437\u0430\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0438\u043F\u0438\u0441\u0442\u043E\u0447\u043D\u0438\u043A\u0430\u0434\u0430\u043D\u043D\u044B\u0445\u043F\u043E\u0438\u0441\u043A\u0430\u0430\u0441\u0441\u043E\u0446\u0438\u0430\u0446\u0438\u0439 \u0442\u0438\u043F\u043A\u043E\u043B\u043E\u043D\u043A\u0438\u0430\u043D\u0430\u043B\u0438\u0437\u0430\u0434\u0430\u043D\u043D\u044B\u0445\u0434\u0435\u0440\u0435\u0432\u043E\u0440\u0435\u0448\u0435\u043D\u0438\u0439 \u0442\u0438\u043F\u043A\u043E\u043B\u043E\u043D\u043A\u0438\u0430\u043D\u0430\u043B\u0438\u0437\u0430\u0434\u0430\u043D\u043D\u044B\u0445\u043A\u043B\u0430\u0441\u0442\u0435\u0440\u0438\u0437\u0430\u0446\u0438\u044F \u0442\u0438\u043F\u043A\u043E\u043B\u043E\u043D\u043A\u0438\u0430\u043D\u0430\u043B\u0438\u0437\u0430\u0434\u0430\u043D\u043D\u044B\u0445\u043E\u0431\u0449\u0430\u044F\u0441\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043A\u0430 \u0442\u0438\u043F\u043A\u043E\u043B\u043E\u043D\u043A\u0438\u0430\u043D\u0430\u043B\u0438\u0437\u0430\u0434\u0430\u043D\u043D\u044B\u0445\u043F\u043E\u0438\u0441\u043A\u0430\u0441\u0441\u043E\u0446\u0438\u0430\u0446\u0438\u0439 \u0442\u0438\u043F\u043A\u043E\u043B\u043E\u043D\u043A\u0438\u0430\u043D\u0430\u043B\u0438\u0437\u0430\u0434\u0430\u043D\u043D\u044B\u0445\u043F\u043E\u0438\u0441\u043A\u043F\u043E\u0441\u043B\u0435\u0434\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u0435\u0439 \u0442\u0438\u043F\u043A\u043E\u043B\u043E\u043D\u043A\u0438\u043C\u043E\u0434\u0435\u043B\u0438\u043F\u0440\u043E\u0433\u043D\u043E\u0437\u0430 \u0442\u0438\u043F\u043C\u0435\u0440\u044B\u0440\u0430\u0441\u0441\u0442\u043E\u044F\u043D\u0438\u044F\u0430\u043D\u0430\u043B\u0438\u0437\u0430\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0438\u043F\u043E\u0442\u0441\u0435\u0447\u0435\u043D\u0438\u044F\u043F\u0440\u0430\u0432\u0438\u043B\u0430\u0441\u0441\u043E\u0446\u0438\u0430\u0446\u0438\u0438 \u0442\u0438\u043F\u043F\u043E\u043B\u044F\u0430\u043D\u0430\u043B\u0438\u0437\u0430\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0438\u043F\u0441\u0442\u0430\u043D\u0434\u0430\u0440\u0442\u0438\u0437\u0430\u0446\u0438\u0438\u0430\u043D\u0430\u043B\u0438\u0437\u0430\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0438\u043F\u0443\u043F\u043E\u0440\u044F\u0434\u043E\u0447\u0438\u0432\u0430\u043D\u0438\u044F\u043F\u0440\u0430\u0432\u0438\u043B\u0430\u0441\u0441\u043E\u0446\u0438\u0430\u0446\u0438\u0438\u0430\u043D\u0430\u043B\u0438\u0437\u0430\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0438\u043F\u0443\u043F\u043E\u0440\u044F\u0434\u043E\u0447\u0438\u0432\u0430\u043D\u0438\u044F\u0448\u0430\u0431\u043B\u043E\u043D\u043E\u0432\u043F\u043E\u0441\u043B\u0435\u0434\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u0435\u0439\u0430\u043D\u0430\u043B\u0438\u0437\u0430\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0438\u043F\u0443\u043F\u0440\u043E\u0449\u0435\u043D\u0438\u044F\u0434\u0435\u0440\u0435\u0432\u0430\u0440\u0435\u0448\u0435\u043D\u0438\u0439 ";
      var v8_system_enums_xml_json_xs_dom_xdto_ws = "ws\u043D\u0430\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u0435\u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u0430 \u0432\u0430\u0440\u0438\u0430\u043D\u0442xpathxs \u0432\u0430\u0440\u0438\u0430\u043D\u0442\u0437\u0430\u043F\u0438\u0441\u0438\u0434\u0430\u0442\u044Bjson \u0432\u0430\u0440\u0438\u0430\u043D\u0442\u043F\u0440\u043E\u0441\u0442\u043E\u0433\u043E\u0442\u0438\u043F\u0430xs \u0432\u0438\u0434\u0433\u0440\u0443\u043F\u043F\u044B\u043C\u043E\u0434\u0435\u043B\u0438xs \u0432\u0438\u0434\u0444\u0430\u0441\u0435\u0442\u0430xdto \u0434\u0435\u0439\u0441\u0442\u0432\u0438\u0435\u043F\u043E\u0441\u0442\u0440\u043E\u0438\u0442\u0435\u043B\u044Fdom \u0437\u0430\u0432\u0435\u0440\u0448\u0435\u043D\u043D\u043E\u0441\u0442\u044C\u043F\u0440\u043E\u0441\u0442\u043E\u0433\u043E\u0442\u0438\u043F\u0430xs \u0437\u0430\u0432\u0435\u0440\u0448\u0435\u043D\u043D\u043E\u0441\u0442\u044C\u0441\u043E\u0441\u0442\u0430\u0432\u043D\u043E\u0433\u043E\u0442\u0438\u043F\u0430xs \u0437\u0430\u0432\u0435\u0440\u0448\u0435\u043D\u043D\u043E\u0441\u0442\u044C\u0441\u0445\u0435\u043C\u044Bxs \u0437\u0430\u043F\u0440\u0435\u0449\u0435\u043D\u043D\u044B\u0435\u043F\u043E\u0434\u0441\u0442\u0430\u043D\u043E\u0432\u043A\u0438xs \u0438\u0441\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u044F\u0433\u0440\u0443\u043F\u043F\u043F\u043E\u0434\u0441\u0442\u0430\u043D\u043E\u0432\u043A\u0438xs \u043A\u0430\u0442\u0435\u0433\u043E\u0440\u0438\u044F\u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u044F\u0430\u0442\u0440\u0438\u0431\u0443\u0442\u0430xs \u043A\u0430\u0442\u0435\u0433\u043E\u0440\u0438\u044F\u043E\u0433\u0440\u0430\u043D\u0438\u0447\u0435\u043D\u0438\u044F\u0438\u0434\u0435\u043D\u0442\u0438\u0447\u043D\u043E\u0441\u0442\u0438xs \u043A\u0430\u0442\u0435\u0433\u043E\u0440\u0438\u044F\u043E\u0433\u0440\u0430\u043D\u0438\u0447\u0435\u043D\u0438\u044F\u043F\u0440\u043E\u0441\u0442\u0440\u0430\u043D\u0441\u0442\u0432\u0438\u043C\u0435\u043Dxs \u043C\u0435\u0442\u043E\u0434\u043D\u0430\u0441\u043B\u0435\u0434\u043E\u0432\u0430\u043D\u0438\u044Fxs \u043C\u043E\u0434\u0435\u043B\u044C\u0441\u043E\u0434\u0435\u0440\u0436\u0438\u043C\u043E\u0433\u043Exs \u043D\u0430\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435\u0442\u0438\u043F\u0430xml \u043D\u0435\u0434\u043E\u043F\u0443\u0441\u0442\u0438\u043C\u044B\u0435\u043F\u043E\u0434\u0441\u0442\u0430\u043D\u043E\u0432\u043A\u0438xs \u043E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0430\u043F\u0440\u043E\u0431\u0435\u043B\u044C\u043D\u044B\u0445\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432xs \u043E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0430\u0441\u043E\u0434\u0435\u0440\u0436\u0438\u043C\u043E\u0433\u043Exs \u043E\u0433\u0440\u0430\u043D\u0438\u0447\u0435\u043D\u0438\u0435\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044Fxs \u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u044B\u043E\u0442\u0431\u043E\u0440\u0430\u0443\u0437\u043B\u043E\u0432dom \u043F\u0435\u0440\u0435\u043D\u043E\u0441\u0441\u0442\u0440\u043E\u043Ajson \u043F\u043E\u0437\u0438\u0446\u0438\u044F\u0432\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0435dom \u043F\u0440\u043E\u0431\u0435\u043B\u044C\u043D\u044B\u0435\u0441\u0438\u043C\u0432\u043E\u043B\u044Bxml \u0442\u0438\u043F\u0430\u0442\u0440\u0438\u0431\u0443\u0442\u0430xml \u0442\u0438\u043F\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044Fjson \u0442\u0438\u043F\u043A\u0430\u043D\u043E\u043D\u0438\u0447\u0435\u0441\u043A\u043E\u0433\u043Exml \u0442\u0438\u043F\u043A\u043E\u043C\u043F\u043E\u043D\u0435\u043D\u0442\u044Bxs \u0442\u0438\u043F\u043F\u0440\u043E\u0432\u0435\u0440\u043A\u0438xml \u0442\u0438\u043F\u0440\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442\u0430domxpath \u0442\u0438\u043F\u0443\u0437\u043B\u0430dom \u0442\u0438\u043F\u0443\u0437\u043B\u0430xml \u0444\u043E\u0440\u043C\u0430xml \u0444\u043E\u0440\u043C\u0430\u043F\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043B\u0435\u043D\u0438\u044Fxs \u0444\u043E\u0440\u043C\u0430\u0442\u0434\u0430\u0442\u044Bjson \u044D\u043A\u0440\u0430\u043D\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432json ";
      var v8_system_enums_data_composition_system = "\u0432\u0438\u0434\u0441\u0440\u0430\u0432\u043D\u0435\u043D\u0438\u044F\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0434\u0435\u0439\u0441\u0442\u0432\u0438\u0435\u043E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0438\u0440\u0430\u0441\u0448\u0438\u0444\u0440\u043E\u0432\u043A\u0438\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u043D\u0430\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u0435\u0441\u043E\u0440\u0442\u0438\u0440\u043E\u0432\u043A\u0438\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0440\u0430\u0441\u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u0432\u043B\u043E\u0436\u0435\u043D\u043D\u044B\u0445\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432\u0440\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442\u0430\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0440\u0430\u0441\u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u0438\u0442\u043E\u0433\u043E\u0432\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0440\u0430\u0441\u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u0433\u0440\u0443\u043F\u043F\u0438\u0440\u043E\u0432\u043A\u0438\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0440\u0430\u0441\u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u043F\u043E\u043B\u0435\u0439\u0433\u0440\u0443\u043F\u043F\u0438\u0440\u043E\u0432\u043A\u0438\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0440\u0430\u0441\u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u043F\u043E\u043B\u044F\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0440\u0430\u0441\u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u0440\u0435\u043A\u0432\u0438\u0437\u0438\u0442\u043E\u0432\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0440\u0430\u0441\u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u0440\u0435\u0441\u0443\u0440\u0441\u043E\u0432\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0438\u043F\u0431\u0443\u0445\u0433\u0430\u043B\u0442\u0435\u0440\u0441\u043A\u043E\u0433\u043E\u043E\u0441\u0442\u0430\u0442\u043A\u0430\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0438\u043F\u0432\u044B\u0432\u043E\u0434\u0430\u0442\u0435\u043A\u0441\u0442\u0430\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0438\u043F\u0433\u0440\u0443\u043F\u043F\u0438\u0440\u043E\u0432\u043A\u0438\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0438\u043F\u0433\u0440\u0443\u043F\u043F\u044B\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432\u043E\u0442\u0431\u043E\u0440\u0430\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0438\u043F\u0434\u043E\u043F\u043E\u043B\u043D\u0435\u043D\u0438\u044F\u043F\u0435\u0440\u0438\u043E\u0434\u0430\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0438\u043F\u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043A\u0430\u043F\u043E\u043B\u0435\u0439\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0438\u043F\u043C\u0430\u043A\u0435\u0442\u0430\u0433\u0440\u0443\u043F\u043F\u0438\u0440\u043E\u0432\u043A\u0438\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0438\u043F\u043C\u0430\u043A\u0435\u0442\u0430\u043E\u0431\u043B\u0430\u0441\u0442\u0438\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0438\u043F\u043E\u0441\u0442\u0430\u0442\u043A\u0430\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0438\u043F\u043F\u0435\u0440\u0438\u043E\u0434\u0430\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0438\u043F\u0440\u0430\u0437\u043C\u0435\u0449\u0435\u043D\u0438\u044F\u0442\u0435\u043A\u0441\u0442\u0430\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0438\u043F\u0441\u0432\u044F\u0437\u0438\u043D\u0430\u0431\u043E\u0440\u043E\u0432\u0434\u0430\u043D\u043D\u044B\u0445\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0438\u043F\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u0440\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442\u0430\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0440\u0430\u0441\u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u043B\u0435\u0433\u0435\u043D\u0434\u044B\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0438\u043F\u043F\u0440\u0438\u043C\u0435\u043D\u0435\u043D\u0438\u044F\u043E\u0442\u0431\u043E\u0440\u0430\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0440\u0435\u0436\u0438\u043C\u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u044F\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0440\u0435\u0436\u0438\u043C\u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u044F\u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043A\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0441\u043E\u0441\u0442\u043E\u044F\u043D\u0438\u0435\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0441\u043F\u043E\u0441\u043E\u0431\u0432\u043E\u0441\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u044F\u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043A\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0440\u0435\u0436\u0438\u043C\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0440\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442\u0430 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u0430\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0430\u0432\u0442\u043E\u043F\u043E\u0437\u0438\u0446\u0438\u044F\u0440\u0435\u0441\u0443\u0440\u0441\u043E\u0432\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0432\u0430\u0440\u0438\u0430\u043D\u0442\u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u044F\u0433\u0440\u0443\u043F\u043F\u0438\u0440\u043E\u0432\u043A\u0438\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0440\u0430\u0441\u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u0440\u0435\u0441\u0443\u0440\u0441\u043E\u0432\u0432\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u0435\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0444\u0438\u043A\u0441\u0430\u0446\u0438\u044F\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u0443\u0441\u043B\u043E\u0432\u043D\u043E\u0433\u043E\u043E\u0444\u043E\u0440\u043C\u043B\u0435\u043D\u0438\u044F\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 ";
      var v8_system_enums_email = "\u0432\u0430\u0436\u043D\u043E\u0441\u0442\u044C\u0438\u043D\u0442\u0435\u0440\u043D\u0435\u0442\u043F\u043E\u0447\u0442\u043E\u0432\u043E\u0433\u043E\u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u044F \u043E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0430\u0442\u0435\u043A\u0441\u0442\u0430\u0438\u043D\u0442\u0435\u0440\u043D\u0435\u0442\u043F\u043E\u0447\u0442\u043E\u0432\u043E\u0433\u043E\u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u044F \u0441\u043F\u043E\u0441\u043E\u0431\u043A\u043E\u0434\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F\u0438\u043D\u0442\u0435\u0440\u043D\u0435\u0442\u043F\u043E\u0447\u0442\u043E\u0432\u043E\u0433\u043E\u0432\u043B\u043E\u0436\u0435\u043D\u0438\u044F \u0441\u043F\u043E\u0441\u043E\u0431\u043A\u043E\u0434\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F\u043D\u0435ascii\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432\u0438\u043D\u0442\u0435\u0440\u043D\u0435\u0442\u043F\u043E\u0447\u0442\u043E\u0432\u043E\u0433\u043E\u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u044F \u0442\u0438\u043F\u0442\u0435\u043A\u0441\u0442\u0430\u043F\u043E\u0447\u0442\u043E\u0432\u043E\u0433\u043E\u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u044F \u043F\u0440\u043E\u0442\u043E\u043A\u043E\u043B\u0438\u043D\u0442\u0435\u0440\u043D\u0435\u0442\u043F\u043E\u0447\u0442\u044B \u0441\u0442\u0430\u0442\u0443\u0441\u0440\u0430\u0437\u0431\u043E\u0440\u0430\u043F\u043E\u0447\u0442\u043E\u0432\u043E\u0433\u043E\u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u044F ";
      var v8_system_enums_logbook = "\u0440\u0435\u0436\u0438\u043C\u0442\u0440\u0430\u043D\u0437\u0430\u043A\u0446\u0438\u0438\u0437\u0430\u043F\u0438\u0441\u0438\u0436\u0443\u0440\u043D\u0430\u043B\u0430\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0446\u0438\u0438 \u0441\u0442\u0430\u0442\u0443\u0441\u0442\u0440\u0430\u043D\u0437\u0430\u043A\u0446\u0438\u0438\u0437\u0430\u043F\u0438\u0441\u0438\u0436\u0443\u0440\u043D\u0430\u043B\u0430\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0446\u0438\u0438 \u0443\u0440\u043E\u0432\u0435\u043D\u044C\u0436\u0443\u0440\u043D\u0430\u043B\u0430\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0446\u0438\u0438 ";
      var v8_system_enums_cryptography = "\u0440\u0430\u0441\u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430\u0441\u0435\u0440\u0442\u0438\u0444\u0438\u043A\u0430\u0442\u043E\u0432\u043A\u0440\u0438\u043F\u0442\u043E\u0433\u0440\u0430\u0444\u0438\u0438 \u0440\u0435\u0436\u0438\u043C\u0432\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u044F\u0441\u0435\u0440\u0442\u0438\u0444\u0438\u043A\u0430\u0442\u043E\u0432\u043A\u0440\u0438\u043F\u0442\u043E\u0433\u0440\u0430\u0444\u0438\u0438 \u0440\u0435\u0436\u0438\u043C\u043F\u0440\u043E\u0432\u0435\u0440\u043A\u0438\u0441\u0435\u0440\u0442\u0438\u0444\u0438\u043A\u0430\u0442\u0430\u043A\u0440\u0438\u043F\u0442\u043E\u0433\u0440\u0430\u0444\u0438\u0438 \u0442\u0438\u043F\u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430\u0441\u0435\u0440\u0442\u0438\u0444\u0438\u043A\u0430\u0442\u043E\u0432\u043A\u0440\u0438\u043F\u0442\u043E\u0433\u0440\u0430\u0444\u0438\u0438 ";
      var v8_system_enums_zip = "\u043A\u043E\u0434\u0438\u0440\u043E\u0432\u043A\u0430\u0438\u043C\u0435\u043D\u0444\u0430\u0439\u043B\u043E\u0432\u0432zip\u0444\u0430\u0439\u043B\u0435 \u043C\u0435\u0442\u043E\u0434\u0441\u0436\u0430\u0442\u0438\u044Fzip \u043C\u0435\u0442\u043E\u0434\u0448\u0438\u0444\u0440\u043E\u0432\u0430\u043D\u0438\u044Fzip \u0440\u0435\u0436\u0438\u043C\u0432\u043E\u0441\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u044F\u043F\u0443\u0442\u0435\u0439\u0444\u0430\u0439\u043B\u043E\u0432zip \u0440\u0435\u0436\u0438\u043C\u043E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0438\u043F\u043E\u0434\u043A\u0430\u0442\u0430\u043B\u043E\u0433\u043E\u0432zip \u0440\u0435\u0436\u0438\u043C\u0441\u043E\u0445\u0440\u0430\u043D\u0435\u043D\u0438\u044F\u043F\u0443\u0442\u0435\u0439zip \u0443\u0440\u043E\u0432\u0435\u043D\u044C\u0441\u0436\u0430\u0442\u0438\u044Fzip ";
      var v8_system_enums_other = "\u0437\u0432\u0443\u043A\u043E\u0432\u043E\u0435\u043E\u043F\u043E\u0432\u0435\u0449\u0435\u043D\u0438\u0435 \u043D\u0430\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u0435\u043F\u0435\u0440\u0435\u0445\u043E\u0434\u0430\u043A\u0441\u0442\u0440\u043E\u043A\u0435 \u043F\u043E\u0437\u0438\u0446\u0438\u044F\u0432\u043F\u043E\u0442\u043E\u043A\u0435 \u043F\u043E\u0440\u044F\u0434\u043E\u043A\u0431\u0430\u0439\u0442\u043E\u0432 \u0440\u0435\u0436\u0438\u043C\u0431\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0440\u0435\u0436\u0438\u043C\u0443\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u044F\u0431\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u043A\u043E\u0439\u0434\u0430\u043D\u043D\u044B\u0445 \u0441\u0435\u0440\u0432\u0438\u0441\u0432\u0441\u0442\u0440\u043E\u0435\u043D\u043D\u044B\u0445\u043F\u043E\u043A\u0443\u043F\u043E\u043A \u0441\u043E\u0441\u0442\u043E\u044F\u043D\u0438\u0435\u0444\u043E\u043D\u043E\u0432\u043E\u0433\u043E\u0437\u0430\u0434\u0430\u043D\u0438\u044F \u0442\u0438\u043F\u043F\u043E\u0434\u043F\u0438\u0441\u0447\u0438\u043A\u0430\u0434\u043E\u0441\u0442\u0430\u0432\u043B\u044F\u0435\u043C\u044B\u0445\u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0439 \u0443\u0440\u043E\u0432\u0435\u043D\u044C\u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u044F\u0437\u0430\u0449\u0438\u0449\u0435\u043D\u043D\u043E\u0433\u043E\u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u044Fftp ";
      var v8_system_enums_request_schema = "\u043D\u0430\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u0435\u043F\u043E\u0440\u044F\u0434\u043A\u0430\u0441\u0445\u0435\u043C\u044B\u0437\u0430\u043F\u0440\u043E\u0441\u0430 \u0442\u0438\u043F\u0434\u043E\u043F\u043E\u043B\u043D\u0435\u043D\u0438\u044F\u043F\u0435\u0440\u0438\u043E\u0434\u0430\u043C\u0438\u0441\u0445\u0435\u043C\u044B\u0437\u0430\u043F\u0440\u043E\u0441\u0430 \u0442\u0438\u043F\u043A\u043E\u043D\u0442\u0440\u043E\u043B\u044C\u043D\u043E\u0439\u0442\u043E\u0447\u043A\u0438\u0441\u0445\u0435\u043C\u044B\u0437\u0430\u043F\u0440\u043E\u0441\u0430 \u0442\u0438\u043F\u043E\u0431\u044A\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u044F\u0441\u0445\u0435\u043C\u044B\u0437\u0430\u043F\u0440\u043E\u0441\u0430 \u0442\u0438\u043F\u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u0430\u0434\u043E\u0441\u0442\u0443\u043F\u043D\u043E\u0439\u0442\u0430\u0431\u043B\u0438\u0446\u044B\u0441\u0445\u0435\u043C\u044B\u0437\u0430\u043F\u0440\u043E\u0441\u0430 \u0442\u0438\u043F\u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u044F\u0441\u0445\u0435\u043C\u044B\u0437\u0430\u043F\u0440\u043E\u0441\u0430 ";
      var v8_system_enums_properties_of_metadata_objects = "http\u043C\u0435\u0442\u043E\u0434 \u0430\u0432\u0442\u043E\u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u043E\u0431\u0449\u0435\u0433\u043E\u0440\u0435\u043A\u0432\u0438\u0437\u0438\u0442\u0430 \u0430\u0432\u0442\u043E\u043F\u0440\u0435\u0444\u0438\u043A\u0441\u043D\u043E\u043C\u0435\u0440\u0430\u0437\u0430\u0434\u0430\u0447\u0438 \u0432\u0430\u0440\u0438\u0430\u043D\u0442\u0432\u0441\u0442\u0440\u043E\u0435\u043D\u043D\u043E\u0433\u043E\u044F\u0437\u044B\u043A\u0430 \u0432\u0438\u0434\u0438\u0435\u0440\u0430\u0440\u0445\u0438\u0438 \u0432\u0438\u0434\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u043D\u0430\u043A\u043E\u043F\u043B\u0435\u043D\u0438\u044F \u0432\u0438\u0434\u0442\u0430\u0431\u043B\u0438\u0446\u044B\u0432\u043D\u0435\u0448\u043D\u0435\u0433\u043E\u0438\u0441\u0442\u043E\u0447\u043D\u0438\u043A\u0430\u0434\u0430\u043D\u043D\u044B\u0445 \u0437\u0430\u043F\u0438\u0441\u044C\u0434\u0432\u0438\u0436\u0435\u043D\u0438\u0439\u043F\u0440\u0438\u043F\u0440\u043E\u0432\u0435\u0434\u0435\u043D\u0438\u0438 \u0437\u0430\u043F\u043E\u043B\u043D\u0435\u043D\u0438\u0435\u043F\u043E\u0441\u043B\u0435\u0434\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u0435\u0439 \u0438\u043D\u0434\u0435\u043A\u0441\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u0431\u0430\u0437\u044B\u043F\u043B\u0430\u043D\u0430\u0432\u0438\u0434\u043E\u0432\u0440\u0430\u0441\u0447\u0435\u0442\u0430 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u0431\u044B\u0441\u0442\u0440\u043E\u0433\u043E\u0432\u044B\u0431\u043E\u0440\u0430 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u043E\u0431\u0449\u0435\u0433\u043E\u0440\u0435\u043A\u0432\u0438\u0437\u0438\u0442\u0430 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u043F\u043E\u0434\u0447\u0438\u043D\u0435\u043D\u0438\u044F \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u043F\u043E\u043B\u043D\u043E\u0442\u0435\u043A\u0441\u0442\u043E\u0432\u043E\u0433\u043E\u043F\u043E\u0438\u0441\u043A\u0430 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u0440\u0430\u0437\u0434\u0435\u043B\u044F\u0435\u043C\u044B\u0445\u0434\u0430\u043D\u043D\u044B\u0445\u043E\u0431\u0449\u0435\u0433\u043E\u0440\u0435\u043A\u0432\u0438\u0437\u0438\u0442\u0430 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u0440\u0435\u043A\u0432\u0438\u0437\u0438\u0442\u0430 \u043D\u0430\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435\u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u044F\u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u044F \u043D\u0430\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435\u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F\u043A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u0438 \u043D\u0430\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u0435\u043F\u0435\u0440\u0435\u0434\u0430\u0447\u0438 \u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u0435\u043F\u0440\u0435\u0434\u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u043D\u044B\u0445\u0434\u0430\u043D\u043D\u044B\u0445 \u043E\u043F\u0435\u0440\u0430\u0442\u0438\u0432\u043D\u043E\u0435\u043F\u0440\u043E\u0432\u0435\u0434\u0435\u043D\u0438\u0435 \u043E\u0441\u043D\u043E\u0432\u043D\u043E\u0435\u043F\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043B\u0435\u043D\u0438\u0435\u0432\u0438\u0434\u0430\u0440\u0430\u0441\u0447\u0435\u0442\u0430 \u043E\u0441\u043D\u043E\u0432\u043D\u043E\u0435\u043F\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043B\u0435\u043D\u0438\u0435\u0432\u0438\u0434\u0430\u0445\u0430\u0440\u0430\u043A\u0442\u0435\u0440\u0438\u0441\u0442\u0438\u043A\u0438 \u043E\u0441\u043D\u043E\u0432\u043D\u043E\u0435\u043F\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043B\u0435\u043D\u0438\u0435\u0437\u0430\u0434\u0430\u0447\u0438 \u043E\u0441\u043D\u043E\u0432\u043D\u043E\u0435\u043F\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043B\u0435\u043D\u0438\u0435\u043F\u043B\u0430\u043D\u0430\u043E\u0431\u043C\u0435\u043D\u0430 \u043E\u0441\u043D\u043E\u0432\u043D\u043E\u0435\u043F\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043B\u0435\u043D\u0438\u0435\u0441\u043F\u0440\u0430\u0432\u043E\u0447\u043D\u0438\u043A\u0430 \u043E\u0441\u043D\u043E\u0432\u043D\u043E\u0435\u043F\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043B\u0435\u043D\u0438\u0435\u0441\u0447\u0435\u0442\u0430 \u043F\u0435\u0440\u0435\u043C\u0435\u0449\u0435\u043D\u0438\u0435\u0433\u0440\u0430\u043D\u0438\u0446\u044B\u043F\u0440\u0438\u043F\u0440\u043E\u0432\u0435\u0434\u0435\u043D\u0438\u0438 \u043F\u0435\u0440\u0438\u043E\u0434\u0438\u0447\u043D\u043E\u0441\u0442\u044C\u043D\u043E\u043C\u0435\u0440\u0430\u0431\u0438\u0437\u043D\u0435\u0441\u043F\u0440\u043E\u0446\u0435\u0441\u0441\u0430 \u043F\u0435\u0440\u0438\u043E\u0434\u0438\u0447\u043D\u043E\u0441\u0442\u044C\u043D\u043E\u043C\u0435\u0440\u0430\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430 \u043F\u0435\u0440\u0438\u043E\u0434\u0438\u0447\u043D\u043E\u0441\u0442\u044C\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0440\u0430\u0441\u0447\u0435\u0442\u0430 \u043F\u0435\u0440\u0438\u043E\u0434\u0438\u0447\u043D\u043E\u0441\u0442\u044C\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0441\u0432\u0435\u0434\u0435\u043D\u0438\u0439 \u043F\u043E\u0432\u0442\u043E\u0440\u043D\u043E\u0435\u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u0432\u043E\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u043C\u044B\u0445\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0439 \u043F\u043E\u043B\u043D\u043E\u0442\u0435\u043A\u0441\u0442\u043E\u0432\u044B\u0439\u043F\u043E\u0438\u0441\u043A\u043F\u0440\u0438\u0432\u0432\u043E\u0434\u0435\u043F\u043E\u0441\u0442\u0440\u043E\u043A\u0435 \u043F\u0440\u0438\u043D\u0430\u0434\u043B\u0435\u0436\u043D\u043E\u0441\u0442\u044C\u043E\u0431\u044A\u0435\u043A\u0442\u0430 \u043F\u0440\u043E\u0432\u0435\u0434\u0435\u043D\u0438\u0435 \u0440\u0430\u0437\u0434\u0435\u043B\u0435\u043D\u0438\u0435\u0430\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u0438\u043E\u0431\u0449\u0435\u0433\u043E\u0440\u0435\u043A\u0432\u0438\u0437\u0438\u0442\u0430 \u0440\u0430\u0437\u0434\u0435\u043B\u0435\u043D\u0438\u0435\u0434\u0430\u043D\u043D\u044B\u0445\u043E\u0431\u0449\u0435\u0433\u043E\u0440\u0435\u043A\u0432\u0438\u0437\u0438\u0442\u0430 \u0440\u0430\u0437\u0434\u0435\u043B\u0435\u043D\u0438\u0435\u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0439\u043A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u0438\u043E\u0431\u0449\u0435\u0433\u043E\u0440\u0435\u043A\u0432\u0438\u0437\u0438\u0442\u0430 \u0440\u0435\u0436\u0438\u043C\u0430\u0432\u0442\u043E\u043D\u0443\u043C\u0435\u0440\u0430\u0446\u0438\u0438\u043E\u0431\u044A\u0435\u043A\u0442\u043E\u0432 \u0440\u0435\u0436\u0438\u043C\u0437\u0430\u043F\u0438\u0441\u0438\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430 \u0440\u0435\u0436\u0438\u043C\u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u044F\u043C\u043E\u0434\u0430\u043B\u044C\u043D\u043E\u0441\u0442\u0438 \u0440\u0435\u0436\u0438\u043C\u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u044F\u0441\u0438\u043D\u0445\u0440\u043E\u043D\u043D\u044B\u0445\u0432\u044B\u0437\u043E\u0432\u043E\u0432\u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0439\u043F\u043B\u0430\u0442\u0444\u043E\u0440\u043C\u044B\u0438\u0432\u043D\u0435\u0448\u043D\u0438\u0445\u043A\u043E\u043C\u043F\u043E\u043D\u0435\u043D\u0442 \u0440\u0435\u0436\u0438\u043C\u043F\u043E\u0432\u0442\u043E\u0440\u043D\u043E\u0433\u043E\u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u044F\u0441\u0435\u0430\u043D\u0441\u043E\u0432 \u0440\u0435\u0436\u0438\u043C\u043F\u043E\u043B\u0443\u0447\u0435\u043D\u0438\u044F\u0434\u0430\u043D\u043D\u044B\u0445\u0432\u044B\u0431\u043E\u0440\u0430\u043F\u0440\u0438\u0432\u0432\u043E\u0434\u0435\u043F\u043E\u0441\u0442\u0440\u043E\u043A\u0435 \u0440\u0435\u0436\u0438\u043C\u0441\u043E\u0432\u043C\u0435\u0441\u0442\u0438\u043C\u043E\u0441\u0442\u0438 \u0440\u0435\u0436\u0438\u043C\u0441\u043E\u0432\u043C\u0435\u0441\u0442\u0438\u043C\u043E\u0441\u0442\u0438\u0438\u043D\u0442\u0435\u0440\u0444\u0435\u0439\u0441\u0430 \u0440\u0435\u0436\u0438\u043C\u0443\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u044F\u0431\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u043A\u043E\u0439\u0434\u0430\u043D\u043D\u044B\u0445\u043F\u043E\u0443\u043C\u043E\u043B\u0447\u0430\u043D\u0438\u044E \u0441\u0435\u0440\u0438\u0438\u043A\u043E\u0434\u043E\u0432\u043F\u043B\u0430\u043D\u0430\u0432\u0438\u0434\u043E\u0432\u0445\u0430\u0440\u0430\u043A\u0442\u0435\u0440\u0438\u0441\u0442\u0438\u043A \u0441\u0435\u0440\u0438\u0438\u043A\u043E\u0434\u043E\u0432\u043F\u043B\u0430\u043D\u0430\u0441\u0447\u0435\u0442\u043E\u0432 \u0441\u0435\u0440\u0438\u0438\u043A\u043E\u0434\u043E\u0432\u0441\u043F\u0440\u0430\u0432\u043E\u0447\u043D\u0438\u043A\u0430 \u0441\u043E\u0437\u0434\u0430\u043D\u0438\u0435\u043F\u0440\u0438\u0432\u0432\u043E\u0434\u0435 \u0441\u043F\u043E\u0441\u043E\u0431\u0432\u044B\u0431\u043E\u0440\u0430 \u0441\u043F\u043E\u0441\u043E\u0431\u043F\u043E\u0438\u0441\u043A\u0430\u0441\u0442\u0440\u043E\u043A\u0438\u043F\u0440\u0438\u0432\u0432\u043E\u0434\u0435\u043F\u043E\u0441\u0442\u0440\u043E\u043A\u0435 \u0441\u043F\u043E\u0441\u043E\u0431\u0440\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F \u0442\u0438\u043F\u0434\u0430\u043D\u043D\u044B\u0445\u0442\u0430\u0431\u043B\u0438\u0446\u044B\u0432\u043D\u0435\u0448\u043D\u0435\u0433\u043E\u0438\u0441\u0442\u043E\u0447\u043D\u0438\u043A\u0430\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0438\u043F\u043A\u043E\u0434\u0430\u043F\u043B\u0430\u043D\u0430\u0432\u0438\u0434\u043E\u0432\u0440\u0430\u0441\u0447\u0435\u0442\u0430 \u0442\u0438\u043F\u043A\u043E\u0434\u0430\u0441\u043F\u0440\u0430\u0432\u043E\u0447\u043D\u0438\u043A\u0430 \u0442\u0438\u043F\u043C\u0430\u043A\u0435\u0442\u0430 \u0442\u0438\u043F\u043D\u043E\u043C\u0435\u0440\u0430\u0431\u0438\u0437\u043D\u0435\u0441\u043F\u0440\u043E\u0446\u0435\u0441\u0441\u0430 \u0442\u0438\u043F\u043D\u043E\u043C\u0435\u0440\u0430\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430 \u0442\u0438\u043F\u043D\u043E\u043C\u0435\u0440\u0430\u0437\u0430\u0434\u0430\u0447\u0438 \u0442\u0438\u043F\u0444\u043E\u0440\u043C\u044B \u0443\u0434\u0430\u043B\u0435\u043D\u0438\u0435\u0434\u0432\u0438\u0436\u0435\u043D\u0438\u0439 ";
      var v8_system_enums_differents = "\u0432\u0430\u0436\u043D\u043E\u0441\u0442\u044C\u043F\u0440\u043E\u0431\u043B\u0435\u043C\u044B\u043F\u0440\u0438\u043C\u0435\u043D\u0435\u043D\u0438\u044F\u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F\u043A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u0438 \u0432\u0430\u0440\u0438\u0430\u043D\u0442\u0438\u043D\u0442\u0435\u0440\u0444\u0435\u0439\u0441\u0430\u043A\u043B\u0438\u0435\u043D\u0442\u0441\u043A\u043E\u0433\u043E\u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u044F \u0432\u0430\u0440\u0438\u0430\u043D\u0442\u043C\u0430\u0441\u0448\u0442\u0430\u0431\u0430\u0444\u043E\u0440\u043C\u043A\u043B\u0438\u0435\u043D\u0442\u0441\u043A\u043E\u0433\u043E\u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u044F \u0432\u0430\u0440\u0438\u0430\u043D\u0442\u043E\u0441\u043D\u043E\u0432\u043D\u043E\u0433\u043E\u0448\u0440\u0438\u0444\u0442\u0430\u043A\u043B\u0438\u0435\u043D\u0442\u0441\u043A\u043E\u0433\u043E\u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u044F \u0432\u0430\u0440\u0438\u0430\u043D\u0442\u0441\u0442\u0430\u043D\u0434\u0430\u0440\u0442\u043D\u043E\u0433\u043E\u043F\u0435\u0440\u0438\u043E\u0434\u0430 \u0432\u0430\u0440\u0438\u0430\u043D\u0442\u0441\u0442\u0430\u043D\u0434\u0430\u0440\u0442\u043D\u043E\u0439\u0434\u0430\u0442\u044B\u043D\u0430\u0447\u0430\u043B\u0430 \u0432\u0438\u0434\u0433\u0440\u0430\u043D\u0438\u0446\u044B \u0432\u0438\u0434\u043A\u0430\u0440\u0442\u0438\u043D\u043A\u0438 \u0432\u0438\u0434\u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u044F\u043F\u043E\u043B\u043D\u043E\u0442\u0435\u043A\u0441\u0442\u043E\u0432\u043E\u0433\u043E\u043F\u043E\u0438\u0441\u043A\u0430 \u0432\u0438\u0434\u0440\u0430\u043C\u043A\u0438 \u0432\u0438\u0434\u0441\u0440\u0430\u0432\u043D\u0435\u043D\u0438\u044F \u0432\u0438\u0434\u0446\u0432\u0435\u0442\u0430 \u0432\u0438\u0434\u0447\u0438\u0441\u043B\u043E\u0432\u043E\u0433\u043E\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044F \u0432\u0438\u0434\u0448\u0440\u0438\u0444\u0442\u0430 \u0434\u043E\u043F\u0443\u0441\u0442\u0438\u043C\u0430\u044F\u0434\u043B\u0438\u043D\u0430 \u0434\u043E\u043F\u0443\u0441\u0442\u0438\u043C\u044B\u0439\u0437\u043D\u0430\u043A \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435byteordermark \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u043C\u0435\u0442\u0430\u0434\u0430\u043D\u043D\u044B\u0445\u043F\u043E\u043B\u043D\u043E\u0442\u0435\u043A\u0441\u0442\u043E\u0432\u043E\u0433\u043E\u043F\u043E\u0438\u0441\u043A\u0430 \u0438\u0441\u0442\u043E\u0447\u043D\u0438\u043A\u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0439\u043A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u0438 \u043A\u043B\u0430\u0432\u0438\u0448\u0430 \u043A\u043E\u0434\u0432\u043E\u0437\u0432\u0440\u0430\u0442\u0430\u0434\u0438\u0430\u043B\u043E\u0433\u0430 \u043A\u043E\u0434\u0438\u0440\u043E\u0432\u043A\u0430xbase \u043A\u043E\u0434\u0438\u0440\u043E\u0432\u043A\u0430\u0442\u0435\u043A\u0441\u0442\u0430 \u043D\u0430\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u0435\u043F\u043E\u0438\u0441\u043A\u0430 \u043D\u0430\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u0435\u0441\u043E\u0440\u0442\u0438\u0440\u043E\u0432\u043A\u0438 \u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u0435\u043F\u0440\u0435\u0434\u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u043D\u044B\u0445\u0434\u0430\u043D\u043D\u044B\u0445 \u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u0435\u043F\u0440\u0438\u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u043F\u0430\u043D\u0435\u043B\u0438\u0440\u0430\u0437\u0434\u0435\u043B\u043E\u0432 \u043F\u0440\u043E\u0432\u0435\u0440\u043A\u0430\u0437\u0430\u043F\u043E\u043B\u043D\u0435\u043D\u0438\u044F \u0440\u0435\u0436\u0438\u043C\u0434\u0438\u0430\u043B\u043E\u0433\u0430\u0432\u043E\u043F\u0440\u043E\u0441 \u0440\u0435\u0436\u0438\u043C\u0437\u0430\u043F\u0443\u0441\u043A\u0430\u043A\u043B\u0438\u0435\u043D\u0442\u0441\u043A\u043E\u0433\u043E\u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u044F \u0440\u0435\u0436\u0438\u043C\u043E\u043A\u0440\u0443\u0433\u043B\u0435\u043D\u0438\u044F \u0440\u0435\u0436\u0438\u043C\u043E\u0442\u043A\u0440\u044B\u0442\u0438\u044F\u0444\u043E\u0440\u043C\u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u044F \u0440\u0435\u0436\u0438\u043C\u043F\u043E\u043B\u043D\u043E\u0442\u0435\u043A\u0441\u0442\u043E\u0432\u043E\u0433\u043E\u043F\u043E\u0438\u0441\u043A\u0430 \u0441\u043A\u043E\u0440\u043E\u0441\u0442\u044C\u043A\u043B\u0438\u0435\u043D\u0442\u0441\u043A\u043E\u0433\u043E\u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u044F \u0441\u043E\u0441\u0442\u043E\u044F\u043D\u0438\u0435\u0432\u043D\u0435\u0448\u043D\u0435\u0433\u043E\u0438\u0441\u0442\u043E\u0447\u043D\u0438\u043A\u0430\u0434\u0430\u043D\u043D\u044B\u0445 \u0441\u043E\u0441\u0442\u043E\u044F\u043D\u0438\u0435\u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u044F\u043A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u0438\u0431\u0430\u0437\u044B\u0434\u0430\u043D\u043D\u044B\u0445 \u0441\u043F\u043E\u0441\u043E\u0431\u0432\u044B\u0431\u043E\u0440\u0430\u0441\u0435\u0440\u0442\u0438\u0444\u0438\u043A\u0430\u0442\u0430windows \u0441\u043F\u043E\u0441\u043E\u0431\u043A\u043E\u0434\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F\u0441\u0442\u0440\u043E\u043A\u0438 \u0441\u0442\u0430\u0442\u0443\u0441\u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u044F \u0442\u0438\u043F\u0432\u043D\u0435\u0448\u043D\u0435\u0439\u043A\u043E\u043C\u043F\u043E\u043D\u0435\u043D\u0442\u044B \u0442\u0438\u043F\u043F\u043B\u0430\u0442\u0444\u043E\u0440\u043C\u044B \u0442\u0438\u043F\u043F\u043E\u0432\u0435\u0434\u0435\u043D\u0438\u044F\u043A\u043B\u0430\u0432\u0438\u0448\u0438enter \u0442\u0438\u043F\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u0438\u043E\u0432\u044B\u043F\u043E\u043B\u043D\u0435\u043D\u0438\u0438\u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u044F\u043A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u0438\u0431\u0430\u0437\u044B\u0434\u0430\u043D\u043D\u044B\u0445 \u0443\u0440\u043E\u0432\u0435\u043D\u044C\u0438\u0437\u043E\u043B\u044F\u0446\u0438\u0438\u0442\u0440\u0430\u043D\u0437\u0430\u043A\u0446\u0438\u0439 \u0445\u0435\u0448\u0444\u0443\u043D\u043A\u0446\u0438\u044F \u0447\u0430\u0441\u0442\u0438\u0434\u0430\u0442\u044B";
      var CLASS = v8_system_sets_of_values + v8_system_enums_interface + v8_system_enums_objects_properties + v8_system_enums_exchange_plans + v8_system_enums_tabular_document + v8_system_enums_sheduler + v8_system_enums_formatted_document + v8_system_enums_query + v8_system_enums_report_builder + v8_system_enums_files + v8_system_enums_query_builder + v8_system_enums_data_analysis + v8_system_enums_xml_json_xs_dom_xdto_ws + v8_system_enums_data_composition_system + v8_system_enums_email + v8_system_enums_logbook + v8_system_enums_cryptography + v8_system_enums_zip + v8_system_enums_other + v8_system_enums_request_schema + v8_system_enums_properties_of_metadata_objects + v8_system_enums_differents;
      var v8_shared_object = "com\u043E\u0431\u044A\u0435\u043A\u0442 ftp\u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0435 http\u0437\u0430\u043F\u0440\u043E\u0441 http\u0441\u0435\u0440\u0432\u0438\u0441\u043E\u0442\u0432\u0435\u0442 http\u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0435 ws\u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u0438\u044F ws\u043F\u0440\u043E\u043A\u0441\u0438 xbase \u0430\u043D\u0430\u043B\u0438\u0437\u0434\u0430\u043D\u043D\u044B\u0445 \u0430\u043D\u043D\u043E\u0442\u0430\u0446\u0438\u044Fxs \u0431\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u043A\u0430\u0434\u0430\u043D\u043D\u044B\u0445 \u0431\u0443\u0444\u0435\u0440\u0434\u0432\u043E\u0438\u0447\u043D\u044B\u0445\u0434\u0430\u043D\u043D\u044B\u0445 \u0432\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u0435xs \u0432\u044B\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0433\u0435\u043D\u0435\u0440\u0430\u0442\u043E\u0440\u0441\u043B\u0443\u0447\u0430\u0439\u043D\u044B\u0445\u0447\u0438\u0441\u0435\u043B \u0433\u0435\u043E\u0433\u0440\u0430\u0444\u0438\u0447\u0435\u0441\u043A\u0430\u044F\u0441\u0445\u0435\u043C\u0430 \u0433\u0435\u043E\u0433\u0440\u0430\u0444\u0438\u0447\u0435\u0441\u043A\u0438\u0435\u043A\u043E\u043E\u0440\u0434\u0438\u043D\u0430\u0442\u044B \u0433\u0440\u0430\u0444\u0438\u0447\u0435\u0441\u043A\u0430\u044F\u0441\u0445\u0435\u043C\u0430 \u0433\u0440\u0443\u043F\u043F\u0430\u043C\u043E\u0434\u0435\u043B\u0438xs \u0434\u0430\u043D\u043D\u044B\u0435\u0440\u0430\u0441\u0448\u0438\u0444\u0440\u043E\u0432\u043A\u0438\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0434\u0432\u043E\u0438\u0447\u043D\u044B\u0435\u0434\u0430\u043D\u043D\u044B\u0435 \u0434\u0435\u043D\u0434\u0440\u043E\u0433\u0440\u0430\u043C\u043C\u0430 \u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u0430 \u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u0430\u0433\u0430\u043D\u0442\u0430 \u0434\u0438\u0430\u043B\u043E\u0433\u0432\u044B\u0431\u043E\u0440\u0430\u0444\u0430\u0439\u043B\u0430 \u0434\u0438\u0430\u043B\u043E\u0433\u0432\u044B\u0431\u043E\u0440\u0430\u0446\u0432\u0435\u0442\u0430 \u0434\u0438\u0430\u043B\u043E\u0433\u0432\u044B\u0431\u043E\u0440\u0430\u0448\u0440\u0438\u0444\u0442\u0430 \u0434\u0438\u0430\u043B\u043E\u0433\u0440\u0430\u0441\u043F\u0438\u0441\u0430\u043D\u0438\u044F\u0440\u0435\u0433\u043B\u0430\u043C\u0435\u043D\u0442\u043D\u043E\u0433\u043E\u0437\u0430\u0434\u0430\u043D\u0438\u044F \u0434\u0438\u0430\u043B\u043E\u0433\u0440\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F\u0441\u0442\u0430\u043D\u0434\u0430\u0440\u0442\u043D\u043E\u0433\u043E\u043F\u0435\u0440\u0438\u043E\u0434\u0430 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D \u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442dom \u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442html \u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430\u0446\u0438\u044Fxs \u0434\u043E\u0441\u0442\u0430\u0432\u043B\u044F\u0435\u043C\u043E\u0435\u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0435 \u0437\u0430\u043F\u0438\u0441\u044Cdom \u0437\u0430\u043F\u0438\u0441\u044Cfastinfoset \u0437\u0430\u043F\u0438\u0441\u044Chtml \u0437\u0430\u043F\u0438\u0441\u044Cjson \u0437\u0430\u043F\u0438\u0441\u044Cxml \u0437\u0430\u043F\u0438\u0441\u044Czip\u0444\u0430\u0439\u043B\u0430 \u0437\u0430\u043F\u0438\u0441\u044C\u0434\u0430\u043D\u043D\u044B\u0445 \u0437\u0430\u043F\u0438\u0441\u044C\u0442\u0435\u043A\u0441\u0442\u0430 \u0437\u0430\u043F\u0438\u0441\u044C\u0443\u0437\u043B\u043E\u0432dom \u0437\u0430\u043F\u0440\u043E\u0441 \u0437\u0430\u0449\u0438\u0449\u0435\u043D\u043D\u043E\u0435\u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0435openssl \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044F\u043F\u043E\u043B\u0435\u0439\u0440\u0430\u0441\u0448\u0438\u0444\u0440\u043E\u0432\u043A\u0438\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0438\u0437\u0432\u043B\u0435\u0447\u0435\u043D\u0438\u0435\u0442\u0435\u043A\u0441\u0442\u0430 \u0438\u043C\u043F\u043E\u0440\u0442xs \u0438\u043D\u0442\u0435\u0440\u043D\u0435\u0442\u043F\u043E\u0447\u0442\u0430 \u0438\u043D\u0442\u0435\u0440\u043D\u0435\u0442\u043F\u043E\u0447\u0442\u043E\u0432\u043E\u0435\u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0435 \u0438\u043D\u0442\u0435\u0440\u043D\u0435\u0442\u043F\u043E\u0447\u0442\u043E\u0432\u044B\u0439\u043F\u0440\u043E\u0444\u0438\u043B\u044C \u0438\u043D\u0442\u0435\u0440\u043D\u0435\u0442\u043F\u0440\u043E\u043A\u0441\u0438 \u0438\u043D\u0442\u0435\u0440\u043D\u0435\u0442\u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0435 \u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u044F\u0434\u043B\u044F\u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u044Fxs \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u0430\u0442\u0440\u0438\u0431\u0443\u0442\u0430xs \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u0441\u043E\u0431\u044B\u0442\u0438\u044F\u0436\u0443\u0440\u043D\u0430\u043B\u0430\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0446\u0438\u0438 \u0438\u0441\u0442\u043E\u0447\u043D\u0438\u043A\u0434\u043E\u0441\u0442\u0443\u043F\u043D\u044B\u0445\u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043A\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0438\u0442\u0435\u0440\u0430\u0442\u043E\u0440\u0443\u0437\u043B\u043E\u0432dom \u043A\u0430\u0440\u0442\u0438\u043D\u043A\u0430 \u043A\u0432\u0430\u043B\u0438\u0444\u0438\u043A\u0430\u0442\u043E\u0440\u044B\u0434\u0430\u0442\u044B \u043A\u0432\u0430\u043B\u0438\u0444\u0438\u043A\u0430\u0442\u043E\u0440\u044B\u0434\u0432\u043E\u0438\u0447\u043D\u044B\u0445\u0434\u0430\u043D\u043D\u044B\u0445 \u043A\u0432\u0430\u043B\u0438\u0444\u0438\u043A\u0430\u0442\u043E\u0440\u044B\u0441\u0442\u0440\u043E\u043A\u0438 \u043A\u0432\u0430\u043B\u0438\u0444\u0438\u043A\u0430\u0442\u043E\u0440\u044B\u0447\u0438\u0441\u043B\u0430 \u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u0449\u0438\u043A\u043C\u0430\u043A\u0435\u0442\u0430\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u0449\u0438\u043A\u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043A\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u043A\u043E\u043D\u0441\u0442\u0440\u0443\u043A\u0442\u043E\u0440\u043C\u0430\u043A\u0435\u0442\u0430\u043E\u0444\u043E\u0440\u043C\u043B\u0435\u043D\u0438\u044F\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u043A\u043E\u043D\u0441\u0442\u0440\u0443\u043A\u0442\u043E\u0440\u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043A\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u043A\u043E\u043D\u0441\u0442\u0440\u0443\u043A\u0442\u043E\u0440\u0444\u043E\u0440\u043C\u0430\u0442\u043D\u043E\u0439\u0441\u0442\u0440\u043E\u043A\u0438 \u043B\u0438\u043D\u0438\u044F \u043C\u0430\u043A\u0435\u0442\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u043C\u0430\u043A\u0435\u0442\u043E\u0431\u043B\u0430\u0441\u0442\u0438\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u043C\u0430\u043A\u0435\u0442\u043E\u0444\u043E\u0440\u043C\u043B\u0435\u043D\u0438\u044F\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u043C\u0430\u0441\u043A\u0430xs \u043C\u0435\u043D\u0435\u0434\u0436\u0435\u0440\u043A\u0440\u0438\u043F\u0442\u043E\u0433\u0440\u0430\u0444\u0438\u0438 \u043D\u0430\u0431\u043E\u0440\u0441\u0445\u0435\u043Cxml \u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438\u0441\u0435\u0440\u0438\u0430\u043B\u0438\u0437\u0430\u0446\u0438\u0438json \u043E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0430\u043A\u0430\u0440\u0442\u0438\u043D\u043E\u043A \u043E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0430\u0440\u0430\u0441\u0448\u0438\u0444\u0440\u043E\u0432\u043A\u0438\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u043E\u0431\u0445\u043E\u0434\u0434\u0435\u0440\u0435\u0432\u0430dom \u043E\u0431\u044A\u044F\u0432\u043B\u0435\u043D\u0438\u0435\u0430\u0442\u0440\u0438\u0431\u0443\u0442\u0430xs \u043E\u0431\u044A\u044F\u0432\u043B\u0435\u043D\u0438\u0435\u043D\u043E\u0442\u0430\u0446\u0438\u0438xs \u043E\u0431\u044A\u044F\u0432\u043B\u0435\u043D\u0438\u0435\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430xs \u043E\u043F\u0438\u0441\u0430\u043D\u0438\u0435\u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u044F\u0441\u043E\u0431\u044B\u0442\u0438\u044F\u0434\u043E\u0441\u0442\u0443\u043F\u0436\u0443\u0440\u043D\u0430\u043B\u0430\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0446\u0438\u0438 \u043E\u043F\u0438\u0441\u0430\u043D\u0438\u0435\u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u044F\u0441\u043E\u0431\u044B\u0442\u0438\u044F\u043E\u0442\u043A\u0430\u0437\u0432\u0434\u043E\u0441\u0442\u0443\u043F\u0435\u0436\u0443\u0440\u043D\u0430\u043B\u0430\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0446\u0438\u0438 \u043E\u043F\u0438\u0441\u0430\u043D\u0438\u0435\u043E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0438\u0440\u0430\u0441\u0448\u0438\u0444\u0440\u043E\u0432\u043A\u0438\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u043E\u043F\u0438\u0441\u0430\u043D\u0438\u0435\u043F\u0435\u0440\u0435\u0434\u0430\u0432\u0430\u0435\u043C\u043E\u0433\u043E\u0444\u0430\u0439\u043B\u0430 \u043E\u043F\u0438\u0441\u0430\u043D\u0438\u0435\u0442\u0438\u043F\u043E\u0432 \u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u0438\u0435\u0433\u0440\u0443\u043F\u043F\u044B\u0430\u0442\u0440\u0438\u0431\u0443\u0442\u043E\u0432xs \u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u0438\u0435\u0433\u0440\u0443\u043F\u043F\u044B\u043C\u043E\u0434\u0435\u043B\u0438xs \u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u0438\u0435\u043E\u0433\u0440\u0430\u043D\u0438\u0447\u0435\u043D\u0438\u044F\u0438\u0434\u0435\u043D\u0442\u0438\u0447\u043D\u043E\u0441\u0442\u0438xs \u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u0438\u0435\u043F\u0440\u043E\u0441\u0442\u043E\u0433\u043E\u0442\u0438\u043F\u0430xs \u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u0438\u0435\u0441\u043E\u0441\u0442\u0430\u0432\u043D\u043E\u0433\u043E\u0442\u0438\u043F\u0430xs \u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u0438\u0435\u0442\u0438\u043F\u0430\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430dom \u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u0438\u044Fxpathxs \u043E\u0442\u0431\u043E\u0440\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u043F\u0430\u043A\u0435\u0442\u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0430\u0435\u043C\u044B\u0445\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u043E\u0432 \u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u0432\u044B\u0431\u043E\u0440\u0430 \u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u044B\u0437\u0430\u043F\u0438\u0441\u0438json \u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u044B\u0437\u0430\u043F\u0438\u0441\u0438xml \u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u044B\u0447\u0442\u0435\u043D\u0438\u044Fxml \u043F\u0435\u0440\u0435\u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u0438\u0435xs \u043F\u043B\u0430\u043D\u0438\u0440\u043E\u0432\u0449\u0438\u043A \u043F\u043E\u043B\u0435\u0430\u043D\u0430\u043B\u0438\u0437\u0430\u0434\u0430\u043D\u043D\u044B\u0445 \u043F\u043E\u043B\u0435\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u043F\u043E\u0441\u0442\u0440\u043E\u0438\u0442\u0435\u043B\u044Cdom \u043F\u043E\u0441\u0442\u0440\u043E\u0438\u0442\u0435\u043B\u044C\u0437\u0430\u043F\u0440\u043E\u0441\u0430 \u043F\u043E\u0441\u0442\u0440\u043E\u0438\u0442\u0435\u043B\u044C\u043E\u0442\u0447\u0435\u0442\u0430 \u043F\u043E\u0441\u0442\u0440\u043E\u0438\u0442\u0435\u043B\u044C\u043E\u0442\u0447\u0435\u0442\u0430\u0430\u043D\u0430\u043B\u0438\u0437\u0430\u0434\u0430\u043D\u043D\u044B\u0445 \u043F\u043E\u0441\u0442\u0440\u043E\u0438\u0442\u0435\u043B\u044C\u0441\u0445\u0435\u043Cxml \u043F\u043E\u0442\u043E\u043A \u043F\u043E\u0442\u043E\u043A\u0432\u043F\u0430\u043C\u044F\u0442\u0438 \u043F\u043E\u0447\u0442\u0430 \u043F\u043E\u0447\u0442\u043E\u0432\u043E\u0435\u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0435 \u043F\u0440\u0435\u043E\u0431\u0440\u0430\u0437\u043E\u0432\u0430\u043D\u0438\u0435xsl \u043F\u0440\u0435\u043E\u0431\u0440\u0430\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u043A\u043A\u0430\u043D\u043E\u043D\u0438\u0447\u0435\u0441\u043A\u043E\u043C\u0443xml \u043F\u0440\u043E\u0446\u0435\u0441\u0441\u043E\u0440\u0432\u044B\u0432\u043E\u0434\u0430\u0440\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442\u0430\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445\u0432\u043A\u043E\u043B\u043B\u0435\u043A\u0446\u0438\u044E\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0439 \u043F\u0440\u043E\u0446\u0435\u0441\u0441\u043E\u0440\u0432\u044B\u0432\u043E\u0434\u0430\u0440\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442\u0430\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445\u0432\u0442\u0430\u0431\u043B\u0438\u0447\u043D\u044B\u0439\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442 \u043F\u0440\u043E\u0446\u0435\u0441\u0441\u043E\u0440\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0440\u0430\u0437\u044B\u043C\u0435\u043D\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u043F\u0440\u043E\u0441\u0442\u0440\u0430\u043D\u0441\u0442\u0432\u0438\u043C\u0435\u043Ddom \u0440\u0430\u043C\u043A\u0430 \u0440\u0430\u0441\u043F\u0438\u0441\u0430\u043D\u0438\u0435\u0440\u0435\u0433\u043B\u0430\u043C\u0435\u043D\u0442\u043D\u043E\u0433\u043E\u0437\u0430\u0434\u0430\u043D\u0438\u044F \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u043D\u043E\u0435\u0438\u043C\u044Fxml \u0440\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442\u0447\u0442\u0435\u043D\u0438\u044F\u0434\u0430\u043D\u043D\u044B\u0445 \u0441\u0432\u043E\u0434\u043D\u0430\u044F\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u0430 \u0441\u0432\u044F\u0437\u044C\u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u0430\u0432\u044B\u0431\u043E\u0440\u0430 \u0441\u0432\u044F\u0437\u044C\u043F\u043E\u0442\u0438\u043F\u0443 \u0441\u0432\u044F\u0437\u044C\u043F\u043E\u0442\u0438\u043F\u0443\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0441\u0435\u0440\u0438\u0430\u043B\u0438\u0437\u0430\u0442\u043E\u0440xdto \u0441\u0435\u0440\u0442\u0438\u0444\u0438\u043A\u0430\u0442\u043A\u043B\u0438\u0435\u043D\u0442\u0430windows \u0441\u0435\u0440\u0442\u0438\u0444\u0438\u043A\u0430\u0442\u043A\u043B\u0438\u0435\u043D\u0442\u0430\u0444\u0430\u0439\u043B \u0441\u0435\u0440\u0442\u0438\u0444\u0438\u043A\u0430\u0442\u043A\u0440\u0438\u043F\u0442\u043E\u0433\u0440\u0430\u0444\u0438\u0438 \u0441\u0435\u0440\u0442\u0438\u0444\u0438\u043A\u0430\u0442\u044B\u0443\u0434\u043E\u0441\u0442\u043E\u0432\u0435\u0440\u044F\u044E\u0449\u0438\u0445\u0446\u0435\u043D\u0442\u0440\u043E\u0432windows \u0441\u0435\u0440\u0442\u0438\u0444\u0438\u043A\u0430\u0442\u044B\u0443\u0434\u043E\u0441\u0442\u043E\u0432\u0435\u0440\u044F\u044E\u0449\u0438\u0445\u0446\u0435\u043D\u0442\u0440\u043E\u0432\u0444\u0430\u0439\u043B \u0441\u0436\u0430\u0442\u0438\u0435\u0434\u0430\u043D\u043D\u044B\u0445 \u0441\u0438\u0441\u0442\u0435\u043C\u043D\u0430\u044F\u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u044F \u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0435\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044E \u0441\u043E\u0447\u0435\u0442\u0430\u043D\u0438\u0435\u043A\u043B\u0430\u0432\u0438\u0448 \u0441\u0440\u0430\u0432\u043D\u0435\u043D\u0438\u0435\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0439 \u0441\u0442\u0430\u043D\u0434\u0430\u0440\u0442\u043D\u0430\u044F\u0434\u0430\u0442\u0430\u043D\u0430\u0447\u0430\u043B\u0430 \u0441\u0442\u0430\u043D\u0434\u0430\u0440\u0442\u043D\u044B\u0439\u043F\u0435\u0440\u0438\u043E\u0434 \u0441\u0445\u0435\u043C\u0430xml \u0441\u0445\u0435\u043C\u0430\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0430\u0431\u043B\u0438\u0447\u043D\u044B\u0439\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442 \u0442\u0435\u043A\u0441\u0442\u043E\u0432\u044B\u0439\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442 \u0442\u0435\u0441\u0442\u0438\u0440\u0443\u0435\u043C\u043E\u0435\u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u0435 \u0442\u0438\u043F\u0434\u0430\u043D\u043D\u044B\u0445xml \u0443\u043D\u0438\u043A\u0430\u043B\u044C\u043D\u044B\u0439\u0438\u0434\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0442\u043E\u0440 \u0444\u0430\u0431\u0440\u0438\u043A\u0430xdto \u0444\u0430\u0439\u043B \u0444\u0430\u0439\u043B\u043E\u0432\u044B\u0439\u043F\u043E\u0442\u043E\u043A \u0444\u0430\u0441\u0435\u0442\u0434\u043B\u0438\u043D\u044Bxs \u0444\u0430\u0441\u0435\u0442\u043A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u0430\u0440\u0430\u0437\u0440\u044F\u0434\u043E\u0432\u0434\u0440\u043E\u0431\u043D\u043E\u0439\u0447\u0430\u0441\u0442\u0438xs \u0444\u0430\u0441\u0435\u0442\u043C\u0430\u043A\u0441\u0438\u043C\u0430\u043B\u044C\u043D\u043E\u0433\u043E\u0432\u043A\u043B\u044E\u0447\u0430\u044E\u0449\u0435\u0433\u043E\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044Fxs \u0444\u0430\u0441\u0435\u0442\u043C\u0430\u043A\u0441\u0438\u043C\u0430\u043B\u044C\u043D\u043E\u0433\u043E\u0438\u0441\u043A\u043B\u044E\u0447\u0430\u044E\u0449\u0435\u0433\u043E\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044Fxs \u0444\u0430\u0441\u0435\u0442\u043C\u0430\u043A\u0441\u0438\u043C\u0430\u043B\u044C\u043D\u043E\u0439\u0434\u043B\u0438\u043D\u044Bxs \u0444\u0430\u0441\u0435\u0442\u043C\u0438\u043D\u0438\u043C\u0430\u043B\u044C\u043D\u043E\u0433\u043E\u0432\u043A\u043B\u044E\u0447\u0430\u044E\u0449\u0435\u0433\u043E\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044Fxs \u0444\u0430\u0441\u0435\u0442\u043C\u0438\u043D\u0438\u043C\u0430\u043B\u044C\u043D\u043E\u0433\u043E\u0438\u0441\u043A\u043B\u044E\u0447\u0430\u044E\u0449\u0435\u0433\u043E\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044Fxs \u0444\u0430\u0441\u0435\u0442\u043C\u0438\u043D\u0438\u043C\u0430\u043B\u044C\u043D\u043E\u0439\u0434\u043B\u0438\u043D\u044Bxs \u0444\u0430\u0441\u0435\u0442\u043E\u0431\u0440\u0430\u0437\u0446\u0430xs \u0444\u0430\u0441\u0435\u0442\u043E\u0431\u0449\u0435\u0433\u043E\u043A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u0430\u0440\u0430\u0437\u0440\u044F\u0434\u043E\u0432xs \u0444\u0430\u0441\u0435\u0442\u043F\u0435\u0440\u0435\u0447\u0438\u0441\u043B\u0435\u043D\u0438\u044Fxs \u0444\u0430\u0441\u0435\u0442\u043F\u0440\u043E\u0431\u0435\u043B\u044C\u043D\u044B\u0445\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432xs \u0444\u0438\u043B\u044C\u0442\u0440\u0443\u0437\u043B\u043E\u0432dom \u0444\u043E\u0440\u043C\u0430\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u0430\u044F\u0441\u0442\u0440\u043E\u043A\u0430 \u0444\u043E\u0440\u043C\u0430\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u044B\u0439\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442 \u0444\u0440\u0430\u0433\u043C\u0435\u043D\u0442xs \u0445\u0435\u0448\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435\u0434\u0430\u043D\u043D\u044B\u0445 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0435\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044F \u0446\u0432\u0435\u0442 \u0447\u0442\u0435\u043D\u0438\u0435fastinfoset \u0447\u0442\u0435\u043D\u0438\u0435html \u0447\u0442\u0435\u043D\u0438\u0435json \u0447\u0442\u0435\u043D\u0438\u0435xml \u0447\u0442\u0435\u043D\u0438\u0435zip\u0444\u0430\u0439\u043B\u0430 \u0447\u0442\u0435\u043D\u0438\u0435\u0434\u0430\u043D\u043D\u044B\u0445 \u0447\u0442\u0435\u043D\u0438\u0435\u0442\u0435\u043A\u0441\u0442\u0430 \u0447\u0442\u0435\u043D\u0438\u0435\u0443\u0437\u043B\u043E\u0432dom \u0448\u0440\u0438\u0444\u0442 \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0440\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442\u0430\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 ";
      var v8_universal_collection = "comsafearray \u0434\u0435\u0440\u0435\u0432\u043E\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0439 \u043C\u0430\u0441\u0441\u0438\u0432 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0438\u0435 \u0441\u043F\u0438\u0441\u043E\u043A\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0439 \u0441\u0442\u0440\u0443\u043A\u0442\u0443\u0440\u0430 \u0442\u0430\u0431\u043B\u0438\u0446\u0430\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0439 \u0444\u0438\u043A\u0441\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u0430\u044F\u0441\u0442\u0440\u0443\u043A\u0442\u0443\u0440\u0430 \u0444\u0438\u043A\u0441\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u043E\u0435\u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0438\u0435 \u0444\u0438\u043A\u0441\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u044B\u0439\u043C\u0430\u0441\u0441\u0438\u0432 ";
      var TYPE = v8_shared_object + v8_universal_collection;
      var LITERAL = "null \u0438\u0441\u0442\u0438\u043D\u0430 \u043B\u043E\u0436\u044C \u043D\u0435\u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u043E";
      var NUMBERS = hljs5.inherit(hljs5.NUMBER_MODE);
      var STRINGS = {
        className: "string",
        begin: '"|\\|',
        end: '"|$',
        contains: [{ begin: '""' }]
      };
      var DATE = {
        begin: "'",
        end: "'",
        excludeBegin: true,
        excludeEnd: true,
        contains: [
          {
            className: "number",
            begin: "\\d{4}([\\.\\\\/:-]?\\d{2}){0,5}"
          }
        ]
      };
      var COMMENTS = hljs5.inherit(hljs5.C_LINE_COMMENT_MODE);
      var META = {
        className: "meta",
        begin: "#|&",
        end: "$",
        keywords: {
          $pattern: UNDERSCORE_IDENT_RE,
          "meta-keyword": KEYWORD + METAKEYWORD
        },
        contains: [
          COMMENTS
        ]
      };
      var SYMBOL = {
        className: "symbol",
        begin: "~",
        end: ";|:",
        excludeEnd: true
      };
      var FUNCTION = {
        className: "function",
        variants: [
          { begin: "\u043F\u0440\u043E\u0446\u0435\u0434\u0443\u0440\u0430|\u0444\u0443\u043D\u043A\u0446\u0438\u044F", end: "\\)", keywords: "\u043F\u0440\u043E\u0446\u0435\u0434\u0443\u0440\u0430 \u0444\u0443\u043D\u043A\u0446\u0438\u044F" },
          { begin: "\u043A\u043E\u043D\u0435\u0446\u043F\u0440\u043E\u0446\u0435\u0434\u0443\u0440\u044B|\u043A\u043E\u043D\u0435\u0446\u0444\u0443\u043D\u043A\u0446\u0438\u0438", keywords: "\u043A\u043E\u043D\u0435\u0446\u043F\u0440\u043E\u0446\u0435\u0434\u0443\u0440\u044B \u043A\u043E\u043D\u0435\u0446\u0444\u0443\u043D\u043A\u0446\u0438\u0438" }
        ],
        contains: [
          {
            begin: "\\(",
            end: "\\)",
            endsParent: true,
            contains: [
              {
                className: "params",
                begin: UNDERSCORE_IDENT_RE,
                end: ",",
                excludeEnd: true,
                endsWithParent: true,
                keywords: {
                  $pattern: UNDERSCORE_IDENT_RE,
                  keyword: "\u0437\u043D\u0430\u0447",
                  literal: LITERAL
                },
                contains: [
                  NUMBERS,
                  STRINGS,
                  DATE
                ]
              },
              COMMENTS
            ]
          },
          hljs5.inherit(hljs5.TITLE_MODE, { begin: UNDERSCORE_IDENT_RE })
        ]
      };
      return {
        name: "1C:Enterprise",
        case_insensitive: true,
        keywords: {
          $pattern: UNDERSCORE_IDENT_RE,
          keyword: KEYWORD,
          built_in: BUILTIN,
          class: CLASS,
          type: TYPE,
          literal: LITERAL
        },
        contains: [
          META,
          FUNCTION,
          COMMENTS,
          SYMBOL,
          NUMBERS,
          STRINGS,
          DATE
        ]
      };
    }
    module.exports = _1c;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/abnf.js
var require_abnf = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/abnf.js"(exports, module) {
    init_process_shim();
    function source(re2) {
      if (!re2) return null;
      if (typeof re2 === "string") return re2;
      return re2.source;
    }
    function concat(...args) {
      const joined = args.map((x2) => source(x2)).join("");
      return joined;
    }
    function abnf(hljs5) {
      const regexes = {
        ruleDeclaration: /^[a-zA-Z][a-zA-Z0-9-]*/,
        unexpectedChars: /[!@#$^&',?+~`|:]/
      };
      const keywords = [
        "ALPHA",
        "BIT",
        "CHAR",
        "CR",
        "CRLF",
        "CTL",
        "DIGIT",
        "DQUOTE",
        "HEXDIG",
        "HTAB",
        "LF",
        "LWSP",
        "OCTET",
        "SP",
        "VCHAR",
        "WSP"
      ];
      const commentMode = hljs5.COMMENT(/;/, /$/);
      const terminalBinaryMode = {
        className: "symbol",
        begin: /%b[0-1]+(-[0-1]+|(\.[0-1]+)+){0,1}/
      };
      const terminalDecimalMode = {
        className: "symbol",
        begin: /%d[0-9]+(-[0-9]+|(\.[0-9]+)+){0,1}/
      };
      const terminalHexadecimalMode = {
        className: "symbol",
        begin: /%x[0-9A-F]+(-[0-9A-F]+|(\.[0-9A-F]+)+){0,1}/
      };
      const caseSensitivityIndicatorMode = {
        className: "symbol",
        begin: /%[si]/
      };
      const ruleDeclarationMode = {
        className: "attribute",
        begin: concat(regexes.ruleDeclaration, /(?=\s*=)/)
      };
      return {
        name: "Augmented Backus-Naur Form",
        illegal: regexes.unexpectedChars,
        keywords,
        contains: [
          ruleDeclarationMode,
          commentMode,
          terminalBinaryMode,
          terminalDecimalMode,
          terminalHexadecimalMode,
          caseSensitivityIndicatorMode,
          hljs5.QUOTE_STRING_MODE,
          hljs5.NUMBER_MODE
        ]
      };
    }
    module.exports = abnf;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/accesslog.js
var require_accesslog = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/accesslog.js"(exports, module) {
    init_process_shim();
    function source(re2) {
      if (!re2) return null;
      if (typeof re2 === "string") return re2;
      return re2.source;
    }
    function concat(...args) {
      const joined = args.map((x2) => source(x2)).join("");
      return joined;
    }
    function either(...args) {
      const joined = "(" + args.map((x2) => source(x2)).join("|") + ")";
      return joined;
    }
    function accesslog(_hljs) {
      const HTTP_VERBS = [
        "GET",
        "POST",
        "HEAD",
        "PUT",
        "DELETE",
        "CONNECT",
        "OPTIONS",
        "PATCH",
        "TRACE"
      ];
      return {
        name: "Apache Access Log",
        contains: [
          // IP
          {
            className: "number",
            begin: /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(:\d{1,5})?\b/,
            relevance: 5
          },
          // Other numbers
          {
            className: "number",
            begin: /\b\d+\b/,
            relevance: 0
          },
          // Requests
          {
            className: "string",
            begin: concat(/"/, either(...HTTP_VERBS)),
            end: /"/,
            keywords: HTTP_VERBS,
            illegal: /\n/,
            relevance: 5,
            contains: [
              {
                begin: /HTTP\/[12]\.\d'/,
                relevance: 5
              }
            ]
          },
          // Dates
          {
            className: "string",
            // dates must have a certain length, this prevents matching
            // simple array accesses a[123] and [] and other common patterns
            // found in other languages
            begin: /\[\d[^\]\n]{8,}\]/,
            illegal: /\n/,
            relevance: 1
          },
          {
            className: "string",
            begin: /\[/,
            end: /\]/,
            illegal: /\n/,
            relevance: 0
          },
          // User agent / relevance boost
          {
            className: "string",
            begin: /"Mozilla\/\d\.\d \(/,
            end: /"/,
            illegal: /\n/,
            relevance: 3
          },
          // Strings
          {
            className: "string",
            begin: /"/,
            end: /"/,
            illegal: /\n/,
            relevance: 0
          }
        ]
      };
    }
    module.exports = accesslog;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/actionscript.js
var require_actionscript = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/actionscript.js"(exports, module) {
    init_process_shim();
    function source(re2) {
      if (!re2) return null;
      if (typeof re2 === "string") return re2;
      return re2.source;
    }
    function concat(...args) {
      const joined = args.map((x2) => source(x2)).join("");
      return joined;
    }
    function actionscript(hljs5) {
      const IDENT_RE3 = /[a-zA-Z_$][a-zA-Z0-9_$]*/;
      const IDENT_FUNC_RETURN_TYPE_RE = /([*]|[a-zA-Z_$][a-zA-Z0-9_$]*)/;
      const AS3_REST_ARG_MODE = {
        className: "rest_arg",
        begin: /[.]{3}/,
        end: IDENT_RE3,
        relevance: 10
      };
      return {
        name: "ActionScript",
        aliases: ["as"],
        keywords: {
          keyword: "as break case catch class const continue default delete do dynamic each else extends final finally for function get if implements import in include instanceof interface internal is namespace native new override package private protected public return set static super switch this throw try typeof use var void while with",
          literal: "true false null undefined"
        },
        contains: [
          hljs5.APOS_STRING_MODE,
          hljs5.QUOTE_STRING_MODE,
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          hljs5.C_NUMBER_MODE,
          {
            className: "class",
            beginKeywords: "package",
            end: /\{/,
            contains: [hljs5.TITLE_MODE]
          },
          {
            className: "class",
            beginKeywords: "class interface",
            end: /\{/,
            excludeEnd: true,
            contains: [
              { beginKeywords: "extends implements" },
              hljs5.TITLE_MODE
            ]
          },
          {
            className: "meta",
            beginKeywords: "import include",
            end: /;/,
            keywords: { "meta-keyword": "import include" }
          },
          {
            className: "function",
            beginKeywords: "function",
            end: /[{;]/,
            excludeEnd: true,
            illegal: /\S/,
            contains: [
              hljs5.TITLE_MODE,
              {
                className: "params",
                begin: /\(/,
                end: /\)/,
                contains: [
                  hljs5.APOS_STRING_MODE,
                  hljs5.QUOTE_STRING_MODE,
                  hljs5.C_LINE_COMMENT_MODE,
                  hljs5.C_BLOCK_COMMENT_MODE,
                  AS3_REST_ARG_MODE
                ]
              },
              { begin: concat(/:\s*/, IDENT_FUNC_RETURN_TYPE_RE) }
            ]
          },
          hljs5.METHOD_GUARD
        ],
        illegal: /#/
      };
    }
    module.exports = actionscript;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/ada.js
var require_ada = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/ada.js"(exports, module) {
    init_process_shim();
    function ada(hljs5) {
      const INTEGER_RE = "\\d(_|\\d)*";
      const EXPONENT_RE = "[eE][-+]?" + INTEGER_RE;
      const DECIMAL_LITERAL_RE = INTEGER_RE + "(\\." + INTEGER_RE + ")?(" + EXPONENT_RE + ")?";
      const BASED_INTEGER_RE = "\\w+";
      const BASED_LITERAL_RE = INTEGER_RE + "#" + BASED_INTEGER_RE + "(\\." + BASED_INTEGER_RE + ")?#(" + EXPONENT_RE + ")?";
      const NUMBER_RE = "\\b(" + BASED_LITERAL_RE + "|" + DECIMAL_LITERAL_RE + ")";
      const ID_REGEX = "[A-Za-z](_?[A-Za-z0-9.])*";
      const BAD_CHARS = `[]\\{\\}%#'"`;
      const COMMENTS = hljs5.COMMENT("--", "$");
      const VAR_DECLS = {
        // TODO: These spaces are not required by the Ada syntax
        // however, I have yet to see handwritten Ada code where
        // someone does not put spaces around :
        begin: "\\s+:\\s+",
        end: "\\s*(:=|;|\\)|=>|$)",
        // endsWithParent: true,
        // returnBegin: true,
        illegal: BAD_CHARS,
        contains: [
          {
            // workaround to avoid highlighting
            // named loops and declare blocks
            beginKeywords: "loop for declare others",
            endsParent: true
          },
          {
            // properly highlight all modifiers
            className: "keyword",
            beginKeywords: "not null constant access function procedure in out aliased exception"
          },
          {
            className: "type",
            begin: ID_REGEX,
            endsParent: true,
            relevance: 0
          }
        ]
      };
      return {
        name: "Ada",
        case_insensitive: true,
        keywords: {
          keyword: "abort else new return abs elsif not reverse abstract end accept entry select access exception of separate aliased exit or some all others subtype and for out synchronized array function overriding at tagged generic package task begin goto pragma terminate body private then if procedure type case in protected constant interface is raise use declare range delay limited record when delta loop rem while digits renames with do mod requeue xor",
          literal: "True False"
        },
        contains: [
          COMMENTS,
          // strings "foobar"
          {
            className: "string",
            begin: /"/,
            end: /"/,
            contains: [{
              begin: /""/,
              relevance: 0
            }]
          },
          // characters ''
          {
            // character literals always contain one char
            className: "string",
            begin: /'.'/
          },
          {
            // number literals
            className: "number",
            begin: NUMBER_RE,
            relevance: 0
          },
          {
            // Attributes
            className: "symbol",
            begin: "'" + ID_REGEX
          },
          {
            // package definition, maybe inside generic
            className: "title",
            begin: "(\\bwith\\s+)?(\\bprivate\\s+)?\\bpackage\\s+(\\bbody\\s+)?",
            end: "(is|$)",
            keywords: "package body",
            excludeBegin: true,
            excludeEnd: true,
            illegal: BAD_CHARS
          },
          {
            // function/procedure declaration/definition
            // maybe inside generic
            begin: "(\\b(with|overriding)\\s+)?\\b(function|procedure)\\s+",
            end: "(\\bis|\\bwith|\\brenames|\\)\\s*;)",
            keywords: "overriding function procedure with is renames return",
            // we need to re-match the 'function' keyword, so that
            // the title mode below matches only exactly once
            returnBegin: true,
            contains: [
              COMMENTS,
              {
                // name of the function/procedure
                className: "title",
                begin: "(\\bwith\\s+)?\\b(function|procedure)\\s+",
                end: "(\\(|\\s+|$)",
                excludeBegin: true,
                excludeEnd: true,
                illegal: BAD_CHARS
              },
              // 'self'
              // // parameter types
              VAR_DECLS,
              {
                // return type
                className: "type",
                begin: "\\breturn\\s+",
                end: "(\\s+|;|$)",
                keywords: "return",
                excludeBegin: true,
                excludeEnd: true,
                // we are done with functions
                endsParent: true,
                illegal: BAD_CHARS
              }
            ]
          },
          {
            // new type declarations
            // maybe inside generic
            className: "type",
            begin: "\\b(sub)?type\\s+",
            end: "\\s+",
            keywords: "type",
            excludeBegin: true,
            illegal: BAD_CHARS
          },
          // see comment above the definition
          VAR_DECLS
          // no markup
          // relevance boosters for small snippets
          // {begin: '\\s*=>\\s*'},
          // {begin: '\\s*:=\\s*'},
          // {begin: '\\s+:=\\s+'},
        ]
      };
    }
    module.exports = ada;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/angelscript.js
var require_angelscript = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/angelscript.js"(exports, module) {
    init_process_shim();
    function angelscript(hljs5) {
      var builtInTypeMode = {
        className: "built_in",
        begin: "\\b(void|bool|int|int8|int16|int32|int64|uint|uint8|uint16|uint32|uint64|string|ref|array|double|float|auto|dictionary)"
      };
      var objectHandleMode = {
        className: "symbol",
        begin: "[a-zA-Z0-9_]+@"
      };
      var genericMode = {
        className: "keyword",
        begin: "<",
        end: ">",
        contains: [builtInTypeMode, objectHandleMode]
      };
      builtInTypeMode.contains = [genericMode];
      objectHandleMode.contains = [genericMode];
      return {
        name: "AngelScript",
        aliases: ["asc"],
        keywords: "for in|0 break continue while do|0 return if else case switch namespace is cast or and xor not get|0 in inout|10 out override set|0 private public const default|0 final shared external mixin|10 enum typedef funcdef this super import from interface abstract|0 try catch protected explicit property",
        // avoid close detection with C# and JS
        illegal: "(^using\\s+[A-Za-z0-9_\\.]+;$|\\bfunction\\s*[^\\(])",
        contains: [
          {
            // 'strings'
            className: "string",
            begin: "'",
            end: "'",
            illegal: "\\n",
            contains: [hljs5.BACKSLASH_ESCAPE],
            relevance: 0
          },
          // """heredoc strings"""
          {
            className: "string",
            begin: '"""',
            end: '"""'
          },
          {
            // "strings"
            className: "string",
            begin: '"',
            end: '"',
            illegal: "\\n",
            contains: [hljs5.BACKSLASH_ESCAPE],
            relevance: 0
          },
          hljs5.C_LINE_COMMENT_MODE,
          // single-line comments
          hljs5.C_BLOCK_COMMENT_MODE,
          // comment blocks
          {
            // metadata
            className: "string",
            begin: "^\\s*\\[",
            end: "\\]"
          },
          {
            // interface or namespace declaration
            beginKeywords: "interface namespace",
            end: /\{/,
            illegal: "[;.\\-]",
            contains: [
              {
                // interface or namespace name
                className: "symbol",
                begin: "[a-zA-Z0-9_]+"
              }
            ]
          },
          {
            // class declaration
            beginKeywords: "class",
            end: /\{/,
            illegal: "[;.\\-]",
            contains: [
              {
                // class name
                className: "symbol",
                begin: "[a-zA-Z0-9_]+",
                contains: [
                  {
                    begin: "[:,]\\s*",
                    contains: [
                      {
                        className: "symbol",
                        begin: "[a-zA-Z0-9_]+"
                      }
                    ]
                  }
                ]
              }
            ]
          },
          builtInTypeMode,
          // built-in types
          objectHandleMode,
          // object handles
          {
            // literals
            className: "literal",
            begin: "\\b(null|true|false)"
          },
          {
            // numbers
            className: "number",
            relevance: 0,
            begin: "(-?)(\\b0[xXbBoOdD][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?f?|\\.\\d+f?)([eE][-+]?\\d+f?)?)"
          }
        ]
      };
    }
    module.exports = angelscript;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/apache.js
var require_apache = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/apache.js"(exports, module) {
    init_process_shim();
    function apache(hljs5) {
      const NUMBER_REF = {
        className: "number",
        begin: /[$%]\d+/
      };
      const NUMBER = {
        className: "number",
        begin: /\d+/
      };
      const IP_ADDRESS = {
        className: "number",
        begin: /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(:\d{1,5})?/
      };
      const PORT_NUMBER = {
        className: "number",
        begin: /:\d{1,5}/
      };
      return {
        name: "Apache config",
        aliases: ["apacheconf"],
        case_insensitive: true,
        contains: [
          hljs5.HASH_COMMENT_MODE,
          {
            className: "section",
            begin: /<\/?/,
            end: />/,
            contains: [
              IP_ADDRESS,
              PORT_NUMBER,
              // low relevance prevents us from claming XML/HTML where this rule would
              // match strings inside of XML tags
              hljs5.inherit(hljs5.QUOTE_STRING_MODE, { relevance: 0 })
            ]
          },
          {
            className: "attribute",
            begin: /\w+/,
            relevance: 0,
            // keywords aren’t needed for highlighting per se, they only boost relevance
            // for a very generally defined mode (starts with a word, ends with line-end
            keywords: {
              nomarkup: "order deny allow setenv rewriterule rewriteengine rewritecond documentroot sethandler errordocument loadmodule options header listen serverroot servername"
            },
            starts: {
              end: /$/,
              relevance: 0,
              keywords: { literal: "on off all deny allow" },
              contains: [
                {
                  className: "meta",
                  begin: /\s\[/,
                  end: /\]$/
                },
                {
                  className: "variable",
                  begin: /[\$%]\{/,
                  end: /\}/,
                  contains: [
                    "self",
                    NUMBER_REF
                  ]
                },
                IP_ADDRESS,
                NUMBER,
                hljs5.QUOTE_STRING_MODE
              ]
            }
          }
        ],
        illegal: /\S/
      };
    }
    module.exports = apache;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/applescript.js
var require_applescript = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/applescript.js"(exports, module) {
    init_process_shim();
    function source(re2) {
      if (!re2) return null;
      if (typeof re2 === "string") return re2;
      return re2.source;
    }
    function concat(...args) {
      const joined = args.map((x2) => source(x2)).join("");
      return joined;
    }
    function either(...args) {
      const joined = "(" + args.map((x2) => source(x2)).join("|") + ")";
      return joined;
    }
    function applescript(hljs5) {
      const STRING = hljs5.inherit(
        hljs5.QUOTE_STRING_MODE,
        {
          illegal: null
        }
      );
      const PARAMS = {
        className: "params",
        begin: /\(/,
        end: /\)/,
        contains: [
          "self",
          hljs5.C_NUMBER_MODE,
          STRING
        ]
      };
      const COMMENT_MODE_1 = hljs5.COMMENT(/--/, /$/);
      const COMMENT_MODE_2 = hljs5.COMMENT(
        /\(\*/,
        /\*\)/,
        {
          contains: [
            "self",
            // allow nesting
            COMMENT_MODE_1
          ]
        }
      );
      const COMMENTS = [
        COMMENT_MODE_1,
        COMMENT_MODE_2,
        hljs5.HASH_COMMENT_MODE
      ];
      const KEYWORD_PATTERNS = [
        /apart from/,
        /aside from/,
        /instead of/,
        /out of/,
        /greater than/,
        /isn't|(doesn't|does not) (equal|come before|come after|contain)/,
        /(greater|less) than( or equal)?/,
        /(starts?|ends|begins?) with/,
        /contained by/,
        /comes (before|after)/,
        /a (ref|reference)/,
        /POSIX (file|path)/,
        /(date|time) string/,
        /quoted form/
      ];
      const BUILT_IN_PATTERNS = [
        /clipboard info/,
        /the clipboard/,
        /info for/,
        /list (disks|folder)/,
        /mount volume/,
        /path to/,
        /(close|open for) access/,
        /(get|set) eof/,
        /current date/,
        /do shell script/,
        /get volume settings/,
        /random number/,
        /set volume/,
        /system attribute/,
        /system info/,
        /time to GMT/,
        /(load|run|store) script/,
        /scripting components/,
        /ASCII (character|number)/,
        /localized string/,
        /choose (application|color|file|file name|folder|from list|remote application|URL)/,
        /display (alert|dialog)/
      ];
      return {
        name: "AppleScript",
        aliases: ["osascript"],
        keywords: {
          keyword: "about above after against and around as at back before beginning behind below beneath beside between but by considering contain contains continue copy div does eighth else end equal equals error every exit fifth first for fourth from front get given global if ignoring in into is it its last local me middle mod my ninth not of on onto or over prop property put ref reference repeat returning script second set seventh since sixth some tell tenth that the|0 then third through thru timeout times to transaction try until where while whose with without",
          literal: "AppleScript false linefeed return pi quote result space tab true",
          built_in: "alias application boolean class constant date file integer list number real record string text activate beep count delay launch log offset read round run say summarize write character characters contents day frontmost id item length month name paragraph paragraphs rest reverse running time version weekday word words year"
        },
        contains: [
          STRING,
          hljs5.C_NUMBER_MODE,
          {
            className: "built_in",
            begin: concat(
              /\b/,
              either(...BUILT_IN_PATTERNS),
              /\b/
            )
          },
          {
            className: "built_in",
            begin: /^\s*return\b/
          },
          {
            className: "literal",
            begin: /\b(text item delimiters|current application|missing value)\b/
          },
          {
            className: "keyword",
            begin: concat(
              /\b/,
              either(...KEYWORD_PATTERNS),
              /\b/
            )
          },
          {
            beginKeywords: "on",
            illegal: /[${=;\n]/,
            contains: [
              hljs5.UNDERSCORE_TITLE_MODE,
              PARAMS
            ]
          },
          ...COMMENTS
        ],
        illegal: /\/\/|->|=>|\[\[/
      };
    }
    module.exports = applescript;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/arcade.js
var require_arcade = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/arcade.js"(exports, module) {
    init_process_shim();
    function arcade(hljs5) {
      const IDENT_RE3 = "[A-Za-z_][0-9A-Za-z_]*";
      const KEYWORDS3 = {
        keyword: "if for while var new function do return void else break",
        literal: "BackSlash DoubleQuote false ForwardSlash Infinity NaN NewLine null PI SingleQuote Tab TextFormatting true undefined",
        built_in: "Abs Acos Angle Attachments Area AreaGeodetic Asin Atan Atan2 Average Bearing Boolean Buffer BufferGeodetic Ceil Centroid Clip Console Constrain Contains Cos Count Crosses Cut Date DateAdd DateDiff Day Decode DefaultValue Dictionary Difference Disjoint Distance DistanceGeodetic Distinct DomainCode DomainName Equals Exp Extent Feature FeatureSet FeatureSetByAssociation FeatureSetById FeatureSetByPortalItem FeatureSetByRelationshipName FeatureSetByTitle FeatureSetByUrl Filter First Floor Geometry GroupBy Guid HasKey Hour IIf IndexOf Intersection Intersects IsEmpty IsNan IsSelfIntersecting Length LengthGeodetic Log Max Mean Millisecond Min Minute Month MultiPartToSinglePart Multipoint NextSequenceValue Now Number OrderBy Overlaps Point Polygon Polyline Portal Pow Random Relate Reverse RingIsClockWise Round Second SetGeometry Sin Sort Sqrt Stdev Sum SymmetricDifference Tan Text Timestamp Today ToLocal Top Touches ToUTC TrackCurrentTime TrackGeometryWindow TrackIndex TrackStartTime TrackWindow TypeOf Union UrlEncode Variance Weekday When Within Year "
      };
      const SYMBOL = {
        className: "symbol",
        begin: "\\$[datastore|feature|layer|map|measure|sourcefeature|sourcelayer|targetfeature|targetlayer|value|view]+"
      };
      const NUMBER = {
        className: "number",
        variants: [
          {
            begin: "\\b(0[bB][01]+)"
          },
          {
            begin: "\\b(0[oO][0-7]+)"
          },
          {
            begin: hljs5.C_NUMBER_RE
          }
        ],
        relevance: 0
      };
      const SUBST = {
        className: "subst",
        begin: "\\$\\{",
        end: "\\}",
        keywords: KEYWORDS3,
        contains: []
        // defined later
      };
      const TEMPLATE_STRING = {
        className: "string",
        begin: "`",
        end: "`",
        contains: [
          hljs5.BACKSLASH_ESCAPE,
          SUBST
        ]
      };
      SUBST.contains = [
        hljs5.APOS_STRING_MODE,
        hljs5.QUOTE_STRING_MODE,
        TEMPLATE_STRING,
        NUMBER,
        hljs5.REGEXP_MODE
      ];
      const PARAMS_CONTAINS = SUBST.contains.concat([
        hljs5.C_BLOCK_COMMENT_MODE,
        hljs5.C_LINE_COMMENT_MODE
      ]);
      return {
        name: "ArcGIS Arcade",
        keywords: KEYWORDS3,
        contains: [
          hljs5.APOS_STRING_MODE,
          hljs5.QUOTE_STRING_MODE,
          TEMPLATE_STRING,
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          SYMBOL,
          NUMBER,
          {
            // object attr container
            begin: /[{,]\s*/,
            relevance: 0,
            contains: [{
              begin: IDENT_RE3 + "\\s*:",
              returnBegin: true,
              relevance: 0,
              contains: [{
                className: "attr",
                begin: IDENT_RE3,
                relevance: 0
              }]
            }]
          },
          {
            // "value" container
            begin: "(" + hljs5.RE_STARTERS_RE + "|\\b(return)\\b)\\s*",
            keywords: "return",
            contains: [
              hljs5.C_LINE_COMMENT_MODE,
              hljs5.C_BLOCK_COMMENT_MODE,
              hljs5.REGEXP_MODE,
              {
                className: "function",
                begin: "(\\(.*?\\)|" + IDENT_RE3 + ")\\s*=>",
                returnBegin: true,
                end: "\\s*=>",
                contains: [{
                  className: "params",
                  variants: [
                    {
                      begin: IDENT_RE3
                    },
                    {
                      begin: /\(\s*\)/
                    },
                    {
                      begin: /\(/,
                      end: /\)/,
                      excludeBegin: true,
                      excludeEnd: true,
                      keywords: KEYWORDS3,
                      contains: PARAMS_CONTAINS
                    }
                  ]
                }]
              }
            ],
            relevance: 0
          },
          {
            className: "function",
            beginKeywords: "function",
            end: /\{/,
            excludeEnd: true,
            contains: [
              hljs5.inherit(hljs5.TITLE_MODE, {
                begin: IDENT_RE3
              }),
              {
                className: "params",
                begin: /\(/,
                end: /\)/,
                excludeBegin: true,
                excludeEnd: true,
                contains: PARAMS_CONTAINS
              }
            ],
            illegal: /\[|%/
          },
          {
            begin: /\$[(.]/
          }
        ],
        illegal: /#(?!!)/
      };
    }
    module.exports = arcade;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/arduino.js
var require_arduino = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/arduino.js"(exports, module) {
    init_process_shim();
    function source(re2) {
      if (!re2) return null;
      if (typeof re2 === "string") return re2;
      return re2.source;
    }
    function lookahead(re2) {
      return concat("(?=", re2, ")");
    }
    function optional(re2) {
      return concat("(", re2, ")?");
    }
    function concat(...args) {
      const joined = args.map((x2) => source(x2)).join("");
      return joined;
    }
    function cPlusPlus(hljs5) {
      const C_LINE_COMMENT_MODE = hljs5.COMMENT("//", "$", {
        contains: [
          {
            begin: /\\\n/
          }
        ]
      });
      const DECLTYPE_AUTO_RE = "decltype\\(auto\\)";
      const NAMESPACE_RE = "[a-zA-Z_]\\w*::";
      const TEMPLATE_ARGUMENT_RE = "<[^<>]+>";
      const FUNCTION_TYPE_RE = "(" + DECLTYPE_AUTO_RE + "|" + optional(NAMESPACE_RE) + "[a-zA-Z_]\\w*" + optional(TEMPLATE_ARGUMENT_RE) + ")";
      const CPP_PRIMITIVE_TYPES = {
        className: "keyword",
        begin: "\\b[a-z\\d_]*_t\\b"
      };
      const CHARACTER_ESCAPES = "\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)";
      const STRINGS = {
        className: "string",
        variants: [
          {
            begin: '(u8?|U|L)?"',
            end: '"',
            illegal: "\\n",
            contains: [hljs5.BACKSLASH_ESCAPE]
          },
          {
            begin: "(u8?|U|L)?'(" + CHARACTER_ESCAPES + "|.)",
            end: "'",
            illegal: "."
          },
          hljs5.END_SAME_AS_BEGIN({
            begin: /(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/,
            end: /\)([^()\\ ]{0,16})"/
          })
        ]
      };
      const NUMBERS = {
        className: "number",
        variants: [
          {
            begin: "\\b(0b[01']+)"
          },
          {
            begin: "(-?)\\b([\\d']+(\\.[\\d']*)?|\\.[\\d']+)((ll|LL|l|L)(u|U)?|(u|U)(ll|LL|l|L)?|f|F|b|B)"
          },
          {
            begin: "(-?)(\\b0[xX][a-fA-F0-9']+|(\\b[\\d']+(\\.[\\d']*)?|\\.[\\d']+)([eE][-+]?[\\d']+)?)"
          }
        ],
        relevance: 0
      };
      const PREPROCESSOR = {
        className: "meta",
        begin: /#\s*[a-z]+\b/,
        end: /$/,
        keywords: {
          "meta-keyword": "if else elif endif define undef warning error line pragma _Pragma ifdef ifndef include"
        },
        contains: [
          {
            begin: /\\\n/,
            relevance: 0
          },
          hljs5.inherit(STRINGS, {
            className: "meta-string"
          }),
          {
            className: "meta-string",
            begin: /<.*?>/
          },
          C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE
        ]
      };
      const TITLE_MODE = {
        className: "title",
        begin: optional(NAMESPACE_RE) + hljs5.IDENT_RE,
        relevance: 0
      };
      const FUNCTION_TITLE = optional(NAMESPACE_RE) + hljs5.IDENT_RE + "\\s*\\(";
      const COMMON_CPP_HINTS = [
        "asin",
        "atan2",
        "atan",
        "calloc",
        "ceil",
        "cosh",
        "cos",
        "exit",
        "exp",
        "fabs",
        "floor",
        "fmod",
        "fprintf",
        "fputs",
        "free",
        "frexp",
        "auto_ptr",
        "deque",
        "list",
        "queue",
        "stack",
        "vector",
        "map",
        "set",
        "pair",
        "bitset",
        "multiset",
        "multimap",
        "unordered_set",
        "fscanf",
        "future",
        "isalnum",
        "isalpha",
        "iscntrl",
        "isdigit",
        "isgraph",
        "islower",
        "isprint",
        "ispunct",
        "isspace",
        "isupper",
        "isxdigit",
        "tolower",
        "toupper",
        "labs",
        "ldexp",
        "log10",
        "log",
        "malloc",
        "realloc",
        "memchr",
        "memcmp",
        "memcpy",
        "memset",
        "modf",
        "pow",
        "printf",
        "putchar",
        "puts",
        "scanf",
        "sinh",
        "sin",
        "snprintf",
        "sprintf",
        "sqrt",
        "sscanf",
        "strcat",
        "strchr",
        "strcmp",
        "strcpy",
        "strcspn",
        "strlen",
        "strncat",
        "strncmp",
        "strncpy",
        "strpbrk",
        "strrchr",
        "strspn",
        "strstr",
        "tanh",
        "tan",
        "unordered_map",
        "unordered_multiset",
        "unordered_multimap",
        "priority_queue",
        "make_pair",
        "array",
        "shared_ptr",
        "abort",
        "terminate",
        "abs",
        "acos",
        "vfprintf",
        "vprintf",
        "vsprintf",
        "endl",
        "initializer_list",
        "unique_ptr",
        "complex",
        "imaginary",
        "std",
        "string",
        "wstring",
        "cin",
        "cout",
        "cerr",
        "clog",
        "stdin",
        "stdout",
        "stderr",
        "stringstream",
        "istringstream",
        "ostringstream"
      ];
      const CPP_KEYWORDS = {
        keyword: "int float while private char char8_t char16_t char32_t catch import module export virtual operator sizeof dynamic_cast|10 typedef const_cast|10 const for static_cast|10 union namespace unsigned long volatile static protected bool template mutable if public friend do goto auto void enum else break extern using asm case typeid wchar_t short reinterpret_cast|10 default double register explicit signed typename try this switch continue inline delete alignas alignof constexpr consteval constinit decltype concept co_await co_return co_yield requires noexcept static_assert thread_local restrict final override atomic_bool atomic_char atomic_schar atomic_uchar atomic_short atomic_ushort atomic_int atomic_uint atomic_long atomic_ulong atomic_llong atomic_ullong new throw return and and_eq bitand bitor compl not not_eq or or_eq xor xor_eq",
        built_in: "_Bool _Complex _Imaginary",
        _relevance_hints: COMMON_CPP_HINTS,
        literal: "true false nullptr NULL"
      };
      const FUNCTION_DISPATCH = {
        className: "function.dispatch",
        relevance: 0,
        keywords: CPP_KEYWORDS,
        begin: concat(
          /\b/,
          /(?!decltype)/,
          /(?!if)/,
          /(?!for)/,
          /(?!while)/,
          hljs5.IDENT_RE,
          lookahead(/\s*\(/)
        )
      };
      const EXPRESSION_CONTAINS = [
        FUNCTION_DISPATCH,
        PREPROCESSOR,
        CPP_PRIMITIVE_TYPES,
        C_LINE_COMMENT_MODE,
        hljs5.C_BLOCK_COMMENT_MODE,
        NUMBERS,
        STRINGS
      ];
      const EXPRESSION_CONTEXT = {
        // This mode covers expression context where we can't expect a function
        // definition and shouldn't highlight anything that looks like one:
        // `return some()`, `else if()`, `(x*sum(1, 2))`
        variants: [
          {
            begin: /=/,
            end: /;/
          },
          {
            begin: /\(/,
            end: /\)/
          },
          {
            beginKeywords: "new throw return else",
            end: /;/
          }
        ],
        keywords: CPP_KEYWORDS,
        contains: EXPRESSION_CONTAINS.concat([
          {
            begin: /\(/,
            end: /\)/,
            keywords: CPP_KEYWORDS,
            contains: EXPRESSION_CONTAINS.concat(["self"]),
            relevance: 0
          }
        ]),
        relevance: 0
      };
      const FUNCTION_DECLARATION = {
        className: "function",
        begin: "(" + FUNCTION_TYPE_RE + "[\\*&\\s]+)+" + FUNCTION_TITLE,
        returnBegin: true,
        end: /[{;=]/,
        excludeEnd: true,
        keywords: CPP_KEYWORDS,
        illegal: /[^\w\s\*&:<>.]/,
        contains: [
          {
            // to prevent it from being confused as the function title
            begin: DECLTYPE_AUTO_RE,
            keywords: CPP_KEYWORDS,
            relevance: 0
          },
          {
            begin: FUNCTION_TITLE,
            returnBegin: true,
            contains: [TITLE_MODE],
            relevance: 0
          },
          // needed because we do not have look-behind on the below rule
          // to prevent it from grabbing the final : in a :: pair
          {
            begin: /::/,
            relevance: 0
          },
          // initializers
          {
            begin: /:/,
            endsWithParent: true,
            contains: [
              STRINGS,
              NUMBERS
            ]
          },
          {
            className: "params",
            begin: /\(/,
            end: /\)/,
            keywords: CPP_KEYWORDS,
            relevance: 0,
            contains: [
              C_LINE_COMMENT_MODE,
              hljs5.C_BLOCK_COMMENT_MODE,
              STRINGS,
              NUMBERS,
              CPP_PRIMITIVE_TYPES,
              // Count matching parentheses.
              {
                begin: /\(/,
                end: /\)/,
                keywords: CPP_KEYWORDS,
                relevance: 0,
                contains: [
                  "self",
                  C_LINE_COMMENT_MODE,
                  hljs5.C_BLOCK_COMMENT_MODE,
                  STRINGS,
                  NUMBERS,
                  CPP_PRIMITIVE_TYPES
                ]
              }
            ]
          },
          CPP_PRIMITIVE_TYPES,
          C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          PREPROCESSOR
        ]
      };
      return {
        name: "C++",
        aliases: [
          "cc",
          "c++",
          "h++",
          "hpp",
          "hh",
          "hxx",
          "cxx"
        ],
        keywords: CPP_KEYWORDS,
        illegal: "</",
        classNameAliases: {
          "function.dispatch": "built_in"
        },
        contains: [].concat(
          EXPRESSION_CONTEXT,
          FUNCTION_DECLARATION,
          FUNCTION_DISPATCH,
          EXPRESSION_CONTAINS,
          [
            PREPROCESSOR,
            {
              // containers: ie, `vector <int> rooms (9);`
              begin: "\\b(deque|list|queue|priority_queue|pair|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array)\\s*<",
              end: ">",
              keywords: CPP_KEYWORDS,
              contains: [
                "self",
                CPP_PRIMITIVE_TYPES
              ]
            },
            {
              begin: hljs5.IDENT_RE + "::",
              keywords: CPP_KEYWORDS
            },
            {
              className: "class",
              beginKeywords: "enum class struct union",
              end: /[{;:<>=]/,
              contains: [
                {
                  beginKeywords: "final class struct"
                },
                hljs5.TITLE_MODE
              ]
            }
          ]
        ),
        exports: {
          preprocessor: PREPROCESSOR,
          strings: STRINGS,
          keywords: CPP_KEYWORDS
        }
      };
    }
    function arduino(hljs5) {
      const ARDUINO_KW = {
        keyword: "boolean byte word String",
        built_in: "KeyboardController MouseController SoftwareSerial EthernetServer EthernetClient LiquidCrystal RobotControl GSMVoiceCall EthernetUDP EsploraTFT HttpClient RobotMotor WiFiClient GSMScanner FileSystem Scheduler GSMServer YunClient YunServer IPAddress GSMClient GSMModem Keyboard Ethernet Console GSMBand Esplora Stepper Process WiFiUDP GSM_SMS Mailbox USBHost Firmata PImage Client Server GSMPIN FileIO Bridge Serial EEPROM Stream Mouse Audio Servo File Task GPRS WiFi Wire TFT GSM SPI SD ",
        _: "setup loop runShellCommandAsynchronously analogWriteResolution retrieveCallingNumber printFirmwareVersion analogReadResolution sendDigitalPortPair noListenOnLocalhost readJoystickButton setFirmwareVersion readJoystickSwitch scrollDisplayRight getVoiceCallStatus scrollDisplayLeft writeMicroseconds delayMicroseconds beginTransmission getSignalStrength runAsynchronously getAsynchronously listenOnLocalhost getCurrentCarrier readAccelerometer messageAvailable sendDigitalPorts lineFollowConfig countryNameWrite runShellCommand readStringUntil rewindDirectory readTemperature setClockDivider readLightSensor endTransmission analogReference detachInterrupt countryNameRead attachInterrupt encryptionType readBytesUntil robotNameWrite readMicrophone robotNameRead cityNameWrite userNameWrite readJoystickY readJoystickX mouseReleased openNextFile scanNetworks noInterrupts digitalWrite beginSpeaker mousePressed isActionDone mouseDragged displayLogos noAutoscroll addParameter remoteNumber getModifiers keyboardRead userNameRead waitContinue processInput parseCommand printVersion readNetworks writeMessage blinkVersion cityNameRead readMessage setDataMode parsePacket isListening setBitOrder beginPacket isDirectory motorsWrite drawCompass digitalRead clearScreen serialEvent rightToLeft setTextSize leftToRight requestFrom keyReleased compassRead analogWrite interrupts WiFiServer disconnect playMelody parseFloat autoscroll getPINUsed setPINUsed setTimeout sendAnalog readSlider analogRead beginWrite createChar motorsStop keyPressed tempoWrite readButton subnetMask debugPrint macAddress writeGreen randomSeed attachGPRS readString sendString remotePort releaseAll mouseMoved background getXChange getYChange answerCall getResult voiceCall endPacket constrain getSocket writeJSON getButton available connected findUntil readBytes exitValue readGreen writeBlue startLoop IPAddress isPressed sendSysex pauseMode gatewayIP setCursor getOemKey tuneWrite noDisplay loadImage switchPIN onRequest onReceive changePIN playFile noBuffer parseInt overflow checkPIN knobRead beginTFT bitClear updateIR bitWrite position writeRGB highByte writeRed setSpeed readBlue noStroke remoteIP transfer shutdown hangCall beginSMS endWrite attached maintain noCursor checkReg checkPUK shiftOut isValid shiftIn pulseIn connect println localIP pinMode getIMEI display noBlink process getBand running beginSD drawBMP lowByte setBand release bitRead prepare pointTo readRed setMode noFill remove listen stroke detach attach noTone exists buffer height bitSet circle config cursor random IRread setDNS endSMS getKey micros millis begin print write ready flush width isPIN blink clear press mkdir rmdir close point yield image BSSID click delay read text move peek beep rect line open seek fill size turn stop home find step tone sqrt RSSI SSID end bit tan cos sin pow map abs max min get run put",
        literal: "DIGITAL_MESSAGE FIRMATA_STRING ANALOG_MESSAGE REPORT_DIGITAL REPORT_ANALOG INPUT_PULLUP SET_PIN_MODE INTERNAL2V56 SYSTEM_RESET LED_BUILTIN INTERNAL1V1 SYSEX_START INTERNAL EXTERNAL DEFAULT OUTPUT INPUT HIGH LOW"
      };
      const ARDUINO = cPlusPlus(hljs5);
      const kws = (
        /** @type {Record<string,any>} */
        ARDUINO.keywords
      );
      kws.keyword += " " + ARDUINO_KW.keyword;
      kws.literal += " " + ARDUINO_KW.literal;
      kws.built_in += " " + ARDUINO_KW.built_in;
      kws._ += " " + ARDUINO_KW._;
      ARDUINO.name = "Arduino";
      ARDUINO.aliases = ["ino"];
      ARDUINO.supersetOf = "cpp";
      return ARDUINO;
    }
    module.exports = arduino;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/armasm.js
var require_armasm = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/armasm.js"(exports, module) {
    init_process_shim();
    function armasm(hljs5) {
      const COMMENT = {
        variants: [
          hljs5.COMMENT("^[ \\t]*(?=#)", "$", {
            relevance: 0,
            excludeBegin: true
          }),
          hljs5.COMMENT("[;@]", "$", {
            relevance: 0
          }),
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE
        ]
      };
      return {
        name: "ARM Assembly",
        case_insensitive: true,
        aliases: ["arm"],
        keywords: {
          $pattern: "\\.?" + hljs5.IDENT_RE,
          meta: (
            // GNU preprocs
            ".2byte .4byte .align .ascii .asciz .balign .byte .code .data .else .end .endif .endm .endr .equ .err .exitm .extern .global .hword .if .ifdef .ifndef .include .irp .long .macro .rept .req .section .set .skip .space .text .word .arm .thumb .code16 .code32 .force_thumb .thumb_func .ltorg ALIAS ALIGN ARM AREA ASSERT ATTR CN CODE CODE16 CODE32 COMMON CP DATA DCB DCD DCDU DCDO DCFD DCFDU DCI DCQ DCQU DCW DCWU DN ELIF ELSE END ENDFUNC ENDIF ENDP ENTRY EQU EXPORT EXPORTAS EXTERN FIELD FILL FUNCTION GBLA GBLL GBLS GET GLOBAL IF IMPORT INCBIN INCLUDE INFO KEEP LCLA LCLL LCLS LTORG MACRO MAP MEND MEXIT NOFP OPT PRESERVE8 PROC QN READONLY RELOC REQUIRE REQUIRE8 RLIST FN ROUT SETA SETL SETS SN SPACE SUBT THUMB THUMBX TTL WHILE WEND "
          ),
          built_in: "r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 pc lr sp ip sl sb fp a1 a2 a3 a4 v1 v2 v3 v4 v5 v6 v7 v8 f0 f1 f2 f3 f4 f5 f6 f7 p0 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 p13 p14 p15 c0 c1 c2 c3 c4 c5 c6 c7 c8 c9 c10 c11 c12 c13 c14 c15 q0 q1 q2 q3 q4 q5 q6 q7 q8 q9 q10 q11 q12 q13 q14 q15 cpsr_c cpsr_x cpsr_s cpsr_f cpsr_cx cpsr_cxs cpsr_xs cpsr_xsf cpsr_sf cpsr_cxsf spsr_c spsr_x spsr_s spsr_f spsr_cx spsr_cxs spsr_xs spsr_xsf spsr_sf spsr_cxsf s0 s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 s12 s13 s14 s15 s16 s17 s18 s19 s20 s21 s22 s23 s24 s25 s26 s27 s28 s29 s30 s31 d0 d1 d2 d3 d4 d5 d6 d7 d8 d9 d10 d11 d12 d13 d14 d15 d16 d17 d18 d19 d20 d21 d22 d23 d24 d25 d26 d27 d28 d29 d30 d31 {PC} {VAR} {TRUE} {FALSE} {OPT} {CONFIG} {ENDIAN} {CODESIZE} {CPU} {FPU} {ARCHITECTURE} {PCSTOREOFFSET} {ARMASM_VERSION} {INTER} {ROPI} {RWPI} {SWST} {NOSWST} . @"
        },
        contains: [
          {
            className: "keyword",
            begin: "\\b(adc|(qd?|sh?|u[qh]?)?add(8|16)?|usada?8|(q|sh?|u[qh]?)?(as|sa)x|and|adrl?|sbc|rs[bc]|asr|b[lx]?|blx|bxj|cbn?z|tb[bh]|bic|bfc|bfi|[su]bfx|bkpt|cdp2?|clz|clrex|cmp|cmn|cpsi[ed]|cps|setend|dbg|dmb|dsb|eor|isb|it[te]{0,3}|lsl|lsr|ror|rrx|ldm(([id][ab])|f[ds])?|ldr((s|ex)?[bhd])?|movt?|mvn|mra|mar|mul|[us]mull|smul[bwt][bt]|smu[as]d|smmul|smmla|mla|umlaal|smlal?([wbt][bt]|d)|mls|smlsl?[ds]|smc|svc|sev|mia([bt]{2}|ph)?|mrr?c2?|mcrr2?|mrs|msr|orr|orn|pkh(tb|bt)|rbit|rev(16|sh)?|sel|[su]sat(16)?|nop|pop|push|rfe([id][ab])?|stm([id][ab])?|str(ex)?[bhd]?|(qd?)?sub|(sh?|q|u[qh]?)?sub(8|16)|[su]xt(a?h|a?b(16)?)|srs([id][ab])?|swpb?|swi|smi|tst|teq|wfe|wfi|yield)(eq|ne|cs|cc|mi|pl|vs|vc|hi|ls|ge|lt|gt|le|al|hs|lo)?[sptrx]?(?=\\s)"
            // followed by space
          },
          COMMENT,
          hljs5.QUOTE_STRING_MODE,
          {
            className: "string",
            begin: "'",
            end: "[^\\\\]'",
            relevance: 0
          },
          {
            className: "title",
            begin: "\\|",
            end: "\\|",
            illegal: "\\n",
            relevance: 0
          },
          {
            className: "number",
            variants: [
              {
                // hex
                begin: "[#$=]?0x[0-9a-f]+"
              },
              {
                // bin
                begin: "[#$=]?0b[01]+"
              },
              {
                // literal
                begin: "[#$=]\\d+"
              },
              {
                // bare number
                begin: "\\b\\d+"
              }
            ],
            relevance: 0
          },
          {
            className: "symbol",
            variants: [
              {
                // GNU ARM syntax
                begin: "^[ \\t]*[a-z_\\.\\$][a-z0-9_\\.\\$]+:"
              },
              {
                // ARM syntax
                begin: "^[a-z_\\.\\$][a-z0-9_\\.\\$]+"
              },
              {
                // label reference
                begin: "[=#]\\w+"
              }
            ],
            relevance: 0
          }
        ]
      };
    }
    module.exports = armasm;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/xml.js
var require_xml = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/xml.js"(exports, module) {
    init_process_shim();
    function source(re2) {
      if (!re2) return null;
      if (typeof re2 === "string") return re2;
      return re2.source;
    }
    function lookahead(re2) {
      return concat("(?=", re2, ")");
    }
    function optional(re2) {
      return concat("(", re2, ")?");
    }
    function concat(...args) {
      const joined = args.map((x2) => source(x2)).join("");
      return joined;
    }
    function either(...args) {
      const joined = "(" + args.map((x2) => source(x2)).join("|") + ")";
      return joined;
    }
    function xml2(hljs5) {
      const TAG_NAME_RE = concat(/[A-Z_]/, optional(/[A-Z0-9_.-]*:/), /[A-Z0-9_.-]*/);
      const XML_IDENT_RE = /[A-Za-z0-9._:-]+/;
      const XML_ENTITIES = {
        className: "symbol",
        begin: /&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;/
      };
      const XML_META_KEYWORDS = {
        begin: /\s/,
        contains: [
          {
            className: "meta-keyword",
            begin: /#?[a-z_][a-z1-9_-]+/,
            illegal: /\n/
          }
        ]
      };
      const XML_META_PAR_KEYWORDS = hljs5.inherit(XML_META_KEYWORDS, {
        begin: /\(/,
        end: /\)/
      });
      const APOS_META_STRING_MODE = hljs5.inherit(hljs5.APOS_STRING_MODE, {
        className: "meta-string"
      });
      const QUOTE_META_STRING_MODE = hljs5.inherit(hljs5.QUOTE_STRING_MODE, {
        className: "meta-string"
      });
      const TAG_INTERNALS = {
        endsWithParent: true,
        illegal: /</,
        relevance: 0,
        contains: [
          {
            className: "attr",
            begin: XML_IDENT_RE,
            relevance: 0
          },
          {
            begin: /=\s*/,
            relevance: 0,
            contains: [
              {
                className: "string",
                endsParent: true,
                variants: [
                  {
                    begin: /"/,
                    end: /"/,
                    contains: [XML_ENTITIES]
                  },
                  {
                    begin: /'/,
                    end: /'/,
                    contains: [XML_ENTITIES]
                  },
                  {
                    begin: /[^\s"'=<>`]+/
                  }
                ]
              }
            ]
          }
        ]
      };
      return {
        name: "HTML, XML",
        aliases: [
          "html",
          "xhtml",
          "rss",
          "atom",
          "xjb",
          "xsd",
          "xsl",
          "plist",
          "wsf",
          "svg"
        ],
        case_insensitive: true,
        contains: [
          {
            className: "meta",
            begin: /<![a-z]/,
            end: />/,
            relevance: 10,
            contains: [
              XML_META_KEYWORDS,
              QUOTE_META_STRING_MODE,
              APOS_META_STRING_MODE,
              XML_META_PAR_KEYWORDS,
              {
                begin: /\[/,
                end: /\]/,
                contains: [
                  {
                    className: "meta",
                    begin: /<![a-z]/,
                    end: />/,
                    contains: [
                      XML_META_KEYWORDS,
                      XML_META_PAR_KEYWORDS,
                      QUOTE_META_STRING_MODE,
                      APOS_META_STRING_MODE
                    ]
                  }
                ]
              }
            ]
          },
          hljs5.COMMENT(
            /<!--/,
            /-->/,
            {
              relevance: 10
            }
          ),
          {
            begin: /<!\[CDATA\[/,
            end: /\]\]>/,
            relevance: 10
          },
          XML_ENTITIES,
          {
            className: "meta",
            begin: /<\?xml/,
            end: /\?>/,
            relevance: 10
          },
          {
            className: "tag",
            /*
            The lookahead pattern (?=...) ensures that 'begin' only matches
            '<style' as a single word, followed by a whitespace or an
            ending braket. The '$' is needed for the lexeme to be recognized
            by hljs.subMode() that tests lexemes outside the stream.
            */
            begin: /<style(?=\s|>)/,
            end: />/,
            keywords: {
              name: "style"
            },
            contains: [TAG_INTERNALS],
            starts: {
              end: /<\/style>/,
              returnEnd: true,
              subLanguage: [
                "css",
                "xml"
              ]
            }
          },
          {
            className: "tag",
            // See the comment in the <style tag about the lookahead pattern
            begin: /<script(?=\s|>)/,
            end: />/,
            keywords: {
              name: "script"
            },
            contains: [TAG_INTERNALS],
            starts: {
              end: /<\/script>/,
              returnEnd: true,
              subLanguage: [
                "javascript",
                "handlebars",
                "xml"
              ]
            }
          },
          // we need this for now for jSX
          {
            className: "tag",
            begin: /<>|<\/>/
          },
          // open tag
          {
            className: "tag",
            begin: concat(
              /</,
              lookahead(concat(
                TAG_NAME_RE,
                // <tag/>
                // <tag>
                // <tag ...
                either(/\/>/, />/, /\s/)
              ))
            ),
            end: /\/?>/,
            contains: [
              {
                className: "name",
                begin: TAG_NAME_RE,
                relevance: 0,
                starts: TAG_INTERNALS
              }
            ]
          },
          // close tag
          {
            className: "tag",
            begin: concat(
              /<\//,
              lookahead(concat(
                TAG_NAME_RE,
                />/
              ))
            ),
            contains: [
              {
                className: "name",
                begin: TAG_NAME_RE,
                relevance: 0
              },
              {
                begin: />/,
                relevance: 0,
                endsParent: true
              }
            ]
          }
        ]
      };
    }
    module.exports = xml2;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/asciidoc.js
var require_asciidoc = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/asciidoc.js"(exports, module) {
    init_process_shim();
    function source(re2) {
      if (!re2) return null;
      if (typeof re2 === "string") return re2;
      return re2.source;
    }
    function concat(...args) {
      const joined = args.map((x2) => source(x2)).join("");
      return joined;
    }
    function asciidoc(hljs5) {
      const HORIZONTAL_RULE = {
        begin: "^'{3,}[ \\t]*$",
        relevance: 10
      };
      const ESCAPED_FORMATTING = [
        // escaped constrained formatting marks (i.e., \* \_ or \`)
        {
          begin: /\\[*_`]/
        },
        // escaped unconstrained formatting marks (i.e., \\** \\__ or \\``)
        // must ignore until the next formatting marks
        // this rule might not be 100% compliant with Asciidoctor 2.0 but we are entering undefined behavior territory...
        {
          begin: /\\\\\*{2}[^\n]*?\*{2}/
        },
        {
          begin: /\\\\_{2}[^\n]*_{2}/
        },
        {
          begin: /\\\\`{2}[^\n]*`{2}/
        },
        // guard: constrained formatting mark may not be preceded by ":", ";" or
        // "}". match these so the constrained rule doesn't see them
        {
          begin: /[:;}][*_`](?![*_`])/
        }
      ];
      const STRONG = [
        // inline unconstrained strong (single line)
        {
          className: "strong",
          begin: /\*{2}([^\n]+?)\*{2}/
        },
        // inline unconstrained strong (multi-line)
        {
          className: "strong",
          begin: concat(
            /\*\*/,
            /((\*(?!\*)|\\[^\n]|[^*\n\\])+\n)+/,
            /(\*(?!\*)|\\[^\n]|[^*\n\\])*/,
            /\*\*/
          ),
          relevance: 0
        },
        // inline constrained strong (single line)
        {
          className: "strong",
          // must not precede or follow a word character
          begin: /\B\*(\S|\S[^\n]*?\S)\*(?!\w)/
        },
        // inline constrained strong (multi-line)
        {
          className: "strong",
          // must not precede or follow a word character
          begin: /\*[^\s]([^\n]+\n)+([^\n]+)\*/
        }
      ];
      const EMPHASIS = [
        // inline unconstrained emphasis (single line)
        {
          className: "emphasis",
          begin: /_{2}([^\n]+?)_{2}/
        },
        // inline unconstrained emphasis (multi-line)
        {
          className: "emphasis",
          begin: concat(
            /__/,
            /((_(?!_)|\\[^\n]|[^_\n\\])+\n)+/,
            /(_(?!_)|\\[^\n]|[^_\n\\])*/,
            /__/
          ),
          relevance: 0
        },
        // inline constrained emphasis (single line)
        {
          className: "emphasis",
          // must not precede or follow a word character
          begin: /\b_(\S|\S[^\n]*?\S)_(?!\w)/
        },
        // inline constrained emphasis (multi-line)
        {
          className: "emphasis",
          // must not precede or follow a word character
          begin: /_[^\s]([^\n]+\n)+([^\n]+)_/
        },
        // inline constrained emphasis using single quote (legacy)
        {
          className: "emphasis",
          // must not follow a word character or be followed by a single quote or space
          begin: "\\B'(?!['\\s])",
          end: "(\\n{2}|')",
          // allow escaped single quote followed by word char
          contains: [{
            begin: "\\\\'\\w",
            relevance: 0
          }],
          relevance: 0
        }
      ];
      const ADMONITION = {
        className: "symbol",
        begin: "^(NOTE|TIP|IMPORTANT|WARNING|CAUTION):\\s+",
        relevance: 10
      };
      const BULLET_LIST = {
        className: "bullet",
        begin: "^(\\*+|-+|\\.+|[^\\n]+?::)\\s+"
      };
      return {
        name: "AsciiDoc",
        aliases: ["adoc"],
        contains: [
          // block comment
          hljs5.COMMENT(
            "^/{4,}\\n",
            "\\n/{4,}$",
            // can also be done as...
            // '^/{4,}$',
            // '^/{4,}$',
            {
              relevance: 10
            }
          ),
          // line comment
          hljs5.COMMENT(
            "^//",
            "$",
            {
              relevance: 0
            }
          ),
          // title
          {
            className: "title",
            begin: "^\\.\\w.*$"
          },
          // example, admonition & sidebar blocks
          {
            begin: "^[=\\*]{4,}\\n",
            end: "\\n^[=\\*]{4,}$",
            relevance: 10
          },
          // headings
          {
            className: "section",
            relevance: 10,
            variants: [
              {
                begin: "^(={1,6})[ 	].+?([ 	]\\1)?$"
              },
              {
                begin: "^[^\\[\\]\\n]+?\\n[=\\-~\\^\\+]{2,}$"
              }
            ]
          },
          // document attributes
          {
            className: "meta",
            begin: "^:.+?:",
            end: "\\s",
            excludeEnd: true,
            relevance: 10
          },
          // block attributes
          {
            className: "meta",
            begin: "^\\[.+?\\]$",
            relevance: 0
          },
          // quoteblocks
          {
            className: "quote",
            begin: "^_{4,}\\n",
            end: "\\n_{4,}$",
            relevance: 10
          },
          // listing and literal blocks
          {
            className: "code",
            begin: "^[\\-\\.]{4,}\\n",
            end: "\\n[\\-\\.]{4,}$",
            relevance: 10
          },
          // passthrough blocks
          {
            begin: "^\\+{4,}\\n",
            end: "\\n\\+{4,}$",
            contains: [{
              begin: "<",
              end: ">",
              subLanguage: "xml",
              relevance: 0
            }],
            relevance: 10
          },
          BULLET_LIST,
          ADMONITION,
          ...ESCAPED_FORMATTING,
          ...STRONG,
          ...EMPHASIS,
          // inline smart quotes
          {
            className: "string",
            variants: [
              {
                begin: "``.+?''"
              },
              {
                begin: "`.+?'"
              }
            ]
          },
          // inline unconstrained emphasis
          {
            className: "code",
            begin: /`{2}/,
            end: /(\n{2}|`{2})/
          },
          // inline code snippets (TODO should get same treatment as strong and emphasis)
          {
            className: "code",
            begin: "(`.+?`|\\+.+?\\+)",
            relevance: 0
          },
          // indented literal block
          {
            className: "code",
            begin: "^[ \\t]",
            end: "$",
            relevance: 0
          },
          HORIZONTAL_RULE,
          // images and links
          {
            begin: "(link:)?(http|https|ftp|file|irc|image:?):\\S+?\\[[^[]*?\\]",
            returnBegin: true,
            contains: [
              {
                begin: "(link|image:?):",
                relevance: 0
              },
              {
                className: "link",
                begin: "\\w",
                end: "[^\\[]+",
                relevance: 0
              },
              {
                className: "string",
                begin: "\\[",
                end: "\\]",
                excludeBegin: true,
                excludeEnd: true,
                relevance: 0
              }
            ],
            relevance: 10
          }
        ]
      };
    }
    module.exports = asciidoc;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/aspectj.js
var require_aspectj = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/aspectj.js"(exports, module) {
    init_process_shim();
    function source(re2) {
      if (!re2) return null;
      if (typeof re2 === "string") return re2;
      return re2.source;
    }
    function concat(...args) {
      const joined = args.map((x2) => source(x2)).join("");
      return joined;
    }
    function aspectj(hljs5) {
      const KEYWORDS3 = "false synchronized int abstract float private char boolean static null if const for true while long throw strictfp finally protected import native final return void enum else extends implements break transient new catch instanceof byte super volatile case assert short package default double public try this switch continue throws privileged aspectOf adviceexecution proceed cflowbelow cflow initialization preinitialization staticinitialization withincode target within execution getWithinTypeName handler thisJoinPoint thisJoinPointStaticPart thisEnclosingJoinPointStaticPart declare parents warning error soft precedence thisAspectInstance";
      const SHORTKEYS = "get set args call";
      return {
        name: "AspectJ",
        keywords: KEYWORDS3,
        illegal: /<\/|#/,
        contains: [
          hljs5.COMMENT(
            /\/\*\*/,
            /\*\//,
            {
              relevance: 0,
              contains: [
                {
                  // eat up @'s in emails to prevent them to be recognized as doctags
                  begin: /\w+@/,
                  relevance: 0
                },
                {
                  className: "doctag",
                  begin: /@[A-Za-z]+/
                }
              ]
            }
          ),
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          hljs5.APOS_STRING_MODE,
          hljs5.QUOTE_STRING_MODE,
          {
            className: "class",
            beginKeywords: "aspect",
            end: /[{;=]/,
            excludeEnd: true,
            illegal: /[:;"\[\]]/,
            contains: [
              {
                beginKeywords: "extends implements pertypewithin perthis pertarget percflowbelow percflow issingleton"
              },
              hljs5.UNDERSCORE_TITLE_MODE,
              {
                begin: /\([^\)]*/,
                end: /[)]+/,
                keywords: KEYWORDS3 + " " + SHORTKEYS,
                excludeEnd: false
              }
            ]
          },
          {
            className: "class",
            beginKeywords: "class interface",
            end: /[{;=]/,
            excludeEnd: true,
            relevance: 0,
            keywords: "class interface",
            illegal: /[:"\[\]]/,
            contains: [
              {
                beginKeywords: "extends implements"
              },
              hljs5.UNDERSCORE_TITLE_MODE
            ]
          },
          {
            // AspectJ Constructs
            beginKeywords: "pointcut after before around throwing returning",
            end: /[)]/,
            excludeEnd: false,
            illegal: /["\[\]]/,
            contains: [
              {
                begin: concat(hljs5.UNDERSCORE_IDENT_RE, /\s*\(/),
                returnBegin: true,
                contains: [hljs5.UNDERSCORE_TITLE_MODE]
              }
            ]
          },
          {
            begin: /[:]/,
            returnBegin: true,
            end: /[{;]/,
            relevance: 0,
            excludeEnd: false,
            keywords: KEYWORDS3,
            illegal: /["\[\]]/,
            contains: [
              {
                begin: concat(hljs5.UNDERSCORE_IDENT_RE, /\s*\(/),
                keywords: KEYWORDS3 + " " + SHORTKEYS,
                relevance: 0
              },
              hljs5.QUOTE_STRING_MODE
            ]
          },
          {
            // this prevents 'new Name(...), or throw ...' from being recognized as a function definition
            beginKeywords: "new throw",
            relevance: 0
          },
          {
            // the function class is a bit different for AspectJ compared to the Java language
            className: "function",
            begin: /\w+ +\w+(\.\w+)?\s*\([^\)]*\)\s*((throws)[\w\s,]+)?[\{;]/,
            returnBegin: true,
            end: /[{;=]/,
            keywords: KEYWORDS3,
            excludeEnd: true,
            contains: [
              {
                begin: concat(hljs5.UNDERSCORE_IDENT_RE, /\s*\(/),
                returnBegin: true,
                relevance: 0,
                contains: [hljs5.UNDERSCORE_TITLE_MODE]
              },
              {
                className: "params",
                begin: /\(/,
                end: /\)/,
                relevance: 0,
                keywords: KEYWORDS3,
                contains: [
                  hljs5.APOS_STRING_MODE,
                  hljs5.QUOTE_STRING_MODE,
                  hljs5.C_NUMBER_MODE,
                  hljs5.C_BLOCK_COMMENT_MODE
                ]
              },
              hljs5.C_LINE_COMMENT_MODE,
              hljs5.C_BLOCK_COMMENT_MODE
            ]
          },
          hljs5.C_NUMBER_MODE,
          {
            // annotation is also used in this language
            className: "meta",
            begin: /@[A-Za-z]+/
          }
        ]
      };
    }
    module.exports = aspectj;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/autohotkey.js
var require_autohotkey = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/autohotkey.js"(exports, module) {
    init_process_shim();
    function autohotkey(hljs5) {
      const BACKTICK_ESCAPE = {
        begin: "`[\\s\\S]"
      };
      return {
        name: "AutoHotkey",
        case_insensitive: true,
        aliases: ["ahk"],
        keywords: {
          keyword: "Break Continue Critical Exit ExitApp Gosub Goto New OnExit Pause return SetBatchLines SetTimer Suspend Thread Throw Until ahk_id ahk_class ahk_pid ahk_exe ahk_group",
          literal: "true false NOT AND OR",
          built_in: "ComSpec Clipboard ClipboardAll ErrorLevel"
        },
        contains: [
          BACKTICK_ESCAPE,
          hljs5.inherit(hljs5.QUOTE_STRING_MODE, {
            contains: [BACKTICK_ESCAPE]
          }),
          hljs5.COMMENT(";", "$", {
            relevance: 0
          }),
          hljs5.C_BLOCK_COMMENT_MODE,
          {
            className: "number",
            begin: hljs5.NUMBER_RE,
            relevance: 0
          },
          {
            // subst would be the most accurate however fails the point of
            // highlighting. variable is comparably the most accurate that actually
            // has some effect
            className: "variable",
            begin: "%[a-zA-Z0-9#_$@]+%"
          },
          {
            className: "built_in",
            begin: "^\\s*\\w+\\s*(,|%)"
            // I don't really know if this is totally relevant
          },
          {
            // symbol would be most accurate however is highlighted just like
            // built_in and that makes up a lot of AutoHotkey code meaning that it
            // would fail to highlight anything
            className: "title",
            variants: [
              {
                begin: '^[^\\n";]+::(?!=)'
              },
              {
                begin: '^[^\\n";]+:(?!=)',
                // zero relevance as it catches a lot of things
                // followed by a single ':' in many languages
                relevance: 0
              }
            ]
          },
          {
            className: "meta",
            begin: "^\\s*#\\w+",
            end: "$",
            relevance: 0
          },
          {
            className: "built_in",
            begin: "A_[a-zA-Z0-9]+"
          },
          {
            // consecutive commas, not for highlighting but just for relevance
            begin: ",\\s*,"
          }
        ]
      };
    }
    module.exports = autohotkey;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/autoit.js
var require_autoit = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/autoit.js"(exports, module) {
    init_process_shim();
    function autoit(hljs5) {
      const KEYWORDS3 = "ByRef Case Const ContinueCase ContinueLoop Dim Do Else ElseIf EndFunc EndIf EndSelect EndSwitch EndWith Enum Exit ExitLoop For Func Global If In Local Next ReDim Return Select Static Step Switch Then To Until Volatile WEnd While With";
      const DIRECTIVES = [
        "EndRegion",
        "forcedef",
        "forceref",
        "ignorefunc",
        "include",
        "include-once",
        "NoTrayIcon",
        "OnAutoItStartRegister",
        "pragma",
        "Region",
        "RequireAdmin",
        "Tidy_Off",
        "Tidy_On",
        "Tidy_Parameters"
      ];
      const LITERAL = "True False And Null Not Or Default";
      const BUILT_IN = "Abs ACos AdlibRegister AdlibUnRegister Asc AscW ASin Assign ATan AutoItSetOption AutoItWinGetTitle AutoItWinSetTitle Beep Binary BinaryLen BinaryMid BinaryToString BitAND BitNOT BitOR BitRotate BitShift BitXOR BlockInput Break Call CDTray Ceiling Chr ChrW ClipGet ClipPut ConsoleRead ConsoleWrite ConsoleWriteError ControlClick ControlCommand ControlDisable ControlEnable ControlFocus ControlGetFocus ControlGetHandle ControlGetPos ControlGetText ControlHide ControlListView ControlMove ControlSend ControlSetText ControlShow ControlTreeView Cos Dec DirCopy DirCreate DirGetSize DirMove DirRemove DllCall DllCallAddress DllCallbackFree DllCallbackGetPtr DllCallbackRegister DllClose DllOpen DllStructCreate DllStructGetData DllStructGetPtr DllStructGetSize DllStructSetData DriveGetDrive DriveGetFileSystem DriveGetLabel DriveGetSerial DriveGetType DriveMapAdd DriveMapDel DriveMapGet DriveSetLabel DriveSpaceFree DriveSpaceTotal DriveStatus EnvGet EnvSet EnvUpdate Eval Execute Exp FileChangeDir FileClose FileCopy FileCreateNTFSLink FileCreateShortcut FileDelete FileExists FileFindFirstFile FileFindNextFile FileFlush FileGetAttrib FileGetEncoding FileGetLongName FileGetPos FileGetShortcut FileGetShortName FileGetSize FileGetTime FileGetVersion FileInstall FileMove FileOpen FileOpenDialog FileRead FileReadLine FileReadToArray FileRecycle FileRecycleEmpty FileSaveDialog FileSelectFolder FileSetAttrib FileSetEnd FileSetPos FileSetTime FileWrite FileWriteLine Floor FtpSetProxy FuncName GUICreate GUICtrlCreateAvi GUICtrlCreateButton GUICtrlCreateCheckbox GUICtrlCreateCombo GUICtrlCreateContextMenu GUICtrlCreateDate GUICtrlCreateDummy GUICtrlCreateEdit GUICtrlCreateGraphic GUICtrlCreateGroup GUICtrlCreateIcon GUICtrlCreateInput GUICtrlCreateLabel GUICtrlCreateList GUICtrlCreateListView GUICtrlCreateListViewItem GUICtrlCreateMenu GUICtrlCreateMenuItem GUICtrlCreateMonthCal GUICtrlCreateObj GUICtrlCreatePic GUICtrlCreateProgress GUICtrlCreateRadio GUICtrlCreateSlider GUICtrlCreateTab GUICtrlCreateTabItem GUICtrlCreateTreeView GUICtrlCreateTreeViewItem GUICtrlCreateUpdown GUICtrlDelete GUICtrlGetHandle GUICtrlGetState GUICtrlRead GUICtrlRecvMsg GUICtrlRegisterListViewSort GUICtrlSendMsg GUICtrlSendToDummy GUICtrlSetBkColor GUICtrlSetColor GUICtrlSetCursor GUICtrlSetData GUICtrlSetDefBkColor GUICtrlSetDefColor GUICtrlSetFont GUICtrlSetGraphic GUICtrlSetImage GUICtrlSetLimit GUICtrlSetOnEvent GUICtrlSetPos GUICtrlSetResizing GUICtrlSetState GUICtrlSetStyle GUICtrlSetTip GUIDelete GUIGetCursorInfo GUIGetMsg GUIGetStyle GUIRegisterMsg GUISetAccelerators GUISetBkColor GUISetCoord GUISetCursor GUISetFont GUISetHelp GUISetIcon GUISetOnEvent GUISetState GUISetStyle GUIStartGroup GUISwitch Hex HotKeySet HttpSetProxy HttpSetUserAgent HWnd InetClose InetGet InetGetInfo InetGetSize InetRead IniDelete IniRead IniReadSection IniReadSectionNames IniRenameSection IniWrite IniWriteSection InputBox Int IsAdmin IsArray IsBinary IsBool IsDeclared IsDllStruct IsFloat IsFunc IsHWnd IsInt IsKeyword IsNumber IsObj IsPtr IsString Log MemGetStats Mod MouseClick MouseClickDrag MouseDown MouseGetCursor MouseGetPos MouseMove MouseUp MouseWheel MsgBox Number ObjCreate ObjCreateInterface ObjEvent ObjGet ObjName OnAutoItExitRegister OnAutoItExitUnRegister Ping PixelChecksum PixelGetColor PixelSearch ProcessClose ProcessExists ProcessGetStats ProcessList ProcessSetPriority ProcessWait ProcessWaitClose ProgressOff ProgressOn ProgressSet Ptr Random RegDelete RegEnumKey RegEnumVal RegRead RegWrite Round Run RunAs RunAsWait RunWait Send SendKeepActive SetError SetExtended ShellExecute ShellExecuteWait Shutdown Sin Sleep SoundPlay SoundSetWaveVolume SplashImageOn SplashOff SplashTextOn Sqrt SRandom StatusbarGetText StderrRead StdinWrite StdioClose StdoutRead String StringAddCR StringCompare StringFormat StringFromASCIIArray StringInStr StringIsAlNum StringIsAlpha StringIsASCII StringIsDigit StringIsFloat StringIsInt StringIsLower StringIsSpace StringIsUpper StringIsXDigit StringLeft StringLen StringLower StringMid StringRegExp StringRegExpReplace StringReplace StringReverse StringRight StringSplit StringStripCR StringStripWS StringToASCIIArray StringToBinary StringTrimLeft StringTrimRight StringUpper Tan TCPAccept TCPCloseSocket TCPConnect TCPListen TCPNameToIP TCPRecv TCPSend TCPShutdown, UDPShutdown TCPStartup, UDPStartup TimerDiff TimerInit ToolTip TrayCreateItem TrayCreateMenu TrayGetMsg TrayItemDelete TrayItemGetHandle TrayItemGetState TrayItemGetText TrayItemSetOnEvent TrayItemSetState TrayItemSetText TraySetClick TraySetIcon TraySetOnEvent TraySetPauseIcon TraySetState TraySetToolTip TrayTip UBound UDPBind UDPCloseSocket UDPOpen UDPRecv UDPSend VarGetType WinActivate WinActive WinClose WinExists WinFlash WinGetCaretPos WinGetClassList WinGetClientSize WinGetHandle WinGetPos WinGetProcess WinGetState WinGetText WinGetTitle WinKill WinList WinMenuSelectItem WinMinimizeAll WinMinimizeAllUndo WinMove WinSetOnTop WinSetState WinSetTitle WinSetTrans WinWait WinWaitActive WinWaitClose WinWaitNotActive";
      const COMMENT = {
        variants: [
          hljs5.COMMENT(";", "$", {
            relevance: 0
          }),
          hljs5.COMMENT("#cs", "#ce"),
          hljs5.COMMENT("#comments-start", "#comments-end")
        ]
      };
      const VARIABLE = {
        begin: "\\$[A-z0-9_]+"
      };
      const STRING = {
        className: "string",
        variants: [
          {
            begin: /"/,
            end: /"/,
            contains: [{
              begin: /""/,
              relevance: 0
            }]
          },
          {
            begin: /'/,
            end: /'/,
            contains: [{
              begin: /''/,
              relevance: 0
            }]
          }
        ]
      };
      const NUMBER = {
        variants: [
          hljs5.BINARY_NUMBER_MODE,
          hljs5.C_NUMBER_MODE
        ]
      };
      const PREPROCESSOR = {
        className: "meta",
        begin: "#",
        end: "$",
        keywords: {
          "meta-keyword": DIRECTIVES
        },
        contains: [
          {
            begin: /\\\n/,
            relevance: 0
          },
          {
            beginKeywords: "include",
            keywords: {
              "meta-keyword": "include"
            },
            end: "$",
            contains: [
              STRING,
              {
                className: "meta-string",
                variants: [
                  {
                    begin: "<",
                    end: ">"
                  },
                  {
                    begin: /"/,
                    end: /"/,
                    contains: [{
                      begin: /""/,
                      relevance: 0
                    }]
                  },
                  {
                    begin: /'/,
                    end: /'/,
                    contains: [{
                      begin: /''/,
                      relevance: 0
                    }]
                  }
                ]
              }
            ]
          },
          STRING,
          COMMENT
        ]
      };
      const CONSTANT = {
        className: "symbol",
        // begin: '@',
        // end: '$',
        // keywords: 'AppDataCommonDir AppDataDir AutoItExe AutoItPID AutoItVersion AutoItX64 COM_EventObj CommonFilesDir Compiled ComputerName ComSpec CPUArch CR CRLF DesktopCommonDir DesktopDepth DesktopDir DesktopHeight DesktopRefresh DesktopWidth DocumentsCommonDir error exitCode exitMethod extended FavoritesCommonDir FavoritesDir GUI_CtrlHandle GUI_CtrlId GUI_DragFile GUI_DragId GUI_DropId GUI_WinHandle HomeDrive HomePath HomeShare HotKeyPressed HOUR IPAddress1 IPAddress2 IPAddress3 IPAddress4 KBLayout LF LocalAppDataDir LogonDNSDomain LogonDomain LogonServer MDAY MIN MON MSEC MUILang MyDocumentsDir NumParams OSArch OSBuild OSLang OSServicePack OSType OSVersion ProgramFilesDir ProgramsCommonDir ProgramsDir ScriptDir ScriptFullPath ScriptLineNumber ScriptName SEC StartMenuCommonDir StartMenuDir StartupCommonDir StartupDir SW_DISABLE SW_ENABLE SW_HIDE SW_LOCK SW_MAXIMIZE SW_MINIMIZE SW_RESTORE SW_SHOW SW_SHOWDEFAULT SW_SHOWMAXIMIZED SW_SHOWMINIMIZED SW_SHOWMINNOACTIVE SW_SHOWNA SW_SHOWNOACTIVATE SW_SHOWNORMAL SW_UNLOCK SystemDir TAB TempDir TRAY_ID TrayIconFlashing TrayIconVisible UserName UserProfileDir WDAY WindowsDir WorkingDir YDAY YEAR',
        // relevance: 5
        begin: "@[A-z0-9_]+"
      };
      const FUNCTION = {
        className: "function",
        beginKeywords: "Func",
        end: "$",
        illegal: "\\$|\\[|%",
        contains: [
          hljs5.UNDERSCORE_TITLE_MODE,
          {
            className: "params",
            begin: "\\(",
            end: "\\)",
            contains: [
              VARIABLE,
              STRING,
              NUMBER
            ]
          }
        ]
      };
      return {
        name: "AutoIt",
        case_insensitive: true,
        illegal: /\/\*/,
        keywords: {
          keyword: KEYWORDS3,
          built_in: BUILT_IN,
          literal: LITERAL
        },
        contains: [
          COMMENT,
          VARIABLE,
          STRING,
          NUMBER,
          PREPROCESSOR,
          CONSTANT,
          FUNCTION
        ]
      };
    }
    module.exports = autoit;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/avrasm.js
var require_avrasm = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/avrasm.js"(exports, module) {
    init_process_shim();
    function avrasm(hljs5) {
      return {
        name: "AVR Assembly",
        case_insensitive: true,
        keywords: {
          $pattern: "\\.?" + hljs5.IDENT_RE,
          keyword: (
            /* mnemonic */
            "adc add adiw and andi asr bclr bld brbc brbs brcc brcs break breq brge brhc brhs brid brie brlo brlt brmi brne brpl brsh brtc brts brvc brvs bset bst call cbi cbr clc clh cli cln clr cls clt clv clz com cp cpc cpi cpse dec eicall eijmp elpm eor fmul fmuls fmulsu icall ijmp in inc jmp ld ldd ldi lds lpm lsl lsr mov movw mul muls mulsu neg nop or ori out pop push rcall ret reti rjmp rol ror sbc sbr sbrc sbrs sec seh sbi sbci sbic sbis sbiw sei sen ser ses set sev sez sleep spm st std sts sub subi swap tst wdr"
          ),
          built_in: (
            /* general purpose registers */
            "r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 r16 r17 r18 r19 r20 r21 r22 r23 r24 r25 r26 r27 r28 r29 r30 r31 x|0 xh xl y|0 yh yl z|0 zh zl ucsr1c udr1 ucsr1a ucsr1b ubrr1l ubrr1h ucsr0c ubrr0h tccr3c tccr3a tccr3b tcnt3h tcnt3l ocr3ah ocr3al ocr3bh ocr3bl ocr3ch ocr3cl icr3h icr3l etimsk etifr tccr1c ocr1ch ocr1cl twcr twdr twar twsr twbr osccal xmcra xmcrb eicra spmcsr spmcr portg ddrg ping portf ddrf sreg sph spl xdiv rampz eicrb eimsk gimsk gicr eifr gifr timsk tifr mcucr mcucsr tccr0 tcnt0 ocr0 assr tccr1a tccr1b tcnt1h tcnt1l ocr1ah ocr1al ocr1bh ocr1bl icr1h icr1l tccr2 tcnt2 ocr2 ocdr wdtcr sfior eearh eearl eedr eecr porta ddra pina portb ddrb pinb portc ddrc pinc portd ddrd pind spdr spsr spcr udr0 ucsr0a ucsr0b ubrr0l acsr admux adcsr adch adcl porte ddre pine pinf"
          ),
          meta: ".byte .cseg .db .def .device .dseg .dw .endmacro .equ .eseg .exit .include .list .listmac .macro .nolist .org .set"
        },
        contains: [
          hljs5.C_BLOCK_COMMENT_MODE,
          hljs5.COMMENT(
            ";",
            "$",
            {
              relevance: 0
            }
          ),
          hljs5.C_NUMBER_MODE,
          // 0x..., decimal, float
          hljs5.BINARY_NUMBER_MODE,
          // 0b...
          {
            className: "number",
            begin: "\\b(\\$[a-zA-Z0-9]+|0o[0-7]+)"
            // $..., 0o...
          },
          hljs5.QUOTE_STRING_MODE,
          {
            className: "string",
            begin: "'",
            end: "[^\\\\]'",
            illegal: "[^\\\\][^']"
          },
          {
            className: "symbol",
            begin: "^[A-Za-z0-9_.$]+:"
          },
          {
            className: "meta",
            begin: "#",
            end: "$"
          },
          {
            // substitution within a macro
            className: "subst",
            begin: "@[0-9]+"
          }
        ]
      };
    }
    module.exports = avrasm;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/awk.js
var require_awk = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/awk.js"(exports, module) {
    init_process_shim();
    function awk(hljs5) {
      const VARIABLE = {
        className: "variable",
        variants: [
          {
            begin: /\$[\w\d#@][\w\d_]*/
          },
          {
            begin: /\$\{(.*?)\}/
          }
        ]
      };
      const KEYWORDS3 = "BEGIN END if else while do for in break continue delete next nextfile function func exit|10";
      const STRING = {
        className: "string",
        contains: [hljs5.BACKSLASH_ESCAPE],
        variants: [
          {
            begin: /(u|b)?r?'''/,
            end: /'''/,
            relevance: 10
          },
          {
            begin: /(u|b)?r?"""/,
            end: /"""/,
            relevance: 10
          },
          {
            begin: /(u|r|ur)'/,
            end: /'/,
            relevance: 10
          },
          {
            begin: /(u|r|ur)"/,
            end: /"/,
            relevance: 10
          },
          {
            begin: /(b|br)'/,
            end: /'/
          },
          {
            begin: /(b|br)"/,
            end: /"/
          },
          hljs5.APOS_STRING_MODE,
          hljs5.QUOTE_STRING_MODE
        ]
      };
      return {
        name: "Awk",
        keywords: {
          keyword: KEYWORDS3
        },
        contains: [
          VARIABLE,
          STRING,
          hljs5.REGEXP_MODE,
          hljs5.HASH_COMMENT_MODE,
          hljs5.NUMBER_MODE
        ]
      };
    }
    module.exports = awk;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/axapta.js
var require_axapta = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/axapta.js"(exports, module) {
    init_process_shim();
    function axapta(hljs5) {
      const BUILT_IN_KEYWORDS = [
        "anytype",
        "boolean",
        "byte",
        "char",
        "container",
        "date",
        "double",
        "enum",
        "guid",
        "int",
        "int64",
        "long",
        "real",
        "short",
        "str",
        "utcdatetime",
        "var"
      ];
      const LITERAL_KEYWORDS = [
        "default",
        "false",
        "null",
        "true"
      ];
      const NORMAL_KEYWORDS = [
        "abstract",
        "as",
        "asc",
        "avg",
        "break",
        "breakpoint",
        "by",
        "byref",
        "case",
        "catch",
        "changecompany",
        "class",
        "client",
        "client",
        "common",
        "const",
        "continue",
        "count",
        "crosscompany",
        "delegate",
        "delete_from",
        "desc",
        "display",
        "div",
        "do",
        "edit",
        "else",
        "eventhandler",
        "exists",
        "extends",
        "final",
        "finally",
        "firstfast",
        "firstonly",
        "firstonly1",
        "firstonly10",
        "firstonly100",
        "firstonly1000",
        "flush",
        "for",
        "forceliterals",
        "forcenestedloop",
        "forceplaceholders",
        "forceselectorder",
        "forupdate",
        "from",
        "generateonly",
        "group",
        "hint",
        "if",
        "implements",
        "in",
        "index",
        "insert_recordset",
        "interface",
        "internal",
        "is",
        "join",
        "like",
        "maxof",
        "minof",
        "mod",
        "namespace",
        "new",
        "next",
        "nofetch",
        "notexists",
        "optimisticlock",
        "order",
        "outer",
        "pessimisticlock",
        "print",
        "private",
        "protected",
        "public",
        "readonly",
        "repeatableread",
        "retry",
        "return",
        "reverse",
        "select",
        "server",
        "setting",
        "static",
        "sum",
        "super",
        "switch",
        "this",
        "throw",
        "try",
        "ttsabort",
        "ttsbegin",
        "ttscommit",
        "unchecked",
        "update_recordset",
        "using",
        "validtimestate",
        "void",
        "where",
        "while"
      ];
      const KEYWORDS3 = {
        keyword: NORMAL_KEYWORDS,
        built_in: BUILT_IN_KEYWORDS,
        literal: LITERAL_KEYWORDS
      };
      return {
        name: "X++",
        aliases: ["x++"],
        keywords: KEYWORDS3,
        contains: [
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          hljs5.APOS_STRING_MODE,
          hljs5.QUOTE_STRING_MODE,
          hljs5.C_NUMBER_MODE,
          {
            className: "meta",
            begin: "#",
            end: "$"
          },
          {
            className: "class",
            beginKeywords: "class interface",
            end: /\{/,
            excludeEnd: true,
            illegal: ":",
            contains: [
              {
                beginKeywords: "extends implements"
              },
              hljs5.UNDERSCORE_TITLE_MODE
            ]
          }
        ]
      };
    }
    module.exports = axapta;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/bash.js
var require_bash = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/bash.js"(exports, module) {
    init_process_shim();
    function source(re2) {
      if (!re2) return null;
      if (typeof re2 === "string") return re2;
      return re2.source;
    }
    function concat(...args) {
      const joined = args.map((x2) => source(x2)).join("");
      return joined;
    }
    function bash2(hljs5) {
      const VAR = {};
      const BRACED_VAR = {
        begin: /\$\{/,
        end: /\}/,
        contains: [
          "self",
          {
            begin: /:-/,
            contains: [VAR]
          }
          // default values
        ]
      };
      Object.assign(VAR, {
        className: "variable",
        variants: [
          { begin: concat(
            /\$[\w\d#@][\w\d_]*/,
            // negative look-ahead tries to avoid matching patterns that are not
            // Perl at all like $ident$, @ident@, etc.
            `(?![\\w\\d])(?![$])`
          ) },
          BRACED_VAR
        ]
      });
      const SUBST = {
        className: "subst",
        begin: /\$\(/,
        end: /\)/,
        contains: [hljs5.BACKSLASH_ESCAPE]
      };
      const HERE_DOC = {
        begin: /<<-?\s*(?=\w+)/,
        starts: {
          contains: [
            hljs5.END_SAME_AS_BEGIN({
              begin: /(\w+)/,
              end: /(\w+)/,
              className: "string"
            })
          ]
        }
      };
      const QUOTE_STRING = {
        className: "string",
        begin: /"/,
        end: /"/,
        contains: [
          hljs5.BACKSLASH_ESCAPE,
          VAR,
          SUBST
        ]
      };
      SUBST.contains.push(QUOTE_STRING);
      const ESCAPED_QUOTE = {
        className: "",
        begin: /\\"/
      };
      const APOS_STRING = {
        className: "string",
        begin: /'/,
        end: /'/
      };
      const ARITHMETIC = {
        begin: /\$\(\(/,
        end: /\)\)/,
        contains: [
          { begin: /\d+#[0-9a-f]+/, className: "number" },
          hljs5.NUMBER_MODE,
          VAR
        ]
      };
      const SH_LIKE_SHELLS = [
        "fish",
        "bash",
        "zsh",
        "sh",
        "csh",
        "ksh",
        "tcsh",
        "dash",
        "scsh"
      ];
      const KNOWN_SHEBANG = hljs5.SHEBANG({
        binary: `(${SH_LIKE_SHELLS.join("|")})`,
        relevance: 10
      });
      const FUNCTION = {
        className: "function",
        begin: /\w[\w\d_]*\s*\(\s*\)\s*\{/,
        returnBegin: true,
        contains: [hljs5.inherit(hljs5.TITLE_MODE, { begin: /\w[\w\d_]*/ })],
        relevance: 0
      };
      return {
        name: "Bash",
        aliases: ["sh", "zsh"],
        keywords: {
          $pattern: /\b[a-z._-]+\b/,
          keyword: "if then else elif fi for while in do done case esac function",
          literal: "true false",
          built_in: (
            // Shell built-ins
            // http://www.gnu.org/software/bash/manual/html_node/Shell-Builtin-Commands.html
            "break cd continue eval exec exit export getopts hash pwd readonly return shift test times trap umask unset alias bind builtin caller command declare echo enable help let local logout mapfile printf read readarray source type typeset ulimit unalias set shopt autoload bg bindkey bye cap chdir clone comparguments compcall compctl compdescribe compfiles compgroups compquote comptags comptry compvalues dirs disable disown echotc echoti emulate fc fg float functions getcap getln history integer jobs kill limit log noglob popd print pushd pushln rehash sched setcap setopt stat suspend ttyctl unfunction unhash unlimit unsetopt vared wait whence where which zcompile zformat zftp zle zmodload zparseopts zprof zpty zregexparse zsocket zstyle ztcp"
          )
        },
        contains: [
          KNOWN_SHEBANG,
          // to catch known shells and boost relevancy
          hljs5.SHEBANG(),
          // to catch unknown shells but still highlight the shebang
          FUNCTION,
          ARITHMETIC,
          hljs5.HASH_COMMENT_MODE,
          HERE_DOC,
          QUOTE_STRING,
          ESCAPED_QUOTE,
          APOS_STRING,
          VAR
        ]
      };
    }
    module.exports = bash2;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/basic.js
var require_basic = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/basic.js"(exports, module) {
    init_process_shim();
    function basic(hljs5) {
      return {
        name: "BASIC",
        case_insensitive: true,
        illegal: "^.",
        // Support explicitly typed variables that end with $%! or #.
        keywords: {
          $pattern: "[a-zA-Z][a-zA-Z0-9_$%!#]*",
          keyword: "ABS ASC AND ATN AUTO|0 BEEP BLOAD|10 BSAVE|10 CALL CALLS CDBL CHAIN CHDIR CHR$|10 CINT CIRCLE CLEAR CLOSE CLS COLOR COM COMMON CONT COS CSNG CSRLIN CVD CVI CVS DATA DATE$ DEFDBL DEFINT DEFSNG DEFSTR DEF|0 SEG USR DELETE DIM DRAW EDIT END ENVIRON ENVIRON$ EOF EQV ERASE ERDEV ERDEV$ ERL ERR ERROR EXP FIELD FILES FIX FOR|0 FRE GET GOSUB|10 GOTO HEX$ IF THEN ELSE|0 INKEY$ INP INPUT INPUT# INPUT$ INSTR IMP INT IOCTL IOCTL$ KEY ON OFF LIST KILL LEFT$ LEN LET LINE LLIST LOAD LOC LOCATE LOF LOG LPRINT USING LSET MERGE MID$ MKDIR MKD$ MKI$ MKS$ MOD NAME NEW NEXT NOISE NOT OCT$ ON OR PEN PLAY STRIG OPEN OPTION BASE OUT PAINT PALETTE PCOPY PEEK PMAP POINT POKE POS PRINT PRINT] PSET PRESET PUT RANDOMIZE READ REM RENUM RESET|0 RESTORE RESUME RETURN|0 RIGHT$ RMDIR RND RSET RUN SAVE SCREEN SGN SHELL SIN SOUND SPACE$ SPC SQR STEP STICK STOP STR$ STRING$ SWAP SYSTEM TAB TAN TIME$ TIMER TROFF TRON TO USR VAL VARPTR VARPTR$ VIEW WAIT WHILE WEND WIDTH WINDOW WRITE XOR"
        },
        contains: [
          hljs5.QUOTE_STRING_MODE,
          hljs5.COMMENT("REM", "$", {
            relevance: 10
          }),
          hljs5.COMMENT("'", "$", {
            relevance: 0
          }),
          {
            // Match line numbers
            className: "symbol",
            begin: "^[0-9]+ ",
            relevance: 10
          },
          {
            // Match typed numeric constants (1000, 12.34!, 1.2e5, 1.5#, 1.2D2)
            className: "number",
            begin: "\\b\\d+(\\.\\d+)?([edED]\\d+)?[#!]?",
            relevance: 0
          },
          {
            // Match hexadecimal numbers (&Hxxxx)
            className: "number",
            begin: "(&[hH][0-9a-fA-F]{1,4})"
          },
          {
            // Match octal numbers (&Oxxxxxx)
            className: "number",
            begin: "(&[oO][0-7]{1,6})"
          }
        ]
      };
    }
    module.exports = basic;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/bnf.js
var require_bnf = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/bnf.js"(exports, module) {
    init_process_shim();
    function bnf(hljs5) {
      return {
        name: "Backus\u2013Naur Form",
        contains: [
          // Attribute
          {
            className: "attribute",
            begin: /</,
            end: />/
          },
          // Specific
          {
            begin: /::=/,
            end: /$/,
            contains: [
              {
                begin: /</,
                end: />/
              },
              // Common
              hljs5.C_LINE_COMMENT_MODE,
              hljs5.C_BLOCK_COMMENT_MODE,
              hljs5.APOS_STRING_MODE,
              hljs5.QUOTE_STRING_MODE
            ]
          }
        ]
      };
    }
    module.exports = bnf;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/brainfuck.js
var require_brainfuck = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/brainfuck.js"(exports, module) {
    init_process_shim();
    function brainfuck(hljs5) {
      const LITERAL = {
        className: "literal",
        begin: /[+-]/,
        relevance: 0
      };
      return {
        name: "Brainfuck",
        aliases: ["bf"],
        contains: [
          hljs5.COMMENT(
            "[^\\[\\]\\.,\\+\\-<> \r\n]",
            "[\\[\\]\\.,\\+\\-<> \r\n]",
            {
              returnEnd: true,
              relevance: 0
            }
          ),
          {
            className: "title",
            begin: "[\\[\\]]",
            relevance: 0
          },
          {
            className: "string",
            begin: "[\\.,]",
            relevance: 0
          },
          {
            // this mode works as the only relevance counter
            begin: /(?:\+\+|--)/,
            contains: [LITERAL]
          },
          LITERAL
        ]
      };
    }
    module.exports = brainfuck;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/c-like.js
var require_c_like = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/c-like.js"(exports, module) {
    init_process_shim();
    function source(re2) {
      if (!re2) return null;
      if (typeof re2 === "string") return re2;
      return re2.source;
    }
    function lookahead(re2) {
      return concat("(?=", re2, ")");
    }
    function optional(re2) {
      return concat("(", re2, ")?");
    }
    function concat(...args) {
      const joined = args.map((x2) => source(x2)).join("");
      return joined;
    }
    function cPlusPlus(hljs5) {
      const C_LINE_COMMENT_MODE = hljs5.COMMENT("//", "$", {
        contains: [
          {
            begin: /\\\n/
          }
        ]
      });
      const DECLTYPE_AUTO_RE = "decltype\\(auto\\)";
      const NAMESPACE_RE = "[a-zA-Z_]\\w*::";
      const TEMPLATE_ARGUMENT_RE = "<[^<>]+>";
      const FUNCTION_TYPE_RE = "(" + DECLTYPE_AUTO_RE + "|" + optional(NAMESPACE_RE) + "[a-zA-Z_]\\w*" + optional(TEMPLATE_ARGUMENT_RE) + ")";
      const CPP_PRIMITIVE_TYPES = {
        className: "keyword",
        begin: "\\b[a-z\\d_]*_t\\b"
      };
      const CHARACTER_ESCAPES = "\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)";
      const STRINGS = {
        className: "string",
        variants: [
          {
            begin: '(u8?|U|L)?"',
            end: '"',
            illegal: "\\n",
            contains: [hljs5.BACKSLASH_ESCAPE]
          },
          {
            begin: "(u8?|U|L)?'(" + CHARACTER_ESCAPES + "|.)",
            end: "'",
            illegal: "."
          },
          hljs5.END_SAME_AS_BEGIN({
            begin: /(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/,
            end: /\)([^()\\ ]{0,16})"/
          })
        ]
      };
      const NUMBERS = {
        className: "number",
        variants: [
          {
            begin: "\\b(0b[01']+)"
          },
          {
            begin: "(-?)\\b([\\d']+(\\.[\\d']*)?|\\.[\\d']+)((ll|LL|l|L)(u|U)?|(u|U)(ll|LL|l|L)?|f|F|b|B)"
          },
          {
            begin: "(-?)(\\b0[xX][a-fA-F0-9']+|(\\b[\\d']+(\\.[\\d']*)?|\\.[\\d']+)([eE][-+]?[\\d']+)?)"
          }
        ],
        relevance: 0
      };
      const PREPROCESSOR = {
        className: "meta",
        begin: /#\s*[a-z]+\b/,
        end: /$/,
        keywords: {
          "meta-keyword": "if else elif endif define undef warning error line pragma _Pragma ifdef ifndef include"
        },
        contains: [
          {
            begin: /\\\n/,
            relevance: 0
          },
          hljs5.inherit(STRINGS, {
            className: "meta-string"
          }),
          {
            className: "meta-string",
            begin: /<.*?>/
          },
          C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE
        ]
      };
      const TITLE_MODE = {
        className: "title",
        begin: optional(NAMESPACE_RE) + hljs5.IDENT_RE,
        relevance: 0
      };
      const FUNCTION_TITLE = optional(NAMESPACE_RE) + hljs5.IDENT_RE + "\\s*\\(";
      const COMMON_CPP_HINTS = [
        "asin",
        "atan2",
        "atan",
        "calloc",
        "ceil",
        "cosh",
        "cos",
        "exit",
        "exp",
        "fabs",
        "floor",
        "fmod",
        "fprintf",
        "fputs",
        "free",
        "frexp",
        "auto_ptr",
        "deque",
        "list",
        "queue",
        "stack",
        "vector",
        "map",
        "set",
        "pair",
        "bitset",
        "multiset",
        "multimap",
        "unordered_set",
        "fscanf",
        "future",
        "isalnum",
        "isalpha",
        "iscntrl",
        "isdigit",
        "isgraph",
        "islower",
        "isprint",
        "ispunct",
        "isspace",
        "isupper",
        "isxdigit",
        "tolower",
        "toupper",
        "labs",
        "ldexp",
        "log10",
        "log",
        "malloc",
        "realloc",
        "memchr",
        "memcmp",
        "memcpy",
        "memset",
        "modf",
        "pow",
        "printf",
        "putchar",
        "puts",
        "scanf",
        "sinh",
        "sin",
        "snprintf",
        "sprintf",
        "sqrt",
        "sscanf",
        "strcat",
        "strchr",
        "strcmp",
        "strcpy",
        "strcspn",
        "strlen",
        "strncat",
        "strncmp",
        "strncpy",
        "strpbrk",
        "strrchr",
        "strspn",
        "strstr",
        "tanh",
        "tan",
        "unordered_map",
        "unordered_multiset",
        "unordered_multimap",
        "priority_queue",
        "make_pair",
        "array",
        "shared_ptr",
        "abort",
        "terminate",
        "abs",
        "acos",
        "vfprintf",
        "vprintf",
        "vsprintf",
        "endl",
        "initializer_list",
        "unique_ptr",
        "complex",
        "imaginary",
        "std",
        "string",
        "wstring",
        "cin",
        "cout",
        "cerr",
        "clog",
        "stdin",
        "stdout",
        "stderr",
        "stringstream",
        "istringstream",
        "ostringstream"
      ];
      const CPP_KEYWORDS = {
        keyword: "int float while private char char8_t char16_t char32_t catch import module export virtual operator sizeof dynamic_cast|10 typedef const_cast|10 const for static_cast|10 union namespace unsigned long volatile static protected bool template mutable if public friend do goto auto void enum else break extern using asm case typeid wchar_t short reinterpret_cast|10 default double register explicit signed typename try this switch continue inline delete alignas alignof constexpr consteval constinit decltype concept co_await co_return co_yield requires noexcept static_assert thread_local restrict final override atomic_bool atomic_char atomic_schar atomic_uchar atomic_short atomic_ushort atomic_int atomic_uint atomic_long atomic_ulong atomic_llong atomic_ullong new throw return and and_eq bitand bitor compl not not_eq or or_eq xor xor_eq",
        built_in: "_Bool _Complex _Imaginary",
        _relevance_hints: COMMON_CPP_HINTS,
        literal: "true false nullptr NULL"
      };
      const FUNCTION_DISPATCH = {
        className: "function.dispatch",
        relevance: 0,
        keywords: CPP_KEYWORDS,
        begin: concat(
          /\b/,
          /(?!decltype)/,
          /(?!if)/,
          /(?!for)/,
          /(?!while)/,
          hljs5.IDENT_RE,
          lookahead(/\s*\(/)
        )
      };
      const EXPRESSION_CONTAINS = [
        FUNCTION_DISPATCH,
        PREPROCESSOR,
        CPP_PRIMITIVE_TYPES,
        C_LINE_COMMENT_MODE,
        hljs5.C_BLOCK_COMMENT_MODE,
        NUMBERS,
        STRINGS
      ];
      const EXPRESSION_CONTEXT = {
        // This mode covers expression context where we can't expect a function
        // definition and shouldn't highlight anything that looks like one:
        // `return some()`, `else if()`, `(x*sum(1, 2))`
        variants: [
          {
            begin: /=/,
            end: /;/
          },
          {
            begin: /\(/,
            end: /\)/
          },
          {
            beginKeywords: "new throw return else",
            end: /;/
          }
        ],
        keywords: CPP_KEYWORDS,
        contains: EXPRESSION_CONTAINS.concat([
          {
            begin: /\(/,
            end: /\)/,
            keywords: CPP_KEYWORDS,
            contains: EXPRESSION_CONTAINS.concat(["self"]),
            relevance: 0
          }
        ]),
        relevance: 0
      };
      const FUNCTION_DECLARATION = {
        className: "function",
        begin: "(" + FUNCTION_TYPE_RE + "[\\*&\\s]+)+" + FUNCTION_TITLE,
        returnBegin: true,
        end: /[{;=]/,
        excludeEnd: true,
        keywords: CPP_KEYWORDS,
        illegal: /[^\w\s\*&:<>.]/,
        contains: [
          {
            // to prevent it from being confused as the function title
            begin: DECLTYPE_AUTO_RE,
            keywords: CPP_KEYWORDS,
            relevance: 0
          },
          {
            begin: FUNCTION_TITLE,
            returnBegin: true,
            contains: [TITLE_MODE],
            relevance: 0
          },
          // needed because we do not have look-behind on the below rule
          // to prevent it from grabbing the final : in a :: pair
          {
            begin: /::/,
            relevance: 0
          },
          // initializers
          {
            begin: /:/,
            endsWithParent: true,
            contains: [
              STRINGS,
              NUMBERS
            ]
          },
          {
            className: "params",
            begin: /\(/,
            end: /\)/,
            keywords: CPP_KEYWORDS,
            relevance: 0,
            contains: [
              C_LINE_COMMENT_MODE,
              hljs5.C_BLOCK_COMMENT_MODE,
              STRINGS,
              NUMBERS,
              CPP_PRIMITIVE_TYPES,
              // Count matching parentheses.
              {
                begin: /\(/,
                end: /\)/,
                keywords: CPP_KEYWORDS,
                relevance: 0,
                contains: [
                  "self",
                  C_LINE_COMMENT_MODE,
                  hljs5.C_BLOCK_COMMENT_MODE,
                  STRINGS,
                  NUMBERS,
                  CPP_PRIMITIVE_TYPES
                ]
              }
            ]
          },
          CPP_PRIMITIVE_TYPES,
          C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          PREPROCESSOR
        ]
      };
      return {
        name: "C++",
        aliases: [
          "cc",
          "c++",
          "h++",
          "hpp",
          "hh",
          "hxx",
          "cxx"
        ],
        keywords: CPP_KEYWORDS,
        illegal: "</",
        classNameAliases: {
          "function.dispatch": "built_in"
        },
        contains: [].concat(
          EXPRESSION_CONTEXT,
          FUNCTION_DECLARATION,
          FUNCTION_DISPATCH,
          EXPRESSION_CONTAINS,
          [
            PREPROCESSOR,
            {
              // containers: ie, `vector <int> rooms (9);`
              begin: "\\b(deque|list|queue|priority_queue|pair|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array)\\s*<",
              end: ">",
              keywords: CPP_KEYWORDS,
              contains: [
                "self",
                CPP_PRIMITIVE_TYPES
              ]
            },
            {
              begin: hljs5.IDENT_RE + "::",
              keywords: CPP_KEYWORDS
            },
            {
              className: "class",
              beginKeywords: "enum class struct union",
              end: /[{;:<>=]/,
              contains: [
                {
                  beginKeywords: "final class struct"
                },
                hljs5.TITLE_MODE
              ]
            }
          ]
        ),
        exports: {
          preprocessor: PREPROCESSOR,
          strings: STRINGS,
          keywords: CPP_KEYWORDS
        }
      };
    }
    function cLike(hljs5) {
      const lang = cPlusPlus(hljs5);
      const C_ALIASES = [
        "c",
        "h"
      ];
      const CPP_ALIASES = [
        "cc",
        "c++",
        "h++",
        "hpp",
        "hh",
        "hxx",
        "cxx"
      ];
      lang.disableAutodetect = true;
      lang.aliases = [];
      if (!hljs5.getLanguage("c")) lang.aliases.push(...C_ALIASES);
      if (!hljs5.getLanguage("cpp")) lang.aliases.push(...CPP_ALIASES);
      return lang;
    }
    module.exports = cLike;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/c.js
var require_c2 = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/c.js"(exports, module) {
    init_process_shim();
    function source(re2) {
      if (!re2) return null;
      if (typeof re2 === "string") return re2;
      return re2.source;
    }
    function optional(re2) {
      return concat("(", re2, ")?");
    }
    function concat(...args) {
      const joined = args.map((x2) => source(x2)).join("");
      return joined;
    }
    function c6(hljs5) {
      const C_LINE_COMMENT_MODE = hljs5.COMMENT("//", "$", {
        contains: [
          {
            begin: /\\\n/
          }
        ]
      });
      const DECLTYPE_AUTO_RE = "decltype\\(auto\\)";
      const NAMESPACE_RE = "[a-zA-Z_]\\w*::";
      const TEMPLATE_ARGUMENT_RE = "<[^<>]+>";
      const FUNCTION_TYPE_RE = "(" + DECLTYPE_AUTO_RE + "|" + optional(NAMESPACE_RE) + "[a-zA-Z_]\\w*" + optional(TEMPLATE_ARGUMENT_RE) + ")";
      const CPP_PRIMITIVE_TYPES = {
        className: "keyword",
        begin: "\\b[a-z\\d_]*_t\\b"
      };
      const CHARACTER_ESCAPES = "\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)";
      const STRINGS = {
        className: "string",
        variants: [
          {
            begin: '(u8?|U|L)?"',
            end: '"',
            illegal: "\\n",
            contains: [hljs5.BACKSLASH_ESCAPE]
          },
          {
            begin: "(u8?|U|L)?'(" + CHARACTER_ESCAPES + "|.)",
            end: "'",
            illegal: "."
          },
          hljs5.END_SAME_AS_BEGIN({
            begin: /(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/,
            end: /\)([^()\\ ]{0,16})"/
          })
        ]
      };
      const NUMBERS = {
        className: "number",
        variants: [
          {
            begin: "\\b(0b[01']+)"
          },
          {
            begin: "(-?)\\b([\\d']+(\\.[\\d']*)?|\\.[\\d']+)((ll|LL|l|L)(u|U)?|(u|U)(ll|LL|l|L)?|f|F|b|B)"
          },
          {
            begin: "(-?)(\\b0[xX][a-fA-F0-9']+|(\\b[\\d']+(\\.[\\d']*)?|\\.[\\d']+)([eE][-+]?[\\d']+)?)"
          }
        ],
        relevance: 0
      };
      const PREPROCESSOR = {
        className: "meta",
        begin: /#\s*[a-z]+\b/,
        end: /$/,
        keywords: {
          "meta-keyword": "if else elif endif define undef warning error line pragma _Pragma ifdef ifndef include"
        },
        contains: [
          {
            begin: /\\\n/,
            relevance: 0
          },
          hljs5.inherit(STRINGS, {
            className: "meta-string"
          }),
          {
            className: "meta-string",
            begin: /<.*?>/
          },
          C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE
        ]
      };
      const TITLE_MODE = {
        className: "title",
        begin: optional(NAMESPACE_RE) + hljs5.IDENT_RE,
        relevance: 0
      };
      const FUNCTION_TITLE = optional(NAMESPACE_RE) + hljs5.IDENT_RE + "\\s*\\(";
      const CPP_KEYWORDS = {
        keyword: "int float while private char char8_t char16_t char32_t catch import module export virtual operator sizeof dynamic_cast|10 typedef const_cast|10 const for static_cast|10 union namespace unsigned long volatile static protected bool template mutable if public friend do goto auto void enum else break extern using asm case typeid wchar_t short reinterpret_cast|10 default double register explicit signed typename try this switch continue inline delete alignas alignof constexpr consteval constinit decltype concept co_await co_return co_yield requires noexcept static_assert thread_local restrict final override atomic_bool atomic_char atomic_schar atomic_uchar atomic_short atomic_ushort atomic_int atomic_uint atomic_long atomic_ulong atomic_llong atomic_ullong new throw return and and_eq bitand bitor compl not not_eq or or_eq xor xor_eq",
        built_in: "std string wstring cin cout cerr clog stdin stdout stderr stringstream istringstream ostringstream auto_ptr deque list queue stack vector map set pair bitset multiset multimap unordered_set unordered_map unordered_multiset unordered_multimap priority_queue make_pair array shared_ptr abort terminate abs acos asin atan2 atan calloc ceil cosh cos exit exp fabs floor fmod fprintf fputs free frexp fscanf future isalnum isalpha iscntrl isdigit isgraph islower isprint ispunct isspace isupper isxdigit tolower toupper labs ldexp log10 log malloc realloc memchr memcmp memcpy memset modf pow printf putchar puts scanf sinh sin snprintf sprintf sqrt sscanf strcat strchr strcmp strcpy strcspn strlen strncat strncmp strncpy strpbrk strrchr strspn strstr tanh tan vfprintf vprintf vsprintf endl initializer_list unique_ptr _Bool complex _Complex imaginary _Imaginary",
        literal: "true false nullptr NULL"
      };
      const EXPRESSION_CONTAINS = [
        PREPROCESSOR,
        CPP_PRIMITIVE_TYPES,
        C_LINE_COMMENT_MODE,
        hljs5.C_BLOCK_COMMENT_MODE,
        NUMBERS,
        STRINGS
      ];
      const EXPRESSION_CONTEXT = {
        // This mode covers expression context where we can't expect a function
        // definition and shouldn't highlight anything that looks like one:
        // `return some()`, `else if()`, `(x*sum(1, 2))`
        variants: [
          {
            begin: /=/,
            end: /;/
          },
          {
            begin: /\(/,
            end: /\)/
          },
          {
            beginKeywords: "new throw return else",
            end: /;/
          }
        ],
        keywords: CPP_KEYWORDS,
        contains: EXPRESSION_CONTAINS.concat([
          {
            begin: /\(/,
            end: /\)/,
            keywords: CPP_KEYWORDS,
            contains: EXPRESSION_CONTAINS.concat(["self"]),
            relevance: 0
          }
        ]),
        relevance: 0
      };
      const FUNCTION_DECLARATION = {
        className: "function",
        begin: "(" + FUNCTION_TYPE_RE + "[\\*&\\s]+)+" + FUNCTION_TITLE,
        returnBegin: true,
        end: /[{;=]/,
        excludeEnd: true,
        keywords: CPP_KEYWORDS,
        illegal: /[^\w\s\*&:<>.]/,
        contains: [
          {
            // to prevent it from being confused as the function title
            begin: DECLTYPE_AUTO_RE,
            keywords: CPP_KEYWORDS,
            relevance: 0
          },
          {
            begin: FUNCTION_TITLE,
            returnBegin: true,
            contains: [TITLE_MODE],
            relevance: 0
          },
          {
            className: "params",
            begin: /\(/,
            end: /\)/,
            keywords: CPP_KEYWORDS,
            relevance: 0,
            contains: [
              C_LINE_COMMENT_MODE,
              hljs5.C_BLOCK_COMMENT_MODE,
              STRINGS,
              NUMBERS,
              CPP_PRIMITIVE_TYPES,
              // Count matching parentheses.
              {
                begin: /\(/,
                end: /\)/,
                keywords: CPP_KEYWORDS,
                relevance: 0,
                contains: [
                  "self",
                  C_LINE_COMMENT_MODE,
                  hljs5.C_BLOCK_COMMENT_MODE,
                  STRINGS,
                  NUMBERS,
                  CPP_PRIMITIVE_TYPES
                ]
              }
            ]
          },
          CPP_PRIMITIVE_TYPES,
          C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          PREPROCESSOR
        ]
      };
      return {
        name: "C",
        aliases: [
          "h"
        ],
        keywords: CPP_KEYWORDS,
        // Until differentiations are added between `c` and `cpp`, `c` will
        // not be auto-detected to avoid auto-detect conflicts between C and C++
        disableAutodetect: true,
        illegal: "</",
        contains: [].concat(
          EXPRESSION_CONTEXT,
          FUNCTION_DECLARATION,
          EXPRESSION_CONTAINS,
          [
            PREPROCESSOR,
            {
              // containers: ie, `vector <int> rooms (9);`
              begin: "\\b(deque|list|queue|priority_queue|pair|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array)\\s*<",
              end: ">",
              keywords: CPP_KEYWORDS,
              contains: [
                "self",
                CPP_PRIMITIVE_TYPES
              ]
            },
            {
              begin: hljs5.IDENT_RE + "::",
              keywords: CPP_KEYWORDS
            },
            {
              className: "class",
              beginKeywords: "enum class struct union",
              end: /[{;:<>=]/,
              contains: [
                {
                  beginKeywords: "final class struct"
                },
                hljs5.TITLE_MODE
              ]
            }
          ]
        ),
        exports: {
          preprocessor: PREPROCESSOR,
          strings: STRINGS,
          keywords: CPP_KEYWORDS
        }
      };
    }
    module.exports = c6;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/cal.js
var require_cal = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/cal.js"(exports, module) {
    init_process_shim();
    function cal(hljs5) {
      const KEYWORDS3 = "div mod in and or not xor asserterror begin case do downto else end exit for if of repeat then to until while with var";
      const LITERALS3 = "false true";
      const COMMENT_MODES = [
        hljs5.C_LINE_COMMENT_MODE,
        hljs5.COMMENT(
          /\{/,
          /\}/,
          {
            relevance: 0
          }
        ),
        hljs5.COMMENT(
          /\(\*/,
          /\*\)/,
          {
            relevance: 10
          }
        )
      ];
      const STRING = {
        className: "string",
        begin: /'/,
        end: /'/,
        contains: [{
          begin: /''/
        }]
      };
      const CHAR_STRING = {
        className: "string",
        begin: /(#\d+)+/
      };
      const DATE = {
        className: "number",
        begin: "\\b\\d+(\\.\\d+)?(DT|D|T)",
        relevance: 0
      };
      const DBL_QUOTED_VARIABLE = {
        className: "string",
        // not a string technically but makes sense to be highlighted in the same style
        begin: '"',
        end: '"'
      };
      const PROCEDURE = {
        className: "function",
        beginKeywords: "procedure",
        end: /[:;]/,
        keywords: "procedure|10",
        contains: [
          hljs5.TITLE_MODE,
          {
            className: "params",
            begin: /\(/,
            end: /\)/,
            keywords: KEYWORDS3,
            contains: [
              STRING,
              CHAR_STRING
            ]
          }
        ].concat(COMMENT_MODES)
      };
      const OBJECT = {
        className: "class",
        begin: "OBJECT (Table|Form|Report|Dataport|Codeunit|XMLport|MenuSuite|Page|Query) (\\d+) ([^\\r\\n]+)",
        returnBegin: true,
        contains: [
          hljs5.TITLE_MODE,
          PROCEDURE
        ]
      };
      return {
        name: "C/AL",
        case_insensitive: true,
        keywords: {
          keyword: KEYWORDS3,
          literal: LITERALS3
        },
        illegal: /\/\*/,
        contains: [
          STRING,
          CHAR_STRING,
          DATE,
          DBL_QUOTED_VARIABLE,
          hljs5.NUMBER_MODE,
          OBJECT,
          PROCEDURE
        ]
      };
    }
    module.exports = cal;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/capnproto.js
var require_capnproto = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/capnproto.js"(exports, module) {
    init_process_shim();
    function capnproto(hljs5) {
      return {
        name: "Cap\u2019n Proto",
        aliases: ["capnp"],
        keywords: {
          keyword: "struct enum interface union group import using const annotation extends in of on as with from fixed",
          built_in: "Void Bool Int8 Int16 Int32 Int64 UInt8 UInt16 UInt32 UInt64 Float32 Float64 Text Data AnyPointer AnyStruct Capability List",
          literal: "true false"
        },
        contains: [
          hljs5.QUOTE_STRING_MODE,
          hljs5.NUMBER_MODE,
          hljs5.HASH_COMMENT_MODE,
          {
            className: "meta",
            begin: /@0x[\w\d]{16};/,
            illegal: /\n/
          },
          {
            className: "symbol",
            begin: /@\d+\b/
          },
          {
            className: "class",
            beginKeywords: "struct enum",
            end: /\{/,
            illegal: /\n/,
            contains: [hljs5.inherit(hljs5.TITLE_MODE, {
              starts: {
                endsWithParent: true,
                excludeEnd: true
              }
              // hack: eating everything after the first title
            })]
          },
          {
            className: "class",
            beginKeywords: "interface",
            end: /\{/,
            illegal: /\n/,
            contains: [hljs5.inherit(hljs5.TITLE_MODE, {
              starts: {
                endsWithParent: true,
                excludeEnd: true
              }
              // hack: eating everything after the first title
            })]
          }
        ]
      };
    }
    module.exports = capnproto;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/ceylon.js
var require_ceylon = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/ceylon.js"(exports, module) {
    init_process_shim();
    function ceylon(hljs5) {
      const KEYWORDS3 = "assembly module package import alias class interface object given value assign void function new of extends satisfies abstracts in out return break continue throw assert dynamic if else switch case for while try catch finally then let this outer super is exists nonempty";
      const DECLARATION_MODIFIERS = "shared abstract formal default actual variable late native deprecated final sealed annotation suppressWarnings small";
      const DOCUMENTATION = "doc by license see throws tagged";
      const SUBST = {
        className: "subst",
        excludeBegin: true,
        excludeEnd: true,
        begin: /``/,
        end: /``/,
        keywords: KEYWORDS3,
        relevance: 10
      };
      const EXPRESSIONS = [
        {
          // verbatim string
          className: "string",
          begin: '"""',
          end: '"""',
          relevance: 10
        },
        {
          // string literal or template
          className: "string",
          begin: '"',
          end: '"',
          contains: [SUBST]
        },
        {
          // character literal
          className: "string",
          begin: "'",
          end: "'"
        },
        {
          // numeric literal
          className: "number",
          begin: "#[0-9a-fA-F_]+|\\$[01_]+|[0-9_]+(?:\\.[0-9_](?:[eE][+-]?\\d+)?)?[kMGTPmunpf]?",
          relevance: 0
        }
      ];
      SUBST.contains = EXPRESSIONS;
      return {
        name: "Ceylon",
        keywords: {
          keyword: KEYWORDS3 + " " + DECLARATION_MODIFIERS,
          meta: DOCUMENTATION
        },
        illegal: "\\$[^01]|#[^0-9a-fA-F]",
        contains: [
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.COMMENT("/\\*", "\\*/", {
            contains: ["self"]
          }),
          {
            // compiler annotation
            className: "meta",
            begin: '@[a-z]\\w*(?::"[^"]*")?'
          }
        ].concat(EXPRESSIONS)
      };
    }
    module.exports = ceylon;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/clean.js
var require_clean = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/clean.js"(exports, module) {
    init_process_shim();
    function clean(hljs5) {
      return {
        name: "Clean",
        aliases: [
          "icl",
          "dcl"
        ],
        keywords: {
          keyword: "if let in with where case of class instance otherwise implementation definition system module from import qualified as special code inline foreign export ccall stdcall generic derive infix infixl infixr",
          built_in: "Int Real Char Bool",
          literal: "True False"
        },
        contains: [
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          hljs5.APOS_STRING_MODE,
          hljs5.QUOTE_STRING_MODE,
          hljs5.C_NUMBER_MODE,
          {
            // relevance booster
            begin: "->|<-[|:]?|#!?|>>=|\\{\\||\\|\\}|:==|=:|<>"
          }
        ]
      };
    }
    module.exports = clean;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/clojure.js
var require_clojure = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/clojure.js"(exports, module) {
    init_process_shim();
    function clojure(hljs5) {
      const SYMBOLSTART = "a-zA-Z_\\-!.?+*=<>&#'";
      const SYMBOL_RE = "[" + SYMBOLSTART + "][" + SYMBOLSTART + "0-9/;:]*";
      const globals = "def defonce defprotocol defstruct defmulti defmethod defn- defn defmacro deftype defrecord";
      const keywords = {
        $pattern: SYMBOL_RE,
        "builtin-name": (
          // Clojure keywords
          globals + " cond apply if-not if-let if not not= =|0 <|0 >|0 <=|0 >=|0 ==|0 +|0 /|0 *|0 -|0 rem quot neg? pos? delay? symbol? keyword? true? false? integer? empty? coll? list? set? ifn? fn? associative? sequential? sorted? counted? reversible? number? decimal? class? distinct? isa? float? rational? reduced? ratio? odd? even? char? seq? vector? string? map? nil? contains? zero? instance? not-every? not-any? libspec? -> ->> .. . inc compare do dotimes mapcat take remove take-while drop letfn drop-last take-last drop-while while intern condp case reduced cycle split-at split-with repeat replicate iterate range merge zipmap declare line-seq sort comparator sort-by dorun doall nthnext nthrest partition eval doseq await await-for let agent atom send send-off release-pending-sends add-watch mapv filterv remove-watch agent-error restart-agent set-error-handler error-handler set-error-mode! error-mode shutdown-agents quote var fn loop recur throw try monitor-enter monitor-exit macroexpand macroexpand-1 for dosync and or when when-not when-let comp juxt partial sequence memoize constantly complement identity assert peek pop doto proxy first rest cons cast coll last butlast sigs reify second ffirst fnext nfirst nnext meta with-meta ns in-ns create-ns import refer keys select-keys vals key val rseq name namespace promise into transient persistent! conj! assoc! dissoc! pop! disj! use class type num float double short byte boolean bigint biginteger bigdec print-method print-dup throw-if printf format load compile get-in update-in pr pr-on newline flush read slurp read-line subvec with-open memfn time re-find re-groups rand-int rand mod locking assert-valid-fdecl alias resolve ref deref refset swap! reset! set-validator! compare-and-set! alter-meta! reset-meta! commute get-validator alter ref-set ref-history-count ref-min-history ref-max-history ensure sync io! new next conj set! to-array future future-call into-array aset gen-class reduce map filter find empty hash-map hash-set sorted-map sorted-map-by sorted-set sorted-set-by vec vector seq flatten reverse assoc dissoc list disj get union difference intersection extend extend-type extend-protocol int nth delay count concat chunk chunk-buffer chunk-append chunk-first chunk-rest max min dec unchecked-inc-int unchecked-inc unchecked-dec-inc unchecked-dec unchecked-negate unchecked-add-int unchecked-add unchecked-subtract-int unchecked-subtract chunk-next chunk-cons chunked-seq? prn vary-meta lazy-seq spread list* str find-keyword keyword symbol gensym force rationalize"
        )
      };
      const SIMPLE_NUMBER_RE = "[-+]?\\d+(\\.\\d+)?";
      const SYMBOL = {
        begin: SYMBOL_RE,
        relevance: 0
      };
      const NUMBER = {
        className: "number",
        begin: SIMPLE_NUMBER_RE,
        relevance: 0
      };
      const STRING = hljs5.inherit(hljs5.QUOTE_STRING_MODE, {
        illegal: null
      });
      const COMMENT = hljs5.COMMENT(
        ";",
        "$",
        {
          relevance: 0
        }
      );
      const LITERAL = {
        className: "literal",
        begin: /\b(true|false|nil)\b/
      };
      const COLLECTION2 = {
        begin: "[\\[\\{]",
        end: "[\\]\\}]"
      };
      const HINT = {
        className: "comment",
        begin: "\\^" + SYMBOL_RE
      };
      const HINT_COL = hljs5.COMMENT("\\^\\{", "\\}");
      const KEY = {
        className: "symbol",
        begin: "[:]{1,2}" + SYMBOL_RE
      };
      const LIST = {
        begin: "\\(",
        end: "\\)"
      };
      const BODY = {
        endsWithParent: true,
        relevance: 0
      };
      const NAME = {
        keywords,
        className: "name",
        begin: SYMBOL_RE,
        relevance: 0,
        starts: BODY
      };
      const DEFAULT_CONTAINS = [
        LIST,
        STRING,
        HINT,
        HINT_COL,
        COMMENT,
        KEY,
        COLLECTION2,
        NUMBER,
        LITERAL,
        SYMBOL
      ];
      const GLOBAL = {
        beginKeywords: globals,
        lexemes: SYMBOL_RE,
        end: '(\\[|#|\\d|"|:|\\{|\\)|\\(|$)',
        contains: [
          {
            className: "title",
            begin: SYMBOL_RE,
            relevance: 0,
            excludeEnd: true,
            // we can only have a single title
            endsParent: true
          }
        ].concat(DEFAULT_CONTAINS)
      };
      LIST.contains = [
        hljs5.COMMENT("comment", ""),
        GLOBAL,
        NAME,
        BODY
      ];
      BODY.contains = DEFAULT_CONTAINS;
      COLLECTION2.contains = DEFAULT_CONTAINS;
      HINT_COL.contains = [COLLECTION2];
      return {
        name: "Clojure",
        aliases: ["clj"],
        illegal: /\S/,
        contains: [
          LIST,
          STRING,
          HINT,
          HINT_COL,
          COMMENT,
          KEY,
          COLLECTION2,
          NUMBER,
          LITERAL
        ]
      };
    }
    module.exports = clojure;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/clojure-repl.js
var require_clojure_repl = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/clojure-repl.js"(exports, module) {
    init_process_shim();
    function clojureRepl(hljs5) {
      return {
        name: "Clojure REPL",
        contains: [
          {
            className: "meta",
            begin: /^([\w.-]+|\s*#_)?=>/,
            starts: {
              end: /$/,
              subLanguage: "clojure"
            }
          }
        ]
      };
    }
    module.exports = clojureRepl;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/cmake.js
var require_cmake = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/cmake.js"(exports, module) {
    init_process_shim();
    function cmake(hljs5) {
      return {
        name: "CMake",
        aliases: ["cmake.in"],
        case_insensitive: true,
        keywords: {
          keyword: (
            // scripting commands
            "break cmake_host_system_information cmake_minimum_required cmake_parse_arguments cmake_policy configure_file continue elseif else endforeach endfunction endif endmacro endwhile execute_process file find_file find_library find_package find_path find_program foreach function get_cmake_property get_directory_property get_filename_component get_property if include include_guard list macro mark_as_advanced math message option return separate_arguments set_directory_properties set_property set site_name string unset variable_watch while add_compile_definitions add_compile_options add_custom_command add_custom_target add_definitions add_dependencies add_executable add_library add_link_options add_subdirectory add_test aux_source_directory build_command create_test_sourcelist define_property enable_language enable_testing export fltk_wrap_ui get_source_file_property get_target_property get_test_property include_directories include_external_msproject include_regular_expression install link_directories link_libraries load_cache project qt_wrap_cpp qt_wrap_ui remove_definitions set_source_files_properties set_target_properties set_tests_properties source_group target_compile_definitions target_compile_features target_compile_options target_include_directories target_link_directories target_link_libraries target_link_options target_sources try_compile try_run ctest_build ctest_configure ctest_coverage ctest_empty_binary_directory ctest_memcheck ctest_read_custom_files ctest_run_script ctest_sleep ctest_start ctest_submit ctest_test ctest_update ctest_upload build_name exec_program export_library_dependencies install_files install_programs install_targets load_command make_directory output_required_files remove subdir_depends subdirs use_mangled_mesa utility_source variable_requires write_file qt5_use_modules qt5_use_package qt5_wrap_cpp on off true false and or not command policy target test exists is_newer_than is_directory is_symlink is_absolute matches less greater equal less_equal greater_equal strless strgreater strequal strless_equal strgreater_equal version_less version_greater version_equal version_less_equal version_greater_equal in_list defined"
          )
        },
        contains: [
          {
            className: "variable",
            begin: /\$\{/,
            end: /\}/
          },
          hljs5.HASH_COMMENT_MODE,
          hljs5.QUOTE_STRING_MODE,
          hljs5.NUMBER_MODE
        ]
      };
    }
    module.exports = cmake;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/coffeescript.js
var require_coffeescript = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/coffeescript.js"(exports, module) {
    init_process_shim();
    var KEYWORDS3 = [
      "as",
      // for exports
      "in",
      "of",
      "if",
      "for",
      "while",
      "finally",
      "var",
      "new",
      "function",
      "do",
      "return",
      "void",
      "else",
      "break",
      "catch",
      "instanceof",
      "with",
      "throw",
      "case",
      "default",
      "try",
      "switch",
      "continue",
      "typeof",
      "delete",
      "let",
      "yield",
      "const",
      "class",
      // JS handles these with a special rule
      // "get",
      // "set",
      "debugger",
      "async",
      "await",
      "static",
      "import",
      "from",
      "export",
      "extends"
    ];
    var LITERALS3 = [
      "true",
      "false",
      "null",
      "undefined",
      "NaN",
      "Infinity"
    ];
    var TYPES3 = [
      "Intl",
      "DataView",
      "Number",
      "Math",
      "Date",
      "String",
      "RegExp",
      "Object",
      "Function",
      "Boolean",
      "Error",
      "Symbol",
      "Set",
      "Map",
      "WeakSet",
      "WeakMap",
      "Proxy",
      "Reflect",
      "JSON",
      "Promise",
      "Float64Array",
      "Int16Array",
      "Int32Array",
      "Int8Array",
      "Uint16Array",
      "Uint32Array",
      "Float32Array",
      "Array",
      "Uint8Array",
      "Uint8ClampedArray",
      "ArrayBuffer",
      "BigInt64Array",
      "BigUint64Array",
      "BigInt"
    ];
    var ERROR_TYPES3 = [
      "EvalError",
      "InternalError",
      "RangeError",
      "ReferenceError",
      "SyntaxError",
      "TypeError",
      "URIError"
    ];
    var BUILT_IN_GLOBALS3 = [
      "setInterval",
      "setTimeout",
      "clearInterval",
      "clearTimeout",
      "require",
      "exports",
      "eval",
      "isFinite",
      "isNaN",
      "parseFloat",
      "parseInt",
      "decodeURI",
      "decodeURIComponent",
      "encodeURI",
      "encodeURIComponent",
      "escape",
      "unescape"
    ];
    var BUILT_IN_VARIABLES3 = [
      "arguments",
      "this",
      "super",
      "console",
      "window",
      "document",
      "localStorage",
      "module",
      "global"
      // Node.js
    ];
    var BUILT_INS3 = [].concat(
      BUILT_IN_GLOBALS3,
      BUILT_IN_VARIABLES3,
      TYPES3,
      ERROR_TYPES3
    );
    function coffeescript(hljs5) {
      const COFFEE_BUILT_INS = [
        "npm",
        "print"
      ];
      const COFFEE_LITERALS = [
        "yes",
        "no",
        "on",
        "off"
      ];
      const COFFEE_KEYWORDS = [
        "then",
        "unless",
        "until",
        "loop",
        "by",
        "when",
        "and",
        "or",
        "is",
        "isnt",
        "not"
      ];
      const NOT_VALID_KEYWORDS = [
        "var",
        "const",
        "let",
        "function",
        "static"
      ];
      const excluding = (list) => (kw) => !list.includes(kw);
      const KEYWORDS$1 = {
        keyword: KEYWORDS3.concat(COFFEE_KEYWORDS).filter(excluding(NOT_VALID_KEYWORDS)),
        literal: LITERALS3.concat(COFFEE_LITERALS),
        built_in: BUILT_INS3.concat(COFFEE_BUILT_INS)
      };
      const JS_IDENT_RE = "[A-Za-z$_][0-9A-Za-z$_]*";
      const SUBST = {
        className: "subst",
        begin: /#\{/,
        end: /\}/,
        keywords: KEYWORDS$1
      };
      const EXPRESSIONS = [
        hljs5.BINARY_NUMBER_MODE,
        hljs5.inherit(hljs5.C_NUMBER_MODE, {
          starts: {
            end: "(\\s*/)?",
            relevance: 0
          }
        }),
        // a number tries to eat the following slash to prevent treating it as a regexp
        {
          className: "string",
          variants: [
            {
              begin: /'''/,
              end: /'''/,
              contains: [hljs5.BACKSLASH_ESCAPE]
            },
            {
              begin: /'/,
              end: /'/,
              contains: [hljs5.BACKSLASH_ESCAPE]
            },
            {
              begin: /"""/,
              end: /"""/,
              contains: [
                hljs5.BACKSLASH_ESCAPE,
                SUBST
              ]
            },
            {
              begin: /"/,
              end: /"/,
              contains: [
                hljs5.BACKSLASH_ESCAPE,
                SUBST
              ]
            }
          ]
        },
        {
          className: "regexp",
          variants: [
            {
              begin: "///",
              end: "///",
              contains: [
                SUBST,
                hljs5.HASH_COMMENT_MODE
              ]
            },
            {
              begin: "//[gim]{0,3}(?=\\W)",
              relevance: 0
            },
            {
              // regex can't start with space to parse x / 2 / 3 as two divisions
              // regex can't start with *, and it supports an "illegal" in the main mode
              begin: /\/(?![ *]).*?(?![\\]).\/[gim]{0,3}(?=\W)/
            }
          ]
        },
        {
          begin: "@" + JS_IDENT_RE
          // relevance booster
        },
        {
          subLanguage: "javascript",
          excludeBegin: true,
          excludeEnd: true,
          variants: [
            {
              begin: "```",
              end: "```"
            },
            {
              begin: "`",
              end: "`"
            }
          ]
        }
      ];
      SUBST.contains = EXPRESSIONS;
      const TITLE = hljs5.inherit(hljs5.TITLE_MODE, {
        begin: JS_IDENT_RE
      });
      const POSSIBLE_PARAMS_RE = "(\\(.*\\)\\s*)?\\B[-=]>";
      const PARAMS = {
        className: "params",
        begin: "\\([^\\(]",
        returnBegin: true,
        /* We need another contained nameless mode to not have every nested
        pair of parens to be called "params" */
        contains: [{
          begin: /\(/,
          end: /\)/,
          keywords: KEYWORDS$1,
          contains: ["self"].concat(EXPRESSIONS)
        }]
      };
      return {
        name: "CoffeeScript",
        aliases: [
          "coffee",
          "cson",
          "iced"
        ],
        keywords: KEYWORDS$1,
        illegal: /\/\*/,
        contains: EXPRESSIONS.concat([
          hljs5.COMMENT("###", "###"),
          hljs5.HASH_COMMENT_MODE,
          {
            className: "function",
            begin: "^\\s*" + JS_IDENT_RE + "\\s*=\\s*" + POSSIBLE_PARAMS_RE,
            end: "[-=]>",
            returnBegin: true,
            contains: [
              TITLE,
              PARAMS
            ]
          },
          {
            // anonymous function start
            begin: /[:\(,=]\s*/,
            relevance: 0,
            contains: [{
              className: "function",
              begin: POSSIBLE_PARAMS_RE,
              end: "[-=]>",
              returnBegin: true,
              contains: [PARAMS]
            }]
          },
          {
            className: "class",
            beginKeywords: "class",
            end: "$",
            illegal: /[:="\[\]]/,
            contains: [
              {
                beginKeywords: "extends",
                endsWithParent: true,
                illegal: /[:="\[\]]/,
                contains: [TITLE]
              },
              TITLE
            ]
          },
          {
            begin: JS_IDENT_RE + ":",
            end: ":",
            returnBegin: true,
            returnEnd: true,
            relevance: 0
          }
        ])
      };
    }
    module.exports = coffeescript;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/coq.js
var require_coq = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/coq.js"(exports, module) {
    init_process_shim();
    function coq(hljs5) {
      return {
        name: "Coq",
        keywords: {
          keyword: "_|0 as at cofix else end exists exists2 fix for forall fun if IF in let match mod Prop return Set then Type using where with Abort About Add Admit Admitted All Arguments Assumptions Axiom Back BackTo Backtrack Bind Blacklist Canonical Cd Check Class Classes Close Coercion Coercions CoFixpoint CoInductive Collection Combined Compute Conjecture Conjectures Constant constr Constraint Constructors Context Corollary CreateHintDb Cut Declare Defined Definition Delimit Dependencies Dependent Derive Drop eauto End Equality Eval Example Existential Existentials Existing Export exporting Extern Extract Extraction Fact Field Fields File Fixpoint Focus for From Function Functional Generalizable Global Goal Grab Grammar Graph Guarded Heap Hint HintDb Hints Hypotheses Hypothesis ident Identity If Immediate Implicit Import Include Inductive Infix Info Initial Inline Inspect Instance Instances Intro Intros Inversion Inversion_clear Language Left Lemma Let Libraries Library Load LoadPath Local Locate Ltac ML Mode Module Modules Monomorphic Morphism Next NoInline Notation Obligation Obligations Opaque Open Optimize Options Parameter Parameters Parametric Path Paths pattern Polymorphic Preterm Print Printing Program Projections Proof Proposition Pwd Qed Quit Rec Record Recursive Redirect Relation Remark Remove Require Reserved Reset Resolve Restart Rewrite Right Ring Rings Save Scheme Scope Scopes Script Search SearchAbout SearchHead SearchPattern SearchRewrite Section Separate Set Setoid Show Solve Sorted Step Strategies Strategy Structure SubClass Table Tables Tactic Term Test Theorem Time Timeout Transparent Type Typeclasses Types Undelimit Undo Unfocus Unfocused Unfold Universe Universes Unset Unshelve using Variable Variables Variant Verbose Visibility where with",
          built_in: "abstract absurd admit after apply as assert assumption at auto autorewrite autounfold before bottom btauto by case case_eq cbn cbv change classical_left classical_right clear clearbody cofix compare compute congruence constr_eq constructor contradict contradiction cut cutrewrite cycle decide decompose dependent destruct destruction dintuition discriminate discrR do double dtauto eapply eassumption eauto ecase econstructor edestruct ediscriminate eelim eexact eexists einduction einjection eleft elim elimtype enough equality erewrite eright esimplify_eq esplit evar exact exactly_once exfalso exists f_equal fail field field_simplify field_simplify_eq first firstorder fix fold fourier functional generalize generalizing gfail give_up has_evar hnf idtac in induction injection instantiate intro intro_pattern intros intuition inversion inversion_clear is_evar is_var lapply lazy left lia lra move native_compute nia nsatz omega once pattern pose progress proof psatz quote record red refine reflexivity remember rename repeat replace revert revgoals rewrite rewrite_strat right ring ring_simplify rtauto set setoid_reflexivity setoid_replace setoid_rewrite setoid_symmetry setoid_transitivity shelve shelve_unifiable simpl simple simplify_eq solve specialize split split_Rabs split_Rmult stepl stepr subst sum swap symmetry tactic tauto time timeout top transitivity trivial try tryif unfold unify until using vm_compute with"
        },
        contains: [
          hljs5.QUOTE_STRING_MODE,
          hljs5.COMMENT("\\(\\*", "\\*\\)"),
          hljs5.C_NUMBER_MODE,
          {
            className: "type",
            excludeBegin: true,
            begin: "\\|\\s*",
            end: "\\w+"
          },
          {
            // relevance booster
            begin: /[-=]>/
          }
        ]
      };
    }
    module.exports = coq;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/cos.js
var require_cos = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/cos.js"(exports, module) {
    init_process_shim();
    function cos(hljs5) {
      const STRINGS = {
        className: "string",
        variants: [{
          begin: '"',
          end: '"',
          contains: [{
            // escaped
            begin: '""',
            relevance: 0
          }]
        }]
      };
      const NUMBERS = {
        className: "number",
        begin: "\\b(\\d+(\\.\\d*)?|\\.\\d+)",
        relevance: 0
      };
      const COS_KEYWORDS = "property parameter class classmethod clientmethod extends as break catch close continue do d|0 else elseif for goto halt hang h|0 if job j|0 kill k|0 lock l|0 merge new open quit q|0 read r|0 return set s|0 tcommit throw trollback try tstart use view while write w|0 xecute x|0 zkill znspace zn ztrap zwrite zw zzdump zzwrite print zbreak zinsert zload zprint zremove zsave zzprint mv mvcall mvcrt mvdim mvprint zquit zsync ascii";
      return {
        name: "Cach\xE9 Object Script",
        case_insensitive: true,
        aliases: [
          "cls"
        ],
        keywords: COS_KEYWORDS,
        contains: [
          NUMBERS,
          STRINGS,
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          {
            className: "comment",
            begin: /;/,
            end: "$",
            relevance: 0
          },
          {
            // Functions and user-defined functions: write $ztime(60*60*3), $$myFunc(10), $$^Val(1)
            className: "built_in",
            begin: /(?:\$\$?|\.\.)\^?[a-zA-Z]+/
          },
          {
            // Macro command: quit $$$OK
            className: "built_in",
            begin: /\$\$\$[a-zA-Z]+/
          },
          {
            // Special (global) variables: write %request.Content; Built-in classes: %Library.Integer
            className: "built_in",
            begin: /%[a-z]+(?:\.[a-z]+)*/
          },
          {
            // Global variable: set ^globalName = 12 write ^globalName
            className: "symbol",
            begin: /\^%?[a-zA-Z][\w]*/
          },
          {
            // Some control constructions: do ##class(Package.ClassName).Method(), ##super()
            className: "keyword",
            begin: /##class|##super|#define|#dim/
          },
          // sub-languages: are not fully supported by hljs by 11/15/2015
          // left for the future implementation.
          {
            begin: /&sql\(/,
            end: /\)/,
            excludeBegin: true,
            excludeEnd: true,
            subLanguage: "sql"
          },
          {
            begin: /&(js|jscript|javascript)</,
            end: />/,
            excludeBegin: true,
            excludeEnd: true,
            subLanguage: "javascript"
          },
          {
            // this brakes first and last tag, but this is the only way to embed a valid html
            begin: /&html<\s*</,
            end: />\s*>/,
            subLanguage: "xml"
          }
        ]
      };
    }
    module.exports = cos;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/cpp.js
var require_cpp = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/cpp.js"(exports, module) {
    init_process_shim();
    function source(re2) {
      if (!re2) return null;
      if (typeof re2 === "string") return re2;
      return re2.source;
    }
    function lookahead(re2) {
      return concat("(?=", re2, ")");
    }
    function optional(re2) {
      return concat("(", re2, ")?");
    }
    function concat(...args) {
      const joined = args.map((x2) => source(x2)).join("");
      return joined;
    }
    function cpp(hljs5) {
      const C_LINE_COMMENT_MODE = hljs5.COMMENT("//", "$", {
        contains: [
          {
            begin: /\\\n/
          }
        ]
      });
      const DECLTYPE_AUTO_RE = "decltype\\(auto\\)";
      const NAMESPACE_RE = "[a-zA-Z_]\\w*::";
      const TEMPLATE_ARGUMENT_RE = "<[^<>]+>";
      const FUNCTION_TYPE_RE = "(" + DECLTYPE_AUTO_RE + "|" + optional(NAMESPACE_RE) + "[a-zA-Z_]\\w*" + optional(TEMPLATE_ARGUMENT_RE) + ")";
      const CPP_PRIMITIVE_TYPES = {
        className: "keyword",
        begin: "\\b[a-z\\d_]*_t\\b"
      };
      const CHARACTER_ESCAPES = "\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)";
      const STRINGS = {
        className: "string",
        variants: [
          {
            begin: '(u8?|U|L)?"',
            end: '"',
            illegal: "\\n",
            contains: [hljs5.BACKSLASH_ESCAPE]
          },
          {
            begin: "(u8?|U|L)?'(" + CHARACTER_ESCAPES + "|.)",
            end: "'",
            illegal: "."
          },
          hljs5.END_SAME_AS_BEGIN({
            begin: /(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/,
            end: /\)([^()\\ ]{0,16})"/
          })
        ]
      };
      const NUMBERS = {
        className: "number",
        variants: [
          {
            begin: "\\b(0b[01']+)"
          },
          {
            begin: "(-?)\\b([\\d']+(\\.[\\d']*)?|\\.[\\d']+)((ll|LL|l|L)(u|U)?|(u|U)(ll|LL|l|L)?|f|F|b|B)"
          },
          {
            begin: "(-?)(\\b0[xX][a-fA-F0-9']+|(\\b[\\d']+(\\.[\\d']*)?|\\.[\\d']+)([eE][-+]?[\\d']+)?)"
          }
        ],
        relevance: 0
      };
      const PREPROCESSOR = {
        className: "meta",
        begin: /#\s*[a-z]+\b/,
        end: /$/,
        keywords: {
          "meta-keyword": "if else elif endif define undef warning error line pragma _Pragma ifdef ifndef include"
        },
        contains: [
          {
            begin: /\\\n/,
            relevance: 0
          },
          hljs5.inherit(STRINGS, {
            className: "meta-string"
          }),
          {
            className: "meta-string",
            begin: /<.*?>/
          },
          C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE
        ]
      };
      const TITLE_MODE = {
        className: "title",
        begin: optional(NAMESPACE_RE) + hljs5.IDENT_RE,
        relevance: 0
      };
      const FUNCTION_TITLE = optional(NAMESPACE_RE) + hljs5.IDENT_RE + "\\s*\\(";
      const COMMON_CPP_HINTS = [
        "asin",
        "atan2",
        "atan",
        "calloc",
        "ceil",
        "cosh",
        "cos",
        "exit",
        "exp",
        "fabs",
        "floor",
        "fmod",
        "fprintf",
        "fputs",
        "free",
        "frexp",
        "auto_ptr",
        "deque",
        "list",
        "queue",
        "stack",
        "vector",
        "map",
        "set",
        "pair",
        "bitset",
        "multiset",
        "multimap",
        "unordered_set",
        "fscanf",
        "future",
        "isalnum",
        "isalpha",
        "iscntrl",
        "isdigit",
        "isgraph",
        "islower",
        "isprint",
        "ispunct",
        "isspace",
        "isupper",
        "isxdigit",
        "tolower",
        "toupper",
        "labs",
        "ldexp",
        "log10",
        "log",
        "malloc",
        "realloc",
        "memchr",
        "memcmp",
        "memcpy",
        "memset",
        "modf",
        "pow",
        "printf",
        "putchar",
        "puts",
        "scanf",
        "sinh",
        "sin",
        "snprintf",
        "sprintf",
        "sqrt",
        "sscanf",
        "strcat",
        "strchr",
        "strcmp",
        "strcpy",
        "strcspn",
        "strlen",
        "strncat",
        "strncmp",
        "strncpy",
        "strpbrk",
        "strrchr",
        "strspn",
        "strstr",
        "tanh",
        "tan",
        "unordered_map",
        "unordered_multiset",
        "unordered_multimap",
        "priority_queue",
        "make_pair",
        "array",
        "shared_ptr",
        "abort",
        "terminate",
        "abs",
        "acos",
        "vfprintf",
        "vprintf",
        "vsprintf",
        "endl",
        "initializer_list",
        "unique_ptr",
        "complex",
        "imaginary",
        "std",
        "string",
        "wstring",
        "cin",
        "cout",
        "cerr",
        "clog",
        "stdin",
        "stdout",
        "stderr",
        "stringstream",
        "istringstream",
        "ostringstream"
      ];
      const CPP_KEYWORDS = {
        keyword: "int float while private char char8_t char16_t char32_t catch import module export virtual operator sizeof dynamic_cast|10 typedef const_cast|10 const for static_cast|10 union namespace unsigned long volatile static protected bool template mutable if public friend do goto auto void enum else break extern using asm case typeid wchar_t short reinterpret_cast|10 default double register explicit signed typename try this switch continue inline delete alignas alignof constexpr consteval constinit decltype concept co_await co_return co_yield requires noexcept static_assert thread_local restrict final override atomic_bool atomic_char atomic_schar atomic_uchar atomic_short atomic_ushort atomic_int atomic_uint atomic_long atomic_ulong atomic_llong atomic_ullong new throw return and and_eq bitand bitor compl not not_eq or or_eq xor xor_eq",
        built_in: "_Bool _Complex _Imaginary",
        _relevance_hints: COMMON_CPP_HINTS,
        literal: "true false nullptr NULL"
      };
      const FUNCTION_DISPATCH = {
        className: "function.dispatch",
        relevance: 0,
        keywords: CPP_KEYWORDS,
        begin: concat(
          /\b/,
          /(?!decltype)/,
          /(?!if)/,
          /(?!for)/,
          /(?!while)/,
          hljs5.IDENT_RE,
          lookahead(/\s*\(/)
        )
      };
      const EXPRESSION_CONTAINS = [
        FUNCTION_DISPATCH,
        PREPROCESSOR,
        CPP_PRIMITIVE_TYPES,
        C_LINE_COMMENT_MODE,
        hljs5.C_BLOCK_COMMENT_MODE,
        NUMBERS,
        STRINGS
      ];
      const EXPRESSION_CONTEXT = {
        // This mode covers expression context where we can't expect a function
        // definition and shouldn't highlight anything that looks like one:
        // `return some()`, `else if()`, `(x*sum(1, 2))`
        variants: [
          {
            begin: /=/,
            end: /;/
          },
          {
            begin: /\(/,
            end: /\)/
          },
          {
            beginKeywords: "new throw return else",
            end: /;/
          }
        ],
        keywords: CPP_KEYWORDS,
        contains: EXPRESSION_CONTAINS.concat([
          {
            begin: /\(/,
            end: /\)/,
            keywords: CPP_KEYWORDS,
            contains: EXPRESSION_CONTAINS.concat(["self"]),
            relevance: 0
          }
        ]),
        relevance: 0
      };
      const FUNCTION_DECLARATION = {
        className: "function",
        begin: "(" + FUNCTION_TYPE_RE + "[\\*&\\s]+)+" + FUNCTION_TITLE,
        returnBegin: true,
        end: /[{;=]/,
        excludeEnd: true,
        keywords: CPP_KEYWORDS,
        illegal: /[^\w\s\*&:<>.]/,
        contains: [
          {
            // to prevent it from being confused as the function title
            begin: DECLTYPE_AUTO_RE,
            keywords: CPP_KEYWORDS,
            relevance: 0
          },
          {
            begin: FUNCTION_TITLE,
            returnBegin: true,
            contains: [TITLE_MODE],
            relevance: 0
          },
          // needed because we do not have look-behind on the below rule
          // to prevent it from grabbing the final : in a :: pair
          {
            begin: /::/,
            relevance: 0
          },
          // initializers
          {
            begin: /:/,
            endsWithParent: true,
            contains: [
              STRINGS,
              NUMBERS
            ]
          },
          {
            className: "params",
            begin: /\(/,
            end: /\)/,
            keywords: CPP_KEYWORDS,
            relevance: 0,
            contains: [
              C_LINE_COMMENT_MODE,
              hljs5.C_BLOCK_COMMENT_MODE,
              STRINGS,
              NUMBERS,
              CPP_PRIMITIVE_TYPES,
              // Count matching parentheses.
              {
                begin: /\(/,
                end: /\)/,
                keywords: CPP_KEYWORDS,
                relevance: 0,
                contains: [
                  "self",
                  C_LINE_COMMENT_MODE,
                  hljs5.C_BLOCK_COMMENT_MODE,
                  STRINGS,
                  NUMBERS,
                  CPP_PRIMITIVE_TYPES
                ]
              }
            ]
          },
          CPP_PRIMITIVE_TYPES,
          C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          PREPROCESSOR
        ]
      };
      return {
        name: "C++",
        aliases: [
          "cc",
          "c++",
          "h++",
          "hpp",
          "hh",
          "hxx",
          "cxx"
        ],
        keywords: CPP_KEYWORDS,
        illegal: "</",
        classNameAliases: {
          "function.dispatch": "built_in"
        },
        contains: [].concat(
          EXPRESSION_CONTEXT,
          FUNCTION_DECLARATION,
          FUNCTION_DISPATCH,
          EXPRESSION_CONTAINS,
          [
            PREPROCESSOR,
            {
              // containers: ie, `vector <int> rooms (9);`
              begin: "\\b(deque|list|queue|priority_queue|pair|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array)\\s*<",
              end: ">",
              keywords: CPP_KEYWORDS,
              contains: [
                "self",
                CPP_PRIMITIVE_TYPES
              ]
            },
            {
              begin: hljs5.IDENT_RE + "::",
              keywords: CPP_KEYWORDS
            },
            {
              className: "class",
              beginKeywords: "enum class struct union",
              end: /[{;:<>=]/,
              contains: [
                {
                  beginKeywords: "final class struct"
                },
                hljs5.TITLE_MODE
              ]
            }
          ]
        ),
        exports: {
          preprocessor: PREPROCESSOR,
          strings: STRINGS,
          keywords: CPP_KEYWORDS
        }
      };
    }
    module.exports = cpp;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/crmsh.js
var require_crmsh = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/crmsh.js"(exports, module) {
    init_process_shim();
    function crmsh(hljs5) {
      const RESOURCES = "primitive rsc_template";
      const COMMANDS = "group clone ms master location colocation order fencing_topology rsc_ticket acl_target acl_group user role tag xml";
      const PROPERTY_SETS = "property rsc_defaults op_defaults";
      const KEYWORDS3 = "params meta operations op rule attributes utilization";
      const OPERATORS = "read write deny defined not_defined in_range date spec in ref reference attribute type xpath version and or lt gt tag lte gte eq ne \\";
      const TYPES3 = "number string";
      const LITERALS3 = "Master Started Slave Stopped start promote demote stop monitor true false";
      return {
        name: "crmsh",
        aliases: [
          "crm",
          "pcmk"
        ],
        case_insensitive: true,
        keywords: {
          keyword: KEYWORDS3 + " " + OPERATORS + " " + TYPES3,
          literal: LITERALS3
        },
        contains: [
          hljs5.HASH_COMMENT_MODE,
          {
            beginKeywords: "node",
            starts: {
              end: "\\s*([\\w_-]+:)?",
              starts: {
                className: "title",
                end: "\\s*[\\$\\w_][\\w_-]*"
              }
            }
          },
          {
            beginKeywords: RESOURCES,
            starts: {
              className: "title",
              end: "\\s*[\\$\\w_][\\w_-]*",
              starts: {
                end: "\\s*@?[\\w_][\\w_\\.:-]*"
              }
            }
          },
          {
            begin: "\\b(" + COMMANDS.split(" ").join("|") + ")\\s+",
            keywords: COMMANDS,
            starts: {
              className: "title",
              end: "[\\$\\w_][\\w_-]*"
            }
          },
          {
            beginKeywords: PROPERTY_SETS,
            starts: {
              className: "title",
              end: "\\s*([\\w_-]+:)?"
            }
          },
          hljs5.QUOTE_STRING_MODE,
          {
            className: "meta",
            begin: "(ocf|systemd|service|lsb):[\\w_:-]+",
            relevance: 0
          },
          {
            className: "number",
            begin: "\\b\\d+(\\.\\d+)?(ms|s|h|m)?",
            relevance: 0
          },
          {
            className: "literal",
            begin: "[-]?(infinity|inf)",
            relevance: 0
          },
          {
            className: "attr",
            begin: /([A-Za-z$_#][\w_-]+)=/,
            relevance: 0
          },
          {
            className: "tag",
            begin: "</?",
            end: "/?>",
            relevance: 0
          }
        ]
      };
    }
    module.exports = crmsh;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/crystal.js
var require_crystal = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/crystal.js"(exports, module) {
    init_process_shim();
    function crystal(hljs5) {
      const INT_SUFFIX = "(_?[ui](8|16|32|64|128))?";
      const FLOAT_SUFFIX = "(_?f(32|64))?";
      const CRYSTAL_IDENT_RE = "[a-zA-Z_]\\w*[!?=]?";
      const CRYSTAL_METHOD_RE = "[a-zA-Z_]\\w*[!?=]?|[-+~]@|<<|>>|[=!]~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~|]|//|//=|&[-+*]=?|&\\*\\*|\\[\\][=?]?";
      const CRYSTAL_PATH_RE = "[A-Za-z_]\\w*(::\\w+)*(\\?|!)?";
      const CRYSTAL_KEYWORDS = {
        $pattern: CRYSTAL_IDENT_RE,
        keyword: "abstract alias annotation as as? asm begin break case class def do else elsif end ensure enum extend for fun if include instance_sizeof is_a? lib macro module next nil? of out pointerof private protected rescue responds_to? return require select self sizeof struct super then type typeof union uninitialized unless until verbatim when while with yield __DIR__ __END_LINE__ __FILE__ __LINE__",
        literal: "false nil true"
      };
      const SUBST = {
        className: "subst",
        begin: /#\{/,
        end: /\}/,
        keywords: CRYSTAL_KEYWORDS
      };
      const EXPANSION = {
        className: "template-variable",
        variants: [
          {
            begin: "\\{\\{",
            end: "\\}\\}"
          },
          {
            begin: "\\{%",
            end: "%\\}"
          }
        ],
        keywords: CRYSTAL_KEYWORDS
      };
      function recursiveParen(begin, end) {
        const contains3 = [
          {
            begin,
            end
          }
        ];
        contains3[0].contains = contains3;
        return contains3;
      }
      const STRING = {
        className: "string",
        contains: [
          hljs5.BACKSLASH_ESCAPE,
          SUBST
        ],
        variants: [
          {
            begin: /'/,
            end: /'/
          },
          {
            begin: /"/,
            end: /"/
          },
          {
            begin: /`/,
            end: /`/
          },
          {
            begin: "%[Qwi]?\\(",
            end: "\\)",
            contains: recursiveParen("\\(", "\\)")
          },
          {
            begin: "%[Qwi]?\\[",
            end: "\\]",
            contains: recursiveParen("\\[", "\\]")
          },
          {
            begin: "%[Qwi]?\\{",
            end: /\}/,
            contains: recursiveParen(/\{/, /\}/)
          },
          {
            begin: "%[Qwi]?<",
            end: ">",
            contains: recursiveParen("<", ">")
          },
          {
            begin: "%[Qwi]?\\|",
            end: "\\|"
          },
          {
            begin: /<<-\w+$/,
            end: /^\s*\w+$/
          }
        ],
        relevance: 0
      };
      const Q_STRING = {
        className: "string",
        variants: [
          {
            begin: "%q\\(",
            end: "\\)",
            contains: recursiveParen("\\(", "\\)")
          },
          {
            begin: "%q\\[",
            end: "\\]",
            contains: recursiveParen("\\[", "\\]")
          },
          {
            begin: "%q\\{",
            end: /\}/,
            contains: recursiveParen(/\{/, /\}/)
          },
          {
            begin: "%q<",
            end: ">",
            contains: recursiveParen("<", ">")
          },
          {
            begin: "%q\\|",
            end: "\\|"
          },
          {
            begin: /<<-'\w+'$/,
            end: /^\s*\w+$/
          }
        ],
        relevance: 0
      };
      const REGEXP = {
        begin: "(?!%\\})(" + hljs5.RE_STARTERS_RE + "|\\n|\\b(case|if|select|unless|until|when|while)\\b)\\s*",
        keywords: "case if select unless until when while",
        contains: [
          {
            className: "regexp",
            contains: [
              hljs5.BACKSLASH_ESCAPE,
              SUBST
            ],
            variants: [
              {
                begin: "//[a-z]*",
                relevance: 0
              },
              {
                begin: "/(?!\\/)",
                end: "/[a-z]*"
              }
            ]
          }
        ],
        relevance: 0
      };
      const REGEXP2 = {
        className: "regexp",
        contains: [
          hljs5.BACKSLASH_ESCAPE,
          SUBST
        ],
        variants: [
          {
            begin: "%r\\(",
            end: "\\)",
            contains: recursiveParen("\\(", "\\)")
          },
          {
            begin: "%r\\[",
            end: "\\]",
            contains: recursiveParen("\\[", "\\]")
          },
          {
            begin: "%r\\{",
            end: /\}/,
            contains: recursiveParen(/\{/, /\}/)
          },
          {
            begin: "%r<",
            end: ">",
            contains: recursiveParen("<", ">")
          },
          {
            begin: "%r\\|",
            end: "\\|"
          }
        ],
        relevance: 0
      };
      const ATTRIBUTE = {
        className: "meta",
        begin: "@\\[",
        end: "\\]",
        contains: [
          hljs5.inherit(hljs5.QUOTE_STRING_MODE, {
            className: "meta-string"
          })
        ]
      };
      const CRYSTAL_DEFAULT_CONTAINS = [
        EXPANSION,
        STRING,
        Q_STRING,
        REGEXP2,
        REGEXP,
        ATTRIBUTE,
        hljs5.HASH_COMMENT_MODE,
        {
          className: "class",
          beginKeywords: "class module struct",
          end: "$|;",
          illegal: /=/,
          contains: [
            hljs5.HASH_COMMENT_MODE,
            hljs5.inherit(hljs5.TITLE_MODE, {
              begin: CRYSTAL_PATH_RE
            }),
            {
              // relevance booster for inheritance
              begin: "<"
            }
          ]
        },
        {
          className: "class",
          beginKeywords: "lib enum union",
          end: "$|;",
          illegal: /=/,
          contains: [
            hljs5.HASH_COMMENT_MODE,
            hljs5.inherit(hljs5.TITLE_MODE, {
              begin: CRYSTAL_PATH_RE
            })
          ]
        },
        {
          beginKeywords: "annotation",
          end: "$|;",
          illegal: /=/,
          contains: [
            hljs5.HASH_COMMENT_MODE,
            hljs5.inherit(hljs5.TITLE_MODE, {
              begin: CRYSTAL_PATH_RE
            })
          ],
          relevance: 2
        },
        {
          className: "function",
          beginKeywords: "def",
          end: /\B\b/,
          contains: [
            hljs5.inherit(hljs5.TITLE_MODE, {
              begin: CRYSTAL_METHOD_RE,
              endsParent: true
            })
          ]
        },
        {
          className: "function",
          beginKeywords: "fun macro",
          end: /\B\b/,
          contains: [
            hljs5.inherit(hljs5.TITLE_MODE, {
              begin: CRYSTAL_METHOD_RE,
              endsParent: true
            })
          ],
          relevance: 2
        },
        {
          className: "symbol",
          begin: hljs5.UNDERSCORE_IDENT_RE + "(!|\\?)?:",
          relevance: 0
        },
        {
          className: "symbol",
          begin: ":",
          contains: [
            STRING,
            {
              begin: CRYSTAL_METHOD_RE
            }
          ],
          relevance: 0
        },
        {
          className: "number",
          variants: [
            {
              begin: "\\b0b([01_]+)" + INT_SUFFIX
            },
            {
              begin: "\\b0o([0-7_]+)" + INT_SUFFIX
            },
            {
              begin: "\\b0x([A-Fa-f0-9_]+)" + INT_SUFFIX
            },
            {
              begin: "\\b([1-9][0-9_]*[0-9]|[0-9])(\\.[0-9][0-9_]*)?([eE]_?[-+]?[0-9_]*)?" + FLOAT_SUFFIX + "(?!_)"
            },
            {
              begin: "\\b([1-9][0-9_]*|0)" + INT_SUFFIX
            }
          ],
          relevance: 0
        }
      ];
      SUBST.contains = CRYSTAL_DEFAULT_CONTAINS;
      EXPANSION.contains = CRYSTAL_DEFAULT_CONTAINS.slice(1);
      return {
        name: "Crystal",
        aliases: ["cr"],
        keywords: CRYSTAL_KEYWORDS,
        contains: CRYSTAL_DEFAULT_CONTAINS
      };
    }
    module.exports = crystal;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/csharp.js
var require_csharp = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/csharp.js"(exports, module) {
    init_process_shim();
    function csharp(hljs5) {
      const BUILT_IN_KEYWORDS = [
        "bool",
        "byte",
        "char",
        "decimal",
        "delegate",
        "double",
        "dynamic",
        "enum",
        "float",
        "int",
        "long",
        "nint",
        "nuint",
        "object",
        "sbyte",
        "short",
        "string",
        "ulong",
        "uint",
        "ushort"
      ];
      const FUNCTION_MODIFIERS = [
        "public",
        "private",
        "protected",
        "static",
        "internal",
        "protected",
        "abstract",
        "async",
        "extern",
        "override",
        "unsafe",
        "virtual",
        "new",
        "sealed",
        "partial"
      ];
      const LITERAL_KEYWORDS = [
        "default",
        "false",
        "null",
        "true"
      ];
      const NORMAL_KEYWORDS = [
        "abstract",
        "as",
        "base",
        "break",
        "case",
        "class",
        "const",
        "continue",
        "do",
        "else",
        "event",
        "explicit",
        "extern",
        "finally",
        "fixed",
        "for",
        "foreach",
        "goto",
        "if",
        "implicit",
        "in",
        "interface",
        "internal",
        "is",
        "lock",
        "namespace",
        "new",
        "operator",
        "out",
        "override",
        "params",
        "private",
        "protected",
        "public",
        "readonly",
        "record",
        "ref",
        "return",
        "sealed",
        "sizeof",
        "stackalloc",
        "static",
        "struct",
        "switch",
        "this",
        "throw",
        "try",
        "typeof",
        "unchecked",
        "unsafe",
        "using",
        "virtual",
        "void",
        "volatile",
        "while"
      ];
      const CONTEXTUAL_KEYWORDS = [
        "add",
        "alias",
        "and",
        "ascending",
        "async",
        "await",
        "by",
        "descending",
        "equals",
        "from",
        "get",
        "global",
        "group",
        "init",
        "into",
        "join",
        "let",
        "nameof",
        "not",
        "notnull",
        "on",
        "or",
        "orderby",
        "partial",
        "remove",
        "select",
        "set",
        "unmanaged",
        "value|0",
        "var",
        "when",
        "where",
        "with",
        "yield"
      ];
      const KEYWORDS3 = {
        keyword: NORMAL_KEYWORDS.concat(CONTEXTUAL_KEYWORDS),
        built_in: BUILT_IN_KEYWORDS,
        literal: LITERAL_KEYWORDS
      };
      const TITLE_MODE = hljs5.inherit(hljs5.TITLE_MODE, {
        begin: "[a-zA-Z](\\.?\\w)*"
      });
      const NUMBERS = {
        className: "number",
        variants: [
          {
            begin: "\\b(0b[01']+)"
          },
          {
            begin: "(-?)\\b([\\d']+(\\.[\\d']*)?|\\.[\\d']+)(u|U|l|L|ul|UL|f|F|b|B)"
          },
          {
            begin: "(-?)(\\b0[xX][a-fA-F0-9']+|(\\b[\\d']+(\\.[\\d']*)?|\\.[\\d']+)([eE][-+]?[\\d']+)?)"
          }
        ],
        relevance: 0
      };
      const VERBATIM_STRING = {
        className: "string",
        begin: '@"',
        end: '"',
        contains: [
          {
            begin: '""'
          }
        ]
      };
      const VERBATIM_STRING_NO_LF = hljs5.inherit(VERBATIM_STRING, {
        illegal: /\n/
      });
      const SUBST = {
        className: "subst",
        begin: /\{/,
        end: /\}/,
        keywords: KEYWORDS3
      };
      const SUBST_NO_LF = hljs5.inherit(SUBST, {
        illegal: /\n/
      });
      const INTERPOLATED_STRING = {
        className: "string",
        begin: /\$"/,
        end: '"',
        illegal: /\n/,
        contains: [
          {
            begin: /\{\{/
          },
          {
            begin: /\}\}/
          },
          hljs5.BACKSLASH_ESCAPE,
          SUBST_NO_LF
        ]
      };
      const INTERPOLATED_VERBATIM_STRING = {
        className: "string",
        begin: /\$@"/,
        end: '"',
        contains: [
          {
            begin: /\{\{/
          },
          {
            begin: /\}\}/
          },
          {
            begin: '""'
          },
          SUBST
        ]
      };
      const INTERPOLATED_VERBATIM_STRING_NO_LF = hljs5.inherit(INTERPOLATED_VERBATIM_STRING, {
        illegal: /\n/,
        contains: [
          {
            begin: /\{\{/
          },
          {
            begin: /\}\}/
          },
          {
            begin: '""'
          },
          SUBST_NO_LF
        ]
      });
      SUBST.contains = [
        INTERPOLATED_VERBATIM_STRING,
        INTERPOLATED_STRING,
        VERBATIM_STRING,
        hljs5.APOS_STRING_MODE,
        hljs5.QUOTE_STRING_MODE,
        NUMBERS,
        hljs5.C_BLOCK_COMMENT_MODE
      ];
      SUBST_NO_LF.contains = [
        INTERPOLATED_VERBATIM_STRING_NO_LF,
        INTERPOLATED_STRING,
        VERBATIM_STRING_NO_LF,
        hljs5.APOS_STRING_MODE,
        hljs5.QUOTE_STRING_MODE,
        NUMBERS,
        hljs5.inherit(hljs5.C_BLOCK_COMMENT_MODE, {
          illegal: /\n/
        })
      ];
      const STRING = {
        variants: [
          INTERPOLATED_VERBATIM_STRING,
          INTERPOLATED_STRING,
          VERBATIM_STRING,
          hljs5.APOS_STRING_MODE,
          hljs5.QUOTE_STRING_MODE
        ]
      };
      const GENERIC_MODIFIER = {
        begin: "<",
        end: ">",
        contains: [
          {
            beginKeywords: "in out"
          },
          TITLE_MODE
        ]
      };
      const TYPE_IDENT_RE = hljs5.IDENT_RE + "(<" + hljs5.IDENT_RE + "(\\s*,\\s*" + hljs5.IDENT_RE + ")*>)?(\\[\\])?";
      const AT_IDENTIFIER = {
        // prevents expressions like `@class` from incorrect flagging
        // `class` as a keyword
        begin: "@" + hljs5.IDENT_RE,
        relevance: 0
      };
      return {
        name: "C#",
        aliases: [
          "cs",
          "c#"
        ],
        keywords: KEYWORDS3,
        illegal: /::/,
        contains: [
          hljs5.COMMENT(
            "///",
            "$",
            {
              returnBegin: true,
              contains: [
                {
                  className: "doctag",
                  variants: [
                    {
                      begin: "///",
                      relevance: 0
                    },
                    {
                      begin: "<!--|-->"
                    },
                    {
                      begin: "</?",
                      end: ">"
                    }
                  ]
                }
              ]
            }
          ),
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          {
            className: "meta",
            begin: "#",
            end: "$",
            keywords: {
              "meta-keyword": "if else elif endif define undef warning error line region endregion pragma checksum"
            }
          },
          STRING,
          NUMBERS,
          {
            beginKeywords: "class interface",
            relevance: 0,
            end: /[{;=]/,
            illegal: /[^\s:,]/,
            contains: [
              {
                beginKeywords: "where class"
              },
              TITLE_MODE,
              GENERIC_MODIFIER,
              hljs5.C_LINE_COMMENT_MODE,
              hljs5.C_BLOCK_COMMENT_MODE
            ]
          },
          {
            beginKeywords: "namespace",
            relevance: 0,
            end: /[{;=]/,
            illegal: /[^\s:]/,
            contains: [
              TITLE_MODE,
              hljs5.C_LINE_COMMENT_MODE,
              hljs5.C_BLOCK_COMMENT_MODE
            ]
          },
          {
            beginKeywords: "record",
            relevance: 0,
            end: /[{;=]/,
            illegal: /[^\s:]/,
            contains: [
              TITLE_MODE,
              GENERIC_MODIFIER,
              hljs5.C_LINE_COMMENT_MODE,
              hljs5.C_BLOCK_COMMENT_MODE
            ]
          },
          {
            // [Attributes("")]
            className: "meta",
            begin: "^\\s*\\[",
            excludeBegin: true,
            end: "\\]",
            excludeEnd: true,
            contains: [
              {
                className: "meta-string",
                begin: /"/,
                end: /"/
              }
            ]
          },
          {
            // Expression keywords prevent 'keyword Name(...)' from being
            // recognized as a function definition
            beginKeywords: "new return throw await else",
            relevance: 0
          },
          {
            className: "function",
            begin: "(" + TYPE_IDENT_RE + "\\s+)+" + hljs5.IDENT_RE + "\\s*(<.+>\\s*)?\\(",
            returnBegin: true,
            end: /\s*[{;=]/,
            excludeEnd: true,
            keywords: KEYWORDS3,
            contains: [
              // prevents these from being highlighted `title`
              {
                beginKeywords: FUNCTION_MODIFIERS.join(" "),
                relevance: 0
              },
              {
                begin: hljs5.IDENT_RE + "\\s*(<.+>\\s*)?\\(",
                returnBegin: true,
                contains: [
                  hljs5.TITLE_MODE,
                  GENERIC_MODIFIER
                ],
                relevance: 0
              },
              {
                className: "params",
                begin: /\(/,
                end: /\)/,
                excludeBegin: true,
                excludeEnd: true,
                keywords: KEYWORDS3,
                relevance: 0,
                contains: [
                  STRING,
                  NUMBERS,
                  hljs5.C_BLOCK_COMMENT_MODE
                ]
              },
              hljs5.C_LINE_COMMENT_MODE,
              hljs5.C_BLOCK_COMMENT_MODE
            ]
          },
          AT_IDENTIFIER
        ]
      };
    }
    module.exports = csharp;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/csp.js
var require_csp = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/csp.js"(exports, module) {
    init_process_shim();
    function csp(hljs5) {
      return {
        name: "CSP",
        case_insensitive: false,
        keywords: {
          $pattern: "[a-zA-Z][a-zA-Z0-9_-]*",
          keyword: "base-uri child-src connect-src default-src font-src form-action frame-ancestors frame-src img-src media-src object-src plugin-types report-uri sandbox script-src style-src"
        },
        contains: [
          {
            className: "string",
            begin: "'",
            end: "'"
          },
          {
            className: "attribute",
            begin: "^Content",
            end: ":",
            excludeEnd: true
          }
        ]
      };
    }
    module.exports = csp;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/css.js
var require_css = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/css.js"(exports, module) {
    init_process_shim();
    var MODES2 = (hljs5) => {
      return {
        IMPORTANT: {
          className: "meta",
          begin: "!important"
        },
        HEXCOLOR: {
          className: "number",
          begin: "#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})"
        },
        ATTRIBUTE_SELECTOR_MODE: {
          className: "selector-attr",
          begin: /\[/,
          end: /\]/,
          illegal: "$",
          contains: [
            hljs5.APOS_STRING_MODE,
            hljs5.QUOTE_STRING_MODE
          ]
        }
      };
    };
    var TAGS2 = [
      "a",
      "abbr",
      "address",
      "article",
      "aside",
      "audio",
      "b",
      "blockquote",
      "body",
      "button",
      "canvas",
      "caption",
      "cite",
      "code",
      "dd",
      "del",
      "details",
      "dfn",
      "div",
      "dl",
      "dt",
      "em",
      "fieldset",
      "figcaption",
      "figure",
      "footer",
      "form",
      "h1",
      "h2",
      "h3",
      "h4",
      "h5",
      "h6",
      "header",
      "hgroup",
      "html",
      "i",
      "iframe",
      "img",
      "input",
      "ins",
      "kbd",
      "label",
      "legend",
      "li",
      "main",
      "mark",
      "menu",
      "nav",
      "object",
      "ol",
      "p",
      "q",
      "quote",
      "samp",
      "section",
      "span",
      "strong",
      "summary",
      "sup",
      "table",
      "tbody",
      "td",
      "textarea",
      "tfoot",
      "th",
      "thead",
      "time",
      "tr",
      "ul",
      "var",
      "video"
    ];
    var MEDIA_FEATURES2 = [
      "any-hover",
      "any-pointer",
      "aspect-ratio",
      "color",
      "color-gamut",
      "color-index",
      "device-aspect-ratio",
      "device-height",
      "device-width",
      "display-mode",
      "forced-colors",
      "grid",
      "height",
      "hover",
      "inverted-colors",
      "monochrome",
      "orientation",
      "overflow-block",
      "overflow-inline",
      "pointer",
      "prefers-color-scheme",
      "prefers-contrast",
      "prefers-reduced-motion",
      "prefers-reduced-transparency",
      "resolution",
      "scan",
      "scripting",
      "update",
      "width",
      // TODO: find a better solution?
      "min-width",
      "max-width",
      "min-height",
      "max-height"
    ];
    var PSEUDO_CLASSES2 = [
      "active",
      "any-link",
      "blank",
      "checked",
      "current",
      "default",
      "defined",
      "dir",
      // dir()
      "disabled",
      "drop",
      "empty",
      "enabled",
      "first",
      "first-child",
      "first-of-type",
      "fullscreen",
      "future",
      "focus",
      "focus-visible",
      "focus-within",
      "has",
      // has()
      "host",
      // host or host()
      "host-context",
      // host-context()
      "hover",
      "indeterminate",
      "in-range",
      "invalid",
      "is",
      // is()
      "lang",
      // lang()
      "last-child",
      "last-of-type",
      "left",
      "link",
      "local-link",
      "not",
      // not()
      "nth-child",
      // nth-child()
      "nth-col",
      // nth-col()
      "nth-last-child",
      // nth-last-child()
      "nth-last-col",
      // nth-last-col()
      "nth-last-of-type",
      //nth-last-of-type()
      "nth-of-type",
      //nth-of-type()
      "only-child",
      "only-of-type",
      "optional",
      "out-of-range",
      "past",
      "placeholder-shown",
      "read-only",
      "read-write",
      "required",
      "right",
      "root",
      "scope",
      "target",
      "target-within",
      "user-invalid",
      "valid",
      "visited",
      "where"
      // where()
    ];
    var PSEUDO_ELEMENTS2 = [
      "after",
      "backdrop",
      "before",
      "cue",
      "cue-region",
      "first-letter",
      "first-line",
      "grammar-error",
      "marker",
      "part",
      "placeholder",
      "selection",
      "slotted",
      "spelling-error"
    ];
    var ATTRIBUTES2 = [
      "align-content",
      "align-items",
      "align-self",
      "animation",
      "animation-delay",
      "animation-direction",
      "animation-duration",
      "animation-fill-mode",
      "animation-iteration-count",
      "animation-name",
      "animation-play-state",
      "animation-timing-function",
      "auto",
      "backface-visibility",
      "background",
      "background-attachment",
      "background-clip",
      "background-color",
      "background-image",
      "background-origin",
      "background-position",
      "background-repeat",
      "background-size",
      "border",
      "border-bottom",
      "border-bottom-color",
      "border-bottom-left-radius",
      "border-bottom-right-radius",
      "border-bottom-style",
      "border-bottom-width",
      "border-collapse",
      "border-color",
      "border-image",
      "border-image-outset",
      "border-image-repeat",
      "border-image-slice",
      "border-image-source",
      "border-image-width",
      "border-left",
      "border-left-color",
      "border-left-style",
      "border-left-width",
      "border-radius",
      "border-right",
      "border-right-color",
      "border-right-style",
      "border-right-width",
      "border-spacing",
      "border-style",
      "border-top",
      "border-top-color",
      "border-top-left-radius",
      "border-top-right-radius",
      "border-top-style",
      "border-top-width",
      "border-width",
      "bottom",
      "box-decoration-break",
      "box-shadow",
      "box-sizing",
      "break-after",
      "break-before",
      "break-inside",
      "caption-side",
      "clear",
      "clip",
      "clip-path",
      "color",
      "column-count",
      "column-fill",
      "column-gap",
      "column-rule",
      "column-rule-color",
      "column-rule-style",
      "column-rule-width",
      "column-span",
      "column-width",
      "columns",
      "content",
      "counter-increment",
      "counter-reset",
      "cursor",
      "direction",
      "display",
      "empty-cells",
      "filter",
      "flex",
      "flex-basis",
      "flex-direction",
      "flex-flow",
      "flex-grow",
      "flex-shrink",
      "flex-wrap",
      "float",
      "font",
      "font-display",
      "font-family",
      "font-feature-settings",
      "font-kerning",
      "font-language-override",
      "font-size",
      "font-size-adjust",
      "font-smoothing",
      "font-stretch",
      "font-style",
      "font-variant",
      "font-variant-ligatures",
      "font-variation-settings",
      "font-weight",
      "height",
      "hyphens",
      "icon",
      "image-orientation",
      "image-rendering",
      "image-resolution",
      "ime-mode",
      "inherit",
      "initial",
      "justify-content",
      "left",
      "letter-spacing",
      "line-height",
      "list-style",
      "list-style-image",
      "list-style-position",
      "list-style-type",
      "margin",
      "margin-bottom",
      "margin-left",
      "margin-right",
      "margin-top",
      "marks",
      "mask",
      "max-height",
      "max-width",
      "min-height",
      "min-width",
      "nav-down",
      "nav-index",
      "nav-left",
      "nav-right",
      "nav-up",
      "none",
      "normal",
      "object-fit",
      "object-position",
      "opacity",
      "order",
      "orphans",
      "outline",
      "outline-color",
      "outline-offset",
      "outline-style",
      "outline-width",
      "overflow",
      "overflow-wrap",
      "overflow-x",
      "overflow-y",
      "padding",
      "padding-bottom",
      "padding-left",
      "padding-right",
      "padding-top",
      "page-break-after",
      "page-break-before",
      "page-break-inside",
      "perspective",
      "perspective-origin",
      "pointer-events",
      "position",
      "quotes",
      "resize",
      "right",
      "src",
      // @font-face
      "tab-size",
      "table-layout",
      "text-align",
      "text-align-last",
      "text-decoration",
      "text-decoration-color",
      "text-decoration-line",
      "text-decoration-style",
      "text-indent",
      "text-overflow",
      "text-rendering",
      "text-shadow",
      "text-transform",
      "text-underline-position",
      "top",
      "transform",
      "transform-origin",
      "transform-style",
      "transition",
      "transition-delay",
      "transition-duration",
      "transition-property",
      "transition-timing-function",
      "unicode-bidi",
      "vertical-align",
      "visibility",
      "white-space",
      "widows",
      "width",
      "word-break",
      "word-spacing",
      "word-wrap",
      "z-index"
      // reverse makes sure longer attributes `font-weight` are matched fully
      // instead of getting false positives on say `font`
    ].reverse();
    function source(re2) {
      if (!re2) return null;
      if (typeof re2 === "string") return re2;
      return re2.source;
    }
    function lookahead(re2) {
      return concat("(?=", re2, ")");
    }
    function concat(...args) {
      const joined = args.map((x2) => source(x2)).join("");
      return joined;
    }
    function css2(hljs5) {
      const modes = MODES2(hljs5);
      const FUNCTION_DISPATCH = {
        className: "built_in",
        begin: /[\w-]+(?=\()/
      };
      const VENDOR_PREFIX = {
        begin: /-(webkit|moz|ms|o)-(?=[a-z])/
      };
      const AT_MODIFIERS = "and or not only";
      const AT_PROPERTY_RE = /@-?\w[\w]*(-\w+)*/;
      const IDENT_RE3 = "[a-zA-Z-][a-zA-Z0-9_-]*";
      const STRINGS = [
        hljs5.APOS_STRING_MODE,
        hljs5.QUOTE_STRING_MODE
      ];
      return {
        name: "CSS",
        case_insensitive: true,
        illegal: /[=|'\$]/,
        keywords: {
          keyframePosition: "from to"
        },
        classNameAliases: {
          // for visual continuity with `tag {}` and because we
          // don't have a great class for this?
          keyframePosition: "selector-tag"
        },
        contains: [
          hljs5.C_BLOCK_COMMENT_MODE,
          VENDOR_PREFIX,
          // to recognize keyframe 40% etc which are outside the scope of our
          // attribute value mode
          hljs5.CSS_NUMBER_MODE,
          {
            className: "selector-id",
            begin: /#[A-Za-z0-9_-]+/,
            relevance: 0
          },
          {
            className: "selector-class",
            begin: "\\." + IDENT_RE3,
            relevance: 0
          },
          modes.ATTRIBUTE_SELECTOR_MODE,
          {
            className: "selector-pseudo",
            variants: [
              {
                begin: ":(" + PSEUDO_CLASSES2.join("|") + ")"
              },
              {
                begin: "::(" + PSEUDO_ELEMENTS2.join("|") + ")"
              }
            ]
          },
          // we may actually need this (12/2020)
          // { // pseudo-selector params
          //   begin: /\(/,
          //   end: /\)/,
          //   contains: [ hljs.CSS_NUMBER_MODE ]
          // },
          {
            className: "attribute",
            begin: "\\b(" + ATTRIBUTES2.join("|") + ")\\b"
          },
          // attribute values
          {
            begin: ":",
            end: "[;}]",
            contains: [
              modes.HEXCOLOR,
              modes.IMPORTANT,
              hljs5.CSS_NUMBER_MODE,
              ...STRINGS,
              // needed to highlight these as strings and to avoid issues with
              // illegal characters that might be inside urls that would tigger the
              // languages illegal stack
              {
                begin: /(url|data-uri)\(/,
                end: /\)/,
                relevance: 0,
                // from keywords
                keywords: {
                  built_in: "url data-uri"
                },
                contains: [
                  {
                    className: "string",
                    // any character other than `)` as in `url()` will be the start
                    // of a string, which ends with `)` (from the parent mode)
                    begin: /[^)]/,
                    endsWithParent: true,
                    excludeEnd: true
                  }
                ]
              },
              FUNCTION_DISPATCH
            ]
          },
          {
            begin: lookahead(/@/),
            end: "[{;]",
            relevance: 0,
            illegal: /:/,
            // break on Less variables @var: ...
            contains: [
              {
                className: "keyword",
                begin: AT_PROPERTY_RE
              },
              {
                begin: /\s/,
                endsWithParent: true,
                excludeEnd: true,
                relevance: 0,
                keywords: {
                  $pattern: /[a-z-]+/,
                  keyword: AT_MODIFIERS,
                  attribute: MEDIA_FEATURES2.join(" ")
                },
                contains: [
                  {
                    begin: /[a-z-]+(?=:)/,
                    className: "attribute"
                  },
                  ...STRINGS,
                  hljs5.CSS_NUMBER_MODE
                ]
              }
            ]
          },
          {
            className: "selector-tag",
            begin: "\\b(" + TAGS2.join("|") + ")\\b"
          }
        ]
      };
    }
    module.exports = css2;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/d.js
var require_d = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/d.js"(exports, module) {
    init_process_shim();
    function d4(hljs5) {
      const D_KEYWORDS = {
        $pattern: hljs5.UNDERSCORE_IDENT_RE,
        keyword: "abstract alias align asm assert auto body break byte case cast catch class const continue debug default delete deprecated do else enum export extern final finally for foreach foreach_reverse|10 goto if immutable import in inout int interface invariant is lazy macro mixin module new nothrow out override package pragma private protected public pure ref return scope shared static struct super switch synchronized template this throw try typedef typeid typeof union unittest version void volatile while with __FILE__ __LINE__ __gshared|10 __thread __traits __DATE__ __EOF__ __TIME__ __TIMESTAMP__ __VENDOR__ __VERSION__",
        built_in: "bool cdouble cent cfloat char creal dchar delegate double dstring float function idouble ifloat ireal long real short string ubyte ucent uint ulong ushort wchar wstring",
        literal: "false null true"
      };
      const decimal_integer_re = "(0|[1-9][\\d_]*)";
      const decimal_integer_nosus_re = "(0|[1-9][\\d_]*|\\d[\\d_]*|[\\d_]+?\\d)";
      const binary_integer_re = "0[bB][01_]+";
      const hexadecimal_digits_re = "([\\da-fA-F][\\da-fA-F_]*|_[\\da-fA-F][\\da-fA-F_]*)";
      const hexadecimal_integer_re = "0[xX]" + hexadecimal_digits_re;
      const decimal_exponent_re = "([eE][+-]?" + decimal_integer_nosus_re + ")";
      const decimal_float_re = "(" + decimal_integer_nosus_re + "(\\.\\d*|" + decimal_exponent_re + ")|\\d+\\." + decimal_integer_nosus_re + "|\\." + decimal_integer_re + decimal_exponent_re + "?)";
      const hexadecimal_float_re = "(0[xX](" + hexadecimal_digits_re + "\\." + hexadecimal_digits_re + "|\\.?" + hexadecimal_digits_re + ")[pP][+-]?" + decimal_integer_nosus_re + ")";
      const integer_re = "(" + decimal_integer_re + "|" + binary_integer_re + "|" + hexadecimal_integer_re + ")";
      const float_re = "(" + hexadecimal_float_re + "|" + decimal_float_re + ")";
      const escape_sequence_re = `\\\\(['"\\?\\\\abfnrtv]|u[\\dA-Fa-f]{4}|[0-7]{1,3}|x[\\dA-Fa-f]{2}|U[\\dA-Fa-f]{8})|&[a-zA-Z\\d]{2,};`;
      const D_INTEGER_MODE = {
        className: "number",
        begin: "\\b" + integer_re + "(L|u|U|Lu|LU|uL|UL)?",
        relevance: 0
      };
      const D_FLOAT_MODE = {
        className: "number",
        begin: "\\b(" + float_re + "([fF]|L|i|[fF]i|Li)?|" + integer_re + "(i|[fF]i|Li))",
        relevance: 0
      };
      const D_CHARACTER_MODE = {
        className: "string",
        begin: "'(" + escape_sequence_re + "|.)",
        end: "'",
        illegal: "."
      };
      const D_ESCAPE_SEQUENCE = {
        begin: escape_sequence_re,
        relevance: 0
      };
      const D_STRING_MODE = {
        className: "string",
        begin: '"',
        contains: [D_ESCAPE_SEQUENCE],
        end: '"[cwd]?'
      };
      const D_WYSIWYG_DELIMITED_STRING_MODE = {
        className: "string",
        begin: '[rq]"',
        end: '"[cwd]?',
        relevance: 5
      };
      const D_ALTERNATE_WYSIWYG_STRING_MODE = {
        className: "string",
        begin: "`",
        end: "`[cwd]?"
      };
      const D_HEX_STRING_MODE = {
        className: "string",
        begin: 'x"[\\da-fA-F\\s\\n\\r]*"[cwd]?',
        relevance: 10
      };
      const D_TOKEN_STRING_MODE = {
        className: "string",
        begin: 'q"\\{',
        end: '\\}"'
      };
      const D_HASHBANG_MODE = {
        className: "meta",
        begin: "^#!",
        end: "$",
        relevance: 5
      };
      const D_SPECIAL_TOKEN_SEQUENCE_MODE = {
        className: "meta",
        begin: "#(line)",
        end: "$",
        relevance: 5
      };
      const D_ATTRIBUTE_MODE = {
        className: "keyword",
        begin: "@[a-zA-Z_][a-zA-Z_\\d]*"
      };
      const D_NESTING_COMMENT_MODE = hljs5.COMMENT(
        "\\/\\+",
        "\\+\\/",
        {
          contains: ["self"],
          relevance: 10
        }
      );
      return {
        name: "D",
        keywords: D_KEYWORDS,
        contains: [
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          D_NESTING_COMMENT_MODE,
          D_HEX_STRING_MODE,
          D_STRING_MODE,
          D_WYSIWYG_DELIMITED_STRING_MODE,
          D_ALTERNATE_WYSIWYG_STRING_MODE,
          D_TOKEN_STRING_MODE,
          D_FLOAT_MODE,
          D_INTEGER_MODE,
          D_CHARACTER_MODE,
          D_HASHBANG_MODE,
          D_SPECIAL_TOKEN_SEQUENCE_MODE,
          D_ATTRIBUTE_MODE
        ]
      };
    }
    module.exports = d4;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/markdown.js
var require_markdown = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/markdown.js"(exports, module) {
    init_process_shim();
    function source(re2) {
      if (!re2) return null;
      if (typeof re2 === "string") return re2;
      return re2.source;
    }
    function concat(...args) {
      const joined = args.map((x2) => source(x2)).join("");
      return joined;
    }
    function markdown(hljs5) {
      const INLINE_HTML = {
        begin: /<\/?[A-Za-z_]/,
        end: ">",
        subLanguage: "xml",
        relevance: 0
      };
      const HORIZONTAL_RULE = {
        begin: "^[-\\*]{3,}",
        end: "$"
      };
      const CODE = {
        className: "code",
        variants: [
          // TODO: fix to allow these to work with sublanguage also
          {
            begin: "(`{3,})[^`](.|\\n)*?\\1`*[ ]*"
          },
          {
            begin: "(~{3,})[^~](.|\\n)*?\\1~*[ ]*"
          },
          // needed to allow markdown as a sublanguage to work
          {
            begin: "```",
            end: "```+[ ]*$"
          },
          {
            begin: "~~~",
            end: "~~~+[ ]*$"
          },
          {
            begin: "`.+?`"
          },
          {
            begin: "(?=^( {4}|\\t))",
            // use contains to gobble up multiple lines to allow the block to be whatever size
            // but only have a single open/close tag vs one per line
            contains: [
              {
                begin: "^( {4}|\\t)",
                end: "(\\n)$"
              }
            ],
            relevance: 0
          }
        ]
      };
      const LIST = {
        className: "bullet",
        begin: "^[ 	]*([*+-]|(\\d+\\.))(?=\\s+)",
        end: "\\s+",
        excludeEnd: true
      };
      const LINK_REFERENCE = {
        begin: /^\[[^\n]+\]:/,
        returnBegin: true,
        contains: [
          {
            className: "symbol",
            begin: /\[/,
            end: /\]/,
            excludeBegin: true,
            excludeEnd: true
          },
          {
            className: "link",
            begin: /:\s*/,
            end: /$/,
            excludeBegin: true
          }
        ]
      };
      const URL_SCHEME = /[A-Za-z][A-Za-z0-9+.-]*/;
      const LINK = {
        variants: [
          // too much like nested array access in so many languages
          // to have any real relevance
          {
            begin: /\[.+?\]\[.*?\]/,
            relevance: 0
          },
          // popular internet URLs
          {
            begin: /\[.+?\]\(((data|javascript|mailto):|(?:http|ftp)s?:\/\/).*?\)/,
            relevance: 2
          },
          {
            begin: concat(/\[.+?\]\(/, URL_SCHEME, /:\/\/.*?\)/),
            relevance: 2
          },
          // relative urls
          {
            begin: /\[.+?\]\([./?&#].*?\)/,
            relevance: 1
          },
          // whatever else, lower relevance (might not be a link at all)
          {
            begin: /\[.+?\]\(.*?\)/,
            relevance: 0
          }
        ],
        returnBegin: true,
        contains: [
          {
            className: "string",
            relevance: 0,
            begin: "\\[",
            end: "\\]",
            excludeBegin: true,
            returnEnd: true
          },
          {
            className: "link",
            relevance: 0,
            begin: "\\]\\(",
            end: "\\)",
            excludeBegin: true,
            excludeEnd: true
          },
          {
            className: "symbol",
            relevance: 0,
            begin: "\\]\\[",
            end: "\\]",
            excludeBegin: true,
            excludeEnd: true
          }
        ]
      };
      const BOLD = {
        className: "strong",
        contains: [],
        // defined later
        variants: [
          {
            begin: /_{2}/,
            end: /_{2}/
          },
          {
            begin: /\*{2}/,
            end: /\*{2}/
          }
        ]
      };
      const ITALIC = {
        className: "emphasis",
        contains: [],
        // defined later
        variants: [
          {
            begin: /\*(?!\*)/,
            end: /\*/
          },
          {
            begin: /_(?!_)/,
            end: /_/,
            relevance: 0
          }
        ]
      };
      BOLD.contains.push(ITALIC);
      ITALIC.contains.push(BOLD);
      let CONTAINABLE = [
        INLINE_HTML,
        LINK
      ];
      BOLD.contains = BOLD.contains.concat(CONTAINABLE);
      ITALIC.contains = ITALIC.contains.concat(CONTAINABLE);
      CONTAINABLE = CONTAINABLE.concat(BOLD, ITALIC);
      const HEADER = {
        className: "section",
        variants: [
          {
            begin: "^#{1,6}",
            end: "$",
            contains: CONTAINABLE
          },
          {
            begin: "(?=^.+?\\n[=-]{2,}$)",
            contains: [
              {
                begin: "^[=-]*$"
              },
              {
                begin: "^",
                end: "\\n",
                contains: CONTAINABLE
              }
            ]
          }
        ]
      };
      const BLOCKQUOTE = {
        className: "quote",
        begin: "^>\\s+",
        contains: CONTAINABLE,
        end: "$"
      };
      return {
        name: "Markdown",
        aliases: [
          "md",
          "mkdown",
          "mkd"
        ],
        contains: [
          HEADER,
          INLINE_HTML,
          LIST,
          BOLD,
          ITALIC,
          BLOCKQUOTE,
          CODE,
          HORIZONTAL_RULE,
          LINK,
          LINK_REFERENCE
        ]
      };
    }
    module.exports = markdown;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/dart.js
var require_dart = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/dart.js"(exports, module) {
    init_process_shim();
    function dart(hljs5) {
      const SUBST = {
        className: "subst",
        variants: [{
          begin: "\\$[A-Za-z0-9_]+"
        }]
      };
      const BRACED_SUBST = {
        className: "subst",
        variants: [{
          begin: /\$\{/,
          end: /\}/
        }],
        keywords: "true false null this is new super"
      };
      const STRING = {
        className: "string",
        variants: [
          {
            begin: "r'''",
            end: "'''"
          },
          {
            begin: 'r"""',
            end: '"""'
          },
          {
            begin: "r'",
            end: "'",
            illegal: "\\n"
          },
          {
            begin: 'r"',
            end: '"',
            illegal: "\\n"
          },
          {
            begin: "'''",
            end: "'''",
            contains: [
              hljs5.BACKSLASH_ESCAPE,
              SUBST,
              BRACED_SUBST
            ]
          },
          {
            begin: '"""',
            end: '"""',
            contains: [
              hljs5.BACKSLASH_ESCAPE,
              SUBST,
              BRACED_SUBST
            ]
          },
          {
            begin: "'",
            end: "'",
            illegal: "\\n",
            contains: [
              hljs5.BACKSLASH_ESCAPE,
              SUBST,
              BRACED_SUBST
            ]
          },
          {
            begin: '"',
            end: '"',
            illegal: "\\n",
            contains: [
              hljs5.BACKSLASH_ESCAPE,
              SUBST,
              BRACED_SUBST
            ]
          }
        ]
      };
      BRACED_SUBST.contains = [
        hljs5.C_NUMBER_MODE,
        STRING
      ];
      const BUILT_IN_TYPES = [
        // dart:core
        "Comparable",
        "DateTime",
        "Duration",
        "Function",
        "Iterable",
        "Iterator",
        "List",
        "Map",
        "Match",
        "Object",
        "Pattern",
        "RegExp",
        "Set",
        "Stopwatch",
        "String",
        "StringBuffer",
        "StringSink",
        "Symbol",
        "Type",
        "Uri",
        "bool",
        "double",
        "int",
        "num",
        // dart:html
        "Element",
        "ElementList"
      ];
      const NULLABLE_BUILT_IN_TYPES = BUILT_IN_TYPES.map((e9) => `${e9}?`);
      const KEYWORDS3 = {
        keyword: "abstract as assert async await break case catch class const continue covariant default deferred do dynamic else enum export extends extension external factory false final finally for Function get hide if implements import in inferface is late library mixin new null on operator part required rethrow return set show static super switch sync this throw true try typedef var void while with yield",
        built_in: BUILT_IN_TYPES.concat(NULLABLE_BUILT_IN_TYPES).concat([
          // dart:core
          "Never",
          "Null",
          "dynamic",
          "print",
          // dart:html
          "document",
          "querySelector",
          "querySelectorAll",
          "window"
        ]),
        $pattern: /[A-Za-z][A-Za-z0-9_]*\??/
      };
      return {
        name: "Dart",
        keywords: KEYWORDS3,
        contains: [
          STRING,
          hljs5.COMMENT(
            /\/\*\*(?!\/)/,
            /\*\//,
            {
              subLanguage: "markdown",
              relevance: 0
            }
          ),
          hljs5.COMMENT(
            /\/{3,} ?/,
            /$/,
            {
              contains: [{
                subLanguage: "markdown",
                begin: ".",
                end: "$",
                relevance: 0
              }]
            }
          ),
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          {
            className: "class",
            beginKeywords: "class interface",
            end: /\{/,
            excludeEnd: true,
            contains: [
              {
                beginKeywords: "extends implements"
              },
              hljs5.UNDERSCORE_TITLE_MODE
            ]
          },
          hljs5.C_NUMBER_MODE,
          {
            className: "meta",
            begin: "@[A-Za-z]+"
          },
          {
            begin: "=>"
            // No markup, just a relevance booster
          }
        ]
      };
    }
    module.exports = dart;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/delphi.js
var require_delphi = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/delphi.js"(exports, module) {
    init_process_shim();
    function delphi(hljs5) {
      const KEYWORDS3 = "exports register file shl array record property for mod while set ally label uses raise not stored class safecall var interface or private static exit index inherited to else stdcall override shr asm far resourcestring finalization packed virtual out and protected library do xorwrite goto near function end div overload object unit begin string on inline repeat until destructor write message program with read initialization except default nil if case cdecl in downto threadvar of try pascal const external constructor type public then implementation finally published procedure absolute reintroduce operator as is abstract alias assembler bitpacked break continue cppdecl cvar enumerator experimental platform deprecated unimplemented dynamic export far16 forward generic helper implements interrupt iochecks local name nodefault noreturn nostackframe oldfpccall otherwise saveregisters softfloat specialize strict unaligned varargs ";
      const COMMENT_MODES = [
        hljs5.C_LINE_COMMENT_MODE,
        hljs5.COMMENT(/\{/, /\}/, {
          relevance: 0
        }),
        hljs5.COMMENT(/\(\*/, /\*\)/, {
          relevance: 10
        })
      ];
      const DIRECTIVE = {
        className: "meta",
        variants: [
          {
            begin: /\{\$/,
            end: /\}/
          },
          {
            begin: /\(\*\$/,
            end: /\*\)/
          }
        ]
      };
      const STRING = {
        className: "string",
        begin: /'/,
        end: /'/,
        contains: [{
          begin: /''/
        }]
      };
      const NUMBER = {
        className: "number",
        relevance: 0,
        // Source: https://www.freepascal.org/docs-html/ref/refse6.html
        variants: [
          {
            // Hexadecimal notation, e.g., $7F.
            begin: "\\$[0-9A-Fa-f]+"
          },
          {
            // Octal notation, e.g., &42.
            begin: "&[0-7]+"
          },
          {
            // Binary notation, e.g., %1010.
            begin: "%[01]+"
          }
        ]
      };
      const CHAR_STRING = {
        className: "string",
        begin: /(#\d+)+/
      };
      const CLASS = {
        begin: hljs5.IDENT_RE + "\\s*=\\s*class\\s*\\(",
        returnBegin: true,
        contains: [hljs5.TITLE_MODE]
      };
      const FUNCTION = {
        className: "function",
        beginKeywords: "function constructor destructor procedure",
        end: /[:;]/,
        keywords: "function constructor|10 destructor|10 procedure|10",
        contains: [
          hljs5.TITLE_MODE,
          {
            className: "params",
            begin: /\(/,
            end: /\)/,
            keywords: KEYWORDS3,
            contains: [
              STRING,
              CHAR_STRING,
              DIRECTIVE
            ].concat(COMMENT_MODES)
          },
          DIRECTIVE
        ].concat(COMMENT_MODES)
      };
      return {
        name: "Delphi",
        aliases: [
          "dpr",
          "dfm",
          "pas",
          "pascal",
          "freepascal",
          "lazarus",
          "lpr",
          "lfm"
        ],
        case_insensitive: true,
        keywords: KEYWORDS3,
        illegal: /"|\$[G-Zg-z]|\/\*|<\/|\|/,
        contains: [
          STRING,
          CHAR_STRING,
          hljs5.NUMBER_MODE,
          NUMBER,
          CLASS,
          FUNCTION,
          DIRECTIVE
        ].concat(COMMENT_MODES)
      };
    }
    module.exports = delphi;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/diff.js
var require_diff = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/diff.js"(exports, module) {
    init_process_shim();
    function diff(hljs5) {
      return {
        name: "Diff",
        aliases: ["patch"],
        contains: [
          {
            className: "meta",
            relevance: 10,
            variants: [
              {
                begin: /^@@ +-\d+,\d+ +\+\d+,\d+ +@@/
              },
              {
                begin: /^\*\*\* +\d+,\d+ +\*\*\*\*$/
              },
              {
                begin: /^--- +\d+,\d+ +----$/
              }
            ]
          },
          {
            className: "comment",
            variants: [
              {
                begin: /Index: /,
                end: /$/
              },
              {
                begin: /^index/,
                end: /$/
              },
              {
                begin: /={3,}/,
                end: /$/
              },
              {
                begin: /^-{3}/,
                end: /$/
              },
              {
                begin: /^\*{3} /,
                end: /$/
              },
              {
                begin: /^\+{3}/,
                end: /$/
              },
              {
                begin: /^\*{15}$/
              },
              {
                begin: /^diff --git/,
                end: /$/
              }
            ]
          },
          {
            className: "addition",
            begin: /^\+/,
            end: /$/
          },
          {
            className: "deletion",
            begin: /^-/,
            end: /$/
          },
          {
            className: "addition",
            begin: /^!/,
            end: /$/
          }
        ]
      };
    }
    module.exports = diff;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/django.js
var require_django = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/django.js"(exports, module) {
    init_process_shim();
    function django(hljs5) {
      const FILTER = {
        begin: /\|[A-Za-z]+:?/,
        keywords: {
          name: "truncatewords removetags linebreaksbr yesno get_digit timesince random striptags filesizeformat escape linebreaks length_is ljust rjust cut urlize fix_ampersands title floatformat capfirst pprint divisibleby add make_list unordered_list urlencode timeuntil urlizetrunc wordcount stringformat linenumbers slice date dictsort dictsortreversed default_if_none pluralize lower join center default truncatewords_html upper length phone2numeric wordwrap time addslashes slugify first escapejs force_escape iriencode last safe safeseq truncatechars localize unlocalize localtime utc timezone"
        },
        contains: [
          hljs5.QUOTE_STRING_MODE,
          hljs5.APOS_STRING_MODE
        ]
      };
      return {
        name: "Django",
        aliases: ["jinja"],
        case_insensitive: true,
        subLanguage: "xml",
        contains: [
          hljs5.COMMENT(/\{%\s*comment\s*%\}/, /\{%\s*endcomment\s*%\}/),
          hljs5.COMMENT(/\{#/, /#\}/),
          {
            className: "template-tag",
            begin: /\{%/,
            end: /%\}/,
            contains: [{
              className: "name",
              begin: /\w+/,
              keywords: {
                name: "comment endcomment load templatetag ifchanged endifchanged if endif firstof for endfor ifnotequal endifnotequal widthratio extends include spaceless endspaceless regroup ifequal endifequal ssi now with cycle url filter endfilter debug block endblock else autoescape endautoescape csrf_token empty elif endwith static trans blocktrans endblocktrans get_static_prefix get_media_prefix plural get_current_language language get_available_languages get_current_language_bidi get_language_info get_language_info_list localize endlocalize localtime endlocaltime timezone endtimezone get_current_timezone verbatim"
              },
              starts: {
                endsWithParent: true,
                keywords: "in by as",
                contains: [FILTER],
                relevance: 0
              }
            }]
          },
          {
            className: "template-variable",
            begin: /\{\{/,
            end: /\}\}/,
            contains: [FILTER]
          }
        ]
      };
    }
    module.exports = django;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/dns.js
var require_dns = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/dns.js"(exports, module) {
    init_process_shim();
    function dns(hljs5) {
      return {
        name: "DNS Zone",
        aliases: [
          "bind",
          "zone"
        ],
        keywords: {
          keyword: "IN A AAAA AFSDB APL CAA CDNSKEY CDS CERT CNAME DHCID DLV DNAME DNSKEY DS HIP IPSECKEY KEY KX LOC MX NAPTR NS NSEC NSEC3 NSEC3PARAM PTR RRSIG RP SIG SOA SRV SSHFP TA TKEY TLSA TSIG TXT"
        },
        contains: [
          hljs5.COMMENT(";", "$", {
            relevance: 0
          }),
          {
            className: "meta",
            begin: /^\$(TTL|GENERATE|INCLUDE|ORIGIN)\b/
          },
          // IPv6
          {
            className: "number",
            begin: "((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))\\b"
          },
          // IPv4
          {
            className: "number",
            begin: "((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])\\b"
          },
          hljs5.inherit(hljs5.NUMBER_MODE, {
            begin: /\b\d+[dhwm]?/
          })
        ]
      };
    }
    module.exports = dns;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/dockerfile.js
var require_dockerfile = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/dockerfile.js"(exports, module) {
    init_process_shim();
    function dockerfile(hljs5) {
      return {
        name: "Dockerfile",
        aliases: ["docker"],
        case_insensitive: true,
        keywords: "from maintainer expose env arg user onbuild stopsignal",
        contains: [
          hljs5.HASH_COMMENT_MODE,
          hljs5.APOS_STRING_MODE,
          hljs5.QUOTE_STRING_MODE,
          hljs5.NUMBER_MODE,
          {
            beginKeywords: "run cmd entrypoint volume add copy workdir label healthcheck shell",
            starts: {
              end: /[^\\]$/,
              subLanguage: "bash"
            }
          }
        ],
        illegal: "</"
      };
    }
    module.exports = dockerfile;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/dos.js
var require_dos = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/dos.js"(exports, module) {
    init_process_shim();
    function dos(hljs5) {
      const COMMENT = hljs5.COMMENT(
        /^\s*@?rem\b/,
        /$/,
        {
          relevance: 10
        }
      );
      const LABEL = {
        className: "symbol",
        begin: "^\\s*[A-Za-z._?][A-Za-z0-9_$#@~.?]*(:|\\s+label)",
        relevance: 0
      };
      return {
        name: "Batch file (DOS)",
        aliases: [
          "bat",
          "cmd"
        ],
        case_insensitive: true,
        illegal: /\/\*/,
        keywords: {
          keyword: "if else goto for in do call exit not exist errorlevel defined equ neq lss leq gtr geq",
          built_in: "prn nul lpt3 lpt2 lpt1 con com4 com3 com2 com1 aux shift cd dir echo setlocal endlocal set pause copy append assoc at attrib break cacls cd chcp chdir chkdsk chkntfs cls cmd color comp compact convert date dir diskcomp diskcopy doskey erase fs find findstr format ftype graftabl help keyb label md mkdir mode more move path pause print popd pushd promt rd recover rem rename replace restore rmdir shift sort start subst time title tree type ver verify vol ping net ipconfig taskkill xcopy ren del"
        },
        contains: [
          {
            className: "variable",
            begin: /%%[^ ]|%[^ ]+?%|![^ ]+?!/
          },
          {
            className: "function",
            begin: LABEL.begin,
            end: "goto:eof",
            contains: [
              hljs5.inherit(hljs5.TITLE_MODE, {
                begin: "([_a-zA-Z]\\w*\\.)*([_a-zA-Z]\\w*:)?[_a-zA-Z]\\w*"
              }),
              COMMENT
            ]
          },
          {
            className: "number",
            begin: "\\b\\d+",
            relevance: 0
          },
          COMMENT
        ]
      };
    }
    module.exports = dos;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/dsconfig.js
var require_dsconfig = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/dsconfig.js"(exports, module) {
    init_process_shim();
    function dsconfig(hljs5) {
      const QUOTED_PROPERTY = {
        className: "string",
        begin: /"/,
        end: /"/
      };
      const APOS_PROPERTY = {
        className: "string",
        begin: /'/,
        end: /'/
      };
      const UNQUOTED_PROPERTY = {
        className: "string",
        begin: /[\w\-?]+:\w+/,
        end: /\W/,
        relevance: 0
      };
      const VALUELESS_PROPERTY = {
        className: "string",
        begin: /\w+(\-\w+)*/,
        end: /(?=\W)/,
        relevance: 0
      };
      return {
        keywords: "dsconfig",
        contains: [
          {
            className: "keyword",
            begin: "^dsconfig",
            end: /\s/,
            excludeEnd: true,
            relevance: 10
          },
          {
            className: "built_in",
            begin: /(list|create|get|set|delete)-(\w+)/,
            end: /\s/,
            excludeEnd: true,
            illegal: "!@#$%^&*()",
            relevance: 10
          },
          {
            className: "built_in",
            begin: /--(\w+)/,
            end: /\s/,
            excludeEnd: true
          },
          QUOTED_PROPERTY,
          APOS_PROPERTY,
          UNQUOTED_PROPERTY,
          VALUELESS_PROPERTY,
          hljs5.HASH_COMMENT_MODE
        ]
      };
    }
    module.exports = dsconfig;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/dts.js
var require_dts = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/dts.js"(exports, module) {
    init_process_shim();
    function dts(hljs5) {
      const STRINGS = {
        className: "string",
        variants: [
          hljs5.inherit(hljs5.QUOTE_STRING_MODE, {
            begin: '((u8?|U)|L)?"'
          }),
          {
            begin: '(u8?|U)?R"',
            end: '"',
            contains: [hljs5.BACKSLASH_ESCAPE]
          },
          {
            begin: "'\\\\?.",
            end: "'",
            illegal: "."
          }
        ]
      };
      const NUMBERS = {
        className: "number",
        variants: [
          {
            begin: "\\b(\\d+(\\.\\d*)?|\\.\\d+)(u|U|l|L|ul|UL|f|F)"
          },
          {
            begin: hljs5.C_NUMBER_RE
          }
        ],
        relevance: 0
      };
      const PREPROCESSOR = {
        className: "meta",
        begin: "#",
        end: "$",
        keywords: {
          "meta-keyword": "if else elif endif define undef ifdef ifndef"
        },
        contains: [
          {
            begin: /\\\n/,
            relevance: 0
          },
          {
            beginKeywords: "include",
            end: "$",
            keywords: {
              "meta-keyword": "include"
            },
            contains: [
              hljs5.inherit(STRINGS, {
                className: "meta-string"
              }),
              {
                className: "meta-string",
                begin: "<",
                end: ">",
                illegal: "\\n"
              }
            ]
          },
          STRINGS,
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE
        ]
      };
      const DTS_REFERENCE = {
        className: "variable",
        begin: /&[a-z\d_]*\b/
      };
      const DTS_KEYWORD = {
        className: "meta-keyword",
        begin: "/[a-z][a-z\\d-]*/"
      };
      const DTS_LABEL = {
        className: "symbol",
        begin: "^\\s*[a-zA-Z_][a-zA-Z\\d_]*:"
      };
      const DTS_CELL_PROPERTY = {
        className: "params",
        begin: "<",
        end: ">",
        contains: [
          NUMBERS,
          DTS_REFERENCE
        ]
      };
      const DTS_NODE = {
        className: "class",
        begin: /[a-zA-Z_][a-zA-Z\d_@]*\s\{/,
        end: /[{;=]/,
        returnBegin: true,
        excludeEnd: true
      };
      const DTS_ROOT_NODE = {
        className: "class",
        begin: "/\\s*\\{",
        end: /\};/,
        relevance: 10,
        contains: [
          DTS_REFERENCE,
          DTS_KEYWORD,
          DTS_LABEL,
          DTS_NODE,
          DTS_CELL_PROPERTY,
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          NUMBERS,
          STRINGS
        ]
      };
      return {
        name: "Device Tree",
        keywords: "",
        contains: [
          DTS_ROOT_NODE,
          DTS_REFERENCE,
          DTS_KEYWORD,
          DTS_LABEL,
          DTS_NODE,
          DTS_CELL_PROPERTY,
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          NUMBERS,
          STRINGS,
          PREPROCESSOR,
          {
            begin: hljs5.IDENT_RE + "::",
            keywords: ""
          }
        ]
      };
    }
    module.exports = dts;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/dust.js
var require_dust = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/dust.js"(exports, module) {
    init_process_shim();
    function dust(hljs5) {
      const EXPRESSION_KEYWORDS = "if eq ne lt lte gt gte select default math sep";
      return {
        name: "Dust",
        aliases: ["dst"],
        case_insensitive: true,
        subLanguage: "xml",
        contains: [
          {
            className: "template-tag",
            begin: /\{[#\/]/,
            end: /\}/,
            illegal: /;/,
            contains: [{
              className: "name",
              begin: /[a-zA-Z\.-]+/,
              starts: {
                endsWithParent: true,
                relevance: 0,
                contains: [hljs5.QUOTE_STRING_MODE]
              }
            }]
          },
          {
            className: "template-variable",
            begin: /\{/,
            end: /\}/,
            illegal: /;/,
            keywords: EXPRESSION_KEYWORDS
          }
        ]
      };
    }
    module.exports = dust;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/ebnf.js
var require_ebnf = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/ebnf.js"(exports, module) {
    init_process_shim();
    function ebnf(hljs5) {
      const commentMode = hljs5.COMMENT(/\(\*/, /\*\)/);
      const nonTerminalMode = {
        className: "attribute",
        begin: /^[ ]*[a-zA-Z]+([\s_-]+[a-zA-Z]+)*/
      };
      const specialSequenceMode = {
        className: "meta",
        begin: /\?.*\?/
      };
      const ruleBodyMode = {
        begin: /=/,
        end: /[.;]/,
        contains: [
          commentMode,
          specialSequenceMode,
          {
            // terminals
            className: "string",
            variants: [
              hljs5.APOS_STRING_MODE,
              hljs5.QUOTE_STRING_MODE,
              {
                begin: "`",
                end: "`"
              }
            ]
          }
        ]
      };
      return {
        name: "Extended Backus-Naur Form",
        illegal: /\S/,
        contains: [
          commentMode,
          nonTerminalMode,
          ruleBodyMode
        ]
      };
    }
    module.exports = ebnf;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/elixir.js
var require_elixir = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/elixir.js"(exports, module) {
    init_process_shim();
    function elixir(hljs5) {
      const ELIXIR_IDENT_RE = "[a-zA-Z_][a-zA-Z0-9_.]*(!|\\?)?";
      const ELIXIR_METHOD_RE = "[a-zA-Z_]\\w*[!?=]?|[-+~]@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?";
      const ELIXIR_KEYWORDS = {
        $pattern: ELIXIR_IDENT_RE,
        keyword: "and false then defined module in return redo retry end for true self when next until do begin unless nil break not case cond alias while ensure or include use alias fn quote require import with|0"
      };
      const SUBST = {
        className: "subst",
        begin: /#\{/,
        end: /\}/,
        keywords: ELIXIR_KEYWORDS
      };
      const NUMBER = {
        className: "number",
        begin: "(\\b0o[0-7_]+)|(\\b0b[01_]+)|(\\b0x[0-9a-fA-F_]+)|(-?\\b[1-9][0-9_]*(\\.[0-9_]+([eE][-+]?[0-9]+)?)?)",
        relevance: 0
      };
      const SIGIL_DELIMITERS = `[/|([{<"']`;
      const LOWERCASE_SIGIL = {
        className: "string",
        begin: "~[a-z](?=" + SIGIL_DELIMITERS + ")",
        contains: [
          {
            endsParent: true,
            contains: [
              {
                contains: [
                  hljs5.BACKSLASH_ESCAPE,
                  SUBST
                ],
                variants: [
                  {
                    begin: /"/,
                    end: /"/
                  },
                  {
                    begin: /'/,
                    end: /'/
                  },
                  {
                    begin: /\//,
                    end: /\//
                  },
                  {
                    begin: /\|/,
                    end: /\|/
                  },
                  {
                    begin: /\(/,
                    end: /\)/
                  },
                  {
                    begin: /\[/,
                    end: /\]/
                  },
                  {
                    begin: /\{/,
                    end: /\}/
                  },
                  {
                    begin: /</,
                    end: />/
                  }
                ]
              }
            ]
          }
        ]
      };
      const UPCASE_SIGIL = {
        className: "string",
        begin: "~[A-Z](?=" + SIGIL_DELIMITERS + ")",
        contains: [
          {
            begin: /"/,
            end: /"/
          },
          {
            begin: /'/,
            end: /'/
          },
          {
            begin: /\//,
            end: /\//
          },
          {
            begin: /\|/,
            end: /\|/
          },
          {
            begin: /\(/,
            end: /\)/
          },
          {
            begin: /\[/,
            end: /\]/
          },
          {
            begin: /\{/,
            end: /\}/
          },
          {
            begin: /</,
            end: />/
          }
        ]
      };
      const STRING = {
        className: "string",
        contains: [
          hljs5.BACKSLASH_ESCAPE,
          SUBST
        ],
        variants: [
          {
            begin: /"""/,
            end: /"""/
          },
          {
            begin: /'''/,
            end: /'''/
          },
          {
            begin: /~S"""/,
            end: /"""/,
            contains: []
            // override default
          },
          {
            begin: /~S"/,
            end: /"/,
            contains: []
            // override default
          },
          {
            begin: /~S'''/,
            end: /'''/,
            contains: []
            // override default
          },
          {
            begin: /~S'/,
            end: /'/,
            contains: []
            // override default
          },
          {
            begin: /'/,
            end: /'/
          },
          {
            begin: /"/,
            end: /"/
          }
        ]
      };
      const FUNCTION = {
        className: "function",
        beginKeywords: "def defp defmacro",
        end: /\B\b/,
        // the mode is ended by the title
        contains: [
          hljs5.inherit(hljs5.TITLE_MODE, {
            begin: ELIXIR_IDENT_RE,
            endsParent: true
          })
        ]
      };
      const CLASS = hljs5.inherit(FUNCTION, {
        className: "class",
        beginKeywords: "defimpl defmodule defprotocol defrecord",
        end: /\bdo\b|$|;/
      });
      const ELIXIR_DEFAULT_CONTAINS = [
        STRING,
        UPCASE_SIGIL,
        LOWERCASE_SIGIL,
        hljs5.HASH_COMMENT_MODE,
        CLASS,
        FUNCTION,
        {
          begin: "::"
        },
        {
          className: "symbol",
          begin: ":(?![\\s:])",
          contains: [
            STRING,
            {
              begin: ELIXIR_METHOD_RE
            }
          ],
          relevance: 0
        },
        {
          className: "symbol",
          begin: ELIXIR_IDENT_RE + ":(?!:)",
          relevance: 0
        },
        NUMBER,
        {
          className: "variable",
          begin: "(\\$\\W)|((\\$|@@?)(\\w+))"
        },
        {
          begin: "->"
        },
        {
          // regexp container
          begin: "(" + hljs5.RE_STARTERS_RE + ")\\s*",
          contains: [
            hljs5.HASH_COMMENT_MODE,
            {
              // to prevent false regex triggers for the division function:
              // /:
              begin: /\/: (?=\d+\s*[,\]])/,
              relevance: 0,
              contains: [NUMBER]
            },
            {
              className: "regexp",
              illegal: "\\n",
              contains: [
                hljs5.BACKSLASH_ESCAPE,
                SUBST
              ],
              variants: [
                {
                  begin: "/",
                  end: "/[a-z]*"
                },
                {
                  begin: "%r\\[",
                  end: "\\][a-z]*"
                }
              ]
            }
          ],
          relevance: 0
        }
      ];
      SUBST.contains = ELIXIR_DEFAULT_CONTAINS;
      return {
        name: "Elixir",
        keywords: ELIXIR_KEYWORDS,
        contains: ELIXIR_DEFAULT_CONTAINS
      };
    }
    module.exports = elixir;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/elm.js
var require_elm = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/elm.js"(exports, module) {
    init_process_shim();
    function elm(hljs5) {
      const COMMENT = {
        variants: [
          hljs5.COMMENT("--", "$"),
          hljs5.COMMENT(
            /\{-/,
            /-\}/,
            {
              contains: ["self"]
            }
          )
        ]
      };
      const CONSTRUCTOR = {
        className: "type",
        begin: "\\b[A-Z][\\w']*",
        // TODO: other constructors (built-in, infix).
        relevance: 0
      };
      const LIST = {
        begin: "\\(",
        end: "\\)",
        illegal: '"',
        contains: [
          {
            className: "type",
            begin: "\\b[A-Z][\\w]*(\\((\\.\\.|,|\\w+)\\))?"
          },
          COMMENT
        ]
      };
      const RECORD = {
        begin: /\{/,
        end: /\}/,
        contains: LIST.contains
      };
      const CHARACTER = {
        className: "string",
        begin: "'\\\\?.",
        end: "'",
        illegal: "."
      };
      return {
        name: "Elm",
        keywords: "let in if then else case of where module import exposing type alias as infix infixl infixr port effect command subscription",
        contains: [
          // Top-level constructions.
          {
            beginKeywords: "port effect module",
            end: "exposing",
            keywords: "port effect module where command subscription exposing",
            contains: [
              LIST,
              COMMENT
            ],
            illegal: "\\W\\.|;"
          },
          {
            begin: "import",
            end: "$",
            keywords: "import as exposing",
            contains: [
              LIST,
              COMMENT
            ],
            illegal: "\\W\\.|;"
          },
          {
            begin: "type",
            end: "$",
            keywords: "type alias",
            contains: [
              CONSTRUCTOR,
              LIST,
              RECORD,
              COMMENT
            ]
          },
          {
            beginKeywords: "infix infixl infixr",
            end: "$",
            contains: [
              hljs5.C_NUMBER_MODE,
              COMMENT
            ]
          },
          {
            begin: "port",
            end: "$",
            keywords: "port",
            contains: [COMMENT]
          },
          // Literals and names.
          CHARACTER,
          hljs5.QUOTE_STRING_MODE,
          hljs5.C_NUMBER_MODE,
          CONSTRUCTOR,
          hljs5.inherit(hljs5.TITLE_MODE, {
            begin: "^[_a-z][\\w']*"
          }),
          COMMENT,
          {
            begin: "->|<-"
          }
          // No markup, relevance booster
        ],
        illegal: /;/
      };
    }
    module.exports = elm;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/ruby.js
var require_ruby = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/ruby.js"(exports, module) {
    init_process_shim();
    function source(re2) {
      if (!re2) return null;
      if (typeof re2 === "string") return re2;
      return re2.source;
    }
    function lookahead(re2) {
      return concat("(?=", re2, ")");
    }
    function concat(...args) {
      const joined = args.map((x2) => source(x2)).join("");
      return joined;
    }
    function ruby(hljs5) {
      const RUBY_METHOD_RE = "([a-zA-Z_]\\w*[!?=]?|[-+~]@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?)";
      const RUBY_KEYWORDS = {
        keyword: "and then defined module in return redo if BEGIN retry end for self when next until do begin unless END rescue else break undef not super class case require yield alias while ensure elsif or include attr_reader attr_writer attr_accessor __FILE__",
        built_in: "proc lambda",
        literal: "true false nil"
      };
      const YARDOCTAG = {
        className: "doctag",
        begin: "@[A-Za-z]+"
      };
      const IRB_OBJECT = {
        begin: "#<",
        end: ">"
      };
      const COMMENT_MODES = [
        hljs5.COMMENT(
          "#",
          "$",
          {
            contains: [YARDOCTAG]
          }
        ),
        hljs5.COMMENT(
          "^=begin",
          "^=end",
          {
            contains: [YARDOCTAG],
            relevance: 10
          }
        ),
        hljs5.COMMENT("^__END__", "\\n$")
      ];
      const SUBST = {
        className: "subst",
        begin: /#\{/,
        end: /\}/,
        keywords: RUBY_KEYWORDS
      };
      const STRING = {
        className: "string",
        contains: [
          hljs5.BACKSLASH_ESCAPE,
          SUBST
        ],
        variants: [
          {
            begin: /'/,
            end: /'/
          },
          {
            begin: /"/,
            end: /"/
          },
          {
            begin: /`/,
            end: /`/
          },
          {
            begin: /%[qQwWx]?\(/,
            end: /\)/
          },
          {
            begin: /%[qQwWx]?\[/,
            end: /\]/
          },
          {
            begin: /%[qQwWx]?\{/,
            end: /\}/
          },
          {
            begin: /%[qQwWx]?</,
            end: />/
          },
          {
            begin: /%[qQwWx]?\//,
            end: /\//
          },
          {
            begin: /%[qQwWx]?%/,
            end: /%/
          },
          {
            begin: /%[qQwWx]?-/,
            end: /-/
          },
          {
            begin: /%[qQwWx]?\|/,
            end: /\|/
          },
          // in the following expressions, \B in the beginning suppresses recognition of ?-sequences
          // where ? is the last character of a preceding identifier, as in: `func?4`
          {
            begin: /\B\?(\\\d{1,3})/
          },
          {
            begin: /\B\?(\\x[A-Fa-f0-9]{1,2})/
          },
          {
            begin: /\B\?(\\u\{?[A-Fa-f0-9]{1,6}\}?)/
          },
          {
            begin: /\B\?(\\M-\\C-|\\M-\\c|\\c\\M-|\\M-|\\C-\\M-)[\x20-\x7e]/
          },
          {
            begin: /\B\?\\(c|C-)[\x20-\x7e]/
          },
          {
            begin: /\B\?\\?\S/
          },
          {
            // heredocs
            begin: /<<[-~]?'?(\w+)\n(?:[^\n]*\n)*?\s*\1\b/,
            returnBegin: true,
            contains: [
              {
                begin: /<<[-~]?'?/
              },
              hljs5.END_SAME_AS_BEGIN({
                begin: /(\w+)/,
                end: /(\w+)/,
                contains: [
                  hljs5.BACKSLASH_ESCAPE,
                  SUBST
                ]
              })
            ]
          }
        ]
      };
      const decimal = "[1-9](_?[0-9])*|0";
      const digits = "[0-9](_?[0-9])*";
      const NUMBER = {
        className: "number",
        relevance: 0,
        variants: [
          // decimal integer/float, optionally exponential or rational, optionally imaginary
          {
            begin: `\\b(${decimal})(\\.(${digits}))?([eE][+-]?(${digits})|r)?i?\\b`
          },
          // explicit decimal/binary/octal/hexadecimal integer,
          // optionally rational and/or imaginary
          {
            begin: "\\b0[dD][0-9](_?[0-9])*r?i?\\b"
          },
          {
            begin: "\\b0[bB][0-1](_?[0-1])*r?i?\\b"
          },
          {
            begin: "\\b0[oO][0-7](_?[0-7])*r?i?\\b"
          },
          {
            begin: "\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*r?i?\\b"
          },
          // 0-prefixed implicit octal integer, optionally rational and/or imaginary
          {
            begin: "\\b0(_?[0-7])+r?i?\\b"
          }
        ]
      };
      const PARAMS = {
        className: "params",
        begin: "\\(",
        end: "\\)",
        endsParent: true,
        keywords: RUBY_KEYWORDS
      };
      const RUBY_DEFAULT_CONTAINS = [
        STRING,
        {
          className: "class",
          beginKeywords: "class module",
          end: "$|;",
          illegal: /=/,
          contains: [
            hljs5.inherit(hljs5.TITLE_MODE, {
              begin: "[A-Za-z_]\\w*(::\\w+)*(\\?|!)?"
            }),
            {
              begin: "<\\s*",
              contains: [
                {
                  begin: "(" + hljs5.IDENT_RE + "::)?" + hljs5.IDENT_RE,
                  // we already get points for <, we don't need poitns
                  // for the name also
                  relevance: 0
                }
              ]
            }
          ].concat(COMMENT_MODES)
        },
        {
          className: "function",
          // def method_name(
          // def method_name;
          // def method_name (end of line)
          begin: concat(/def\s+/, lookahead(RUBY_METHOD_RE + "\\s*(\\(|;|$)")),
          relevance: 0,
          // relevance comes from kewords
          keywords: "def",
          end: "$|;",
          contains: [
            hljs5.inherit(hljs5.TITLE_MODE, {
              begin: RUBY_METHOD_RE
            }),
            PARAMS
          ].concat(COMMENT_MODES)
        },
        {
          // swallow namespace qualifiers before symbols
          begin: hljs5.IDENT_RE + "::"
        },
        {
          className: "symbol",
          begin: hljs5.UNDERSCORE_IDENT_RE + "(!|\\?)?:",
          relevance: 0
        },
        {
          className: "symbol",
          begin: ":(?!\\s)",
          contains: [
            STRING,
            {
              begin: RUBY_METHOD_RE
            }
          ],
          relevance: 0
        },
        NUMBER,
        {
          // negative-look forward attemps to prevent false matches like:
          // @ident@ or $ident$ that might indicate this is not ruby at all
          className: "variable",
          begin: `(\\$\\W)|((\\$|@@?)(\\w+))(?=[^@$?])(?![A-Za-z])(?![@$?'])`
        },
        {
          className: "params",
          begin: /\|/,
          end: /\|/,
          relevance: 0,
          // this could be a lot of things (in other languages) other than params
          keywords: RUBY_KEYWORDS
        },
        {
          // regexp container
          begin: "(" + hljs5.RE_STARTERS_RE + "|unless)\\s*",
          keywords: "unless",
          contains: [
            {
              className: "regexp",
              contains: [
                hljs5.BACKSLASH_ESCAPE,
                SUBST
              ],
              illegal: /\n/,
              variants: [
                {
                  begin: "/",
                  end: "/[a-z]*"
                },
                {
                  begin: /%r\{/,
                  end: /\}[a-z]*/
                },
                {
                  begin: "%r\\(",
                  end: "\\)[a-z]*"
                },
                {
                  begin: "%r!",
                  end: "![a-z]*"
                },
                {
                  begin: "%r\\[",
                  end: "\\][a-z]*"
                }
              ]
            }
          ].concat(IRB_OBJECT, COMMENT_MODES),
          relevance: 0
        }
      ].concat(IRB_OBJECT, COMMENT_MODES);
      SUBST.contains = RUBY_DEFAULT_CONTAINS;
      PARAMS.contains = RUBY_DEFAULT_CONTAINS;
      const SIMPLE_PROMPT = "[>?]>";
      const DEFAULT_PROMPT = "[\\w#]+\\(\\w+\\):\\d+:\\d+>";
      const RVM_PROMPT = "(\\w+-)?\\d+\\.\\d+\\.\\d+(p\\d+)?[^\\d][^>]+>";
      const IRB_DEFAULT = [
        {
          begin: /^\s*=>/,
          starts: {
            end: "$",
            contains: RUBY_DEFAULT_CONTAINS
          }
        },
        {
          className: "meta",
          begin: "^(" + SIMPLE_PROMPT + "|" + DEFAULT_PROMPT + "|" + RVM_PROMPT + ")(?=[ ])",
          starts: {
            end: "$",
            contains: RUBY_DEFAULT_CONTAINS
          }
        }
      ];
      COMMENT_MODES.unshift(IRB_OBJECT);
      return {
        name: "Ruby",
        aliases: [
          "rb",
          "gemspec",
          "podspec",
          "thor",
          "irb"
        ],
        keywords: RUBY_KEYWORDS,
        illegal: /\/\*/,
        contains: [
          hljs5.SHEBANG({
            binary: "ruby"
          })
        ].concat(IRB_DEFAULT).concat(COMMENT_MODES).concat(RUBY_DEFAULT_CONTAINS)
      };
    }
    module.exports = ruby;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/erb.js
var require_erb = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/erb.js"(exports, module) {
    init_process_shim();
    function erb(hljs5) {
      return {
        name: "ERB",
        subLanguage: "xml",
        contains: [
          hljs5.COMMENT("<%#", "%>"),
          {
            begin: "<%[%=-]?",
            end: "[%-]?%>",
            subLanguage: "ruby",
            excludeBegin: true,
            excludeEnd: true
          }
        ]
      };
    }
    module.exports = erb;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/erlang-repl.js
var require_erlang_repl = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/erlang-repl.js"(exports, module) {
    init_process_shim();
    function source(re2) {
      if (!re2) return null;
      if (typeof re2 === "string") return re2;
      return re2.source;
    }
    function concat(...args) {
      const joined = args.map((x2) => source(x2)).join("");
      return joined;
    }
    function erlangRepl(hljs5) {
      return {
        name: "Erlang REPL",
        keywords: {
          built_in: "spawn spawn_link self",
          keyword: "after and andalso|10 band begin bnot bor bsl bsr bxor case catch cond div end fun if let not of or orelse|10 query receive rem try when xor"
        },
        contains: [
          {
            className: "meta",
            begin: "^[0-9]+> ",
            relevance: 10
          },
          hljs5.COMMENT("%", "$"),
          {
            className: "number",
            begin: "\\b(\\d+(_\\d+)*#[a-fA-F0-9]+(_[a-fA-F0-9]+)*|\\d+(_\\d+)*(\\.\\d+(_\\d+)*)?([eE][-+]?\\d+)?)",
            relevance: 0
          },
          hljs5.APOS_STRING_MODE,
          hljs5.QUOTE_STRING_MODE,
          {
            begin: concat(
              /\?(::)?/,
              /([A-Z]\w*)/,
              // at least one identifier
              /((::)[A-Z]\w*)*/
              // perhaps more
            )
          },
          {
            begin: "->"
          },
          {
            begin: "ok"
          },
          {
            begin: "!"
          },
          {
            begin: "(\\b[a-z'][a-zA-Z0-9_']*:[a-z'][a-zA-Z0-9_']*)|(\\b[a-z'][a-zA-Z0-9_']*)",
            relevance: 0
          },
          {
            begin: "[A-Z][a-zA-Z0-9_']*",
            relevance: 0
          }
        ]
      };
    }
    module.exports = erlangRepl;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/erlang.js
var require_erlang = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/erlang.js"(exports, module) {
    init_process_shim();
    function erlang(hljs5) {
      const BASIC_ATOM_RE = "[a-z'][a-zA-Z0-9_']*";
      const FUNCTION_NAME_RE = "(" + BASIC_ATOM_RE + ":" + BASIC_ATOM_RE + "|" + BASIC_ATOM_RE + ")";
      const ERLANG_RESERVED = {
        keyword: "after and andalso|10 band begin bnot bor bsl bzr bxor case catch cond div end fun if let not of orelse|10 query receive rem try when xor",
        literal: "false true"
      };
      const COMMENT = hljs5.COMMENT("%", "$");
      const NUMBER = {
        className: "number",
        begin: "\\b(\\d+(_\\d+)*#[a-fA-F0-9]+(_[a-fA-F0-9]+)*|\\d+(_\\d+)*(\\.\\d+(_\\d+)*)?([eE][-+]?\\d+)?)",
        relevance: 0
      };
      const NAMED_FUN = {
        begin: "fun\\s+" + BASIC_ATOM_RE + "/\\d+"
      };
      const FUNCTION_CALL = {
        begin: FUNCTION_NAME_RE + "\\(",
        end: "\\)",
        returnBegin: true,
        relevance: 0,
        contains: [
          {
            begin: FUNCTION_NAME_RE,
            relevance: 0
          },
          {
            begin: "\\(",
            end: "\\)",
            endsWithParent: true,
            returnEnd: true,
            relevance: 0
            // "contains" defined later
          }
        ]
      };
      const TUPLE = {
        begin: /\{/,
        end: /\}/,
        relevance: 0
        // "contains" defined later
      };
      const VAR1 = {
        begin: "\\b_([A-Z][A-Za-z0-9_]*)?",
        relevance: 0
      };
      const VAR2 = {
        begin: "[A-Z][a-zA-Z0-9_]*",
        relevance: 0
      };
      const RECORD_ACCESS = {
        begin: "#" + hljs5.UNDERSCORE_IDENT_RE,
        relevance: 0,
        returnBegin: true,
        contains: [
          {
            begin: "#" + hljs5.UNDERSCORE_IDENT_RE,
            relevance: 0
          },
          {
            begin: /\{/,
            end: /\}/,
            relevance: 0
            // "contains" defined later
          }
        ]
      };
      const BLOCK_STATEMENTS = {
        beginKeywords: "fun receive if try case",
        end: "end",
        keywords: ERLANG_RESERVED
      };
      BLOCK_STATEMENTS.contains = [
        COMMENT,
        NAMED_FUN,
        hljs5.inherit(hljs5.APOS_STRING_MODE, {
          className: ""
        }),
        BLOCK_STATEMENTS,
        FUNCTION_CALL,
        hljs5.QUOTE_STRING_MODE,
        NUMBER,
        TUPLE,
        VAR1,
        VAR2,
        RECORD_ACCESS
      ];
      const BASIC_MODES = [
        COMMENT,
        NAMED_FUN,
        BLOCK_STATEMENTS,
        FUNCTION_CALL,
        hljs5.QUOTE_STRING_MODE,
        NUMBER,
        TUPLE,
        VAR1,
        VAR2,
        RECORD_ACCESS
      ];
      FUNCTION_CALL.contains[1].contains = BASIC_MODES;
      TUPLE.contains = BASIC_MODES;
      RECORD_ACCESS.contains[1].contains = BASIC_MODES;
      const DIRECTIVES = [
        "-module",
        "-record",
        "-undef",
        "-export",
        "-ifdef",
        "-ifndef",
        "-author",
        "-copyright",
        "-doc",
        "-vsn",
        "-import",
        "-include",
        "-include_lib",
        "-compile",
        "-define",
        "-else",
        "-endif",
        "-file",
        "-behaviour",
        "-behavior",
        "-spec"
      ];
      const PARAMS = {
        className: "params",
        begin: "\\(",
        end: "\\)",
        contains: BASIC_MODES
      };
      return {
        name: "Erlang",
        aliases: ["erl"],
        keywords: ERLANG_RESERVED,
        illegal: "(</|\\*=|\\+=|-=|/\\*|\\*/|\\(\\*|\\*\\))",
        contains: [
          {
            className: "function",
            begin: "^" + BASIC_ATOM_RE + "\\s*\\(",
            end: "->",
            returnBegin: true,
            illegal: "\\(|#|//|/\\*|\\\\|:|;",
            contains: [
              PARAMS,
              hljs5.inherit(hljs5.TITLE_MODE, {
                begin: BASIC_ATOM_RE
              })
            ],
            starts: {
              end: ";|\\.",
              keywords: ERLANG_RESERVED,
              contains: BASIC_MODES
            }
          },
          COMMENT,
          {
            begin: "^-",
            end: "\\.",
            relevance: 0,
            excludeEnd: true,
            returnBegin: true,
            keywords: {
              $pattern: "-" + hljs5.IDENT_RE,
              keyword: DIRECTIVES.map((x2) => `${x2}|1.5`).join(" ")
            },
            contains: [PARAMS]
          },
          NUMBER,
          hljs5.QUOTE_STRING_MODE,
          RECORD_ACCESS,
          VAR1,
          VAR2,
          TUPLE,
          {
            begin: /\.$/
          }
          // relevance booster
        ]
      };
    }
    module.exports = erlang;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/excel.js
var require_excel = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/excel.js"(exports, module) {
    init_process_shim();
    function excel(hljs5) {
      return {
        name: "Excel formulae",
        aliases: [
          "xlsx",
          "xls"
        ],
        case_insensitive: true,
        // built-in functions imported from https://web.archive.org/web/20160513042710/https://support.office.com/en-us/article/Excel-functions-alphabetical-b3944572-255d-4efb-bb96-c6d90033e188
        keywords: {
          $pattern: /[a-zA-Z][\w\.]*/,
          built_in: "ABS ACCRINT ACCRINTM ACOS ACOSH ACOT ACOTH AGGREGATE ADDRESS AMORDEGRC AMORLINC AND ARABIC AREAS ASC ASIN ASINH ATAN ATAN2 ATANH AVEDEV AVERAGE AVERAGEA AVERAGEIF AVERAGEIFS BAHTTEXT BASE BESSELI BESSELJ BESSELK BESSELY BETADIST BETA.DIST BETAINV BETA.INV BIN2DEC BIN2HEX BIN2OCT BINOMDIST BINOM.DIST BINOM.DIST.RANGE BINOM.INV BITAND BITLSHIFT BITOR BITRSHIFT BITXOR CALL CEILING CEILING.MATH CEILING.PRECISE CELL CHAR CHIDIST CHIINV CHITEST CHISQ.DIST CHISQ.DIST.RT CHISQ.INV CHISQ.INV.RT CHISQ.TEST CHOOSE CLEAN CODE COLUMN COLUMNS COMBIN COMBINA COMPLEX CONCAT CONCATENATE CONFIDENCE CONFIDENCE.NORM CONFIDENCE.T CONVERT CORREL COS COSH COT COTH COUNT COUNTA COUNTBLANK COUNTIF COUNTIFS COUPDAYBS COUPDAYS COUPDAYSNC COUPNCD COUPNUM COUPPCD COVAR COVARIANCE.P COVARIANCE.S CRITBINOM CSC CSCH CUBEKPIMEMBER CUBEMEMBER CUBEMEMBERPROPERTY CUBERANKEDMEMBER CUBESET CUBESETCOUNT CUBEVALUE CUMIPMT CUMPRINC DATE DATEDIF DATEVALUE DAVERAGE DAY DAYS DAYS360 DB DBCS DCOUNT DCOUNTA DDB DEC2BIN DEC2HEX DEC2OCT DECIMAL DEGREES DELTA DEVSQ DGET DISC DMAX DMIN DOLLAR DOLLARDE DOLLARFR DPRODUCT DSTDEV DSTDEVP DSUM DURATION DVAR DVARP EDATE EFFECT ENCODEURL EOMONTH ERF ERF.PRECISE ERFC ERFC.PRECISE ERROR.TYPE EUROCONVERT EVEN EXACT EXP EXPON.DIST EXPONDIST FACT FACTDOUBLE FALSE|0 F.DIST FDIST F.DIST.RT FILTERXML FIND FINDB F.INV F.INV.RT FINV FISHER FISHERINV FIXED FLOOR FLOOR.MATH FLOOR.PRECISE FORECAST FORECAST.ETS FORECAST.ETS.CONFINT FORECAST.ETS.SEASONALITY FORECAST.ETS.STAT FORECAST.LINEAR FORMULATEXT FREQUENCY F.TEST FTEST FV FVSCHEDULE GAMMA GAMMA.DIST GAMMADIST GAMMA.INV GAMMAINV GAMMALN GAMMALN.PRECISE GAUSS GCD GEOMEAN GESTEP GETPIVOTDATA GROWTH HARMEAN HEX2BIN HEX2DEC HEX2OCT HLOOKUP HOUR HYPERLINK HYPGEOM.DIST HYPGEOMDIST IF IFERROR IFNA IFS IMABS IMAGINARY IMARGUMENT IMCONJUGATE IMCOS IMCOSH IMCOT IMCSC IMCSCH IMDIV IMEXP IMLN IMLOG10 IMLOG2 IMPOWER IMPRODUCT IMREAL IMSEC IMSECH IMSIN IMSINH IMSQRT IMSUB IMSUM IMTAN INDEX INDIRECT INFO INT INTERCEPT INTRATE IPMT IRR ISBLANK ISERR ISERROR ISEVEN ISFORMULA ISLOGICAL ISNA ISNONTEXT ISNUMBER ISODD ISREF ISTEXT ISO.CEILING ISOWEEKNUM ISPMT JIS KURT LARGE LCM LEFT LEFTB LEN LENB LINEST LN LOG LOG10 LOGEST LOGINV LOGNORM.DIST LOGNORMDIST LOGNORM.INV LOOKUP LOWER MATCH MAX MAXA MAXIFS MDETERM MDURATION MEDIAN MID MIDBs MIN MINIFS MINA MINUTE MINVERSE MIRR MMULT MOD MODE MODE.MULT MODE.SNGL MONTH MROUND MULTINOMIAL MUNIT N NA NEGBINOM.DIST NEGBINOMDIST NETWORKDAYS NETWORKDAYS.INTL NOMINAL NORM.DIST NORMDIST NORMINV NORM.INV NORM.S.DIST NORMSDIST NORM.S.INV NORMSINV NOT NOW NPER NPV NUMBERVALUE OCT2BIN OCT2DEC OCT2HEX ODD ODDFPRICE ODDFYIELD ODDLPRICE ODDLYIELD OFFSET OR PDURATION PEARSON PERCENTILE.EXC PERCENTILE.INC PERCENTILE PERCENTRANK.EXC PERCENTRANK.INC PERCENTRANK PERMUT PERMUTATIONA PHI PHONETIC PI PMT POISSON.DIST POISSON POWER PPMT PRICE PRICEDISC PRICEMAT PROB PRODUCT PROPER PV QUARTILE QUARTILE.EXC QUARTILE.INC QUOTIENT RADIANS RAND RANDBETWEEN RANK.AVG RANK.EQ RANK RATE RECEIVED REGISTER.ID REPLACE REPLACEB REPT RIGHT RIGHTB ROMAN ROUND ROUNDDOWN ROUNDUP ROW ROWS RRI RSQ RTD SEARCH SEARCHB SEC SECH SECOND SERIESSUM SHEET SHEETS SIGN SIN SINH SKEW SKEW.P SLN SLOPE SMALL SQL.REQUEST SQRT SQRTPI STANDARDIZE STDEV STDEV.P STDEV.S STDEVA STDEVP STDEVPA STEYX SUBSTITUTE SUBTOTAL SUM SUMIF SUMIFS SUMPRODUCT SUMSQ SUMX2MY2 SUMX2PY2 SUMXMY2 SWITCH SYD T TAN TANH TBILLEQ TBILLPRICE TBILLYIELD T.DIST T.DIST.2T T.DIST.RT TDIST TEXT TEXTJOIN TIME TIMEVALUE T.INV T.INV.2T TINV TODAY TRANSPOSE TREND TRIM TRIMMEAN TRUE|0 TRUNC T.TEST TTEST TYPE UNICHAR UNICODE UPPER VALUE VAR VAR.P VAR.S VARA VARP VARPA VDB VLOOKUP WEBSERVICE WEEKDAY WEEKNUM WEIBULL WEIBULL.DIST WORKDAY WORKDAY.INTL XIRR XNPV XOR YEAR YEARFRAC YIELD YIELDDISC YIELDMAT Z.TEST ZTEST"
        },
        contains: [
          {
            /* matches a beginning equal sign found in Excel formula examples */
            begin: /^=/,
            end: /[^=]/,
            returnEnd: true,
            illegal: /=/,
            /* only allow single equal sign at front of line */
            relevance: 10
          },
          /* technically, there can be more than 2 letters in column names, but this prevents conflict with some keywords */
          {
            /* matches a reference to a single cell */
            className: "symbol",
            begin: /\b[A-Z]{1,2}\d+\b/,
            end: /[^\d]/,
            excludeEnd: true,
            relevance: 0
          },
          {
            /* matches a reference to a range of cells */
            className: "symbol",
            begin: /[A-Z]{0,2}\d*:[A-Z]{0,2}\d*/,
            relevance: 0
          },
          hljs5.BACKSLASH_ESCAPE,
          hljs5.QUOTE_STRING_MODE,
          {
            className: "number",
            begin: hljs5.NUMBER_RE + "(%)?",
            relevance: 0
          },
          /* Excel formula comments are done by putting the comment in a function call to N() */
          hljs5.COMMENT(
            /\bN\(/,
            /\)/,
            {
              excludeBegin: true,
              excludeEnd: true,
              illegal: /\n/
            }
          )
        ]
      };
    }
    module.exports = excel;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/fix.js
var require_fix = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/fix.js"(exports, module) {
    init_process_shim();
    function fix(hljs5) {
      return {
        name: "FIX",
        contains: [{
          begin: /[^\u2401\u0001]+/,
          end: /[\u2401\u0001]/,
          excludeEnd: true,
          returnBegin: true,
          returnEnd: false,
          contains: [
            {
              begin: /([^\u2401\u0001=]+)/,
              end: /=([^\u2401\u0001=]+)/,
              returnEnd: true,
              returnBegin: false,
              className: "attr"
            },
            {
              begin: /=/,
              end: /([\u2401\u0001])/,
              excludeEnd: true,
              excludeBegin: true,
              className: "string"
            }
          ]
        }],
        case_insensitive: true
      };
    }
    module.exports = fix;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/flix.js
var require_flix = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/flix.js"(exports, module) {
    init_process_shim();
    function flix(hljs5) {
      const CHAR = {
        className: "string",
        begin: /'(.|\\[xXuU][a-zA-Z0-9]+)'/
      };
      const STRING = {
        className: "string",
        variants: [{
          begin: '"',
          end: '"'
        }]
      };
      const NAME = {
        className: "title",
        relevance: 0,
        begin: /[^0-9\n\t "'(),.`{}\[\]:;][^\n\t "'(),.`{}\[\]:;]+|[^0-9\n\t "'(),.`{}\[\]:;=]/
      };
      const METHOD = {
        className: "function",
        beginKeywords: "def",
        end: /[:={\[(\n;]/,
        excludeEnd: true,
        contains: [NAME]
      };
      return {
        name: "Flix",
        keywords: {
          literal: "true false",
          keyword: "case class def else enum if impl import in lat rel index let match namespace switch type yield with"
        },
        contains: [
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          CHAR,
          STRING,
          METHOD,
          hljs5.C_NUMBER_MODE
        ]
      };
    }
    module.exports = flix;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/fortran.js
var require_fortran = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/fortran.js"(exports, module) {
    init_process_shim();
    function source(re2) {
      if (!re2) return null;
      if (typeof re2 === "string") return re2;
      return re2.source;
    }
    function concat(...args) {
      const joined = args.map((x2) => source(x2)).join("");
      return joined;
    }
    function fortran(hljs5) {
      const PARAMS = {
        className: "params",
        begin: "\\(",
        end: "\\)"
      };
      const COMMENT = {
        variants: [
          hljs5.COMMENT("!", "$", {
            relevance: 0
          }),
          // allow FORTRAN 77 style comments
          hljs5.COMMENT("^C[ ]", "$", {
            relevance: 0
          }),
          hljs5.COMMENT("^C$", "$", {
            relevance: 0
          })
        ]
      };
      const OPTIONAL_NUMBER_SUFFIX = /(_[a-z_\d]+)?/;
      const OPTIONAL_NUMBER_EXP = /([de][+-]?\d+)?/;
      const NUMBER = {
        className: "number",
        variants: [
          {
            begin: concat(/\b\d+/, /\.(\d*)/, OPTIONAL_NUMBER_EXP, OPTIONAL_NUMBER_SUFFIX)
          },
          {
            begin: concat(/\b\d+/, OPTIONAL_NUMBER_EXP, OPTIONAL_NUMBER_SUFFIX)
          },
          {
            begin: concat(/\.\d+/, OPTIONAL_NUMBER_EXP, OPTIONAL_NUMBER_SUFFIX)
          }
        ],
        relevance: 0
      };
      const FUNCTION_DEF = {
        className: "function",
        beginKeywords: "subroutine function program",
        illegal: "[${=\\n]",
        contains: [
          hljs5.UNDERSCORE_TITLE_MODE,
          PARAMS
        ]
      };
      const STRING = {
        className: "string",
        relevance: 0,
        variants: [
          hljs5.APOS_STRING_MODE,
          hljs5.QUOTE_STRING_MODE
        ]
      };
      const KEYWORDS3 = {
        literal: ".False. .True.",
        keyword: "kind do concurrent local shared while private call intrinsic where elsewhere type endtype endmodule endselect endinterface end enddo endif if forall endforall only contains default return stop then block endblock endassociate public subroutine|10 function program .and. .or. .not. .le. .eq. .ge. .gt. .lt. goto save else use module select case access blank direct exist file fmt form formatted iostat name named nextrec number opened rec recl sequential status unformatted unit continue format pause cycle exit c_null_char c_alert c_backspace c_form_feed flush wait decimal round iomsg synchronous nopass non_overridable pass protected volatile abstract extends import non_intrinsic value deferred generic final enumerator class associate bind enum c_int c_short c_long c_long_long c_signed_char c_size_t c_int8_t c_int16_t c_int32_t c_int64_t c_int_least8_t c_int_least16_t c_int_least32_t c_int_least64_t c_int_fast8_t c_int_fast16_t c_int_fast32_t c_int_fast64_t c_intmax_t C_intptr_t c_float c_double c_long_double c_float_complex c_double_complex c_long_double_complex c_bool c_char c_null_ptr c_null_funptr c_new_line c_carriage_return c_horizontal_tab c_vertical_tab iso_c_binding c_loc c_funloc c_associated  c_f_pointer c_ptr c_funptr iso_fortran_env character_storage_size error_unit file_storage_size input_unit iostat_end iostat_eor numeric_storage_size output_unit c_f_procpointer ieee_arithmetic ieee_support_underflow_control ieee_get_underflow_mode ieee_set_underflow_mode newunit contiguous recursive pad position action delim readwrite eor advance nml interface procedure namelist include sequence elemental pure impure integer real character complex logical codimension dimension allocatable|10 parameter external implicit|10 none double precision assign intent optional pointer target in out common equivalence data",
        built_in: "alog alog10 amax0 amax1 amin0 amin1 amod cabs ccos cexp clog csin csqrt dabs dacos dasin datan datan2 dcos dcosh ddim dexp dint dlog dlog10 dmax1 dmin1 dmod dnint dsign dsin dsinh dsqrt dtan dtanh float iabs idim idint idnint ifix isign max0 max1 min0 min1 sngl algama cdabs cdcos cdexp cdlog cdsin cdsqrt cqabs cqcos cqexp cqlog cqsin cqsqrt dcmplx dconjg derf derfc dfloat dgamma dimag dlgama iqint qabs qacos qasin qatan qatan2 qcmplx qconjg qcos qcosh qdim qerf qerfc qexp qgamma qimag qlgama qlog qlog10 qmax1 qmin1 qmod qnint qsign qsin qsinh qsqrt qtan qtanh abs acos aimag aint anint asin atan atan2 char cmplx conjg cos cosh exp ichar index int log log10 max min nint sign sin sinh sqrt tan tanh print write dim lge lgt lle llt mod nullify allocate deallocate adjustl adjustr all allocated any associated bit_size btest ceiling count cshift date_and_time digits dot_product eoshift epsilon exponent floor fraction huge iand ibclr ibits ibset ieor ior ishft ishftc lbound len_trim matmul maxexponent maxloc maxval merge minexponent minloc minval modulo mvbits nearest pack present product radix random_number random_seed range repeat reshape rrspacing scale scan selected_int_kind selected_real_kind set_exponent shape size spacing spread sum system_clock tiny transpose trim ubound unpack verify achar iachar transfer dble entry dprod cpu_time command_argument_count get_command get_command_argument get_environment_variable is_iostat_end ieee_arithmetic ieee_support_underflow_control ieee_get_underflow_mode ieee_set_underflow_mode is_iostat_eor move_alloc new_line selected_char_kind same_type_as extends_type_of acosh asinh atanh bessel_j0 bessel_j1 bessel_jn bessel_y0 bessel_y1 bessel_yn erf erfc erfc_scaled gamma log_gamma hypot norm2 atomic_define atomic_ref execute_command_line leadz trailz storage_size merge_bits bge bgt ble blt dshiftl dshiftr findloc iall iany iparity image_index lcobound ucobound maskl maskr num_images parity popcnt poppar shifta shiftl shiftr this_image sync change team co_broadcast co_max co_min co_sum co_reduce"
      };
      return {
        name: "Fortran",
        case_insensitive: true,
        aliases: [
          "f90",
          "f95"
        ],
        keywords: KEYWORDS3,
        illegal: /\/\*/,
        contains: [
          STRING,
          FUNCTION_DEF,
          // allow `C = value` for assignments so they aren't misdetected
          // as Fortran 77 style comments
          {
            begin: /^C\s*=(?!=)/,
            relevance: 0
          },
          COMMENT,
          NUMBER
        ]
      };
    }
    module.exports = fortran;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/fsharp.js
var require_fsharp = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/fsharp.js"(exports, module) {
    init_process_shim();
    function fsharp(hljs5) {
      const TYPEPARAM = {
        begin: "<",
        end: ">",
        contains: [
          hljs5.inherit(hljs5.TITLE_MODE, {
            begin: /'[a-zA-Z0-9_]+/
          })
        ]
      };
      return {
        name: "F#",
        aliases: ["fs"],
        keywords: "abstract and as assert base begin class default delegate do done downcast downto elif else end exception extern false finally for fun function global if in inherit inline interface internal lazy let match member module mutable namespace new null of open or override private public rec return sig static struct then to true try type upcast use val void when while with yield",
        illegal: /\/\*/,
        contains: [
          {
            // monad builder keywords (matches before non-bang kws)
            className: "keyword",
            begin: /\b(yield|return|let|do)!/
          },
          {
            className: "string",
            begin: '@"',
            end: '"',
            contains: [
              {
                begin: '""'
              }
            ]
          },
          {
            className: "string",
            begin: '"""',
            end: '"""'
          },
          hljs5.COMMENT("\\(\\*(\\s)", "\\*\\)", {
            contains: ["self"]
          }),
          {
            className: "class",
            beginKeywords: "type",
            end: "\\(|=|$",
            excludeEnd: true,
            contains: [
              hljs5.UNDERSCORE_TITLE_MODE,
              TYPEPARAM
            ]
          },
          {
            className: "meta",
            begin: "\\[<",
            end: ">\\]",
            relevance: 10
          },
          {
            className: "symbol",
            begin: "\\B('[A-Za-z])\\b",
            contains: [hljs5.BACKSLASH_ESCAPE]
          },
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.inherit(hljs5.QUOTE_STRING_MODE, {
            illegal: null
          }),
          hljs5.C_NUMBER_MODE
        ]
      };
    }
    module.exports = fsharp;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/gams.js
var require_gams = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/gams.js"(exports, module) {
    init_process_shim();
    function source(re2) {
      if (!re2) return null;
      if (typeof re2 === "string") return re2;
      return re2.source;
    }
    function anyNumberOfTimes(re2) {
      return concat("(", re2, ")*");
    }
    function concat(...args) {
      const joined = args.map((x2) => source(x2)).join("");
      return joined;
    }
    function gams(hljs5) {
      const KEYWORDS3 = {
        keyword: "abort acronym acronyms alias all and assign binary card diag display else eq file files for free ge gt if integer le loop lt maximizing minimizing model models ne negative no not option options or ord positive prod put putpage puttl repeat sameas semicont semiint smax smin solve sos1 sos2 sum system table then until using while xor yes",
        literal: "eps inf na",
        built_in: "abs arccos arcsin arctan arctan2 Beta betaReg binomial ceil centropy cos cosh cvPower div div0 eDist entropy errorf execSeed exp fact floor frac gamma gammaReg log logBeta logGamma log10 log2 mapVal max min mod ncpCM ncpF ncpVUpow ncpVUsin normal pi poly power randBinomial randLinear randTriangle round rPower sigmoid sign signPower sin sinh slexp sllog10 slrec sqexp sqlog10 sqr sqrec sqrt tan tanh trunc uniform uniformInt vcPower bool_and bool_eqv bool_imp bool_not bool_or bool_xor ifThen rel_eq rel_ge rel_gt rel_le rel_lt rel_ne gday gdow ghour gleap gmillisec gminute gmonth gsecond gyear jdate jnow jstart jtime errorLevel execError gamsRelease gamsVersion handleCollect handleDelete handleStatus handleSubmit heapFree heapLimit heapSize jobHandle jobKill jobStatus jobTerminate licenseLevel licenseStatus maxExecError sleep timeClose timeComp timeElapsed timeExec timeStart"
      };
      const PARAMS = {
        className: "params",
        begin: /\(/,
        end: /\)/,
        excludeBegin: true,
        excludeEnd: true
      };
      const SYMBOLS = {
        className: "symbol",
        variants: [
          {
            begin: /=[lgenxc]=/
          },
          {
            begin: /\$/
          }
        ]
      };
      const QSTR = {
        // One-line quoted comment string
        className: "comment",
        variants: [
          {
            begin: "'",
            end: "'"
          },
          {
            begin: '"',
            end: '"'
          }
        ],
        illegal: "\\n",
        contains: [hljs5.BACKSLASH_ESCAPE]
      };
      const ASSIGNMENT = {
        begin: "/",
        end: "/",
        keywords: KEYWORDS3,
        contains: [
          QSTR,
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          hljs5.QUOTE_STRING_MODE,
          hljs5.APOS_STRING_MODE,
          hljs5.C_NUMBER_MODE
        ]
      };
      const COMMENT_WORD = /[a-z0-9&#*=?@\\><:,()$[\]_.{}!+%^-]+/;
      const DESCTEXT = {
        // Parameter/set/variable description text
        begin: /[a-z][a-z0-9_]*(\([a-z0-9_, ]*\))?[ \t]+/,
        excludeBegin: true,
        end: "$",
        endsWithParent: true,
        contains: [
          QSTR,
          ASSIGNMENT,
          {
            className: "comment",
            // one comment word, then possibly more
            begin: concat(
              COMMENT_WORD,
              // [ ] because \s would be too broad (matching newlines)
              anyNumberOfTimes(concat(/[ ]+/, COMMENT_WORD))
            ),
            relevance: 0
          }
        ]
      };
      return {
        name: "GAMS",
        aliases: ["gms"],
        case_insensitive: true,
        keywords: KEYWORDS3,
        contains: [
          hljs5.COMMENT(/^\$ontext/, /^\$offtext/),
          {
            className: "meta",
            begin: "^\\$[a-z0-9]+",
            end: "$",
            returnBegin: true,
            contains: [
              {
                className: "meta-keyword",
                begin: "^\\$[a-z0-9]+"
              }
            ]
          },
          hljs5.COMMENT("^\\*", "$"),
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          hljs5.QUOTE_STRING_MODE,
          hljs5.APOS_STRING_MODE,
          // Declarations
          {
            beginKeywords: "set sets parameter parameters variable variables scalar scalars equation equations",
            end: ";",
            contains: [
              hljs5.COMMENT("^\\*", "$"),
              hljs5.C_LINE_COMMENT_MODE,
              hljs5.C_BLOCK_COMMENT_MODE,
              hljs5.QUOTE_STRING_MODE,
              hljs5.APOS_STRING_MODE,
              ASSIGNMENT,
              DESCTEXT
            ]
          },
          {
            // table environment
            beginKeywords: "table",
            end: ";",
            returnBegin: true,
            contains: [
              {
                // table header row
                beginKeywords: "table",
                end: "$",
                contains: [DESCTEXT]
              },
              hljs5.COMMENT("^\\*", "$"),
              hljs5.C_LINE_COMMENT_MODE,
              hljs5.C_BLOCK_COMMENT_MODE,
              hljs5.QUOTE_STRING_MODE,
              hljs5.APOS_STRING_MODE,
              hljs5.C_NUMBER_MODE
              // Table does not contain DESCTEXT or ASSIGNMENT
            ]
          },
          // Function definitions
          {
            className: "function",
            begin: /^[a-z][a-z0-9_,\-+' ()$]+\.{2}/,
            returnBegin: true,
            contains: [
              {
                // Function title
                className: "title",
                begin: /^[a-z0-9_]+/
              },
              PARAMS,
              SYMBOLS
            ]
          },
          hljs5.C_NUMBER_MODE,
          SYMBOLS
        ]
      };
    }
    module.exports = gams;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/gauss.js
var require_gauss = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/gauss.js"(exports, module) {
    init_process_shim();
    function gauss(hljs5) {
      const KEYWORDS3 = {
        keyword: "bool break call callexe checkinterrupt clear clearg closeall cls comlog compile continue create debug declare delete disable dlibrary dllcall do dos ed edit else elseif enable end endfor endif endp endo errorlog errorlogat expr external fn for format goto gosub graph if keyword let lib library line load loadarray loadexe loadf loadk loadm loadp loads loadx local locate loopnextindex lprint lpwidth lshow matrix msym ndpclex new open output outwidth plot plotsym pop prcsn print printdos proc push retp return rndcon rndmod rndmult rndseed run save saveall screen scroll setarray show sparse stop string struct system trace trap threadfor threadendfor threadbegin threadjoin threadstat threadend until use while winprint ne ge le gt lt and xor or not eq eqv",
        built_in: "abs acf aconcat aeye amax amean AmericanBinomCall AmericanBinomCall_Greeks AmericanBinomCall_ImpVol AmericanBinomPut AmericanBinomPut_Greeks AmericanBinomPut_ImpVol AmericanBSCall AmericanBSCall_Greeks AmericanBSCall_ImpVol AmericanBSPut AmericanBSPut_Greeks AmericanBSPut_ImpVol amin amult annotationGetDefaults annotationSetBkd annotationSetFont annotationSetLineColor annotationSetLineStyle annotationSetLineThickness annualTradingDays arccos arcsin areshape arrayalloc arrayindex arrayinit arraytomat asciiload asclabel astd astds asum atan atan2 atranspose axmargin balance band bandchol bandcholsol bandltsol bandrv bandsolpd bar base10 begwind besselj bessely beta box boxcox cdfBeta cdfBetaInv cdfBinomial cdfBinomialInv cdfBvn cdfBvn2 cdfBvn2e cdfCauchy cdfCauchyInv cdfChic cdfChii cdfChinc cdfChincInv cdfExp cdfExpInv cdfFc cdfFnc cdfFncInv cdfGam cdfGenPareto cdfHyperGeo cdfLaplace cdfLaplaceInv cdfLogistic cdfLogisticInv cdfmControlCreate cdfMvn cdfMvn2e cdfMvnce cdfMvne cdfMvt2e cdfMvtce cdfMvte cdfN cdfN2 cdfNc cdfNegBinomial cdfNegBinomialInv cdfNi cdfPoisson cdfPoissonInv cdfRayleigh cdfRayleighInv cdfTc cdfTci cdfTnc cdfTvn cdfWeibull cdfWeibullInv cdir ceil ChangeDir chdir chiBarSquare chol choldn cholsol cholup chrs close code cols colsf combinate combinated complex con cond conj cons ConScore contour conv convertsatostr convertstrtosa corrm corrms corrvc corrx corrxs cos cosh counts countwts crossprd crout croutp csrcol csrlin csvReadM csvReadSA cumprodc cumsumc curve cvtos datacreate datacreatecomplex datalist dataload dataloop dataopen datasave date datestr datestring datestrymd dayinyr dayofweek dbAddDatabase dbClose dbCommit dbCreateQuery dbExecQuery dbGetConnectOptions dbGetDatabaseName dbGetDriverName dbGetDrivers dbGetHostName dbGetLastErrorNum dbGetLastErrorText dbGetNumericalPrecPolicy dbGetPassword dbGetPort dbGetTableHeaders dbGetTables dbGetUserName dbHasFeature dbIsDriverAvailable dbIsOpen dbIsOpenError dbOpen dbQueryBindValue dbQueryClear dbQueryCols dbQueryExecPrepared dbQueryFetchAllM dbQueryFetchAllSA dbQueryFetchOneM dbQueryFetchOneSA dbQueryFinish dbQueryGetBoundValue dbQueryGetBoundValues dbQueryGetField dbQueryGetLastErrorNum dbQueryGetLastErrorText dbQueryGetLastInsertID dbQueryGetLastQuery dbQueryGetPosition dbQueryIsActive dbQueryIsForwardOnly dbQueryIsNull dbQueryIsSelect dbQueryIsValid dbQueryPrepare dbQueryRows dbQuerySeek dbQuerySeekFirst dbQuerySeekLast dbQuerySeekNext dbQuerySeekPrevious dbQuerySetForwardOnly dbRemoveDatabase dbRollback dbSetConnectOptions dbSetDatabaseName dbSetHostName dbSetNumericalPrecPolicy dbSetPort dbSetUserName dbTransaction DeleteFile delif delrows denseToSp denseToSpRE denToZero design det detl dfft dffti diag diagrv digamma doswin DOSWinCloseall DOSWinOpen dotfeq dotfeqmt dotfge dotfgemt dotfgt dotfgtmt dotfle dotflemt dotflt dotfltmt dotfne dotfnemt draw drop dsCreate dstat dstatmt dstatmtControlCreate dtdate dtday dttime dttodtv dttostr dttoutc dtvnormal dtvtodt dtvtoutc dummy dummybr dummydn eig eigh eighv eigv elapsedTradingDays endwind envget eof eqSolve eqSolvemt eqSolvemtControlCreate eqSolvemtOutCreate eqSolveset erf erfc erfccplx erfcplx error etdays ethsec etstr EuropeanBinomCall EuropeanBinomCall_Greeks EuropeanBinomCall_ImpVol EuropeanBinomPut EuropeanBinomPut_Greeks EuropeanBinomPut_ImpVol EuropeanBSCall EuropeanBSCall_Greeks EuropeanBSCall_ImpVol EuropeanBSPut EuropeanBSPut_Greeks EuropeanBSPut_ImpVol exctsmpl exec execbg exp extern eye fcheckerr fclearerr feq feqmt fflush fft ffti fftm fftmi fftn fge fgemt fgets fgetsa fgetsat fgetst fgt fgtmt fileinfo filesa fle flemt floor flt fltmt fmod fne fnemt fonts fopen formatcv formatnv fputs fputst fseek fstrerror ftell ftocv ftos ftostrC gamma gammacplx gammaii gausset gdaAppend gdaCreate gdaDStat gdaDStatMat gdaGetIndex gdaGetName gdaGetNames gdaGetOrders gdaGetType gdaGetTypes gdaGetVarInfo gdaIsCplx gdaLoad gdaPack gdaRead gdaReadByIndex gdaReadSome gdaReadSparse gdaReadStruct gdaReportVarInfo gdaSave gdaUpdate gdaUpdateAndPack gdaVars gdaWrite gdaWrite32 gdaWriteSome getarray getdims getf getGAUSShome getmatrix getmatrix4D getname getnamef getNextTradingDay getNextWeekDay getnr getorders getpath getPreviousTradingDay getPreviousWeekDay getRow getscalar3D getscalar4D getTrRow getwind glm gradcplx gradMT gradMTm gradMTT gradMTTm gradp graphprt graphset hasimag header headermt hess hessMT hessMTg hessMTgw hessMTm hessMTmw hessMTT hessMTTg hessMTTgw hessMTTm hessMTw hessp hist histf histp hsec imag indcv indexcat indices indices2 indicesf indicesfn indnv indsav integrate1d integrateControlCreate intgrat2 intgrat3 inthp1 inthp2 inthp3 inthp4 inthpControlCreate intquad1 intquad2 intquad3 intrleav intrleavsa intrsect intsimp inv invpd invswp iscplx iscplxf isden isinfnanmiss ismiss key keyav keyw lag lag1 lagn lapEighb lapEighi lapEighvb lapEighvi lapgEig lapgEigh lapgEighv lapgEigv lapgSchur lapgSvdcst lapgSvds lapgSvdst lapSvdcusv lapSvds lapSvdusv ldlp ldlsol linSolve listwise ln lncdfbvn lncdfbvn2 lncdfmvn lncdfn lncdfn2 lncdfnc lnfact lngammacplx lnpdfmvn lnpdfmvt lnpdfn lnpdft loadd loadstruct loadwind loess loessmt loessmtControlCreate log loglog logx logy lower lowmat lowmat1 ltrisol lu lusol machEpsilon make makevars makewind margin matalloc matinit mattoarray maxbytes maxc maxindc maxv maxvec mbesselei mbesselei0 mbesselei1 mbesseli mbesseli0 mbesseli1 meanc median mergeby mergevar minc minindc minv miss missex missrv moment momentd movingave movingaveExpwgt movingaveWgt nextindex nextn nextnevn nextwind ntos null null1 numCombinations ols olsmt olsmtControlCreate olsqr olsqr2 olsqrmt ones optn optnevn orth outtyp pacf packedToSp packr parse pause pdfCauchy pdfChi pdfExp pdfGenPareto pdfHyperGeo pdfLaplace pdfLogistic pdfn pdfPoisson pdfRayleigh pdfWeibull pi pinv pinvmt plotAddArrow plotAddBar plotAddBox plotAddHist plotAddHistF plotAddHistP plotAddPolar plotAddScatter plotAddShape plotAddTextbox plotAddTS plotAddXY plotArea plotBar plotBox plotClearLayout plotContour plotCustomLayout plotGetDefaults plotHist plotHistF plotHistP plotLayout plotLogLog plotLogX plotLogY plotOpenWindow plotPolar plotSave plotScatter plotSetAxesPen plotSetBar plotSetBarFill plotSetBarStacked plotSetBkdColor plotSetFill plotSetGrid plotSetLegend plotSetLineColor plotSetLineStyle plotSetLineSymbol plotSetLineThickness plotSetNewWindow plotSetTitle plotSetWhichYAxis plotSetXAxisShow plotSetXLabel plotSetXRange plotSetXTicInterval plotSetXTicLabel plotSetYAxisShow plotSetYLabel plotSetYRange plotSetZAxisShow plotSetZLabel plotSurface plotTS plotXY polar polychar polyeval polygamma polyint polymake polymat polymroot polymult polyroot pqgwin previousindex princomp printfm printfmt prodc psi putarray putf putvals pvCreate pvGetIndex pvGetParNames pvGetParVector pvLength pvList pvPack pvPacki pvPackm pvPackmi pvPacks pvPacksi pvPacksm pvPacksmi pvPutParVector pvTest pvUnpack QNewton QNewtonmt QNewtonmtControlCreate QNewtonmtOutCreate QNewtonSet QProg QProgmt QProgmtInCreate qqr qqre qqrep qr qre qrep qrsol qrtsol qtyr qtyre qtyrep quantile quantiled qyr qyre qyrep qz rank rankindx readr real reclassify reclassifyCuts recode recserar recsercp recserrc rerun rescale reshape rets rev rfft rffti rfftip rfftn rfftnp rfftp rndBernoulli rndBeta rndBinomial rndCauchy rndChiSquare rndCon rndCreateState rndExp rndGamma rndGeo rndGumbel rndHyperGeo rndi rndKMbeta rndKMgam rndKMi rndKMn rndKMnb rndKMp rndKMu rndKMvm rndLaplace rndLCbeta rndLCgam rndLCi rndLCn rndLCnb rndLCp rndLCu rndLCvm rndLogNorm rndMTu rndMVn rndMVt rndn rndnb rndNegBinomial rndp rndPoisson rndRayleigh rndStateSkip rndu rndvm rndWeibull rndWishart rotater round rows rowsf rref sampleData satostrC saved saveStruct savewind scale scale3d scalerr scalinfnanmiss scalmiss schtoc schur searchsourcepath seekr select selif seqa seqm setdif setdifsa setvars setvwrmode setwind shell shiftr sin singleindex sinh sleep solpd sortc sortcc sortd sorthc sorthcc sortind sortindc sortmc sortr sortrc spBiconjGradSol spChol spConjGradSol spCreate spDenseSubmat spDiagRvMat spEigv spEye spLDL spline spLU spNumNZE spOnes spreadSheetReadM spreadSheetReadSA spreadSheetWrite spScale spSubmat spToDense spTrTDense spTScalar spZeros sqpSolve sqpSolveMT sqpSolveMTControlCreate sqpSolveMTlagrangeCreate sqpSolveMToutCreate sqpSolveSet sqrt statements stdc stdsc stocv stof strcombine strindx strlen strput strrindx strsect strsplit strsplitPad strtodt strtof strtofcplx strtriml strtrimr strtrunc strtruncl strtruncpad strtruncr submat subscat substute subvec sumc sumr surface svd svd1 svd2 svdcusv svds svdusv sysstate tab tan tanh tempname time timedt timestr timeutc title tkf2eps tkf2ps tocart todaydt toeplitz token topolar trapchk trigamma trimr trunc type typecv typef union unionsa uniqindx uniqindxsa unique uniquesa upmat upmat1 upper utctodt utctodtv utrisol vals varCovMS varCovXS varget vargetl varmall varmares varput varputl vartypef vcm vcms vcx vcxs vec vech vecr vector vget view viewxyz vlist vnamecv volume vput vread vtypecv wait waitc walkindex where window writer xlabel xlsGetSheetCount xlsGetSheetSize xlsGetSheetTypes xlsMakeRange xlsReadM xlsReadSA xlsWrite xlsWriteM xlsWriteSA xpnd xtics xy xyz ylabel ytics zeros zeta zlabel ztics cdfEmpirical dot h5create h5open h5read h5readAttribute h5write h5writeAttribute ldl plotAddErrorBar plotAddSurface plotCDFEmpirical plotSetColormap plotSetContourLabels plotSetLegendFont plotSetTextInterpreter plotSetXTicCount plotSetYTicCount plotSetZLevels powerm strjoin sylvester strtrim",
        literal: "DB_AFTER_LAST_ROW DB_ALL_TABLES DB_BATCH_OPERATIONS DB_BEFORE_FIRST_ROW DB_BLOB DB_EVENT_NOTIFICATIONS DB_FINISH_QUERY DB_HIGH_PRECISION DB_LAST_INSERT_ID DB_LOW_PRECISION_DOUBLE DB_LOW_PRECISION_INT32 DB_LOW_PRECISION_INT64 DB_LOW_PRECISION_NUMBERS DB_MULTIPLE_RESULT_SETS DB_NAMED_PLACEHOLDERS DB_POSITIONAL_PLACEHOLDERS DB_PREPARED_QUERIES DB_QUERY_SIZE DB_SIMPLE_LOCKING DB_SYSTEM_TABLES DB_TABLES DB_TRANSACTIONS DB_UNICODE DB_VIEWS __STDIN __STDOUT __STDERR __FILE_DIR"
      };
      const AT_COMMENT_MODE = hljs5.COMMENT("@", "@");
      const PREPROCESSOR = {
        className: "meta",
        begin: "#",
        end: "$",
        keywords: {
          "meta-keyword": "define definecs|10 undef ifdef ifndef iflight ifdllcall ifmac ifos2win ifunix else endif lineson linesoff srcfile srcline"
        },
        contains: [
          {
            begin: /\\\n/,
            relevance: 0
          },
          {
            beginKeywords: "include",
            end: "$",
            keywords: {
              "meta-keyword": "include"
            },
            contains: [
              {
                className: "meta-string",
                begin: '"',
                end: '"',
                illegal: "\\n"
              }
            ]
          },
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          AT_COMMENT_MODE
        ]
      };
      const STRUCT_TYPE = {
        begin: /\bstruct\s+/,
        end: /\s/,
        keywords: "struct",
        contains: [
          {
            className: "type",
            begin: hljs5.UNDERSCORE_IDENT_RE,
            relevance: 0
          }
        ]
      };
      const PARSE_PARAMS = [
        {
          className: "params",
          begin: /\(/,
          end: /\)/,
          excludeBegin: true,
          excludeEnd: true,
          endsWithParent: true,
          relevance: 0,
          contains: [
            {
              // dots
              className: "literal",
              begin: /\.\.\./
            },
            hljs5.C_NUMBER_MODE,
            hljs5.C_BLOCK_COMMENT_MODE,
            AT_COMMENT_MODE,
            STRUCT_TYPE
          ]
        }
      ];
      const FUNCTION_DEF = {
        className: "title",
        begin: hljs5.UNDERSCORE_IDENT_RE,
        relevance: 0
      };
      const DEFINITION = function(beginKeywords, end, inherits) {
        const mode = hljs5.inherit(
          {
            className: "function",
            beginKeywords,
            end,
            excludeEnd: true,
            contains: [].concat(PARSE_PARAMS)
          },
          inherits || {}
        );
        mode.contains.push(FUNCTION_DEF);
        mode.contains.push(hljs5.C_NUMBER_MODE);
        mode.contains.push(hljs5.C_BLOCK_COMMENT_MODE);
        mode.contains.push(AT_COMMENT_MODE);
        return mode;
      };
      const BUILT_IN_REF = {
        // these are explicitly named internal function calls
        className: "built_in",
        begin: "\\b(" + KEYWORDS3.built_in.split(" ").join("|") + ")\\b"
      };
      const STRING_REF = {
        className: "string",
        begin: '"',
        end: '"',
        contains: [hljs5.BACKSLASH_ESCAPE],
        relevance: 0
      };
      const FUNCTION_REF = {
        // className: "fn_ref",
        begin: hljs5.UNDERSCORE_IDENT_RE + "\\s*\\(",
        returnBegin: true,
        keywords: KEYWORDS3,
        relevance: 0,
        contains: [
          {
            beginKeywords: KEYWORDS3.keyword
          },
          BUILT_IN_REF,
          {
            // ambiguously named function calls get a relevance of 0
            className: "built_in",
            begin: hljs5.UNDERSCORE_IDENT_RE,
            relevance: 0
          }
        ]
      };
      const FUNCTION_REF_PARAMS = {
        // className: "fn_ref_params",
        begin: /\(/,
        end: /\)/,
        relevance: 0,
        keywords: {
          built_in: KEYWORDS3.built_in,
          literal: KEYWORDS3.literal
        },
        contains: [
          hljs5.C_NUMBER_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          AT_COMMENT_MODE,
          BUILT_IN_REF,
          FUNCTION_REF,
          STRING_REF,
          "self"
        ]
      };
      FUNCTION_REF.contains.push(FUNCTION_REF_PARAMS);
      return {
        name: "GAUSS",
        aliases: ["gss"],
        case_insensitive: true,
        // language is case-insensitive
        keywords: KEYWORDS3,
        illegal: /(\{[%#]|[%#]\}| <- )/,
        contains: [
          hljs5.C_NUMBER_MODE,
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          AT_COMMENT_MODE,
          STRING_REF,
          PREPROCESSOR,
          {
            className: "keyword",
            begin: /\bexternal (matrix|string|array|sparse matrix|struct|proc|keyword|fn)/
          },
          DEFINITION("proc keyword", ";"),
          DEFINITION("fn", "="),
          {
            beginKeywords: "for threadfor",
            end: /;/,
            // end: /\(/,
            relevance: 0,
            contains: [
              hljs5.C_BLOCK_COMMENT_MODE,
              AT_COMMENT_MODE,
              FUNCTION_REF_PARAMS
            ]
          },
          {
            // custom method guard
            // excludes method names from keyword processing
            variants: [
              {
                begin: hljs5.UNDERSCORE_IDENT_RE + "\\." + hljs5.UNDERSCORE_IDENT_RE
              },
              {
                begin: hljs5.UNDERSCORE_IDENT_RE + "\\s*="
              }
            ],
            relevance: 0
          },
          FUNCTION_REF,
          STRUCT_TYPE
        ]
      };
    }
    module.exports = gauss;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/gcode.js
var require_gcode = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/gcode.js"(exports, module) {
    init_process_shim();
    function gcode(hljs5) {
      const GCODE_IDENT_RE = "[A-Z_][A-Z0-9_.]*";
      const GCODE_CLOSE_RE = "%";
      const GCODE_KEYWORDS = {
        $pattern: GCODE_IDENT_RE,
        keyword: "IF DO WHILE ENDWHILE CALL ENDIF SUB ENDSUB GOTO REPEAT ENDREPEAT EQ LT GT NE GE LE OR XOR"
      };
      const GCODE_START = {
        className: "meta",
        begin: "([O])([0-9]+)"
      };
      const NUMBER = hljs5.inherit(hljs5.C_NUMBER_MODE, {
        begin: "([-+]?((\\.\\d+)|(\\d+)(\\.\\d*)?))|" + hljs5.C_NUMBER_RE
      });
      const GCODE_CODE = [
        hljs5.C_LINE_COMMENT_MODE,
        hljs5.C_BLOCK_COMMENT_MODE,
        hljs5.COMMENT(/\(/, /\)/),
        NUMBER,
        hljs5.inherit(hljs5.APOS_STRING_MODE, {
          illegal: null
        }),
        hljs5.inherit(hljs5.QUOTE_STRING_MODE, {
          illegal: null
        }),
        {
          className: "name",
          begin: "([G])([0-9]+\\.?[0-9]?)"
        },
        {
          className: "name",
          begin: "([M])([0-9]+\\.?[0-9]?)"
        },
        {
          className: "attr",
          begin: "(VC|VS|#)",
          end: "(\\d+)"
        },
        {
          className: "attr",
          begin: "(VZOFX|VZOFY|VZOFZ)"
        },
        {
          className: "built_in",
          begin: "(ATAN|ABS|ACOS|ASIN|SIN|COS|EXP|FIX|FUP|ROUND|LN|TAN)(\\[)",
          contains: [
            NUMBER
          ],
          end: "\\]"
        },
        {
          className: "symbol",
          variants: [
            {
              begin: "N",
              end: "\\d+",
              illegal: "\\W"
            }
          ]
        }
      ];
      return {
        name: "G-code (ISO 6983)",
        aliases: ["nc"],
        // Some implementations (CNC controls) of G-code are interoperable with uppercase and lowercase letters seamlessly.
        // However, most prefer all uppercase and uppercase is customary.
        case_insensitive: true,
        keywords: GCODE_KEYWORDS,
        contains: [
          {
            className: "meta",
            begin: GCODE_CLOSE_RE
          },
          GCODE_START
        ].concat(GCODE_CODE)
      };
    }
    module.exports = gcode;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/gherkin.js
var require_gherkin = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/gherkin.js"(exports, module) {
    init_process_shim();
    function gherkin(hljs5) {
      return {
        name: "Gherkin",
        aliases: ["feature"],
        keywords: "Feature Background Ability Business Need Scenario Scenarios Scenario Outline Scenario Template Examples Given And Then But When",
        contains: [
          {
            className: "symbol",
            begin: "\\*",
            relevance: 0
          },
          {
            className: "meta",
            begin: "@[^@\\s]+"
          },
          {
            begin: "\\|",
            end: "\\|\\w*$",
            contains: [
              {
                className: "string",
                begin: "[^|]+"
              }
            ]
          },
          {
            className: "variable",
            begin: "<",
            end: ">"
          },
          hljs5.HASH_COMMENT_MODE,
          {
            className: "string",
            begin: '"""',
            end: '"""'
          },
          hljs5.QUOTE_STRING_MODE
        ]
      };
    }
    module.exports = gherkin;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/glsl.js
var require_glsl = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/glsl.js"(exports, module) {
    init_process_shim();
    function glsl(hljs5) {
      return {
        name: "GLSL",
        keywords: {
          keyword: (
            // Statements
            "break continue discard do else for if return while switch case default attribute binding buffer ccw centroid centroid varying coherent column_major const cw depth_any depth_greater depth_less depth_unchanged early_fragment_tests equal_spacing flat fractional_even_spacing fractional_odd_spacing highp in index inout invariant invocations isolines layout line_strip lines lines_adjacency local_size_x local_size_y local_size_z location lowp max_vertices mediump noperspective offset origin_upper_left out packed patch pixel_center_integer point_mode points precise precision quads r11f_g11f_b10f r16 r16_snorm r16f r16i r16ui r32f r32i r32ui r8 r8_snorm r8i r8ui readonly restrict rg16 rg16_snorm rg16f rg16i rg16ui rg32f rg32i rg32ui rg8 rg8_snorm rg8i rg8ui rgb10_a2 rgb10_a2ui rgba16 rgba16_snorm rgba16f rgba16i rgba16ui rgba32f rgba32i rgba32ui rgba8 rgba8_snorm rgba8i rgba8ui row_major sample shared smooth std140 std430 stream triangle_strip triangles triangles_adjacency uniform varying vertices volatile writeonly"
          ),
          type: "atomic_uint bool bvec2 bvec3 bvec4 dmat2 dmat2x2 dmat2x3 dmat2x4 dmat3 dmat3x2 dmat3x3 dmat3x4 dmat4 dmat4x2 dmat4x3 dmat4x4 double dvec2 dvec3 dvec4 float iimage1D iimage1DArray iimage2D iimage2DArray iimage2DMS iimage2DMSArray iimage2DRect iimage3D iimageBuffer iimageCube iimageCubeArray image1D image1DArray image2D image2DArray image2DMS image2DMSArray image2DRect image3D imageBuffer imageCube imageCubeArray int isampler1D isampler1DArray isampler2D isampler2DArray isampler2DMS isampler2DMSArray isampler2DRect isampler3D isamplerBuffer isamplerCube isamplerCubeArray ivec2 ivec3 ivec4 mat2 mat2x2 mat2x3 mat2x4 mat3 mat3x2 mat3x3 mat3x4 mat4 mat4x2 mat4x3 mat4x4 sampler1D sampler1DArray sampler1DArrayShadow sampler1DShadow sampler2D sampler2DArray sampler2DArrayShadow sampler2DMS sampler2DMSArray sampler2DRect sampler2DRectShadow sampler2DShadow sampler3D samplerBuffer samplerCube samplerCubeArray samplerCubeArrayShadow samplerCubeShadow image1D uimage1DArray uimage2D uimage2DArray uimage2DMS uimage2DMSArray uimage2DRect uimage3D uimageBuffer uimageCube uimageCubeArray uint usampler1D usampler1DArray usampler2D usampler2DArray usampler2DMS usampler2DMSArray usampler2DRect usampler3D samplerBuffer usamplerCube usamplerCubeArray uvec2 uvec3 uvec4 vec2 vec3 vec4 void",
          built_in: (
            // Constants
            "gl_MaxAtomicCounterBindings gl_MaxAtomicCounterBufferSize gl_MaxClipDistances gl_MaxClipPlanes gl_MaxCombinedAtomicCounterBuffers gl_MaxCombinedAtomicCounters gl_MaxCombinedImageUniforms gl_MaxCombinedImageUnitsAndFragmentOutputs gl_MaxCombinedTextureImageUnits gl_MaxComputeAtomicCounterBuffers gl_MaxComputeAtomicCounters gl_MaxComputeImageUniforms gl_MaxComputeTextureImageUnits gl_MaxComputeUniformComponents gl_MaxComputeWorkGroupCount gl_MaxComputeWorkGroupSize gl_MaxDrawBuffers gl_MaxFragmentAtomicCounterBuffers gl_MaxFragmentAtomicCounters gl_MaxFragmentImageUniforms gl_MaxFragmentInputComponents gl_MaxFragmentInputVectors gl_MaxFragmentUniformComponents gl_MaxFragmentUniformVectors gl_MaxGeometryAtomicCounterBuffers gl_MaxGeometryAtomicCounters gl_MaxGeometryImageUniforms gl_MaxGeometryInputComponents gl_MaxGeometryOutputComponents gl_MaxGeometryOutputVertices gl_MaxGeometryTextureImageUnits gl_MaxGeometryTotalOutputComponents gl_MaxGeometryUniformComponents gl_MaxGeometryVaryingComponents gl_MaxImageSamples gl_MaxImageUnits gl_MaxLights gl_MaxPatchVertices gl_MaxProgramTexelOffset gl_MaxTessControlAtomicCounterBuffers gl_MaxTessControlAtomicCounters gl_MaxTessControlImageUniforms gl_MaxTessControlInputComponents gl_MaxTessControlOutputComponents gl_MaxTessControlTextureImageUnits gl_MaxTessControlTotalOutputComponents gl_MaxTessControlUniformComponents gl_MaxTessEvaluationAtomicCounterBuffers gl_MaxTessEvaluationAtomicCounters gl_MaxTessEvaluationImageUniforms gl_MaxTessEvaluationInputComponents gl_MaxTessEvaluationOutputComponents gl_MaxTessEvaluationTextureImageUnits gl_MaxTessEvaluationUniformComponents gl_MaxTessGenLevel gl_MaxTessPatchComponents gl_MaxTextureCoords gl_MaxTextureImageUnits gl_MaxTextureUnits gl_MaxVaryingComponents gl_MaxVaryingFloats gl_MaxVaryingVectors gl_MaxVertexAtomicCounterBuffers gl_MaxVertexAtomicCounters gl_MaxVertexAttribs gl_MaxVertexImageUniforms gl_MaxVertexOutputComponents gl_MaxVertexOutputVectors gl_MaxVertexTextureImageUnits gl_MaxVertexUniformComponents gl_MaxVertexUniformVectors gl_MaxViewports gl_MinProgramTexelOffset gl_BackColor gl_BackLightModelProduct gl_BackLightProduct gl_BackMaterial gl_BackSecondaryColor gl_ClipDistance gl_ClipPlane gl_ClipVertex gl_Color gl_DepthRange gl_EyePlaneQ gl_EyePlaneR gl_EyePlaneS gl_EyePlaneT gl_Fog gl_FogCoord gl_FogFragCoord gl_FragColor gl_FragCoord gl_FragData gl_FragDepth gl_FrontColor gl_FrontFacing gl_FrontLightModelProduct gl_FrontLightProduct gl_FrontMaterial gl_FrontSecondaryColor gl_GlobalInvocationID gl_InstanceID gl_InvocationID gl_Layer gl_LightModel gl_LightSource gl_LocalInvocationID gl_LocalInvocationIndex gl_ModelViewMatrix gl_ModelViewMatrixInverse gl_ModelViewMatrixInverseTranspose gl_ModelViewMatrixTranspose gl_ModelViewProjectionMatrix gl_ModelViewProjectionMatrixInverse gl_ModelViewProjectionMatrixInverseTranspose gl_ModelViewProjectionMatrixTranspose gl_MultiTexCoord0 gl_MultiTexCoord1 gl_MultiTexCoord2 gl_MultiTexCoord3 gl_MultiTexCoord4 gl_MultiTexCoord5 gl_MultiTexCoord6 gl_MultiTexCoord7 gl_Normal gl_NormalMatrix gl_NormalScale gl_NumSamples gl_NumWorkGroups gl_ObjectPlaneQ gl_ObjectPlaneR gl_ObjectPlaneS gl_ObjectPlaneT gl_PatchVerticesIn gl_Point gl_PointCoord gl_PointSize gl_Position gl_PrimitiveID gl_PrimitiveIDIn gl_ProjectionMatrix gl_ProjectionMatrixInverse gl_ProjectionMatrixInverseTranspose gl_ProjectionMatrixTranspose gl_SampleID gl_SampleMask gl_SampleMaskIn gl_SamplePosition gl_SecondaryColor gl_TessCoord gl_TessLevelInner gl_TessLevelOuter gl_TexCoord gl_TextureEnvColor gl_TextureMatrix gl_TextureMatrixInverse gl_TextureMatrixInverseTranspose gl_TextureMatrixTranspose gl_Vertex gl_VertexID gl_ViewportIndex gl_WorkGroupID gl_WorkGroupSize gl_in gl_out EmitStreamVertex EmitVertex EndPrimitive EndStreamPrimitive abs acos acosh all any asin asinh atan atanh atomicAdd atomicAnd atomicCompSwap atomicCounter atomicCounterDecrement atomicCounterIncrement atomicExchange atomicMax atomicMin atomicOr atomicXor barrier bitCount bitfieldExtract bitfieldInsert bitfieldReverse ceil clamp cos cosh cross dFdx dFdy degrees determinant distance dot equal exp exp2 faceforward findLSB findMSB floatBitsToInt floatBitsToUint floor fma fract frexp ftransform fwidth greaterThan greaterThanEqual groupMemoryBarrier imageAtomicAdd imageAtomicAnd imageAtomicCompSwap imageAtomicExchange imageAtomicMax imageAtomicMin imageAtomicOr imageAtomicXor imageLoad imageSize imageStore imulExtended intBitsToFloat interpolateAtCentroid interpolateAtOffset interpolateAtSample inverse inversesqrt isinf isnan ldexp length lessThan lessThanEqual log log2 matrixCompMult max memoryBarrier memoryBarrierAtomicCounter memoryBarrierBuffer memoryBarrierImage memoryBarrierShared min mix mod modf noise1 noise2 noise3 noise4 normalize not notEqual outerProduct packDouble2x32 packHalf2x16 packSnorm2x16 packSnorm4x8 packUnorm2x16 packUnorm4x8 pow radians reflect refract round roundEven shadow1D shadow1DLod shadow1DProj shadow1DProjLod shadow2D shadow2DLod shadow2DProj shadow2DProjLod sign sin sinh smoothstep sqrt step tan tanh texelFetch texelFetchOffset texture texture1D texture1DLod texture1DProj texture1DProjLod texture2D texture2DLod texture2DProj texture2DProjLod texture3D texture3DLod texture3DProj texture3DProjLod textureCube textureCubeLod textureGather textureGatherOffset textureGatherOffsets textureGrad textureGradOffset textureLod textureLodOffset textureOffset textureProj textureProjGrad textureProjGradOffset textureProjLod textureProjLodOffset textureProjOffset textureQueryLevels textureQueryLod textureSize transpose trunc uaddCarry uintBitsToFloat umulExtended unpackDouble2x32 unpackHalf2x16 unpackSnorm2x16 unpackSnorm4x8 unpackUnorm2x16 unpackUnorm4x8 usubBorrow"
          ),
          literal: "true false"
        },
        illegal: '"',
        contains: [
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          hljs5.C_NUMBER_MODE,
          {
            className: "meta",
            begin: "#",
            end: "$"
          }
        ]
      };
    }
    module.exports = glsl;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/gml.js
var require_gml = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/gml.js"(exports, module) {
    init_process_shim();
    function gml(hljs5) {
      const GML_KEYWORDS = {
        keyword: "begin end if then else while do for break continue with until repeat exit and or xor not return mod div switch case default var globalvar enum function constructor delete #macro #region #endregion",
        built_in: "is_real is_string is_array is_undefined is_int32 is_int64 is_ptr is_vec3 is_vec4 is_matrix is_bool is_method is_struct is_infinity is_nan is_numeric typeof variable_global_exists variable_global_get variable_global_set variable_instance_exists variable_instance_get variable_instance_set variable_instance_get_names variable_struct_exists variable_struct_get variable_struct_get_names variable_struct_names_count variable_struct_remove variable_struct_set array_delete array_insert array_length array_length_1d array_length_2d array_height_2d array_equals array_create array_copy array_pop array_push array_resize array_sort random random_range irandom irandom_range random_set_seed random_get_seed randomize randomise choose abs round floor ceil sign frac sqrt sqr exp ln log2 log10 sin cos tan arcsin arccos arctan arctan2 dsin dcos dtan darcsin darccos darctan darctan2 degtorad radtodeg power logn min max mean median clamp lerp dot_product dot_product_3d dot_product_normalised dot_product_3d_normalised dot_product_normalized dot_product_3d_normalized math_set_epsilon math_get_epsilon angle_difference point_distance_3d point_distance point_direction lengthdir_x lengthdir_y real string int64 ptr string_format chr ansi_char ord string_length string_byte_length string_pos string_copy string_char_at string_ord_at string_byte_at string_set_byte_at string_delete string_insert string_lower string_upper string_repeat string_letters string_digits string_lettersdigits string_replace string_replace_all string_count string_hash_to_newline clipboard_has_text clipboard_set_text clipboard_get_text date_current_datetime date_create_datetime date_valid_datetime date_inc_year date_inc_month date_inc_week date_inc_day date_inc_hour date_inc_minute date_inc_second date_get_year date_get_month date_get_week date_get_day date_get_hour date_get_minute date_get_second date_get_weekday date_get_day_of_year date_get_hour_of_year date_get_minute_of_year date_get_second_of_year date_year_span date_month_span date_week_span date_day_span date_hour_span date_minute_span date_second_span date_compare_datetime date_compare_date date_compare_time date_date_of date_time_of date_datetime_string date_date_string date_time_string date_days_in_month date_days_in_year date_leap_year date_is_today date_set_timezone date_get_timezone game_set_speed game_get_speed motion_set motion_add place_free place_empty place_meeting place_snapped move_random move_snap move_towards_point move_contact_solid move_contact_all move_outside_solid move_outside_all move_bounce_solid move_bounce_all move_wrap distance_to_point distance_to_object position_empty position_meeting path_start path_end mp_linear_step mp_potential_step mp_linear_step_object mp_potential_step_object mp_potential_settings mp_linear_path mp_potential_path mp_linear_path_object mp_potential_path_object mp_grid_create mp_grid_destroy mp_grid_clear_all mp_grid_clear_cell mp_grid_clear_rectangle mp_grid_add_cell mp_grid_get_cell mp_grid_add_rectangle mp_grid_add_instances mp_grid_path mp_grid_draw mp_grid_to_ds_grid collision_point collision_rectangle collision_circle collision_ellipse collision_line collision_point_list collision_rectangle_list collision_circle_list collision_ellipse_list collision_line_list instance_position_list instance_place_list point_in_rectangle point_in_triangle point_in_circle rectangle_in_rectangle rectangle_in_triangle rectangle_in_circle instance_find instance_exists instance_number instance_position instance_nearest instance_furthest instance_place instance_create_depth instance_create_layer instance_copy instance_change instance_destroy position_destroy position_change instance_id_get instance_deactivate_all instance_deactivate_object instance_deactivate_region instance_activate_all instance_activate_object instance_activate_region room_goto room_goto_previous room_goto_next room_previous room_next room_restart game_end game_restart game_load game_save game_save_buffer game_load_buffer event_perform event_user event_perform_object event_inherited show_debug_message show_debug_overlay debug_event debug_get_callstack alarm_get alarm_set font_texture_page_size keyboard_set_map keyboard_get_map keyboard_unset_map keyboard_check keyboard_check_pressed keyboard_check_released keyboard_check_direct keyboard_get_numlock keyboard_set_numlock keyboard_key_press keyboard_key_release keyboard_clear io_clear mouse_check_button mouse_check_button_pressed mouse_check_button_released mouse_wheel_up mouse_wheel_down mouse_clear draw_self draw_sprite draw_sprite_pos draw_sprite_ext draw_sprite_stretched draw_sprite_stretched_ext draw_sprite_tiled draw_sprite_tiled_ext draw_sprite_part draw_sprite_part_ext draw_sprite_general draw_clear draw_clear_alpha draw_point draw_line draw_line_width draw_rectangle draw_roundrect draw_roundrect_ext draw_triangle draw_circle draw_ellipse draw_set_circle_precision draw_arrow draw_button draw_path draw_healthbar draw_getpixel draw_getpixel_ext draw_set_colour draw_set_color draw_set_alpha draw_get_colour draw_get_color draw_get_alpha merge_colour make_colour_rgb make_colour_hsv colour_get_red colour_get_green colour_get_blue colour_get_hue colour_get_saturation colour_get_value merge_color make_color_rgb make_color_hsv color_get_red color_get_green color_get_blue color_get_hue color_get_saturation color_get_value merge_color screen_save screen_save_part draw_set_font draw_set_halign draw_set_valign draw_text draw_text_ext string_width string_height string_width_ext string_height_ext draw_text_transformed draw_text_ext_transformed draw_text_colour draw_text_ext_colour draw_text_transformed_colour draw_text_ext_transformed_colour draw_text_color draw_text_ext_color draw_text_transformed_color draw_text_ext_transformed_color draw_point_colour draw_line_colour draw_line_width_colour draw_rectangle_colour draw_roundrect_colour draw_roundrect_colour_ext draw_triangle_colour draw_circle_colour draw_ellipse_colour draw_point_color draw_line_color draw_line_width_color draw_rectangle_color draw_roundrect_color draw_roundrect_color_ext draw_triangle_color draw_circle_color draw_ellipse_color draw_primitive_begin draw_vertex draw_vertex_colour draw_vertex_color draw_primitive_end sprite_get_uvs font_get_uvs sprite_get_texture font_get_texture texture_get_width texture_get_height texture_get_uvs draw_primitive_begin_texture draw_vertex_texture draw_vertex_texture_colour draw_vertex_texture_color texture_global_scale surface_create surface_create_ext surface_resize surface_free surface_exists surface_get_width surface_get_height surface_get_texture surface_set_target surface_set_target_ext surface_reset_target surface_depth_disable surface_get_depth_disable draw_surface draw_surface_stretched draw_surface_tiled draw_surface_part draw_surface_ext draw_surface_stretched_ext draw_surface_tiled_ext draw_surface_part_ext draw_surface_general surface_getpixel surface_getpixel_ext surface_save surface_save_part surface_copy surface_copy_part application_surface_draw_enable application_get_position application_surface_enable application_surface_is_enabled display_get_width display_get_height display_get_orientation display_get_gui_width display_get_gui_height display_reset display_mouse_get_x display_mouse_get_y display_mouse_set display_set_ui_visibility window_set_fullscreen window_get_fullscreen window_set_caption window_set_min_width window_set_max_width window_set_min_height window_set_max_height window_get_visible_rects window_get_caption window_set_cursor window_get_cursor window_set_colour window_get_colour window_set_color window_get_color window_set_position window_set_size window_set_rectangle window_center window_get_x window_get_y window_get_width window_get_height window_mouse_get_x window_mouse_get_y window_mouse_set window_view_mouse_get_x window_view_mouse_get_y window_views_mouse_get_x window_views_mouse_get_y audio_listener_position audio_listener_velocity audio_listener_orientation audio_emitter_position audio_emitter_create audio_emitter_free audio_emitter_exists audio_emitter_pitch audio_emitter_velocity audio_emitter_falloff audio_emitter_gain audio_play_sound audio_play_sound_on audio_play_sound_at audio_stop_sound audio_resume_music audio_music_is_playing audio_resume_sound audio_pause_sound audio_pause_music audio_channel_num audio_sound_length audio_get_type audio_falloff_set_model audio_play_music audio_stop_music audio_master_gain audio_music_gain audio_sound_gain audio_sound_pitch audio_stop_all audio_resume_all audio_pause_all audio_is_playing audio_is_paused audio_exists audio_sound_set_track_position audio_sound_get_track_position audio_emitter_get_gain audio_emitter_get_pitch audio_emitter_get_x audio_emitter_get_y audio_emitter_get_z audio_emitter_get_vx audio_emitter_get_vy audio_emitter_get_vz audio_listener_set_position audio_listener_set_velocity audio_listener_set_orientation audio_listener_get_data audio_set_master_gain audio_get_master_gain audio_sound_get_gain audio_sound_get_pitch audio_get_name audio_sound_set_track_position audio_sound_get_track_position audio_create_stream audio_destroy_stream audio_create_sync_group audio_destroy_sync_group audio_play_in_sync_group audio_start_sync_group audio_stop_sync_group audio_pause_sync_group audio_resume_sync_group audio_sync_group_get_track_pos audio_sync_group_debug audio_sync_group_is_playing audio_debug audio_group_load audio_group_unload audio_group_is_loaded audio_group_load_progress audio_group_name audio_group_stop_all audio_group_set_gain audio_create_buffer_sound audio_free_buffer_sound audio_create_play_queue audio_free_play_queue audio_queue_sound audio_get_recorder_count audio_get_recorder_info audio_start_recording audio_stop_recording audio_sound_get_listener_mask audio_emitter_get_listener_mask audio_get_listener_mask audio_sound_set_listener_mask audio_emitter_set_listener_mask audio_set_listener_mask audio_get_listener_count audio_get_listener_info audio_system show_message show_message_async clickable_add clickable_add_ext clickable_change clickable_change_ext clickable_delete clickable_exists clickable_set_style show_question show_question_async get_integer get_string get_integer_async get_string_async get_login_async get_open_filename get_save_filename get_open_filename_ext get_save_filename_ext show_error highscore_clear highscore_add highscore_value highscore_name draw_highscore sprite_exists sprite_get_name sprite_get_number sprite_get_width sprite_get_height sprite_get_xoffset sprite_get_yoffset sprite_get_bbox_left sprite_get_bbox_right sprite_get_bbox_top sprite_get_bbox_bottom sprite_save sprite_save_strip sprite_set_cache_size sprite_set_cache_size_ext sprite_get_tpe sprite_prefetch sprite_prefetch_multi sprite_flush sprite_flush_multi sprite_set_speed sprite_get_speed_type sprite_get_speed font_exists font_get_name font_get_fontname font_get_bold font_get_italic font_get_first font_get_last font_get_size font_set_cache_size path_exists path_get_name path_get_length path_get_time path_get_kind path_get_closed path_get_precision path_get_number path_get_point_x path_get_point_y path_get_point_speed path_get_x path_get_y path_get_speed script_exists script_get_name timeline_add timeline_delete timeline_clear timeline_exists timeline_get_name timeline_moment_clear timeline_moment_add_script timeline_size timeline_max_moment object_exists object_get_name object_get_sprite object_get_solid object_get_visible object_get_persistent object_get_mask object_get_parent object_get_physics object_is_ancestor room_exists room_get_name sprite_set_offset sprite_duplicate sprite_assign sprite_merge sprite_add sprite_replace sprite_create_from_surface sprite_add_from_surface sprite_delete sprite_set_alpha_from_sprite sprite_collision_mask font_add_enable_aa font_add_get_enable_aa font_add font_add_sprite font_add_sprite_ext font_replace font_replace_sprite font_replace_sprite_ext font_delete path_set_kind path_set_closed path_set_precision path_add path_assign path_duplicate path_append path_delete path_add_point path_insert_point path_change_point path_delete_point path_clear_points path_reverse path_mirror path_flip path_rotate path_rescale path_shift script_execute object_set_sprite object_set_solid object_set_visible object_set_persistent object_set_mask room_set_width room_set_height room_set_persistent room_set_background_colour room_set_background_color room_set_view room_set_viewport room_get_viewport room_set_view_enabled room_add room_duplicate room_assign room_instance_add room_instance_clear room_get_camera room_set_camera asset_get_index asset_get_type file_text_open_from_string file_text_open_read file_text_open_write file_text_open_append file_text_close file_text_write_string file_text_write_real file_text_writeln file_text_read_string file_text_read_real file_text_readln file_text_eof file_text_eoln file_exists file_delete file_rename file_copy directory_exists directory_create directory_destroy file_find_first file_find_next file_find_close file_attributes filename_name filename_path filename_dir filename_drive filename_ext filename_change_ext file_bin_open file_bin_rewrite file_bin_close file_bin_position file_bin_size file_bin_seek file_bin_write_byte file_bin_read_byte parameter_count parameter_string environment_get_variable ini_open_from_string ini_open ini_close ini_read_string ini_read_real ini_write_string ini_write_real ini_key_exists ini_section_exists ini_key_delete ini_section_delete ds_set_precision ds_exists ds_stack_create ds_stack_destroy ds_stack_clear ds_stack_copy ds_stack_size ds_stack_empty ds_stack_push ds_stack_pop ds_stack_top ds_stack_write ds_stack_read ds_queue_create ds_queue_destroy ds_queue_clear ds_queue_copy ds_queue_size ds_queue_empty ds_queue_enqueue ds_queue_dequeue ds_queue_head ds_queue_tail ds_queue_write ds_queue_read ds_list_create ds_list_destroy ds_list_clear ds_list_copy ds_list_size ds_list_empty ds_list_add ds_list_insert ds_list_replace ds_list_delete ds_list_find_index ds_list_find_value ds_list_mark_as_list ds_list_mark_as_map ds_list_sort ds_list_shuffle ds_list_write ds_list_read ds_list_set ds_map_create ds_map_destroy ds_map_clear ds_map_copy ds_map_size ds_map_empty ds_map_add ds_map_add_list ds_map_add_map ds_map_replace ds_map_replace_map ds_map_replace_list ds_map_delete ds_map_exists ds_map_find_value ds_map_find_previous ds_map_find_next ds_map_find_first ds_map_find_last ds_map_write ds_map_read ds_map_secure_save ds_map_secure_load ds_map_secure_load_buffer ds_map_secure_save_buffer ds_map_set ds_priority_create ds_priority_destroy ds_priority_clear ds_priority_copy ds_priority_size ds_priority_empty ds_priority_add ds_priority_change_priority ds_priority_find_priority ds_priority_delete_value ds_priority_delete_min ds_priority_find_min ds_priority_delete_max ds_priority_find_max ds_priority_write ds_priority_read ds_grid_create ds_grid_destroy ds_grid_copy ds_grid_resize ds_grid_width ds_grid_height ds_grid_clear ds_grid_set ds_grid_add ds_grid_multiply ds_grid_set_region ds_grid_add_region ds_grid_multiply_region ds_grid_set_disk ds_grid_add_disk ds_grid_multiply_disk ds_grid_set_grid_region ds_grid_add_grid_region ds_grid_multiply_grid_region ds_grid_get ds_grid_get_sum ds_grid_get_max ds_grid_get_min ds_grid_get_mean ds_grid_get_disk_sum ds_grid_get_disk_min ds_grid_get_disk_max ds_grid_get_disk_mean ds_grid_value_exists ds_grid_value_x ds_grid_value_y ds_grid_value_disk_exists ds_grid_value_disk_x ds_grid_value_disk_y ds_grid_shuffle ds_grid_write ds_grid_read ds_grid_sort ds_grid_set ds_grid_get effect_create_below effect_create_above effect_clear part_type_create part_type_destroy part_type_exists part_type_clear part_type_shape part_type_sprite part_type_size part_type_scale part_type_orientation part_type_life part_type_step part_type_death part_type_speed part_type_direction part_type_gravity part_type_colour1 part_type_colour2 part_type_colour3 part_type_colour_mix part_type_colour_rgb part_type_colour_hsv part_type_color1 part_type_color2 part_type_color3 part_type_color_mix part_type_color_rgb part_type_color_hsv part_type_alpha1 part_type_alpha2 part_type_alpha3 part_type_blend part_system_create part_system_create_layer part_system_destroy part_system_exists part_system_clear part_system_draw_order part_system_depth part_system_position part_system_automatic_update part_system_automatic_draw part_system_update part_system_drawit part_system_get_layer part_system_layer part_particles_create part_particles_create_colour part_particles_create_color part_particles_clear part_particles_count part_emitter_create part_emitter_destroy part_emitter_destroy_all part_emitter_exists part_emitter_clear part_emitter_region part_emitter_burst part_emitter_stream external_call external_define external_free window_handle window_device matrix_get matrix_set matrix_build_identity matrix_build matrix_build_lookat matrix_build_projection_ortho matrix_build_projection_perspective matrix_build_projection_perspective_fov matrix_multiply matrix_transform_vertex matrix_stack_push matrix_stack_pop matrix_stack_multiply matrix_stack_set matrix_stack_clear matrix_stack_top matrix_stack_is_empty browser_input_capture os_get_config os_get_info os_get_language os_get_region os_lock_orientation display_get_dpi_x display_get_dpi_y display_set_gui_size display_set_gui_maximise display_set_gui_maximize device_mouse_dbclick_enable display_set_timing_method display_get_timing_method display_set_sleep_margin display_get_sleep_margin virtual_key_add virtual_key_hide virtual_key_delete virtual_key_show draw_enable_drawevent draw_enable_swf_aa draw_set_swf_aa_level draw_get_swf_aa_level draw_texture_flush draw_flush gpu_set_blendenable gpu_set_ztestenable gpu_set_zfunc gpu_set_zwriteenable gpu_set_lightingenable gpu_set_fog gpu_set_cullmode gpu_set_blendmode gpu_set_blendmode_ext gpu_set_blendmode_ext_sepalpha gpu_set_colorwriteenable gpu_set_colourwriteenable gpu_set_alphatestenable gpu_set_alphatestref gpu_set_alphatestfunc gpu_set_texfilter gpu_set_texfilter_ext gpu_set_texrepeat gpu_set_texrepeat_ext gpu_set_tex_filter gpu_set_tex_filter_ext gpu_set_tex_repeat gpu_set_tex_repeat_ext gpu_set_tex_mip_filter gpu_set_tex_mip_filter_ext gpu_set_tex_mip_bias gpu_set_tex_mip_bias_ext gpu_set_tex_min_mip gpu_set_tex_min_mip_ext gpu_set_tex_max_mip gpu_set_tex_max_mip_ext gpu_set_tex_max_aniso gpu_set_tex_max_aniso_ext gpu_set_tex_mip_enable gpu_set_tex_mip_enable_ext gpu_get_blendenable gpu_get_ztestenable gpu_get_zfunc gpu_get_zwriteenable gpu_get_lightingenable gpu_get_fog gpu_get_cullmode gpu_get_blendmode gpu_get_blendmode_ext gpu_get_blendmode_ext_sepalpha gpu_get_blendmode_src gpu_get_blendmode_dest gpu_get_blendmode_srcalpha gpu_get_blendmode_destalpha gpu_get_colorwriteenable gpu_get_colourwriteenable gpu_get_alphatestenable gpu_get_alphatestref gpu_get_alphatestfunc gpu_get_texfilter gpu_get_texfilter_ext gpu_get_texrepeat gpu_get_texrepeat_ext gpu_get_tex_filter gpu_get_tex_filter_ext gpu_get_tex_repeat gpu_get_tex_repeat_ext gpu_get_tex_mip_filter gpu_get_tex_mip_filter_ext gpu_get_tex_mip_bias gpu_get_tex_mip_bias_ext gpu_get_tex_min_mip gpu_get_tex_min_mip_ext gpu_get_tex_max_mip gpu_get_tex_max_mip_ext gpu_get_tex_max_aniso gpu_get_tex_max_aniso_ext gpu_get_tex_mip_enable gpu_get_tex_mip_enable_ext gpu_push_state gpu_pop_state gpu_get_state gpu_set_state draw_light_define_ambient draw_light_define_direction draw_light_define_point draw_light_enable draw_set_lighting draw_light_get_ambient draw_light_get draw_get_lighting shop_leave_rating url_get_domain url_open url_open_ext url_open_full get_timer achievement_login achievement_logout achievement_post achievement_increment achievement_post_score achievement_available achievement_show_achievements achievement_show_leaderboards achievement_load_friends achievement_load_leaderboard achievement_send_challenge achievement_load_progress achievement_reset achievement_login_status achievement_get_pic achievement_show_challenge_notifications achievement_get_challenges achievement_event achievement_show achievement_get_info cloud_file_save cloud_string_save cloud_synchronise ads_enable ads_disable ads_setup ads_engagement_launch ads_engagement_available ads_engagement_active ads_event ads_event_preload ads_set_reward_callback ads_get_display_height ads_get_display_width ads_move ads_interstitial_available ads_interstitial_display device_get_tilt_x device_get_tilt_y device_get_tilt_z device_is_keypad_open device_mouse_check_button device_mouse_check_button_pressed device_mouse_check_button_released device_mouse_x device_mouse_y device_mouse_raw_x device_mouse_raw_y device_mouse_x_to_gui device_mouse_y_to_gui iap_activate iap_status iap_enumerate_products iap_restore_all iap_acquire iap_consume iap_product_details iap_purchase_details facebook_init facebook_login facebook_status facebook_graph_request facebook_dialog facebook_logout facebook_launch_offerwall facebook_post_message facebook_send_invite facebook_user_id facebook_accesstoken facebook_check_permission facebook_request_read_permissions facebook_request_publish_permissions gamepad_is_supported gamepad_get_device_count gamepad_is_connected gamepad_get_description gamepad_get_button_threshold gamepad_set_button_threshold gamepad_get_axis_deadzone gamepad_set_axis_deadzone gamepad_button_count gamepad_button_check gamepad_button_check_pressed gamepad_button_check_released gamepad_button_value gamepad_axis_count gamepad_axis_value gamepad_set_vibration gamepad_set_colour gamepad_set_color os_is_paused window_has_focus code_is_compiled http_get http_get_file http_post_string http_request json_encode json_decode zip_unzip load_csv base64_encode base64_decode md5_string_unicode md5_string_utf8 md5_file os_is_network_connected sha1_string_unicode sha1_string_utf8 sha1_file os_powersave_enable analytics_event analytics_event_ext win8_livetile_tile_notification win8_livetile_tile_clear win8_livetile_badge_notification win8_livetile_badge_clear win8_livetile_queue_enable win8_secondarytile_pin win8_secondarytile_badge_notification win8_secondarytile_delete win8_livetile_notification_begin win8_livetile_notification_secondary_begin win8_livetile_notification_expiry win8_livetile_notification_tag win8_livetile_notification_text_add win8_livetile_notification_image_add win8_livetile_notification_end win8_appbar_enable win8_appbar_add_element win8_appbar_remove_element win8_settingscharm_add_entry win8_settingscharm_add_html_entry win8_settingscharm_add_xaml_entry win8_settingscharm_set_xaml_property win8_settingscharm_get_xaml_property win8_settingscharm_remove_entry win8_share_image win8_share_screenshot win8_share_file win8_share_url win8_share_text win8_search_enable win8_search_disable win8_search_add_suggestions win8_device_touchscreen_available win8_license_initialize_sandbox win8_license_trial_version winphone_license_trial_version winphone_tile_title winphone_tile_count winphone_tile_back_title winphone_tile_back_content winphone_tile_back_content_wide winphone_tile_front_image winphone_tile_front_image_small winphone_tile_front_image_wide winphone_tile_back_image winphone_tile_back_image_wide winphone_tile_background_colour winphone_tile_background_color winphone_tile_icon_image winphone_tile_small_icon_image winphone_tile_wide_content winphone_tile_cycle_images winphone_tile_small_background_image physics_world_create physics_world_gravity physics_world_update_speed physics_world_update_iterations physics_world_draw_debug physics_pause_enable physics_fixture_create physics_fixture_set_kinematic physics_fixture_set_density physics_fixture_set_awake physics_fixture_set_restitution physics_fixture_set_friction physics_fixture_set_collision_group physics_fixture_set_sensor physics_fixture_set_linear_damping physics_fixture_set_angular_damping physics_fixture_set_circle_shape physics_fixture_set_box_shape physics_fixture_set_edge_shape physics_fixture_set_polygon_shape physics_fixture_set_chain_shape physics_fixture_add_point physics_fixture_bind physics_fixture_bind_ext physics_fixture_delete physics_apply_force physics_apply_impulse physics_apply_angular_impulse physics_apply_local_force physics_apply_local_impulse physics_apply_torque physics_mass_properties physics_draw_debug physics_test_overlap physics_remove_fixture physics_set_friction physics_set_density physics_set_restitution physics_get_friction physics_get_density physics_get_restitution physics_joint_distance_create physics_joint_rope_create physics_joint_revolute_create physics_joint_prismatic_create physics_joint_pulley_create physics_joint_wheel_create physics_joint_weld_create physics_joint_friction_create physics_joint_gear_create physics_joint_enable_motor physics_joint_get_value physics_joint_set_value physics_joint_delete physics_particle_create physics_particle_delete physics_particle_delete_region_circle physics_particle_delete_region_box physics_particle_delete_region_poly physics_particle_set_flags physics_particle_set_category_flags physics_particle_draw physics_particle_draw_ext physics_particle_count physics_particle_get_data physics_particle_get_data_particle physics_particle_group_begin physics_particle_group_circle physics_particle_group_box physics_particle_group_polygon physics_particle_group_add_point physics_particle_group_end physics_particle_group_join physics_particle_group_delete physics_particle_group_count physics_particle_group_get_data physics_particle_group_get_mass physics_particle_group_get_inertia physics_particle_group_get_centre_x physics_particle_group_get_centre_y physics_particle_group_get_vel_x physics_particle_group_get_vel_y physics_particle_group_get_ang_vel physics_particle_group_get_x physics_particle_group_get_y physics_particle_group_get_angle physics_particle_set_group_flags physics_particle_get_group_flags physics_particle_get_max_count physics_particle_get_radius physics_particle_get_density physics_particle_get_damping physics_particle_get_gravity_scale physics_particle_set_max_count physics_particle_set_radius physics_particle_set_density physics_particle_set_damping physics_particle_set_gravity_scale network_create_socket network_create_socket_ext network_create_server network_create_server_raw network_connect network_connect_raw network_send_packet network_send_raw network_send_broadcast network_send_udp network_send_udp_raw network_set_timeout network_set_config network_resolve network_destroy buffer_create buffer_write buffer_read buffer_seek buffer_get_surface buffer_set_surface buffer_delete buffer_exists buffer_get_type buffer_get_alignment buffer_poke buffer_peek buffer_save buffer_save_ext buffer_load buffer_load_ext buffer_load_partial buffer_copy buffer_fill buffer_get_size buffer_tell buffer_resize buffer_md5 buffer_sha1 buffer_base64_encode buffer_base64_decode buffer_base64_decode_ext buffer_sizeof buffer_get_address buffer_create_from_vertex_buffer buffer_create_from_vertex_buffer_ext buffer_copy_from_vertex_buffer buffer_async_group_begin buffer_async_group_option buffer_async_group_end buffer_load_async buffer_save_async gml_release_mode gml_pragma steam_activate_overlay steam_is_overlay_enabled steam_is_overlay_activated steam_get_persona_name steam_initialised steam_is_cloud_enabled_for_app steam_is_cloud_enabled_for_account steam_file_persisted steam_get_quota_total steam_get_quota_free steam_file_write steam_file_write_file steam_file_read steam_file_delete steam_file_exists steam_file_size steam_file_share steam_is_screenshot_requested steam_send_screenshot steam_is_user_logged_on steam_get_user_steam_id steam_user_owns_dlc steam_user_installed_dlc steam_set_achievement steam_get_achievement steam_clear_achievement steam_set_stat_int steam_set_stat_float steam_set_stat_avg_rate steam_get_stat_int steam_get_stat_float steam_get_stat_avg_rate steam_reset_all_stats steam_reset_all_stats_achievements steam_stats_ready steam_create_leaderboard steam_upload_score steam_upload_score_ext steam_download_scores_around_user steam_download_scores steam_download_friends_scores steam_upload_score_buffer steam_upload_score_buffer_ext steam_current_game_language steam_available_languages steam_activate_overlay_browser steam_activate_overlay_user steam_activate_overlay_store steam_get_user_persona_name steam_get_app_id steam_get_user_account_id steam_ugc_download steam_ugc_create_item steam_ugc_start_item_update steam_ugc_set_item_title steam_ugc_set_item_description steam_ugc_set_item_visibility steam_ugc_set_item_tags steam_ugc_set_item_content steam_ugc_set_item_preview steam_ugc_submit_item_update steam_ugc_get_item_update_progress steam_ugc_subscribe_item steam_ugc_unsubscribe_item steam_ugc_num_subscribed_items steam_ugc_get_subscribed_items steam_ugc_get_item_install_info steam_ugc_get_item_update_info steam_ugc_request_item_details steam_ugc_create_query_user steam_ugc_create_query_user_ex steam_ugc_create_query_all steam_ugc_create_query_all_ex steam_ugc_query_set_cloud_filename_filter steam_ugc_query_set_match_any_tag steam_ugc_query_set_search_text steam_ugc_query_set_ranked_by_trend_days steam_ugc_query_add_required_tag steam_ugc_query_add_excluded_tag steam_ugc_query_set_return_long_description steam_ugc_query_set_return_total_only steam_ugc_query_set_allow_cached_response steam_ugc_send_query shader_set shader_get_name shader_reset shader_current shader_is_compiled shader_get_sampler_index shader_get_uniform shader_set_uniform_i shader_set_uniform_i_array shader_set_uniform_f shader_set_uniform_f_array shader_set_uniform_matrix shader_set_uniform_matrix_array shader_enable_corner_id texture_set_stage texture_get_texel_width texture_get_texel_height shaders_are_supported vertex_format_begin vertex_format_end vertex_format_delete vertex_format_add_position vertex_format_add_position_3d vertex_format_add_colour vertex_format_add_color vertex_format_add_normal vertex_format_add_texcoord vertex_format_add_textcoord vertex_format_add_custom vertex_create_buffer vertex_create_buffer_ext vertex_delete_buffer vertex_begin vertex_end vertex_position vertex_position_3d vertex_colour vertex_color vertex_argb vertex_texcoord vertex_normal vertex_float1 vertex_float2 vertex_float3 vertex_float4 vertex_ubyte4 vertex_submit vertex_freeze vertex_get_number vertex_get_buffer_size vertex_create_buffer_from_buffer vertex_create_buffer_from_buffer_ext push_local_notification push_get_first_local_notification push_get_next_local_notification push_cancel_local_notification skeleton_animation_set skeleton_animation_get skeleton_animation_mix skeleton_animation_set_ext skeleton_animation_get_ext skeleton_animation_get_duration skeleton_animation_get_frames skeleton_animation_clear skeleton_skin_set skeleton_skin_get skeleton_attachment_set skeleton_attachment_get skeleton_attachment_create skeleton_collision_draw_set skeleton_bone_data_get skeleton_bone_data_set skeleton_bone_state_get skeleton_bone_state_set skeleton_get_minmax skeleton_get_num_bounds skeleton_get_bounds skeleton_animation_get_frame skeleton_animation_set_frame draw_skeleton draw_skeleton_time draw_skeleton_instance draw_skeleton_collision skeleton_animation_list skeleton_skin_list skeleton_slot_data layer_get_id layer_get_id_at_depth layer_get_depth layer_create layer_destroy layer_destroy_instances layer_add_instance layer_has_instance layer_set_visible layer_get_visible layer_exists layer_x layer_y layer_get_x layer_get_y layer_hspeed layer_vspeed layer_get_hspeed layer_get_vspeed layer_script_begin layer_script_end layer_shader layer_get_script_begin layer_get_script_end layer_get_shader layer_set_target_room layer_get_target_room layer_reset_target_room layer_get_all layer_get_all_elements layer_get_name layer_depth layer_get_element_layer layer_get_element_type layer_element_move layer_force_draw_depth layer_is_draw_depth_forced layer_get_forced_depth layer_background_get_id layer_background_exists layer_background_create layer_background_destroy layer_background_visible layer_background_change layer_background_sprite layer_background_htiled layer_background_vtiled layer_background_stretch layer_background_yscale layer_background_xscale layer_background_blend layer_background_alpha layer_background_index layer_background_speed layer_background_get_visible layer_background_get_sprite layer_background_get_htiled layer_background_get_vtiled layer_background_get_stretch layer_background_get_yscale layer_background_get_xscale layer_background_get_blend layer_background_get_alpha layer_background_get_index layer_background_get_speed layer_sprite_get_id layer_sprite_exists layer_sprite_create layer_sprite_destroy layer_sprite_change layer_sprite_index layer_sprite_speed layer_sprite_xscale layer_sprite_yscale layer_sprite_angle layer_sprite_blend layer_sprite_alpha layer_sprite_x layer_sprite_y layer_sprite_get_sprite layer_sprite_get_index layer_sprite_get_speed layer_sprite_get_xscale layer_sprite_get_yscale layer_sprite_get_angle layer_sprite_get_blend layer_sprite_get_alpha layer_sprite_get_x layer_sprite_get_y layer_tilemap_get_id layer_tilemap_exists layer_tilemap_create layer_tilemap_destroy tilemap_tileset tilemap_x tilemap_y tilemap_set tilemap_set_at_pixel tilemap_get_tileset tilemap_get_tile_width tilemap_get_tile_height tilemap_get_width tilemap_get_height tilemap_get_x tilemap_get_y tilemap_get tilemap_get_at_pixel tilemap_get_cell_x_at_pixel tilemap_get_cell_y_at_pixel tilemap_clear draw_tilemap draw_tile tilemap_set_global_mask tilemap_get_global_mask tilemap_set_mask tilemap_get_mask tilemap_get_frame tile_set_empty tile_set_index tile_set_flip tile_set_mirror tile_set_rotate tile_get_empty tile_get_index tile_get_flip tile_get_mirror tile_get_rotate layer_tile_exists layer_tile_create layer_tile_destroy layer_tile_change layer_tile_xscale layer_tile_yscale layer_tile_blend layer_tile_alpha layer_tile_x layer_tile_y layer_tile_region layer_tile_visible layer_tile_get_sprite layer_tile_get_xscale layer_tile_get_yscale layer_tile_get_blend layer_tile_get_alpha layer_tile_get_x layer_tile_get_y layer_tile_get_region layer_tile_get_visible layer_instance_get_instance instance_activate_layer instance_deactivate_layer camera_create camera_create_view camera_destroy camera_apply camera_get_active camera_get_default camera_set_default camera_set_view_mat camera_set_proj_mat camera_set_update_script camera_set_begin_script camera_set_end_script camera_set_view_pos camera_set_view_size camera_set_view_speed camera_set_view_border camera_set_view_angle camera_set_view_target camera_get_view_mat camera_get_proj_mat camera_get_update_script camera_get_begin_script camera_get_end_script camera_get_view_x camera_get_view_y camera_get_view_width camera_get_view_height camera_get_view_speed_x camera_get_view_speed_y camera_get_view_border_x camera_get_view_border_y camera_get_view_angle camera_get_view_target view_get_camera view_get_visible view_get_xport view_get_yport view_get_wport view_get_hport view_get_surface_id view_set_camera view_set_visible view_set_xport view_set_yport view_set_wport view_set_hport view_set_surface_id gesture_drag_time gesture_drag_distance gesture_flick_speed gesture_double_tap_time gesture_double_tap_distance gesture_pinch_distance gesture_pinch_angle_towards gesture_pinch_angle_away gesture_rotate_time gesture_rotate_angle gesture_tap_count gesture_get_drag_time gesture_get_drag_distance gesture_get_flick_speed gesture_get_double_tap_time gesture_get_double_tap_distance gesture_get_pinch_distance gesture_get_pinch_angle_towards gesture_get_pinch_angle_away gesture_get_rotate_time gesture_get_rotate_angle gesture_get_tap_count keyboard_virtual_show keyboard_virtual_hide keyboard_virtual_status keyboard_virtual_height",
        literal: "self other all noone global local undefined pointer_invalid pointer_null path_action_stop path_action_restart path_action_continue path_action_reverse true false pi GM_build_date GM_version GM_runtime_version  timezone_local timezone_utc gamespeed_fps gamespeed_microseconds  ev_create ev_destroy ev_step ev_alarm ev_keyboard ev_mouse ev_collision ev_other ev_draw ev_draw_begin ev_draw_end ev_draw_pre ev_draw_post ev_keypress ev_keyrelease ev_trigger ev_left_button ev_right_button ev_middle_button ev_no_button ev_left_press ev_right_press ev_middle_press ev_left_release ev_right_release ev_middle_release ev_mouse_enter ev_mouse_leave ev_mouse_wheel_up ev_mouse_wheel_down ev_global_left_button ev_global_right_button ev_global_middle_button ev_global_left_press ev_global_right_press ev_global_middle_press ev_global_left_release ev_global_right_release ev_global_middle_release ev_joystick1_left ev_joystick1_right ev_joystick1_up ev_joystick1_down ev_joystick1_button1 ev_joystick1_button2 ev_joystick1_button3 ev_joystick1_button4 ev_joystick1_button5 ev_joystick1_button6 ev_joystick1_button7 ev_joystick1_button8 ev_joystick2_left ev_joystick2_right ev_joystick2_up ev_joystick2_down ev_joystick2_button1 ev_joystick2_button2 ev_joystick2_button3 ev_joystick2_button4 ev_joystick2_button5 ev_joystick2_button6 ev_joystick2_button7 ev_joystick2_button8 ev_outside ev_boundary ev_game_start ev_game_end ev_room_start ev_room_end ev_no_more_lives ev_animation_end ev_end_of_path ev_no_more_health ev_close_button ev_user0 ev_user1 ev_user2 ev_user3 ev_user4 ev_user5 ev_user6 ev_user7 ev_user8 ev_user9 ev_user10 ev_user11 ev_user12 ev_user13 ev_user14 ev_user15 ev_step_normal ev_step_begin ev_step_end ev_gui ev_gui_begin ev_gui_end ev_cleanup ev_gesture ev_gesture_tap ev_gesture_double_tap ev_gesture_drag_start ev_gesture_dragging ev_gesture_drag_end ev_gesture_flick ev_gesture_pinch_start ev_gesture_pinch_in ev_gesture_pinch_out ev_gesture_pinch_end ev_gesture_rotate_start ev_gesture_rotating ev_gesture_rotate_end ev_global_gesture_tap ev_global_gesture_double_tap ev_global_gesture_drag_start ev_global_gesture_dragging ev_global_gesture_drag_end ev_global_gesture_flick ev_global_gesture_pinch_start ev_global_gesture_pinch_in ev_global_gesture_pinch_out ev_global_gesture_pinch_end ev_global_gesture_rotate_start ev_global_gesture_rotating ev_global_gesture_rotate_end vk_nokey vk_anykey vk_enter vk_return vk_shift vk_control vk_alt vk_escape vk_space vk_backspace vk_tab vk_pause vk_printscreen vk_left vk_right vk_up vk_down vk_home vk_end vk_delete vk_insert vk_pageup vk_pagedown vk_f1 vk_f2 vk_f3 vk_f4 vk_f5 vk_f6 vk_f7 vk_f8 vk_f9 vk_f10 vk_f11 vk_f12 vk_numpad0 vk_numpad1 vk_numpad2 vk_numpad3 vk_numpad4 vk_numpad5 vk_numpad6 vk_numpad7 vk_numpad8 vk_numpad9 vk_divide vk_multiply vk_subtract vk_add vk_decimal vk_lshift vk_lcontrol vk_lalt vk_rshift vk_rcontrol vk_ralt  mb_any mb_none mb_left mb_right mb_middle c_aqua c_black c_blue c_dkgray c_fuchsia c_gray c_green c_lime c_ltgray c_maroon c_navy c_olive c_purple c_red c_silver c_teal c_white c_yellow c_orange fa_left fa_center fa_right fa_top fa_middle fa_bottom pr_pointlist pr_linelist pr_linestrip pr_trianglelist pr_trianglestrip pr_trianglefan bm_complex bm_normal bm_add bm_max bm_subtract bm_zero bm_one bm_src_colour bm_inv_src_colour bm_src_color bm_inv_src_color bm_src_alpha bm_inv_src_alpha bm_dest_alpha bm_inv_dest_alpha bm_dest_colour bm_inv_dest_colour bm_dest_color bm_inv_dest_color bm_src_alpha_sat tf_point tf_linear tf_anisotropic mip_off mip_on mip_markedonly audio_falloff_none audio_falloff_inverse_distance audio_falloff_inverse_distance_clamped audio_falloff_linear_distance audio_falloff_linear_distance_clamped audio_falloff_exponent_distance audio_falloff_exponent_distance_clamped audio_old_system audio_new_system audio_mono audio_stereo audio_3d cr_default cr_none cr_arrow cr_cross cr_beam cr_size_nesw cr_size_ns cr_size_nwse cr_size_we cr_uparrow cr_hourglass cr_drag cr_appstart cr_handpoint cr_size_all spritespeed_framespersecond spritespeed_framespergameframe asset_object asset_unknown asset_sprite asset_sound asset_room asset_path asset_script asset_font asset_timeline asset_tiles asset_shader fa_readonly fa_hidden fa_sysfile fa_volumeid fa_directory fa_archive  ds_type_map ds_type_list ds_type_stack ds_type_queue ds_type_grid ds_type_priority ef_explosion ef_ring ef_ellipse ef_firework ef_smoke ef_smokeup ef_star ef_spark ef_flare ef_cloud ef_rain ef_snow pt_shape_pixel pt_shape_disk pt_shape_square pt_shape_line pt_shape_star pt_shape_circle pt_shape_ring pt_shape_sphere pt_shape_flare pt_shape_spark pt_shape_explosion pt_shape_cloud pt_shape_smoke pt_shape_snow ps_distr_linear ps_distr_gaussian ps_distr_invgaussian ps_shape_rectangle ps_shape_ellipse ps_shape_diamond ps_shape_line ty_real ty_string dll_cdecl dll_stdcall matrix_view matrix_projection matrix_world os_win32 os_windows os_macosx os_ios os_android os_symbian os_linux os_unknown os_winphone os_tizen os_win8native os_wiiu os_3ds  os_psvita os_bb10 os_ps4 os_xboxone os_ps3 os_xbox360 os_uwp os_tvos os_switch browser_not_a_browser browser_unknown browser_ie browser_firefox browser_chrome browser_safari browser_safari_mobile browser_opera browser_tizen browser_edge browser_windows_store browser_ie_mobile  device_ios_unknown device_ios_iphone device_ios_iphone_retina device_ios_ipad device_ios_ipad_retina device_ios_iphone5 device_ios_iphone6 device_ios_iphone6plus device_emulator device_tablet display_landscape display_landscape_flipped display_portrait display_portrait_flipped tm_sleep tm_countvsyncs of_challenge_win of_challen ge_lose of_challenge_tie leaderboard_type_number leaderboard_type_time_mins_secs cmpfunc_never cmpfunc_less cmpfunc_equal cmpfunc_lessequal cmpfunc_greater cmpfunc_notequal cmpfunc_greaterequal cmpfunc_always cull_noculling cull_clockwise cull_counterclockwise lighttype_dir lighttype_point iap_ev_storeload iap_ev_product iap_ev_purchase iap_ev_consume iap_ev_restore iap_storeload_ok iap_storeload_failed iap_status_uninitialised iap_status_unavailable iap_status_loading iap_status_available iap_status_processing iap_status_restoring iap_failed iap_unavailable iap_available iap_purchased iap_canceled iap_refunded fb_login_default fb_login_fallback_to_webview fb_login_no_fallback_to_webview fb_login_forcing_webview fb_login_use_system_account fb_login_forcing_safari  phy_joint_anchor_1_x phy_joint_anchor_1_y phy_joint_anchor_2_x phy_joint_anchor_2_y phy_joint_reaction_force_x phy_joint_reaction_force_y phy_joint_reaction_torque phy_joint_motor_speed phy_joint_angle phy_joint_motor_torque phy_joint_max_motor_torque phy_joint_translation phy_joint_speed phy_joint_motor_force phy_joint_max_motor_force phy_joint_length_1 phy_joint_length_2 phy_joint_damping_ratio phy_joint_frequency phy_joint_lower_angle_limit phy_joint_upper_angle_limit phy_joint_angle_limits phy_joint_max_length phy_joint_max_torque phy_joint_max_force phy_debug_render_aabb phy_debug_render_collision_pairs phy_debug_render_coms phy_debug_render_core_shapes phy_debug_render_joints phy_debug_render_obb phy_debug_render_shapes  phy_particle_flag_water phy_particle_flag_zombie phy_particle_flag_wall phy_particle_flag_spring phy_particle_flag_elastic phy_particle_flag_viscous phy_particle_flag_powder phy_particle_flag_tensile phy_particle_flag_colourmixing phy_particle_flag_colormixing phy_particle_group_flag_solid phy_particle_group_flag_rigid phy_particle_data_flag_typeflags phy_particle_data_flag_position phy_particle_data_flag_velocity phy_particle_data_flag_colour phy_particle_data_flag_color phy_particle_data_flag_category  achievement_our_info achievement_friends_info achievement_leaderboard_info achievement_achievement_info achievement_filter_all_players achievement_filter_friends_only achievement_filter_favorites_only achievement_type_achievement_challenge achievement_type_score_challenge achievement_pic_loaded  achievement_show_ui achievement_show_profile achievement_show_leaderboard achievement_show_achievement achievement_show_bank achievement_show_friend_picker achievement_show_purchase_prompt network_socket_tcp network_socket_udp network_socket_bluetooth network_type_connect network_type_disconnect network_type_data network_type_non_blocking_connect network_config_connect_timeout network_config_use_non_blocking_socket network_config_enable_reliable_udp network_config_disable_reliable_udp buffer_fixed buffer_grow buffer_wrap buffer_fast buffer_vbuffer buffer_network buffer_u8 buffer_s8 buffer_u16 buffer_s16 buffer_u32 buffer_s32 buffer_u64 buffer_f16 buffer_f32 buffer_f64 buffer_bool buffer_text buffer_string buffer_surface_copy buffer_seek_start buffer_seek_relative buffer_seek_end buffer_generalerror buffer_outofspace buffer_outofbounds buffer_invalidtype  text_type button_type input_type ANSI_CHARSET DEFAULT_CHARSET EASTEUROPE_CHARSET RUSSIAN_CHARSET SYMBOL_CHARSET SHIFTJIS_CHARSET HANGEUL_CHARSET GB2312_CHARSET CHINESEBIG5_CHARSET JOHAB_CHARSET HEBREW_CHARSET ARABIC_CHARSET GREEK_CHARSET TURKISH_CHARSET VIETNAMESE_CHARSET THAI_CHARSET MAC_CHARSET BALTIC_CHARSET OEM_CHARSET  gp_face1 gp_face2 gp_face3 gp_face4 gp_shoulderl gp_shoulderr gp_shoulderlb gp_shoulderrb gp_select gp_start gp_stickl gp_stickr gp_padu gp_padd gp_padl gp_padr gp_axislh gp_axislv gp_axisrh gp_axisrv ov_friends ov_community ov_players ov_settings ov_gamegroup ov_achievements lb_sort_none lb_sort_ascending lb_sort_descending lb_disp_none lb_disp_numeric lb_disp_time_sec lb_disp_time_ms ugc_result_success ugc_filetype_community ugc_filetype_microtrans ugc_visibility_public ugc_visibility_friends_only ugc_visibility_private ugc_query_RankedByVote ugc_query_RankedByPublicationDate ugc_query_AcceptedForGameRankedByAcceptanceDate ugc_query_RankedByTrend ugc_query_FavoritedByFriendsRankedByPublicationDate ugc_query_CreatedByFriendsRankedByPublicationDate ugc_query_RankedByNumTimesReported ugc_query_CreatedByFollowedUsersRankedByPublicationDate ugc_query_NotYetRated ugc_query_RankedByTotalVotesAsc ugc_query_RankedByVotesUp ugc_query_RankedByTextSearch ugc_sortorder_CreationOrderDesc ugc_sortorder_CreationOrderAsc ugc_sortorder_TitleAsc ugc_sortorder_LastUpdatedDesc ugc_sortorder_SubscriptionDateDesc ugc_sortorder_VoteScoreDesc ugc_sortorder_ForModeration ugc_list_Published ugc_list_VotedOn ugc_list_VotedUp ugc_list_VotedDown ugc_list_WillVoteLater ugc_list_Favorited ugc_list_Subscribed ugc_list_UsedOrPlayed ugc_list_Followed ugc_match_Items ugc_match_Items_Mtx ugc_match_Items_ReadyToUse ugc_match_Collections ugc_match_Artwork ugc_match_Videos ugc_match_Screenshots ugc_match_AllGuides ugc_match_WebGuides ugc_match_IntegratedGuides ugc_match_UsableInGame ugc_match_ControllerBindings  vertex_usage_position vertex_usage_colour vertex_usage_color vertex_usage_normal vertex_usage_texcoord vertex_usage_textcoord vertex_usage_blendweight vertex_usage_blendindices vertex_usage_psize vertex_usage_tangent vertex_usage_binormal vertex_usage_fog vertex_usage_depth vertex_usage_sample vertex_type_float1 vertex_type_float2 vertex_type_float3 vertex_type_float4 vertex_type_colour vertex_type_color vertex_type_ubyte4 layerelementtype_undefined layerelementtype_background layerelementtype_instance layerelementtype_oldtilemap layerelementtype_sprite layerelementtype_tilemap layerelementtype_particlesystem layerelementtype_tile tile_rotate tile_flip tile_mirror tile_index_mask kbv_type_default kbv_type_ascii kbv_type_url kbv_type_email kbv_type_numbers kbv_type_phone kbv_type_phone_name kbv_returnkey_default kbv_returnkey_go kbv_returnkey_google kbv_returnkey_join kbv_returnkey_next kbv_returnkey_route kbv_returnkey_search kbv_returnkey_send kbv_returnkey_yahoo kbv_returnkey_done kbv_returnkey_continue kbv_returnkey_emergency kbv_autocapitalize_none kbv_autocapitalize_words kbv_autocapitalize_sentences kbv_autocapitalize_characters",
        symbol: "argument_relative argument argument0 argument1 argument2 argument3 argument4 argument5 argument6 argument7 argument8 argument9 argument10 argument11 argument12 argument13 argument14 argument15 argument_count x|0 y|0 xprevious yprevious xstart ystart hspeed vspeed direction speed friction gravity gravity_direction path_index path_position path_positionprevious path_speed path_scale path_orientation path_endaction object_index id solid persistent mask_index instance_count instance_id room_speed fps fps_real current_time current_year current_month current_day current_weekday current_hour current_minute current_second alarm timeline_index timeline_position timeline_speed timeline_running timeline_loop room room_first room_last room_width room_height room_caption room_persistent score lives health show_score show_lives show_health caption_score caption_lives caption_health event_type event_number event_object event_action application_surface gamemaker_pro gamemaker_registered gamemaker_version error_occurred error_last debug_mode keyboard_key keyboard_lastkey keyboard_lastchar keyboard_string mouse_x mouse_y mouse_button mouse_lastbutton cursor_sprite visible sprite_index sprite_width sprite_height sprite_xoffset sprite_yoffset image_number image_index image_speed depth image_xscale image_yscale image_angle image_alpha image_blend bbox_left bbox_right bbox_top bbox_bottom layer background_colour  background_showcolour background_color background_showcolor view_enabled view_current view_visible view_xview view_yview view_wview view_hview view_xport view_yport view_wport view_hport view_angle view_hborder view_vborder view_hspeed view_vspeed view_object view_surface_id view_camera game_id game_display_name game_project_name game_save_id working_directory temp_directory program_directory browser_width browser_height os_type os_device os_browser os_version display_aa async_load delta_time webgl_enabled event_data iap_data phy_rotation phy_position_x phy_position_y phy_angular_velocity phy_linear_velocity_x phy_linear_velocity_y phy_speed_x phy_speed_y phy_speed phy_angular_damping phy_linear_damping phy_bullet phy_fixed_rotation phy_active phy_mass phy_inertia phy_com_x phy_com_y phy_dynamic phy_kinematic phy_sleeping phy_collision_points phy_collision_x phy_collision_y phy_col_normal_x phy_col_normal_y phy_position_xprevious phy_position_yprevious"
      };
      return {
        name: "GML",
        case_insensitive: false,
        // language is case-insensitive
        keywords: GML_KEYWORDS,
        contains: [
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          hljs5.APOS_STRING_MODE,
          hljs5.QUOTE_STRING_MODE,
          hljs5.C_NUMBER_MODE
        ]
      };
    }
    module.exports = gml;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/go.js
var require_go = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/go.js"(exports, module) {
    init_process_shim();
    function go(hljs5) {
      const GO_KEYWORDS = {
        keyword: "break default func interface select case map struct chan else goto package switch const fallthrough if range type continue for import return var go defer bool byte complex64 complex128 float32 float64 int8 int16 int32 int64 string uint8 uint16 uint32 uint64 int uint uintptr rune",
        literal: "true false iota nil",
        built_in: "append cap close complex copy imag len make new panic print println real recover delete"
      };
      return {
        name: "Go",
        aliases: ["golang"],
        keywords: GO_KEYWORDS,
        illegal: "</",
        contains: [
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          {
            className: "string",
            variants: [
              hljs5.QUOTE_STRING_MODE,
              hljs5.APOS_STRING_MODE,
              {
                begin: "`",
                end: "`"
              }
            ]
          },
          {
            className: "number",
            variants: [
              {
                begin: hljs5.C_NUMBER_RE + "[i]",
                relevance: 1
              },
              hljs5.C_NUMBER_MODE
            ]
          },
          {
            begin: /:=/
            // relevance booster
          },
          {
            className: "function",
            beginKeywords: "func",
            end: "\\s*(\\{|$)",
            excludeEnd: true,
            contains: [
              hljs5.TITLE_MODE,
              {
                className: "params",
                begin: /\(/,
                end: /\)/,
                keywords: GO_KEYWORDS,
                illegal: /["']/
              }
            ]
          }
        ]
      };
    }
    module.exports = go;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/golo.js
var require_golo = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/golo.js"(exports, module) {
    init_process_shim();
    function golo(hljs5) {
      return {
        name: "Golo",
        keywords: {
          keyword: "println readln print import module function local return let var while for foreach times in case when match with break continue augment augmentation each find filter reduce if then else otherwise try catch finally raise throw orIfNull DynamicObject|10 DynamicVariable struct Observable map set vector list array",
          literal: "true false null"
        },
        contains: [
          hljs5.HASH_COMMENT_MODE,
          hljs5.QUOTE_STRING_MODE,
          hljs5.C_NUMBER_MODE,
          {
            className: "meta",
            begin: "@[A-Za-z]+"
          }
        ]
      };
    }
    module.exports = golo;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/gradle.js
var require_gradle = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/gradle.js"(exports, module) {
    init_process_shim();
    function gradle(hljs5) {
      return {
        name: "Gradle",
        case_insensitive: true,
        keywords: {
          keyword: "task project allprojects subprojects artifacts buildscript configurations dependencies repositories sourceSets description delete from into include exclude source classpath destinationDir includes options sourceCompatibility targetCompatibility group flatDir doLast doFirst flatten todir fromdir ant def abstract break case catch continue default do else extends final finally for if implements instanceof native new private protected public return static switch synchronized throw throws transient try volatile while strictfp package import false null super this true antlrtask checkstyle codenarc copy boolean byte char class double float int interface long short void compile runTime file fileTree abs any append asList asWritable call collect compareTo count div dump each eachByte eachFile eachLine every find findAll flatten getAt getErr getIn getOut getText grep immutable inject inspect intersect invokeMethods isCase join leftShift minus multiply newInputStream newOutputStream newPrintWriter newReader newWriter next plus pop power previous print println push putAt read readBytes readLines reverse reverseEach round size sort splitEachLine step subMap times toInteger toList tokenize upto waitForOrKill withPrintWriter withReader withStream withWriter withWriterAppend write writeLine"
        },
        contains: [
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          hljs5.APOS_STRING_MODE,
          hljs5.QUOTE_STRING_MODE,
          hljs5.NUMBER_MODE,
          hljs5.REGEXP_MODE
        ]
      };
    }
    module.exports = gradle;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/groovy.js
var require_groovy = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/groovy.js"(exports, module) {
    init_process_shim();
    function source(re2) {
      if (!re2) return null;
      if (typeof re2 === "string") return re2;
      return re2.source;
    }
    function lookahead(re2) {
      return concat("(?=", re2, ")");
    }
    function concat(...args) {
      const joined = args.map((x2) => source(x2)).join("");
      return joined;
    }
    function variants(variants2, obj = {}) {
      obj.variants = variants2;
      return obj;
    }
    function groovy(hljs5) {
      const IDENT_RE3 = "[A-Za-z0-9_$]+";
      const COMMENT = variants([
        hljs5.C_LINE_COMMENT_MODE,
        hljs5.C_BLOCK_COMMENT_MODE,
        hljs5.COMMENT(
          "/\\*\\*",
          "\\*/",
          {
            relevance: 0,
            contains: [
              {
                // eat up @'s in emails to prevent them to be recognized as doctags
                begin: /\w+@/,
                relevance: 0
              },
              {
                className: "doctag",
                begin: "@[A-Za-z]+"
              }
            ]
          }
        )
      ]);
      const REGEXP = {
        className: "regexp",
        begin: /~?\/[^\/\n]+\//,
        contains: [hljs5.BACKSLASH_ESCAPE]
      };
      const NUMBER = variants([
        hljs5.BINARY_NUMBER_MODE,
        hljs5.C_NUMBER_MODE
      ]);
      const STRING = variants(
        [
          {
            begin: /"""/,
            end: /"""/
          },
          {
            begin: /'''/,
            end: /'''/
          },
          {
            begin: "\\$/",
            end: "/\\$",
            relevance: 10
          },
          hljs5.APOS_STRING_MODE,
          hljs5.QUOTE_STRING_MODE
        ],
        {
          className: "string"
        }
      );
      return {
        name: "Groovy",
        keywords: {
          built_in: "this super",
          literal: "true false null",
          keyword: "byte short char int long boolean float double void def as in assert trait abstract static volatile transient public private protected synchronized final class interface enum if else for while switch case break default continue throw throws try catch finally implements extends new import package return instanceof"
        },
        contains: [
          hljs5.SHEBANG({
            binary: "groovy",
            relevance: 10
          }),
          COMMENT,
          STRING,
          REGEXP,
          NUMBER,
          {
            className: "class",
            beginKeywords: "class interface trait enum",
            end: /\{/,
            illegal: ":",
            contains: [
              {
                beginKeywords: "extends implements"
              },
              hljs5.UNDERSCORE_TITLE_MODE
            ]
          },
          {
            className: "meta",
            begin: "@[A-Za-z]+",
            relevance: 0
          },
          {
            // highlight map keys and named parameters as attrs
            className: "attr",
            begin: IDENT_RE3 + "[ 	]*:",
            relevance: 0
          },
          {
            // catch middle element of the ternary operator
            // to avoid highlight it as a label, named parameter, or map key
            begin: /\?/,
            end: /:/,
            relevance: 0,
            contains: [
              COMMENT,
              STRING,
              REGEXP,
              NUMBER,
              "self"
            ]
          },
          {
            // highlight labeled statements
            className: "symbol",
            begin: "^[ 	]*" + lookahead(IDENT_RE3 + ":"),
            excludeBegin: true,
            end: IDENT_RE3 + ":",
            relevance: 0
          }
        ],
        illegal: /#|<\//
      };
    }
    module.exports = groovy;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/haml.js
var require_haml = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/haml.js"(exports, module) {
    init_process_shim();
    function haml(hljs5) {
      return {
        name: "HAML",
        case_insensitive: true,
        contains: [
          {
            className: "meta",
            begin: "^!!!( (5|1\\.1|Strict|Frameset|Basic|Mobile|RDFa|XML\\b.*))?$",
            relevance: 10
          },
          // FIXME these comments should be allowed to span indented lines
          hljs5.COMMENT(
            "^\\s*(!=#|=#|-#|/).*$",
            false,
            {
              relevance: 0
            }
          ),
          {
            begin: "^\\s*(-|=|!=)(?!#)",
            starts: {
              end: "\\n",
              subLanguage: "ruby"
            }
          },
          {
            className: "tag",
            begin: "^\\s*%",
            contains: [
              {
                className: "selector-tag",
                begin: "\\w+"
              },
              {
                className: "selector-id",
                begin: "#[\\w-]+"
              },
              {
                className: "selector-class",
                begin: "\\.[\\w-]+"
              },
              {
                begin: /\{\s*/,
                end: /\s*\}/,
                contains: [
                  {
                    begin: ":\\w+\\s*=>",
                    end: ",\\s+",
                    returnBegin: true,
                    endsWithParent: true,
                    contains: [
                      {
                        className: "attr",
                        begin: ":\\w+"
                      },
                      hljs5.APOS_STRING_MODE,
                      hljs5.QUOTE_STRING_MODE,
                      {
                        begin: "\\w+",
                        relevance: 0
                      }
                    ]
                  }
                ]
              },
              {
                begin: "\\(\\s*",
                end: "\\s*\\)",
                excludeEnd: true,
                contains: [
                  {
                    begin: "\\w+\\s*=",
                    end: "\\s+",
                    returnBegin: true,
                    endsWithParent: true,
                    contains: [
                      {
                        className: "attr",
                        begin: "\\w+",
                        relevance: 0
                      },
                      hljs5.APOS_STRING_MODE,
                      hljs5.QUOTE_STRING_MODE,
                      {
                        begin: "\\w+",
                        relevance: 0
                      }
                    ]
                  }
                ]
              }
            ]
          },
          {
            begin: "^\\s*[=~]\\s*"
          },
          {
            begin: /#\{/,
            starts: {
              end: /\}/,
              subLanguage: "ruby"
            }
          }
        ]
      };
    }
    module.exports = haml;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/handlebars.js
var require_handlebars = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/handlebars.js"(exports, module) {
    init_process_shim();
    function source(re2) {
      if (!re2) return null;
      if (typeof re2 === "string") return re2;
      return re2.source;
    }
    function anyNumberOfTimes(re2) {
      return concat("(", re2, ")*");
    }
    function optional(re2) {
      return concat("(", re2, ")?");
    }
    function concat(...args) {
      const joined = args.map((x2) => source(x2)).join("");
      return joined;
    }
    function either(...args) {
      const joined = "(" + args.map((x2) => source(x2)).join("|") + ")";
      return joined;
    }
    function handlebars(hljs5) {
      const BUILT_INS3 = {
        "builtin-name": [
          "action",
          "bindattr",
          "collection",
          "component",
          "concat",
          "debugger",
          "each",
          "each-in",
          "get",
          "hash",
          "if",
          "in",
          "input",
          "link-to",
          "loc",
          "log",
          "lookup",
          "mut",
          "outlet",
          "partial",
          "query-params",
          "render",
          "template",
          "textarea",
          "unbound",
          "unless",
          "view",
          "with",
          "yield"
        ]
      };
      const LITERALS3 = {
        literal: [
          "true",
          "false",
          "undefined",
          "null"
        ]
      };
      const DOUBLE_QUOTED_ID_REGEX = /""|"[^"]+"/;
      const SINGLE_QUOTED_ID_REGEX = /''|'[^']+'/;
      const BRACKET_QUOTED_ID_REGEX = /\[\]|\[[^\]]+\]/;
      const PLAIN_ID_REGEX = /[^\s!"#%&'()*+,.\/;<=>@\[\\\]^`{|}~]+/;
      const PATH_DELIMITER_REGEX = /(\.|\/)/;
      const ANY_ID = either(
        DOUBLE_QUOTED_ID_REGEX,
        SINGLE_QUOTED_ID_REGEX,
        BRACKET_QUOTED_ID_REGEX,
        PLAIN_ID_REGEX
      );
      const IDENTIFIER_REGEX = concat(
        optional(/\.|\.\/|\//),
        // relative or absolute path
        ANY_ID,
        anyNumberOfTimes(concat(
          PATH_DELIMITER_REGEX,
          ANY_ID
        ))
      );
      const HASH_PARAM_REGEX = concat(
        "(",
        BRACKET_QUOTED_ID_REGEX,
        "|",
        PLAIN_ID_REGEX,
        ")(?==)"
      );
      const HELPER_NAME_OR_PATH_EXPRESSION = {
        begin: IDENTIFIER_REGEX,
        lexemes: /[\w.\/]+/
      };
      const HELPER_PARAMETER = hljs5.inherit(HELPER_NAME_OR_PATH_EXPRESSION, {
        keywords: LITERALS3
      });
      const SUB_EXPRESSION = {
        begin: /\(/,
        end: /\)/
        // the "contains" is added below when all necessary sub-modes are defined
      };
      const HASH = {
        // fka "attribute-assignment", parameters of the form 'key=value'
        className: "attr",
        begin: HASH_PARAM_REGEX,
        relevance: 0,
        starts: {
          begin: /=/,
          end: /=/,
          starts: {
            contains: [
              hljs5.NUMBER_MODE,
              hljs5.QUOTE_STRING_MODE,
              hljs5.APOS_STRING_MODE,
              HELPER_PARAMETER,
              SUB_EXPRESSION
            ]
          }
        }
      };
      const BLOCK_PARAMS = {
        // parameters of the form '{{#with x as | y |}}...{{/with}}'
        begin: /as\s+\|/,
        keywords: {
          keyword: "as"
        },
        end: /\|/,
        contains: [
          {
            // define sub-mode in order to prevent highlighting of block-parameter named "as"
            begin: /\w+/
          }
        ]
      };
      const HELPER_PARAMETERS = {
        contains: [
          hljs5.NUMBER_MODE,
          hljs5.QUOTE_STRING_MODE,
          hljs5.APOS_STRING_MODE,
          BLOCK_PARAMS,
          HASH,
          HELPER_PARAMETER,
          SUB_EXPRESSION
        ],
        returnEnd: true
        // the property "end" is defined through inheritance when the mode is used. If depends
        // on the surrounding mode, but "endsWithParent" does not work here (i.e. it includes the
        // end-token of the surrounding mode)
      };
      const SUB_EXPRESSION_CONTENTS = hljs5.inherit(HELPER_NAME_OR_PATH_EXPRESSION, {
        className: "name",
        keywords: BUILT_INS3,
        starts: hljs5.inherit(HELPER_PARAMETERS, {
          end: /\)/
        })
      });
      SUB_EXPRESSION.contains = [SUB_EXPRESSION_CONTENTS];
      const OPENING_BLOCK_MUSTACHE_CONTENTS = hljs5.inherit(HELPER_NAME_OR_PATH_EXPRESSION, {
        keywords: BUILT_INS3,
        className: "name",
        starts: hljs5.inherit(HELPER_PARAMETERS, {
          end: /\}\}/
        })
      });
      const CLOSING_BLOCK_MUSTACHE_CONTENTS = hljs5.inherit(HELPER_NAME_OR_PATH_EXPRESSION, {
        keywords: BUILT_INS3,
        className: "name"
      });
      const BASIC_MUSTACHE_CONTENTS = hljs5.inherit(HELPER_NAME_OR_PATH_EXPRESSION, {
        className: "name",
        keywords: BUILT_INS3,
        starts: hljs5.inherit(HELPER_PARAMETERS, {
          end: /\}\}/
        })
      });
      const ESCAPE_MUSTACHE_WITH_PRECEEDING_BACKSLASH = {
        begin: /\\\{\{/,
        skip: true
      };
      const PREVENT_ESCAPE_WITH_ANOTHER_PRECEEDING_BACKSLASH = {
        begin: /\\\\(?=\{\{)/,
        skip: true
      };
      return {
        name: "Handlebars",
        aliases: [
          "hbs",
          "html.hbs",
          "html.handlebars",
          "htmlbars"
        ],
        case_insensitive: true,
        subLanguage: "xml",
        contains: [
          ESCAPE_MUSTACHE_WITH_PRECEEDING_BACKSLASH,
          PREVENT_ESCAPE_WITH_ANOTHER_PRECEEDING_BACKSLASH,
          hljs5.COMMENT(/\{\{!--/, /--\}\}/),
          hljs5.COMMENT(/\{\{!/, /\}\}/),
          {
            // open raw block "{{{{raw}}}} content not evaluated {{{{/raw}}}}"
            className: "template-tag",
            begin: /\{\{\{\{(?!\/)/,
            end: /\}\}\}\}/,
            contains: [OPENING_BLOCK_MUSTACHE_CONTENTS],
            starts: {
              end: /\{\{\{\{\//,
              returnEnd: true,
              subLanguage: "xml"
            }
          },
          {
            // close raw block
            className: "template-tag",
            begin: /\{\{\{\{\//,
            end: /\}\}\}\}/,
            contains: [CLOSING_BLOCK_MUSTACHE_CONTENTS]
          },
          {
            // open block statement
            className: "template-tag",
            begin: /\{\{#/,
            end: /\}\}/,
            contains: [OPENING_BLOCK_MUSTACHE_CONTENTS]
          },
          {
            className: "template-tag",
            begin: /\{\{(?=else\}\})/,
            end: /\}\}/,
            keywords: "else"
          },
          {
            className: "template-tag",
            begin: /\{\{(?=else if)/,
            end: /\}\}/,
            keywords: "else if"
          },
          {
            // closing block statement
            className: "template-tag",
            begin: /\{\{\//,
            end: /\}\}/,
            contains: [CLOSING_BLOCK_MUSTACHE_CONTENTS]
          },
          {
            // template variable or helper-call that is NOT html-escaped
            className: "template-variable",
            begin: /\{\{\{/,
            end: /\}\}\}/,
            contains: [BASIC_MUSTACHE_CONTENTS]
          },
          {
            // template variable or helper-call that is html-escaped
            className: "template-variable",
            begin: /\{\{/,
            end: /\}\}/,
            contains: [BASIC_MUSTACHE_CONTENTS]
          }
        ]
      };
    }
    module.exports = handlebars;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/haskell.js
var require_haskell = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/haskell.js"(exports, module) {
    init_process_shim();
    function haskell(hljs5) {
      const COMMENT = {
        variants: [
          hljs5.COMMENT("--", "$"),
          hljs5.COMMENT(
            /\{-/,
            /-\}/,
            {
              contains: ["self"]
            }
          )
        ]
      };
      const PRAGMA = {
        className: "meta",
        begin: /\{-#/,
        end: /#-\}/
      };
      const PREPROCESSOR = {
        className: "meta",
        begin: "^#",
        end: "$"
      };
      const CONSTRUCTOR = {
        className: "type",
        begin: "\\b[A-Z][\\w']*",
        // TODO: other constructors (build-in, infix).
        relevance: 0
      };
      const LIST = {
        begin: "\\(",
        end: "\\)",
        illegal: '"',
        contains: [
          PRAGMA,
          PREPROCESSOR,
          {
            className: "type",
            begin: "\\b[A-Z][\\w]*(\\((\\.\\.|,|\\w+)\\))?"
          },
          hljs5.inherit(hljs5.TITLE_MODE, {
            begin: "[_a-z][\\w']*"
          }),
          COMMENT
        ]
      };
      const RECORD = {
        begin: /\{/,
        end: /\}/,
        contains: LIST.contains
      };
      return {
        name: "Haskell",
        aliases: ["hs"],
        keywords: "let in if then else case of where do module import hiding qualified type data newtype deriving class instance as default infix infixl infixr foreign export ccall stdcall cplusplus jvm dotnet safe unsafe family forall mdo proc rec",
        contains: [
          // Top-level constructions.
          {
            beginKeywords: "module",
            end: "where",
            keywords: "module where",
            contains: [
              LIST,
              COMMENT
            ],
            illegal: "\\W\\.|;"
          },
          {
            begin: "\\bimport\\b",
            end: "$",
            keywords: "import qualified as hiding",
            contains: [
              LIST,
              COMMENT
            ],
            illegal: "\\W\\.|;"
          },
          {
            className: "class",
            begin: "^(\\s*)?(class|instance)\\b",
            end: "where",
            keywords: "class family instance where",
            contains: [
              CONSTRUCTOR,
              LIST,
              COMMENT
            ]
          },
          {
            className: "class",
            begin: "\\b(data|(new)?type)\\b",
            end: "$",
            keywords: "data family type newtype deriving",
            contains: [
              PRAGMA,
              CONSTRUCTOR,
              LIST,
              RECORD,
              COMMENT
            ]
          },
          {
            beginKeywords: "default",
            end: "$",
            contains: [
              CONSTRUCTOR,
              LIST,
              COMMENT
            ]
          },
          {
            beginKeywords: "infix infixl infixr",
            end: "$",
            contains: [
              hljs5.C_NUMBER_MODE,
              COMMENT
            ]
          },
          {
            begin: "\\bforeign\\b",
            end: "$",
            keywords: "foreign import export ccall stdcall cplusplus jvm dotnet safe unsafe",
            contains: [
              CONSTRUCTOR,
              hljs5.QUOTE_STRING_MODE,
              COMMENT
            ]
          },
          {
            className: "meta",
            begin: "#!\\/usr\\/bin\\/env runhaskell",
            end: "$"
          },
          // "Whitespaces".
          PRAGMA,
          PREPROCESSOR,
          // Literals and names.
          // TODO: characters.
          hljs5.QUOTE_STRING_MODE,
          hljs5.C_NUMBER_MODE,
          CONSTRUCTOR,
          hljs5.inherit(hljs5.TITLE_MODE, {
            begin: "^[_a-z][\\w']*"
          }),
          COMMENT,
          {
            // No markup, relevance booster
            begin: "->|<-"
          }
        ]
      };
    }
    module.exports = haskell;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/haxe.js
var require_haxe = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/haxe.js"(exports, module) {
    init_process_shim();
    function haxe(hljs5) {
      const HAXE_BASIC_TYPES = "Int Float String Bool Dynamic Void Array ";
      return {
        name: "Haxe",
        aliases: ["hx"],
        keywords: {
          keyword: "break case cast catch continue default do dynamic else enum extern for function here if import in inline never new override package private get set public return static super switch this throw trace try typedef untyped using var while " + HAXE_BASIC_TYPES,
          built_in: "trace this",
          literal: "true false null _"
        },
        contains: [
          {
            className: "string",
            // interpolate-able strings
            begin: "'",
            end: "'",
            contains: [
              hljs5.BACKSLASH_ESCAPE,
              {
                className: "subst",
                // interpolation
                begin: "\\$\\{",
                end: "\\}"
              },
              {
                className: "subst",
                // interpolation
                begin: "\\$",
                end: /\W\}/
              }
            ]
          },
          hljs5.QUOTE_STRING_MODE,
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          hljs5.C_NUMBER_MODE,
          {
            className: "meta",
            // compiler meta
            begin: "@:",
            end: "$"
          },
          {
            className: "meta",
            // compiler conditionals
            begin: "#",
            end: "$",
            keywords: {
              "meta-keyword": "if else elseif end error"
            }
          },
          {
            className: "type",
            // function types
            begin: ":[ 	]*",
            end: "[^A-Za-z0-9_ 	\\->]",
            excludeBegin: true,
            excludeEnd: true,
            relevance: 0
          },
          {
            className: "type",
            // types
            begin: ":[ 	]*",
            end: "\\W",
            excludeBegin: true,
            excludeEnd: true
          },
          {
            className: "type",
            // instantiation
            begin: "new *",
            end: "\\W",
            excludeBegin: true,
            excludeEnd: true
          },
          {
            className: "class",
            // enums
            beginKeywords: "enum",
            end: "\\{",
            contains: [hljs5.TITLE_MODE]
          },
          {
            className: "class",
            // abstracts
            beginKeywords: "abstract",
            end: "[\\{$]",
            contains: [
              {
                className: "type",
                begin: "\\(",
                end: "\\)",
                excludeBegin: true,
                excludeEnd: true
              },
              {
                className: "type",
                begin: "from +",
                end: "\\W",
                excludeBegin: true,
                excludeEnd: true
              },
              {
                className: "type",
                begin: "to +",
                end: "\\W",
                excludeBegin: true,
                excludeEnd: true
              },
              hljs5.TITLE_MODE
            ],
            keywords: {
              keyword: "abstract from to"
            }
          },
          {
            className: "class",
            // classes
            begin: "\\b(class|interface) +",
            end: "[\\{$]",
            excludeEnd: true,
            keywords: "class interface",
            contains: [
              {
                className: "keyword",
                begin: "\\b(extends|implements) +",
                keywords: "extends implements",
                contains: [
                  {
                    className: "type",
                    begin: hljs5.IDENT_RE,
                    relevance: 0
                  }
                ]
              },
              hljs5.TITLE_MODE
            ]
          },
          {
            className: "function",
            beginKeywords: "function",
            end: "\\(",
            excludeEnd: true,
            illegal: "\\S",
            contains: [hljs5.TITLE_MODE]
          }
        ],
        illegal: /<\//
      };
    }
    module.exports = haxe;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/hsp.js
var require_hsp = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/hsp.js"(exports, module) {
    init_process_shim();
    function hsp(hljs5) {
      return {
        name: "HSP",
        case_insensitive: true,
        keywords: {
          $pattern: /[\w._]+/,
          keyword: "goto gosub return break repeat loop continue wait await dim sdim foreach dimtype dup dupptr end stop newmod delmod mref run exgoto on mcall assert logmes newlab resume yield onexit onerror onkey onclick oncmd exist delete mkdir chdir dirlist bload bsave bcopy memfile if else poke wpoke lpoke getstr chdpm memexpand memcpy memset notesel noteadd notedel noteload notesave randomize noteunsel noteget split strrep setease button chgdisp exec dialog mmload mmplay mmstop mci pset pget syscolor mes print title pos circle cls font sysfont objsize picload color palcolor palette redraw width gsel gcopy gzoom gmode bmpsave hsvcolor getkey listbox chkbox combox input mesbox buffer screen bgscr mouse objsel groll line clrobj boxf objprm objmode stick grect grotate gsquare gradf objimage objskip objenable celload celdiv celput newcom querycom delcom cnvstow comres axobj winobj sendmsg comevent comevarg sarrayconv callfunc cnvwtos comevdisp libptr system hspstat hspver stat cnt err strsize looplev sublev iparam wparam lparam refstr refdval int rnd strlen length length2 length3 length4 vartype gettime peek wpeek lpeek varptr varuse noteinfo instr abs limit getease str strmid strf getpath strtrim sin cos tan atan sqrt double absf expf logf limitf powf geteasef mousex mousey mousew hwnd hinstance hdc ginfo objinfo dirinfo sysinfo thismod __hspver__ __hsp30__ __date__ __time__ __line__ __file__ _debug __hspdef__ and or xor not screen_normal screen_palette screen_hide screen_fixedsize screen_tool screen_frame gmode_gdi gmode_mem gmode_rgb0 gmode_alpha gmode_rgb0alpha gmode_add gmode_sub gmode_pixela ginfo_mx ginfo_my ginfo_act ginfo_sel ginfo_wx1 ginfo_wy1 ginfo_wx2 ginfo_wy2 ginfo_vx ginfo_vy ginfo_sizex ginfo_sizey ginfo_winx ginfo_winy ginfo_mesx ginfo_mesy ginfo_r ginfo_g ginfo_b ginfo_paluse ginfo_dispx ginfo_dispy ginfo_cx ginfo_cy ginfo_intid ginfo_newid ginfo_sx ginfo_sy objinfo_mode objinfo_bmscr objinfo_hwnd notemax notesize dir_cur dir_exe dir_win dir_sys dir_cmdline dir_desktop dir_mydoc dir_tv font_normal font_bold font_italic font_underline font_strikeout font_antialias objmode_normal objmode_guifont objmode_usefont gsquare_grad msgothic msmincho do until while wend for next _break _continue switch case default swbreak swend ddim ldim alloc m_pi rad2deg deg2rad ease_linear ease_quad_in ease_quad_out ease_quad_inout ease_cubic_in ease_cubic_out ease_cubic_inout ease_quartic_in ease_quartic_out ease_quartic_inout ease_bounce_in ease_bounce_out ease_bounce_inout ease_shake_in ease_shake_out ease_shake_inout ease_loop"
        },
        contains: [
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          hljs5.QUOTE_STRING_MODE,
          hljs5.APOS_STRING_MODE,
          {
            // multi-line string
            className: "string",
            begin: /\{"/,
            end: /"\}/,
            contains: [hljs5.BACKSLASH_ESCAPE]
          },
          hljs5.COMMENT(";", "$", {
            relevance: 0
          }),
          {
            // pre-processor
            className: "meta",
            begin: "#",
            end: "$",
            keywords: {
              "meta-keyword": "addion cfunc cmd cmpopt comfunc const defcfunc deffunc define else endif enum epack func global if ifdef ifndef include modcfunc modfunc modinit modterm module pack packopt regcmd runtime undef usecom uselib"
            },
            contains: [
              hljs5.inherit(hljs5.QUOTE_STRING_MODE, {
                className: "meta-string"
              }),
              hljs5.NUMBER_MODE,
              hljs5.C_NUMBER_MODE,
              hljs5.C_LINE_COMMENT_MODE,
              hljs5.C_BLOCK_COMMENT_MODE
            ]
          },
          {
            // label
            className: "symbol",
            begin: "^\\*(\\w+|@)"
          },
          hljs5.NUMBER_MODE,
          hljs5.C_NUMBER_MODE
        ]
      };
    }
    module.exports = hsp;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/htmlbars.js
var require_htmlbars = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/htmlbars.js"(exports, module) {
    init_process_shim();
    function source(re2) {
      if (!re2) return null;
      if (typeof re2 === "string") return re2;
      return re2.source;
    }
    function anyNumberOfTimes(re2) {
      return concat("(", re2, ")*");
    }
    function optional(re2) {
      return concat("(", re2, ")?");
    }
    function concat(...args) {
      const joined = args.map((x2) => source(x2)).join("");
      return joined;
    }
    function either(...args) {
      const joined = "(" + args.map((x2) => source(x2)).join("|") + ")";
      return joined;
    }
    function handlebars(hljs5) {
      const BUILT_INS3 = {
        "builtin-name": [
          "action",
          "bindattr",
          "collection",
          "component",
          "concat",
          "debugger",
          "each",
          "each-in",
          "get",
          "hash",
          "if",
          "in",
          "input",
          "link-to",
          "loc",
          "log",
          "lookup",
          "mut",
          "outlet",
          "partial",
          "query-params",
          "render",
          "template",
          "textarea",
          "unbound",
          "unless",
          "view",
          "with",
          "yield"
        ]
      };
      const LITERALS3 = {
        literal: [
          "true",
          "false",
          "undefined",
          "null"
        ]
      };
      const DOUBLE_QUOTED_ID_REGEX = /""|"[^"]+"/;
      const SINGLE_QUOTED_ID_REGEX = /''|'[^']+'/;
      const BRACKET_QUOTED_ID_REGEX = /\[\]|\[[^\]]+\]/;
      const PLAIN_ID_REGEX = /[^\s!"#%&'()*+,.\/;<=>@\[\\\]^`{|}~]+/;
      const PATH_DELIMITER_REGEX = /(\.|\/)/;
      const ANY_ID = either(
        DOUBLE_QUOTED_ID_REGEX,
        SINGLE_QUOTED_ID_REGEX,
        BRACKET_QUOTED_ID_REGEX,
        PLAIN_ID_REGEX
      );
      const IDENTIFIER_REGEX = concat(
        optional(/\.|\.\/|\//),
        // relative or absolute path
        ANY_ID,
        anyNumberOfTimes(concat(
          PATH_DELIMITER_REGEX,
          ANY_ID
        ))
      );
      const HASH_PARAM_REGEX = concat(
        "(",
        BRACKET_QUOTED_ID_REGEX,
        "|",
        PLAIN_ID_REGEX,
        ")(?==)"
      );
      const HELPER_NAME_OR_PATH_EXPRESSION = {
        begin: IDENTIFIER_REGEX,
        lexemes: /[\w.\/]+/
      };
      const HELPER_PARAMETER = hljs5.inherit(HELPER_NAME_OR_PATH_EXPRESSION, {
        keywords: LITERALS3
      });
      const SUB_EXPRESSION = {
        begin: /\(/,
        end: /\)/
        // the "contains" is added below when all necessary sub-modes are defined
      };
      const HASH = {
        // fka "attribute-assignment", parameters of the form 'key=value'
        className: "attr",
        begin: HASH_PARAM_REGEX,
        relevance: 0,
        starts: {
          begin: /=/,
          end: /=/,
          starts: {
            contains: [
              hljs5.NUMBER_MODE,
              hljs5.QUOTE_STRING_MODE,
              hljs5.APOS_STRING_MODE,
              HELPER_PARAMETER,
              SUB_EXPRESSION
            ]
          }
        }
      };
      const BLOCK_PARAMS = {
        // parameters of the form '{{#with x as | y |}}...{{/with}}'
        begin: /as\s+\|/,
        keywords: {
          keyword: "as"
        },
        end: /\|/,
        contains: [
          {
            // define sub-mode in order to prevent highlighting of block-parameter named "as"
            begin: /\w+/
          }
        ]
      };
      const HELPER_PARAMETERS = {
        contains: [
          hljs5.NUMBER_MODE,
          hljs5.QUOTE_STRING_MODE,
          hljs5.APOS_STRING_MODE,
          BLOCK_PARAMS,
          HASH,
          HELPER_PARAMETER,
          SUB_EXPRESSION
        ],
        returnEnd: true
        // the property "end" is defined through inheritance when the mode is used. If depends
        // on the surrounding mode, but "endsWithParent" does not work here (i.e. it includes the
        // end-token of the surrounding mode)
      };
      const SUB_EXPRESSION_CONTENTS = hljs5.inherit(HELPER_NAME_OR_PATH_EXPRESSION, {
        className: "name",
        keywords: BUILT_INS3,
        starts: hljs5.inherit(HELPER_PARAMETERS, {
          end: /\)/
        })
      });
      SUB_EXPRESSION.contains = [SUB_EXPRESSION_CONTENTS];
      const OPENING_BLOCK_MUSTACHE_CONTENTS = hljs5.inherit(HELPER_NAME_OR_PATH_EXPRESSION, {
        keywords: BUILT_INS3,
        className: "name",
        starts: hljs5.inherit(HELPER_PARAMETERS, {
          end: /\}\}/
        })
      });
      const CLOSING_BLOCK_MUSTACHE_CONTENTS = hljs5.inherit(HELPER_NAME_OR_PATH_EXPRESSION, {
        keywords: BUILT_INS3,
        className: "name"
      });
      const BASIC_MUSTACHE_CONTENTS = hljs5.inherit(HELPER_NAME_OR_PATH_EXPRESSION, {
        className: "name",
        keywords: BUILT_INS3,
        starts: hljs5.inherit(HELPER_PARAMETERS, {
          end: /\}\}/
        })
      });
      const ESCAPE_MUSTACHE_WITH_PRECEEDING_BACKSLASH = {
        begin: /\\\{\{/,
        skip: true
      };
      const PREVENT_ESCAPE_WITH_ANOTHER_PRECEEDING_BACKSLASH = {
        begin: /\\\\(?=\{\{)/,
        skip: true
      };
      return {
        name: "Handlebars",
        aliases: [
          "hbs",
          "html.hbs",
          "html.handlebars",
          "htmlbars"
        ],
        case_insensitive: true,
        subLanguage: "xml",
        contains: [
          ESCAPE_MUSTACHE_WITH_PRECEEDING_BACKSLASH,
          PREVENT_ESCAPE_WITH_ANOTHER_PRECEEDING_BACKSLASH,
          hljs5.COMMENT(/\{\{!--/, /--\}\}/),
          hljs5.COMMENT(/\{\{!/, /\}\}/),
          {
            // open raw block "{{{{raw}}}} content not evaluated {{{{/raw}}}}"
            className: "template-tag",
            begin: /\{\{\{\{(?!\/)/,
            end: /\}\}\}\}/,
            contains: [OPENING_BLOCK_MUSTACHE_CONTENTS],
            starts: {
              end: /\{\{\{\{\//,
              returnEnd: true,
              subLanguage: "xml"
            }
          },
          {
            // close raw block
            className: "template-tag",
            begin: /\{\{\{\{\//,
            end: /\}\}\}\}/,
            contains: [CLOSING_BLOCK_MUSTACHE_CONTENTS]
          },
          {
            // open block statement
            className: "template-tag",
            begin: /\{\{#/,
            end: /\}\}/,
            contains: [OPENING_BLOCK_MUSTACHE_CONTENTS]
          },
          {
            className: "template-tag",
            begin: /\{\{(?=else\}\})/,
            end: /\}\}/,
            keywords: "else"
          },
          {
            className: "template-tag",
            begin: /\{\{(?=else if)/,
            end: /\}\}/,
            keywords: "else if"
          },
          {
            // closing block statement
            className: "template-tag",
            begin: /\{\{\//,
            end: /\}\}/,
            contains: [CLOSING_BLOCK_MUSTACHE_CONTENTS]
          },
          {
            // template variable or helper-call that is NOT html-escaped
            className: "template-variable",
            begin: /\{\{\{/,
            end: /\}\}\}/,
            contains: [BASIC_MUSTACHE_CONTENTS]
          },
          {
            // template variable or helper-call that is html-escaped
            className: "template-variable",
            begin: /\{\{/,
            end: /\}\}/,
            contains: [BASIC_MUSTACHE_CONTENTS]
          }
        ]
      };
    }
    function htmlbars(hljs5) {
      const definition = handlebars(hljs5);
      definition.name = "HTMLbars";
      if (hljs5.getLanguage("handlebars")) {
        definition.disableAutodetect = true;
      }
      return definition;
    }
    module.exports = htmlbars;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/http.js
var require_http2 = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/http.js"(exports, module) {
    init_process_shim();
    function source(re2) {
      if (!re2) return null;
      if (typeof re2 === "string") return re2;
      return re2.source;
    }
    function concat(...args) {
      const joined = args.map((x2) => source(x2)).join("");
      return joined;
    }
    function http(hljs5) {
      const VERSION4 = "HTTP/(2|1\\.[01])";
      const HEADER_NAME = /[A-Za-z][A-Za-z0-9-]*/;
      const HEADER = {
        className: "attribute",
        begin: concat("^", HEADER_NAME, "(?=\\:\\s)"),
        starts: {
          contains: [
            {
              className: "punctuation",
              begin: /: /,
              relevance: 0,
              starts: {
                end: "$",
                relevance: 0
              }
            }
          ]
        }
      };
      const HEADERS_AND_BODY = [
        HEADER,
        {
          begin: "\\n\\n",
          starts: { subLanguage: [], endsWithParent: true }
        }
      ];
      return {
        name: "HTTP",
        aliases: ["https"],
        illegal: /\S/,
        contains: [
          // response
          {
            begin: "^(?=" + VERSION4 + " \\d{3})",
            end: /$/,
            contains: [
              {
                className: "meta",
                begin: VERSION4
              },
              {
                className: "number",
                begin: "\\b\\d{3}\\b"
              }
            ],
            starts: {
              end: /\b\B/,
              illegal: /\S/,
              contains: HEADERS_AND_BODY
            }
          },
          // request
          {
            begin: "(?=^[A-Z]+ (.*?) " + VERSION4 + "$)",
            end: /$/,
            contains: [
              {
                className: "string",
                begin: " ",
                end: " ",
                excludeBegin: true,
                excludeEnd: true
              },
              {
                className: "meta",
                begin: VERSION4
              },
              {
                className: "keyword",
                begin: "[A-Z]+"
              }
            ],
            starts: {
              end: /\b\B/,
              illegal: /\S/,
              contains: HEADERS_AND_BODY
            }
          },
          // to allow headers to work even without a preamble
          hljs5.inherit(HEADER, {
            relevance: 0
          })
        ]
      };
    }
    module.exports = http;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/hy.js
var require_hy = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/hy.js"(exports, module) {
    init_process_shim();
    function hy(hljs5) {
      var SYMBOLSTART = "a-zA-Z_\\-!.?+*=<>&#'";
      var SYMBOL_RE = "[" + SYMBOLSTART + "][" + SYMBOLSTART + "0-9/;:]*";
      var keywords = {
        $pattern: SYMBOL_RE,
        "builtin-name": (
          // keywords
          "!= % %= & &= * ** **= *= *map + += , --build-class-- --import-- -= . / // //= /= < << <<= <= = > >= >> >>= @ @= ^ ^= abs accumulate all and any ap-compose ap-dotimes ap-each ap-each-while ap-filter ap-first ap-if ap-last ap-map ap-map-when ap-pipe ap-reduce ap-reject apply as-> ascii assert assoc bin break butlast callable calling-module-name car case cdr chain chr coll? combinations compile compress cond cons cons? continue count curry cut cycle dec def default-method defclass defmacro defmacro-alias defmacro/g! defmain defmethod defmulti defn defn-alias defnc defnr defreader defseq del delattr delete-route dict-comp dir disassemble dispatch-reader-macro distinct divmod do doto drop drop-last drop-while empty? end-sequence eval eval-and-compile eval-when-compile even? every? except exec filter first flatten float? fn fnc fnr for for* format fraction genexpr gensym get getattr global globals group-by hasattr hash hex id identity if if* if-not if-python2 import in inc input instance? integer integer-char? integer? interleave interpose is is-coll is-cons is-empty is-even is-every is-float is-instance is-integer is-integer-char is-iterable is-iterator is-keyword is-neg is-none is-not is-numeric is-odd is-pos is-string is-symbol is-zero isinstance islice issubclass iter iterable? iterate iterator? keyword keyword? lambda last len let lif lif-not list* list-comp locals loop macro-error macroexpand macroexpand-1 macroexpand-all map max merge-with method-decorator min multi-decorator multicombinations name neg? next none? nonlocal not not-in not? nth numeric? oct odd? open or ord partition permutations pos? post-route postwalk pow prewalk print product profile/calls profile/cpu put-route quasiquote quote raise range read read-str recursive-replace reduce remove repeat repeatedly repr require rest round route route-with-methods rwm second seq set-comp setattr setv some sorted string string? sum switch symbol? take take-nth take-while tee try unless unquote unquote-splicing vars walk when while with with* with-decorator with-gensyms xi xor yield yield-from zero? zip zip-longest | |= ~"
        )
      };
      var SIMPLE_NUMBER_RE = "[-+]?\\d+(\\.\\d+)?";
      var SYMBOL = {
        begin: SYMBOL_RE,
        relevance: 0
      };
      var NUMBER = {
        className: "number",
        begin: SIMPLE_NUMBER_RE,
        relevance: 0
      };
      var STRING = hljs5.inherit(hljs5.QUOTE_STRING_MODE, { illegal: null });
      var COMMENT = hljs5.COMMENT(
        ";",
        "$",
        {
          relevance: 0
        }
      );
      var LITERAL = {
        className: "literal",
        begin: /\b([Tt]rue|[Ff]alse|nil|None)\b/
      };
      var COLLECTION2 = {
        begin: "[\\[\\{]",
        end: "[\\]\\}]"
      };
      var HINT = {
        className: "comment",
        begin: "\\^" + SYMBOL_RE
      };
      var HINT_COL = hljs5.COMMENT("\\^\\{", "\\}");
      var KEY = {
        className: "symbol",
        begin: "[:]{1,2}" + SYMBOL_RE
      };
      var LIST = {
        begin: "\\(",
        end: "\\)"
      };
      var BODY = {
        endsWithParent: true,
        relevance: 0
      };
      var NAME = {
        className: "name",
        relevance: 0,
        keywords,
        begin: SYMBOL_RE,
        starts: BODY
      };
      var DEFAULT_CONTAINS = [LIST, STRING, HINT, HINT_COL, COMMENT, KEY, COLLECTION2, NUMBER, LITERAL, SYMBOL];
      LIST.contains = [hljs5.COMMENT("comment", ""), NAME, BODY];
      BODY.contains = DEFAULT_CONTAINS;
      COLLECTION2.contains = DEFAULT_CONTAINS;
      return {
        name: "Hy",
        aliases: ["hylang"],
        illegal: /\S/,
        contains: [hljs5.SHEBANG(), LIST, STRING, HINT, HINT_COL, COMMENT, KEY, COLLECTION2, NUMBER, LITERAL]
      };
    }
    module.exports = hy;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/inform7.js
var require_inform7 = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/inform7.js"(exports, module) {
    init_process_shim();
    function inform7(hljs5) {
      const START_BRACKET = "\\[";
      const END_BRACKET = "\\]";
      return {
        name: "Inform 7",
        aliases: ["i7"],
        case_insensitive: true,
        keywords: {
          // Some keywords more or less unique to I7, for relevance.
          keyword: (
            // kind:
            "thing room person man woman animal container supporter backdrop door scenery open closed locked inside gender is are say understand kind of rule"
          )
        },
        contains: [
          {
            className: "string",
            begin: '"',
            end: '"',
            relevance: 0,
            contains: [
              {
                className: "subst",
                begin: START_BRACKET,
                end: END_BRACKET
              }
            ]
          },
          {
            className: "section",
            begin: /^(Volume|Book|Part|Chapter|Section|Table)\b/,
            end: "$"
          },
          {
            // Rule definition
            // This is here for relevance.
            begin: /^(Check|Carry out|Report|Instead of|To|Rule|When|Before|After)\b/,
            end: ":",
            contains: [
              {
                // Rule name
                begin: "\\(This",
                end: "\\)"
              }
            ]
          },
          {
            className: "comment",
            begin: START_BRACKET,
            end: END_BRACKET,
            contains: ["self"]
          }
        ]
      };
    }
    module.exports = inform7;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/ini.js
var require_ini = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/ini.js"(exports, module) {
    init_process_shim();
    function source(re2) {
      if (!re2) return null;
      if (typeof re2 === "string") return re2;
      return re2.source;
    }
    function lookahead(re2) {
      return concat("(?=", re2, ")");
    }
    function concat(...args) {
      const joined = args.map((x2) => source(x2)).join("");
      return joined;
    }
    function either(...args) {
      const joined = "(" + args.map((x2) => source(x2)).join("|") + ")";
      return joined;
    }
    function ini(hljs5) {
      const NUMBERS = {
        className: "number",
        relevance: 0,
        variants: [
          {
            begin: /([+-]+)?[\d]+_[\d_]+/
          },
          {
            begin: hljs5.NUMBER_RE
          }
        ]
      };
      const COMMENTS = hljs5.COMMENT();
      COMMENTS.variants = [
        {
          begin: /;/,
          end: /$/
        },
        {
          begin: /#/,
          end: /$/
        }
      ];
      const VARIABLES = {
        className: "variable",
        variants: [
          {
            begin: /\$[\w\d"][\w\d_]*/
          },
          {
            begin: /\$\{(.*?)\}/
          }
        ]
      };
      const LITERALS3 = {
        className: "literal",
        begin: /\bon|off|true|false|yes|no\b/
      };
      const STRINGS = {
        className: "string",
        contains: [hljs5.BACKSLASH_ESCAPE],
        variants: [
          {
            begin: "'''",
            end: "'''",
            relevance: 10
          },
          {
            begin: '"""',
            end: '"""',
            relevance: 10
          },
          {
            begin: '"',
            end: '"'
          },
          {
            begin: "'",
            end: "'"
          }
        ]
      };
      const ARRAY = {
        begin: /\[/,
        end: /\]/,
        contains: [
          COMMENTS,
          LITERALS3,
          VARIABLES,
          STRINGS,
          NUMBERS,
          "self"
        ],
        relevance: 0
      };
      const BARE_KEY = /[A-Za-z0-9_-]+/;
      const QUOTED_KEY_DOUBLE_QUOTE = /"(\\"|[^"])*"/;
      const QUOTED_KEY_SINGLE_QUOTE = /'[^']*'/;
      const ANY_KEY = either(
        BARE_KEY,
        QUOTED_KEY_DOUBLE_QUOTE,
        QUOTED_KEY_SINGLE_QUOTE
      );
      const DOTTED_KEY = concat(
        ANY_KEY,
        "(\\s*\\.\\s*",
        ANY_KEY,
        ")*",
        lookahead(/\s*=\s*[^#\s]/)
      );
      return {
        name: "TOML, also INI",
        aliases: ["toml"],
        case_insensitive: true,
        illegal: /\S/,
        contains: [
          COMMENTS,
          {
            className: "section",
            begin: /\[+/,
            end: /\]+/
          },
          {
            begin: DOTTED_KEY,
            className: "attr",
            starts: {
              end: /$/,
              contains: [
                COMMENTS,
                ARRAY,
                LITERALS3,
                VARIABLES,
                STRINGS,
                NUMBERS
              ]
            }
          }
        ]
      };
    }
    module.exports = ini;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/irpf90.js
var require_irpf90 = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/irpf90.js"(exports, module) {
    init_process_shim();
    function source(re2) {
      if (!re2) return null;
      if (typeof re2 === "string") return re2;
      return re2.source;
    }
    function concat(...args) {
      const joined = args.map((x2) => source(x2)).join("");
      return joined;
    }
    function irpf90(hljs5) {
      const PARAMS = {
        className: "params",
        begin: "\\(",
        end: "\\)"
      };
      const OPTIONAL_NUMBER_SUFFIX = /(_[a-z_\d]+)?/;
      const OPTIONAL_NUMBER_EXP = /([de][+-]?\d+)?/;
      const NUMBER = {
        className: "number",
        variants: [
          {
            begin: concat(/\b\d+/, /\.(\d*)/, OPTIONAL_NUMBER_EXP, OPTIONAL_NUMBER_SUFFIX)
          },
          {
            begin: concat(/\b\d+/, OPTIONAL_NUMBER_EXP, OPTIONAL_NUMBER_SUFFIX)
          },
          {
            begin: concat(/\.\d+/, OPTIONAL_NUMBER_EXP, OPTIONAL_NUMBER_SUFFIX)
          }
        ],
        relevance: 0
      };
      const F_KEYWORDS = {
        literal: ".False. .True.",
        keyword: "kind do while private call intrinsic where elsewhere type endtype endmodule endselect endinterface end enddo endif if forall endforall only contains default return stop then public subroutine|10 function program .and. .or. .not. .le. .eq. .ge. .gt. .lt. goto save else use module select case access blank direct exist file fmt form formatted iostat name named nextrec number opened rec recl sequential status unformatted unit continue format pause cycle exit c_null_char c_alert c_backspace c_form_feed flush wait decimal round iomsg synchronous nopass non_overridable pass protected volatile abstract extends import non_intrinsic value deferred generic final enumerator class associate bind enum c_int c_short c_long c_long_long c_signed_char c_size_t c_int8_t c_int16_t c_int32_t c_int64_t c_int_least8_t c_int_least16_t c_int_least32_t c_int_least64_t c_int_fast8_t c_int_fast16_t c_int_fast32_t c_int_fast64_t c_intmax_t C_intptr_t c_float c_double c_long_double c_float_complex c_double_complex c_long_double_complex c_bool c_char c_null_ptr c_null_funptr c_new_line c_carriage_return c_horizontal_tab c_vertical_tab iso_c_binding c_loc c_funloc c_associated  c_f_pointer c_ptr c_funptr iso_fortran_env character_storage_size error_unit file_storage_size input_unit iostat_end iostat_eor numeric_storage_size output_unit c_f_procpointer ieee_arithmetic ieee_support_underflow_control ieee_get_underflow_mode ieee_set_underflow_mode newunit contiguous recursive pad position action delim readwrite eor advance nml interface procedure namelist include sequence elemental pure integer real character complex logical dimension allocatable|10 parameter external implicit|10 none double precision assign intent optional pointer target in out common equivalence data begin_provider &begin_provider end_provider begin_shell end_shell begin_template end_template subst assert touch soft_touch provide no_dep free irp_if irp_else irp_endif irp_write irp_read",
        built_in: "alog alog10 amax0 amax1 amin0 amin1 amod cabs ccos cexp clog csin csqrt dabs dacos dasin datan datan2 dcos dcosh ddim dexp dint dlog dlog10 dmax1 dmin1 dmod dnint dsign dsin dsinh dsqrt dtan dtanh float iabs idim idint idnint ifix isign max0 max1 min0 min1 sngl algama cdabs cdcos cdexp cdlog cdsin cdsqrt cqabs cqcos cqexp cqlog cqsin cqsqrt dcmplx dconjg derf derfc dfloat dgamma dimag dlgama iqint qabs qacos qasin qatan qatan2 qcmplx qconjg qcos qcosh qdim qerf qerfc qexp qgamma qimag qlgama qlog qlog10 qmax1 qmin1 qmod qnint qsign qsin qsinh qsqrt qtan qtanh abs acos aimag aint anint asin atan atan2 char cmplx conjg cos cosh exp ichar index int log log10 max min nint sign sin sinh sqrt tan tanh print write dim lge lgt lle llt mod nullify allocate deallocate adjustl adjustr all allocated any associated bit_size btest ceiling count cshift date_and_time digits dot_product eoshift epsilon exponent floor fraction huge iand ibclr ibits ibset ieor ior ishft ishftc lbound len_trim matmul maxexponent maxloc maxval merge minexponent minloc minval modulo mvbits nearest pack present product radix random_number random_seed range repeat reshape rrspacing scale scan selected_int_kind selected_real_kind set_exponent shape size spacing spread sum system_clock tiny transpose trim ubound unpack verify achar iachar transfer dble entry dprod cpu_time command_argument_count get_command get_command_argument get_environment_variable is_iostat_end ieee_arithmetic ieee_support_underflow_control ieee_get_underflow_mode ieee_set_underflow_mode is_iostat_eor move_alloc new_line selected_char_kind same_type_as extends_type_of acosh asinh atanh bessel_j0 bessel_j1 bessel_jn bessel_y0 bessel_y1 bessel_yn erf erfc erfc_scaled gamma log_gamma hypot norm2 atomic_define atomic_ref execute_command_line leadz trailz storage_size merge_bits bge bgt ble blt dshiftl dshiftr findloc iall iany iparity image_index lcobound ucobound maskl maskr num_images parity popcnt poppar shifta shiftl shiftr this_image IRP_ALIGN irp_here"
      };
      return {
        name: "IRPF90",
        case_insensitive: true,
        keywords: F_KEYWORDS,
        illegal: /\/\*/,
        contains: [
          hljs5.inherit(hljs5.APOS_STRING_MODE, {
            className: "string",
            relevance: 0
          }),
          hljs5.inherit(hljs5.QUOTE_STRING_MODE, {
            className: "string",
            relevance: 0
          }),
          {
            className: "function",
            beginKeywords: "subroutine function program",
            illegal: "[${=\\n]",
            contains: [
              hljs5.UNDERSCORE_TITLE_MODE,
              PARAMS
            ]
          },
          hljs5.COMMENT("!", "$", {
            relevance: 0
          }),
          hljs5.COMMENT("begin_doc", "end_doc", {
            relevance: 10
          }),
          NUMBER
        ]
      };
    }
    module.exports = irpf90;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/isbl.js
var require_isbl = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/isbl.js"(exports, module) {
    init_process_shim();
    function isbl(hljs5) {
      const UNDERSCORE_IDENT_RE = "[A-Za-z\u0410-\u042F\u0430-\u044F\u0451\u0401_!][A-Za-z\u0410-\u042F\u0430-\u044F\u0451\u0401_0-9]*";
      const FUNCTION_NAME_IDENT_RE = "[A-Za-z\u0410-\u042F\u0430-\u044F\u0451\u0401_][A-Za-z\u0410-\u042F\u0430-\u044F\u0451\u0401_0-9]*";
      const KEYWORD = "and \u0438 else \u0438\u043D\u0430\u0447\u0435 endexcept endfinally endforeach \u043A\u043E\u043D\u0435\u0446\u0432\u0441\u0435 endif \u043A\u043E\u043D\u0435\u0446\u0435\u0441\u043B\u0438 endwhile \u043A\u043E\u043D\u0435\u0446\u043F\u043E\u043A\u0430 except exitfor finally foreach \u0432\u0441\u0435 if \u0435\u0441\u043B\u0438 in \u0432 not \u043D\u0435 or \u0438\u043B\u0438 try while \u043F\u043E\u043A\u0430 ";
      const sysres_constants = "SYSRES_CONST_ACCES_RIGHT_TYPE_EDIT SYSRES_CONST_ACCES_RIGHT_TYPE_FULL SYSRES_CONST_ACCES_RIGHT_TYPE_VIEW SYSRES_CONST_ACCESS_MODE_REQUISITE_CODE SYSRES_CONST_ACCESS_NO_ACCESS_VIEW SYSRES_CONST_ACCESS_NO_ACCESS_VIEW_CODE SYSRES_CONST_ACCESS_RIGHTS_ADD_REQUISITE_CODE SYSRES_CONST_ACCESS_RIGHTS_ADD_REQUISITE_YES_CODE SYSRES_CONST_ACCESS_RIGHTS_CHANGE_REQUISITE_CODE SYSRES_CONST_ACCESS_RIGHTS_CHANGE_REQUISITE_YES_CODE SYSRES_CONST_ACCESS_RIGHTS_DELETE_REQUISITE_CODE SYSRES_CONST_ACCESS_RIGHTS_DELETE_REQUISITE_YES_CODE SYSRES_CONST_ACCESS_RIGHTS_EXECUTE_REQUISITE_CODE SYSRES_CONST_ACCESS_RIGHTS_EXECUTE_REQUISITE_YES_CODE SYSRES_CONST_ACCESS_RIGHTS_NO_ACCESS_REQUISITE_CODE SYSRES_CONST_ACCESS_RIGHTS_NO_ACCESS_REQUISITE_YES_CODE SYSRES_CONST_ACCESS_RIGHTS_RATIFY_REQUISITE_CODE SYSRES_CONST_ACCESS_RIGHTS_RATIFY_REQUISITE_YES_CODE SYSRES_CONST_ACCESS_RIGHTS_REQUISITE_CODE SYSRES_CONST_ACCESS_RIGHTS_VIEW SYSRES_CONST_ACCESS_RIGHTS_VIEW_CODE SYSRES_CONST_ACCESS_RIGHTS_VIEW_REQUISITE_CODE SYSRES_CONST_ACCESS_RIGHTS_VIEW_REQUISITE_YES_CODE SYSRES_CONST_ACCESS_TYPE_CHANGE SYSRES_CONST_ACCESS_TYPE_CHANGE_CODE SYSRES_CONST_ACCESS_TYPE_EXISTS SYSRES_CONST_ACCESS_TYPE_EXISTS_CODE SYSRES_CONST_ACCESS_TYPE_FULL SYSRES_CONST_ACCESS_TYPE_FULL_CODE SYSRES_CONST_ACCESS_TYPE_VIEW SYSRES_CONST_ACCESS_TYPE_VIEW_CODE SYSRES_CONST_ACTION_TYPE_ABORT SYSRES_CONST_ACTION_TYPE_ACCEPT SYSRES_CONST_ACTION_TYPE_ACCESS_RIGHTS SYSRES_CONST_ACTION_TYPE_ADD_ATTACHMENT SYSRES_CONST_ACTION_TYPE_CHANGE_CARD SYSRES_CONST_ACTION_TYPE_CHANGE_KIND SYSRES_CONST_ACTION_TYPE_CHANGE_STORAGE SYSRES_CONST_ACTION_TYPE_CONTINUE SYSRES_CONST_ACTION_TYPE_COPY SYSRES_CONST_ACTION_TYPE_CREATE SYSRES_CONST_ACTION_TYPE_CREATE_VERSION SYSRES_CONST_ACTION_TYPE_DELETE SYSRES_CONST_ACTION_TYPE_DELETE_ATTACHMENT SYSRES_CONST_ACTION_TYPE_DELETE_VERSION SYSRES_CONST_ACTION_TYPE_DISABLE_DELEGATE_ACCESS_RIGHTS SYSRES_CONST_ACTION_TYPE_ENABLE_DELEGATE_ACCESS_RIGHTS SYSRES_CONST_ACTION_TYPE_ENCRYPTION_BY_CERTIFICATE SYSRES_CONST_ACTION_TYPE_ENCRYPTION_BY_CERTIFICATE_AND_PASSWORD SYSRES_CONST_ACTION_TYPE_ENCRYPTION_BY_PASSWORD SYSRES_CONST_ACTION_TYPE_EXPORT_WITH_LOCK SYSRES_CONST_ACTION_TYPE_EXPORT_WITHOUT_LOCK SYSRES_CONST_ACTION_TYPE_IMPORT_WITH_UNLOCK SYSRES_CONST_ACTION_TYPE_IMPORT_WITHOUT_UNLOCK SYSRES_CONST_ACTION_TYPE_LIFE_CYCLE_STAGE SYSRES_CONST_ACTION_TYPE_LOCK SYSRES_CONST_ACTION_TYPE_LOCK_FOR_SERVER SYSRES_CONST_ACTION_TYPE_LOCK_MODIFY SYSRES_CONST_ACTION_TYPE_MARK_AS_READED SYSRES_CONST_ACTION_TYPE_MARK_AS_UNREADED SYSRES_CONST_ACTION_TYPE_MODIFY SYSRES_CONST_ACTION_TYPE_MODIFY_CARD SYSRES_CONST_ACTION_TYPE_MOVE_TO_ARCHIVE SYSRES_CONST_ACTION_TYPE_OFF_ENCRYPTION SYSRES_CONST_ACTION_TYPE_PASSWORD_CHANGE SYSRES_CONST_ACTION_TYPE_PERFORM SYSRES_CONST_ACTION_TYPE_RECOVER_FROM_LOCAL_COPY SYSRES_CONST_ACTION_TYPE_RESTART SYSRES_CONST_ACTION_TYPE_RESTORE_FROM_ARCHIVE SYSRES_CONST_ACTION_TYPE_REVISION SYSRES_CONST_ACTION_TYPE_SEND_BY_MAIL SYSRES_CONST_ACTION_TYPE_SIGN SYSRES_CONST_ACTION_TYPE_START SYSRES_CONST_ACTION_TYPE_UNLOCK SYSRES_CONST_ACTION_TYPE_UNLOCK_FROM_SERVER SYSRES_CONST_ACTION_TYPE_VERSION_STATE SYSRES_CONST_ACTION_TYPE_VERSION_VISIBILITY SYSRES_CONST_ACTION_TYPE_VIEW SYSRES_CONST_ACTION_TYPE_VIEW_SHADOW_COPY SYSRES_CONST_ACTION_TYPE_WORKFLOW_DESCRIPTION_MODIFY SYSRES_CONST_ACTION_TYPE_WRITE_HISTORY SYSRES_CONST_ACTIVE_VERSION_STATE_PICK_VALUE SYSRES_CONST_ADD_REFERENCE_MODE_NAME SYSRES_CONST_ADDITION_REQUISITE_CODE SYSRES_CONST_ADDITIONAL_PARAMS_REQUISITE_CODE SYSRES_CONST_ADITIONAL_JOB_END_DATE_REQUISITE_NAME SYSRES_CONST_ADITIONAL_JOB_READ_REQUISITE_NAME SYSRES_CONST_ADITIONAL_JOB_START_DATE_REQUISITE_NAME SYSRES_CONST_ADITIONAL_JOB_STATE_REQUISITE_NAME SYSRES_CONST_ADMINISTRATION_HISTORY_ADDING_USER_TO_GROUP_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_ADDING_USER_TO_GROUP_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_CREATION_COMP_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_CREATION_COMP_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_CREATION_GROUP_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_CREATION_GROUP_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_CREATION_USER_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_CREATION_USER_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_DATABASE_USER_CREATION SYSRES_CONST_ADMINISTRATION_HISTORY_DATABASE_USER_CREATION_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_DATABASE_USER_DELETION SYSRES_CONST_ADMINISTRATION_HISTORY_DATABASE_USER_DELETION_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_DELETION_COMP_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_DELETION_COMP_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_DELETION_GROUP_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_DELETION_GROUP_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_DELETION_USER_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_DELETION_USER_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_DELETION_USER_FROM_GROUP_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_DELETION_USER_FROM_GROUP_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_GRANTING_FILTERER_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_GRANTING_FILTERER_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_GRANTING_FILTERER_RESTRICTION_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_GRANTING_FILTERER_RESTRICTION_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_GRANTING_PRIVILEGE_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_GRANTING_PRIVILEGE_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_GRANTING_RIGHTS_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_GRANTING_RIGHTS_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_IS_MAIN_SERVER_CHANGED_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_IS_MAIN_SERVER_CHANGED_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_IS_PUBLIC_CHANGED_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_IS_PUBLIC_CHANGED_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_REMOVING_FILTERER_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_REMOVING_FILTERER_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_REMOVING_FILTERER_RESTRICTION_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_REMOVING_FILTERER_RESTRICTION_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_REMOVING_PRIVILEGE_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_REMOVING_PRIVILEGE_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_REMOVING_RIGHTS_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_REMOVING_RIGHTS_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_SERVER_LOGIN_CREATION SYSRES_CONST_ADMINISTRATION_HISTORY_SERVER_LOGIN_CREATION_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_SERVER_LOGIN_DELETION SYSRES_CONST_ADMINISTRATION_HISTORY_SERVER_LOGIN_DELETION_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_CATEGORY_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_CATEGORY_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_COMP_TITLE_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_COMP_TITLE_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_FULL_NAME_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_FULL_NAME_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_GROUP_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_GROUP_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_PARENT_GROUP_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_PARENT_GROUP_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_USER_AUTH_TYPE_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_USER_AUTH_TYPE_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_USER_LOGIN_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_USER_LOGIN_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_USER_STATUS_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_USER_STATUS_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_USER_PASSWORD_CHANGE SYSRES_CONST_ADMINISTRATION_HISTORY_USER_PASSWORD_CHANGE_ACTION SYSRES_CONST_ALL_ACCEPT_CONDITION_RUS SYSRES_CONST_ALL_USERS_GROUP SYSRES_CONST_ALL_USERS_GROUP_NAME SYSRES_CONST_ALL_USERS_SERVER_GROUP_NAME SYSRES_CONST_ALLOWED_ACCESS_TYPE_CODE SYSRES_CONST_ALLOWED_ACCESS_TYPE_NAME SYSRES_CONST_APP_VIEWER_TYPE_REQUISITE_CODE SYSRES_CONST_APPROVING_SIGNATURE_NAME SYSRES_CONST_APPROVING_SIGNATURE_REQUISITE_CODE SYSRES_CONST_ASSISTANT_SUBSTITUE_TYPE SYSRES_CONST_ASSISTANT_SUBSTITUE_TYPE_CODE SYSRES_CONST_ATTACH_TYPE_COMPONENT_TOKEN SYSRES_CONST_ATTACH_TYPE_DOC SYSRES_CONST_ATTACH_TYPE_EDOC SYSRES_CONST_ATTACH_TYPE_FOLDER SYSRES_CONST_ATTACH_TYPE_JOB SYSRES_CONST_ATTACH_TYPE_REFERENCE SYSRES_CONST_ATTACH_TYPE_TASK SYSRES_CONST_AUTH_ENCODED_PASSWORD SYSRES_CONST_AUTH_ENCODED_PASSWORD_CODE SYSRES_CONST_AUTH_NOVELL SYSRES_CONST_AUTH_PASSWORD SYSRES_CONST_AUTH_PASSWORD_CODE SYSRES_CONST_AUTH_WINDOWS SYSRES_CONST_AUTHENTICATING_SIGNATURE_NAME SYSRES_CONST_AUTHENTICATING_SIGNATURE_REQUISITE_CODE SYSRES_CONST_AUTO_ENUM_METHOD_FLAG SYSRES_CONST_AUTO_NUMERATION_CODE SYSRES_CONST_AUTO_STRONG_ENUM_METHOD_FLAG SYSRES_CONST_AUTOTEXT_NAME_REQUISITE_CODE SYSRES_CONST_AUTOTEXT_TEXT_REQUISITE_CODE SYSRES_CONST_AUTOTEXT_USAGE_ALL SYSRES_CONST_AUTOTEXT_USAGE_ALL_CODE SYSRES_CONST_AUTOTEXT_USAGE_SIGN SYSRES_CONST_AUTOTEXT_USAGE_SIGN_CODE SYSRES_CONST_AUTOTEXT_USAGE_WORK SYSRES_CONST_AUTOTEXT_USAGE_WORK_CODE SYSRES_CONST_AUTOTEXT_USE_ANYWHERE_CODE SYSRES_CONST_AUTOTEXT_USE_ON_SIGNING_CODE SYSRES_CONST_AUTOTEXT_USE_ON_WORK_CODE SYSRES_CONST_BEGIN_DATE_REQUISITE_CODE SYSRES_CONST_BLACK_LIFE_CYCLE_STAGE_FONT_COLOR SYSRES_CONST_BLUE_LIFE_CYCLE_STAGE_FONT_COLOR SYSRES_CONST_BTN_PART SYSRES_CONST_CALCULATED_ROLE_TYPE_CODE SYSRES_CONST_CALL_TYPE_VARIABLE_BUTTON_VALUE SYSRES_CONST_CALL_TYPE_VARIABLE_PROGRAM_VALUE SYSRES_CONST_CANCEL_MESSAGE_FUNCTION_RESULT SYSRES_CONST_CARD_PART SYSRES_CONST_CARD_REFERENCE_MODE_NAME SYSRES_CONST_CERTIFICATE_TYPE_REQUISITE_ENCRYPT_VALUE SYSRES_CONST_CERTIFICATE_TYPE_REQUISITE_SIGN_AND_ENCRYPT_VALUE SYSRES_CONST_CERTIFICATE_TYPE_REQUISITE_SIGN_VALUE SYSRES_CONST_CHECK_PARAM_VALUE_DATE_PARAM_TYPE SYSRES_CONST_CHECK_PARAM_VALUE_FLOAT_PARAM_TYPE SYSRES_CONST_CHECK_PARAM_VALUE_INTEGER_PARAM_TYPE SYSRES_CONST_CHECK_PARAM_VALUE_PICK_PARAM_TYPE SYSRES_CONST_CHECK_PARAM_VALUE_REEFRENCE_PARAM_TYPE SYSRES_CONST_CLOSED_RECORD_FLAG_VALUE_FEMININE SYSRES_CONST_CLOSED_RECORD_FLAG_VALUE_MASCULINE SYSRES_CONST_CODE_COMPONENT_TYPE_ADMIN SYSRES_CONST_CODE_COMPONENT_TYPE_DEVELOPER SYSRES_CONST_CODE_COMPONENT_TYPE_DOCS SYSRES_CONST_CODE_COMPONENT_TYPE_EDOC_CARDS SYSRES_CONST_CODE_COMPONENT_TYPE_EXTERNAL_EXECUTABLE SYSRES_CONST_CODE_COMPONENT_TYPE_OTHER SYSRES_CONST_CODE_COMPONENT_TYPE_REFERENCE SYSRES_CONST_CODE_COMPONENT_TYPE_REPORT SYSRES_CONST_CODE_COMPONENT_TYPE_SCRIPT SYSRES_CONST_CODE_COMPONENT_TYPE_URL SYSRES_CONST_CODE_REQUISITE_ACCESS SYSRES_CONST_CODE_REQUISITE_CODE SYSRES_CONST_CODE_REQUISITE_COMPONENT SYSRES_CONST_CODE_REQUISITE_DESCRIPTION SYSRES_CONST_CODE_REQUISITE_EXCLUDE_COMPONENT SYSRES_CONST_CODE_REQUISITE_RECORD SYSRES_CONST_COMMENT_REQ_CODE SYSRES_CONST_COMMON_SETTINGS_REQUISITE_CODE SYSRES_CONST_COMP_CODE_GRD SYSRES_CONST_COMPONENT_GROUP_TYPE_REQUISITE_CODE SYSRES_CONST_COMPONENT_TYPE_ADMIN_COMPONENTS SYSRES_CONST_COMPONENT_TYPE_DEVELOPER_COMPONENTS SYSRES_CONST_COMPONENT_TYPE_DOCS SYSRES_CONST_COMPONENT_TYPE_EDOC_CARDS SYSRES_CONST_COMPONENT_TYPE_EDOCS SYSRES_CONST_COMPONENT_TYPE_EXTERNAL_EXECUTABLE SYSRES_CONST_COMPONENT_TYPE_OTHER SYSRES_CONST_COMPONENT_TYPE_REFERENCE_TYPES SYSRES_CONST_COMPONENT_TYPE_REFERENCES SYSRES_CONST_COMPONENT_TYPE_REPORTS SYSRES_CONST_COMPONENT_TYPE_SCRIPTS SYSRES_CONST_COMPONENT_TYPE_URL SYSRES_CONST_COMPONENTS_REMOTE_SERVERS_VIEW_CODE SYSRES_CONST_CONDITION_BLOCK_DESCRIPTION SYSRES_CONST_CONST_FIRM_STATUS_COMMON SYSRES_CONST_CONST_FIRM_STATUS_INDIVIDUAL SYSRES_CONST_CONST_NEGATIVE_VALUE SYSRES_CONST_CONST_POSITIVE_VALUE SYSRES_CONST_CONST_SERVER_STATUS_DONT_REPLICATE SYSRES_CONST_CONST_SERVER_STATUS_REPLICATE SYSRES_CONST_CONTENTS_REQUISITE_CODE SYSRES_CONST_DATA_TYPE_BOOLEAN SYSRES_CONST_DATA_TYPE_DATE SYSRES_CONST_DATA_TYPE_FLOAT SYSRES_CONST_DATA_TYPE_INTEGER SYSRES_CONST_DATA_TYPE_PICK SYSRES_CONST_DATA_TYPE_REFERENCE SYSRES_CONST_DATA_TYPE_STRING SYSRES_CONST_DATA_TYPE_TEXT SYSRES_CONST_DATA_TYPE_VARIANT SYSRES_CONST_DATE_CLOSE_REQ_CODE SYSRES_CONST_DATE_FORMAT_DATE_ONLY_CHAR SYSRES_CONST_DATE_OPEN_REQ_CODE SYSRES_CONST_DATE_REQUISITE SYSRES_CONST_DATE_REQUISITE_CODE SYSRES_CONST_DATE_REQUISITE_NAME SYSRES_CONST_DATE_REQUISITE_TYPE SYSRES_CONST_DATE_TYPE_CHAR SYSRES_CONST_DATETIME_FORMAT_VALUE SYSRES_CONST_DEA_ACCESS_RIGHTS_ACTION_CODE SYSRES_CONST_DESCRIPTION_LOCALIZE_ID_REQUISITE_CODE SYSRES_CONST_DESCRIPTION_REQUISITE_CODE SYSRES_CONST_DET1_PART SYSRES_CONST_DET2_PART SYSRES_CONST_DET3_PART SYSRES_CONST_DET4_PART SYSRES_CONST_DET5_PART SYSRES_CONST_DET6_PART SYSRES_CONST_DETAIL_DATASET_KEY_REQUISITE_CODE SYSRES_CONST_DETAIL_PICK_REQUISITE_CODE SYSRES_CONST_DETAIL_REQ_CODE SYSRES_CONST_DO_NOT_USE_ACCESS_TYPE_CODE SYSRES_CONST_DO_NOT_USE_ACCESS_TYPE_NAME SYSRES_CONST_DO_NOT_USE_ON_VIEW_ACCESS_TYPE_CODE SYSRES_CONST_DO_NOT_USE_ON_VIEW_ACCESS_TYPE_NAME SYSRES_CONST_DOCUMENT_STORAGES_CODE SYSRES_CONST_DOCUMENT_TEMPLATES_TYPE_NAME SYSRES_CONST_DOUBLE_REQUISITE_CODE SYSRES_CONST_EDITOR_CLOSE_FILE_OBSERV_TYPE_CODE SYSRES_CONST_EDITOR_CLOSE_PROCESS_OBSERV_TYPE_CODE SYSRES_CONST_EDITOR_TYPE_REQUISITE_CODE SYSRES_CONST_EDITORS_APPLICATION_NAME_REQUISITE_CODE SYSRES_CONST_EDITORS_CREATE_SEVERAL_PROCESSES_REQUISITE_CODE SYSRES_CONST_EDITORS_EXTENSION_REQUISITE_CODE SYSRES_CONST_EDITORS_OBSERVER_BY_PROCESS_TYPE SYSRES_CONST_EDITORS_REFERENCE_CODE SYSRES_CONST_EDITORS_REPLACE_SPEC_CHARS_REQUISITE_CODE SYSRES_CONST_EDITORS_USE_PLUGINS_REQUISITE_CODE SYSRES_CONST_EDITORS_VIEW_DOCUMENT_OPENED_TO_EDIT_CODE SYSRES_CONST_EDOC_CARD_TYPE_REQUISITE_CODE SYSRES_CONST_EDOC_CARD_TYPES_LINK_REQUISITE_CODE SYSRES_CONST_EDOC_CERTIFICATE_AND_PASSWORD_ENCODE_CODE SYSRES_CONST_EDOC_CERTIFICATE_ENCODE_CODE SYSRES_CONST_EDOC_DATE_REQUISITE_CODE SYSRES_CONST_EDOC_KIND_REFERENCE_CODE SYSRES_CONST_EDOC_KINDS_BY_TEMPLATE_ACTION_CODE SYSRES_CONST_EDOC_MANAGE_ACCESS_CODE SYSRES_CONST_EDOC_NONE_ENCODE_CODE SYSRES_CONST_EDOC_NUMBER_REQUISITE_CODE SYSRES_CONST_EDOC_PASSWORD_ENCODE_CODE SYSRES_CONST_EDOC_READONLY_ACCESS_CODE SYSRES_CONST_EDOC_SHELL_LIFE_TYPE_VIEW_VALUE SYSRES_CONST_EDOC_SIZE_RESTRICTION_PRIORITY_REQUISITE_CODE SYSRES_CONST_EDOC_STORAGE_CHECK_ACCESS_RIGHTS_REQUISITE_CODE SYSRES_CONST_EDOC_STORAGE_COMPUTER_NAME_REQUISITE_CODE SYSRES_CONST_EDOC_STORAGE_DATABASE_NAME_REQUISITE_CODE SYSRES_CONST_EDOC_STORAGE_EDIT_IN_STORAGE_REQUISITE_CODE SYSRES_CONST_EDOC_STORAGE_LOCAL_PATH_REQUISITE_CODE SYSRES_CONST_EDOC_STORAGE_SHARED_SOURCE_NAME_REQUISITE_CODE SYSRES_CONST_EDOC_TEMPLATE_REQUISITE_CODE SYSRES_CONST_EDOC_TYPES_REFERENCE_CODE SYSRES_CONST_EDOC_VERSION_ACTIVE_STAGE_CODE SYSRES_CONST_EDOC_VERSION_DESIGN_STAGE_CODE SYSRES_CONST_EDOC_VERSION_OBSOLETE_STAGE_CODE SYSRES_CONST_EDOC_WRITE_ACCES_CODE SYSRES_CONST_EDOCUMENT_CARD_REQUISITES_REFERENCE_CODE_SELECTED_REQUISITE SYSRES_CONST_ENCODE_CERTIFICATE_TYPE_CODE SYSRES_CONST_END_DATE_REQUISITE_CODE SYSRES_CONST_ENUMERATION_TYPE_REQUISITE_CODE SYSRES_CONST_EXECUTE_ACCESS_RIGHTS_TYPE_CODE SYSRES_CONST_EXECUTIVE_FILE_STORAGE_TYPE SYSRES_CONST_EXIST_CONST SYSRES_CONST_EXIST_VALUE SYSRES_CONST_EXPORT_LOCK_TYPE_ASK SYSRES_CONST_EXPORT_LOCK_TYPE_WITH_LOCK SYSRES_CONST_EXPORT_LOCK_TYPE_WITHOUT_LOCK SYSRES_CONST_EXPORT_VERSION_TYPE_ASK SYSRES_CONST_EXPORT_VERSION_TYPE_LAST SYSRES_CONST_EXPORT_VERSION_TYPE_LAST_ACTIVE SYSRES_CONST_EXTENSION_REQUISITE_CODE SYSRES_CONST_FILTER_NAME_REQUISITE_CODE SYSRES_CONST_FILTER_REQUISITE_CODE SYSRES_CONST_FILTER_TYPE_COMMON_CODE SYSRES_CONST_FILTER_TYPE_COMMON_NAME SYSRES_CONST_FILTER_TYPE_USER_CODE SYSRES_CONST_FILTER_TYPE_USER_NAME SYSRES_CONST_FILTER_VALUE_REQUISITE_NAME SYSRES_CONST_FLOAT_NUMBER_FORMAT_CHAR SYSRES_CONST_FLOAT_REQUISITE_TYPE SYSRES_CONST_FOLDER_AUTHOR_VALUE SYSRES_CONST_FOLDER_KIND_ANY_OBJECTS SYSRES_CONST_FOLDER_KIND_COMPONENTS SYSRES_CONST_FOLDER_KIND_EDOCS SYSRES_CONST_FOLDER_KIND_JOBS SYSRES_CONST_FOLDER_KIND_TASKS SYSRES_CONST_FOLDER_TYPE_COMMON SYSRES_CONST_FOLDER_TYPE_COMPONENT SYSRES_CONST_FOLDER_TYPE_FAVORITES SYSRES_CONST_FOLDER_TYPE_INBOX SYSRES_CONST_FOLDER_TYPE_OUTBOX SYSRES_CONST_FOLDER_TYPE_QUICK_LAUNCH SYSRES_CONST_FOLDER_TYPE_SEARCH SYSRES_CONST_FOLDER_TYPE_SHORTCUTS SYSRES_CONST_FOLDER_TYPE_USER SYSRES_CONST_FROM_DICTIONARY_ENUM_METHOD_FLAG SYSRES_CONST_FULL_SUBSTITUTE_TYPE SYSRES_CONST_FULL_SUBSTITUTE_TYPE_CODE SYSRES_CONST_FUNCTION_CANCEL_RESULT SYSRES_CONST_FUNCTION_CATEGORY_SYSTEM SYSRES_CONST_FUNCTION_CATEGORY_USER SYSRES_CONST_FUNCTION_FAILURE_RESULT SYSRES_CONST_FUNCTION_SAVE_RESULT SYSRES_CONST_GENERATED_REQUISITE SYSRES_CONST_GREEN_LIFE_CYCLE_STAGE_FONT_COLOR SYSRES_CONST_GROUP_ACCOUNT_TYPE_VALUE_CODE SYSRES_CONST_GROUP_CATEGORY_NORMAL_CODE SYSRES_CONST_GROUP_CATEGORY_NORMAL_NAME SYSRES_CONST_GROUP_CATEGORY_SERVICE_CODE SYSRES_CONST_GROUP_CATEGORY_SERVICE_NAME SYSRES_CONST_GROUP_COMMON_CATEGORY_FIELD_VALUE SYSRES_CONST_GROUP_FULL_NAME_REQUISITE_CODE SYSRES_CONST_GROUP_NAME_REQUISITE_CODE SYSRES_CONST_GROUP_RIGHTS_T_REQUISITE_CODE SYSRES_CONST_GROUP_SERVER_CODES_REQUISITE_CODE SYSRES_CONST_GROUP_SERVER_NAME_REQUISITE_CODE SYSRES_CONST_GROUP_SERVICE_CATEGORY_FIELD_VALUE SYSRES_CONST_GROUP_USER_REQUISITE_CODE SYSRES_CONST_GROUPS_REFERENCE_CODE SYSRES_CONST_GROUPS_REQUISITE_CODE SYSRES_CONST_HIDDEN_MODE_NAME SYSRES_CONST_HIGH_LVL_REQUISITE_CODE SYSRES_CONST_HISTORY_ACTION_CREATE_CODE SYSRES_CONST_HISTORY_ACTION_DELETE_CODE SYSRES_CONST_HISTORY_ACTION_EDIT_CODE SYSRES_CONST_HOUR_CHAR SYSRES_CONST_ID_REQUISITE_CODE SYSRES_CONST_IDSPS_REQUISITE_CODE SYSRES_CONST_IMAGE_MODE_COLOR SYSRES_CONST_IMAGE_MODE_GREYSCALE SYSRES_CONST_IMAGE_MODE_MONOCHROME SYSRES_CONST_IMPORTANCE_HIGH SYSRES_CONST_IMPORTANCE_LOW SYSRES_CONST_IMPORTANCE_NORMAL SYSRES_CONST_IN_DESIGN_VERSION_STATE_PICK_VALUE SYSRES_CONST_INCOMING_WORK_RULE_TYPE_CODE SYSRES_CONST_INT_REQUISITE SYSRES_CONST_INT_REQUISITE_TYPE SYSRES_CONST_INTEGER_NUMBER_FORMAT_CHAR SYSRES_CONST_INTEGER_TYPE_CHAR SYSRES_CONST_IS_GENERATED_REQUISITE_NEGATIVE_VALUE SYSRES_CONST_IS_PUBLIC_ROLE_REQUISITE_CODE SYSRES_CONST_IS_REMOTE_USER_NEGATIVE_VALUE SYSRES_CONST_IS_REMOTE_USER_POSITIVE_VALUE SYSRES_CONST_IS_STORED_REQUISITE_NEGATIVE_VALUE SYSRES_CONST_IS_STORED_REQUISITE_STORED_VALUE SYSRES_CONST_ITALIC_LIFE_CYCLE_STAGE_DRAW_STYLE SYSRES_CONST_JOB_BLOCK_DESCRIPTION SYSRES_CONST_JOB_KIND_CONTROL_JOB SYSRES_CONST_JOB_KIND_JOB SYSRES_CONST_JOB_KIND_NOTICE SYSRES_CONST_JOB_STATE_ABORTED SYSRES_CONST_JOB_STATE_COMPLETE SYSRES_CONST_JOB_STATE_WORKING SYSRES_CONST_KIND_REQUISITE_CODE SYSRES_CONST_KIND_REQUISITE_NAME SYSRES_CONST_KINDS_CREATE_SHADOW_COPIES_REQUISITE_CODE SYSRES_CONST_KINDS_DEFAULT_EDOC_LIFE_STAGE_REQUISITE_CODE SYSRES_CONST_KINDS_EDOC_ALL_TEPLATES_ALLOWED_REQUISITE_CODE SYSRES_CONST_KINDS_EDOC_ALLOW_LIFE_CYCLE_STAGE_CHANGING_REQUISITE_CODE SYSRES_CONST_KINDS_EDOC_ALLOW_MULTIPLE_ACTIVE_VERSIONS_REQUISITE_CODE SYSRES_CONST_KINDS_EDOC_SHARE_ACCES_RIGHTS_BY_DEFAULT_CODE SYSRES_CONST_KINDS_EDOC_TEMPLATE_REQUISITE_CODE SYSRES_CONST_KINDS_EDOC_TYPE_REQUISITE_CODE SYSRES_CONST_KINDS_SIGNERS_REQUISITES_CODE SYSRES_CONST_KOD_INPUT_TYPE SYSRES_CONST_LAST_UPDATE_DATE_REQUISITE_CODE SYSRES_CONST_LIFE_CYCLE_START_STAGE_REQUISITE_CODE SYSRES_CONST_LILAC_LIFE_CYCLE_STAGE_FONT_COLOR SYSRES_CONST_LINK_OBJECT_KIND_COMPONENT SYSRES_CONST_LINK_OBJECT_KIND_DOCUMENT SYSRES_CONST_LINK_OBJECT_KIND_EDOC SYSRES_CONST_LINK_OBJECT_KIND_FOLDER SYSRES_CONST_LINK_OBJECT_KIND_JOB SYSRES_CONST_LINK_OBJECT_KIND_REFERENCE SYSRES_CONST_LINK_OBJECT_KIND_TASK SYSRES_CONST_LINK_REF_TYPE_REQUISITE_CODE SYSRES_CONST_LIST_REFERENCE_MODE_NAME SYSRES_CONST_LOCALIZATION_DICTIONARY_MAIN_VIEW_CODE SYSRES_CONST_MAIN_VIEW_CODE SYSRES_CONST_MANUAL_ENUM_METHOD_FLAG SYSRES_CONST_MASTER_COMP_TYPE_REQUISITE_CODE SYSRES_CONST_MASTER_TABLE_REC_ID_REQUISITE_CODE SYSRES_CONST_MAXIMIZED_MODE_NAME SYSRES_CONST_ME_VALUE SYSRES_CONST_MESSAGE_ATTENTION_CAPTION SYSRES_CONST_MESSAGE_CONFIRMATION_CAPTION SYSRES_CONST_MESSAGE_ERROR_CAPTION SYSRES_CONST_MESSAGE_INFORMATION_CAPTION SYSRES_CONST_MINIMIZED_MODE_NAME SYSRES_CONST_MINUTE_CHAR SYSRES_CONST_MODULE_REQUISITE_CODE SYSRES_CONST_MONITORING_BLOCK_DESCRIPTION SYSRES_CONST_MONTH_FORMAT_VALUE SYSRES_CONST_NAME_LOCALIZE_ID_REQUISITE_CODE SYSRES_CONST_NAME_REQUISITE_CODE SYSRES_CONST_NAME_SINGULAR_REQUISITE_CODE SYSRES_CONST_NAMEAN_INPUT_TYPE SYSRES_CONST_NEGATIVE_PICK_VALUE SYSRES_CONST_NEGATIVE_VALUE SYSRES_CONST_NO SYSRES_CONST_NO_PICK_VALUE SYSRES_CONST_NO_SIGNATURE_REQUISITE_CODE SYSRES_CONST_NO_VALUE SYSRES_CONST_NONE_ACCESS_RIGHTS_TYPE_CODE SYSRES_CONST_NONOPERATING_RECORD_FLAG_VALUE SYSRES_CONST_NONOPERATING_RECORD_FLAG_VALUE_MASCULINE SYSRES_CONST_NORMAL_ACCESS_RIGHTS_TYPE_CODE SYSRES_CONST_NORMAL_LIFE_CYCLE_STAGE_DRAW_STYLE SYSRES_CONST_NORMAL_MODE_NAME SYSRES_CONST_NOT_ALLOWED_ACCESS_TYPE_CODE SYSRES_CONST_NOT_ALLOWED_ACCESS_TYPE_NAME SYSRES_CONST_NOTE_REQUISITE_CODE SYSRES_CONST_NOTICE_BLOCK_DESCRIPTION SYSRES_CONST_NUM_REQUISITE SYSRES_CONST_NUM_STR_REQUISITE_CODE SYSRES_CONST_NUMERATION_AUTO_NOT_STRONG SYSRES_CONST_NUMERATION_AUTO_STRONG SYSRES_CONST_NUMERATION_FROM_DICTONARY SYSRES_CONST_NUMERATION_MANUAL SYSRES_CONST_NUMERIC_TYPE_CHAR SYSRES_CONST_NUMREQ_REQUISITE_CODE SYSRES_CONST_OBSOLETE_VERSION_STATE_PICK_VALUE SYSRES_CONST_OPERATING_RECORD_FLAG_VALUE SYSRES_CONST_OPERATING_RECORD_FLAG_VALUE_CODE SYSRES_CONST_OPERATING_RECORD_FLAG_VALUE_FEMININE SYSRES_CONST_OPERATING_RECORD_FLAG_VALUE_MASCULINE SYSRES_CONST_OPTIONAL_FORM_COMP_REQCODE_PREFIX SYSRES_CONST_ORANGE_LIFE_CYCLE_STAGE_FONT_COLOR SYSRES_CONST_ORIGINALREF_REQUISITE_CODE SYSRES_CONST_OURFIRM_REF_CODE SYSRES_CONST_OURFIRM_REQUISITE_CODE SYSRES_CONST_OURFIRM_VAR SYSRES_CONST_OUTGOING_WORK_RULE_TYPE_CODE SYSRES_CONST_PICK_NEGATIVE_RESULT SYSRES_CONST_PICK_POSITIVE_RESULT SYSRES_CONST_PICK_REQUISITE SYSRES_CONST_PICK_REQUISITE_TYPE SYSRES_CONST_PICK_TYPE_CHAR SYSRES_CONST_PLAN_STATUS_REQUISITE_CODE SYSRES_CONST_PLATFORM_VERSION_COMMENT SYSRES_CONST_PLUGINS_SETTINGS_DESCRIPTION_REQUISITE_CODE SYSRES_CONST_POSITIVE_PICK_VALUE SYSRES_CONST_POWER_TO_CREATE_ACTION_CODE SYSRES_CONST_POWER_TO_SIGN_ACTION_CODE SYSRES_CONST_PRIORITY_REQUISITE_CODE SYSRES_CONST_QUALIFIED_TASK_TYPE SYSRES_CONST_QUALIFIED_TASK_TYPE_CODE SYSRES_CONST_RECSTAT_REQUISITE_CODE SYSRES_CONST_RED_LIFE_CYCLE_STAGE_FONT_COLOR SYSRES_CONST_REF_ID_T_REF_TYPE_REQUISITE_CODE SYSRES_CONST_REF_REQUISITE SYSRES_CONST_REF_REQUISITE_TYPE SYSRES_CONST_REF_REQUISITES_REFERENCE_CODE_SELECTED_REQUISITE SYSRES_CONST_REFERENCE_RECORD_HISTORY_CREATE_ACTION_CODE SYSRES_CONST_REFERENCE_RECORD_HISTORY_DELETE_ACTION_CODE SYSRES_CONST_REFERENCE_RECORD_HISTORY_MODIFY_ACTION_CODE SYSRES_CONST_REFERENCE_TYPE_CHAR SYSRES_CONST_REFERENCE_TYPE_REQUISITE_NAME SYSRES_CONST_REFERENCES_ADD_PARAMS_REQUISITE_CODE SYSRES_CONST_REFERENCES_DISPLAY_REQUISITE_REQUISITE_CODE SYSRES_CONST_REMOTE_SERVER_STATUS_WORKING SYSRES_CONST_REMOTE_SERVER_TYPE_MAIN SYSRES_CONST_REMOTE_SERVER_TYPE_SECONDARY SYSRES_CONST_REMOTE_USER_FLAG_VALUE_CODE SYSRES_CONST_REPORT_APP_EDITOR_INTERNAL SYSRES_CONST_REPORT_BASE_REPORT_ID_REQUISITE_CODE SYSRES_CONST_REPORT_BASE_REPORT_REQUISITE_CODE SYSRES_CONST_REPORT_SCRIPT_REQUISITE_CODE SYSRES_CONST_REPORT_TEMPLATE_REQUISITE_CODE SYSRES_CONST_REPORT_VIEWER_CODE_REQUISITE_CODE SYSRES_CONST_REQ_ALLOW_COMPONENT_DEFAULT_VALUE SYSRES_CONST_REQ_ALLOW_RECORD_DEFAULT_VALUE SYSRES_CONST_REQ_ALLOW_SERVER_COMPONENT_DEFAULT_VALUE SYSRES_CONST_REQ_MODE_AVAILABLE_CODE SYSRES_CONST_REQ_MODE_EDIT_CODE SYSRES_CONST_REQ_MODE_HIDDEN_CODE SYSRES_CONST_REQ_MODE_NOT_AVAILABLE_CODE SYSRES_CONST_REQ_MODE_VIEW_CODE SYSRES_CONST_REQ_NUMBER_REQUISITE_CODE SYSRES_CONST_REQ_SECTION_VALUE SYSRES_CONST_REQ_TYPE_VALUE SYSRES_CONST_REQUISITE_FORMAT_BY_UNIT SYSRES_CONST_REQUISITE_FORMAT_DATE_FULL SYSRES_CONST_REQUISITE_FORMAT_DATE_TIME SYSRES_CONST_REQUISITE_FORMAT_LEFT SYSRES_CONST_REQUISITE_FORMAT_RIGHT SYSRES_CONST_REQUISITE_FORMAT_WITHOUT_UNIT SYSRES_CONST_REQUISITE_NUMBER_REQUISITE_CODE SYSRES_CONST_REQUISITE_SECTION_ACTIONS SYSRES_CONST_REQUISITE_SECTION_BUTTON SYSRES_CONST_REQUISITE_SECTION_BUTTONS SYSRES_CONST_REQUISITE_SECTION_CARD SYSRES_CONST_REQUISITE_SECTION_TABLE SYSRES_CONST_REQUISITE_SECTION_TABLE10 SYSRES_CONST_REQUISITE_SECTION_TABLE11 SYSRES_CONST_REQUISITE_SECTION_TABLE12 SYSRES_CONST_REQUISITE_SECTION_TABLE13 SYSRES_CONST_REQUISITE_SECTION_TABLE14 SYSRES_CONST_REQUISITE_SECTION_TABLE15 SYSRES_CONST_REQUISITE_SECTION_TABLE16 SYSRES_CONST_REQUISITE_SECTION_TABLE17 SYSRES_CONST_REQUISITE_SECTION_TABLE18 SYSRES_CONST_REQUISITE_SECTION_TABLE19 SYSRES_CONST_REQUISITE_SECTION_TABLE2 SYSRES_CONST_REQUISITE_SECTION_TABLE20 SYSRES_CONST_REQUISITE_SECTION_TABLE21 SYSRES_CONST_REQUISITE_SECTION_TABLE22 SYSRES_CONST_REQUISITE_SECTION_TABLE23 SYSRES_CONST_REQUISITE_SECTION_TABLE24 SYSRES_CONST_REQUISITE_SECTION_TABLE3 SYSRES_CONST_REQUISITE_SECTION_TABLE4 SYSRES_CONST_REQUISITE_SECTION_TABLE5 SYSRES_CONST_REQUISITE_SECTION_TABLE6 SYSRES_CONST_REQUISITE_SECTION_TABLE7 SYSRES_CONST_REQUISITE_SECTION_TABLE8 SYSRES_CONST_REQUISITE_SECTION_TABLE9 SYSRES_CONST_REQUISITES_PSEUDOREFERENCE_REQUISITE_NUMBER_REQUISITE_CODE SYSRES_CONST_RIGHT_ALIGNMENT_CODE SYSRES_CONST_ROLES_REFERENCE_CODE SYSRES_CONST_ROUTE_STEP_AFTER_RUS SYSRES_CONST_ROUTE_STEP_AND_CONDITION_RUS SYSRES_CONST_ROUTE_STEP_OR_CONDITION_RUS SYSRES_CONST_ROUTE_TYPE_COMPLEX SYSRES_CONST_ROUTE_TYPE_PARALLEL SYSRES_CONST_ROUTE_TYPE_SERIAL SYSRES_CONST_SBDATASETDESC_NEGATIVE_VALUE SYSRES_CONST_SBDATASETDESC_POSITIVE_VALUE SYSRES_CONST_SBVIEWSDESC_POSITIVE_VALUE SYSRES_CONST_SCRIPT_BLOCK_DESCRIPTION SYSRES_CONST_SEARCH_BY_TEXT_REQUISITE_CODE SYSRES_CONST_SEARCHES_COMPONENT_CONTENT SYSRES_CONST_SEARCHES_CRITERIA_ACTION_NAME SYSRES_CONST_SEARCHES_EDOC_CONTENT SYSRES_CONST_SEARCHES_FOLDER_CONTENT SYSRES_CONST_SEARCHES_JOB_CONTENT SYSRES_CONST_SEARCHES_REFERENCE_CODE SYSRES_CONST_SEARCHES_TASK_CONTENT SYSRES_CONST_SECOND_CHAR SYSRES_CONST_SECTION_REQUISITE_ACTIONS_VALUE SYSRES_CONST_SECTION_REQUISITE_CARD_VALUE SYSRES_CONST_SECTION_REQUISITE_CODE SYSRES_CONST_SECTION_REQUISITE_DETAIL_1_VALUE SYSRES_CONST_SECTION_REQUISITE_DETAIL_2_VALUE SYSRES_CONST_SECTION_REQUISITE_DETAIL_3_VALUE SYSRES_CONST_SECTION_REQUISITE_DETAIL_4_VALUE SYSRES_CONST_SECTION_REQUISITE_DETAIL_5_VALUE SYSRES_CONST_SECTION_REQUISITE_DETAIL_6_VALUE SYSRES_CONST_SELECT_REFERENCE_MODE_NAME SYSRES_CONST_SELECT_TYPE_SELECTABLE SYSRES_CONST_SELECT_TYPE_SELECTABLE_ONLY_CHILD SYSRES_CONST_SELECT_TYPE_SELECTABLE_WITH_CHILD SYSRES_CONST_SELECT_TYPE_UNSLECTABLE SYSRES_CONST_SERVER_TYPE_MAIN SYSRES_CONST_SERVICE_USER_CATEGORY_FIELD_VALUE SYSRES_CONST_SETTINGS_USER_REQUISITE_CODE SYSRES_CONST_SIGNATURE_AND_ENCODE_CERTIFICATE_TYPE_CODE SYSRES_CONST_SIGNATURE_CERTIFICATE_TYPE_CODE SYSRES_CONST_SINGULAR_TITLE_REQUISITE_CODE SYSRES_CONST_SQL_SERVER_AUTHENTIFICATION_FLAG_VALUE_CODE SYSRES_CONST_SQL_SERVER_ENCODE_AUTHENTIFICATION_FLAG_VALUE_CODE SYSRES_CONST_STANDART_ROUTE_REFERENCE_CODE SYSRES_CONST_STANDART_ROUTE_REFERENCE_COMMENT_REQUISITE_CODE SYSRES_CONST_STANDART_ROUTES_GROUPS_REFERENCE_CODE SYSRES_CONST_STATE_REQ_NAME SYSRES_CONST_STATE_REQUISITE_ACTIVE_VALUE SYSRES_CONST_STATE_REQUISITE_CLOSED_VALUE SYSRES_CONST_STATE_REQUISITE_CODE SYSRES_CONST_STATIC_ROLE_TYPE_CODE SYSRES_CONST_STATUS_PLAN_DEFAULT_VALUE SYSRES_CONST_STATUS_VALUE_AUTOCLEANING SYSRES_CONST_STATUS_VALUE_BLUE_SQUARE SYSRES_CONST_STATUS_VALUE_COMPLETE SYSRES_CONST_STATUS_VALUE_GREEN_SQUARE SYSRES_CONST_STATUS_VALUE_ORANGE_SQUARE SYSRES_CONST_STATUS_VALUE_PURPLE_SQUARE SYSRES_CONST_STATUS_VALUE_RED_SQUARE SYSRES_CONST_STATUS_VALUE_SUSPEND SYSRES_CONST_STATUS_VALUE_YELLOW_SQUARE SYSRES_CONST_STDROUTE_SHOW_TO_USERS_REQUISITE_CODE SYSRES_CONST_STORAGE_TYPE_FILE SYSRES_CONST_STORAGE_TYPE_SQL_SERVER SYSRES_CONST_STR_REQUISITE SYSRES_CONST_STRIKEOUT_LIFE_CYCLE_STAGE_DRAW_STYLE SYSRES_CONST_STRING_FORMAT_LEFT_ALIGN_CHAR SYSRES_CONST_STRING_FORMAT_RIGHT_ALIGN_CHAR SYSRES_CONST_STRING_REQUISITE_CODE SYSRES_CONST_STRING_REQUISITE_TYPE SYSRES_CONST_STRING_TYPE_CHAR SYSRES_CONST_SUBSTITUTES_PSEUDOREFERENCE_CODE SYSRES_CONST_SUBTASK_BLOCK_DESCRIPTION SYSRES_CONST_SYSTEM_SETTING_CURRENT_USER_PARAM_VALUE SYSRES_CONST_SYSTEM_SETTING_EMPTY_VALUE_PARAM_VALUE SYSRES_CONST_SYSTEM_VERSION_COMMENT SYSRES_CONST_TASK_ACCESS_TYPE_ALL SYSRES_CONST_TASK_ACCESS_TYPE_ALL_MEMBERS SYSRES_CONST_TASK_ACCESS_TYPE_MANUAL SYSRES_CONST_TASK_ENCODE_TYPE_CERTIFICATION SYSRES_CONST_TASK_ENCODE_TYPE_CERTIFICATION_AND_PASSWORD SYSRES_CONST_TASK_ENCODE_TYPE_NONE SYSRES_CONST_TASK_ENCODE_TYPE_PASSWORD SYSRES_CONST_TASK_ROUTE_ALL_CONDITION SYSRES_CONST_TASK_ROUTE_AND_CONDITION SYSRES_CONST_TASK_ROUTE_OR_CONDITION SYSRES_CONST_TASK_STATE_ABORTED SYSRES_CONST_TASK_STATE_COMPLETE SYSRES_CONST_TASK_STATE_CONTINUED SYSRES_CONST_TASK_STATE_CONTROL SYSRES_CONST_TASK_STATE_INIT SYSRES_CONST_TASK_STATE_WORKING SYSRES_CONST_TASK_TITLE SYSRES_CONST_TASK_TYPES_GROUPS_REFERENCE_CODE SYSRES_CONST_TASK_TYPES_REFERENCE_CODE SYSRES_CONST_TEMPLATES_REFERENCE_CODE SYSRES_CONST_TEST_DATE_REQUISITE_NAME SYSRES_CONST_TEST_DEV_DATABASE_NAME SYSRES_CONST_TEST_DEV_SYSTEM_CODE SYSRES_CONST_TEST_EDMS_DATABASE_NAME SYSRES_CONST_TEST_EDMS_MAIN_CODE SYSRES_CONST_TEST_EDMS_MAIN_DB_NAME SYSRES_CONST_TEST_EDMS_SECOND_CODE SYSRES_CONST_TEST_EDMS_SECOND_DB_NAME SYSRES_CONST_TEST_EDMS_SYSTEM_CODE SYSRES_CONST_TEST_NUMERIC_REQUISITE_NAME SYSRES_CONST_TEXT_REQUISITE SYSRES_CONST_TEXT_REQUISITE_CODE SYSRES_CONST_TEXT_REQUISITE_TYPE SYSRES_CONST_TEXT_TYPE_CHAR SYSRES_CONST_TYPE_CODE_REQUISITE_CODE SYSRES_CONST_TYPE_REQUISITE_CODE SYSRES_CONST_UNDEFINED_LIFE_CYCLE_STAGE_FONT_COLOR SYSRES_CONST_UNITS_SECTION_ID_REQUISITE_CODE SYSRES_CONST_UNITS_SECTION_REQUISITE_CODE SYSRES_CONST_UNOPERATING_RECORD_FLAG_VALUE_CODE SYSRES_CONST_UNSTORED_DATA_REQUISITE_CODE SYSRES_CONST_UNSTORED_DATA_REQUISITE_NAME SYSRES_CONST_USE_ACCESS_TYPE_CODE SYSRES_CONST_USE_ACCESS_TYPE_NAME SYSRES_CONST_USER_ACCOUNT_TYPE_VALUE_CODE SYSRES_CONST_USER_ADDITIONAL_INFORMATION_REQUISITE_CODE SYSRES_CONST_USER_AND_GROUP_ID_FROM_PSEUDOREFERENCE_REQUISITE_CODE SYSRES_CONST_USER_CATEGORY_NORMAL SYSRES_CONST_USER_CERTIFICATE_REQUISITE_CODE SYSRES_CONST_USER_CERTIFICATE_STATE_REQUISITE_CODE SYSRES_CONST_USER_CERTIFICATE_SUBJECT_NAME_REQUISITE_CODE SYSRES_CONST_USER_CERTIFICATE_THUMBPRINT_REQUISITE_CODE SYSRES_CONST_USER_COMMON_CATEGORY SYSRES_CONST_USER_COMMON_CATEGORY_CODE SYSRES_CONST_USER_FULL_NAME_REQUISITE_CODE SYSRES_CONST_USER_GROUP_TYPE_REQUISITE_CODE SYSRES_CONST_USER_LOGIN_REQUISITE_CODE SYSRES_CONST_USER_REMOTE_CONTROLLER_REQUISITE_CODE SYSRES_CONST_USER_REMOTE_SYSTEM_REQUISITE_CODE SYSRES_CONST_USER_RIGHTS_T_REQUISITE_CODE SYSRES_CONST_USER_SERVER_NAME_REQUISITE_CODE SYSRES_CONST_USER_SERVICE_CATEGORY SYSRES_CONST_USER_SERVICE_CATEGORY_CODE SYSRES_CONST_USER_STATUS_ADMINISTRATOR_CODE SYSRES_CONST_USER_STATUS_ADMINISTRATOR_NAME SYSRES_CONST_USER_STATUS_DEVELOPER_CODE SYSRES_CONST_USER_STATUS_DEVELOPER_NAME SYSRES_CONST_USER_STATUS_DISABLED_CODE SYSRES_CONST_USER_STATUS_DISABLED_NAME SYSRES_CONST_USER_STATUS_SYSTEM_DEVELOPER_CODE SYSRES_CONST_USER_STATUS_USER_CODE SYSRES_CONST_USER_STATUS_USER_NAME SYSRES_CONST_USER_STATUS_USER_NAME_DEPRECATED SYSRES_CONST_USER_TYPE_FIELD_VALUE_USER SYSRES_CONST_USER_TYPE_REQUISITE_CODE SYSRES_CONST_USERS_CONTROLLER_REQUISITE_CODE SYSRES_CONST_USERS_IS_MAIN_SERVER_REQUISITE_CODE SYSRES_CONST_USERS_REFERENCE_CODE SYSRES_CONST_USERS_REGISTRATION_CERTIFICATES_ACTION_NAME SYSRES_CONST_USERS_REQUISITE_CODE SYSRES_CONST_USERS_SYSTEM_REQUISITE_CODE SYSRES_CONST_USERS_USER_ACCESS_RIGHTS_TYPR_REQUISITE_CODE SYSRES_CONST_USERS_USER_AUTHENTICATION_REQUISITE_CODE SYSRES_CONST_USERS_USER_COMPONENT_REQUISITE_CODE SYSRES_CONST_USERS_USER_GROUP_REQUISITE_CODE SYSRES_CONST_USERS_VIEW_CERTIFICATES_ACTION_NAME SYSRES_CONST_VIEW_DEFAULT_CODE SYSRES_CONST_VIEW_DEFAULT_NAME SYSRES_CONST_VIEWER_REQUISITE_CODE SYSRES_CONST_WAITING_BLOCK_DESCRIPTION SYSRES_CONST_WIZARD_FORM_LABEL_TEST_STRING  SYSRES_CONST_WIZARD_QUERY_PARAM_HEIGHT_ETALON_STRING SYSRES_CONST_WIZARD_REFERENCE_COMMENT_REQUISITE_CODE SYSRES_CONST_WORK_RULES_DESCRIPTION_REQUISITE_CODE SYSRES_CONST_WORK_TIME_CALENDAR_REFERENCE_CODE SYSRES_CONST_WORK_WORKFLOW_HARD_ROUTE_TYPE_VALUE SYSRES_CONST_WORK_WORKFLOW_HARD_ROUTE_TYPE_VALUE_CODE SYSRES_CONST_WORK_WORKFLOW_HARD_ROUTE_TYPE_VALUE_CODE_RUS SYSRES_CONST_WORK_WORKFLOW_SOFT_ROUTE_TYPE_VALUE_CODE_RUS SYSRES_CONST_WORKFLOW_ROUTE_TYPR_HARD SYSRES_CONST_WORKFLOW_ROUTE_TYPR_SOFT SYSRES_CONST_XML_ENCODING SYSRES_CONST_XREC_STAT_REQUISITE_CODE SYSRES_CONST_XRECID_FIELD_NAME SYSRES_CONST_YES SYSRES_CONST_YES_NO_2_REQUISITE_CODE SYSRES_CONST_YES_NO_REQUISITE_CODE SYSRES_CONST_YES_NO_T_REF_TYPE_REQUISITE_CODE SYSRES_CONST_YES_PICK_VALUE SYSRES_CONST_YES_VALUE ";
      const base_constants = "CR FALSE nil NO_VALUE NULL TAB TRUE YES_VALUE ";
      const base_group_name_constants = "ADMINISTRATORS_GROUP_NAME CUSTOMIZERS_GROUP_NAME DEVELOPERS_GROUP_NAME SERVICE_USERS_GROUP_NAME ";
      const decision_block_properties_constants = "DECISION_BLOCK_FIRST_OPERAND_PROPERTY DECISION_BLOCK_NAME_PROPERTY DECISION_BLOCK_OPERATION_PROPERTY DECISION_BLOCK_RESULT_TYPE_PROPERTY DECISION_BLOCK_SECOND_OPERAND_PROPERTY ";
      const file_extension_constants = "ANY_FILE_EXTENTION COMPRESSED_DOCUMENT_EXTENSION EXTENDED_DOCUMENT_EXTENSION SHORT_COMPRESSED_DOCUMENT_EXTENSION SHORT_EXTENDED_DOCUMENT_EXTENSION ";
      const job_block_properties_constants = "JOB_BLOCK_ABORT_DEADLINE_PROPERTY JOB_BLOCK_AFTER_FINISH_EVENT JOB_BLOCK_AFTER_QUERY_PARAMETERS_EVENT JOB_BLOCK_ATTACHMENT_PROPERTY JOB_BLOCK_ATTACHMENTS_RIGHTS_GROUP_PROPERTY JOB_BLOCK_ATTACHMENTS_RIGHTS_TYPE_PROPERTY JOB_BLOCK_BEFORE_QUERY_PARAMETERS_EVENT JOB_BLOCK_BEFORE_START_EVENT JOB_BLOCK_CREATED_JOBS_PROPERTY JOB_BLOCK_DEADLINE_PROPERTY JOB_BLOCK_EXECUTION_RESULTS_PROPERTY JOB_BLOCK_IS_PARALLEL_PROPERTY JOB_BLOCK_IS_RELATIVE_ABORT_DEADLINE_PROPERTY JOB_BLOCK_IS_RELATIVE_DEADLINE_PROPERTY JOB_BLOCK_JOB_TEXT_PROPERTY JOB_BLOCK_NAME_PROPERTY JOB_BLOCK_NEED_SIGN_ON_PERFORM_PROPERTY JOB_BLOCK_PERFORMER_PROPERTY JOB_BLOCK_RELATIVE_ABORT_DEADLINE_TYPE_PROPERTY JOB_BLOCK_RELATIVE_DEADLINE_TYPE_PROPERTY JOB_BLOCK_SUBJECT_PROPERTY ";
      const language_code_constants = "ENGLISH_LANGUAGE_CODE RUSSIAN_LANGUAGE_CODE ";
      const launching_external_applications_constants = "smHidden smMaximized smMinimized smNormal wmNo wmYes ";
      const link_kind_constants = "COMPONENT_TOKEN_LINK_KIND DOCUMENT_LINK_KIND EDOCUMENT_LINK_KIND FOLDER_LINK_KIND JOB_LINK_KIND REFERENCE_LINK_KIND TASK_LINK_KIND ";
      const lock_type_constants = "COMPONENT_TOKEN_LOCK_TYPE EDOCUMENT_VERSION_LOCK_TYPE ";
      const monitor_block_properties_constants = "MONITOR_BLOCK_AFTER_FINISH_EVENT MONITOR_BLOCK_BEFORE_START_EVENT MONITOR_BLOCK_DEADLINE_PROPERTY MONITOR_BLOCK_INTERVAL_PROPERTY MONITOR_BLOCK_INTERVAL_TYPE_PROPERTY MONITOR_BLOCK_IS_RELATIVE_DEADLINE_PROPERTY MONITOR_BLOCK_NAME_PROPERTY MONITOR_BLOCK_RELATIVE_DEADLINE_TYPE_PROPERTY MONITOR_BLOCK_SEARCH_SCRIPT_PROPERTY ";
      const notice_block_properties_constants = "NOTICE_BLOCK_AFTER_FINISH_EVENT NOTICE_BLOCK_ATTACHMENT_PROPERTY NOTICE_BLOCK_ATTACHMENTS_RIGHTS_GROUP_PROPERTY NOTICE_BLOCK_ATTACHMENTS_RIGHTS_TYPE_PROPERTY NOTICE_BLOCK_BEFORE_START_EVENT NOTICE_BLOCK_CREATED_NOTICES_PROPERTY NOTICE_BLOCK_DEADLINE_PROPERTY NOTICE_BLOCK_IS_RELATIVE_DEADLINE_PROPERTY NOTICE_BLOCK_NAME_PROPERTY NOTICE_BLOCK_NOTICE_TEXT_PROPERTY NOTICE_BLOCK_PERFORMER_PROPERTY NOTICE_BLOCK_RELATIVE_DEADLINE_TYPE_PROPERTY NOTICE_BLOCK_SUBJECT_PROPERTY ";
      const object_events_constants = "dseAfterCancel dseAfterClose dseAfterDelete dseAfterDeleteOutOfTransaction dseAfterInsert dseAfterOpen dseAfterScroll dseAfterUpdate dseAfterUpdateOutOfTransaction dseBeforeCancel dseBeforeClose dseBeforeDelete dseBeforeDetailUpdate dseBeforeInsert dseBeforeOpen dseBeforeUpdate dseOnAnyRequisiteChange dseOnCloseRecord dseOnDeleteError dseOnOpenRecord dseOnPrepareUpdate dseOnUpdateError dseOnUpdateRatifiedRecord dseOnValidDelete dseOnValidUpdate reOnChange reOnChangeValues SELECTION_BEGIN_ROUTE_EVENT SELECTION_END_ROUTE_EVENT ";
      const object_params_constants = "CURRENT_PERIOD_IS_REQUIRED PREVIOUS_CARD_TYPE_NAME SHOW_RECORD_PROPERTIES_FORM ";
      const other_constants = "ACCESS_RIGHTS_SETTING_DIALOG_CODE ADMINISTRATOR_USER_CODE ANALYTIC_REPORT_TYPE asrtHideLocal asrtHideRemote CALCULATED_ROLE_TYPE_CODE COMPONENTS_REFERENCE_DEVELOPER_VIEW_CODE DCTS_TEST_PROTOCOLS_FOLDER_PATH E_EDOC_VERSION_ALREADY_APPROVINGLY_SIGNED E_EDOC_VERSION_ALREADY_APPROVINGLY_SIGNED_BY_USER E_EDOC_VERSION_ALREDY_SIGNED E_EDOC_VERSION_ALREDY_SIGNED_BY_USER EDOC_TYPES_CODE_REQUISITE_FIELD_NAME EDOCUMENTS_ALIAS_NAME FILES_FOLDER_PATH FILTER_OPERANDS_DELIMITER FILTER_OPERATIONS_DELIMITER FORMCARD_NAME FORMLIST_NAME GET_EXTENDED_DOCUMENT_EXTENSION_CREATION_MODE GET_EXTENDED_DOCUMENT_EXTENSION_IMPORT_MODE INTEGRATED_REPORT_TYPE IS_BUILDER_APPLICATION_ROLE IS_BUILDER_APPLICATION_ROLE2 IS_BUILDER_USERS ISBSYSDEV LOG_FOLDER_PATH mbCancel mbNo mbNoToAll mbOK mbYes mbYesToAll MEMORY_DATASET_DESRIPTIONS_FILENAME mrNo mrNoToAll mrYes mrYesToAll MULTIPLE_SELECT_DIALOG_CODE NONOPERATING_RECORD_FLAG_FEMININE NONOPERATING_RECORD_FLAG_MASCULINE OPERATING_RECORD_FLAG_FEMININE OPERATING_RECORD_FLAG_MASCULINE PROFILING_SETTINGS_COMMON_SETTINGS_CODE_VALUE PROGRAM_INITIATED_LOOKUP_ACTION ratDelete ratEdit ratInsert REPORT_TYPE REQUIRED_PICK_VALUES_VARIABLE rmCard rmList SBRTE_PROGID_DEV SBRTE_PROGID_RELEASE STATIC_ROLE_TYPE_CODE SUPPRESS_EMPTY_TEMPLATE_CREATION SYSTEM_USER_CODE UPDATE_DIALOG_DATASET USED_IN_OBJECT_HINT_PARAM USER_INITIATED_LOOKUP_ACTION USER_NAME_FORMAT USER_SELECTION_RESTRICTIONS WORKFLOW_TEST_PROTOCOLS_FOLDER_PATH ELS_SUBTYPE_CONTROL_NAME ELS_FOLDER_KIND_CONTROL_NAME REPEAT_PROCESS_CURRENT_OBJECT_EXCEPTION_NAME ";
      const privileges_constants = "PRIVILEGE_COMPONENT_FULL_ACCESS PRIVILEGE_DEVELOPMENT_EXPORT PRIVILEGE_DEVELOPMENT_IMPORT PRIVILEGE_DOCUMENT_DELETE PRIVILEGE_ESD PRIVILEGE_FOLDER_DELETE PRIVILEGE_MANAGE_ACCESS_RIGHTS PRIVILEGE_MANAGE_REPLICATION PRIVILEGE_MANAGE_SESSION_SERVER PRIVILEGE_OBJECT_FULL_ACCESS PRIVILEGE_OBJECT_VIEW PRIVILEGE_RESERVE_LICENSE PRIVILEGE_SYSTEM_CUSTOMIZE PRIVILEGE_SYSTEM_DEVELOP PRIVILEGE_SYSTEM_INSTALL PRIVILEGE_TASK_DELETE PRIVILEGE_USER_PLUGIN_SETTINGS_CUSTOMIZE PRIVILEGES_PSEUDOREFERENCE_CODE ";
      const pseudoreference_code_constants = "ACCESS_TYPES_PSEUDOREFERENCE_CODE ALL_AVAILABLE_COMPONENTS_PSEUDOREFERENCE_CODE ALL_AVAILABLE_PRIVILEGES_PSEUDOREFERENCE_CODE ALL_REPLICATE_COMPONENTS_PSEUDOREFERENCE_CODE AVAILABLE_DEVELOPERS_COMPONENTS_PSEUDOREFERENCE_CODE COMPONENTS_PSEUDOREFERENCE_CODE FILTRATER_SETTINGS_CONFLICTS_PSEUDOREFERENCE_CODE GROUPS_PSEUDOREFERENCE_CODE RECEIVE_PROTOCOL_PSEUDOREFERENCE_CODE REFERENCE_REQUISITE_PSEUDOREFERENCE_CODE REFERENCE_REQUISITES_PSEUDOREFERENCE_CODE REFTYPES_PSEUDOREFERENCE_CODE REPLICATION_SEANCES_DIARY_PSEUDOREFERENCE_CODE SEND_PROTOCOL_PSEUDOREFERENCE_CODE SUBSTITUTES_PSEUDOREFERENCE_CODE SYSTEM_SETTINGS_PSEUDOREFERENCE_CODE UNITS_PSEUDOREFERENCE_CODE USERS_PSEUDOREFERENCE_CODE VIEWERS_PSEUDOREFERENCE_CODE ";
      const requisite_ISBCertificateType_values_constants = "CERTIFICATE_TYPE_ENCRYPT CERTIFICATE_TYPE_SIGN CERTIFICATE_TYPE_SIGN_AND_ENCRYPT ";
      const requisite_ISBEDocStorageType_values_constants = "STORAGE_TYPE_FILE STORAGE_TYPE_NAS_CIFS STORAGE_TYPE_SAPERION STORAGE_TYPE_SQL_SERVER ";
      const requisite_compType2_values_constants = "COMPTYPE2_REQUISITE_DOCUMENTS_VALUE COMPTYPE2_REQUISITE_TASKS_VALUE COMPTYPE2_REQUISITE_FOLDERS_VALUE COMPTYPE2_REQUISITE_REFERENCES_VALUE ";
      const requisite_name_constants = "SYSREQ_CODE SYSREQ_COMPTYPE2 SYSREQ_CONST_AVAILABLE_FOR_WEB SYSREQ_CONST_COMMON_CODE SYSREQ_CONST_COMMON_VALUE SYSREQ_CONST_FIRM_CODE SYSREQ_CONST_FIRM_STATUS SYSREQ_CONST_FIRM_VALUE SYSREQ_CONST_SERVER_STATUS SYSREQ_CONTENTS SYSREQ_DATE_OPEN SYSREQ_DATE_CLOSE SYSREQ_DESCRIPTION SYSREQ_DESCRIPTION_LOCALIZE_ID SYSREQ_DOUBLE SYSREQ_EDOC_ACCESS_TYPE SYSREQ_EDOC_AUTHOR SYSREQ_EDOC_CREATED SYSREQ_EDOC_DELEGATE_RIGHTS_REQUISITE_CODE SYSREQ_EDOC_EDITOR SYSREQ_EDOC_ENCODE_TYPE SYSREQ_EDOC_ENCRYPTION_PLUGIN_NAME SYSREQ_EDOC_ENCRYPTION_PLUGIN_VERSION SYSREQ_EDOC_EXPORT_DATE SYSREQ_EDOC_EXPORTER SYSREQ_EDOC_KIND SYSREQ_EDOC_LIFE_STAGE_NAME SYSREQ_EDOC_LOCKED_FOR_SERVER_CODE SYSREQ_EDOC_MODIFIED SYSREQ_EDOC_NAME SYSREQ_EDOC_NOTE SYSREQ_EDOC_QUALIFIED_ID SYSREQ_EDOC_SESSION_KEY SYSREQ_EDOC_SESSION_KEY_ENCRYPTION_PLUGIN_NAME SYSREQ_EDOC_SESSION_KEY_ENCRYPTION_PLUGIN_VERSION SYSREQ_EDOC_SIGNATURE_TYPE SYSREQ_EDOC_SIGNED SYSREQ_EDOC_STORAGE SYSREQ_EDOC_STORAGES_ARCHIVE_STORAGE SYSREQ_EDOC_STORAGES_CHECK_RIGHTS SYSREQ_EDOC_STORAGES_COMPUTER_NAME SYSREQ_EDOC_STORAGES_EDIT_IN_STORAGE SYSREQ_EDOC_STORAGES_EXECUTIVE_STORAGE SYSREQ_EDOC_STORAGES_FUNCTION SYSREQ_EDOC_STORAGES_INITIALIZED SYSREQ_EDOC_STORAGES_LOCAL_PATH SYSREQ_EDOC_STORAGES_SAPERION_DATABASE_NAME SYSREQ_EDOC_STORAGES_SEARCH_BY_TEXT SYSREQ_EDOC_STORAGES_SERVER_NAME SYSREQ_EDOC_STORAGES_SHARED_SOURCE_NAME SYSREQ_EDOC_STORAGES_TYPE SYSREQ_EDOC_TEXT_MODIFIED SYSREQ_EDOC_TYPE_ACT_CODE SYSREQ_EDOC_TYPE_ACT_DESCRIPTION SYSREQ_EDOC_TYPE_ACT_DESCRIPTION_LOCALIZE_ID SYSREQ_EDOC_TYPE_ACT_ON_EXECUTE SYSREQ_EDOC_TYPE_ACT_ON_EXECUTE_EXISTS SYSREQ_EDOC_TYPE_ACT_SECTION SYSREQ_EDOC_TYPE_ADD_PARAMS SYSREQ_EDOC_TYPE_COMMENT SYSREQ_EDOC_TYPE_EVENT_TEXT SYSREQ_EDOC_TYPE_NAME_IN_SINGULAR SYSREQ_EDOC_TYPE_NAME_IN_SINGULAR_LOCALIZE_ID SYSREQ_EDOC_TYPE_NAME_LOCALIZE_ID SYSREQ_EDOC_TYPE_NUMERATION_METHOD SYSREQ_EDOC_TYPE_PSEUDO_REQUISITE_CODE SYSREQ_EDOC_TYPE_REQ_CODE SYSREQ_EDOC_TYPE_REQ_DESCRIPTION SYSREQ_EDOC_TYPE_REQ_DESCRIPTION_LOCALIZE_ID SYSREQ_EDOC_TYPE_REQ_IS_LEADING SYSREQ_EDOC_TYPE_REQ_IS_REQUIRED SYSREQ_EDOC_TYPE_REQ_NUMBER SYSREQ_EDOC_TYPE_REQ_ON_CHANGE SYSREQ_EDOC_TYPE_REQ_ON_CHANGE_EXISTS SYSREQ_EDOC_TYPE_REQ_ON_SELECT SYSREQ_EDOC_TYPE_REQ_ON_SELECT_KIND SYSREQ_EDOC_TYPE_REQ_SECTION SYSREQ_EDOC_TYPE_VIEW_CARD SYSREQ_EDOC_TYPE_VIEW_CODE SYSREQ_EDOC_TYPE_VIEW_COMMENT SYSREQ_EDOC_TYPE_VIEW_IS_MAIN SYSREQ_EDOC_TYPE_VIEW_NAME SYSREQ_EDOC_TYPE_VIEW_NAME_LOCALIZE_ID SYSREQ_EDOC_VERSION_AUTHOR SYSREQ_EDOC_VERSION_CRC SYSREQ_EDOC_VERSION_DATA SYSREQ_EDOC_VERSION_EDITOR SYSREQ_EDOC_VERSION_EXPORT_DATE SYSREQ_EDOC_VERSION_EXPORTER SYSREQ_EDOC_VERSION_HIDDEN SYSREQ_EDOC_VERSION_LIFE_STAGE SYSREQ_EDOC_VERSION_MODIFIED SYSREQ_EDOC_VERSION_NOTE SYSREQ_EDOC_VERSION_SIGNATURE_TYPE SYSREQ_EDOC_VERSION_SIGNED SYSREQ_EDOC_VERSION_SIZE SYSREQ_EDOC_VERSION_SOURCE SYSREQ_EDOC_VERSION_TEXT_MODIFIED SYSREQ_EDOCKIND_DEFAULT_VERSION_STATE_CODE SYSREQ_FOLDER_KIND SYSREQ_FUNC_CATEGORY SYSREQ_FUNC_COMMENT SYSREQ_FUNC_GROUP SYSREQ_FUNC_GROUP_COMMENT SYSREQ_FUNC_GROUP_NUMBER SYSREQ_FUNC_HELP SYSREQ_FUNC_PARAM_DEF_VALUE SYSREQ_FUNC_PARAM_IDENT SYSREQ_FUNC_PARAM_NUMBER SYSREQ_FUNC_PARAM_TYPE SYSREQ_FUNC_TEXT SYSREQ_GROUP_CATEGORY SYSREQ_ID SYSREQ_LAST_UPDATE SYSREQ_LEADER_REFERENCE SYSREQ_LINE_NUMBER SYSREQ_MAIN_RECORD_ID SYSREQ_NAME SYSREQ_NAME_LOCALIZE_ID SYSREQ_NOTE SYSREQ_ORIGINAL_RECORD SYSREQ_OUR_FIRM SYSREQ_PROFILING_SETTINGS_BATCH_LOGING SYSREQ_PROFILING_SETTINGS_BATCH_SIZE SYSREQ_PROFILING_SETTINGS_PROFILING_ENABLED SYSREQ_PROFILING_SETTINGS_SQL_PROFILING_ENABLED SYSREQ_PROFILING_SETTINGS_START_LOGGED SYSREQ_RECORD_STATUS SYSREQ_REF_REQ_FIELD_NAME SYSREQ_REF_REQ_FORMAT SYSREQ_REF_REQ_GENERATED SYSREQ_REF_REQ_LENGTH SYSREQ_REF_REQ_PRECISION SYSREQ_REF_REQ_REFERENCE SYSREQ_REF_REQ_SECTION SYSREQ_REF_REQ_STORED SYSREQ_REF_REQ_TOKENS SYSREQ_REF_REQ_TYPE SYSREQ_REF_REQ_VIEW SYSREQ_REF_TYPE_ACT_CODE SYSREQ_REF_TYPE_ACT_DESCRIPTION SYSREQ_REF_TYPE_ACT_DESCRIPTION_LOCALIZE_ID SYSREQ_REF_TYPE_ACT_ON_EXECUTE SYSREQ_REF_TYPE_ACT_ON_EXECUTE_EXISTS SYSREQ_REF_TYPE_ACT_SECTION SYSREQ_REF_TYPE_ADD_PARAMS SYSREQ_REF_TYPE_COMMENT SYSREQ_REF_TYPE_COMMON_SETTINGS SYSREQ_REF_TYPE_DISPLAY_REQUISITE_NAME SYSREQ_REF_TYPE_EVENT_TEXT SYSREQ_REF_TYPE_MAIN_LEADING_REF SYSREQ_REF_TYPE_NAME_IN_SINGULAR SYSREQ_REF_TYPE_NAME_IN_SINGULAR_LOCALIZE_ID SYSREQ_REF_TYPE_NAME_LOCALIZE_ID SYSREQ_REF_TYPE_NUMERATION_METHOD SYSREQ_REF_TYPE_REQ_CODE SYSREQ_REF_TYPE_REQ_DESCRIPTION SYSREQ_REF_TYPE_REQ_DESCRIPTION_LOCALIZE_ID SYSREQ_REF_TYPE_REQ_IS_CONTROL SYSREQ_REF_TYPE_REQ_IS_FILTER SYSREQ_REF_TYPE_REQ_IS_LEADING SYSREQ_REF_TYPE_REQ_IS_REQUIRED SYSREQ_REF_TYPE_REQ_NUMBER SYSREQ_REF_TYPE_REQ_ON_CHANGE SYSREQ_REF_TYPE_REQ_ON_CHANGE_EXISTS SYSREQ_REF_TYPE_REQ_ON_SELECT SYSREQ_REF_TYPE_REQ_ON_SELECT_KIND SYSREQ_REF_TYPE_REQ_SECTION SYSREQ_REF_TYPE_VIEW_CARD SYSREQ_REF_TYPE_VIEW_CODE SYSREQ_REF_TYPE_VIEW_COMMENT SYSREQ_REF_TYPE_VIEW_IS_MAIN SYSREQ_REF_TYPE_VIEW_NAME SYSREQ_REF_TYPE_VIEW_NAME_LOCALIZE_ID SYSREQ_REFERENCE_TYPE_ID SYSREQ_STATE SYSREQ_STAT\u0415 SYSREQ_SYSTEM_SETTINGS_VALUE SYSREQ_TYPE SYSREQ_UNIT SYSREQ_UNIT_ID SYSREQ_USER_GROUPS_GROUP_FULL_NAME SYSREQ_USER_GROUPS_GROUP_NAME SYSREQ_USER_GROUPS_GROUP_SERVER_NAME SYSREQ_USERS_ACCESS_RIGHTS SYSREQ_USERS_AUTHENTICATION SYSREQ_USERS_CATEGORY SYSREQ_USERS_COMPONENT SYSREQ_USERS_COMPONENT_USER_IS_PUBLIC SYSREQ_USERS_DOMAIN SYSREQ_USERS_FULL_USER_NAME SYSREQ_USERS_GROUP SYSREQ_USERS_IS_MAIN_SERVER SYSREQ_USERS_LOGIN SYSREQ_USERS_REFERENCE_USER_IS_PUBLIC SYSREQ_USERS_STATUS SYSREQ_USERS_USER_CERTIFICATE SYSREQ_USERS_USER_CERTIFICATE_INFO SYSREQ_USERS_USER_CERTIFICATE_PLUGIN_NAME SYSREQ_USERS_USER_CERTIFICATE_PLUGIN_VERSION SYSREQ_USERS_USER_CERTIFICATE_STATE SYSREQ_USERS_USER_CERTIFICATE_SUBJECT_NAME SYSREQ_USERS_USER_CERTIFICATE_THUMBPRINT SYSREQ_USERS_USER_DEFAULT_CERTIFICATE SYSREQ_USERS_USER_DESCRIPTION SYSREQ_USERS_USER_GLOBAL_NAME SYSREQ_USERS_USER_LOGIN SYSREQ_USERS_USER_MAIN_SERVER SYSREQ_USERS_USER_TYPE SYSREQ_WORK_RULES_FOLDER_ID ";
      const result_constants = "RESULT_VAR_NAME RESULT_VAR_NAME_ENG ";
      const rule_identification_constants = "AUTO_NUMERATION_RULE_ID CANT_CHANGE_ID_REQUISITE_RULE_ID CANT_CHANGE_OURFIRM_REQUISITE_RULE_ID CHECK_CHANGING_REFERENCE_RECORD_USE_RULE_ID CHECK_CODE_REQUISITE_RULE_ID CHECK_DELETING_REFERENCE_RECORD_USE_RULE_ID CHECK_FILTRATER_CHANGES_RULE_ID CHECK_RECORD_INTERVAL_RULE_ID CHECK_REFERENCE_INTERVAL_RULE_ID CHECK_REQUIRED_DATA_FULLNESS_RULE_ID CHECK_REQUIRED_REQUISITES_FULLNESS_RULE_ID MAKE_RECORD_UNRATIFIED_RULE_ID RESTORE_AUTO_NUMERATION_RULE_ID SET_FIRM_CONTEXT_FROM_RECORD_RULE_ID SET_FIRST_RECORD_IN_LIST_FORM_RULE_ID SET_IDSPS_VALUE_RULE_ID SET_NEXT_CODE_VALUE_RULE_ID SET_OURFIRM_BOUNDS_RULE_ID SET_OURFIRM_REQUISITE_RULE_ID ";
      const script_block_properties_constants = "SCRIPT_BLOCK_AFTER_FINISH_EVENT SCRIPT_BLOCK_BEFORE_START_EVENT SCRIPT_BLOCK_EXECUTION_RESULTS_PROPERTY SCRIPT_BLOCK_NAME_PROPERTY SCRIPT_BLOCK_SCRIPT_PROPERTY ";
      const subtask_block_properties_constants = "SUBTASK_BLOCK_ABORT_DEADLINE_PROPERTY SUBTASK_BLOCK_AFTER_FINISH_EVENT SUBTASK_BLOCK_ASSIGN_PARAMS_EVENT SUBTASK_BLOCK_ATTACHMENTS_PROPERTY SUBTASK_BLOCK_ATTACHMENTS_RIGHTS_GROUP_PROPERTY SUBTASK_BLOCK_ATTACHMENTS_RIGHTS_TYPE_PROPERTY SUBTASK_BLOCK_BEFORE_START_EVENT SUBTASK_BLOCK_CREATED_TASK_PROPERTY SUBTASK_BLOCK_CREATION_EVENT SUBTASK_BLOCK_DEADLINE_PROPERTY SUBTASK_BLOCK_IMPORTANCE_PROPERTY SUBTASK_BLOCK_INITIATOR_PROPERTY SUBTASK_BLOCK_IS_RELATIVE_ABORT_DEADLINE_PROPERTY SUBTASK_BLOCK_IS_RELATIVE_DEADLINE_PROPERTY SUBTASK_BLOCK_JOBS_TYPE_PROPERTY SUBTASK_BLOCK_NAME_PROPERTY SUBTASK_BLOCK_PARALLEL_ROUTE_PROPERTY SUBTASK_BLOCK_PERFORMERS_PROPERTY SUBTASK_BLOCK_RELATIVE_ABORT_DEADLINE_TYPE_PROPERTY SUBTASK_BLOCK_RELATIVE_DEADLINE_TYPE_PROPERTY SUBTASK_BLOCK_REQUIRE_SIGN_PROPERTY SUBTASK_BLOCK_STANDARD_ROUTE_PROPERTY SUBTASK_BLOCK_START_EVENT SUBTASK_BLOCK_STEP_CONTROL_PROPERTY SUBTASK_BLOCK_SUBJECT_PROPERTY SUBTASK_BLOCK_TASK_CONTROL_PROPERTY SUBTASK_BLOCK_TEXT_PROPERTY SUBTASK_BLOCK_UNLOCK_ATTACHMENTS_ON_STOP_PROPERTY SUBTASK_BLOCK_USE_STANDARD_ROUTE_PROPERTY SUBTASK_BLOCK_WAIT_FOR_TASK_COMPLETE_PROPERTY ";
      const system_component_constants = "SYSCOMP_CONTROL_JOBS SYSCOMP_FOLDERS SYSCOMP_JOBS SYSCOMP_NOTICES SYSCOMP_TASKS ";
      const system_dialogs_constants = "SYSDLG_CREATE_EDOCUMENT SYSDLG_CREATE_EDOCUMENT_VERSION SYSDLG_CURRENT_PERIOD SYSDLG_EDIT_FUNCTION_HELP SYSDLG_EDOCUMENT_KINDS_FOR_TEMPLATE SYSDLG_EXPORT_MULTIPLE_EDOCUMENTS SYSDLG_EXPORT_SINGLE_EDOCUMENT SYSDLG_IMPORT_EDOCUMENT SYSDLG_MULTIPLE_SELECT SYSDLG_SETUP_ACCESS_RIGHTS SYSDLG_SETUP_DEFAULT_RIGHTS SYSDLG_SETUP_FILTER_CONDITION SYSDLG_SETUP_SIGN_RIGHTS SYSDLG_SETUP_TASK_OBSERVERS SYSDLG_SETUP_TASK_ROUTE SYSDLG_SETUP_USERS_LIST SYSDLG_SIGN_EDOCUMENT SYSDLG_SIGN_MULTIPLE_EDOCUMENTS ";
      const system_reference_names_constants = "SYSREF_ACCESS_RIGHTS_TYPES SYSREF_ADMINISTRATION_HISTORY SYSREF_ALL_AVAILABLE_COMPONENTS SYSREF_ALL_AVAILABLE_PRIVILEGES SYSREF_ALL_REPLICATING_COMPONENTS SYSREF_AVAILABLE_DEVELOPERS_COMPONENTS SYSREF_CALENDAR_EVENTS SYSREF_COMPONENT_TOKEN_HISTORY SYSREF_COMPONENT_TOKENS SYSREF_COMPONENTS SYSREF_CONSTANTS SYSREF_DATA_RECEIVE_PROTOCOL SYSREF_DATA_SEND_PROTOCOL SYSREF_DIALOGS SYSREF_DIALOGS_REQUISITES SYSREF_EDITORS SYSREF_EDOC_CARDS SYSREF_EDOC_TYPES SYSREF_EDOCUMENT_CARD_REQUISITES SYSREF_EDOCUMENT_CARD_TYPES SYSREF_EDOCUMENT_CARD_TYPES_REFERENCE SYSREF_EDOCUMENT_CARDS SYSREF_EDOCUMENT_HISTORY SYSREF_EDOCUMENT_KINDS SYSREF_EDOCUMENT_REQUISITES SYSREF_EDOCUMENT_SIGNATURES SYSREF_EDOCUMENT_TEMPLATES SYSREF_EDOCUMENT_TEXT_STORAGES SYSREF_EDOCUMENT_VIEWS SYSREF_FILTERER_SETUP_CONFLICTS SYSREF_FILTRATER_SETTING_CONFLICTS SYSREF_FOLDER_HISTORY SYSREF_FOLDERS SYSREF_FUNCTION_GROUPS SYSREF_FUNCTION_PARAMS SYSREF_FUNCTIONS SYSREF_JOB_HISTORY SYSREF_LINKS SYSREF_LOCALIZATION_DICTIONARY SYSREF_LOCALIZATION_LANGUAGES SYSREF_MODULES SYSREF_PRIVILEGES SYSREF_RECORD_HISTORY SYSREF_REFERENCE_REQUISITES SYSREF_REFERENCE_TYPE_VIEWS SYSREF_REFERENCE_TYPES SYSREF_REFERENCES SYSREF_REFERENCES_REQUISITES SYSREF_REMOTE_SERVERS SYSREF_REPLICATION_SESSIONS_LOG SYSREF_REPLICATION_SESSIONS_PROTOCOL SYSREF_REPORTS SYSREF_ROLES SYSREF_ROUTE_BLOCK_GROUPS SYSREF_ROUTE_BLOCKS SYSREF_SCRIPTS SYSREF_SEARCHES SYSREF_SERVER_EVENTS SYSREF_SERVER_EVENTS_HISTORY SYSREF_STANDARD_ROUTE_GROUPS SYSREF_STANDARD_ROUTES SYSREF_STATUSES SYSREF_SYSTEM_SETTINGS SYSREF_TASK_HISTORY SYSREF_TASK_KIND_GROUPS SYSREF_TASK_KINDS SYSREF_TASK_RIGHTS SYSREF_TASK_SIGNATURES SYSREF_TASKS SYSREF_UNITS SYSREF_USER_GROUPS SYSREF_USER_GROUPS_REFERENCE SYSREF_USER_SUBSTITUTION SYSREF_USERS SYSREF_USERS_REFERENCE SYSREF_VIEWERS SYSREF_WORKING_TIME_CALENDARS ";
      const table_name_constants = "ACCESS_RIGHTS_TABLE_NAME EDMS_ACCESS_TABLE_NAME EDOC_TYPES_TABLE_NAME ";
      const test_constants = "TEST_DEV_DB_NAME TEST_DEV_SYSTEM_CODE TEST_EDMS_DB_NAME TEST_EDMS_MAIN_CODE TEST_EDMS_MAIN_DB_NAME TEST_EDMS_SECOND_CODE TEST_EDMS_SECOND_DB_NAME TEST_EDMS_SYSTEM_CODE TEST_ISB5_MAIN_CODE TEST_ISB5_SECOND_CODE TEST_SQL_SERVER_2005_NAME TEST_SQL_SERVER_NAME ";
      const using_the_dialog_windows_constants = "ATTENTION_CAPTION cbsCommandLinks cbsDefault CONFIRMATION_CAPTION ERROR_CAPTION INFORMATION_CAPTION mrCancel mrOk ";
      const using_the_document_constants = "EDOC_VERSION_ACTIVE_STAGE_CODE EDOC_VERSION_DESIGN_STAGE_CODE EDOC_VERSION_OBSOLETE_STAGE_CODE ";
      const using_the_EA_and_encryption_constants = "cpDataEnciphermentEnabled cpDigitalSignatureEnabled cpID cpIssuer cpPluginVersion cpSerial cpSubjectName cpSubjSimpleName cpValidFromDate cpValidToDate ";
      const using_the_ISBL_editor_constants = "ISBL_SYNTAX NO_SYNTAX XML_SYNTAX ";
      const wait_block_properties_constants = "WAIT_BLOCK_AFTER_FINISH_EVENT WAIT_BLOCK_BEFORE_START_EVENT WAIT_BLOCK_DEADLINE_PROPERTY WAIT_BLOCK_IS_RELATIVE_DEADLINE_PROPERTY WAIT_BLOCK_NAME_PROPERTY WAIT_BLOCK_RELATIVE_DEADLINE_TYPE_PROPERTY ";
      const sysres_common_constants = "SYSRES_COMMON SYSRES_CONST SYSRES_MBFUNC SYSRES_SBDATA SYSRES_SBGUI SYSRES_SBINTF SYSRES_SBREFDSC SYSRES_SQLERRORS SYSRES_SYSCOMP ";
      const CONSTANTS = sysres_constants + base_constants + base_group_name_constants + decision_block_properties_constants + file_extension_constants + job_block_properties_constants + language_code_constants + launching_external_applications_constants + link_kind_constants + lock_type_constants + monitor_block_properties_constants + notice_block_properties_constants + object_events_constants + object_params_constants + other_constants + privileges_constants + pseudoreference_code_constants + requisite_ISBCertificateType_values_constants + requisite_ISBEDocStorageType_values_constants + requisite_compType2_values_constants + requisite_name_constants + result_constants + rule_identification_constants + script_block_properties_constants + subtask_block_properties_constants + system_component_constants + system_dialogs_constants + system_reference_names_constants + table_name_constants + test_constants + using_the_dialog_windows_constants + using_the_document_constants + using_the_EA_and_encryption_constants + using_the_ISBL_editor_constants + wait_block_properties_constants + sysres_common_constants;
      const TAccountType = "atUser atGroup atRole ";
      const TActionEnabledMode = "aemEnabledAlways aemDisabledAlways aemEnabledOnBrowse aemEnabledOnEdit aemDisabledOnBrowseEmpty ";
      const TAddPosition = "apBegin apEnd ";
      const TAlignment = "alLeft alRight ";
      const TAreaShowMode = "asmNever asmNoButCustomize asmAsLastTime asmYesButCustomize asmAlways ";
      const TCertificateInvalidationReason = "cirCommon cirRevoked ";
      const TCertificateType = "ctSignature ctEncode ctSignatureEncode ";
      const TCheckListBoxItemState = "clbUnchecked clbChecked clbGrayed ";
      const TCloseOnEsc = "ceISB ceAlways ceNever ";
      const TCompType = "ctDocument ctReference ctScript ctUnknown ctReport ctDialog ctFunction ctFolder ctEDocument ctTask ctJob ctNotice ctControlJob ";
      const TConditionFormat = "cfInternal cfDisplay ";
      const TConnectionIntent = "ciUnspecified ciWrite ciRead ";
      const TContentKind = "ckFolder ckEDocument ckTask ckJob ckComponentToken ckAny ckReference ckScript ckReport ckDialog ";
      const TControlType = "ctISBLEditor ctBevel ctButton ctCheckListBox ctComboBox ctComboEdit ctGrid ctDBCheckBox ctDBComboBox ctDBEdit ctDBEllipsis ctDBMemo ctDBNavigator ctDBRadioGroup ctDBStatusLabel ctEdit ctGroupBox ctInplaceHint ctMemo ctPanel ctListBox ctRadioButton ctRichEdit ctTabSheet ctWebBrowser ctImage ctHyperLink ctLabel ctDBMultiEllipsis ctRibbon ctRichView ctInnerPanel ctPanelGroup ctBitButton ";
      const TCriterionContentType = "cctDate cctInteger cctNumeric cctPick cctReference cctString cctText ";
      const TCultureType = "cltInternal cltPrimary cltGUI ";
      const TDataSetEventType = "dseBeforeOpen dseAfterOpen dseBeforeClose dseAfterClose dseOnValidDelete dseBeforeDelete dseAfterDelete dseAfterDeleteOutOfTransaction dseOnDeleteError dseBeforeInsert dseAfterInsert dseOnValidUpdate dseBeforeUpdate dseOnUpdateRatifiedRecord dseAfterUpdate dseAfterUpdateOutOfTransaction dseOnUpdateError dseAfterScroll dseOnOpenRecord dseOnCloseRecord dseBeforeCancel dseAfterCancel dseOnUpdateDeadlockError dseBeforeDetailUpdate dseOnPrepareUpdate dseOnAnyRequisiteChange ";
      const TDataSetState = "dssEdit dssInsert dssBrowse dssInActive ";
      const TDateFormatType = "dftDate dftShortDate dftDateTime dftTimeStamp ";
      const TDateOffsetType = "dotDays dotHours dotMinutes dotSeconds ";
      const TDateTimeKind = "dtkndLocal dtkndUTC ";
      const TDeaAccessRights = "arNone arView arEdit arFull ";
      const TDocumentDefaultAction = "ddaView ddaEdit ";
      const TEditMode = "emLock emEdit emSign emExportWithLock emImportWithUnlock emChangeVersionNote emOpenForModify emChangeLifeStage emDelete emCreateVersion emImport emUnlockExportedWithLock emStart emAbort emReInit emMarkAsReaded emMarkAsUnreaded emPerform emAccept emResume emChangeRights emEditRoute emEditObserver emRecoveryFromLocalCopy emChangeWorkAccessType emChangeEncodeTypeToCertificate emChangeEncodeTypeToPassword emChangeEncodeTypeToNone emChangeEncodeTypeToCertificatePassword emChangeStandardRoute emGetText emOpenForView emMoveToStorage emCreateObject emChangeVersionHidden emDeleteVersion emChangeLifeCycleStage emApprovingSign emExport emContinue emLockFromEdit emUnLockForEdit emLockForServer emUnlockFromServer emDelegateAccessRights emReEncode ";
      const TEditorCloseObservType = "ecotFile ecotProcess ";
      const TEdmsApplicationAction = "eaGet eaCopy eaCreate eaCreateStandardRoute ";
      const TEDocumentLockType = "edltAll edltNothing edltQuery ";
      const TEDocumentStepShowMode = "essmText essmCard ";
      const TEDocumentStepVersionType = "esvtLast esvtLastActive esvtSpecified ";
      const TEDocumentStorageFunction = "edsfExecutive edsfArchive ";
      const TEDocumentStorageType = "edstSQLServer edstFile ";
      const TEDocumentVersionSourceType = "edvstNone edvstEDocumentVersionCopy edvstFile edvstTemplate edvstScannedFile ";
      const TEDocumentVersionState = "vsDefault vsDesign vsActive vsObsolete ";
      const TEncodeType = "etNone etCertificate etPassword etCertificatePassword ";
      const TExceptionCategory = "ecException ecWarning ecInformation ";
      const TExportedSignaturesType = "estAll estApprovingOnly ";
      const TExportedVersionType = "evtLast evtLastActive evtQuery ";
      const TFieldDataType = "fdtString fdtNumeric fdtInteger fdtDate fdtText fdtUnknown fdtWideString fdtLargeInteger ";
      const TFolderType = "ftInbox ftOutbox ftFavorites ftCommonFolder ftUserFolder ftComponents ftQuickLaunch ftShortcuts ftSearch ";
      const TGridRowHeight = "grhAuto grhX1 grhX2 grhX3 ";
      const THyperlinkType = "hltText hltRTF hltHTML ";
      const TImageFileFormat = "iffBMP iffJPEG iffMultiPageTIFF iffSinglePageTIFF iffTIFF iffPNG ";
      const TImageMode = "im8bGrayscale im24bRGB im1bMonochrome ";
      const TImageType = "itBMP itJPEG itWMF itPNG ";
      const TInplaceHintKind = "ikhInformation ikhWarning ikhError ikhNoIcon ";
      const TISBLContext = "icUnknown icScript icFunction icIntegratedReport icAnalyticReport icDataSetEventHandler icActionHandler icFormEventHandler icLookUpEventHandler icRequisiteChangeEventHandler icBeforeSearchEventHandler icRoleCalculation icSelectRouteEventHandler icBlockPropertyCalculation icBlockQueryParamsEventHandler icChangeSearchResultEventHandler icBlockEventHandler icSubTaskInitEventHandler icEDocDataSetEventHandler icEDocLookUpEventHandler icEDocActionHandler icEDocFormEventHandler icEDocRequisiteChangeEventHandler icStructuredConversionRule icStructuredConversionEventBefore icStructuredConversionEventAfter icWizardEventHandler icWizardFinishEventHandler icWizardStepEventHandler icWizardStepFinishEventHandler icWizardActionEnableEventHandler icWizardActionExecuteEventHandler icCreateJobsHandler icCreateNoticesHandler icBeforeLookUpEventHandler icAfterLookUpEventHandler icTaskAbortEventHandler icWorkflowBlockActionHandler icDialogDataSetEventHandler icDialogActionHandler icDialogLookUpEventHandler icDialogRequisiteChangeEventHandler icDialogFormEventHandler icDialogValidCloseEventHandler icBlockFormEventHandler icTaskFormEventHandler icReferenceMethod icEDocMethod icDialogMethod icProcessMessageHandler ";
      const TItemShow = "isShow isHide isByUserSettings ";
      const TJobKind = "jkJob jkNotice jkControlJob ";
      const TJoinType = "jtInner jtLeft jtRight jtFull jtCross ";
      const TLabelPos = "lbpAbove lbpBelow lbpLeft lbpRight ";
      const TLicensingType = "eltPerConnection eltPerUser ";
      const TLifeCycleStageFontColor = "sfcUndefined sfcBlack sfcGreen sfcRed sfcBlue sfcOrange sfcLilac ";
      const TLifeCycleStageFontStyle = "sfsItalic sfsStrikeout sfsNormal ";
      const TLockableDevelopmentComponentType = "ldctStandardRoute ldctWizard ldctScript ldctFunction ldctRouteBlock ldctIntegratedReport ldctAnalyticReport ldctReferenceType ldctEDocumentType ldctDialog ldctServerEvents ";
      const TMaxRecordCountRestrictionType = "mrcrtNone mrcrtUser mrcrtMaximal mrcrtCustom ";
      const TRangeValueType = "vtEqual vtGreaterOrEqual vtLessOrEqual vtRange ";
      const TRelativeDate = "rdYesterday rdToday rdTomorrow rdThisWeek rdThisMonth rdThisYear rdNextMonth rdNextWeek rdLastWeek rdLastMonth ";
      const TReportDestination = "rdWindow rdFile rdPrinter ";
      const TReqDataType = "rdtString rdtNumeric rdtInteger rdtDate rdtReference rdtAccount rdtText rdtPick rdtUnknown rdtLargeInteger rdtDocument ";
      const TRequisiteEventType = "reOnChange reOnChangeValues ";
      const TSBTimeType = "ttGlobal ttLocal ttUser ttSystem ";
      const TSearchShowMode = "ssmBrowse ssmSelect ssmMultiSelect ssmBrowseModal ";
      const TSelectMode = "smSelect smLike smCard ";
      const TSignatureType = "stNone stAuthenticating stApproving ";
      const TSignerContentType = "sctString sctStream ";
      const TStringsSortType = "sstAnsiSort sstNaturalSort ";
      const TStringValueType = "svtEqual svtContain ";
      const TStructuredObjectAttributeType = "soatString soatNumeric soatInteger soatDatetime soatReferenceRecord soatText soatPick soatBoolean soatEDocument soatAccount soatIntegerCollection soatNumericCollection soatStringCollection soatPickCollection soatDatetimeCollection soatBooleanCollection soatReferenceRecordCollection soatEDocumentCollection soatAccountCollection soatContents soatUnknown ";
      const TTaskAbortReason = "tarAbortByUser tarAbortByWorkflowException ";
      const TTextValueType = "tvtAllWords tvtExactPhrase tvtAnyWord ";
      const TUserObjectStatus = "usNone usCompleted usRedSquare usBlueSquare usYellowSquare usGreenSquare usOrangeSquare usPurpleSquare usFollowUp ";
      const TUserType = "utUnknown utUser utDeveloper utAdministrator utSystemDeveloper utDisconnected ";
      const TValuesBuildType = "btAnd btDetailAnd btOr btNotOr btOnly ";
      const TViewMode = "vmView vmSelect vmNavigation ";
      const TViewSelectionMode = "vsmSingle vsmMultiple vsmMultipleCheck vsmNoSelection ";
      const TWizardActionType = "wfatPrevious wfatNext wfatCancel wfatFinish ";
      const TWizardFormElementProperty = "wfepUndefined wfepText3 wfepText6 wfepText9 wfepSpinEdit wfepDropDown wfepRadioGroup wfepFlag wfepText12 wfepText15 wfepText18 wfepText21 wfepText24 wfepText27 wfepText30 wfepRadioGroupColumn1 wfepRadioGroupColumn2 wfepRadioGroupColumn3 ";
      const TWizardFormElementType = "wfetQueryParameter wfetText wfetDelimiter wfetLabel ";
      const TWizardParamType = "wptString wptInteger wptNumeric wptBoolean wptDateTime wptPick wptText wptUser wptUserList wptEDocumentInfo wptEDocumentInfoList wptReferenceRecordInfo wptReferenceRecordInfoList wptFolderInfo wptTaskInfo wptContents wptFileName wptDate ";
      const TWizardStepResult = "wsrComplete wsrGoNext wsrGoPrevious wsrCustom wsrCancel wsrGoFinal ";
      const TWizardStepType = "wstForm wstEDocument wstTaskCard wstReferenceRecordCard wstFinal ";
      const TWorkAccessType = "waAll waPerformers waManual ";
      const TWorkflowBlockType = "wsbStart wsbFinish wsbNotice wsbStep wsbDecision wsbWait wsbMonitor wsbScript wsbConnector wsbSubTask wsbLifeCycleStage wsbPause ";
      const TWorkflowDataType = "wdtInteger wdtFloat wdtString wdtPick wdtDateTime wdtBoolean wdtTask wdtJob wdtFolder wdtEDocument wdtReferenceRecord wdtUser wdtGroup wdtRole wdtIntegerCollection wdtFloatCollection wdtStringCollection wdtPickCollection wdtDateTimeCollection wdtBooleanCollection wdtTaskCollection wdtJobCollection wdtFolderCollection wdtEDocumentCollection wdtReferenceRecordCollection wdtUserCollection wdtGroupCollection wdtRoleCollection wdtContents wdtUserList wdtSearchDescription wdtDeadLine wdtPickSet wdtAccountCollection ";
      const TWorkImportance = "wiLow wiNormal wiHigh ";
      const TWorkRouteType = "wrtSoft wrtHard ";
      const TWorkState = "wsInit wsRunning wsDone wsControlled wsAborted wsContinued ";
      const TWorkTextBuildingMode = "wtmFull wtmFromCurrent wtmOnlyCurrent ";
      const ENUMS = TAccountType + TActionEnabledMode + TAddPosition + TAlignment + TAreaShowMode + TCertificateInvalidationReason + TCertificateType + TCheckListBoxItemState + TCloseOnEsc + TCompType + TConditionFormat + TConnectionIntent + TContentKind + TControlType + TCriterionContentType + TCultureType + TDataSetEventType + TDataSetState + TDateFormatType + TDateOffsetType + TDateTimeKind + TDeaAccessRights + TDocumentDefaultAction + TEditMode + TEditorCloseObservType + TEdmsApplicationAction + TEDocumentLockType + TEDocumentStepShowMode + TEDocumentStepVersionType + TEDocumentStorageFunction + TEDocumentStorageType + TEDocumentVersionSourceType + TEDocumentVersionState + TEncodeType + TExceptionCategory + TExportedSignaturesType + TExportedVersionType + TFieldDataType + TFolderType + TGridRowHeight + THyperlinkType + TImageFileFormat + TImageMode + TImageType + TInplaceHintKind + TISBLContext + TItemShow + TJobKind + TJoinType + TLabelPos + TLicensingType + TLifeCycleStageFontColor + TLifeCycleStageFontStyle + TLockableDevelopmentComponentType + TMaxRecordCountRestrictionType + TRangeValueType + TRelativeDate + TReportDestination + TReqDataType + TRequisiteEventType + TSBTimeType + TSearchShowMode + TSelectMode + TSignatureType + TSignerContentType + TStringsSortType + TStringValueType + TStructuredObjectAttributeType + TTaskAbortReason + TTextValueType + TUserObjectStatus + TUserType + TValuesBuildType + TViewMode + TViewSelectionMode + TWizardActionType + TWizardFormElementProperty + TWizardFormElementType + TWizardParamType + TWizardStepResult + TWizardStepType + TWorkAccessType + TWorkflowBlockType + TWorkflowDataType + TWorkImportance + TWorkRouteType + TWorkState + TWorkTextBuildingMode;
      const system_functions = "AddSubString AdjustLineBreaks AmountInWords Analysis ArrayDimCount ArrayHighBound ArrayLowBound ArrayOf ArrayReDim Assert Assigned BeginOfMonth BeginOfPeriod BuildProfilingOperationAnalysis CallProcedure CanReadFile CArrayElement CDataSetRequisite ChangeDate ChangeReferenceDataset Char CharPos CheckParam CheckParamValue CompareStrings ConstantExists ControlState ConvertDateStr Copy CopyFile CreateArray CreateCachedReference CreateConnection CreateDialog CreateDualListDialog CreateEditor CreateException CreateFile CreateFolderDialog CreateInputDialog CreateLinkFile CreateList CreateLock CreateMemoryDataSet CreateObject CreateOpenDialog CreateProgress CreateQuery CreateReference CreateReport CreateSaveDialog CreateScript CreateSQLPivotFunction CreateStringList CreateTreeListSelectDialog CSelectSQL CSQL CSubString CurrentUserID CurrentUserName CurrentVersion DataSetLocateEx DateDiff DateTimeDiff DateToStr DayOfWeek DeleteFile DirectoryExists DisableCheckAccessRights DisableCheckFullShowingRestriction DisableMassTaskSendingRestrictions DropTable DupeString EditText EnableCheckAccessRights EnableCheckFullShowingRestriction EnableMassTaskSendingRestrictions EndOfMonth EndOfPeriod ExceptionExists ExceptionsOff ExceptionsOn Execute ExecuteProcess Exit ExpandEnvironmentVariables ExtractFileDrive ExtractFileExt ExtractFileName ExtractFilePath ExtractParams FileExists FileSize FindFile FindSubString FirmContext ForceDirectories Format FormatDate FormatNumeric FormatSQLDate FormatString FreeException GetComponent GetComponentLaunchParam GetConstant GetLastException GetReferenceRecord GetRefTypeByRefID GetTableID GetTempFolder IfThen In IndexOf InputDialog InputDialogEx InteractiveMode IsFileLocked IsGraphicFile IsNumeric Length LoadString LoadStringFmt LocalTimeToUTC LowerCase Max MessageBox MessageBoxEx MimeDecodeBinary MimeDecodeString MimeEncodeBinary MimeEncodeString Min MoneyInWords MoveFile NewID Now OpenFile Ord Precision Raise ReadCertificateFromFile ReadFile ReferenceCodeByID ReferenceNumber ReferenceRequisiteMode ReferenceRequisiteValue RegionDateSettings RegionNumberSettings RegionTimeSettings RegRead RegWrite RenameFile Replace Round SelectServerCode SelectSQL ServerDateTime SetConstant SetManagedFolderFieldsState ShowConstantsInputDialog ShowMessage Sleep Split SQL SQL2XLSTAB SQLProfilingSendReport StrToDate SubString SubStringCount SystemSetting Time TimeDiff Today Transliterate Trim UpperCase UserStatus UTCToLocalTime ValidateXML VarIsClear VarIsEmpty VarIsNull WorkTimeDiff WriteFile WriteFileEx WriteObjectHistory \u0410\u043D\u0430\u043B\u0438\u0437 \u0411\u0430\u0437\u0430\u0414\u0430\u043D\u043D\u044B\u0445 \u0411\u043B\u043E\u043A\u0415\u0441\u0442\u044C \u0411\u043B\u043E\u043A\u0415\u0441\u0442\u044C\u0420\u0430\u0441\u0448 \u0411\u043B\u043E\u043A\u0418\u043D\u0444\u043E \u0411\u043B\u043E\u043A\u0421\u043D\u044F\u0442\u044C \u0411\u043B\u043E\u043A\u0421\u043D\u044F\u0442\u044C\u0420\u0430\u0441\u0448 \u0411\u043B\u043E\u043A\u0423\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C \u0412\u0432\u043E\u0434 \u0412\u0432\u043E\u0434\u041C\u0435\u043D\u044E \u0412\u0435\u0434\u0421 \u0412\u0435\u0434\u0421\u043F\u0440 \u0412\u0435\u0440\u0445\u043D\u044F\u044F\u0413\u0440\u0430\u043D\u0438\u0446\u0430\u041C\u0430\u0441\u0441\u0438\u0432\u0430 \u0412\u043D\u0435\u0448\u041F\u0440\u043E\u0433\u0440 \u0412\u043E\u0441\u0441\u0442 \u0412\u0440\u0435\u043C\u0435\u043D\u043D\u0430\u044F\u041F\u0430\u043F\u043A\u0430 \u0412\u0440\u0435\u043C\u044F \u0412\u044B\u0431\u043E\u0440SQL \u0412\u044B\u0431\u0440\u0430\u0442\u044C\u0417\u0430\u043F\u0438\u0441\u044C \u0412\u044B\u0434\u0435\u043B\u0438\u0442\u044C\u0421\u0442\u0440 \u0412\u044B\u0437\u0432\u0430\u0442\u044C \u0412\u044B\u043F\u043E\u043B\u043D\u0438\u0442\u044C \u0412\u044B\u043F\u041F\u0440\u043E\u0433\u0440 \u0413\u0440\u0430\u0444\u0438\u0447\u0435\u0441\u043A\u0438\u0439\u0424\u0430\u0439\u043B \u0413\u0440\u0443\u043F\u043F\u0430\u0414\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u043E \u0414\u0430\u0442\u0430\u0412\u0440\u0435\u043C\u044F\u0421\u0435\u0440\u0432 \u0414\u0435\u043D\u044C\u041D\u0435\u0434\u0435\u043B\u0438 \u0414\u0438\u0430\u043B\u043E\u0433\u0414\u0430\u041D\u0435\u0442 \u0414\u043B\u0438\u043D\u0430\u0421\u0442\u0440 \u0414\u043E\u0431\u041F\u043E\u0434\u0441\u0442\u0440 \u0415\u041F\u0443\u0441\u0442\u043E \u0415\u0441\u043B\u0438\u0422\u043E \u0415\u0427\u0438\u0441\u043B\u043E \u0417\u0430\u043C\u041F\u043E\u0434\u0441\u0442\u0440 \u0417\u0430\u043F\u0438\u0441\u044C\u0421\u043F\u0440\u0430\u0432\u043E\u0447\u043D\u0438\u043A\u0430 \u0417\u043D\u0430\u0447\u041F\u043E\u043B\u044F\u0421\u043F\u0440 \u0418\u0414\u0422\u0438\u043F\u0421\u043F\u0440 \u0418\u0437\u0432\u043B\u0435\u0447\u044C\u0414\u0438\u0441\u043A \u0418\u0437\u0432\u043B\u0435\u0447\u044C\u0418\u043C\u044F\u0424\u0430\u0439\u043B\u0430 \u0418\u0437\u0432\u043B\u0435\u0447\u044C\u041F\u0443\u0442\u044C \u0418\u0437\u0432\u043B\u0435\u0447\u044C\u0420\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435 \u0418\u0437\u043C\u0414\u0430\u0442 \u0418\u0437\u043C\u0435\u043D\u0438\u0442\u044C\u0420\u0430\u0437\u043C\u0435\u0440\u041C\u0430\u0441\u0441\u0438\u0432\u0430 \u0418\u0437\u043C\u0435\u0440\u0435\u043D\u0438\u0439\u041C\u0430\u0441\u0441\u0438\u0432\u0430 \u0418\u043C\u044F\u041E\u0440\u0433 \u0418\u043C\u044F\u041F\u043E\u043B\u044F\u0421\u043F\u0440 \u0418\u043D\u0434\u0435\u043A\u0441 \u0418\u043D\u0434\u0438\u043A\u0430\u0442\u043E\u0440\u0417\u0430\u043A\u0440\u044B\u0442\u044C \u0418\u043D\u0434\u0438\u043A\u0430\u0442\u043E\u0440\u041E\u0442\u043A\u0440\u044B\u0442\u044C \u0418\u043D\u0434\u0438\u043A\u0430\u0442\u043E\u0440\u0428\u0430\u0433 \u0418\u043D\u0442\u0435\u0440\u0430\u043A\u0442\u0438\u0432\u043D\u044B\u0439\u0420\u0435\u0436\u0438\u043C \u0418\u0442\u043E\u0433\u0422\u0431\u043B\u0421\u043F\u0440 \u041A\u043E\u0434\u0412\u0438\u0434\u0412\u0435\u0434\u0421\u043F\u0440 \u041A\u043E\u0434\u0412\u0438\u0434\u0421\u043F\u0440\u041F\u043E\u0418\u0414 \u041A\u043E\u0434\u041F\u043EAnalit \u041A\u043E\u0434\u0421\u0438\u043C\u0432\u043E\u043B\u0430 \u041A\u043E\u0434\u0421\u043F\u0440 \u041A\u043E\u043B\u041F\u043E\u0434\u0441\u0442\u0440 \u041A\u043E\u043B\u041F\u0440\u043E\u043F \u041A\u043E\u043D\u041C\u0435\u0441 \u041A\u043E\u043D\u0441\u0442 \u041A\u043E\u043D\u0441\u0442\u0415\u0441\u0442\u044C \u041A\u043E\u043D\u0441\u0442\u0417\u043D\u0430\u0447 \u041A\u043E\u043D\u0422\u0440\u0430\u043D \u041A\u043E\u043F\u0438\u0440\u043E\u0432\u0430\u0442\u044C\u0424\u0430\u0439\u043B \u041A\u043E\u043F\u0438\u044F\u0421\u0442\u0440 \u041A\u041F\u0435\u0440\u0438\u043E\u0434 \u041A\u0421\u0442\u0440\u0422\u0431\u043B\u0421\u043F\u0440 \u041C\u0430\u043A\u0441 \u041C\u0430\u043A\u0441\u0421\u0442\u0440\u0422\u0431\u043B\u0421\u043F\u0440 \u041C\u0430\u0441\u0441\u0438\u0432 \u041C\u0435\u043D\u044E \u041C\u0435\u043D\u044E\u0420\u0430\u0441\u0448 \u041C\u0438\u043D \u041D\u0430\u0431\u043E\u0440\u0414\u0430\u043D\u043D\u044B\u0445\u041D\u0430\u0439\u0442\u0438\u0420\u0430\u0441\u0448 \u041D\u0430\u0438\u043C\u0412\u0438\u0434\u0421\u043F\u0440 \u041D\u0430\u0438\u043C\u041F\u043EAnalit \u041D\u0430\u0438\u043C\u0421\u043F\u0440 \u041D\u0430\u0441\u0442\u0440\u043E\u0438\u0442\u044C\u041F\u0435\u0440\u0435\u0432\u043E\u0434\u044B\u0421\u0442\u0440\u043E\u043A \u041D\u0430\u0447\u041C\u0435\u0441 \u041D\u0430\u0447\u0422\u0440\u0430\u043D \u041D\u0438\u0436\u043D\u044F\u044F\u0413\u0440\u0430\u043D\u0438\u0446\u0430\u041C\u0430\u0441\u0441\u0438\u0432\u0430 \u041D\u043E\u043C\u0435\u0440\u0421\u043F\u0440 \u041D\u041F\u0435\u0440\u0438\u043E\u0434 \u041E\u043A\u043D\u043E \u041E\u043A\u0440 \u041E\u043A\u0440\u0443\u0436\u0435\u043D\u0438\u0435 \u041E\u0442\u043B\u0418\u043D\u0444\u0414\u043E\u0431\u0430\u0432\u0438\u0442\u044C \u041E\u0442\u043B\u0418\u043D\u0444\u0423\u0434\u0430\u043B\u0438\u0442\u044C \u041E\u0442\u0447\u0435\u0442 \u041E\u0442\u0447\u0435\u0442\u0410\u043D\u0430\u043B \u041E\u0442\u0447\u0435\u0442\u0418\u043D\u0442 \u041F\u0430\u043F\u043A\u0430\u0421\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u0435\u0442 \u041F\u0430\u0443\u0437\u0430 \u041F\u0412\u044B\u0431\u043E\u0440SQL \u041F\u0435\u0440\u0435\u0438\u043C\u0435\u043D\u043E\u0432\u0430\u0442\u044C\u0424\u0430\u0439\u043B \u041F\u0435\u0440\u0435\u043C\u0435\u043D\u043D\u044B\u0435 \u041F\u0435\u0440\u0435\u043C\u0435\u0441\u0442\u0438\u0442\u044C\u0424\u0430\u0439\u043B \u041F\u043E\u0434\u0441\u0442\u0440 \u041F\u043E\u0438\u0441\u043A\u041F\u043E\u0434\u0441\u0442\u0440 \u041F\u043E\u0438\u0441\u043A\u0421\u0442\u0440 \u041F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0418\u0414\u0422\u0430\u0431\u043B\u0438\u0446\u044B \u041F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u0414\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u043E \u041F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u0418\u0414 \u041F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u0418\u043C\u044F \u041F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u0421\u0442\u0430\u0442\u0443\u0441 \u041F\u0440\u0435\u0440\u0432\u0430\u0442\u044C \u041F\u0440\u043E\u0432\u0435\u0440\u0438\u0442\u044C\u041F\u0430\u0440\u0430\u043C\u0435\u0442\u0440 \u041F\u0440\u043E\u0432\u0435\u0440\u0438\u0442\u044C\u041F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u0417\u043D\u0430\u0447 \u041F\u0440\u043E\u0432\u0435\u0440\u0438\u0442\u044C\u0423\u0441\u043B\u043E\u0432\u0438\u0435 \u0420\u0430\u0437\u0431\u0421\u0442\u0440 \u0420\u0430\u0437\u043D\u0412\u0440\u0435\u043C\u044F \u0420\u0430\u0437\u043D\u0414\u0430\u0442 \u0420\u0430\u0437\u043D\u0414\u0430\u0442\u0430\u0412\u0440\u0435\u043C\u044F \u0420\u0430\u0437\u043D\u0420\u0430\u0431\u0412\u0440\u0435\u043C\u044F \u0420\u0435\u0433\u0423\u0441\u0442\u0412\u0440\u0435\u043C \u0420\u0435\u0433\u0423\u0441\u0442\u0414\u0430\u0442 \u0420\u0435\u0433\u0423\u0441\u0442\u0427\u0441\u043B \u0420\u0435\u0434\u0422\u0435\u043A\u0441\u0442 \u0420\u0435\u0435\u0441\u0442\u0440\u0417\u0430\u043F\u0438\u0441\u044C \u0420\u0435\u0435\u0441\u0442\u0440\u0421\u043F\u0438\u0441\u043E\u043A\u0418\u043C\u0435\u043D\u041F\u0430\u0440\u0430\u043C \u0420\u0435\u0435\u0441\u0442\u0440\u0427\u0442\u0435\u043D\u0438\u0435 \u0420\u0435\u043A\u0432\u0421\u043F\u0440 \u0420\u0435\u043A\u0432\u0421\u043F\u0440\u041F\u0440 \u0421\u0435\u0433\u043E\u0434\u043D\u044F \u0421\u0435\u0439\u0447\u0430\u0441 \u0421\u0435\u0440\u0432\u0435\u0440 \u0421\u0435\u0440\u0432\u0435\u0440\u041F\u0440\u043E\u0446\u0435\u0441\u0441\u0418\u0414 \u0421\u0435\u0440\u0442\u0438\u0444\u0438\u043A\u0430\u0442\u0424\u0430\u0439\u043B\u0421\u0447\u0438\u0442\u0430\u0442\u044C \u0421\u0436\u041F\u0440\u043E\u0431 \u0421\u0438\u043C\u0432\u043E\u043B \u0421\u0438\u0441\u0442\u0435\u043C\u0430\u0414\u0438\u0440\u0435\u043A\u0442\u0443\u043C\u041A\u043E\u0434 \u0421\u0438\u0441\u0442\u0435\u043C\u0430\u0418\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u044F \u0421\u0438\u0441\u0442\u0435\u043C\u0430\u041A\u043E\u0434 \u0421\u043E\u0434\u0435\u0440\u0436\u0438\u0442 \u0421\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0435\u0417\u0430\u043A\u0440\u044B\u0442\u044C \u0421\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0435\u041E\u0442\u043A\u0440\u044B\u0442\u044C \u0421\u043E\u0437\u0434\u0430\u0442\u044C\u0414\u0438\u0430\u043B\u043E\u0433 \u0421\u043E\u0437\u0434\u0430\u0442\u044C\u0414\u0438\u0430\u043B\u043E\u0433\u0412\u044B\u0431\u043E\u0440\u0430\u0418\u0437\u0414\u0432\u0443\u0445\u0421\u043F\u0438\u0441\u043A\u043E\u0432 \u0421\u043E\u0437\u0434\u0430\u0442\u044C\u0414\u0438\u0430\u043B\u043E\u0433\u0412\u044B\u0431\u043E\u0440\u0430\u041F\u0430\u043F\u043A\u0438 \u0421\u043E\u0437\u0434\u0430\u0442\u044C\u0414\u0438\u0430\u043B\u043E\u0433\u041E\u0442\u043A\u0440\u044B\u0442\u0438\u044F\u0424\u0430\u0439\u043B\u0430 \u0421\u043E\u0437\u0434\u0430\u0442\u044C\u0414\u0438\u0430\u043B\u043E\u0433\u0421\u043E\u0445\u0440\u0430\u043D\u0435\u043D\u0438\u044F\u0424\u0430\u0439\u043B\u0430 \u0421\u043E\u0437\u0434\u0430\u0442\u044C\u0417\u0430\u043F\u0440\u043E\u0441 \u0421\u043E\u0437\u0434\u0430\u0442\u044C\u0418\u043D\u0434\u0438\u043A\u0430\u0442\u043E\u0440 \u0421\u043E\u0437\u0434\u0430\u0442\u044C\u0418\u0441\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u0435 \u0421\u043E\u0437\u0434\u0430\u0442\u044C\u041A\u044D\u0448\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u044B\u0439\u0421\u043F\u0440\u0430\u0432\u043E\u0447\u043D\u0438\u043A \u0421\u043E\u0437\u0434\u0430\u0442\u044C\u041C\u0430\u0441\u0441\u0438\u0432 \u0421\u043E\u0437\u0434\u0430\u0442\u044C\u041D\u0430\u0431\u043E\u0440\u0414\u0430\u043D\u043D\u044B\u0445 \u0421\u043E\u0437\u0434\u0430\u0442\u044C\u041E\u0431\u044A\u0435\u043A\u0442 \u0421\u043E\u0437\u0434\u0430\u0442\u044C\u041E\u0442\u0447\u0435\u0442 \u0421\u043E\u0437\u0434\u0430\u0442\u044C\u041F\u0430\u043F\u043A\u0443 \u0421\u043E\u0437\u0434\u0430\u0442\u044C\u0420\u0435\u0434\u0430\u043A\u0442\u043E\u0440 \u0421\u043E\u0437\u0434\u0430\u0442\u044C\u0421\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0435 \u0421\u043E\u0437\u0434\u0430\u0442\u044C\u0421\u043F\u0438\u0441\u043E\u043A \u0421\u043E\u0437\u0434\u0430\u0442\u044C\u0421\u043F\u0438\u0441\u043E\u043A\u0421\u0442\u0440\u043E\u043A \u0421\u043E\u0437\u0434\u0430\u0442\u044C\u0421\u043F\u0440\u0430\u0432\u043E\u0447\u043D\u0438\u043A \u0421\u043E\u0437\u0434\u0430\u0442\u044C\u0421\u0446\u0435\u043D\u0430\u0440\u0438\u0439 \u0421\u043E\u0437\u0434\u0421\u043F\u0440 \u0421\u043E\u0441\u0442\u0421\u043F\u0440 \u0421\u043E\u0445\u0440 \u0421\u043E\u0445\u0440\u0421\u043F\u0440 \u0421\u043F\u0438\u0441\u043E\u043A\u0421\u0438\u0441\u0442\u0435\u043C \u0421\u043F\u0440 \u0421\u043F\u0440\u0430\u0432\u043E\u0447\u043D\u0438\u043A \u0421\u043F\u0440\u0411\u043B\u043E\u043A\u0415\u0441\u0442\u044C \u0421\u043F\u0440\u0411\u043B\u043E\u043A\u0421\u043D\u044F\u0442\u044C \u0421\u043F\u0440\u0411\u043B\u043E\u043A\u0421\u043D\u044F\u0442\u044C\u0420\u0430\u0441\u0448 \u0421\u043F\u0440\u0411\u043B\u043E\u043A\u0423\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C \u0421\u043F\u0440\u0418\u0437\u043C\u041D\u0430\u0431\u0414\u0430\u043D \u0421\u043F\u0440\u041A\u043E\u0434 \u0421\u043F\u0440\u041D\u043E\u043C\u0435\u0440 \u0421\u043F\u0440\u041E\u0431\u043D\u043E\u0432\u0438\u0442\u044C \u0421\u043F\u0440\u041E\u0442\u043A\u0440\u044B\u0442\u044C \u0421\u043F\u0440\u041E\u0442\u043C\u0435\u043D\u0438\u0442\u044C \u0421\u043F\u0440\u041F\u0430\u0440\u0430\u043C \u0421\u043F\u0440\u041F\u043E\u043B\u0435\u0417\u043D\u0430\u0447 \u0421\u043F\u0440\u041F\u043E\u043B\u0435\u0418\u043C\u044F \u0421\u043F\u0440\u0420\u0435\u043A\u0432 \u0421\u043F\u0440\u0420\u0435\u043A\u0432\u0412\u0432\u0435\u0434\u0417\u043D \u0421\u043F\u0440\u0420\u0435\u043A\u0432\u041D\u043E\u0432\u044B\u0435 \u0421\u043F\u0440\u0420\u0435\u043A\u0432\u041F\u0440 \u0421\u043F\u0440\u0420\u0435\u043A\u0432\u041F\u0440\u0435\u0434\u0417\u043D \u0421\u043F\u0440\u0420\u0435\u043A\u0432\u0420\u0435\u0436\u0438\u043C \u0421\u043F\u0440\u0420\u0435\u043A\u0432\u0422\u0438\u043F\u0422\u0435\u043A\u0441\u0442 \u0421\u043F\u0440\u0421\u043E\u0437\u0434\u0430\u0442\u044C \u0421\u043F\u0440\u0421\u043E\u0441\u0442 \u0421\u043F\u0440\u0421\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u044C \u0421\u043F\u0440\u0422\u0431\u043B\u0418\u0442\u043E\u0433 \u0421\u043F\u0440\u0422\u0431\u043B\u0421\u0442\u0440 \u0421\u043F\u0440\u0422\u0431\u043B\u0421\u0442\u0440\u041A\u043E\u043B \u0421\u043F\u0440\u0422\u0431\u043B\u0421\u0442\u0440\u041C\u0430\u043A\u0441 \u0421\u043F\u0440\u0422\u0431\u043B\u0421\u0442\u0440\u041C\u0438\u043D \u0421\u043F\u0440\u0422\u0431\u043B\u0421\u0442\u0440\u041F\u0440\u0435\u0434 \u0421\u043F\u0440\u0422\u0431\u043B\u0421\u0442\u0440\u0421\u043B\u0435\u0434 \u0421\u043F\u0440\u0422\u0431\u043B\u0421\u0442\u0440\u0421\u043E\u0437\u0434 \u0421\u043F\u0440\u0422\u0431\u043B\u0421\u0442\u0440\u0423\u0434 \u0421\u043F\u0440\u0422\u0435\u043A\u041F\u0440\u0435\u0434\u0441\u0442 \u0421\u043F\u0440\u0423\u0434\u0430\u043B\u0438\u0442\u044C \u0421\u0440\u0430\u0432\u043D\u0438\u0442\u044C\u0421\u0442\u0440 \u0421\u0442\u0440\u0412\u0435\u0440\u0445\u0420\u0435\u0433\u0438\u0441\u0442\u0440 \u0421\u0442\u0440\u041D\u0438\u0436\u043D\u0420\u0435\u0433\u0438\u0441\u0442\u0440 \u0421\u0442\u0440\u0422\u0431\u043B\u0421\u043F\u0440 \u0421\u0443\u043C\u041F\u0440\u043E\u043F \u0421\u0446\u0435\u043D\u0430\u0440\u0438\u0439 \u0421\u0446\u0435\u043D\u0430\u0440\u0438\u0439\u041F\u0430\u0440\u0430\u043C \u0422\u0435\u043A\u0412\u0435\u0440\u0441\u0438\u044F \u0422\u0435\u043A\u041E\u0440\u0433 \u0422\u043E\u0447\u043D \u0422\u0440\u0430\u043D \u0422\u0440\u0430\u043D\u0441\u043B\u0438\u0442\u0435\u0440\u0430\u0446\u0438\u044F \u0423\u0434\u0430\u043B\u0438\u0442\u044C\u0422\u0430\u0431\u043B\u0438\u0446\u0443 \u0423\u0434\u0430\u043B\u0438\u0442\u044C\u0424\u0430\u0439\u043B \u0423\u0434\u0421\u043F\u0440 \u0423\u0434\u0421\u0442\u0440\u0422\u0431\u043B\u0421\u043F\u0440 \u0423\u0441\u0442 \u0423\u0441\u0442\u0430\u043D\u043E\u0432\u043A\u0438\u041A\u043E\u043D\u0441\u0442\u0430\u043D\u0442 \u0424\u0430\u0439\u043B\u0410\u0442\u0440\u0438\u0431\u0443\u0442\u0421\u0447\u0438\u0442\u0430\u0442\u044C \u0424\u0430\u0439\u043B\u0410\u0442\u0440\u0438\u0431\u0443\u0442\u0423\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C \u0424\u0430\u0439\u043B\u0412\u0440\u0435\u043C\u044F \u0424\u0430\u0439\u043B\u0412\u0440\u0435\u043C\u044F\u0423\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C \u0424\u0430\u0439\u043B\u0412\u044B\u0431\u0440\u0430\u0442\u044C \u0424\u0430\u0439\u043B\u0417\u0430\u043D\u044F\u0442 \u0424\u0430\u0439\u043B\u0417\u0430\u043F\u0438\u0441\u0430\u0442\u044C \u0424\u0430\u0439\u043B\u0418\u0441\u043A\u0430\u0442\u044C \u0424\u0430\u0439\u043B\u041A\u043E\u043F\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0424\u0430\u0439\u043B\u041C\u043E\u0436\u043D\u043E\u0427\u0438\u0442\u0430\u0442\u044C \u0424\u0430\u0439\u043B\u041E\u0442\u043A\u0440\u044B\u0442\u044C \u0424\u0430\u0439\u043B\u041F\u0435\u0440\u0435\u0438\u043C\u0435\u043D\u043E\u0432\u0430\u0442\u044C \u0424\u0430\u0439\u043B\u041F\u0435\u0440\u0435\u043A\u043E\u0434\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0424\u0430\u0439\u043B\u041F\u0435\u0440\u0435\u043C\u0435\u0441\u0442\u0438\u0442\u044C \u0424\u0430\u0439\u043B\u041F\u0440\u043E\u0441\u043C\u043E\u0442\u0440\u0435\u0442\u044C \u0424\u0430\u0439\u043B\u0420\u0430\u0437\u043C\u0435\u0440 \u0424\u0430\u0439\u043B\u0421\u043E\u0437\u0434\u0430\u0442\u044C \u0424\u0430\u0439\u043B\u0421\u0441\u044B\u043B\u043A\u0430\u0421\u043E\u0437\u0434\u0430\u0442\u044C \u0424\u0430\u0439\u043B\u0421\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u0435\u0442 \u0424\u0430\u0439\u043B\u0421\u0447\u0438\u0442\u0430\u0442\u044C \u0424\u0430\u0439\u043B\u0423\u0434\u0430\u043B\u0438\u0442\u044C \u0424\u043C\u0442SQL\u0414\u0430\u0442 \u0424\u043C\u0442\u0414\u0430\u0442 \u0424\u043C\u0442\u0421\u0442\u0440 \u0424\u043C\u0442\u0427\u0441\u043B \u0424\u043E\u0440\u043C\u0430\u0442 \u0426\u041C\u0430\u0441\u0441\u0438\u0432\u042D\u043B\u0435\u043C\u0435\u043D\u0442 \u0426\u041D\u0430\u0431\u043E\u0440\u0414\u0430\u043D\u043D\u044B\u0445\u0420\u0435\u043A\u0432\u0438\u0437\u0438\u0442 \u0426\u041F\u043E\u0434\u0441\u0442\u0440 ";
      const predefined_variables = "AltState Application CallType ComponentTokens CreatedJobs CreatedNotices ControlState DialogResult Dialogs EDocuments EDocumentVersionSource Folders GlobalIDs Job Jobs InputValue LookUpReference LookUpRequisiteNames LookUpSearch Object ParentComponent Processes References Requisite ReportName Reports Result Scripts Searches SelectedAttachments SelectedItems SelectMode Sender ServerEvents ServiceFactory ShiftState SubTask SystemDialogs Tasks Wizard Wizards Work \u0412\u044B\u0437\u043E\u0432\u0421\u043F\u043E\u0441\u043E\u0431 \u0418\u043C\u044F\u041E\u0442\u0447\u0435\u0442\u0430 \u0420\u0435\u043A\u0432\u0417\u043D\u0430\u0447 ";
      const interfaces = "IApplication IAccessRights IAccountRepository IAccountSelectionRestrictions IAction IActionList IAdministrationHistoryDescription IAnchors IApplication IArchiveInfo IAttachment IAttachmentList ICheckListBox ICheckPointedList IColumn IComponent IComponentDescription IComponentToken IComponentTokenFactory IComponentTokenInfo ICompRecordInfo IConnection IContents IControl IControlJob IControlJobInfo IControlList ICrypto ICrypto2 ICustomJob ICustomJobInfo ICustomListBox ICustomObjectWizardStep ICustomWork ICustomWorkInfo IDataSet IDataSetAccessInfo IDataSigner IDateCriterion IDateRequisite IDateRequisiteDescription IDateValue IDeaAccessRights IDeaObjectInfo IDevelopmentComponentLock IDialog IDialogFactory IDialogPickRequisiteItems IDialogsFactory IDICSFactory IDocRequisite IDocumentInfo IDualListDialog IECertificate IECertificateInfo IECertificates IEditControl IEditorForm IEdmsExplorer IEdmsObject IEdmsObjectDescription IEdmsObjectFactory IEdmsObjectInfo IEDocument IEDocumentAccessRights IEDocumentDescription IEDocumentEditor IEDocumentFactory IEDocumentInfo IEDocumentStorage IEDocumentVersion IEDocumentVersionListDialog IEDocumentVersionSource IEDocumentWizardStep IEDocVerSignature IEDocVersionState IEnabledMode IEncodeProvider IEncrypter IEvent IEventList IException IExternalEvents IExternalHandler IFactory IField IFileDialog IFolder IFolderDescription IFolderDialog IFolderFactory IFolderInfo IForEach IForm IFormTitle IFormWizardStep IGlobalIDFactory IGlobalIDInfo IGrid IHasher IHistoryDescription IHyperLinkControl IImageButton IImageControl IInnerPanel IInplaceHint IIntegerCriterion IIntegerList IIntegerRequisite IIntegerValue IISBLEditorForm IJob IJobDescription IJobFactory IJobForm IJobInfo ILabelControl ILargeIntegerCriterion ILargeIntegerRequisite ILargeIntegerValue ILicenseInfo ILifeCycleStage IList IListBox ILocalIDInfo ILocalization ILock IMemoryDataSet IMessagingFactory IMetadataRepository INotice INoticeInfo INumericCriterion INumericRequisite INumericValue IObject IObjectDescription IObjectImporter IObjectInfo IObserver IPanelGroup IPickCriterion IPickProperty IPickRequisite IPickRequisiteDescription IPickRequisiteItem IPickRequisiteItems IPickValue IPrivilege IPrivilegeList IProcess IProcessFactory IProcessMessage IProgress IProperty IPropertyChangeEvent IQuery IReference IReferenceCriterion IReferenceEnabledMode IReferenceFactory IReferenceHistoryDescription IReferenceInfo IReferenceRecordCardWizardStep IReferenceRequisiteDescription IReferencesFactory IReferenceValue IRefRequisite IReport IReportFactory IRequisite IRequisiteDescription IRequisiteDescriptionList IRequisiteFactory IRichEdit IRouteStep IRule IRuleList ISchemeBlock IScript IScriptFactory ISearchCriteria ISearchCriterion ISearchDescription ISearchFactory ISearchFolderInfo ISearchForObjectDescription ISearchResultRestrictions ISecuredContext ISelectDialog IServerEvent IServerEventFactory IServiceDialog IServiceFactory ISignature ISignProvider ISignProvider2 ISignProvider3 ISimpleCriterion IStringCriterion IStringList IStringRequisite IStringRequisiteDescription IStringValue ISystemDialogsFactory ISystemInfo ITabSheet ITask ITaskAbortReasonInfo ITaskCardWizardStep ITaskDescription ITaskFactory ITaskInfo ITaskRoute ITextCriterion ITextRequisite ITextValue ITreeListSelectDialog IUser IUserList IValue IView IWebBrowserControl IWizard IWizardAction IWizardFactory IWizardFormElement IWizardParam IWizardPickParam IWizardReferenceParam IWizardStep IWorkAccessRights IWorkDescription IWorkflowAskableParam IWorkflowAskableParams IWorkflowBlock IWorkflowBlockResult IWorkflowEnabledMode IWorkflowParam IWorkflowPickParam IWorkflowReferenceParam IWorkState IWorkTreeCustomNode IWorkTreeJobNode IWorkTreeTaskNode IXMLEditorForm SBCrypto ";
      const BUILTIN = CONSTANTS + ENUMS;
      const CLASS = predefined_variables;
      const LITERAL = "null true false nil ";
      const NUMBERS = {
        className: "number",
        begin: hljs5.NUMBER_RE,
        relevance: 0
      };
      const STRINGS = {
        className: "string",
        variants: [
          {
            begin: '"',
            end: '"'
          },
          {
            begin: "'",
            end: "'"
          }
        ]
      };
      const DOCTAGS = {
        className: "doctag",
        begin: "\\b(?:TODO|DONE|BEGIN|END|STUB|CHG|FIXME|NOTE|BUG|XXX)\\b",
        relevance: 0
      };
      const ISBL_LINE_COMMENT_MODE = {
        className: "comment",
        begin: "//",
        end: "$",
        relevance: 0,
        contains: [
          hljs5.PHRASAL_WORDS_MODE,
          DOCTAGS
        ]
      };
      const ISBL_BLOCK_COMMENT_MODE = {
        className: "comment",
        begin: "/\\*",
        end: "\\*/",
        relevance: 0,
        contains: [
          hljs5.PHRASAL_WORDS_MODE,
          DOCTAGS
        ]
      };
      const COMMENTS = {
        variants: [
          ISBL_LINE_COMMENT_MODE,
          ISBL_BLOCK_COMMENT_MODE
        ]
      };
      const KEYWORDS3 = {
        $pattern: UNDERSCORE_IDENT_RE,
        keyword: KEYWORD,
        built_in: BUILTIN,
        class: CLASS,
        literal: LITERAL
      };
      const METHODS = {
        begin: "\\.\\s*" + hljs5.UNDERSCORE_IDENT_RE,
        keywords: KEYWORDS3,
        relevance: 0
      };
      const TYPES3 = {
        className: "type",
        begin: ":[ \\t]*(" + interfaces.trim().replace(/\s/g, "|") + ")",
        end: "[ \\t]*=",
        excludeEnd: true
      };
      const VARIABLES = {
        className: "variable",
        keywords: KEYWORDS3,
        begin: UNDERSCORE_IDENT_RE,
        relevance: 0,
        contains: [
          TYPES3,
          METHODS
        ]
      };
      const FUNCTION_TITLE = FUNCTION_NAME_IDENT_RE + "\\(";
      const TITLE_MODE = {
        className: "title",
        keywords: {
          $pattern: UNDERSCORE_IDENT_RE,
          built_in: system_functions
        },
        begin: FUNCTION_TITLE,
        end: "\\(",
        returnBegin: true,
        excludeEnd: true
      };
      const FUNCTIONS = {
        className: "function",
        begin: FUNCTION_TITLE,
        end: "\\)$",
        returnBegin: true,
        keywords: KEYWORDS3,
        illegal: "[\\[\\]\\|\\$\\?%,~#@]",
        contains: [
          TITLE_MODE,
          METHODS,
          VARIABLES,
          STRINGS,
          NUMBERS,
          COMMENTS
        ]
      };
      return {
        name: "ISBL",
        case_insensitive: true,
        keywords: KEYWORDS3,
        illegal: "\\$|\\?|%|,|;$|~|#|@|</",
        contains: [
          FUNCTIONS,
          TYPES3,
          METHODS,
          VARIABLES,
          STRINGS,
          NUMBERS,
          COMMENTS
        ]
      };
    }
    module.exports = isbl;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/java.js
var require_java = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/java.js"(exports, module) {
    init_process_shim();
    var decimalDigits = "[0-9](_*[0-9])*";
    var frac = `\\.(${decimalDigits})`;
    var hexDigits = "[0-9a-fA-F](_*[0-9a-fA-F])*";
    var NUMERIC = {
      className: "number",
      variants: [
        // DecimalFloatingPointLiteral
        // including ExponentPart
        { begin: `(\\b(${decimalDigits})((${frac})|\\.)?|(${frac}))[eE][+-]?(${decimalDigits})[fFdD]?\\b` },
        // excluding ExponentPart
        { begin: `\\b(${decimalDigits})((${frac})[fFdD]?\\b|\\.([fFdD]\\b)?)` },
        { begin: `(${frac})[fFdD]?\\b` },
        { begin: `\\b(${decimalDigits})[fFdD]\\b` },
        // HexadecimalFloatingPointLiteral
        { begin: `\\b0[xX]((${hexDigits})\\.?|(${hexDigits})?\\.(${hexDigits}))[pP][+-]?(${decimalDigits})[fFdD]?\\b` },
        // DecimalIntegerLiteral
        { begin: "\\b(0|[1-9](_*[0-9])*)[lL]?\\b" },
        // HexIntegerLiteral
        { begin: `\\b0[xX](${hexDigits})[lL]?\\b` },
        // OctalIntegerLiteral
        { begin: "\\b0(_*[0-7])*[lL]?\\b" },
        // BinaryIntegerLiteral
        { begin: "\\b0[bB][01](_*[01])*[lL]?\\b" }
      ],
      relevance: 0
    };
    function java(hljs5) {
      var JAVA_IDENT_RE = "[\xC0-\u02B8a-zA-Z_$][\xC0-\u02B8a-zA-Z_$0-9]*";
      var GENERIC_IDENT_RE = JAVA_IDENT_RE + "(<" + JAVA_IDENT_RE + "(\\s*,\\s*" + JAVA_IDENT_RE + ")*>)?";
      var KEYWORDS3 = "false synchronized int abstract float private char boolean var static null if const for true while long strictfp finally protected import native final void enum else break transient catch instanceof byte super volatile case assert short package default double public try this switch continue throws protected public private module requires exports do";
      var ANNOTATION = {
        className: "meta",
        begin: "@" + JAVA_IDENT_RE,
        contains: [
          {
            begin: /\(/,
            end: /\)/,
            contains: ["self"]
            // allow nested () inside our annotation
          }
        ]
      };
      const NUMBER = NUMERIC;
      return {
        name: "Java",
        aliases: ["jsp"],
        keywords: KEYWORDS3,
        illegal: /<\/|#/,
        contains: [
          hljs5.COMMENT(
            "/\\*\\*",
            "\\*/",
            {
              relevance: 0,
              contains: [
                {
                  // eat up @'s in emails to prevent them to be recognized as doctags
                  begin: /\w+@/,
                  relevance: 0
                },
                {
                  className: "doctag",
                  begin: "@[A-Za-z]+"
                }
              ]
            }
          ),
          // relevance boost
          {
            begin: /import java\.[a-z]+\./,
            keywords: "import",
            relevance: 2
          },
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          hljs5.APOS_STRING_MODE,
          hljs5.QUOTE_STRING_MODE,
          {
            className: "class",
            beginKeywords: "class interface enum",
            end: /[{;=]/,
            excludeEnd: true,
            // TODO: can this be removed somehow?
            // an extra boost because Java is more popular than other languages with
            // this same syntax feature (this is just to preserve our tests passing
            // for now)
            relevance: 1,
            keywords: "class interface enum",
            illegal: /[:"\[\]]/,
            contains: [
              { beginKeywords: "extends implements" },
              hljs5.UNDERSCORE_TITLE_MODE
            ]
          },
          {
            // Expression keywords prevent 'keyword Name(...)' from being
            // recognized as a function definition
            beginKeywords: "new throw return else",
            relevance: 0
          },
          {
            className: "class",
            begin: "record\\s+" + hljs5.UNDERSCORE_IDENT_RE + "\\s*\\(",
            returnBegin: true,
            excludeEnd: true,
            end: /[{;=]/,
            keywords: KEYWORDS3,
            contains: [
              { beginKeywords: "record" },
              {
                begin: hljs5.UNDERSCORE_IDENT_RE + "\\s*\\(",
                returnBegin: true,
                relevance: 0,
                contains: [hljs5.UNDERSCORE_TITLE_MODE]
              },
              {
                className: "params",
                begin: /\(/,
                end: /\)/,
                keywords: KEYWORDS3,
                relevance: 0,
                contains: [
                  hljs5.C_BLOCK_COMMENT_MODE
                ]
              },
              hljs5.C_LINE_COMMENT_MODE,
              hljs5.C_BLOCK_COMMENT_MODE
            ]
          },
          {
            className: "function",
            begin: "(" + GENERIC_IDENT_RE + "\\s+)+" + hljs5.UNDERSCORE_IDENT_RE + "\\s*\\(",
            returnBegin: true,
            end: /[{;=]/,
            excludeEnd: true,
            keywords: KEYWORDS3,
            contains: [
              {
                begin: hljs5.UNDERSCORE_IDENT_RE + "\\s*\\(",
                returnBegin: true,
                relevance: 0,
                contains: [hljs5.UNDERSCORE_TITLE_MODE]
              },
              {
                className: "params",
                begin: /\(/,
                end: /\)/,
                keywords: KEYWORDS3,
                relevance: 0,
                contains: [
                  ANNOTATION,
                  hljs5.APOS_STRING_MODE,
                  hljs5.QUOTE_STRING_MODE,
                  NUMBER,
                  hljs5.C_BLOCK_COMMENT_MODE
                ]
              },
              hljs5.C_LINE_COMMENT_MODE,
              hljs5.C_BLOCK_COMMENT_MODE
            ]
          },
          NUMBER,
          ANNOTATION
        ]
      };
    }
    module.exports = java;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/javascript.js
var require_javascript = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/javascript.js"(exports, module) {
    init_process_shim();
    var IDENT_RE3 = "[A-Za-z$_][0-9A-Za-z$_]*";
    var KEYWORDS3 = [
      "as",
      // for exports
      "in",
      "of",
      "if",
      "for",
      "while",
      "finally",
      "var",
      "new",
      "function",
      "do",
      "return",
      "void",
      "else",
      "break",
      "catch",
      "instanceof",
      "with",
      "throw",
      "case",
      "default",
      "try",
      "switch",
      "continue",
      "typeof",
      "delete",
      "let",
      "yield",
      "const",
      "class",
      // JS handles these with a special rule
      // "get",
      // "set",
      "debugger",
      "async",
      "await",
      "static",
      "import",
      "from",
      "export",
      "extends"
    ];
    var LITERALS3 = [
      "true",
      "false",
      "null",
      "undefined",
      "NaN",
      "Infinity"
    ];
    var TYPES3 = [
      "Intl",
      "DataView",
      "Number",
      "Math",
      "Date",
      "String",
      "RegExp",
      "Object",
      "Function",
      "Boolean",
      "Error",
      "Symbol",
      "Set",
      "Map",
      "WeakSet",
      "WeakMap",
      "Proxy",
      "Reflect",
      "JSON",
      "Promise",
      "Float64Array",
      "Int16Array",
      "Int32Array",
      "Int8Array",
      "Uint16Array",
      "Uint32Array",
      "Float32Array",
      "Array",
      "Uint8Array",
      "Uint8ClampedArray",
      "ArrayBuffer",
      "BigInt64Array",
      "BigUint64Array",
      "BigInt"
    ];
    var ERROR_TYPES3 = [
      "EvalError",
      "InternalError",
      "RangeError",
      "ReferenceError",
      "SyntaxError",
      "TypeError",
      "URIError"
    ];
    var BUILT_IN_GLOBALS3 = [
      "setInterval",
      "setTimeout",
      "clearInterval",
      "clearTimeout",
      "require",
      "exports",
      "eval",
      "isFinite",
      "isNaN",
      "parseFloat",
      "parseInt",
      "decodeURI",
      "decodeURIComponent",
      "encodeURI",
      "encodeURIComponent",
      "escape",
      "unescape"
    ];
    var BUILT_IN_VARIABLES3 = [
      "arguments",
      "this",
      "super",
      "console",
      "window",
      "document",
      "localStorage",
      "module",
      "global"
      // Node.js
    ];
    var BUILT_INS3 = [].concat(
      BUILT_IN_GLOBALS3,
      BUILT_IN_VARIABLES3,
      TYPES3,
      ERROR_TYPES3
    );
    function source(re2) {
      if (!re2) return null;
      if (typeof re2 === "string") return re2;
      return re2.source;
    }
    function lookahead(re2) {
      return concat("(?=", re2, ")");
    }
    function concat(...args) {
      const joined = args.map((x2) => source(x2)).join("");
      return joined;
    }
    function javascript3(hljs5) {
      const hasClosingTag = (match2, { after }) => {
        const tag = "</" + match2[0].slice(1);
        const pos = match2.input.indexOf(tag, after);
        return pos !== -1;
      };
      const IDENT_RE$1 = IDENT_RE3;
      const FRAGMENT = {
        begin: "<>",
        end: "</>"
      };
      const XML_TAG = {
        begin: /<[A-Za-z0-9\\._:-]+/,
        end: /\/[A-Za-z0-9\\._:-]+>|\/>/,
        /**
         * @param {RegExpMatchArray} match
         * @param {CallbackResponse} response
         */
        isTrulyOpeningTag: (match2, response) => {
          const afterMatchIndex = match2[0].length + match2.index;
          const nextChar = match2.input[afterMatchIndex];
          if (nextChar === "<") {
            response.ignoreMatch();
            return;
          }
          if (nextChar === ">") {
            if (!hasClosingTag(match2, { after: afterMatchIndex })) {
              response.ignoreMatch();
            }
          }
        }
      };
      const KEYWORDS$1 = {
        $pattern: IDENT_RE3,
        keyword: KEYWORDS3,
        literal: LITERALS3,
        built_in: BUILT_INS3
      };
      const decimalDigits = "[0-9](_?[0-9])*";
      const frac = `\\.(${decimalDigits})`;
      const decimalInteger = `0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*`;
      const NUMBER = {
        className: "number",
        variants: [
          // DecimalLiteral
          { begin: `(\\b(${decimalInteger})((${frac})|\\.)?|(${frac}))[eE][+-]?(${decimalDigits})\\b` },
          { begin: `\\b(${decimalInteger})\\b((${frac})\\b|\\.)?|(${frac})\\b` },
          // DecimalBigIntegerLiteral
          { begin: `\\b(0|[1-9](_?[0-9])*)n\\b` },
          // NonDecimalIntegerLiteral
          { begin: "\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b" },
          { begin: "\\b0[bB][0-1](_?[0-1])*n?\\b" },
          { begin: "\\b0[oO][0-7](_?[0-7])*n?\\b" },
          // LegacyOctalIntegerLiteral (does not include underscore separators)
          // https://tc39.es/ecma262/#sec-additional-syntax-numeric-literals
          { begin: "\\b0[0-7]+n?\\b" }
        ],
        relevance: 0
      };
      const SUBST = {
        className: "subst",
        begin: "\\$\\{",
        end: "\\}",
        keywords: KEYWORDS$1,
        contains: []
        // defined later
      };
      const HTML_TEMPLATE = {
        begin: "html`",
        end: "",
        starts: {
          end: "`",
          returnEnd: false,
          contains: [
            hljs5.BACKSLASH_ESCAPE,
            SUBST
          ],
          subLanguage: "xml"
        }
      };
      const CSS_TEMPLATE = {
        begin: "css`",
        end: "",
        starts: {
          end: "`",
          returnEnd: false,
          contains: [
            hljs5.BACKSLASH_ESCAPE,
            SUBST
          ],
          subLanguage: "css"
        }
      };
      const TEMPLATE_STRING = {
        className: "string",
        begin: "`",
        end: "`",
        contains: [
          hljs5.BACKSLASH_ESCAPE,
          SUBST
        ]
      };
      const JSDOC_COMMENT = hljs5.COMMENT(
        /\/\*\*(?!\/)/,
        "\\*/",
        {
          relevance: 0,
          contains: [
            {
              className: "doctag",
              begin: "@[A-Za-z]+",
              contains: [
                {
                  className: "type",
                  begin: "\\{",
                  end: "\\}",
                  relevance: 0
                },
                {
                  className: "variable",
                  begin: IDENT_RE$1 + "(?=\\s*(-)|$)",
                  endsParent: true,
                  relevance: 0
                },
                // eat spaces (not newlines) so we can find
                // types or variables
                {
                  begin: /(?=[^\n])\s/,
                  relevance: 0
                }
              ]
            }
          ]
        }
      );
      const COMMENT = {
        className: "comment",
        variants: [
          JSDOC_COMMENT,
          hljs5.C_BLOCK_COMMENT_MODE,
          hljs5.C_LINE_COMMENT_MODE
        ]
      };
      const SUBST_INTERNALS = [
        hljs5.APOS_STRING_MODE,
        hljs5.QUOTE_STRING_MODE,
        HTML_TEMPLATE,
        CSS_TEMPLATE,
        TEMPLATE_STRING,
        NUMBER,
        hljs5.REGEXP_MODE
      ];
      SUBST.contains = SUBST_INTERNALS.concat({
        // we need to pair up {} inside our subst to prevent
        // it from ending too early by matching another }
        begin: /\{/,
        end: /\}/,
        keywords: KEYWORDS$1,
        contains: [
          "self"
        ].concat(SUBST_INTERNALS)
      });
      const SUBST_AND_COMMENTS = [].concat(COMMENT, SUBST.contains);
      const PARAMS_CONTAINS = SUBST_AND_COMMENTS.concat([
        // eat recursive parens in sub expressions
        {
          begin: /\(/,
          end: /\)/,
          keywords: KEYWORDS$1,
          contains: ["self"].concat(SUBST_AND_COMMENTS)
        }
      ]);
      const PARAMS = {
        className: "params",
        begin: /\(/,
        end: /\)/,
        excludeBegin: true,
        excludeEnd: true,
        keywords: KEYWORDS$1,
        contains: PARAMS_CONTAINS
      };
      return {
        name: "Javascript",
        aliases: ["js", "jsx", "mjs", "cjs"],
        keywords: KEYWORDS$1,
        // this will be extended by TypeScript
        exports: { PARAMS_CONTAINS },
        illegal: /#(?![$_A-z])/,
        contains: [
          hljs5.SHEBANG({
            label: "shebang",
            binary: "node",
            relevance: 5
          }),
          {
            label: "use_strict",
            className: "meta",
            relevance: 10,
            begin: /^\s*['"]use (strict|asm)['"]/
          },
          hljs5.APOS_STRING_MODE,
          hljs5.QUOTE_STRING_MODE,
          HTML_TEMPLATE,
          CSS_TEMPLATE,
          TEMPLATE_STRING,
          COMMENT,
          NUMBER,
          {
            // object attr container
            begin: concat(
              /[{,\n]\s*/,
              // we need to look ahead to make sure that we actually have an
              // attribute coming up so we don't steal a comma from a potential
              // "value" container
              //
              // NOTE: this might not work how you think.  We don't actually always
              // enter this mode and stay.  Instead it might merely match `,
              // <comments up next>` and then immediately end after the , because it
              // fails to find any actual attrs. But this still does the job because
              // it prevents the value contain rule from grabbing this instead and
              // prevening this rule from firing when we actually DO have keys.
              lookahead(concat(
                // we also need to allow for multiple possible comments inbetween
                // the first key:value pairing
                /(((\/\/.*$)|(\/\*(\*[^/]|[^*])*\*\/))\s*)*/,
                IDENT_RE$1 + "\\s*:"
              ))
            ),
            relevance: 0,
            contains: [
              {
                className: "attr",
                begin: IDENT_RE$1 + lookahead("\\s*:"),
                relevance: 0
              }
            ]
          },
          {
            // "value" container
            begin: "(" + hljs5.RE_STARTERS_RE + "|\\b(case|return|throw)\\b)\\s*",
            keywords: "return throw case",
            contains: [
              COMMENT,
              hljs5.REGEXP_MODE,
              {
                className: "function",
                // we have to count the parens to make sure we actually have the
                // correct bounding ( ) before the =>.  There could be any number of
                // sub-expressions inside also surrounded by parens.
                begin: "(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|" + hljs5.UNDERSCORE_IDENT_RE + ")\\s*=>",
                returnBegin: true,
                end: "\\s*=>",
                contains: [
                  {
                    className: "params",
                    variants: [
                      {
                        begin: hljs5.UNDERSCORE_IDENT_RE,
                        relevance: 0
                      },
                      {
                        className: null,
                        begin: /\(\s*\)/,
                        skip: true
                      },
                      {
                        begin: /\(/,
                        end: /\)/,
                        excludeBegin: true,
                        excludeEnd: true,
                        keywords: KEYWORDS$1,
                        contains: PARAMS_CONTAINS
                      }
                    ]
                  }
                ]
              },
              {
                // could be a comma delimited list of params to a function call
                begin: /,/,
                relevance: 0
              },
              {
                className: "",
                begin: /\s/,
                end: /\s*/,
                skip: true
              },
              {
                // JSX
                variants: [
                  { begin: FRAGMENT.begin, end: FRAGMENT.end },
                  {
                    begin: XML_TAG.begin,
                    // we carefully check the opening tag to see if it truly
                    // is a tag and not a false positive
                    "on:begin": XML_TAG.isTrulyOpeningTag,
                    end: XML_TAG.end
                  }
                ],
                subLanguage: "xml",
                contains: [
                  {
                    begin: XML_TAG.begin,
                    end: XML_TAG.end,
                    skip: true,
                    contains: ["self"]
                  }
                ]
              }
            ],
            relevance: 0
          },
          {
            className: "function",
            beginKeywords: "function",
            end: /[{;]/,
            excludeEnd: true,
            keywords: KEYWORDS$1,
            contains: [
              "self",
              hljs5.inherit(hljs5.TITLE_MODE, { begin: IDENT_RE$1 }),
              PARAMS
            ],
            illegal: /%/
          },
          {
            // prevent this from getting swallowed up by function
            // since they appear "function like"
            beginKeywords: "while if switch catch for"
          },
          {
            className: "function",
            // we have to count the parens to make sure we actually have the correct
            // bounding ( ).  There could be any number of sub-expressions inside
            // also surrounded by parens.
            begin: hljs5.UNDERSCORE_IDENT_RE + "\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",
            // end parens
            returnBegin: true,
            contains: [
              PARAMS,
              hljs5.inherit(hljs5.TITLE_MODE, { begin: IDENT_RE$1 })
            ]
          },
          // hack: prevents detection of keywords in some circumstances
          // .keyword()
          // $keyword = x
          {
            variants: [
              { begin: "\\." + IDENT_RE$1 },
              { begin: "\\$" + IDENT_RE$1 }
            ],
            relevance: 0
          },
          {
            // ES6 class
            className: "class",
            beginKeywords: "class",
            end: /[{;=]/,
            excludeEnd: true,
            illegal: /[:"[\]]/,
            contains: [
              { beginKeywords: "extends" },
              hljs5.UNDERSCORE_TITLE_MODE
            ]
          },
          {
            begin: /\b(?=constructor)/,
            end: /[{;]/,
            excludeEnd: true,
            contains: [
              hljs5.inherit(hljs5.TITLE_MODE, { begin: IDENT_RE$1 }),
              "self",
              PARAMS
            ]
          },
          {
            begin: "(get|set)\\s+(?=" + IDENT_RE$1 + "\\()",
            end: /\{/,
            keywords: "get set",
            contains: [
              hljs5.inherit(hljs5.TITLE_MODE, { begin: IDENT_RE$1 }),
              { begin: /\(\)/ },
              // eat to avoid empty params
              PARAMS
            ]
          },
          {
            begin: /\$[(.]/
            // relevance booster for a pattern common to JS libs: `$(something)` and `$.something`
          }
        ]
      };
    }
    module.exports = javascript3;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/jboss-cli.js
var require_jboss_cli = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/jboss-cli.js"(exports, module) {
    init_process_shim();
    function jbossCli(hljs5) {
      const PARAM = {
        begin: /[\w-]+ *=/,
        returnBegin: true,
        relevance: 0,
        contains: [
          {
            className: "attr",
            begin: /[\w-]+/
          }
        ]
      };
      const PARAMSBLOCK = {
        className: "params",
        begin: /\(/,
        end: /\)/,
        contains: [PARAM],
        relevance: 0
      };
      const OPERATION = {
        className: "function",
        begin: /:[\w\-.]+/,
        relevance: 0
      };
      const PATH = {
        className: "string",
        begin: /\B([\/.])[\w\-.\/=]+/
      };
      const COMMAND_PARAMS = {
        className: "params",
        begin: /--[\w\-=\/]+/
      };
      return {
        name: "JBoss CLI",
        aliases: ["wildfly-cli"],
        keywords: {
          $pattern: "[a-z-]+",
          keyword: "alias batch cd clear command connect connection-factory connection-info data-source deploy deployment-info deployment-overlay echo echo-dmr help history if jdbc-driver-info jms-queue|20 jms-topic|20 ls patch pwd quit read-attribute read-operation reload rollout-plan run-batch set shutdown try unalias undeploy unset version xa-data-source",
          // module
          literal: "true false"
        },
        contains: [
          hljs5.HASH_COMMENT_MODE,
          hljs5.QUOTE_STRING_MODE,
          COMMAND_PARAMS,
          OPERATION,
          PATH,
          PARAMSBLOCK
        ]
      };
    }
    module.exports = jbossCli;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/json.js
var require_json = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/json.js"(exports, module) {
    init_process_shim();
    function json2(hljs5) {
      const LITERALS3 = {
        literal: "true false null"
      };
      const ALLOWED_COMMENTS = [
        hljs5.C_LINE_COMMENT_MODE,
        hljs5.C_BLOCK_COMMENT_MODE
      ];
      const TYPES3 = [
        hljs5.QUOTE_STRING_MODE,
        hljs5.C_NUMBER_MODE
      ];
      const VALUE_CONTAINER = {
        end: ",",
        endsWithParent: true,
        excludeEnd: true,
        contains: TYPES3,
        keywords: LITERALS3
      };
      const OBJECT = {
        begin: /\{/,
        end: /\}/,
        contains: [
          {
            className: "attr",
            begin: /"/,
            end: /"/,
            contains: [hljs5.BACKSLASH_ESCAPE],
            illegal: "\\n"
          },
          hljs5.inherit(VALUE_CONTAINER, {
            begin: /:/
          })
        ].concat(ALLOWED_COMMENTS),
        illegal: "\\S"
      };
      const ARRAY = {
        begin: "\\[",
        end: "\\]",
        contains: [hljs5.inherit(VALUE_CONTAINER)],
        // inherit is a workaround for a bug that makes shared modes with endsWithParent compile only the ending of one of the parents
        illegal: "\\S"
      };
      TYPES3.push(OBJECT, ARRAY);
      ALLOWED_COMMENTS.forEach(function(rule) {
        TYPES3.push(rule);
      });
      return {
        name: "JSON",
        contains: TYPES3,
        keywords: LITERALS3,
        illegal: "\\S"
      };
    }
    module.exports = json2;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/julia.js
var require_julia = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/julia.js"(exports, module) {
    init_process_shim();
    function julia(hljs5) {
      var VARIABLE_NAME_RE = "[A-Za-z_\\u00A1-\\uFFFF][A-Za-z_0-9\\u00A1-\\uFFFF]*";
      var KEYWORD_LIST = [
        "baremodule",
        "begin",
        "break",
        "catch",
        "ccall",
        "const",
        "continue",
        "do",
        "else",
        "elseif",
        "end",
        "export",
        "false",
        "finally",
        "for",
        "function",
        "global",
        "if",
        "import",
        "in",
        "isa",
        "let",
        "local",
        "macro",
        "module",
        "quote",
        "return",
        "true",
        "try",
        "using",
        "where",
        "while"
      ];
      var LITERAL_LIST = [
        "ARGS",
        "C_NULL",
        "DEPOT_PATH",
        "ENDIAN_BOM",
        "ENV",
        "Inf",
        "Inf16",
        "Inf32",
        "Inf64",
        "InsertionSort",
        "LOAD_PATH",
        "MergeSort",
        "NaN",
        "NaN16",
        "NaN32",
        "NaN64",
        "PROGRAM_FILE",
        "QuickSort",
        "RoundDown",
        "RoundFromZero",
        "RoundNearest",
        "RoundNearestTiesAway",
        "RoundNearestTiesUp",
        "RoundToZero",
        "RoundUp",
        "VERSION|0",
        "devnull",
        "false",
        "im",
        "missing",
        "nothing",
        "pi",
        "stderr",
        "stdin",
        "stdout",
        "true",
        "undef",
        "\u03C0",
        "\u212F"
      ];
      var BUILT_IN_LIST = [
        "AbstractArray",
        "AbstractChannel",
        "AbstractChar",
        "AbstractDict",
        "AbstractDisplay",
        "AbstractFloat",
        "AbstractIrrational",
        "AbstractMatrix",
        "AbstractRange",
        "AbstractSet",
        "AbstractString",
        "AbstractUnitRange",
        "AbstractVecOrMat",
        "AbstractVector",
        "Any",
        "ArgumentError",
        "Array",
        "AssertionError",
        "BigFloat",
        "BigInt",
        "BitArray",
        "BitMatrix",
        "BitSet",
        "BitVector",
        "Bool",
        "BoundsError",
        "CapturedException",
        "CartesianIndex",
        "CartesianIndices",
        "Cchar",
        "Cdouble",
        "Cfloat",
        "Channel",
        "Char",
        "Cint",
        "Cintmax_t",
        "Clong",
        "Clonglong",
        "Cmd",
        "Colon",
        "Complex",
        "ComplexF16",
        "ComplexF32",
        "ComplexF64",
        "CompositeException",
        "Condition",
        "Cptrdiff_t",
        "Cshort",
        "Csize_t",
        "Cssize_t",
        "Cstring",
        "Cuchar",
        "Cuint",
        "Cuintmax_t",
        "Culong",
        "Culonglong",
        "Cushort",
        "Cvoid",
        "Cwchar_t",
        "Cwstring",
        "DataType",
        "DenseArray",
        "DenseMatrix",
        "DenseVecOrMat",
        "DenseVector",
        "Dict",
        "DimensionMismatch",
        "Dims",
        "DivideError",
        "DomainError",
        "EOFError",
        "Enum",
        "ErrorException",
        "Exception",
        "ExponentialBackOff",
        "Expr",
        "Float16",
        "Float32",
        "Float64",
        "Function",
        "GlobalRef",
        "HTML",
        "IO",
        "IOBuffer",
        "IOContext",
        "IOStream",
        "IdDict",
        "IndexCartesian",
        "IndexLinear",
        "IndexStyle",
        "InexactError",
        "InitError",
        "Int",
        "Int128",
        "Int16",
        "Int32",
        "Int64",
        "Int8",
        "Integer",
        "InterruptException",
        "InvalidStateException",
        "Irrational",
        "KeyError",
        "LinRange",
        "LineNumberNode",
        "LinearIndices",
        "LoadError",
        "MIME",
        "Matrix",
        "Method",
        "MethodError",
        "Missing",
        "MissingException",
        "Module",
        "NTuple",
        "NamedTuple",
        "Nothing",
        "Number",
        "OrdinalRange",
        "OutOfMemoryError",
        "OverflowError",
        "Pair",
        "PartialQuickSort",
        "PermutedDimsArray",
        "Pipe",
        "ProcessFailedException",
        "Ptr",
        "QuoteNode",
        "Rational",
        "RawFD",
        "ReadOnlyMemoryError",
        "Real",
        "ReentrantLock",
        "Ref",
        "Regex",
        "RegexMatch",
        "RoundingMode",
        "SegmentationFault",
        "Set",
        "Signed",
        "Some",
        "StackOverflowError",
        "StepRange",
        "StepRangeLen",
        "StridedArray",
        "StridedMatrix",
        "StridedVecOrMat",
        "StridedVector",
        "String",
        "StringIndexError",
        "SubArray",
        "SubString",
        "SubstitutionString",
        "Symbol",
        "SystemError",
        "Task",
        "TaskFailedException",
        "Text",
        "TextDisplay",
        "Timer",
        "Tuple",
        "Type",
        "TypeError",
        "TypeVar",
        "UInt",
        "UInt128",
        "UInt16",
        "UInt32",
        "UInt64",
        "UInt8",
        "UndefInitializer",
        "UndefKeywordError",
        "UndefRefError",
        "UndefVarError",
        "Union",
        "UnionAll",
        "UnitRange",
        "Unsigned",
        "Val",
        "Vararg",
        "VecElement",
        "VecOrMat",
        "Vector",
        "VersionNumber",
        "WeakKeyDict",
        "WeakRef"
      ];
      var KEYWORDS3 = {
        $pattern: VARIABLE_NAME_RE,
        keyword: KEYWORD_LIST,
        literal: LITERAL_LIST,
        built_in: BUILT_IN_LIST
      };
      var DEFAULT = {
        keywords: KEYWORDS3,
        illegal: /<\//
      };
      var NUMBER = {
        className: "number",
        // supported numeric literals:
        //  * binary literal (e.g. 0x10)
        //  * octal literal (e.g. 0o76543210)
        //  * hexadecimal literal (e.g. 0xfedcba876543210)
        //  * hexadecimal floating point literal (e.g. 0x1p0, 0x1.2p2)
        //  * decimal literal (e.g. 9876543210, 100_000_000)
        //  * floating pointe literal (e.g. 1.2, 1.2f, .2, 1., 1.2e10, 1.2e-10)
        begin: /(\b0x[\d_]*(\.[\d_]*)?|0x\.\d[\d_]*)p[-+]?\d+|\b0[box][a-fA-F0-9][a-fA-F0-9_]*|(\b\d[\d_]*(\.[\d_]*)?|\.\d[\d_]*)([eEfF][-+]?\d+)?/,
        relevance: 0
      };
      var CHAR = {
        className: "string",
        begin: /'(.|\\[xXuU][a-zA-Z0-9]+)'/
      };
      var INTERPOLATION = {
        className: "subst",
        begin: /\$\(/,
        end: /\)/,
        keywords: KEYWORDS3
      };
      var INTERPOLATED_VARIABLE = {
        className: "variable",
        begin: "\\$" + VARIABLE_NAME_RE
      };
      var STRING = {
        className: "string",
        contains: [hljs5.BACKSLASH_ESCAPE, INTERPOLATION, INTERPOLATED_VARIABLE],
        variants: [
          { begin: /\w*"""/, end: /"""\w*/, relevance: 10 },
          { begin: /\w*"/, end: /"\w*/ }
        ]
      };
      var COMMAND = {
        className: "string",
        contains: [hljs5.BACKSLASH_ESCAPE, INTERPOLATION, INTERPOLATED_VARIABLE],
        begin: "`",
        end: "`"
      };
      var MACROCALL = {
        className: "meta",
        begin: "@" + VARIABLE_NAME_RE
      };
      var COMMENT = {
        className: "comment",
        variants: [
          { begin: "#=", end: "=#", relevance: 10 },
          { begin: "#", end: "$" }
        ]
      };
      DEFAULT.name = "Julia";
      DEFAULT.contains = [
        NUMBER,
        CHAR,
        STRING,
        COMMAND,
        MACROCALL,
        COMMENT,
        hljs5.HASH_COMMENT_MODE,
        {
          className: "keyword",
          begin: "\\b(((abstract|primitive)\\s+)type|(mutable\\s+)?struct)\\b"
        },
        { begin: /<:/ }
        // relevance booster
      ];
      INTERPOLATION.contains = DEFAULT.contains;
      return DEFAULT;
    }
    module.exports = julia;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/julia-repl.js
var require_julia_repl = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/julia-repl.js"(exports, module) {
    init_process_shim();
    function juliaRepl(hljs5) {
      return {
        name: "Julia REPL",
        contains: [
          {
            className: "meta",
            begin: /^julia>/,
            relevance: 10,
            starts: {
              // end the highlighting if we are on a new line and the line does not have at
              // least six spaces in the beginning
              end: /^(?![ ]{6})/,
              subLanguage: "julia"
            },
            // jldoctest Markdown blocks are used in the Julia manual and package docs indicate
            // code snippets that should be verified when the documentation is built. They can be
            // either REPL-like or script-like, but are usually REPL-like and therefore we apply
            // julia-repl highlighting to them. More information can be found in Documenter's
            // manual: https://juliadocs.github.io/Documenter.jl/latest/man/doctests.html
            aliases: ["jldoctest"]
          }
        ]
      };
    }
    module.exports = juliaRepl;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/kotlin.js
var require_kotlin = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/kotlin.js"(exports, module) {
    init_process_shim();
    var decimalDigits = "[0-9](_*[0-9])*";
    var frac = `\\.(${decimalDigits})`;
    var hexDigits = "[0-9a-fA-F](_*[0-9a-fA-F])*";
    var NUMERIC = {
      className: "number",
      variants: [
        // DecimalFloatingPointLiteral
        // including ExponentPart
        { begin: `(\\b(${decimalDigits})((${frac})|\\.)?|(${frac}))[eE][+-]?(${decimalDigits})[fFdD]?\\b` },
        // excluding ExponentPart
        { begin: `\\b(${decimalDigits})((${frac})[fFdD]?\\b|\\.([fFdD]\\b)?)` },
        { begin: `(${frac})[fFdD]?\\b` },
        { begin: `\\b(${decimalDigits})[fFdD]\\b` },
        // HexadecimalFloatingPointLiteral
        { begin: `\\b0[xX]((${hexDigits})\\.?|(${hexDigits})?\\.(${hexDigits}))[pP][+-]?(${decimalDigits})[fFdD]?\\b` },
        // DecimalIntegerLiteral
        { begin: "\\b(0|[1-9](_*[0-9])*)[lL]?\\b" },
        // HexIntegerLiteral
        { begin: `\\b0[xX](${hexDigits})[lL]?\\b` },
        // OctalIntegerLiteral
        { begin: "\\b0(_*[0-7])*[lL]?\\b" },
        // BinaryIntegerLiteral
        { begin: "\\b0[bB][01](_*[01])*[lL]?\\b" }
      ],
      relevance: 0
    };
    function kotlin(hljs5) {
      const KEYWORDS3 = {
        keyword: "abstract as val var vararg get set class object open private protected public noinline crossinline dynamic final enum if else do while for when throw try catch finally import package is in fun override companion reified inline lateinit init interface annotation data sealed internal infix operator out by constructor super tailrec where const inner suspend typealias external expect actual",
        built_in: "Byte Short Char Int Long Boolean Float Double Void Unit Nothing",
        literal: "true false null"
      };
      const KEYWORDS_WITH_LABEL = {
        className: "keyword",
        begin: /\b(break|continue|return|this)\b/,
        starts: {
          contains: [
            {
              className: "symbol",
              begin: /@\w+/
            }
          ]
        }
      };
      const LABEL = {
        className: "symbol",
        begin: hljs5.UNDERSCORE_IDENT_RE + "@"
      };
      const SUBST = {
        className: "subst",
        begin: /\$\{/,
        end: /\}/,
        contains: [hljs5.C_NUMBER_MODE]
      };
      const VARIABLE = {
        className: "variable",
        begin: "\\$" + hljs5.UNDERSCORE_IDENT_RE
      };
      const STRING = {
        className: "string",
        variants: [
          {
            begin: '"""',
            end: '"""(?=[^"])',
            contains: [
              VARIABLE,
              SUBST
            ]
          },
          // Can't use built-in modes easily, as we want to use STRING in the meta
          // context as 'meta-string' and there's no syntax to remove explicitly set
          // classNames in built-in modes.
          {
            begin: "'",
            end: "'",
            illegal: /\n/,
            contains: [hljs5.BACKSLASH_ESCAPE]
          },
          {
            begin: '"',
            end: '"',
            illegal: /\n/,
            contains: [
              hljs5.BACKSLASH_ESCAPE,
              VARIABLE,
              SUBST
            ]
          }
        ]
      };
      SUBST.contains.push(STRING);
      const ANNOTATION_USE_SITE = {
        className: "meta",
        begin: "@(?:file|property|field|get|set|receiver|param|setparam|delegate)\\s*:(?:\\s*" + hljs5.UNDERSCORE_IDENT_RE + ")?"
      };
      const ANNOTATION = {
        className: "meta",
        begin: "@" + hljs5.UNDERSCORE_IDENT_RE,
        contains: [
          {
            begin: /\(/,
            end: /\)/,
            contains: [
              hljs5.inherit(STRING, {
                className: "meta-string"
              })
            ]
          }
        ]
      };
      const KOTLIN_NUMBER_MODE = NUMERIC;
      const KOTLIN_NESTED_COMMENT = hljs5.COMMENT(
        "/\\*",
        "\\*/",
        {
          contains: [hljs5.C_BLOCK_COMMENT_MODE]
        }
      );
      const KOTLIN_PAREN_TYPE = {
        variants: [
          {
            className: "type",
            begin: hljs5.UNDERSCORE_IDENT_RE
          },
          {
            begin: /\(/,
            end: /\)/,
            contains: []
            // defined later
          }
        ]
      };
      const KOTLIN_PAREN_TYPE2 = KOTLIN_PAREN_TYPE;
      KOTLIN_PAREN_TYPE2.variants[1].contains = [KOTLIN_PAREN_TYPE];
      KOTLIN_PAREN_TYPE.variants[1].contains = [KOTLIN_PAREN_TYPE2];
      return {
        name: "Kotlin",
        aliases: ["kt", "kts"],
        keywords: KEYWORDS3,
        contains: [
          hljs5.COMMENT(
            "/\\*\\*",
            "\\*/",
            {
              relevance: 0,
              contains: [
                {
                  className: "doctag",
                  begin: "@[A-Za-z]+"
                }
              ]
            }
          ),
          hljs5.C_LINE_COMMENT_MODE,
          KOTLIN_NESTED_COMMENT,
          KEYWORDS_WITH_LABEL,
          LABEL,
          ANNOTATION_USE_SITE,
          ANNOTATION,
          {
            className: "function",
            beginKeywords: "fun",
            end: "[(]|$",
            returnBegin: true,
            excludeEnd: true,
            keywords: KEYWORDS3,
            relevance: 5,
            contains: [
              {
                begin: hljs5.UNDERSCORE_IDENT_RE + "\\s*\\(",
                returnBegin: true,
                relevance: 0,
                contains: [hljs5.UNDERSCORE_TITLE_MODE]
              },
              {
                className: "type",
                begin: /</,
                end: />/,
                keywords: "reified",
                relevance: 0
              },
              {
                className: "params",
                begin: /\(/,
                end: /\)/,
                endsParent: true,
                keywords: KEYWORDS3,
                relevance: 0,
                contains: [
                  {
                    begin: /:/,
                    end: /[=,\/]/,
                    endsWithParent: true,
                    contains: [
                      KOTLIN_PAREN_TYPE,
                      hljs5.C_LINE_COMMENT_MODE,
                      KOTLIN_NESTED_COMMENT
                    ],
                    relevance: 0
                  },
                  hljs5.C_LINE_COMMENT_MODE,
                  KOTLIN_NESTED_COMMENT,
                  ANNOTATION_USE_SITE,
                  ANNOTATION,
                  STRING,
                  hljs5.C_NUMBER_MODE
                ]
              },
              KOTLIN_NESTED_COMMENT
            ]
          },
          {
            className: "class",
            beginKeywords: "class interface trait",
            // remove 'trait' when removed from KEYWORDS
            end: /[:\{(]|$/,
            excludeEnd: true,
            illegal: "extends implements",
            contains: [
              {
                beginKeywords: "public protected internal private constructor"
              },
              hljs5.UNDERSCORE_TITLE_MODE,
              {
                className: "type",
                begin: /</,
                end: />/,
                excludeBegin: true,
                excludeEnd: true,
                relevance: 0
              },
              {
                className: "type",
                begin: /[,:]\s*/,
                end: /[<\(,]|$/,
                excludeBegin: true,
                returnEnd: true
              },
              ANNOTATION_USE_SITE,
              ANNOTATION
            ]
          },
          STRING,
          {
            className: "meta",
            begin: "^#!/usr/bin/env",
            end: "$",
            illegal: "\n"
          },
          KOTLIN_NUMBER_MODE
        ]
      };
    }
    module.exports = kotlin;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/lasso.js
var require_lasso = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/lasso.js"(exports, module) {
    init_process_shim();
    function lasso(hljs5) {
      const LASSO_IDENT_RE = "[a-zA-Z_][\\w.]*";
      const LASSO_ANGLE_RE = "<\\?(lasso(script)?|=)";
      const LASSO_CLOSE_RE = "\\]|\\?>";
      const LASSO_KEYWORDS = {
        $pattern: LASSO_IDENT_RE + "|&[lg]t;",
        literal: "true false none minimal full all void and or not bw nbw ew new cn ncn lt lte gt gte eq neq rx nrx ft",
        built_in: "array date decimal duration integer map pair string tag xml null boolean bytes keyword list locale queue set stack staticarray local var variable global data self inherited currentcapture givenblock",
        keyword: "cache database_names database_schemanames database_tablenames define_tag define_type email_batch encode_set html_comment handle handle_error header if inline iterate ljax_target link link_currentaction link_currentgroup link_currentrecord link_detail link_firstgroup link_firstrecord link_lastgroup link_lastrecord link_nextgroup link_nextrecord link_prevgroup link_prevrecord log loop namespace_using output_none portal private protect records referer referrer repeating resultset rows search_args search_arguments select sort_args sort_arguments thread_atomic value_list while abort case else fail_if fail_ifnot fail if_empty if_false if_null if_true loop_abort loop_continue loop_count params params_up return return_value run_children soap_definetag soap_lastrequest soap_lastresponse tag_name ascending average by define descending do equals frozen group handle_failure import in into join let match max min on order parent protected provide public require returnhome skip split_thread sum take thread to trait type where with yield yieldhome"
      };
      const HTML_COMMENT = hljs5.COMMENT(
        "<!--",
        "-->",
        {
          relevance: 0
        }
      );
      const LASSO_NOPROCESS = {
        className: "meta",
        begin: "\\[noprocess\\]",
        starts: {
          end: "\\[/noprocess\\]",
          returnEnd: true,
          contains: [HTML_COMMENT]
        }
      };
      const LASSO_START = {
        className: "meta",
        begin: "\\[/noprocess|" + LASSO_ANGLE_RE
      };
      const LASSO_DATAMEMBER = {
        className: "symbol",
        begin: "'" + LASSO_IDENT_RE + "'"
      };
      const LASSO_CODE = [
        hljs5.C_LINE_COMMENT_MODE,
        hljs5.C_BLOCK_COMMENT_MODE,
        hljs5.inherit(hljs5.C_NUMBER_MODE, {
          begin: hljs5.C_NUMBER_RE + "|(-?infinity|NaN)\\b"
        }),
        hljs5.inherit(hljs5.APOS_STRING_MODE, {
          illegal: null
        }),
        hljs5.inherit(hljs5.QUOTE_STRING_MODE, {
          illegal: null
        }),
        {
          className: "string",
          begin: "`",
          end: "`"
        },
        {
          // variables
          variants: [
            {
              begin: "[#$]" + LASSO_IDENT_RE
            },
            {
              begin: "#",
              end: "\\d+",
              illegal: "\\W"
            }
          ]
        },
        {
          className: "type",
          begin: "::\\s*",
          end: LASSO_IDENT_RE,
          illegal: "\\W"
        },
        {
          className: "params",
          variants: [
            {
              begin: "-(?!infinity)" + LASSO_IDENT_RE,
              relevance: 0
            },
            {
              begin: "(\\.\\.\\.)"
            }
          ]
        },
        {
          begin: /(->|\.)\s*/,
          relevance: 0,
          contains: [LASSO_DATAMEMBER]
        },
        {
          className: "class",
          beginKeywords: "define",
          returnEnd: true,
          end: "\\(|=>",
          contains: [
            hljs5.inherit(hljs5.TITLE_MODE, {
              begin: LASSO_IDENT_RE + "(=(?!>))?|[-+*/%](?!>)"
            })
          ]
        }
      ];
      return {
        name: "Lasso",
        aliases: [
          "ls",
          "lassoscript"
        ],
        case_insensitive: true,
        keywords: LASSO_KEYWORDS,
        contains: [
          {
            className: "meta",
            begin: LASSO_CLOSE_RE,
            relevance: 0,
            starts: {
              // markup
              end: "\\[|" + LASSO_ANGLE_RE,
              returnEnd: true,
              relevance: 0,
              contains: [HTML_COMMENT]
            }
          },
          LASSO_NOPROCESS,
          LASSO_START,
          {
            className: "meta",
            begin: "\\[no_square_brackets",
            starts: {
              end: "\\[/no_square_brackets\\]",
              // not implemented in the language
              keywords: LASSO_KEYWORDS,
              contains: [
                {
                  className: "meta",
                  begin: LASSO_CLOSE_RE,
                  relevance: 0,
                  starts: {
                    end: "\\[noprocess\\]|" + LASSO_ANGLE_RE,
                    returnEnd: true,
                    contains: [HTML_COMMENT]
                  }
                },
                LASSO_NOPROCESS,
                LASSO_START
              ].concat(LASSO_CODE)
            }
          },
          {
            className: "meta",
            begin: "\\[",
            relevance: 0
          },
          {
            className: "meta",
            begin: "^#!",
            end: "lasso9$",
            relevance: 10
          }
        ].concat(LASSO_CODE)
      };
    }
    module.exports = lasso;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/latex.js
var require_latex = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/latex.js"(exports, module) {
    init_process_shim();
    function source(re2) {
      if (!re2) return null;
      if (typeof re2 === "string") return re2;
      return re2.source;
    }
    function either(...args) {
      const joined = "(" + args.map((x2) => source(x2)).join("|") + ")";
      return joined;
    }
    function latex(hljs5) {
      const KNOWN_CONTROL_WORDS = either(...[
        "(?:NeedsTeXFormat|RequirePackage|GetIdInfo)",
        "Provides(?:Expl)?(?:Package|Class|File)",
        "(?:DeclareOption|ProcessOptions)",
        "(?:documentclass|usepackage|input|include)",
        "makeat(?:letter|other)",
        "ExplSyntax(?:On|Off)",
        "(?:new|renew|provide)?command",
        "(?:re)newenvironment",
        "(?:New|Renew|Provide|Declare)(?:Expandable)?DocumentCommand",
        "(?:New|Renew|Provide|Declare)DocumentEnvironment",
        "(?:(?:e|g|x)?def|let)",
        "(?:begin|end)",
        "(?:part|chapter|(?:sub){0,2}section|(?:sub)?paragraph)",
        "caption",
        "(?:label|(?:eq|page|name)?ref|(?:paren|foot|super)?cite)",
        "(?:alpha|beta|[Gg]amma|[Dd]elta|(?:var)?epsilon|zeta|eta|[Tt]heta|vartheta)",
        "(?:iota|(?:var)?kappa|[Ll]ambda|mu|nu|[Xx]i|[Pp]i|varpi|(?:var)rho)",
        "(?:[Ss]igma|varsigma|tau|[Uu]psilon|[Pp]hi|varphi|chi|[Pp]si|[Oo]mega)",
        "(?:frac|sum|prod|lim|infty|times|sqrt|leq|geq|left|right|middle|[bB]igg?)",
        "(?:[lr]angle|q?quad|[lcvdi]?dots|d?dot|hat|tilde|bar)"
      ].map((word) => word + "(?![a-zA-Z@:_])"));
      const L3_REGEX = new RegExp([
        // A function \module_function_name:signature or \__module_function_name:signature,
        // where both module and function_name need at least two characters and
        // function_name may contain single underscores.
        "(?:__)?[a-zA-Z]{2,}_[a-zA-Z](?:_?[a-zA-Z])+:[a-zA-Z]*",
        // A variable \scope_module_and_name_type or \scope__module_ane_name_type,
        // where scope is one of l, g or c, type needs at least two characters
        // and module_and_name may contain single underscores.
        "[lgc]__?[a-zA-Z](?:_?[a-zA-Z])*_[a-zA-Z]{2,}",
        // A quark \q_the_name or \q__the_name or
        // scan mark \s_the_name or \s__vthe_name,
        // where variable_name needs at least two characters and
        // may contain single underscores.
        "[qs]__?[a-zA-Z](?:_?[a-zA-Z])+",
        // Other LaTeX3 macro names that are not covered by the three rules above.
        "use(?:_i)?:[a-zA-Z]*",
        "(?:else|fi|or):",
        "(?:if|cs|exp):w",
        "(?:hbox|vbox):n",
        "::[a-zA-Z]_unbraced",
        "::[a-zA-Z:]"
      ].map((pattern) => pattern + "(?![a-zA-Z:_])").join("|"));
      const L2_VARIANTS = [
        { begin: /[a-zA-Z@]+/ },
        // control word
        { begin: /[^a-zA-Z@]?/ }
        // control symbol
      ];
      const DOUBLE_CARET_VARIANTS = [
        { begin: /\^{6}[0-9a-f]{6}/ },
        { begin: /\^{5}[0-9a-f]{5}/ },
        { begin: /\^{4}[0-9a-f]{4}/ },
        { begin: /\^{3}[0-9a-f]{3}/ },
        { begin: /\^{2}[0-9a-f]{2}/ },
        { begin: /\^{2}[\u0000-\u007f]/ }
      ];
      const CONTROL_SEQUENCE = {
        className: "keyword",
        begin: /\\/,
        relevance: 0,
        contains: [
          {
            endsParent: true,
            begin: KNOWN_CONTROL_WORDS
          },
          {
            endsParent: true,
            begin: L3_REGEX
          },
          {
            endsParent: true,
            variants: DOUBLE_CARET_VARIANTS
          },
          {
            endsParent: true,
            relevance: 0,
            variants: L2_VARIANTS
          }
        ]
      };
      const MACRO_PARAM = {
        className: "params",
        relevance: 0,
        begin: /#+\d?/
      };
      const DOUBLE_CARET_CHAR = {
        // relevance: 1
        variants: DOUBLE_CARET_VARIANTS
      };
      const SPECIAL_CATCODE = {
        className: "built_in",
        relevance: 0,
        begin: /[$&^_]/
      };
      const MAGIC_COMMENT = {
        className: "meta",
        begin: "% !TeX",
        end: "$",
        relevance: 10
      };
      const COMMENT = hljs5.COMMENT(
        "%",
        "$",
        {
          relevance: 0
        }
      );
      const EVERYTHING_BUT_VERBATIM = [
        CONTROL_SEQUENCE,
        MACRO_PARAM,
        DOUBLE_CARET_CHAR,
        SPECIAL_CATCODE,
        MAGIC_COMMENT,
        COMMENT
      ];
      const BRACE_GROUP_NO_VERBATIM = {
        begin: /\{/,
        end: /\}/,
        relevance: 0,
        contains: ["self", ...EVERYTHING_BUT_VERBATIM]
      };
      const ARGUMENT_BRACES = hljs5.inherit(
        BRACE_GROUP_NO_VERBATIM,
        {
          relevance: 0,
          endsParent: true,
          contains: [BRACE_GROUP_NO_VERBATIM, ...EVERYTHING_BUT_VERBATIM]
        }
      );
      const ARGUMENT_BRACKETS = {
        begin: /\[/,
        end: /\]/,
        endsParent: true,
        relevance: 0,
        contains: [BRACE_GROUP_NO_VERBATIM, ...EVERYTHING_BUT_VERBATIM]
      };
      const SPACE_GOBBLER = {
        begin: /\s+/,
        relevance: 0
      };
      const ARGUMENT_M = [ARGUMENT_BRACES];
      const ARGUMENT_O = [ARGUMENT_BRACKETS];
      const ARGUMENT_AND_THEN = function(arg, starts_mode) {
        return {
          contains: [SPACE_GOBBLER],
          starts: {
            relevance: 0,
            contains: arg,
            starts: starts_mode
          }
        };
      };
      const CSNAME = function(csname, starts_mode) {
        return {
          begin: "\\\\" + csname + "(?![a-zA-Z@:_])",
          keywords: { $pattern: /\\[a-zA-Z]+/, keyword: "\\" + csname },
          relevance: 0,
          contains: [SPACE_GOBBLER],
          starts: starts_mode
        };
      };
      const BEGIN_ENV = function(envname, starts_mode) {
        return hljs5.inherit(
          {
            begin: "\\\\begin(?=[ 	]*(\\r?\\n[ 	]*)?\\{" + envname + "\\})",
            keywords: { $pattern: /\\[a-zA-Z]+/, keyword: "\\begin" },
            relevance: 0
          },
          ARGUMENT_AND_THEN(ARGUMENT_M, starts_mode)
        );
      };
      const VERBATIM_DELIMITED_EQUAL = (innerName = "string") => {
        return hljs5.END_SAME_AS_BEGIN({
          className: innerName,
          begin: /(.|\r?\n)/,
          end: /(.|\r?\n)/,
          excludeBegin: true,
          excludeEnd: true,
          endsParent: true
        });
      };
      const VERBATIM_DELIMITED_ENV = function(envname) {
        return {
          className: "string",
          end: "(?=\\\\end\\{" + envname + "\\})"
        };
      };
      const VERBATIM_DELIMITED_BRACES = (innerName = "string") => {
        return {
          relevance: 0,
          begin: /\{/,
          starts: {
            endsParent: true,
            contains: [
              {
                className: innerName,
                end: /(?=\})/,
                endsParent: true,
                contains: [
                  {
                    begin: /\{/,
                    end: /\}/,
                    relevance: 0,
                    contains: ["self"]
                  }
                ]
              }
            ]
          }
        };
      };
      const VERBATIM = [
        ...["verb", "lstinline"].map((csname) => CSNAME(csname, { contains: [VERBATIM_DELIMITED_EQUAL()] })),
        CSNAME("mint", ARGUMENT_AND_THEN(ARGUMENT_M, { contains: [VERBATIM_DELIMITED_EQUAL()] })),
        CSNAME("mintinline", ARGUMENT_AND_THEN(ARGUMENT_M, { contains: [VERBATIM_DELIMITED_BRACES(), VERBATIM_DELIMITED_EQUAL()] })),
        CSNAME("url", { contains: [VERBATIM_DELIMITED_BRACES("link"), VERBATIM_DELIMITED_BRACES("link")] }),
        CSNAME("hyperref", { contains: [VERBATIM_DELIMITED_BRACES("link")] }),
        CSNAME("href", ARGUMENT_AND_THEN(ARGUMENT_O, { contains: [VERBATIM_DELIMITED_BRACES("link")] })),
        ...[].concat(...["", "\\*"].map((suffix) => [
          BEGIN_ENV("verbatim" + suffix, VERBATIM_DELIMITED_ENV("verbatim" + suffix)),
          BEGIN_ENV("filecontents" + suffix, ARGUMENT_AND_THEN(ARGUMENT_M, VERBATIM_DELIMITED_ENV("filecontents" + suffix))),
          ...["", "B", "L"].map(
            (prefix) => BEGIN_ENV(prefix + "Verbatim" + suffix, ARGUMENT_AND_THEN(ARGUMENT_O, VERBATIM_DELIMITED_ENV(prefix + "Verbatim" + suffix)))
          )
        ])),
        BEGIN_ENV("minted", ARGUMENT_AND_THEN(ARGUMENT_O, ARGUMENT_AND_THEN(ARGUMENT_M, VERBATIM_DELIMITED_ENV("minted"))))
      ];
      return {
        name: "LaTeX",
        aliases: ["tex"],
        contains: [
          ...VERBATIM,
          ...EVERYTHING_BUT_VERBATIM
        ]
      };
    }
    module.exports = latex;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/ldif.js
var require_ldif = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/ldif.js"(exports, module) {
    init_process_shim();
    function ldif(hljs5) {
      return {
        name: "LDIF",
        contains: [
          {
            className: "attribute",
            begin: "^dn",
            end: ": ",
            excludeEnd: true,
            starts: {
              end: "$",
              relevance: 0
            },
            relevance: 10
          },
          {
            className: "attribute",
            begin: "^\\w",
            end: ": ",
            excludeEnd: true,
            starts: {
              end: "$",
              relevance: 0
            }
          },
          {
            className: "literal",
            begin: "^-",
            end: "$"
          },
          hljs5.HASH_COMMENT_MODE
        ]
      };
    }
    module.exports = ldif;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/leaf.js
var require_leaf = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/leaf.js"(exports, module) {
    init_process_shim();
    function leaf(hljs5) {
      return {
        name: "Leaf",
        contains: [
          {
            className: "function",
            begin: "#+[A-Za-z_0-9]*\\(",
            end: / \{/,
            returnBegin: true,
            excludeEnd: true,
            contains: [
              {
                className: "keyword",
                begin: "#+"
              },
              {
                className: "title",
                begin: "[A-Za-z_][A-Za-z_0-9]*"
              },
              {
                className: "params",
                begin: "\\(",
                end: "\\)",
                endsParent: true,
                contains: [
                  {
                    className: "string",
                    begin: '"',
                    end: '"'
                  },
                  {
                    className: "variable",
                    begin: "[A-Za-z_][A-Za-z_0-9]*"
                  }
                ]
              }
            ]
          }
        ]
      };
    }
    module.exports = leaf;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/less.js
var require_less = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/less.js"(exports, module) {
    init_process_shim();
    var MODES2 = (hljs5) => {
      return {
        IMPORTANT: {
          className: "meta",
          begin: "!important"
        },
        HEXCOLOR: {
          className: "number",
          begin: "#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})"
        },
        ATTRIBUTE_SELECTOR_MODE: {
          className: "selector-attr",
          begin: /\[/,
          end: /\]/,
          illegal: "$",
          contains: [
            hljs5.APOS_STRING_MODE,
            hljs5.QUOTE_STRING_MODE
          ]
        }
      };
    };
    var TAGS2 = [
      "a",
      "abbr",
      "address",
      "article",
      "aside",
      "audio",
      "b",
      "blockquote",
      "body",
      "button",
      "canvas",
      "caption",
      "cite",
      "code",
      "dd",
      "del",
      "details",
      "dfn",
      "div",
      "dl",
      "dt",
      "em",
      "fieldset",
      "figcaption",
      "figure",
      "footer",
      "form",
      "h1",
      "h2",
      "h3",
      "h4",
      "h5",
      "h6",
      "header",
      "hgroup",
      "html",
      "i",
      "iframe",
      "img",
      "input",
      "ins",
      "kbd",
      "label",
      "legend",
      "li",
      "main",
      "mark",
      "menu",
      "nav",
      "object",
      "ol",
      "p",
      "q",
      "quote",
      "samp",
      "section",
      "span",
      "strong",
      "summary",
      "sup",
      "table",
      "tbody",
      "td",
      "textarea",
      "tfoot",
      "th",
      "thead",
      "time",
      "tr",
      "ul",
      "var",
      "video"
    ];
    var MEDIA_FEATURES2 = [
      "any-hover",
      "any-pointer",
      "aspect-ratio",
      "color",
      "color-gamut",
      "color-index",
      "device-aspect-ratio",
      "device-height",
      "device-width",
      "display-mode",
      "forced-colors",
      "grid",
      "height",
      "hover",
      "inverted-colors",
      "monochrome",
      "orientation",
      "overflow-block",
      "overflow-inline",
      "pointer",
      "prefers-color-scheme",
      "prefers-contrast",
      "prefers-reduced-motion",
      "prefers-reduced-transparency",
      "resolution",
      "scan",
      "scripting",
      "update",
      "width",
      // TODO: find a better solution?
      "min-width",
      "max-width",
      "min-height",
      "max-height"
    ];
    var PSEUDO_CLASSES2 = [
      "active",
      "any-link",
      "blank",
      "checked",
      "current",
      "default",
      "defined",
      "dir",
      // dir()
      "disabled",
      "drop",
      "empty",
      "enabled",
      "first",
      "first-child",
      "first-of-type",
      "fullscreen",
      "future",
      "focus",
      "focus-visible",
      "focus-within",
      "has",
      // has()
      "host",
      // host or host()
      "host-context",
      // host-context()
      "hover",
      "indeterminate",
      "in-range",
      "invalid",
      "is",
      // is()
      "lang",
      // lang()
      "last-child",
      "last-of-type",
      "left",
      "link",
      "local-link",
      "not",
      // not()
      "nth-child",
      // nth-child()
      "nth-col",
      // nth-col()
      "nth-last-child",
      // nth-last-child()
      "nth-last-col",
      // nth-last-col()
      "nth-last-of-type",
      //nth-last-of-type()
      "nth-of-type",
      //nth-of-type()
      "only-child",
      "only-of-type",
      "optional",
      "out-of-range",
      "past",
      "placeholder-shown",
      "read-only",
      "read-write",
      "required",
      "right",
      "root",
      "scope",
      "target",
      "target-within",
      "user-invalid",
      "valid",
      "visited",
      "where"
      // where()
    ];
    var PSEUDO_ELEMENTS2 = [
      "after",
      "backdrop",
      "before",
      "cue",
      "cue-region",
      "first-letter",
      "first-line",
      "grammar-error",
      "marker",
      "part",
      "placeholder",
      "selection",
      "slotted",
      "spelling-error"
    ];
    var ATTRIBUTES2 = [
      "align-content",
      "align-items",
      "align-self",
      "animation",
      "animation-delay",
      "animation-direction",
      "animation-duration",
      "animation-fill-mode",
      "animation-iteration-count",
      "animation-name",
      "animation-play-state",
      "animation-timing-function",
      "auto",
      "backface-visibility",
      "background",
      "background-attachment",
      "background-clip",
      "background-color",
      "background-image",
      "background-origin",
      "background-position",
      "background-repeat",
      "background-size",
      "border",
      "border-bottom",
      "border-bottom-color",
      "border-bottom-left-radius",
      "border-bottom-right-radius",
      "border-bottom-style",
      "border-bottom-width",
      "border-collapse",
      "border-color",
      "border-image",
      "border-image-outset",
      "border-image-repeat",
      "border-image-slice",
      "border-image-source",
      "border-image-width",
      "border-left",
      "border-left-color",
      "border-left-style",
      "border-left-width",
      "border-radius",
      "border-right",
      "border-right-color",
      "border-right-style",
      "border-right-width",
      "border-spacing",
      "border-style",
      "border-top",
      "border-top-color",
      "border-top-left-radius",
      "border-top-right-radius",
      "border-top-style",
      "border-top-width",
      "border-width",
      "bottom",
      "box-decoration-break",
      "box-shadow",
      "box-sizing",
      "break-after",
      "break-before",
      "break-inside",
      "caption-side",
      "clear",
      "clip",
      "clip-path",
      "color",
      "column-count",
      "column-fill",
      "column-gap",
      "column-rule",
      "column-rule-color",
      "column-rule-style",
      "column-rule-width",
      "column-span",
      "column-width",
      "columns",
      "content",
      "counter-increment",
      "counter-reset",
      "cursor",
      "direction",
      "display",
      "empty-cells",
      "filter",
      "flex",
      "flex-basis",
      "flex-direction",
      "flex-flow",
      "flex-grow",
      "flex-shrink",
      "flex-wrap",
      "float",
      "font",
      "font-display",
      "font-family",
      "font-feature-settings",
      "font-kerning",
      "font-language-override",
      "font-size",
      "font-size-adjust",
      "font-smoothing",
      "font-stretch",
      "font-style",
      "font-variant",
      "font-variant-ligatures",
      "font-variation-settings",
      "font-weight",
      "height",
      "hyphens",
      "icon",
      "image-orientation",
      "image-rendering",
      "image-resolution",
      "ime-mode",
      "inherit",
      "initial",
      "justify-content",
      "left",
      "letter-spacing",
      "line-height",
      "list-style",
      "list-style-image",
      "list-style-position",
      "list-style-type",
      "margin",
      "margin-bottom",
      "margin-left",
      "margin-right",
      "margin-top",
      "marks",
      "mask",
      "max-height",
      "max-width",
      "min-height",
      "min-width",
      "nav-down",
      "nav-index",
      "nav-left",
      "nav-right",
      "nav-up",
      "none",
      "normal",
      "object-fit",
      "object-position",
      "opacity",
      "order",
      "orphans",
      "outline",
      "outline-color",
      "outline-offset",
      "outline-style",
      "outline-width",
      "overflow",
      "overflow-wrap",
      "overflow-x",
      "overflow-y",
      "padding",
      "padding-bottom",
      "padding-left",
      "padding-right",
      "padding-top",
      "page-break-after",
      "page-break-before",
      "page-break-inside",
      "perspective",
      "perspective-origin",
      "pointer-events",
      "position",
      "quotes",
      "resize",
      "right",
      "src",
      // @font-face
      "tab-size",
      "table-layout",
      "text-align",
      "text-align-last",
      "text-decoration",
      "text-decoration-color",
      "text-decoration-line",
      "text-decoration-style",
      "text-indent",
      "text-overflow",
      "text-rendering",
      "text-shadow",
      "text-transform",
      "text-underline-position",
      "top",
      "transform",
      "transform-origin",
      "transform-style",
      "transition",
      "transition-delay",
      "transition-duration",
      "transition-property",
      "transition-timing-function",
      "unicode-bidi",
      "vertical-align",
      "visibility",
      "white-space",
      "widows",
      "width",
      "word-break",
      "word-spacing",
      "word-wrap",
      "z-index"
      // reverse makes sure longer attributes `font-weight` are matched fully
      // instead of getting false positives on say `font`
    ].reverse();
    var PSEUDO_SELECTORS = PSEUDO_CLASSES2.concat(PSEUDO_ELEMENTS2);
    function less(hljs5) {
      const modes = MODES2(hljs5);
      const PSEUDO_SELECTORS$1 = PSEUDO_SELECTORS;
      const AT_MODIFIERS = "and or not only";
      const IDENT_RE3 = "[\\w-]+";
      const INTERP_IDENT_RE = "(" + IDENT_RE3 + "|@\\{" + IDENT_RE3 + "\\})";
      const RULES = [];
      const VALUE_MODES = [];
      const STRING_MODE = function(c6) {
        return {
          // Less strings are not multiline (also include '~' for more consistent coloring of "escaped" strings)
          className: "string",
          begin: "~?" + c6 + ".*?" + c6
        };
      };
      const IDENT_MODE = function(name, begin, relevance) {
        return {
          className: name,
          begin,
          relevance
        };
      };
      const AT_KEYWORDS = {
        $pattern: /[a-z-]+/,
        keyword: AT_MODIFIERS,
        attribute: MEDIA_FEATURES2.join(" ")
      };
      const PARENS_MODE = {
        // used only to properly balance nested parens inside mixin call, def. arg list
        begin: "\\(",
        end: "\\)",
        contains: VALUE_MODES,
        keywords: AT_KEYWORDS,
        relevance: 0
      };
      VALUE_MODES.push(
        hljs5.C_LINE_COMMENT_MODE,
        hljs5.C_BLOCK_COMMENT_MODE,
        STRING_MODE("'"),
        STRING_MODE('"'),
        hljs5.CSS_NUMBER_MODE,
        // fixme: it does not include dot for numbers like .5em :(
        {
          begin: "(url|data-uri)\\(",
          starts: {
            className: "string",
            end: "[\\)\\n]",
            excludeEnd: true
          }
        },
        modes.HEXCOLOR,
        PARENS_MODE,
        IDENT_MODE("variable", "@@?" + IDENT_RE3, 10),
        IDENT_MODE("variable", "@\\{" + IDENT_RE3 + "\\}"),
        IDENT_MODE("built_in", "~?`[^`]*?`"),
        // inline javascript (or whatever host language) *multiline* string
        {
          // @media features (it’s here to not duplicate things in AT_RULE_MODE with extra PARENS_MODE overriding):
          className: "attribute",
          begin: IDENT_RE3 + "\\s*:",
          end: ":",
          returnBegin: true,
          excludeEnd: true
        },
        modes.IMPORTANT
      );
      const VALUE_WITH_RULESETS = VALUE_MODES.concat({
        begin: /\{/,
        end: /\}/,
        contains: RULES
      });
      const MIXIN_GUARD_MODE = {
        beginKeywords: "when",
        endsWithParent: true,
        contains: [
          {
            beginKeywords: "and not"
          }
        ].concat(VALUE_MODES)
        // using this form to override VALUE’s 'function' match
      };
      const RULE_MODE = {
        begin: INTERP_IDENT_RE + "\\s*:",
        returnBegin: true,
        end: /[;}]/,
        relevance: 0,
        contains: [
          {
            begin: /-(webkit|moz|ms|o)-/
          },
          {
            className: "attribute",
            begin: "\\b(" + ATTRIBUTES2.join("|") + ")\\b",
            end: /(?=:)/,
            starts: {
              endsWithParent: true,
              illegal: "[<=$]",
              relevance: 0,
              contains: VALUE_MODES
            }
          }
        ]
      };
      const AT_RULE_MODE = {
        className: "keyword",
        begin: "@(import|media|charset|font-face|(-[a-z]+-)?keyframes|supports|document|namespace|page|viewport|host)\\b",
        starts: {
          end: "[;{}]",
          keywords: AT_KEYWORDS,
          returnEnd: true,
          contains: VALUE_MODES,
          relevance: 0
        }
      };
      const VAR_RULE_MODE = {
        className: "variable",
        variants: [
          // using more strict pattern for higher relevance to increase chances of Less detection.
          // this is *the only* Less specific statement used in most of the sources, so...
          // (we’ll still often loose to the css-parser unless there's '//' comment,
          // simply because 1 variable just can't beat 99 properties :)
          {
            begin: "@" + IDENT_RE3 + "\\s*:",
            relevance: 15
          },
          {
            begin: "@" + IDENT_RE3
          }
        ],
        starts: {
          end: "[;}]",
          returnEnd: true,
          contains: VALUE_WITH_RULESETS
        }
      };
      const SELECTOR_MODE = {
        // first parse unambiguous selectors (i.e. those not starting with tag)
        // then fall into the scary lookahead-discriminator variant.
        // this mode also handles mixin definitions and calls
        variants: [
          {
            begin: "[\\.#:&\\[>]",
            end: "[;{}]"
            // mixin calls end with ';'
          },
          {
            begin: INTERP_IDENT_RE,
            end: /\{/
          }
        ],
        returnBegin: true,
        returnEnd: true,
        illegal: `[<='$"]`,
        relevance: 0,
        contains: [
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          MIXIN_GUARD_MODE,
          IDENT_MODE("keyword", "all\\b"),
          IDENT_MODE("variable", "@\\{" + IDENT_RE3 + "\\}"),
          // otherwise it’s identified as tag
          {
            begin: "\\b(" + TAGS2.join("|") + ")\\b",
            className: "selector-tag"
          },
          IDENT_MODE("selector-tag", INTERP_IDENT_RE + "%?", 0),
          // '%' for more consistent coloring of @keyframes "tags"
          IDENT_MODE("selector-id", "#" + INTERP_IDENT_RE),
          IDENT_MODE("selector-class", "\\." + INTERP_IDENT_RE, 0),
          IDENT_MODE("selector-tag", "&", 0),
          modes.ATTRIBUTE_SELECTOR_MODE,
          {
            className: "selector-pseudo",
            begin: ":(" + PSEUDO_CLASSES2.join("|") + ")"
          },
          {
            className: "selector-pseudo",
            begin: "::(" + PSEUDO_ELEMENTS2.join("|") + ")"
          },
          {
            begin: "\\(",
            end: "\\)",
            contains: VALUE_WITH_RULESETS
          },
          // argument list of parametric mixins
          {
            begin: "!important"
          }
          // eat !important after mixin call or it will be colored as tag
        ]
      };
      const PSEUDO_SELECTOR_MODE = {
        begin: IDENT_RE3 + `:(:)?(${PSEUDO_SELECTORS$1.join("|")})`,
        returnBegin: true,
        contains: [SELECTOR_MODE]
      };
      RULES.push(
        hljs5.C_LINE_COMMENT_MODE,
        hljs5.C_BLOCK_COMMENT_MODE,
        AT_RULE_MODE,
        VAR_RULE_MODE,
        PSEUDO_SELECTOR_MODE,
        RULE_MODE,
        SELECTOR_MODE
      );
      return {
        name: "Less",
        case_insensitive: true,
        illegal: `[=>'/<($"]`,
        contains: RULES
      };
    }
    module.exports = less;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/lisp.js
var require_lisp = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/lisp.js"(exports, module) {
    init_process_shim();
    function lisp(hljs5) {
      var LISP_IDENT_RE = "[a-zA-Z_\\-+\\*\\/<=>&#][a-zA-Z0-9_\\-+*\\/<=>&#!]*";
      var MEC_RE = "\\|[^]*?\\|";
      var LISP_SIMPLE_NUMBER_RE = "(-|\\+)?\\d+(\\.\\d+|\\/\\d+)?((d|e|f|l|s|D|E|F|L|S)(\\+|-)?\\d+)?";
      var LITERAL = {
        className: "literal",
        begin: "\\b(t{1}|nil)\\b"
      };
      var NUMBER = {
        className: "number",
        variants: [
          { begin: LISP_SIMPLE_NUMBER_RE, relevance: 0 },
          { begin: "#(b|B)[0-1]+(/[0-1]+)?" },
          { begin: "#(o|O)[0-7]+(/[0-7]+)?" },
          { begin: "#(x|X)[0-9a-fA-F]+(/[0-9a-fA-F]+)?" },
          { begin: "#(c|C)\\(" + LISP_SIMPLE_NUMBER_RE + " +" + LISP_SIMPLE_NUMBER_RE, end: "\\)" }
        ]
      };
      var STRING = hljs5.inherit(hljs5.QUOTE_STRING_MODE, { illegal: null });
      var COMMENT = hljs5.COMMENT(
        ";",
        "$",
        {
          relevance: 0
        }
      );
      var VARIABLE = {
        begin: "\\*",
        end: "\\*"
      };
      var KEYWORD = {
        className: "symbol",
        begin: "[:&]" + LISP_IDENT_RE
      };
      var IDENT = {
        begin: LISP_IDENT_RE,
        relevance: 0
      };
      var MEC = {
        begin: MEC_RE
      };
      var QUOTED_LIST = {
        begin: "\\(",
        end: "\\)",
        contains: ["self", LITERAL, STRING, NUMBER, IDENT]
      };
      var QUOTED = {
        contains: [NUMBER, STRING, VARIABLE, KEYWORD, QUOTED_LIST, IDENT],
        variants: [
          {
            begin: "['`]\\(",
            end: "\\)"
          },
          {
            begin: "\\(quote ",
            end: "\\)",
            keywords: { name: "quote" }
          },
          {
            begin: "'" + MEC_RE
          }
        ]
      };
      var QUOTED_ATOM = {
        variants: [
          { begin: "'" + LISP_IDENT_RE },
          { begin: "#'" + LISP_IDENT_RE + "(::" + LISP_IDENT_RE + ")*" }
        ]
      };
      var LIST = {
        begin: "\\(\\s*",
        end: "\\)"
      };
      var BODY = {
        endsWithParent: true,
        relevance: 0
      };
      LIST.contains = [
        {
          className: "name",
          variants: [
            {
              begin: LISP_IDENT_RE,
              relevance: 0
            },
            { begin: MEC_RE }
          ]
        },
        BODY
      ];
      BODY.contains = [QUOTED, QUOTED_ATOM, LIST, LITERAL, NUMBER, STRING, COMMENT, VARIABLE, KEYWORD, MEC, IDENT];
      return {
        name: "Lisp",
        illegal: /\S/,
        contains: [
          NUMBER,
          hljs5.SHEBANG(),
          LITERAL,
          STRING,
          COMMENT,
          QUOTED,
          QUOTED_ATOM,
          LIST,
          IDENT
        ]
      };
    }
    module.exports = lisp;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/livecodeserver.js
var require_livecodeserver = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/livecodeserver.js"(exports, module) {
    init_process_shim();
    function livecodeserver(hljs5) {
      const VARIABLE = {
        className: "variable",
        variants: [
          {
            begin: "\\b([gtps][A-Z]{1}[a-zA-Z0-9]*)(\\[.+\\])?(?:\\s*?)"
          },
          {
            begin: "\\$_[A-Z]+"
          }
        ],
        relevance: 0
      };
      const COMMENT_MODES = [
        hljs5.C_BLOCK_COMMENT_MODE,
        hljs5.HASH_COMMENT_MODE,
        hljs5.COMMENT("--", "$"),
        hljs5.COMMENT("[^:]//", "$")
      ];
      const TITLE1 = hljs5.inherit(hljs5.TITLE_MODE, {
        variants: [
          {
            begin: "\\b_*rig[A-Z][A-Za-z0-9_\\-]*"
          },
          {
            begin: "\\b_[a-z0-9\\-]+"
          }
        ]
      });
      const TITLE2 = hljs5.inherit(hljs5.TITLE_MODE, {
        begin: "\\b([A-Za-z0-9_\\-]+)\\b"
      });
      return {
        name: "LiveCode",
        case_insensitive: false,
        keywords: {
          keyword: "$_COOKIE $_FILES $_GET $_GET_BINARY $_GET_RAW $_POST $_POST_BINARY $_POST_RAW $_SESSION $_SERVER codepoint codepoints segment segments codeunit codeunits sentence sentences trueWord trueWords paragraph after byte bytes english the until http forever descending using line real8 with seventh for stdout finally element word words fourth before black ninth sixth characters chars stderr uInt1 uInt1s uInt2 uInt2s stdin string lines relative rel any fifth items from middle mid at else of catch then third it file milliseconds seconds second secs sec int1 int1s int4 int4s internet int2 int2s normal text item last long detailed effective uInt4 uInt4s repeat end repeat URL in try into switch to words https token binfile each tenth as ticks tick system real4 by dateItems without char character ascending eighth whole dateTime numeric short first ftp integer abbreviated abbr abbrev private case while if div mod wrap and or bitAnd bitNot bitOr bitXor among not in a an within contains ends with begins the keys of keys",
          literal: "SIX TEN FORMFEED NINE ZERO NONE SPACE FOUR FALSE COLON CRLF PI COMMA ENDOFFILE EOF EIGHT FIVE QUOTE EMPTY ONE TRUE RETURN CR LINEFEED RIGHT BACKSLASH NULL SEVEN TAB THREE TWO six ten formfeed nine zero none space four false colon crlf pi comma endoffile eof eight five quote empty one true return cr linefeed right backslash null seven tab three two RIVERSION RISTATE FILE_READ_MODE FILE_WRITE_MODE FILE_WRITE_MODE DIR_WRITE_MODE FILE_READ_UMASK FILE_WRITE_UMASK DIR_READ_UMASK DIR_WRITE_UMASK",
          built_in: "put abs acos aliasReference annuity arrayDecode arrayEncode asin atan atan2 average avg avgDev base64Decode base64Encode baseConvert binaryDecode binaryEncode byteOffset byteToNum cachedURL cachedURLs charToNum cipherNames codepointOffset codepointProperty codepointToNum codeunitOffset commandNames compound compress constantNames cos date dateFormat decompress difference directories diskSpace DNSServers exp exp1 exp2 exp10 extents files flushEvents folders format functionNames geometricMean global globals hasMemory harmonicMean hostAddress hostAddressToName hostName hostNameToAddress isNumber ISOToMac itemOffset keys len length libURLErrorData libUrlFormData libURLftpCommand libURLLastHTTPHeaders libURLLastRHHeaders libUrlMultipartFormAddPart libUrlMultipartFormData libURLVersion lineOffset ln ln1 localNames log log2 log10 longFilePath lower macToISO matchChunk matchText matrixMultiply max md5Digest median merge messageAuthenticationCode messageDigest millisec millisecs millisecond milliseconds min monthNames nativeCharToNum normalizeText num number numToByte numToChar numToCodepoint numToNativeChar offset open openfiles openProcesses openProcessIDs openSockets paragraphOffset paramCount param params peerAddress pendingMessages platform popStdDev populationStandardDeviation populationVariance popVariance processID random randomBytes replaceText result revCreateXMLTree revCreateXMLTreeFromFile revCurrentRecord revCurrentRecordIsFirst revCurrentRecordIsLast revDatabaseColumnCount revDatabaseColumnIsNull revDatabaseColumnLengths revDatabaseColumnNames revDatabaseColumnNamed revDatabaseColumnNumbered revDatabaseColumnTypes revDatabaseConnectResult revDatabaseCursors revDatabaseID revDatabaseTableNames revDatabaseType revDataFromQuery revdb_closeCursor revdb_columnbynumber revdb_columncount revdb_columnisnull revdb_columnlengths revdb_columnnames revdb_columntypes revdb_commit revdb_connect revdb_connections revdb_connectionerr revdb_currentrecord revdb_cursorconnection revdb_cursorerr revdb_cursors revdb_dbtype revdb_disconnect revdb_execute revdb_iseof revdb_isbof revdb_movefirst revdb_movelast revdb_movenext revdb_moveprev revdb_query revdb_querylist revdb_recordcount revdb_rollback revdb_tablenames revGetDatabaseDriverPath revNumberOfRecords revOpenDatabase revOpenDatabases revQueryDatabase revQueryDatabaseBlob revQueryResult revQueryIsAtStart revQueryIsAtEnd revUnixFromMacPath revXMLAttribute revXMLAttributes revXMLAttributeValues revXMLChildContents revXMLChildNames revXMLCreateTreeFromFileWithNamespaces revXMLCreateTreeWithNamespaces revXMLDataFromXPathQuery revXMLEvaluateXPath revXMLFirstChild revXMLMatchingNode revXMLNextSibling revXMLNodeContents revXMLNumberOfChildren revXMLParent revXMLPreviousSibling revXMLRootNode revXMLRPC_CreateRequest revXMLRPC_Documents revXMLRPC_Error revXMLRPC_GetHost revXMLRPC_GetMethod revXMLRPC_GetParam revXMLText revXMLRPC_Execute revXMLRPC_GetParamCount revXMLRPC_GetParamNode revXMLRPC_GetParamType revXMLRPC_GetPath revXMLRPC_GetPort revXMLRPC_GetProtocol revXMLRPC_GetRequest revXMLRPC_GetResponse revXMLRPC_GetSocket revXMLTree revXMLTrees revXMLValidateDTD revZipDescribeItem revZipEnumerateItems revZipOpenArchives round sampVariance sec secs seconds sentenceOffset sha1Digest shell shortFilePath sin specialFolderPath sqrt standardDeviation statRound stdDev sum sysError systemVersion tan tempName textDecode textEncode tick ticks time to tokenOffset toLower toUpper transpose truewordOffset trunc uniDecode uniEncode upper URLDecode URLEncode URLStatus uuid value variableNames variance version waitDepth weekdayNames wordOffset xsltApplyStylesheet xsltApplyStylesheetFromFile xsltLoadStylesheet xsltLoadStylesheetFromFile add breakpoint cancel clear local variable file word line folder directory URL close socket process combine constant convert create new alias folder directory decrypt delete variable word line folder directory URL dispatch divide do encrypt filter get include intersect kill libURLDownloadToFile libURLFollowHttpRedirects libURLftpUpload libURLftpUploadFile libURLresetAll libUrlSetAuthCallback libURLSetDriver libURLSetCustomHTTPHeaders libUrlSetExpect100 libURLSetFTPListCommand libURLSetFTPMode libURLSetFTPStopTime libURLSetStatusCallback load extension loadedExtensions multiply socket prepare process post seek rel relative read from process rename replace require resetAll resolve revAddXMLNode revAppendXML revCloseCursor revCloseDatabase revCommitDatabase revCopyFile revCopyFolder revCopyXMLNode revDeleteFolder revDeleteXMLNode revDeleteAllXMLTrees revDeleteXMLTree revExecuteSQL revGoURL revInsertXMLNode revMoveFolder revMoveToFirstRecord revMoveToLastRecord revMoveToNextRecord revMoveToPreviousRecord revMoveToRecord revMoveXMLNode revPutIntoXMLNode revRollBackDatabase revSetDatabaseDriverPath revSetXMLAttribute revXMLRPC_AddParam revXMLRPC_DeleteAllDocuments revXMLAddDTD revXMLRPC_Free revXMLRPC_FreeAll revXMLRPC_DeleteDocument revXMLRPC_DeleteParam revXMLRPC_SetHost revXMLRPC_SetMethod revXMLRPC_SetPort revXMLRPC_SetProtocol revXMLRPC_SetSocket revZipAddItemWithData revZipAddItemWithFile revZipAddUncompressedItemWithData revZipAddUncompressedItemWithFile revZipCancel revZipCloseArchive revZipDeleteItem revZipExtractItemToFile revZipExtractItemToVariable revZipSetProgressCallback revZipRenameItem revZipReplaceItemWithData revZipReplaceItemWithFile revZipOpenArchive send set sort split start stop subtract symmetric union unload vectorDotProduct wait write"
        },
        contains: [
          VARIABLE,
          {
            className: "keyword",
            begin: "\\bend\\sif\\b"
          },
          {
            className: "function",
            beginKeywords: "function",
            end: "$",
            contains: [
              VARIABLE,
              TITLE2,
              hljs5.APOS_STRING_MODE,
              hljs5.QUOTE_STRING_MODE,
              hljs5.BINARY_NUMBER_MODE,
              hljs5.C_NUMBER_MODE,
              TITLE1
            ]
          },
          {
            className: "function",
            begin: "\\bend\\s+",
            end: "$",
            keywords: "end",
            contains: [
              TITLE2,
              TITLE1
            ],
            relevance: 0
          },
          {
            beginKeywords: "command on",
            end: "$",
            contains: [
              VARIABLE,
              TITLE2,
              hljs5.APOS_STRING_MODE,
              hljs5.QUOTE_STRING_MODE,
              hljs5.BINARY_NUMBER_MODE,
              hljs5.C_NUMBER_MODE,
              TITLE1
            ]
          },
          {
            className: "meta",
            variants: [
              {
                begin: "<\\?(rev|lc|livecode)",
                relevance: 10
              },
              {
                begin: "<\\?"
              },
              {
                begin: "\\?>"
              }
            ]
          },
          hljs5.APOS_STRING_MODE,
          hljs5.QUOTE_STRING_MODE,
          hljs5.BINARY_NUMBER_MODE,
          hljs5.C_NUMBER_MODE,
          TITLE1
        ].concat(COMMENT_MODES),
        illegal: ";$|^\\[|^=|&|\\{"
      };
    }
    module.exports = livecodeserver;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/livescript.js
var require_livescript = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/livescript.js"(exports, module) {
    init_process_shim();
    var KEYWORDS3 = [
      "as",
      // for exports
      "in",
      "of",
      "if",
      "for",
      "while",
      "finally",
      "var",
      "new",
      "function",
      "do",
      "return",
      "void",
      "else",
      "break",
      "catch",
      "instanceof",
      "with",
      "throw",
      "case",
      "default",
      "try",
      "switch",
      "continue",
      "typeof",
      "delete",
      "let",
      "yield",
      "const",
      "class",
      // JS handles these with a special rule
      // "get",
      // "set",
      "debugger",
      "async",
      "await",
      "static",
      "import",
      "from",
      "export",
      "extends"
    ];
    var LITERALS3 = [
      "true",
      "false",
      "null",
      "undefined",
      "NaN",
      "Infinity"
    ];
    var TYPES3 = [
      "Intl",
      "DataView",
      "Number",
      "Math",
      "Date",
      "String",
      "RegExp",
      "Object",
      "Function",
      "Boolean",
      "Error",
      "Symbol",
      "Set",
      "Map",
      "WeakSet",
      "WeakMap",
      "Proxy",
      "Reflect",
      "JSON",
      "Promise",
      "Float64Array",
      "Int16Array",
      "Int32Array",
      "Int8Array",
      "Uint16Array",
      "Uint32Array",
      "Float32Array",
      "Array",
      "Uint8Array",
      "Uint8ClampedArray",
      "ArrayBuffer",
      "BigInt64Array",
      "BigUint64Array",
      "BigInt"
    ];
    var ERROR_TYPES3 = [
      "EvalError",
      "InternalError",
      "RangeError",
      "ReferenceError",
      "SyntaxError",
      "TypeError",
      "URIError"
    ];
    var BUILT_IN_GLOBALS3 = [
      "setInterval",
      "setTimeout",
      "clearInterval",
      "clearTimeout",
      "require",
      "exports",
      "eval",
      "isFinite",
      "isNaN",
      "parseFloat",
      "parseInt",
      "decodeURI",
      "decodeURIComponent",
      "encodeURI",
      "encodeURIComponent",
      "escape",
      "unescape"
    ];
    var BUILT_IN_VARIABLES3 = [
      "arguments",
      "this",
      "super",
      "console",
      "window",
      "document",
      "localStorage",
      "module",
      "global"
      // Node.js
    ];
    var BUILT_INS3 = [].concat(
      BUILT_IN_GLOBALS3,
      BUILT_IN_VARIABLES3,
      TYPES3,
      ERROR_TYPES3
    );
    function livescript(hljs5) {
      const LIVESCRIPT_BUILT_INS = [
        "npm",
        "print"
      ];
      const LIVESCRIPT_LITERALS = [
        "yes",
        "no",
        "on",
        "off",
        "it",
        "that",
        "void"
      ];
      const LIVESCRIPT_KEYWORDS = [
        "then",
        "unless",
        "until",
        "loop",
        "of",
        "by",
        "when",
        "and",
        "or",
        "is",
        "isnt",
        "not",
        "it",
        "that",
        "otherwise",
        "from",
        "to",
        "til",
        "fallthrough",
        "case",
        "enum",
        "native",
        "list",
        "map",
        "__hasProp",
        "__extends",
        "__slice",
        "__bind",
        "__indexOf"
      ];
      const KEYWORDS$1 = {
        keyword: KEYWORDS3.concat(LIVESCRIPT_KEYWORDS),
        literal: LITERALS3.concat(LIVESCRIPT_LITERALS),
        built_in: BUILT_INS3.concat(LIVESCRIPT_BUILT_INS)
      };
      const JS_IDENT_RE = "[A-Za-z$_](?:-[0-9A-Za-z$_]|[0-9A-Za-z$_])*";
      const TITLE = hljs5.inherit(hljs5.TITLE_MODE, {
        begin: JS_IDENT_RE
      });
      const SUBST = {
        className: "subst",
        begin: /#\{/,
        end: /\}/,
        keywords: KEYWORDS$1
      };
      const SUBST_SIMPLE = {
        className: "subst",
        begin: /#[A-Za-z$_]/,
        end: /(?:-[0-9A-Za-z$_]|[0-9A-Za-z$_])*/,
        keywords: KEYWORDS$1
      };
      const EXPRESSIONS = [
        hljs5.BINARY_NUMBER_MODE,
        {
          className: "number",
          begin: "(\\b0[xX][a-fA-F0-9_]+)|(\\b\\d(\\d|_\\d)*(\\.(\\d(\\d|_\\d)*)?)?(_*[eE]([-+]\\d(_\\d|\\d)*)?)?[_a-z]*)",
          relevance: 0,
          starts: {
            end: "(\\s*/)?",
            relevance: 0
          }
          // a number tries to eat the following slash to prevent treating it as a regexp
        },
        {
          className: "string",
          variants: [
            {
              begin: /'''/,
              end: /'''/,
              contains: [hljs5.BACKSLASH_ESCAPE]
            },
            {
              begin: /'/,
              end: /'/,
              contains: [hljs5.BACKSLASH_ESCAPE]
            },
            {
              begin: /"""/,
              end: /"""/,
              contains: [
                hljs5.BACKSLASH_ESCAPE,
                SUBST,
                SUBST_SIMPLE
              ]
            },
            {
              begin: /"/,
              end: /"/,
              contains: [
                hljs5.BACKSLASH_ESCAPE,
                SUBST,
                SUBST_SIMPLE
              ]
            },
            {
              begin: /\\/,
              end: /(\s|$)/,
              excludeEnd: true
            }
          ]
        },
        {
          className: "regexp",
          variants: [
            {
              begin: "//",
              end: "//[gim]*",
              contains: [
                SUBST,
                hljs5.HASH_COMMENT_MODE
              ]
            },
            {
              // regex can't start with space to parse x / 2 / 3 as two divisions
              // regex can't start with *, and it supports an "illegal" in the main mode
              begin: /\/(?![ *])(\\.|[^\\\n])*?\/[gim]*(?=\W)/
            }
          ]
        },
        {
          begin: "@" + JS_IDENT_RE
        },
        {
          begin: "``",
          end: "``",
          excludeBegin: true,
          excludeEnd: true,
          subLanguage: "javascript"
        }
      ];
      SUBST.contains = EXPRESSIONS;
      const PARAMS = {
        className: "params",
        begin: "\\(",
        returnBegin: true,
        /* We need another contained nameless mode to not have every nested
        pair of parens to be called "params" */
        contains: [
          {
            begin: /\(/,
            end: /\)/,
            keywords: KEYWORDS$1,
            contains: ["self"].concat(EXPRESSIONS)
          }
        ]
      };
      const SYMBOLS = {
        begin: "(#=>|=>|\\|>>|-?->|!->)"
      };
      return {
        name: "LiveScript",
        aliases: ["ls"],
        keywords: KEYWORDS$1,
        illegal: /\/\*/,
        contains: EXPRESSIONS.concat([
          hljs5.COMMENT("\\/\\*", "\\*\\/"),
          hljs5.HASH_COMMENT_MODE,
          SYMBOLS,
          // relevance booster
          {
            className: "function",
            contains: [
              TITLE,
              PARAMS
            ],
            returnBegin: true,
            variants: [
              {
                begin: "(" + JS_IDENT_RE + "\\s*(?:=|:=)\\s*)?(\\(.*\\)\\s*)?\\B->\\*?",
                end: "->\\*?"
              },
              {
                begin: "(" + JS_IDENT_RE + "\\s*(?:=|:=)\\s*)?!?(\\(.*\\)\\s*)?\\B[-~]{1,2}>\\*?",
                end: "[-~]{1,2}>\\*?"
              },
              {
                begin: "(" + JS_IDENT_RE + "\\s*(?:=|:=)\\s*)?(\\(.*\\)\\s*)?\\B!?[-~]{1,2}>\\*?",
                end: "!?[-~]{1,2}>\\*?"
              }
            ]
          },
          {
            className: "class",
            beginKeywords: "class",
            end: "$",
            illegal: /[:="\[\]]/,
            contains: [
              {
                beginKeywords: "extends",
                endsWithParent: true,
                illegal: /[:="\[\]]/,
                contains: [TITLE]
              },
              TITLE
            ]
          },
          {
            begin: JS_IDENT_RE + ":",
            end: ":",
            returnBegin: true,
            returnEnd: true,
            relevance: 0
          }
        ])
      };
    }
    module.exports = livescript;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/llvm.js
var require_llvm = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/llvm.js"(exports, module) {
    init_process_shim();
    function source(re2) {
      if (!re2) return null;
      if (typeof re2 === "string") return re2;
      return re2.source;
    }
    function concat(...args) {
      const joined = args.map((x2) => source(x2)).join("");
      return joined;
    }
    function llvm(hljs5) {
      const IDENT_RE3 = /([-a-zA-Z$._][\w$.-]*)/;
      const TYPE = {
        className: "type",
        begin: /\bi\d+(?=\s|\b)/
      };
      const OPERATOR = {
        className: "operator",
        relevance: 0,
        begin: /=/
      };
      const PUNCTUATION = {
        className: "punctuation",
        relevance: 0,
        begin: /,/
      };
      const NUMBER = {
        className: "number",
        variants: [
          { begin: /0[xX][a-fA-F0-9]+/ },
          { begin: /-?\d+(?:[.]\d+)?(?:[eE][-+]?\d+(?:[.]\d+)?)?/ }
        ],
        relevance: 0
      };
      const LABEL = {
        className: "symbol",
        variants: [
          { begin: /^\s*[a-z]+:/ }
          // labels
        ],
        relevance: 0
      };
      const VARIABLE = {
        className: "variable",
        variants: [
          { begin: concat(/%/, IDENT_RE3) },
          { begin: /%\d+/ },
          { begin: /#\d+/ }
        ]
      };
      const FUNCTION = {
        className: "title",
        variants: [
          { begin: concat(/@/, IDENT_RE3) },
          { begin: /@\d+/ },
          { begin: concat(/!/, IDENT_RE3) },
          { begin: concat(/!\d+/, IDENT_RE3) },
          // https://llvm.org/docs/LangRef.html#namedmetadatastructure
          // obviously a single digit can also be used in this fashion
          { begin: /!\d+/ }
        ]
      };
      return {
        name: "LLVM IR",
        // TODO: split into different categories of keywords
        keywords: "begin end true false declare define global constant private linker_private internal available_externally linkonce linkonce_odr weak weak_odr appending dllimport dllexport common default hidden protected extern_weak external thread_local zeroinitializer undef null to tail target triple datalayout volatile nuw nsw nnan ninf nsz arcp fast exact inbounds align addrspace section alias module asm sideeffect gc dbg linker_private_weak attributes blockaddress initialexec localdynamic localexec prefix unnamed_addr ccc fastcc coldcc x86_stdcallcc x86_fastcallcc arm_apcscc arm_aapcscc arm_aapcs_vfpcc ptx_device ptx_kernel intel_ocl_bicc msp430_intrcc spir_func spir_kernel x86_64_sysvcc x86_64_win64cc x86_thiscallcc cc c signext zeroext inreg sret nounwind noreturn noalias nocapture byval nest readnone readonly inlinehint noinline alwaysinline optsize ssp sspreq noredzone noimplicitfloat naked builtin cold nobuiltin noduplicate nonlazybind optnone returns_twice sanitize_address sanitize_memory sanitize_thread sspstrong uwtable returned type opaque eq ne slt sgt sle sge ult ugt ule uge oeq one olt ogt ole oge ord uno ueq une x acq_rel acquire alignstack atomic catch cleanup filter inteldialect max min monotonic nand personality release seq_cst singlethread umax umin unordered xchg add fadd sub fsub mul fmul udiv sdiv fdiv urem srem frem shl lshr ashr and or xor icmp fcmp phi call trunc zext sext fptrunc fpext uitofp sitofp fptoui fptosi inttoptr ptrtoint bitcast addrspacecast select va_arg ret br switch invoke unwind unreachable indirectbr landingpad resume malloc alloca free load store getelementptr extractelement insertelement shufflevector getresult extractvalue insertvalue atomicrmw cmpxchg fence argmemonly double",
        contains: [
          TYPE,
          // this matches "empty comments"...
          // ...because it's far more likely this is a statement terminator in
          // another language than an actual comment
          hljs5.COMMENT(/;\s*$/, null, { relevance: 0 }),
          hljs5.COMMENT(/;/, /$/),
          hljs5.QUOTE_STRING_MODE,
          {
            className: "string",
            variants: [
              // Double-quoted string
              { begin: /"/, end: /[^\\]"/ }
            ]
          },
          FUNCTION,
          PUNCTUATION,
          OPERATOR,
          VARIABLE,
          LABEL,
          NUMBER
        ]
      };
    }
    module.exports = llvm;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/lsl.js
var require_lsl = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/lsl.js"(exports, module) {
    init_process_shim();
    function lsl(hljs5) {
      var LSL_STRING_ESCAPE_CHARS = {
        className: "subst",
        begin: /\\[tn"\\]/
      };
      var LSL_STRINGS = {
        className: "string",
        begin: '"',
        end: '"',
        contains: [
          LSL_STRING_ESCAPE_CHARS
        ]
      };
      var LSL_NUMBERS = {
        className: "number",
        relevance: 0,
        begin: hljs5.C_NUMBER_RE
      };
      var LSL_CONSTANTS = {
        className: "literal",
        variants: [
          {
            begin: "\\b(PI|TWO_PI|PI_BY_TWO|DEG_TO_RAD|RAD_TO_DEG|SQRT2)\\b"
          },
          {
            begin: "\\b(XP_ERROR_(EXPERIENCES_DISABLED|EXPERIENCE_(DISABLED|SUSPENDED)|INVALID_(EXPERIENCE|PARAMETERS)|KEY_NOT_FOUND|MATURITY_EXCEEDED|NONE|NOT_(FOUND|PERMITTED(_LAND)?)|NO_EXPERIENCE|QUOTA_EXCEEDED|RETRY_UPDATE|STORAGE_EXCEPTION|STORE_DISABLED|THROTTLED|UNKNOWN_ERROR)|JSON_APPEND|STATUS_(PHYSICS|ROTATE_[XYZ]|PHANTOM|SANDBOX|BLOCK_GRAB(_OBJECT)?|(DIE|RETURN)_AT_EDGE|CAST_SHADOWS|OK|MALFORMED_PARAMS|TYPE_MISMATCH|BOUNDS_ERROR|NOT_(FOUND|SUPPORTED)|INTERNAL_ERROR|WHITELIST_FAILED)|AGENT(_(BY_(LEGACY_|USER)NAME|FLYING|ATTACHMENTS|SCRIPTED|MOUSELOOK|SITTING|ON_OBJECT|AWAY|WALKING|IN_AIR|TYPING|CROUCHING|BUSY|ALWAYS_RUN|AUTOPILOT|LIST_(PARCEL(_OWNER)?|REGION)))?|CAMERA_(PITCH|DISTANCE|BEHINDNESS_(ANGLE|LAG)|(FOCUS|POSITION)(_(THRESHOLD|LOCKED|LAG))?|FOCUS_OFFSET|ACTIVE)|ANIM_ON|LOOP|REVERSE|PING_PONG|SMOOTH|ROTATE|SCALE|ALL_SIDES|LINK_(ROOT|SET|ALL_(OTHERS|CHILDREN)|THIS)|ACTIVE|PASS(IVE|_(ALWAYS|IF_NOT_HANDLED|NEVER))|SCRIPTED|CONTROL_(FWD|BACK|(ROT_)?(LEFT|RIGHT)|UP|DOWN|(ML_)?LBUTTON)|PERMISSION_(RETURN_OBJECTS|DEBIT|OVERRIDE_ANIMATIONS|SILENT_ESTATE_MANAGEMENT|TAKE_CONTROLS|TRIGGER_ANIMATION|ATTACH|CHANGE_LINKS|(CONTROL|TRACK)_CAMERA|TELEPORT)|INVENTORY_(TEXTURE|SOUND|OBJECT|SCRIPT|LANDMARK|CLOTHING|NOTECARD|BODYPART|ANIMATION|GESTURE|ALL|NONE)|CHANGED_(INVENTORY|COLOR|SHAPE|SCALE|TEXTURE|LINK|ALLOWED_DROP|OWNER|REGION(_START)?|TELEPORT|MEDIA)|OBJECT_(CLICK_ACTION|HOVER_HEIGHT|LAST_OWNER_ID|(PHYSICS|SERVER|STREAMING)_COST|UNKNOWN_DETAIL|CHARACTER_TIME|PHANTOM|PHYSICS|TEMP_(ATTACHED|ON_REZ)|NAME|DESC|POS|PRIM_(COUNT|EQUIVALENCE)|RETURN_(PARCEL(_OWNER)?|REGION)|REZZER_KEY|ROO?T|VELOCITY|OMEGA|OWNER|GROUP(_TAG)?|CREATOR|ATTACHED_(POINT|SLOTS_AVAILABLE)|RENDER_WEIGHT|(BODY_SHAPE|PATHFINDING)_TYPE|(RUNNING|TOTAL)_SCRIPT_COUNT|TOTAL_INVENTORY_COUNT|SCRIPT_(MEMORY|TIME))|TYPE_(INTEGER|FLOAT|STRING|KEY|VECTOR|ROTATION|INVALID)|(DEBUG|PUBLIC)_CHANNEL|ATTACH_(AVATAR_CENTER|CHEST|HEAD|BACK|PELVIS|MOUTH|CHIN|NECK|NOSE|BELLY|[LR](SHOULDER|HAND|FOOT|EAR|EYE|[UL](ARM|LEG)|HIP)|(LEFT|RIGHT)_PEC|HUD_(CENTER_[12]|TOP_(RIGHT|CENTER|LEFT)|BOTTOM(_(RIGHT|LEFT))?)|[LR]HAND_RING1|TAIL_(BASE|TIP)|[LR]WING|FACE_(JAW|[LR]EAR|[LR]EYE|TOUNGE)|GROIN|HIND_[LR]FOOT)|LAND_(LEVEL|RAISE|LOWER|SMOOTH|NOISE|REVERT)|DATA_(ONLINE|NAME|BORN|SIM_(POS|STATUS|RATING)|PAYINFO)|PAYMENT_INFO_(ON_FILE|USED)|REMOTE_DATA_(CHANNEL|REQUEST|REPLY)|PSYS_(PART_(BF_(ZERO|ONE(_MINUS_(DEST_COLOR|SOURCE_(ALPHA|COLOR)))?|DEST_COLOR|SOURCE_(ALPHA|COLOR))|BLEND_FUNC_(DEST|SOURCE)|FLAGS|(START|END)_(COLOR|ALPHA|SCALE|GLOW)|MAX_AGE|(RIBBON|WIND|INTERP_(COLOR|SCALE)|BOUNCE|FOLLOW_(SRC|VELOCITY)|TARGET_(POS|LINEAR)|EMISSIVE)_MASK)|SRC_(MAX_AGE|PATTERN|ANGLE_(BEGIN|END)|BURST_(RATE|PART_COUNT|RADIUS|SPEED_(MIN|MAX))|ACCEL|TEXTURE|TARGET_KEY|OMEGA|PATTERN_(DROP|EXPLODE|ANGLE(_CONE(_EMPTY)?)?)))|VEHICLE_(REFERENCE_FRAME|TYPE_(NONE|SLED|CAR|BOAT|AIRPLANE|BALLOON)|(LINEAR|ANGULAR)_(FRICTION_TIMESCALE|MOTOR_DIRECTION)|LINEAR_MOTOR_OFFSET|HOVER_(HEIGHT|EFFICIENCY|TIMESCALE)|BUOYANCY|(LINEAR|ANGULAR)_(DEFLECTION_(EFFICIENCY|TIMESCALE)|MOTOR_(DECAY_)?TIMESCALE)|VERTICAL_ATTRACTION_(EFFICIENCY|TIMESCALE)|BANKING_(EFFICIENCY|MIX|TIMESCALE)|FLAG_(NO_DEFLECTION_UP|LIMIT_(ROLL_ONLY|MOTOR_UP)|HOVER_((WATER|TERRAIN|UP)_ONLY|GLOBAL_HEIGHT)|MOUSELOOK_(STEER|BANK)|CAMERA_DECOUPLED))|PRIM_(ALLOW_UNSIT|ALPHA_MODE(_(BLEND|EMISSIVE|MASK|NONE))?|NORMAL|SPECULAR|TYPE(_(BOX|CYLINDER|PRISM|SPHERE|TORUS|TUBE|RING|SCULPT))?|HOLE_(DEFAULT|CIRCLE|SQUARE|TRIANGLE)|MATERIAL(_(STONE|METAL|GLASS|WOOD|FLESH|PLASTIC|RUBBER))?|SHINY_(NONE|LOW|MEDIUM|HIGH)|BUMP_(NONE|BRIGHT|DARK|WOOD|BARK|BRICKS|CHECKER|CONCRETE|TILE|STONE|DISKS|GRAVEL|BLOBS|SIDING|LARGETILE|STUCCO|SUCTION|WEAVE)|TEXGEN_(DEFAULT|PLANAR)|SCRIPTED_SIT_ONLY|SCULPT_(TYPE_(SPHERE|TORUS|PLANE|CYLINDER|MASK)|FLAG_(MIRROR|INVERT))|PHYSICS(_(SHAPE_(CONVEX|NONE|PRIM|TYPE)))?|(POS|ROT)_LOCAL|SLICE|TEXT|FLEXIBLE|POINT_LIGHT|TEMP_ON_REZ|PHANTOM|POSITION|SIT_TARGET|SIZE|ROTATION|TEXTURE|NAME|OMEGA|DESC|LINK_TARGET|COLOR|BUMP_SHINY|FULLBRIGHT|TEXGEN|GLOW|MEDIA_(ALT_IMAGE_ENABLE|CONTROLS|(CURRENT|HOME)_URL|AUTO_(LOOP|PLAY|SCALE|ZOOM)|FIRST_CLICK_INTERACT|(WIDTH|HEIGHT)_PIXELS|WHITELIST(_ENABLE)?|PERMS_(INTERACT|CONTROL)|PARAM_MAX|CONTROLS_(STANDARD|MINI)|PERM_(NONE|OWNER|GROUP|ANYONE)|MAX_(URL_LENGTH|WHITELIST_(SIZE|COUNT)|(WIDTH|HEIGHT)_PIXELS)))|MASK_(BASE|OWNER|GROUP|EVERYONE|NEXT)|PERM_(TRANSFER|MODIFY|COPY|MOVE|ALL)|PARCEL_(MEDIA_COMMAND_(STOP|PAUSE|PLAY|LOOP|TEXTURE|URL|TIME|AGENT|UNLOAD|AUTO_ALIGN|TYPE|SIZE|DESC|LOOP_SET)|FLAG_(ALLOW_(FLY|(GROUP_)?SCRIPTS|LANDMARK|TERRAFORM|DAMAGE|CREATE_(GROUP_)?OBJECTS)|USE_(ACCESS_(GROUP|LIST)|BAN_LIST|LAND_PASS_LIST)|LOCAL_SOUND_ONLY|RESTRICT_PUSHOBJECT|ALLOW_(GROUP|ALL)_OBJECT_ENTRY)|COUNT_(TOTAL|OWNER|GROUP|OTHER|SELECTED|TEMP)|DETAILS_(NAME|DESC|OWNER|GROUP|AREA|ID|SEE_AVATARS))|LIST_STAT_(MAX|MIN|MEAN|MEDIAN|STD_DEV|SUM(_SQUARES)?|NUM_COUNT|GEOMETRIC_MEAN|RANGE)|PAY_(HIDE|DEFAULT)|REGION_FLAG_(ALLOW_DAMAGE|FIXED_SUN|BLOCK_TERRAFORM|SANDBOX|DISABLE_(COLLISIONS|PHYSICS)|BLOCK_FLY|ALLOW_DIRECT_TELEPORT|RESTRICT_PUSHOBJECT)|HTTP_(METHOD|MIMETYPE|BODY_(MAXLENGTH|TRUNCATED)|CUSTOM_HEADER|PRAGMA_NO_CACHE|VERBOSE_THROTTLE|VERIFY_CERT)|SIT_(INVALID_(AGENT|LINK_OBJECT)|NO(T_EXPERIENCE|_(ACCESS|EXPERIENCE_PERMISSION|SIT_TARGET)))|STRING_(TRIM(_(HEAD|TAIL))?)|CLICK_ACTION_(NONE|TOUCH|SIT|BUY|PAY|OPEN(_MEDIA)?|PLAY|ZOOM)|TOUCH_INVALID_FACE|PROFILE_(NONE|SCRIPT_MEMORY)|RC_(DATA_FLAGS|DETECT_PHANTOM|GET_(LINK_NUM|NORMAL|ROOT_KEY)|MAX_HITS|REJECT_(TYPES|AGENTS|(NON)?PHYSICAL|LAND))|RCERR_(CAST_TIME_EXCEEDED|SIM_PERF_LOW|UNKNOWN)|ESTATE_ACCESS_(ALLOWED_(AGENT|GROUP)_(ADD|REMOVE)|BANNED_AGENT_(ADD|REMOVE))|DENSITY|FRICTION|RESTITUTION|GRAVITY_MULTIPLIER|KFM_(COMMAND|CMD_(PLAY|STOP|PAUSE)|MODE|FORWARD|LOOP|PING_PONG|REVERSE|DATA|ROTATION|TRANSLATION)|ERR_(GENERIC|PARCEL_PERMISSIONS|MALFORMED_PARAMS|RUNTIME_PERMISSIONS|THROTTLED)|CHARACTER_(CMD_((SMOOTH_)?STOP|JUMP)|DESIRED_(TURN_)?SPEED|RADIUS|STAY_WITHIN_PARCEL|LENGTH|ORIENTATION|ACCOUNT_FOR_SKIPPED_FRAMES|AVOIDANCE_MODE|TYPE(_([ABCD]|NONE))?|MAX_(DECEL|TURN_RADIUS|(ACCEL|SPEED)))|PURSUIT_(OFFSET|FUZZ_FACTOR|GOAL_TOLERANCE|INTERCEPT)|REQUIRE_LINE_OF_SIGHT|FORCE_DIRECT_PATH|VERTICAL|HORIZONTAL|AVOID_(CHARACTERS|DYNAMIC_OBSTACLES|NONE)|PU_(EVADE_(HIDDEN|SPOTTED)|FAILURE_(DYNAMIC_PATHFINDING_DISABLED|INVALID_(GOAL|START)|NO_(NAVMESH|VALID_DESTINATION)|OTHER|TARGET_GONE|(PARCEL_)?UNREACHABLE)|(GOAL|SLOWDOWN_DISTANCE)_REACHED)|TRAVERSAL_TYPE(_(FAST|NONE|SLOW))?|CONTENT_TYPE_(ATOM|FORM|HTML|JSON|LLSD|RSS|TEXT|XHTML|XML)|GCNP_(RADIUS|STATIC)|(PATROL|WANDER)_PAUSE_AT_WAYPOINTS|OPT_(AVATAR|CHARACTER|EXCLUSION_VOLUME|LEGACY_LINKSET|MATERIAL_VOLUME|OTHER|STATIC_OBSTACLE|WALKABLE)|SIM_STAT_PCT_CHARS_STEPPED)\\b"
          },
          {
            begin: "\\b(FALSE|TRUE)\\b"
          },
          {
            begin: "\\b(ZERO_ROTATION)\\b"
          },
          {
            begin: "\\b(EOF|JSON_(ARRAY|DELETE|FALSE|INVALID|NULL|NUMBER|OBJECT|STRING|TRUE)|NULL_KEY|TEXTURE_(BLANK|DEFAULT|MEDIA|PLYWOOD|TRANSPARENT)|URL_REQUEST_(GRANTED|DENIED))\\b"
          },
          {
            begin: "\\b(ZERO_VECTOR|TOUCH_INVALID_(TEXCOORD|VECTOR))\\b"
          }
        ]
      };
      var LSL_FUNCTIONS = {
        className: "built_in",
        begin: "\\b(ll(AgentInExperience|(Create|DataSize|Delete|KeyCount|Keys|Read|Update)KeyValue|GetExperience(Details|ErrorMessage)|ReturnObjectsBy(ID|Owner)|Json(2List|[GS]etValue|ValueType)|Sin|Cos|Tan|Atan2|Sqrt|Pow|Abs|Fabs|Frand|Floor|Ceil|Round|Vec(Mag|Norm|Dist)|Rot(Between|2(Euler|Fwd|Left|Up))|(Euler|Axes)2Rot|Whisper|(Region|Owner)?Say|Shout|Listen(Control|Remove)?|Sensor(Repeat|Remove)?|Detected(Name|Key|Owner|Type|Pos|Vel|Grab|Rot|Group|LinkNumber)|Die|Ground|Wind|([GS]et)(AnimationOverride|MemoryLimit|PrimMediaParams|ParcelMusicURL|Object(Desc|Name)|PhysicsMaterial|Status|Scale|Color|Alpha|Texture|Pos|Rot|Force|Torque)|ResetAnimationOverride|(Scale|Offset|Rotate)Texture|(Rot)?Target(Remove)?|(Stop)?MoveToTarget|Apply(Rotational)?Impulse|Set(KeyframedMotion|ContentType|RegionPos|(Angular)?Velocity|Buoyancy|HoverHeight|ForceAndTorque|TimerEvent|ScriptState|Damage|TextureAnim|Sound(Queueing|Radius)|Vehicle(Type|(Float|Vector|Rotation)Param)|(Touch|Sit)?Text|Camera(Eye|At)Offset|PrimitiveParams|ClickAction|Link(Alpha|Color|PrimitiveParams(Fast)?|Texture(Anim)?|Camera|Media)|RemoteScriptAccessPin|PayPrice|LocalRot)|ScaleByFactor|Get((Max|Min)ScaleFactor|ClosestNavPoint|StaticPath|SimStats|Env|PrimitiveParams|Link(PrimitiveParams|Number(OfSides)?|Key|Name|Media)|HTTPHeader|FreeURLs|Object(Details|PermMask|PrimCount)|Parcel(MaxPrims|Details|Prim(Count|Owners))|Attached(List)?|(SPMax|Free|Used)Memory|Region(Name|TimeDilation|FPS|Corner|AgentCount)|Root(Position|Rotation)|UnixTime|(Parcel|Region)Flags|(Wall|GMT)clock|SimulatorHostname|BoundingBox|GeometricCenter|Creator|NumberOf(Prims|NotecardLines|Sides)|Animation(List)?|(Camera|Local)(Pos|Rot)|Vel|Accel|Omega|Time(stamp|OfDay)|(Object|CenterOf)?Mass|MassMKS|Energy|Owner|(Owner)?Key|SunDirection|Texture(Offset|Scale|Rot)|Inventory(Number|Name|Key|Type|Creator|PermMask)|Permissions(Key)?|StartParameter|List(Length|EntryType)|Date|Agent(Size|Info|Language|List)|LandOwnerAt|NotecardLine|Script(Name|State))|(Get|Reset|GetAndReset)Time|PlaySound(Slave)?|LoopSound(Master|Slave)?|(Trigger|Stop|Preload)Sound|((Get|Delete)Sub|Insert)String|To(Upper|Lower)|Give(InventoryList|Money)|RezObject|(Stop)?LookAt|Sleep|CollisionFilter|(Take|Release)Controls|DetachFromAvatar|AttachToAvatar(Temp)?|InstantMessage|(GetNext)?Email|StopHover|MinEventDelay|RotLookAt|String(Length|Trim)|(Start|Stop)Animation|TargetOmega|Request(Experience)?Permissions|(Create|Break)Link|BreakAllLinks|(Give|Remove)Inventory|Water|PassTouches|Request(Agent|Inventory)Data|TeleportAgent(Home|GlobalCoords)?|ModifyLand|CollisionSound|ResetScript|MessageLinked|PushObject|PassCollisions|AxisAngle2Rot|Rot2(Axis|Angle)|A(cos|sin)|AngleBetween|AllowInventoryDrop|SubStringIndex|List2(CSV|Integer|Json|Float|String|Key|Vector|Rot|List(Strided)?)|DeleteSubList|List(Statistics|Sort|Randomize|(Insert|Find|Replace)List)|EdgeOfWorld|AdjustSoundVolume|Key2Name|TriggerSoundLimited|EjectFromLand|(CSV|ParseString)2List|OverMyLand|SameGroup|UnSit|Ground(Slope|Normal|Contour)|GroundRepel|(Set|Remove)VehicleFlags|SitOnLink|(AvatarOn)?(Link)?SitTarget|Script(Danger|Profiler)|Dialog|VolumeDetect|ResetOtherScript|RemoteLoadScriptPin|(Open|Close)RemoteDataChannel|SendRemoteData|RemoteDataReply|(Integer|String)ToBase64|XorBase64|Log(10)?|Base64To(String|Integer)|ParseStringKeepNulls|RezAtRoot|RequestSimulatorData|ForceMouselook|(Load|Release|(E|Une)scape)URL|ParcelMedia(CommandList|Query)|ModPow|MapDestination|(RemoveFrom|AddTo|Reset)Land(Pass|Ban)List|(Set|Clear)CameraParams|HTTP(Request|Response)|TextBox|DetectedTouch(UV|Face|Pos|(N|Bin)ormal|ST)|(MD5|SHA1|DumpList2)String|Request(Secure)?URL|Clear(Prim|Link)Media|(Link)?ParticleSystem|(Get|Request)(Username|DisplayName)|RegionSayTo|CastRay|GenerateKey|TransferLindenDollars|ManageEstateAccess|(Create|Delete)Character|ExecCharacterCmd|Evade|FleeFrom|NavigateTo|PatrolPoints|Pursue|UpdateCharacter|WanderWithin))\\b"
      };
      return {
        name: "LSL (Linden Scripting Language)",
        illegal: ":",
        contains: [
          LSL_STRINGS,
          {
            className: "comment",
            variants: [
              hljs5.COMMENT("//", "$"),
              hljs5.COMMENT("/\\*", "\\*/")
            ],
            relevance: 0
          },
          LSL_NUMBERS,
          {
            className: "section",
            variants: [
              {
                begin: "\\b(state|default)\\b"
              },
              {
                begin: "\\b(state_(entry|exit)|touch(_(start|end))?|(land_)?collision(_(start|end))?|timer|listen|(no_)?sensor|control|(not_)?at_(rot_)?target|money|email|experience_permissions(_denied)?|run_time_permissions|changed|attach|dataserver|moving_(start|end)|link_message|(on|object)_rez|remote_data|http_re(sponse|quest)|path_update|transaction_result)\\b"
              }
            ]
          },
          LSL_FUNCTIONS,
          LSL_CONSTANTS,
          {
            className: "type",
            begin: "\\b(integer|float|string|key|vector|quaternion|rotation|list)\\b"
          }
        ]
      };
    }
    module.exports = lsl;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/lua.js
var require_lua = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/lua.js"(exports, module) {
    init_process_shim();
    function lua(hljs5) {
      const OPENING_LONG_BRACKET = "\\[=*\\[";
      const CLOSING_LONG_BRACKET = "\\]=*\\]";
      const LONG_BRACKETS = {
        begin: OPENING_LONG_BRACKET,
        end: CLOSING_LONG_BRACKET,
        contains: ["self"]
      };
      const COMMENTS = [
        hljs5.COMMENT("--(?!" + OPENING_LONG_BRACKET + ")", "$"),
        hljs5.COMMENT(
          "--" + OPENING_LONG_BRACKET,
          CLOSING_LONG_BRACKET,
          {
            contains: [LONG_BRACKETS],
            relevance: 10
          }
        )
      ];
      return {
        name: "Lua",
        keywords: {
          $pattern: hljs5.UNDERSCORE_IDENT_RE,
          literal: "true false nil",
          keyword: "and break do else elseif end for goto if in local not or repeat return then until while",
          built_in: (
            // Metatags and globals:
            "_G _ENV _VERSION __index __newindex __mode __call __metatable __tostring __len __gc __add __sub __mul __div __mod __pow __concat __unm __eq __lt __le assert collectgarbage dofile error getfenv getmetatable ipairs load loadfile loadstring module next pairs pcall print rawequal rawget rawset require select setfenv setmetatable tonumber tostring type unpack xpcall arg self coroutine resume yield status wrap create running debug getupvalue debug sethook getmetatable gethook setmetatable setlocal traceback setfenv getinfo setupvalue getlocal getregistry getfenv io lines write close flush open output type read stderr stdin input stdout popen tmpfile math log max acos huge ldexp pi cos tanh pow deg tan cosh sinh random randomseed frexp ceil floor rad abs sqrt modf asin min mod fmod log10 atan2 exp sin atan os exit setlocale date getenv difftime remove time clock tmpname rename execute package preload loadlib loaded loaders cpath config path seeall string sub upper len gfind rep find match char dump gmatch reverse byte format gsub lower table setn insert getn foreachi maxn foreach concat sort remove"
          )
        },
        contains: COMMENTS.concat([
          {
            className: "function",
            beginKeywords: "function",
            end: "\\)",
            contains: [
              hljs5.inherit(hljs5.TITLE_MODE, {
                begin: "([_a-zA-Z]\\w*\\.)*([_a-zA-Z]\\w*:)?[_a-zA-Z]\\w*"
              }),
              {
                className: "params",
                begin: "\\(",
                endsWithParent: true,
                contains: COMMENTS
              }
            ].concat(COMMENTS)
          },
          hljs5.C_NUMBER_MODE,
          hljs5.APOS_STRING_MODE,
          hljs5.QUOTE_STRING_MODE,
          {
            className: "string",
            begin: OPENING_LONG_BRACKET,
            end: CLOSING_LONG_BRACKET,
            contains: [LONG_BRACKETS],
            relevance: 5
          }
        ])
      };
    }
    module.exports = lua;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/makefile.js
var require_makefile = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/makefile.js"(exports, module) {
    init_process_shim();
    function makefile(hljs5) {
      const VARIABLE = {
        className: "variable",
        variants: [
          {
            begin: "\\$\\(" + hljs5.UNDERSCORE_IDENT_RE + "\\)",
            contains: [hljs5.BACKSLASH_ESCAPE]
          },
          {
            begin: /\$[@%<?\^\+\*]/
          }
        ]
      };
      const QUOTE_STRING = {
        className: "string",
        begin: /"/,
        end: /"/,
        contains: [
          hljs5.BACKSLASH_ESCAPE,
          VARIABLE
        ]
      };
      const FUNC = {
        className: "variable",
        begin: /\$\([\w-]+\s/,
        end: /\)/,
        keywords: {
          built_in: "subst patsubst strip findstring filter filter-out sort word wordlist firstword lastword dir notdir suffix basename addsuffix addprefix join wildcard realpath abspath error warning shell origin flavor foreach if or and call eval file value"
        },
        contains: [VARIABLE]
      };
      const ASSIGNMENT = {
        begin: "^" + hljs5.UNDERSCORE_IDENT_RE + "\\s*(?=[:+?]?=)"
      };
      const META = {
        className: "meta",
        begin: /^\.PHONY:/,
        end: /$/,
        keywords: {
          $pattern: /[\.\w]+/,
          "meta-keyword": ".PHONY"
        }
      };
      const TARGET = {
        className: "section",
        begin: /^[^\s]+:/,
        end: /$/,
        contains: [VARIABLE]
      };
      return {
        name: "Makefile",
        aliases: [
          "mk",
          "mak",
          "make"
        ],
        keywords: {
          $pattern: /[\w-]+/,
          keyword: "define endef undefine ifdef ifndef ifeq ifneq else endif include -include sinclude override export unexport private vpath"
        },
        contains: [
          hljs5.HASH_COMMENT_MODE,
          VARIABLE,
          QUOTE_STRING,
          FUNC,
          ASSIGNMENT,
          META,
          TARGET
        ]
      };
    }
    module.exports = makefile;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/mathematica.js
var require_mathematica = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/mathematica.js"(exports, module) {
    init_process_shim();
    var SYSTEM_SYMBOLS = [
      "AASTriangle",
      "AbelianGroup",
      "Abort",
      "AbortKernels",
      "AbortProtect",
      "AbortScheduledTask",
      "Above",
      "Abs",
      "AbsArg",
      "AbsArgPlot",
      "Absolute",
      "AbsoluteCorrelation",
      "AbsoluteCorrelationFunction",
      "AbsoluteCurrentValue",
      "AbsoluteDashing",
      "AbsoluteFileName",
      "AbsoluteOptions",
      "AbsolutePointSize",
      "AbsoluteThickness",
      "AbsoluteTime",
      "AbsoluteTiming",
      "AcceptanceThreshold",
      "AccountingForm",
      "Accumulate",
      "Accuracy",
      "AccuracyGoal",
      "ActionDelay",
      "ActionMenu",
      "ActionMenuBox",
      "ActionMenuBoxOptions",
      "Activate",
      "Active",
      "ActiveClassification",
      "ActiveClassificationObject",
      "ActiveItem",
      "ActivePrediction",
      "ActivePredictionObject",
      "ActiveStyle",
      "AcyclicGraphQ",
      "AddOnHelpPath",
      "AddSides",
      "AddTo",
      "AddToSearchIndex",
      "AddUsers",
      "AdjacencyGraph",
      "AdjacencyList",
      "AdjacencyMatrix",
      "AdjacentMeshCells",
      "AdjustmentBox",
      "AdjustmentBoxOptions",
      "AdjustTimeSeriesForecast",
      "AdministrativeDivisionData",
      "AffineHalfSpace",
      "AffineSpace",
      "AffineStateSpaceModel",
      "AffineTransform",
      "After",
      "AggregatedEntityClass",
      "AggregationLayer",
      "AircraftData",
      "AirportData",
      "AirPressureData",
      "AirTemperatureData",
      "AiryAi",
      "AiryAiPrime",
      "AiryAiZero",
      "AiryBi",
      "AiryBiPrime",
      "AiryBiZero",
      "AlgebraicIntegerQ",
      "AlgebraicNumber",
      "AlgebraicNumberDenominator",
      "AlgebraicNumberNorm",
      "AlgebraicNumberPolynomial",
      "AlgebraicNumberTrace",
      "AlgebraicRules",
      "AlgebraicRulesData",
      "Algebraics",
      "AlgebraicUnitQ",
      "Alignment",
      "AlignmentMarker",
      "AlignmentPoint",
      "All",
      "AllowAdultContent",
      "AllowedCloudExtraParameters",
      "AllowedCloudParameterExtensions",
      "AllowedDimensions",
      "AllowedFrequencyRange",
      "AllowedHeads",
      "AllowGroupClose",
      "AllowIncomplete",
      "AllowInlineCells",
      "AllowKernelInitialization",
      "AllowLooseGrammar",
      "AllowReverseGroupClose",
      "AllowScriptLevelChange",
      "AllowVersionUpdate",
      "AllTrue",
      "Alphabet",
      "AlphabeticOrder",
      "AlphabeticSort",
      "AlphaChannel",
      "AlternateImage",
      "AlternatingFactorial",
      "AlternatingGroup",
      "AlternativeHypothesis",
      "Alternatives",
      "AltitudeMethod",
      "AmbientLight",
      "AmbiguityFunction",
      "AmbiguityList",
      "Analytic",
      "AnatomyData",
      "AnatomyForm",
      "AnatomyPlot3D",
      "AnatomySkinStyle",
      "AnatomyStyling",
      "AnchoredSearch",
      "And",
      "AndersonDarlingTest",
      "AngerJ",
      "AngleBisector",
      "AngleBracket",
      "AnglePath",
      "AnglePath3D",
      "AngleVector",
      "AngularGauge",
      "Animate",
      "AnimationCycleOffset",
      "AnimationCycleRepetitions",
      "AnimationDirection",
      "AnimationDisplayTime",
      "AnimationRate",
      "AnimationRepetitions",
      "AnimationRunning",
      "AnimationRunTime",
      "AnimationTimeIndex",
      "Animator",
      "AnimatorBox",
      "AnimatorBoxOptions",
      "AnimatorElements",
      "Annotate",
      "Annotation",
      "AnnotationDelete",
      "AnnotationKeys",
      "AnnotationRules",
      "AnnotationValue",
      "Annuity",
      "AnnuityDue",
      "Annulus",
      "AnomalyDetection",
      "AnomalyDetector",
      "AnomalyDetectorFunction",
      "Anonymous",
      "Antialiasing",
      "AntihermitianMatrixQ",
      "Antisymmetric",
      "AntisymmetricMatrixQ",
      "Antonyms",
      "AnyOrder",
      "AnySubset",
      "AnyTrue",
      "Apart",
      "ApartSquareFree",
      "APIFunction",
      "Appearance",
      "AppearanceElements",
      "AppearanceRules",
      "AppellF1",
      "Append",
      "AppendCheck",
      "AppendLayer",
      "AppendTo",
      "Apply",
      "ApplySides",
      "ArcCos",
      "ArcCosh",
      "ArcCot",
      "ArcCoth",
      "ArcCsc",
      "ArcCsch",
      "ArcCurvature",
      "ARCHProcess",
      "ArcLength",
      "ArcSec",
      "ArcSech",
      "ArcSin",
      "ArcSinDistribution",
      "ArcSinh",
      "ArcTan",
      "ArcTanh",
      "Area",
      "Arg",
      "ArgMax",
      "ArgMin",
      "ArgumentCountQ",
      "ARIMAProcess",
      "ArithmeticGeometricMean",
      "ARMAProcess",
      "Around",
      "AroundReplace",
      "ARProcess",
      "Array",
      "ArrayComponents",
      "ArrayDepth",
      "ArrayFilter",
      "ArrayFlatten",
      "ArrayMesh",
      "ArrayPad",
      "ArrayPlot",
      "ArrayQ",
      "ArrayResample",
      "ArrayReshape",
      "ArrayRules",
      "Arrays",
      "Arrow",
      "Arrow3DBox",
      "ArrowBox",
      "Arrowheads",
      "ASATriangle",
      "Ask",
      "AskAppend",
      "AskConfirm",
      "AskDisplay",
      "AskedQ",
      "AskedValue",
      "AskFunction",
      "AskState",
      "AskTemplateDisplay",
      "AspectRatio",
      "AspectRatioFixed",
      "Assert",
      "AssociateTo",
      "Association",
      "AssociationFormat",
      "AssociationMap",
      "AssociationQ",
      "AssociationThread",
      "AssumeDeterministic",
      "Assuming",
      "Assumptions",
      "AstronomicalData",
      "Asymptotic",
      "AsymptoticDSolveValue",
      "AsymptoticEqual",
      "AsymptoticEquivalent",
      "AsymptoticGreater",
      "AsymptoticGreaterEqual",
      "AsymptoticIntegrate",
      "AsymptoticLess",
      "AsymptoticLessEqual",
      "AsymptoticOutputTracker",
      "AsymptoticProduct",
      "AsymptoticRSolveValue",
      "AsymptoticSolve",
      "AsymptoticSum",
      "Asynchronous",
      "AsynchronousTaskObject",
      "AsynchronousTasks",
      "Atom",
      "AtomCoordinates",
      "AtomCount",
      "AtomDiagramCoordinates",
      "AtomList",
      "AtomQ",
      "AttentionLayer",
      "Attributes",
      "Audio",
      "AudioAmplify",
      "AudioAnnotate",
      "AudioAnnotationLookup",
      "AudioBlockMap",
      "AudioCapture",
      "AudioChannelAssignment",
      "AudioChannelCombine",
      "AudioChannelMix",
      "AudioChannels",
      "AudioChannelSeparate",
      "AudioData",
      "AudioDelay",
      "AudioDelete",
      "AudioDevice",
      "AudioDistance",
      "AudioEncoding",
      "AudioFade",
      "AudioFrequencyShift",
      "AudioGenerator",
      "AudioIdentify",
      "AudioInputDevice",
      "AudioInsert",
      "AudioInstanceQ",
      "AudioIntervals",
      "AudioJoin",
      "AudioLabel",
      "AudioLength",
      "AudioLocalMeasurements",
      "AudioLooping",
      "AudioLoudness",
      "AudioMeasurements",
      "AudioNormalize",
      "AudioOutputDevice",
      "AudioOverlay",
      "AudioPad",
      "AudioPan",
      "AudioPartition",
      "AudioPause",
      "AudioPitchShift",
      "AudioPlay",
      "AudioPlot",
      "AudioQ",
      "AudioRecord",
      "AudioReplace",
      "AudioResample",
      "AudioReverb",
      "AudioReverse",
      "AudioSampleRate",
      "AudioSpectralMap",
      "AudioSpectralTransformation",
      "AudioSplit",
      "AudioStop",
      "AudioStream",
      "AudioStreams",
      "AudioTimeStretch",
      "AudioTracks",
      "AudioTrim",
      "AudioType",
      "AugmentedPolyhedron",
      "AugmentedSymmetricPolynomial",
      "Authenticate",
      "Authentication",
      "AuthenticationDialog",
      "AutoAction",
      "Autocomplete",
      "AutocompletionFunction",
      "AutoCopy",
      "AutocorrelationTest",
      "AutoDelete",
      "AutoEvaluateEvents",
      "AutoGeneratedPackage",
      "AutoIndent",
      "AutoIndentSpacings",
      "AutoItalicWords",
      "AutoloadPath",
      "AutoMatch",
      "Automatic",
      "AutomaticImageSize",
      "AutoMultiplicationSymbol",
      "AutoNumberFormatting",
      "AutoOpenNotebooks",
      "AutoOpenPalettes",
      "AutoQuoteCharacters",
      "AutoRefreshed",
      "AutoRemove",
      "AutorunSequencing",
      "AutoScaling",
      "AutoScroll",
      "AutoSpacing",
      "AutoStyleOptions",
      "AutoStyleWords",
      "AutoSubmitting",
      "Axes",
      "AxesEdge",
      "AxesLabel",
      "AxesOrigin",
      "AxesStyle",
      "AxiomaticTheory",
      "Axis",
      "BabyMonsterGroupB",
      "Back",
      "Background",
      "BackgroundAppearance",
      "BackgroundTasksSettings",
      "Backslash",
      "Backsubstitution",
      "Backward",
      "Ball",
      "Band",
      "BandpassFilter",
      "BandstopFilter",
      "BarabasiAlbertGraphDistribution",
      "BarChart",
      "BarChart3D",
      "BarcodeImage",
      "BarcodeRecognize",
      "BaringhausHenzeTest",
      "BarLegend",
      "BarlowProschanImportance",
      "BarnesG",
      "BarOrigin",
      "BarSpacing",
      "BartlettHannWindow",
      "BartlettWindow",
      "BaseDecode",
      "BaseEncode",
      "BaseForm",
      "Baseline",
      "BaselinePosition",
      "BaseStyle",
      "BasicRecurrentLayer",
      "BatchNormalizationLayer",
      "BatchSize",
      "BatesDistribution",
      "BattleLemarieWavelet",
      "BayesianMaximization",
      "BayesianMaximizationObject",
      "BayesianMinimization",
      "BayesianMinimizationObject",
      "Because",
      "BeckmannDistribution",
      "Beep",
      "Before",
      "Begin",
      "BeginDialogPacket",
      "BeginFrontEndInteractionPacket",
      "BeginPackage",
      "BellB",
      "BellY",
      "Below",
      "BenfordDistribution",
      "BeniniDistribution",
      "BenktanderGibratDistribution",
      "BenktanderWeibullDistribution",
      "BernoulliB",
      "BernoulliDistribution",
      "BernoulliGraphDistribution",
      "BernoulliProcess",
      "BernsteinBasis",
      "BesselFilterModel",
      "BesselI",
      "BesselJ",
      "BesselJZero",
      "BesselK",
      "BesselY",
      "BesselYZero",
      "Beta",
      "BetaBinomialDistribution",
      "BetaDistribution",
      "BetaNegativeBinomialDistribution",
      "BetaPrimeDistribution",
      "BetaRegularized",
      "Between",
      "BetweennessCentrality",
      "BeveledPolyhedron",
      "BezierCurve",
      "BezierCurve3DBox",
      "BezierCurve3DBoxOptions",
      "BezierCurveBox",
      "BezierCurveBoxOptions",
      "BezierFunction",
      "BilateralFilter",
      "Binarize",
      "BinaryDeserialize",
      "BinaryDistance",
      "BinaryFormat",
      "BinaryImageQ",
      "BinaryRead",
      "BinaryReadList",
      "BinarySerialize",
      "BinaryWrite",
      "BinCounts",
      "BinLists",
      "Binomial",
      "BinomialDistribution",
      "BinomialProcess",
      "BinormalDistribution",
      "BiorthogonalSplineWavelet",
      "BipartiteGraphQ",
      "BiquadraticFilterModel",
      "BirnbaumImportance",
      "BirnbaumSaundersDistribution",
      "BitAnd",
      "BitClear",
      "BitGet",
      "BitLength",
      "BitNot",
      "BitOr",
      "BitSet",
      "BitShiftLeft",
      "BitShiftRight",
      "BitXor",
      "BiweightLocation",
      "BiweightMidvariance",
      "Black",
      "BlackmanHarrisWindow",
      "BlackmanNuttallWindow",
      "BlackmanWindow",
      "Blank",
      "BlankForm",
      "BlankNullSequence",
      "BlankSequence",
      "Blend",
      "Block",
      "BlockchainAddressData",
      "BlockchainBase",
      "BlockchainBlockData",
      "BlockchainContractValue",
      "BlockchainData",
      "BlockchainGet",
      "BlockchainKeyEncode",
      "BlockchainPut",
      "BlockchainTokenData",
      "BlockchainTransaction",
      "BlockchainTransactionData",
      "BlockchainTransactionSign",
      "BlockchainTransactionSubmit",
      "BlockMap",
      "BlockRandom",
      "BlomqvistBeta",
      "BlomqvistBetaTest",
      "Blue",
      "Blur",
      "BodePlot",
      "BohmanWindow",
      "Bold",
      "Bond",
      "BondCount",
      "BondList",
      "BondQ",
      "Bookmarks",
      "Boole",
      "BooleanConsecutiveFunction",
      "BooleanConvert",
      "BooleanCountingFunction",
      "BooleanFunction",
      "BooleanGraph",
      "BooleanMaxterms",
      "BooleanMinimize",
      "BooleanMinterms",
      "BooleanQ",
      "BooleanRegion",
      "Booleans",
      "BooleanStrings",
      "BooleanTable",
      "BooleanVariables",
      "BorderDimensions",
      "BorelTannerDistribution",
      "Bottom",
      "BottomHatTransform",
      "BoundaryDiscretizeGraphics",
      "BoundaryDiscretizeRegion",
      "BoundaryMesh",
      "BoundaryMeshRegion",
      "BoundaryMeshRegionQ",
      "BoundaryStyle",
      "BoundedRegionQ",
      "BoundingRegion",
      "Bounds",
      "Box",
      "BoxBaselineShift",
      "BoxData",
      "BoxDimensions",
      "Boxed",
      "Boxes",
      "BoxForm",
      "BoxFormFormatTypes",
      "BoxFrame",
      "BoxID",
      "BoxMargins",
      "BoxMatrix",
      "BoxObject",
      "BoxRatios",
      "BoxRotation",
      "BoxRotationPoint",
      "BoxStyle",
      "BoxWhiskerChart",
      "Bra",
      "BracketingBar",
      "BraKet",
      "BrayCurtisDistance",
      "BreadthFirstScan",
      "Break",
      "BridgeData",
      "BrightnessEqualize",
      "BroadcastStationData",
      "Brown",
      "BrownForsytheTest",
      "BrownianBridgeProcess",
      "BrowserCategory",
      "BSplineBasis",
      "BSplineCurve",
      "BSplineCurve3DBox",
      "BSplineCurve3DBoxOptions",
      "BSplineCurveBox",
      "BSplineCurveBoxOptions",
      "BSplineFunction",
      "BSplineSurface",
      "BSplineSurface3DBox",
      "BSplineSurface3DBoxOptions",
      "BubbleChart",
      "BubbleChart3D",
      "BubbleScale",
      "BubbleSizes",
      "BuildingData",
      "BulletGauge",
      "BusinessDayQ",
      "ButterflyGraph",
      "ButterworthFilterModel",
      "Button",
      "ButtonBar",
      "ButtonBox",
      "ButtonBoxOptions",
      "ButtonCell",
      "ButtonContents",
      "ButtonData",
      "ButtonEvaluator",
      "ButtonExpandable",
      "ButtonFrame",
      "ButtonFunction",
      "ButtonMargins",
      "ButtonMinHeight",
      "ButtonNote",
      "ButtonNotebook",
      "ButtonSource",
      "ButtonStyle",
      "ButtonStyleMenuListing",
      "Byte",
      "ByteArray",
      "ByteArrayFormat",
      "ByteArrayQ",
      "ByteArrayToString",
      "ByteCount",
      "ByteOrdering",
      "C",
      "CachedValue",
      "CacheGraphics",
      "CachePersistence",
      "CalendarConvert",
      "CalendarData",
      "CalendarType",
      "Callout",
      "CalloutMarker",
      "CalloutStyle",
      "CallPacket",
      "CanberraDistance",
      "Cancel",
      "CancelButton",
      "CandlestickChart",
      "CanonicalGraph",
      "CanonicalizePolygon",
      "CanonicalizePolyhedron",
      "CanonicalName",
      "CanonicalWarpingCorrespondence",
      "CanonicalWarpingDistance",
      "CantorMesh",
      "CantorStaircase",
      "Cap",
      "CapForm",
      "CapitalDifferentialD",
      "Capitalize",
      "CapsuleShape",
      "CaptureRunning",
      "CardinalBSplineBasis",
      "CarlemanLinearize",
      "CarmichaelLambda",
      "CaseOrdering",
      "Cases",
      "CaseSensitive",
      "Cashflow",
      "Casoratian",
      "Catalan",
      "CatalanNumber",
      "Catch",
      "CategoricalDistribution",
      "Catenate",
      "CatenateLayer",
      "CauchyDistribution",
      "CauchyWindow",
      "CayleyGraph",
      "CDF",
      "CDFDeploy",
      "CDFInformation",
      "CDFWavelet",
      "Ceiling",
      "CelestialSystem",
      "Cell",
      "CellAutoOverwrite",
      "CellBaseline",
      "CellBoundingBox",
      "CellBracketOptions",
      "CellChangeTimes",
      "CellContents",
      "CellContext",
      "CellDingbat",
      "CellDynamicExpression",
      "CellEditDuplicate",
      "CellElementsBoundingBox",
      "CellElementSpacings",
      "CellEpilog",
      "CellEvaluationDuplicate",
      "CellEvaluationFunction",
      "CellEvaluationLanguage",
      "CellEventActions",
      "CellFrame",
      "CellFrameColor",
      "CellFrameLabelMargins",
      "CellFrameLabels",
      "CellFrameMargins",
      "CellGroup",
      "CellGroupData",
      "CellGrouping",
      "CellGroupingRules",
      "CellHorizontalScrolling",
      "CellID",
      "CellLabel",
      "CellLabelAutoDelete",
      "CellLabelMargins",
      "CellLabelPositioning",
      "CellLabelStyle",
      "CellLabelTemplate",
      "CellMargins",
      "CellObject",
      "CellOpen",
      "CellPrint",
      "CellProlog",
      "Cells",
      "CellSize",
      "CellStyle",
      "CellTags",
      "CellularAutomaton",
      "CensoredDistribution",
      "Censoring",
      "Center",
      "CenterArray",
      "CenterDot",
      "CentralFeature",
      "CentralMoment",
      "CentralMomentGeneratingFunction",
      "Cepstrogram",
      "CepstrogramArray",
      "CepstrumArray",
      "CForm",
      "ChampernowneNumber",
      "ChangeOptions",
      "ChannelBase",
      "ChannelBrokerAction",
      "ChannelDatabin",
      "ChannelHistoryLength",
      "ChannelListen",
      "ChannelListener",
      "ChannelListeners",
      "ChannelListenerWait",
      "ChannelObject",
      "ChannelPreSendFunction",
      "ChannelReceiverFunction",
      "ChannelSend",
      "ChannelSubscribers",
      "ChanVeseBinarize",
      "Character",
      "CharacterCounts",
      "CharacterEncoding",
      "CharacterEncodingsPath",
      "CharacteristicFunction",
      "CharacteristicPolynomial",
      "CharacterName",
      "CharacterNormalize",
      "CharacterRange",
      "Characters",
      "ChartBaseStyle",
      "ChartElementData",
      "ChartElementDataFunction",
      "ChartElementFunction",
      "ChartElements",
      "ChartLabels",
      "ChartLayout",
      "ChartLegends",
      "ChartStyle",
      "Chebyshev1FilterModel",
      "Chebyshev2FilterModel",
      "ChebyshevDistance",
      "ChebyshevT",
      "ChebyshevU",
      "Check",
      "CheckAbort",
      "CheckAll",
      "Checkbox",
      "CheckboxBar",
      "CheckboxBox",
      "CheckboxBoxOptions",
      "ChemicalData",
      "ChessboardDistance",
      "ChiDistribution",
      "ChineseRemainder",
      "ChiSquareDistribution",
      "ChoiceButtons",
      "ChoiceDialog",
      "CholeskyDecomposition",
      "Chop",
      "ChromaticityPlot",
      "ChromaticityPlot3D",
      "ChromaticPolynomial",
      "Circle",
      "CircleBox",
      "CircleDot",
      "CircleMinus",
      "CirclePlus",
      "CirclePoints",
      "CircleThrough",
      "CircleTimes",
      "CirculantGraph",
      "CircularOrthogonalMatrixDistribution",
      "CircularQuaternionMatrixDistribution",
      "CircularRealMatrixDistribution",
      "CircularSymplecticMatrixDistribution",
      "CircularUnitaryMatrixDistribution",
      "Circumsphere",
      "CityData",
      "ClassifierFunction",
      "ClassifierInformation",
      "ClassifierMeasurements",
      "ClassifierMeasurementsObject",
      "Classify",
      "ClassPriors",
      "Clear",
      "ClearAll",
      "ClearAttributes",
      "ClearCookies",
      "ClearPermissions",
      "ClearSystemCache",
      "ClebschGordan",
      "ClickPane",
      "Clip",
      "ClipboardNotebook",
      "ClipFill",
      "ClippingStyle",
      "ClipPlanes",
      "ClipPlanesStyle",
      "ClipRange",
      "Clock",
      "ClockGauge",
      "ClockwiseContourIntegral",
      "Close",
      "Closed",
      "CloseKernels",
      "ClosenessCentrality",
      "Closing",
      "ClosingAutoSave",
      "ClosingEvent",
      "ClosingSaveDialog",
      "CloudAccountData",
      "CloudBase",
      "CloudConnect",
      "CloudConnections",
      "CloudDeploy",
      "CloudDirectory",
      "CloudDisconnect",
      "CloudEvaluate",
      "CloudExport",
      "CloudExpression",
      "CloudExpressions",
      "CloudFunction",
      "CloudGet",
      "CloudImport",
      "CloudLoggingData",
      "CloudObject",
      "CloudObjectInformation",
      "CloudObjectInformationData",
      "CloudObjectNameFormat",
      "CloudObjects",
      "CloudObjectURLType",
      "CloudPublish",
      "CloudPut",
      "CloudRenderingMethod",
      "CloudSave",
      "CloudShare",
      "CloudSubmit",
      "CloudSymbol",
      "CloudUnshare",
      "CloudUserID",
      "ClusterClassify",
      "ClusterDissimilarityFunction",
      "ClusteringComponents",
      "ClusteringTree",
      "CMYKColor",
      "Coarse",
      "CodeAssistOptions",
      "Coefficient",
      "CoefficientArrays",
      "CoefficientDomain",
      "CoefficientList",
      "CoefficientRules",
      "CoifletWavelet",
      "Collect",
      "Colon",
      "ColonForm",
      "ColorBalance",
      "ColorCombine",
      "ColorConvert",
      "ColorCoverage",
      "ColorData",
      "ColorDataFunction",
      "ColorDetect",
      "ColorDistance",
      "ColorFunction",
      "ColorFunctionScaling",
      "Colorize",
      "ColorNegate",
      "ColorOutput",
      "ColorProfileData",
      "ColorQ",
      "ColorQuantize",
      "ColorReplace",
      "ColorRules",
      "ColorSelectorSettings",
      "ColorSeparate",
      "ColorSetter",
      "ColorSetterBox",
      "ColorSetterBoxOptions",
      "ColorSlider",
      "ColorsNear",
      "ColorSpace",
      "ColorToneMapping",
      "Column",
      "ColumnAlignments",
      "ColumnBackgrounds",
      "ColumnForm",
      "ColumnLines",
      "ColumnsEqual",
      "ColumnSpacings",
      "ColumnWidths",
      "CombinedEntityClass",
      "CombinerFunction",
      "CometData",
      "CommonDefaultFormatTypes",
      "Commonest",
      "CommonestFilter",
      "CommonName",
      "CommonUnits",
      "CommunityBoundaryStyle",
      "CommunityGraphPlot",
      "CommunityLabels",
      "CommunityRegionStyle",
      "CompanyData",
      "CompatibleUnitQ",
      "CompilationOptions",
      "CompilationTarget",
      "Compile",
      "Compiled",
      "CompiledCodeFunction",
      "CompiledFunction",
      "CompilerOptions",
      "Complement",
      "ComplementedEntityClass",
      "CompleteGraph",
      "CompleteGraphQ",
      "CompleteKaryTree",
      "CompletionsListPacket",
      "Complex",
      "ComplexContourPlot",
      "Complexes",
      "ComplexExpand",
      "ComplexInfinity",
      "ComplexityFunction",
      "ComplexListPlot",
      "ComplexPlot",
      "ComplexPlot3D",
      "ComplexRegionPlot",
      "ComplexStreamPlot",
      "ComplexVectorPlot",
      "ComponentMeasurements",
      "ComponentwiseContextMenu",
      "Compose",
      "ComposeList",
      "ComposeSeries",
      "CompositeQ",
      "Composition",
      "CompoundElement",
      "CompoundExpression",
      "CompoundPoissonDistribution",
      "CompoundPoissonProcess",
      "CompoundRenewalProcess",
      "Compress",
      "CompressedData",
      "CompressionLevel",
      "ComputeUncertainty",
      "Condition",
      "ConditionalExpression",
      "Conditioned",
      "Cone",
      "ConeBox",
      "ConfidenceLevel",
      "ConfidenceRange",
      "ConfidenceTransform",
      "ConfigurationPath",
      "ConformAudio",
      "ConformImages",
      "Congruent",
      "ConicHullRegion",
      "ConicHullRegion3DBox",
      "ConicHullRegionBox",
      "ConicOptimization",
      "Conjugate",
      "ConjugateTranspose",
      "Conjunction",
      "Connect",
      "ConnectedComponents",
      "ConnectedGraphComponents",
      "ConnectedGraphQ",
      "ConnectedMeshComponents",
      "ConnectedMoleculeComponents",
      "ConnectedMoleculeQ",
      "ConnectionSettings",
      "ConnectLibraryCallbackFunction",
      "ConnectSystemModelComponents",
      "ConnesWindow",
      "ConoverTest",
      "ConsoleMessage",
      "ConsoleMessagePacket",
      "Constant",
      "ConstantArray",
      "ConstantArrayLayer",
      "ConstantImage",
      "ConstantPlusLayer",
      "ConstantRegionQ",
      "Constants",
      "ConstantTimesLayer",
      "ConstellationData",
      "ConstrainedMax",
      "ConstrainedMin",
      "Construct",
      "Containing",
      "ContainsAll",
      "ContainsAny",
      "ContainsExactly",
      "ContainsNone",
      "ContainsOnly",
      "ContentFieldOptions",
      "ContentLocationFunction",
      "ContentObject",
      "ContentPadding",
      "ContentsBoundingBox",
      "ContentSelectable",
      "ContentSize",
      "Context",
      "ContextMenu",
      "Contexts",
      "ContextToFileName",
      "Continuation",
      "Continue",
      "ContinuedFraction",
      "ContinuedFractionK",
      "ContinuousAction",
      "ContinuousMarkovProcess",
      "ContinuousTask",
      "ContinuousTimeModelQ",
      "ContinuousWaveletData",
      "ContinuousWaveletTransform",
      "ContourDetect",
      "ContourGraphics",
      "ContourIntegral",
      "ContourLabels",
      "ContourLines",
      "ContourPlot",
      "ContourPlot3D",
      "Contours",
      "ContourShading",
      "ContourSmoothing",
      "ContourStyle",
      "ContraharmonicMean",
      "ContrastiveLossLayer",
      "Control",
      "ControlActive",
      "ControlAlignment",
      "ControlGroupContentsBox",
      "ControllabilityGramian",
      "ControllabilityMatrix",
      "ControllableDecomposition",
      "ControllableModelQ",
      "ControllerDuration",
      "ControllerInformation",
      "ControllerInformationData",
      "ControllerLinking",
      "ControllerManipulate",
      "ControllerMethod",
      "ControllerPath",
      "ControllerState",
      "ControlPlacement",
      "ControlsRendering",
      "ControlType",
      "Convergents",
      "ConversionOptions",
      "ConversionRules",
      "ConvertToBitmapPacket",
      "ConvertToPostScript",
      "ConvertToPostScriptPacket",
      "ConvexHullMesh",
      "ConvexPolygonQ",
      "ConvexPolyhedronQ",
      "ConvolutionLayer",
      "Convolve",
      "ConwayGroupCo1",
      "ConwayGroupCo2",
      "ConwayGroupCo3",
      "CookieFunction",
      "Cookies",
      "CoordinateBoundingBox",
      "CoordinateBoundingBoxArray",
      "CoordinateBounds",
      "CoordinateBoundsArray",
      "CoordinateChartData",
      "CoordinatesToolOptions",
      "CoordinateTransform",
      "CoordinateTransformData",
      "CoprimeQ",
      "Coproduct",
      "CopulaDistribution",
      "Copyable",
      "CopyDatabin",
      "CopyDirectory",
      "CopyFile",
      "CopyTag",
      "CopyToClipboard",
      "CornerFilter",
      "CornerNeighbors",
      "Correlation",
      "CorrelationDistance",
      "CorrelationFunction",
      "CorrelationTest",
      "Cos",
      "Cosh",
      "CoshIntegral",
      "CosineDistance",
      "CosineWindow",
      "CosIntegral",
      "Cot",
      "Coth",
      "Count",
      "CountDistinct",
      "CountDistinctBy",
      "CounterAssignments",
      "CounterBox",
      "CounterBoxOptions",
      "CounterClockwiseContourIntegral",
      "CounterEvaluator",
      "CounterFunction",
      "CounterIncrements",
      "CounterStyle",
      "CounterStyleMenuListing",
      "CountRoots",
      "CountryData",
      "Counts",
      "CountsBy",
      "Covariance",
      "CovarianceEstimatorFunction",
      "CovarianceFunction",
      "CoxianDistribution",
      "CoxIngersollRossProcess",
      "CoxModel",
      "CoxModelFit",
      "CramerVonMisesTest",
      "CreateArchive",
      "CreateCellID",
      "CreateChannel",
      "CreateCloudExpression",
      "CreateDatabin",
      "CreateDataStructure",
      "CreateDataSystemModel",
      "CreateDialog",
      "CreateDirectory",
      "CreateDocument",
      "CreateFile",
      "CreateIntermediateDirectories",
      "CreateManagedLibraryExpression",
      "CreateNotebook",
      "CreatePacletArchive",
      "CreatePalette",
      "CreatePalettePacket",
      "CreatePermissionsGroup",
      "CreateScheduledTask",
      "CreateSearchIndex",
      "CreateSystemModel",
      "CreateTemporary",
      "CreateUUID",
      "CreateWindow",
      "CriterionFunction",
      "CriticalityFailureImportance",
      "CriticalitySuccessImportance",
      "CriticalSection",
      "Cross",
      "CrossEntropyLossLayer",
      "CrossingCount",
      "CrossingDetect",
      "CrossingPolygon",
      "CrossMatrix",
      "Csc",
      "Csch",
      "CTCLossLayer",
      "Cube",
      "CubeRoot",
      "Cubics",
      "Cuboid",
      "CuboidBox",
      "Cumulant",
      "CumulantGeneratingFunction",
      "Cup",
      "CupCap",
      "Curl",
      "CurlyDoubleQuote",
      "CurlyQuote",
      "CurrencyConvert",
      "CurrentDate",
      "CurrentImage",
      "CurrentlySpeakingPacket",
      "CurrentNotebookImage",
      "CurrentScreenImage",
      "CurrentValue",
      "Curry",
      "CurryApplied",
      "CurvatureFlowFilter",
      "CurveClosed",
      "Cyan",
      "CycleGraph",
      "CycleIndexPolynomial",
      "Cycles",
      "CyclicGroup",
      "Cyclotomic",
      "Cylinder",
      "CylinderBox",
      "CylindricalDecomposition",
      "D",
      "DagumDistribution",
      "DamData",
      "DamerauLevenshteinDistance",
      "DampingFactor",
      "Darker",
      "Dashed",
      "Dashing",
      "DatabaseConnect",
      "DatabaseDisconnect",
      "DatabaseReference",
      "Databin",
      "DatabinAdd",
      "DatabinRemove",
      "Databins",
      "DatabinUpload",
      "DataCompression",
      "DataDistribution",
      "DataRange",
      "DataReversed",
      "Dataset",
      "DatasetDisplayPanel",
      "DataStructure",
      "DataStructureQ",
      "Date",
      "DateBounds",
      "Dated",
      "DateDelimiters",
      "DateDifference",
      "DatedUnit",
      "DateFormat",
      "DateFunction",
      "DateHistogram",
      "DateInterval",
      "DateList",
      "DateListLogPlot",
      "DateListPlot",
      "DateListStepPlot",
      "DateObject",
      "DateObjectQ",
      "DateOverlapsQ",
      "DatePattern",
      "DatePlus",
      "DateRange",
      "DateReduction",
      "DateString",
      "DateTicksFormat",
      "DateValue",
      "DateWithinQ",
      "DaubechiesWavelet",
      "DavisDistribution",
      "DawsonF",
      "DayCount",
      "DayCountConvention",
      "DayHemisphere",
      "DaylightQ",
      "DayMatchQ",
      "DayName",
      "DayNightTerminator",
      "DayPlus",
      "DayRange",
      "DayRound",
      "DeBruijnGraph",
      "DeBruijnSequence",
      "Debug",
      "DebugTag",
      "Decapitalize",
      "Decimal",
      "DecimalForm",
      "DeclareKnownSymbols",
      "DeclarePackage",
      "Decompose",
      "DeconvolutionLayer",
      "Decrement",
      "Decrypt",
      "DecryptFile",
      "DedekindEta",
      "DeepSpaceProbeData",
      "Default",
      "DefaultAxesStyle",
      "DefaultBaseStyle",
      "DefaultBoxStyle",
      "DefaultButton",
      "DefaultColor",
      "DefaultControlPlacement",
      "DefaultDuplicateCellStyle",
      "DefaultDuration",
      "DefaultElement",
      "DefaultFaceGridsStyle",
      "DefaultFieldHintStyle",
      "DefaultFont",
      "DefaultFontProperties",
      "DefaultFormatType",
      "DefaultFormatTypeForStyle",
      "DefaultFrameStyle",
      "DefaultFrameTicksStyle",
      "DefaultGridLinesStyle",
      "DefaultInlineFormatType",
      "DefaultInputFormatType",
      "DefaultLabelStyle",
      "DefaultMenuStyle",
      "DefaultNaturalLanguage",
      "DefaultNewCellStyle",
      "DefaultNewInlineCellStyle",
      "DefaultNotebook",
      "DefaultOptions",
      "DefaultOutputFormatType",
      "DefaultPrintPrecision",
      "DefaultStyle",
      "DefaultStyleDefinitions",
      "DefaultTextFormatType",
      "DefaultTextInlineFormatType",
      "DefaultTicksStyle",
      "DefaultTooltipStyle",
      "DefaultValue",
      "DefaultValues",
      "Defer",
      "DefineExternal",
      "DefineInputStreamMethod",
      "DefineOutputStreamMethod",
      "DefineResourceFunction",
      "Definition",
      "Degree",
      "DegreeCentrality",
      "DegreeGraphDistribution",
      "DegreeLexicographic",
      "DegreeReverseLexicographic",
      "DEigensystem",
      "DEigenvalues",
      "Deinitialization",
      "Del",
      "DelaunayMesh",
      "Delayed",
      "Deletable",
      "Delete",
      "DeleteAnomalies",
      "DeleteBorderComponents",
      "DeleteCases",
      "DeleteChannel",
      "DeleteCloudExpression",
      "DeleteContents",
      "DeleteDirectory",
      "DeleteDuplicates",
      "DeleteDuplicatesBy",
      "DeleteFile",
      "DeleteMissing",
      "DeleteObject",
      "DeletePermissionsKey",
      "DeleteSearchIndex",
      "DeleteSmallComponents",
      "DeleteStopwords",
      "DeleteWithContents",
      "DeletionWarning",
      "DelimitedArray",
      "DelimitedSequence",
      "Delimiter",
      "DelimiterFlashTime",
      "DelimiterMatching",
      "Delimiters",
      "DeliveryFunction",
      "Dendrogram",
      "Denominator",
      "DensityGraphics",
      "DensityHistogram",
      "DensityPlot",
      "DensityPlot3D",
      "DependentVariables",
      "Deploy",
      "Deployed",
      "Depth",
      "DepthFirstScan",
      "Derivative",
      "DerivativeFilter",
      "DerivedKey",
      "DescriptorStateSpace",
      "DesignMatrix",
      "DestroyAfterEvaluation",
      "Det",
      "DeviceClose",
      "DeviceConfigure",
      "DeviceExecute",
      "DeviceExecuteAsynchronous",
      "DeviceObject",
      "DeviceOpen",
      "DeviceOpenQ",
      "DeviceRead",
      "DeviceReadBuffer",
      "DeviceReadLatest",
      "DeviceReadList",
      "DeviceReadTimeSeries",
      "Devices",
      "DeviceStreams",
      "DeviceWrite",
      "DeviceWriteBuffer",
      "DGaussianWavelet",
      "DiacriticalPositioning",
      "Diagonal",
      "DiagonalizableMatrixQ",
      "DiagonalMatrix",
      "DiagonalMatrixQ",
      "Dialog",
      "DialogIndent",
      "DialogInput",
      "DialogLevel",
      "DialogNotebook",
      "DialogProlog",
      "DialogReturn",
      "DialogSymbols",
      "Diamond",
      "DiamondMatrix",
      "DiceDissimilarity",
      "DictionaryLookup",
      "DictionaryWordQ",
      "DifferenceDelta",
      "DifferenceOrder",
      "DifferenceQuotient",
      "DifferenceRoot",
      "DifferenceRootReduce",
      "Differences",
      "DifferentialD",
      "DifferentialRoot",
      "DifferentialRootReduce",
      "DifferentiatorFilter",
      "DigitalSignature",
      "DigitBlock",
      "DigitBlockMinimum",
      "DigitCharacter",
      "DigitCount",
      "DigitQ",
      "DihedralAngle",
      "DihedralGroup",
      "Dilation",
      "DimensionalCombinations",
      "DimensionalMeshComponents",
      "DimensionReduce",
      "DimensionReducerFunction",
      "DimensionReduction",
      "Dimensions",
      "DiracComb",
      "DiracDelta",
      "DirectedEdge",
      "DirectedEdges",
      "DirectedGraph",
      "DirectedGraphQ",
      "DirectedInfinity",
      "Direction",
      "Directive",
      "Directory",
      "DirectoryName",
      "DirectoryQ",
      "DirectoryStack",
      "DirichletBeta",
      "DirichletCharacter",
      "DirichletCondition",
      "DirichletConvolve",
      "DirichletDistribution",
      "DirichletEta",
      "DirichletL",
      "DirichletLambda",
      "DirichletTransform",
      "DirichletWindow",
      "DisableConsolePrintPacket",
      "DisableFormatting",
      "DiscreteAsymptotic",
      "DiscreteChirpZTransform",
      "DiscreteConvolve",
      "DiscreteDelta",
      "DiscreteHadamardTransform",
      "DiscreteIndicator",
      "DiscreteLimit",
      "DiscreteLQEstimatorGains",
      "DiscreteLQRegulatorGains",
      "DiscreteLyapunovSolve",
      "DiscreteMarkovProcess",
      "DiscreteMaxLimit",
      "DiscreteMinLimit",
      "DiscretePlot",
      "DiscretePlot3D",
      "DiscreteRatio",
      "DiscreteRiccatiSolve",
      "DiscreteShift",
      "DiscreteTimeModelQ",
      "DiscreteUniformDistribution",
      "DiscreteVariables",
      "DiscreteWaveletData",
      "DiscreteWaveletPacketTransform",
      "DiscreteWaveletTransform",
      "DiscretizeGraphics",
      "DiscretizeRegion",
      "Discriminant",
      "DisjointQ",
      "Disjunction",
      "Disk",
      "DiskBox",
      "DiskMatrix",
      "DiskSegment",
      "Dispatch",
      "DispatchQ",
      "DispersionEstimatorFunction",
      "Display",
      "DisplayAllSteps",
      "DisplayEndPacket",
      "DisplayFlushImagePacket",
      "DisplayForm",
      "DisplayFunction",
      "DisplayPacket",
      "DisplayRules",
      "DisplaySetSizePacket",
      "DisplayString",
      "DisplayTemporary",
      "DisplayWith",
      "DisplayWithRef",
      "DisplayWithVariable",
      "DistanceFunction",
      "DistanceMatrix",
      "DistanceTransform",
      "Distribute",
      "Distributed",
      "DistributedContexts",
      "DistributeDefinitions",
      "DistributionChart",
      "DistributionDomain",
      "DistributionFitTest",
      "DistributionParameterAssumptions",
      "DistributionParameterQ",
      "Dithering",
      "Div",
      "Divergence",
      "Divide",
      "DivideBy",
      "Dividers",
      "DivideSides",
      "Divisible",
      "Divisors",
      "DivisorSigma",
      "DivisorSum",
      "DMSList",
      "DMSString",
      "Do",
      "DockedCells",
      "DocumentGenerator",
      "DocumentGeneratorInformation",
      "DocumentGeneratorInformationData",
      "DocumentGenerators",
      "DocumentNotebook",
      "DocumentWeightingRules",
      "Dodecahedron",
      "DomainRegistrationInformation",
      "DominantColors",
      "DOSTextFormat",
      "Dot",
      "DotDashed",
      "DotEqual",
      "DotLayer",
      "DotPlusLayer",
      "Dotted",
      "DoubleBracketingBar",
      "DoubleContourIntegral",
      "DoubleDownArrow",
      "DoubleLeftArrow",
      "DoubleLeftRightArrow",
      "DoubleLeftTee",
      "DoubleLongLeftArrow",
      "DoubleLongLeftRightArrow",
      "DoubleLongRightArrow",
      "DoubleRightArrow",
      "DoubleRightTee",
      "DoubleUpArrow",
      "DoubleUpDownArrow",
      "DoubleVerticalBar",
      "DoublyInfinite",
      "Down",
      "DownArrow",
      "DownArrowBar",
      "DownArrowUpArrow",
      "DownLeftRightVector",
      "DownLeftTeeVector",
      "DownLeftVector",
      "DownLeftVectorBar",
      "DownRightTeeVector",
      "DownRightVector",
      "DownRightVectorBar",
      "Downsample",
      "DownTee",
      "DownTeeArrow",
      "DownValues",
      "DragAndDrop",
      "DrawEdges",
      "DrawFrontFaces",
      "DrawHighlighted",
      "Drop",
      "DropoutLayer",
      "DSolve",
      "DSolveValue",
      "Dt",
      "DualLinearProgramming",
      "DualPolyhedron",
      "DualSystemsModel",
      "DumpGet",
      "DumpSave",
      "DuplicateFreeQ",
      "Duration",
      "Dynamic",
      "DynamicBox",
      "DynamicBoxOptions",
      "DynamicEvaluationTimeout",
      "DynamicGeoGraphics",
      "DynamicImage",
      "DynamicLocation",
      "DynamicModule",
      "DynamicModuleBox",
      "DynamicModuleBoxOptions",
      "DynamicModuleParent",
      "DynamicModuleValues",
      "DynamicName",
      "DynamicNamespace",
      "DynamicReference",
      "DynamicSetting",
      "DynamicUpdating",
      "DynamicWrapper",
      "DynamicWrapperBox",
      "DynamicWrapperBoxOptions",
      "E",
      "EarthImpactData",
      "EarthquakeData",
      "EccentricityCentrality",
      "Echo",
      "EchoFunction",
      "EclipseType",
      "EdgeAdd",
      "EdgeBetweennessCentrality",
      "EdgeCapacity",
      "EdgeCapForm",
      "EdgeColor",
      "EdgeConnectivity",
      "EdgeContract",
      "EdgeCost",
      "EdgeCount",
      "EdgeCoverQ",
      "EdgeCycleMatrix",
      "EdgeDashing",
      "EdgeDelete",
      "EdgeDetect",
      "EdgeForm",
      "EdgeIndex",
      "EdgeJoinForm",
      "EdgeLabeling",
      "EdgeLabels",
      "EdgeLabelStyle",
      "EdgeList",
      "EdgeOpacity",
      "EdgeQ",
      "EdgeRenderingFunction",
      "EdgeRules",
      "EdgeShapeFunction",
      "EdgeStyle",
      "EdgeTaggedGraph",
      "EdgeTaggedGraphQ",
      "EdgeTags",
      "EdgeThickness",
      "EdgeWeight",
      "EdgeWeightedGraphQ",
      "Editable",
      "EditButtonSettings",
      "EditCellTagsSettings",
      "EditDistance",
      "EffectiveInterest",
      "Eigensystem",
      "Eigenvalues",
      "EigenvectorCentrality",
      "Eigenvectors",
      "Element",
      "ElementData",
      "ElementwiseLayer",
      "ElidedForms",
      "Eliminate",
      "EliminationOrder",
      "Ellipsoid",
      "EllipticE",
      "EllipticExp",
      "EllipticExpPrime",
      "EllipticF",
      "EllipticFilterModel",
      "EllipticK",
      "EllipticLog",
      "EllipticNomeQ",
      "EllipticPi",
      "EllipticReducedHalfPeriods",
      "EllipticTheta",
      "EllipticThetaPrime",
      "EmbedCode",
      "EmbeddedHTML",
      "EmbeddedService",
      "EmbeddingLayer",
      "EmbeddingObject",
      "EmitSound",
      "EmphasizeSyntaxErrors",
      "EmpiricalDistribution",
      "Empty",
      "EmptyGraphQ",
      "EmptyRegion",
      "EnableConsolePrintPacket",
      "Enabled",
      "Encode",
      "Encrypt",
      "EncryptedObject",
      "EncryptFile",
      "End",
      "EndAdd",
      "EndDialogPacket",
      "EndFrontEndInteractionPacket",
      "EndOfBuffer",
      "EndOfFile",
      "EndOfLine",
      "EndOfString",
      "EndPackage",
      "EngineEnvironment",
      "EngineeringForm",
      "Enter",
      "EnterExpressionPacket",
      "EnterTextPacket",
      "Entity",
      "EntityClass",
      "EntityClassList",
      "EntityCopies",
      "EntityFunction",
      "EntityGroup",
      "EntityInstance",
      "EntityList",
      "EntityPrefetch",
      "EntityProperties",
      "EntityProperty",
      "EntityPropertyClass",
      "EntityRegister",
      "EntityStore",
      "EntityStores",
      "EntityTypeName",
      "EntityUnregister",
      "EntityValue",
      "Entropy",
      "EntropyFilter",
      "Environment",
      "Epilog",
      "EpilogFunction",
      "Equal",
      "EqualColumns",
      "EqualRows",
      "EqualTilde",
      "EqualTo",
      "EquatedTo",
      "Equilibrium",
      "EquirippleFilterKernel",
      "Equivalent",
      "Erf",
      "Erfc",
      "Erfi",
      "ErlangB",
      "ErlangC",
      "ErlangDistribution",
      "Erosion",
      "ErrorBox",
      "ErrorBoxOptions",
      "ErrorNorm",
      "ErrorPacket",
      "ErrorsDialogSettings",
      "EscapeRadius",
      "EstimatedBackground",
      "EstimatedDistribution",
      "EstimatedProcess",
      "EstimatorGains",
      "EstimatorRegulator",
      "EuclideanDistance",
      "EulerAngles",
      "EulerCharacteristic",
      "EulerE",
      "EulerGamma",
      "EulerianGraphQ",
      "EulerMatrix",
      "EulerPhi",
      "Evaluatable",
      "Evaluate",
      "Evaluated",
      "EvaluatePacket",
      "EvaluateScheduledTask",
      "EvaluationBox",
      "EvaluationCell",
      "EvaluationCompletionAction",
      "EvaluationData",
      "EvaluationElements",
      "EvaluationEnvironment",
      "EvaluationMode",
      "EvaluationMonitor",
      "EvaluationNotebook",
      "EvaluationObject",
      "EvaluationOrder",
      "Evaluator",
      "EvaluatorNames",
      "EvenQ",
      "EventData",
      "EventEvaluator",
      "EventHandler",
      "EventHandlerTag",
      "EventLabels",
      "EventSeries",
      "ExactBlackmanWindow",
      "ExactNumberQ",
      "ExactRootIsolation",
      "ExampleData",
      "Except",
      "ExcludedForms",
      "ExcludedLines",
      "ExcludedPhysicalQuantities",
      "ExcludePods",
      "Exclusions",
      "ExclusionsStyle",
      "Exists",
      "Exit",
      "ExitDialog",
      "ExoplanetData",
      "Exp",
      "Expand",
      "ExpandAll",
      "ExpandDenominator",
      "ExpandFileName",
      "ExpandNumerator",
      "Expectation",
      "ExpectationE",
      "ExpectedValue",
      "ExpGammaDistribution",
      "ExpIntegralE",
      "ExpIntegralEi",
      "ExpirationDate",
      "Exponent",
      "ExponentFunction",
      "ExponentialDistribution",
      "ExponentialFamily",
      "ExponentialGeneratingFunction",
      "ExponentialMovingAverage",
      "ExponentialPowerDistribution",
      "ExponentPosition",
      "ExponentStep",
      "Export",
      "ExportAutoReplacements",
      "ExportByteArray",
      "ExportForm",
      "ExportPacket",
      "ExportString",
      "Expression",
      "ExpressionCell",
      "ExpressionGraph",
      "ExpressionPacket",
      "ExpressionUUID",
      "ExpToTrig",
      "ExtendedEntityClass",
      "ExtendedGCD",
      "Extension",
      "ExtentElementFunction",
      "ExtentMarkers",
      "ExtentSize",
      "ExternalBundle",
      "ExternalCall",
      "ExternalDataCharacterEncoding",
      "ExternalEvaluate",
      "ExternalFunction",
      "ExternalFunctionName",
      "ExternalIdentifier",
      "ExternalObject",
      "ExternalOptions",
      "ExternalSessionObject",
      "ExternalSessions",
      "ExternalStorageBase",
      "ExternalStorageDownload",
      "ExternalStorageGet",
      "ExternalStorageObject",
      "ExternalStoragePut",
      "ExternalStorageUpload",
      "ExternalTypeSignature",
      "ExternalValue",
      "Extract",
      "ExtractArchive",
      "ExtractLayer",
      "ExtractPacletArchive",
      "ExtremeValueDistribution",
      "FaceAlign",
      "FaceForm",
      "FaceGrids",
      "FaceGridsStyle",
      "FacialFeatures",
      "Factor",
      "FactorComplete",
      "Factorial",
      "Factorial2",
      "FactorialMoment",
      "FactorialMomentGeneratingFunction",
      "FactorialPower",
      "FactorInteger",
      "FactorList",
      "FactorSquareFree",
      "FactorSquareFreeList",
      "FactorTerms",
      "FactorTermsList",
      "Fail",
      "Failure",
      "FailureAction",
      "FailureDistribution",
      "FailureQ",
      "False",
      "FareySequence",
      "FARIMAProcess",
      "FeatureDistance",
      "FeatureExtract",
      "FeatureExtraction",
      "FeatureExtractor",
      "FeatureExtractorFunction",
      "FeatureNames",
      "FeatureNearest",
      "FeatureSpacePlot",
      "FeatureSpacePlot3D",
      "FeatureTypes",
      "FEDisableConsolePrintPacket",
      "FeedbackLinearize",
      "FeedbackSector",
      "FeedbackSectorStyle",
      "FeedbackType",
      "FEEnableConsolePrintPacket",
      "FetalGrowthData",
      "Fibonacci",
      "Fibonorial",
      "FieldCompletionFunction",
      "FieldHint",
      "FieldHintStyle",
      "FieldMasked",
      "FieldSize",
      "File",
      "FileBaseName",
      "FileByteCount",
      "FileConvert",
      "FileDate",
      "FileExistsQ",
      "FileExtension",
      "FileFormat",
      "FileHandler",
      "FileHash",
      "FileInformation",
      "FileName",
      "FileNameDepth",
      "FileNameDialogSettings",
      "FileNameDrop",
      "FileNameForms",
      "FileNameJoin",
      "FileNames",
      "FileNameSetter",
      "FileNameSplit",
      "FileNameTake",
      "FilePrint",
      "FileSize",
      "FileSystemMap",
      "FileSystemScan",
      "FileTemplate",
      "FileTemplateApply",
      "FileType",
      "FilledCurve",
      "FilledCurveBox",
      "FilledCurveBoxOptions",
      "Filling",
      "FillingStyle",
      "FillingTransform",
      "FilteredEntityClass",
      "FilterRules",
      "FinancialBond",
      "FinancialData",
      "FinancialDerivative",
      "FinancialIndicator",
      "Find",
      "FindAnomalies",
      "FindArgMax",
      "FindArgMin",
      "FindChannels",
      "FindClique",
      "FindClusters",
      "FindCookies",
      "FindCurvePath",
      "FindCycle",
      "FindDevices",
      "FindDistribution",
      "FindDistributionParameters",
      "FindDivisions",
      "FindEdgeCover",
      "FindEdgeCut",
      "FindEdgeIndependentPaths",
      "FindEquationalProof",
      "FindEulerianCycle",
      "FindExternalEvaluators",
      "FindFaces",
      "FindFile",
      "FindFit",
      "FindFormula",
      "FindFundamentalCycles",
      "FindGeneratingFunction",
      "FindGeoLocation",
      "FindGeometricConjectures",
      "FindGeometricTransform",
      "FindGraphCommunities",
      "FindGraphIsomorphism",
      "FindGraphPartition",
      "FindHamiltonianCycle",
      "FindHamiltonianPath",
      "FindHiddenMarkovStates",
      "FindImageText",
      "FindIndependentEdgeSet",
      "FindIndependentVertexSet",
      "FindInstance",
      "FindIntegerNullVector",
      "FindKClan",
      "FindKClique",
      "FindKClub",
      "FindKPlex",
      "FindLibrary",
      "FindLinearRecurrence",
      "FindList",
      "FindMatchingColor",
      "FindMaximum",
      "FindMaximumCut",
      "FindMaximumFlow",
      "FindMaxValue",
      "FindMeshDefects",
      "FindMinimum",
      "FindMinimumCostFlow",
      "FindMinimumCut",
      "FindMinValue",
      "FindMoleculeSubstructure",
      "FindPath",
      "FindPeaks",
      "FindPermutation",
      "FindPostmanTour",
      "FindProcessParameters",
      "FindRepeat",
      "FindRoot",
      "FindSequenceFunction",
      "FindSettings",
      "FindShortestPath",
      "FindShortestTour",
      "FindSpanningTree",
      "FindSystemModelEquilibrium",
      "FindTextualAnswer",
      "FindThreshold",
      "FindTransientRepeat",
      "FindVertexCover",
      "FindVertexCut",
      "FindVertexIndependentPaths",
      "Fine",
      "FinishDynamic",
      "FiniteAbelianGroupCount",
      "FiniteGroupCount",
      "FiniteGroupData",
      "First",
      "FirstCase",
      "FirstPassageTimeDistribution",
      "FirstPosition",
      "FischerGroupFi22",
      "FischerGroupFi23",
      "FischerGroupFi24Prime",
      "FisherHypergeometricDistribution",
      "FisherRatioTest",
      "FisherZDistribution",
      "Fit",
      "FitAll",
      "FitRegularization",
      "FittedModel",
      "FixedOrder",
      "FixedPoint",
      "FixedPointList",
      "FlashSelection",
      "Flat",
      "Flatten",
      "FlattenAt",
      "FlattenLayer",
      "FlatTopWindow",
      "FlipView",
      "Floor",
      "FlowPolynomial",
      "FlushPrintOutputPacket",
      "Fold",
      "FoldList",
      "FoldPair",
      "FoldPairList",
      "FollowRedirects",
      "Font",
      "FontColor",
      "FontFamily",
      "FontForm",
      "FontName",
      "FontOpacity",
      "FontPostScriptName",
      "FontProperties",
      "FontReencoding",
      "FontSize",
      "FontSlant",
      "FontSubstitutions",
      "FontTracking",
      "FontVariations",
      "FontWeight",
      "For",
      "ForAll",
      "ForceVersionInstall",
      "Format",
      "FormatRules",
      "FormatType",
      "FormatTypeAutoConvert",
      "FormatValues",
      "FormBox",
      "FormBoxOptions",
      "FormControl",
      "FormFunction",
      "FormLayoutFunction",
      "FormObject",
      "FormPage",
      "FormTheme",
      "FormulaData",
      "FormulaLookup",
      "FortranForm",
      "Forward",
      "ForwardBackward",
      "Fourier",
      "FourierCoefficient",
      "FourierCosCoefficient",
      "FourierCosSeries",
      "FourierCosTransform",
      "FourierDCT",
      "FourierDCTFilter",
      "FourierDCTMatrix",
      "FourierDST",
      "FourierDSTMatrix",
      "FourierMatrix",
      "FourierParameters",
      "FourierSequenceTransform",
      "FourierSeries",
      "FourierSinCoefficient",
      "FourierSinSeries",
      "FourierSinTransform",
      "FourierTransform",
      "FourierTrigSeries",
      "FractionalBrownianMotionProcess",
      "FractionalGaussianNoiseProcess",
      "FractionalPart",
      "FractionBox",
      "FractionBoxOptions",
      "FractionLine",
      "Frame",
      "FrameBox",
      "FrameBoxOptions",
      "Framed",
      "FrameInset",
      "FrameLabel",
      "Frameless",
      "FrameMargins",
      "FrameRate",
      "FrameStyle",
      "FrameTicks",
      "FrameTicksStyle",
      "FRatioDistribution",
      "FrechetDistribution",
      "FreeQ",
      "FrenetSerretSystem",
      "FrequencySamplingFilterKernel",
      "FresnelC",
      "FresnelF",
      "FresnelG",
      "FresnelS",
      "Friday",
      "FrobeniusNumber",
      "FrobeniusSolve",
      "FromAbsoluteTime",
      "FromCharacterCode",
      "FromCoefficientRules",
      "FromContinuedFraction",
      "FromDate",
      "FromDigits",
      "FromDMS",
      "FromEntity",
      "FromJulianDate",
      "FromLetterNumber",
      "FromPolarCoordinates",
      "FromRomanNumeral",
      "FromSphericalCoordinates",
      "FromUnixTime",
      "Front",
      "FrontEndDynamicExpression",
      "FrontEndEventActions",
      "FrontEndExecute",
      "FrontEndObject",
      "FrontEndResource",
      "FrontEndResourceString",
      "FrontEndStackSize",
      "FrontEndToken",
      "FrontEndTokenExecute",
      "FrontEndValueCache",
      "FrontEndVersion",
      "FrontFaceColor",
      "FrontFaceOpacity",
      "Full",
      "FullAxes",
      "FullDefinition",
      "FullForm",
      "FullGraphics",
      "FullInformationOutputRegulator",
      "FullOptions",
      "FullRegion",
      "FullSimplify",
      "Function",
      "FunctionCompile",
      "FunctionCompileExport",
      "FunctionCompileExportByteArray",
      "FunctionCompileExportLibrary",
      "FunctionCompileExportString",
      "FunctionDomain",
      "FunctionExpand",
      "FunctionInterpolation",
      "FunctionPeriod",
      "FunctionRange",
      "FunctionSpace",
      "FussellVeselyImportance",
      "GaborFilter",
      "GaborMatrix",
      "GaborWavelet",
      "GainMargins",
      "GainPhaseMargins",
      "GalaxyData",
      "GalleryView",
      "Gamma",
      "GammaDistribution",
      "GammaRegularized",
      "GapPenalty",
      "GARCHProcess",
      "GatedRecurrentLayer",
      "Gather",
      "GatherBy",
      "GaugeFaceElementFunction",
      "GaugeFaceStyle",
      "GaugeFrameElementFunction",
      "GaugeFrameSize",
      "GaugeFrameStyle",
      "GaugeLabels",
      "GaugeMarkers",
      "GaugeStyle",
      "GaussianFilter",
      "GaussianIntegers",
      "GaussianMatrix",
      "GaussianOrthogonalMatrixDistribution",
      "GaussianSymplecticMatrixDistribution",
      "GaussianUnitaryMatrixDistribution",
      "GaussianWindow",
      "GCD",
      "GegenbauerC",
      "General",
      "GeneralizedLinearModelFit",
      "GenerateAsymmetricKeyPair",
      "GenerateConditions",
      "GeneratedCell",
      "GeneratedDocumentBinding",
      "GenerateDerivedKey",
      "GenerateDigitalSignature",
      "GenerateDocument",
      "GeneratedParameters",
      "GeneratedQuantityMagnitudes",
      "GenerateFileSignature",
      "GenerateHTTPResponse",
      "GenerateSecuredAuthenticationKey",
      "GenerateSymmetricKey",
      "GeneratingFunction",
      "GeneratorDescription",
      "GeneratorHistoryLength",
      "GeneratorOutputType",
      "Generic",
      "GenericCylindricalDecomposition",
      "GenomeData",
      "GenomeLookup",
      "GeoAntipode",
      "GeoArea",
      "GeoArraySize",
      "GeoBackground",
      "GeoBoundingBox",
      "GeoBounds",
      "GeoBoundsRegion",
      "GeoBubbleChart",
      "GeoCenter",
      "GeoCircle",
      "GeoContourPlot",
      "GeoDensityPlot",
      "GeodesicClosing",
      "GeodesicDilation",
      "GeodesicErosion",
      "GeodesicOpening",
      "GeoDestination",
      "GeodesyData",
      "GeoDirection",
      "GeoDisk",
      "GeoDisplacement",
      "GeoDistance",
      "GeoDistanceList",
      "GeoElevationData",
      "GeoEntities",
      "GeoGraphics",
      "GeogravityModelData",
      "GeoGridDirectionDifference",
      "GeoGridLines",
      "GeoGridLinesStyle",
      "GeoGridPosition",
      "GeoGridRange",
      "GeoGridRangePadding",
      "GeoGridUnitArea",
      "GeoGridUnitDistance",
      "GeoGridVector",
      "GeoGroup",
      "GeoHemisphere",
      "GeoHemisphereBoundary",
      "GeoHistogram",
      "GeoIdentify",
      "GeoImage",
      "GeoLabels",
      "GeoLength",
      "GeoListPlot",
      "GeoLocation",
      "GeologicalPeriodData",
      "GeomagneticModelData",
      "GeoMarker",
      "GeometricAssertion",
      "GeometricBrownianMotionProcess",
      "GeometricDistribution",
      "GeometricMean",
      "GeometricMeanFilter",
      "GeometricOptimization",
      "GeometricScene",
      "GeometricTransformation",
      "GeometricTransformation3DBox",
      "GeometricTransformation3DBoxOptions",
      "GeometricTransformationBox",
      "GeometricTransformationBoxOptions",
      "GeoModel",
      "GeoNearest",
      "GeoPath",
      "GeoPosition",
      "GeoPositionENU",
      "GeoPositionXYZ",
      "GeoProjection",
      "GeoProjectionData",
      "GeoRange",
      "GeoRangePadding",
      "GeoRegionValuePlot",
      "GeoResolution",
      "GeoScaleBar",
      "GeoServer",
      "GeoSmoothHistogram",
      "GeoStreamPlot",
      "GeoStyling",
      "GeoStylingImageFunction",
      "GeoVariant",
      "GeoVector",
      "GeoVectorENU",
      "GeoVectorPlot",
      "GeoVectorXYZ",
      "GeoVisibleRegion",
      "GeoVisibleRegionBoundary",
      "GeoWithinQ",
      "GeoZoomLevel",
      "GestureHandler",
      "GestureHandlerTag",
      "Get",
      "GetBoundingBoxSizePacket",
      "GetContext",
      "GetEnvironment",
      "GetFileName",
      "GetFrontEndOptionsDataPacket",
      "GetLinebreakInformationPacket",
      "GetMenusPacket",
      "GetPageBreakInformationPacket",
      "Glaisher",
      "GlobalClusteringCoefficient",
      "GlobalPreferences",
      "GlobalSession",
      "Glow",
      "GoldenAngle",
      "GoldenRatio",
      "GompertzMakehamDistribution",
      "GoochShading",
      "GoodmanKruskalGamma",
      "GoodmanKruskalGammaTest",
      "Goto",
      "Grad",
      "Gradient",
      "GradientFilter",
      "GradientOrientationFilter",
      "GrammarApply",
      "GrammarRules",
      "GrammarToken",
      "Graph",
      "Graph3D",
      "GraphAssortativity",
      "GraphAutomorphismGroup",
      "GraphCenter",
      "GraphComplement",
      "GraphData",
      "GraphDensity",
      "GraphDiameter",
      "GraphDifference",
      "GraphDisjointUnion",
      "GraphDistance",
      "GraphDistanceMatrix",
      "GraphElementData",
      "GraphEmbedding",
      "GraphHighlight",
      "GraphHighlightStyle",
      "GraphHub",
      "Graphics",
      "Graphics3D",
      "Graphics3DBox",
      "Graphics3DBoxOptions",
      "GraphicsArray",
      "GraphicsBaseline",
      "GraphicsBox",
      "GraphicsBoxOptions",
      "GraphicsColor",
      "GraphicsColumn",
      "GraphicsComplex",
      "GraphicsComplex3DBox",
      "GraphicsComplex3DBoxOptions",
      "GraphicsComplexBox",
      "GraphicsComplexBoxOptions",
      "GraphicsContents",
      "GraphicsData",
      "GraphicsGrid",
      "GraphicsGridBox",
      "GraphicsGroup",
      "GraphicsGroup3DBox",
      "GraphicsGroup3DBoxOptions",
      "GraphicsGroupBox",
      "GraphicsGroupBoxOptions",
      "GraphicsGrouping",
      "GraphicsHighlightColor",
      "GraphicsRow",
      "GraphicsSpacing",
      "GraphicsStyle",
      "GraphIntersection",
      "GraphLayout",
      "GraphLinkEfficiency",
      "GraphPeriphery",
      "GraphPlot",
      "GraphPlot3D",
      "GraphPower",
      "GraphPropertyDistribution",
      "GraphQ",
      "GraphRadius",
      "GraphReciprocity",
      "GraphRoot",
      "GraphStyle",
      "GraphUnion",
      "Gray",
      "GrayLevel",
      "Greater",
      "GreaterEqual",
      "GreaterEqualLess",
      "GreaterEqualThan",
      "GreaterFullEqual",
      "GreaterGreater",
      "GreaterLess",
      "GreaterSlantEqual",
      "GreaterThan",
      "GreaterTilde",
      "Green",
      "GreenFunction",
      "Grid",
      "GridBaseline",
      "GridBox",
      "GridBoxAlignment",
      "GridBoxBackground",
      "GridBoxDividers",
      "GridBoxFrame",
      "GridBoxItemSize",
      "GridBoxItemStyle",
      "GridBoxOptions",
      "GridBoxSpacings",
      "GridCreationSettings",
      "GridDefaultElement",
      "GridElementStyleOptions",
      "GridFrame",
      "GridFrameMargins",
      "GridGraph",
      "GridLines",
      "GridLinesStyle",
      "GroebnerBasis",
      "GroupActionBase",
      "GroupBy",
      "GroupCentralizer",
      "GroupElementFromWord",
      "GroupElementPosition",
      "GroupElementQ",
      "GroupElements",
      "GroupElementToWord",
      "GroupGenerators",
      "Groupings",
      "GroupMultiplicationTable",
      "GroupOrbits",
      "GroupOrder",
      "GroupPageBreakWithin",
      "GroupSetwiseStabilizer",
      "GroupStabilizer",
      "GroupStabilizerChain",
      "GroupTogetherGrouping",
      "GroupTogetherNestedGrouping",
      "GrowCutComponents",
      "Gudermannian",
      "GuidedFilter",
      "GumbelDistribution",
      "HaarWavelet",
      "HadamardMatrix",
      "HalfLine",
      "HalfNormalDistribution",
      "HalfPlane",
      "HalfSpace",
      "HalftoneShading",
      "HamiltonianGraphQ",
      "HammingDistance",
      "HammingWindow",
      "HandlerFunctions",
      "HandlerFunctionsKeys",
      "HankelH1",
      "HankelH2",
      "HankelMatrix",
      "HankelTransform",
      "HannPoissonWindow",
      "HannWindow",
      "HaradaNortonGroupHN",
      "HararyGraph",
      "HarmonicMean",
      "HarmonicMeanFilter",
      "HarmonicNumber",
      "Hash",
      "HatchFilling",
      "HatchShading",
      "Haversine",
      "HazardFunction",
      "Head",
      "HeadCompose",
      "HeaderAlignment",
      "HeaderBackground",
      "HeaderDisplayFunction",
      "HeaderLines",
      "HeaderSize",
      "HeaderStyle",
      "Heads",
      "HeavisideLambda",
      "HeavisidePi",
      "HeavisideTheta",
      "HeldGroupHe",
      "HeldPart",
      "HelpBrowserLookup",
      "HelpBrowserNotebook",
      "HelpBrowserSettings",
      "Here",
      "HermiteDecomposition",
      "HermiteH",
      "HermitianMatrixQ",
      "HessenbergDecomposition",
      "Hessian",
      "HeunB",
      "HeunBPrime",
      "HeunC",
      "HeunCPrime",
      "HeunD",
      "HeunDPrime",
      "HeunG",
      "HeunGPrime",
      "HeunT",
      "HeunTPrime",
      "HexadecimalCharacter",
      "Hexahedron",
      "HexahedronBox",
      "HexahedronBoxOptions",
      "HiddenItems",
      "HiddenMarkovProcess",
      "HiddenSurface",
      "Highlighted",
      "HighlightGraph",
      "HighlightImage",
      "HighlightMesh",
      "HighpassFilter",
      "HigmanSimsGroupHS",
      "HilbertCurve",
      "HilbertFilter",
      "HilbertMatrix",
      "Histogram",
      "Histogram3D",
      "HistogramDistribution",
      "HistogramList",
      "HistogramTransform",
      "HistogramTransformInterpolation",
      "HistoricalPeriodData",
      "HitMissTransform",
      "HITSCentrality",
      "HjorthDistribution",
      "HodgeDual",
      "HoeffdingD",
      "HoeffdingDTest",
      "Hold",
      "HoldAll",
      "HoldAllComplete",
      "HoldComplete",
      "HoldFirst",
      "HoldForm",
      "HoldPattern",
      "HoldRest",
      "HolidayCalendar",
      "HomeDirectory",
      "HomePage",
      "Horizontal",
      "HorizontalForm",
      "HorizontalGauge",
      "HorizontalScrollPosition",
      "HornerForm",
      "HostLookup",
      "HotellingTSquareDistribution",
      "HoytDistribution",
      "HTMLSave",
      "HTTPErrorResponse",
      "HTTPRedirect",
      "HTTPRequest",
      "HTTPRequestData",
      "HTTPResponse",
      "Hue",
      "HumanGrowthData",
      "HumpDownHump",
      "HumpEqual",
      "HurwitzLerchPhi",
      "HurwitzZeta",
      "HyperbolicDistribution",
      "HypercubeGraph",
      "HyperexponentialDistribution",
      "Hyperfactorial",
      "Hypergeometric0F1",
      "Hypergeometric0F1Regularized",
      "Hypergeometric1F1",
      "Hypergeometric1F1Regularized",
      "Hypergeometric2F1",
      "Hypergeometric2F1Regularized",
      "HypergeometricDistribution",
      "HypergeometricPFQ",
      "HypergeometricPFQRegularized",
      "HypergeometricU",
      "Hyperlink",
      "HyperlinkAction",
      "HyperlinkCreationSettings",
      "Hyperplane",
      "Hyphenation",
      "HyphenationOptions",
      "HypoexponentialDistribution",
      "HypothesisTestData",
      "I",
      "IconData",
      "Iconize",
      "IconizedObject",
      "IconRules",
      "Icosahedron",
      "Identity",
      "IdentityMatrix",
      "If",
      "IgnoreCase",
      "IgnoreDiacritics",
      "IgnorePunctuation",
      "IgnoreSpellCheck",
      "IgnoringInactive",
      "Im",
      "Image",
      "Image3D",
      "Image3DProjection",
      "Image3DSlices",
      "ImageAccumulate",
      "ImageAdd",
      "ImageAdjust",
      "ImageAlign",
      "ImageApply",
      "ImageApplyIndexed",
      "ImageAspectRatio",
      "ImageAssemble",
      "ImageAugmentationLayer",
      "ImageBoundingBoxes",
      "ImageCache",
      "ImageCacheValid",
      "ImageCapture",
      "ImageCaptureFunction",
      "ImageCases",
      "ImageChannels",
      "ImageClip",
      "ImageCollage",
      "ImageColorSpace",
      "ImageCompose",
      "ImageContainsQ",
      "ImageContents",
      "ImageConvolve",
      "ImageCooccurrence",
      "ImageCorners",
      "ImageCorrelate",
      "ImageCorrespondingPoints",
      "ImageCrop",
      "ImageData",
      "ImageDeconvolve",
      "ImageDemosaic",
      "ImageDifference",
      "ImageDimensions",
      "ImageDisplacements",
      "ImageDistance",
      "ImageEffect",
      "ImageExposureCombine",
      "ImageFeatureTrack",
      "ImageFileApply",
      "ImageFileFilter",
      "ImageFileScan",
      "ImageFilter",
      "ImageFocusCombine",
      "ImageForestingComponents",
      "ImageFormattingWidth",
      "ImageForwardTransformation",
      "ImageGraphics",
      "ImageHistogram",
      "ImageIdentify",
      "ImageInstanceQ",
      "ImageKeypoints",
      "ImageLabels",
      "ImageLegends",
      "ImageLevels",
      "ImageLines",
      "ImageMargins",
      "ImageMarker",
      "ImageMarkers",
      "ImageMeasurements",
      "ImageMesh",
      "ImageMultiply",
      "ImageOffset",
      "ImagePad",
      "ImagePadding",
      "ImagePartition",
      "ImagePeriodogram",
      "ImagePerspectiveTransformation",
      "ImagePosition",
      "ImagePreviewFunction",
      "ImagePyramid",
      "ImagePyramidApply",
      "ImageQ",
      "ImageRangeCache",
      "ImageRecolor",
      "ImageReflect",
      "ImageRegion",
      "ImageResize",
      "ImageResolution",
      "ImageRestyle",
      "ImageRotate",
      "ImageRotated",
      "ImageSaliencyFilter",
      "ImageScaled",
      "ImageScan",
      "ImageSize",
      "ImageSizeAction",
      "ImageSizeCache",
      "ImageSizeMultipliers",
      "ImageSizeRaw",
      "ImageSubtract",
      "ImageTake",
      "ImageTransformation",
      "ImageTrim",
      "ImageType",
      "ImageValue",
      "ImageValuePositions",
      "ImagingDevice",
      "ImplicitRegion",
      "Implies",
      "Import",
      "ImportAutoReplacements",
      "ImportByteArray",
      "ImportOptions",
      "ImportString",
      "ImprovementImportance",
      "In",
      "Inactivate",
      "Inactive",
      "IncidenceGraph",
      "IncidenceList",
      "IncidenceMatrix",
      "IncludeAromaticBonds",
      "IncludeConstantBasis",
      "IncludeDefinitions",
      "IncludeDirectories",
      "IncludeFileExtension",
      "IncludeGeneratorTasks",
      "IncludeHydrogens",
      "IncludeInflections",
      "IncludeMetaInformation",
      "IncludePods",
      "IncludeQuantities",
      "IncludeRelatedTables",
      "IncludeSingularTerm",
      "IncludeWindowTimes",
      "Increment",
      "IndefiniteMatrixQ",
      "Indent",
      "IndentingNewlineSpacings",
      "IndentMaxFraction",
      "IndependenceTest",
      "IndependentEdgeSetQ",
      "IndependentPhysicalQuantity",
      "IndependentUnit",
      "IndependentUnitDimension",
      "IndependentVertexSetQ",
      "Indeterminate",
      "IndeterminateThreshold",
      "IndexCreationOptions",
      "Indexed",
      "IndexEdgeTaggedGraph",
      "IndexGraph",
      "IndexTag",
      "Inequality",
      "InexactNumberQ",
      "InexactNumbers",
      "InfiniteFuture",
      "InfiniteLine",
      "InfinitePast",
      "InfinitePlane",
      "Infinity",
      "Infix",
      "InflationAdjust",
      "InflationMethod",
      "Information",
      "InformationData",
      "InformationDataGrid",
      "Inherited",
      "InheritScope",
      "InhomogeneousPoissonProcess",
      "InitialEvaluationHistory",
      "Initialization",
      "InitializationCell",
      "InitializationCellEvaluation",
      "InitializationCellWarning",
      "InitializationObjects",
      "InitializationValue",
      "Initialize",
      "InitialSeeding",
      "InlineCounterAssignments",
      "InlineCounterIncrements",
      "InlineRules",
      "Inner",
      "InnerPolygon",
      "InnerPolyhedron",
      "Inpaint",
      "Input",
      "InputAliases",
      "InputAssumptions",
      "InputAutoReplacements",
      "InputField",
      "InputFieldBox",
      "InputFieldBoxOptions",
      "InputForm",
      "InputGrouping",
      "InputNamePacket",
      "InputNotebook",
      "InputPacket",
      "InputSettings",
      "InputStream",
      "InputString",
      "InputStringPacket",
      "InputToBoxFormPacket",
      "Insert",
      "InsertionFunction",
      "InsertionPointObject",
      "InsertLinebreaks",
      "InsertResults",
      "Inset",
      "Inset3DBox",
      "Inset3DBoxOptions",
      "InsetBox",
      "InsetBoxOptions",
      "Insphere",
      "Install",
      "InstallService",
      "InstanceNormalizationLayer",
      "InString",
      "Integer",
      "IntegerDigits",
      "IntegerExponent",
      "IntegerLength",
      "IntegerName",
      "IntegerPart",
      "IntegerPartitions",
      "IntegerQ",
      "IntegerReverse",
      "Integers",
      "IntegerString",
      "Integral",
      "Integrate",
      "Interactive",
      "InteractiveTradingChart",
      "Interlaced",
      "Interleaving",
      "InternallyBalancedDecomposition",
      "InterpolatingFunction",
      "InterpolatingPolynomial",
      "Interpolation",
      "InterpolationOrder",
      "InterpolationPoints",
      "InterpolationPrecision",
      "Interpretation",
      "InterpretationBox",
      "InterpretationBoxOptions",
      "InterpretationFunction",
      "Interpreter",
      "InterpretTemplate",
      "InterquartileRange",
      "Interrupt",
      "InterruptSettings",
      "IntersectedEntityClass",
      "IntersectingQ",
      "Intersection",
      "Interval",
      "IntervalIntersection",
      "IntervalMarkers",
      "IntervalMarkersStyle",
      "IntervalMemberQ",
      "IntervalSlider",
      "IntervalUnion",
      "Into",
      "Inverse",
      "InverseBetaRegularized",
      "InverseCDF",
      "InverseChiSquareDistribution",
      "InverseContinuousWaveletTransform",
      "InverseDistanceTransform",
      "InverseEllipticNomeQ",
      "InverseErf",
      "InverseErfc",
      "InverseFourier",
      "InverseFourierCosTransform",
      "InverseFourierSequenceTransform",
      "InverseFourierSinTransform",
      "InverseFourierTransform",
      "InverseFunction",
      "InverseFunctions",
      "InverseGammaDistribution",
      "InverseGammaRegularized",
      "InverseGaussianDistribution",
      "InverseGudermannian",
      "InverseHankelTransform",
      "InverseHaversine",
      "InverseImagePyramid",
      "InverseJacobiCD",
      "InverseJacobiCN",
      "InverseJacobiCS",
      "InverseJacobiDC",
      "InverseJacobiDN",
      "InverseJacobiDS",
      "InverseJacobiNC",
      "InverseJacobiND",
      "InverseJacobiNS",
      "InverseJacobiSC",
      "InverseJacobiSD",
      "InverseJacobiSN",
      "InverseLaplaceTransform",
      "InverseMellinTransform",
      "InversePermutation",
      "InverseRadon",
      "InverseRadonTransform",
      "InverseSeries",
      "InverseShortTimeFourier",
      "InverseSpectrogram",
      "InverseSurvivalFunction",
      "InverseTransformedRegion",
      "InverseWaveletTransform",
      "InverseWeierstrassP",
      "InverseWishartMatrixDistribution",
      "InverseZTransform",
      "Invisible",
      "InvisibleApplication",
      "InvisibleTimes",
      "IPAddress",
      "IrreduciblePolynomialQ",
      "IslandData",
      "IsolatingInterval",
      "IsomorphicGraphQ",
      "IsotopeData",
      "Italic",
      "Item",
      "ItemAspectRatio",
      "ItemBox",
      "ItemBoxOptions",
      "ItemDisplayFunction",
      "ItemSize",
      "ItemStyle",
      "ItoProcess",
      "JaccardDissimilarity",
      "JacobiAmplitude",
      "Jacobian",
      "JacobiCD",
      "JacobiCN",
      "JacobiCS",
      "JacobiDC",
      "JacobiDN",
      "JacobiDS",
      "JacobiNC",
      "JacobiND",
      "JacobiNS",
      "JacobiP",
      "JacobiSC",
      "JacobiSD",
      "JacobiSN",
      "JacobiSymbol",
      "JacobiZeta",
      "JankoGroupJ1",
      "JankoGroupJ2",
      "JankoGroupJ3",
      "JankoGroupJ4",
      "JarqueBeraALMTest",
      "JohnsonDistribution",
      "Join",
      "JoinAcross",
      "Joined",
      "JoinedCurve",
      "JoinedCurveBox",
      "JoinedCurveBoxOptions",
      "JoinForm",
      "JordanDecomposition",
      "JordanModelDecomposition",
      "JulianDate",
      "JuliaSetBoettcher",
      "JuliaSetIterationCount",
      "JuliaSetPlot",
      "JuliaSetPoints",
      "K",
      "KagiChart",
      "KaiserBesselWindow",
      "KaiserWindow",
      "KalmanEstimator",
      "KalmanFilter",
      "KarhunenLoeveDecomposition",
      "KaryTree",
      "KatzCentrality",
      "KCoreComponents",
      "KDistribution",
      "KEdgeConnectedComponents",
      "KEdgeConnectedGraphQ",
      "KeepExistingVersion",
      "KelvinBei",
      "KelvinBer",
      "KelvinKei",
      "KelvinKer",
      "KendallTau",
      "KendallTauTest",
      "KernelExecute",
      "KernelFunction",
      "KernelMixtureDistribution",
      "KernelObject",
      "Kernels",
      "Ket",
      "Key",
      "KeyCollisionFunction",
      "KeyComplement",
      "KeyDrop",
      "KeyDropFrom",
      "KeyExistsQ",
      "KeyFreeQ",
      "KeyIntersection",
      "KeyMap",
      "KeyMemberQ",
      "KeypointStrength",
      "Keys",
      "KeySelect",
      "KeySort",
      "KeySortBy",
      "KeyTake",
      "KeyUnion",
      "KeyValueMap",
      "KeyValuePattern",
      "Khinchin",
      "KillProcess",
      "KirchhoffGraph",
      "KirchhoffMatrix",
      "KleinInvariantJ",
      "KnapsackSolve",
      "KnightTourGraph",
      "KnotData",
      "KnownUnitQ",
      "KochCurve",
      "KolmogorovSmirnovTest",
      "KroneckerDelta",
      "KroneckerModelDecomposition",
      "KroneckerProduct",
      "KroneckerSymbol",
      "KuiperTest",
      "KumaraswamyDistribution",
      "Kurtosis",
      "KuwaharaFilter",
      "KVertexConnectedComponents",
      "KVertexConnectedGraphQ",
      "LABColor",
      "Label",
      "Labeled",
      "LabeledSlider",
      "LabelingFunction",
      "LabelingSize",
      "LabelStyle",
      "LabelVisibility",
      "LaguerreL",
      "LakeData",
      "LambdaComponents",
      "LambertW",
      "LaminaData",
      "LanczosWindow",
      "LandauDistribution",
      "Language",
      "LanguageCategory",
      "LanguageData",
      "LanguageIdentify",
      "LanguageOptions",
      "LaplaceDistribution",
      "LaplaceTransform",
      "Laplacian",
      "LaplacianFilter",
      "LaplacianGaussianFilter",
      "Large",
      "Larger",
      "Last",
      "Latitude",
      "LatitudeLongitude",
      "LatticeData",
      "LatticeReduce",
      "Launch",
      "LaunchKernels",
      "LayeredGraphPlot",
      "LayerSizeFunction",
      "LayoutInformation",
      "LCHColor",
      "LCM",
      "LeaderSize",
      "LeafCount",
      "LeapYearQ",
      "LearnDistribution",
      "LearnedDistribution",
      "LearningRate",
      "LearningRateMultipliers",
      "LeastSquares",
      "LeastSquaresFilterKernel",
      "Left",
      "LeftArrow",
      "LeftArrowBar",
      "LeftArrowRightArrow",
      "LeftDownTeeVector",
      "LeftDownVector",
      "LeftDownVectorBar",
      "LeftRightArrow",
      "LeftRightVector",
      "LeftTee",
      "LeftTeeArrow",
      "LeftTeeVector",
      "LeftTriangle",
      "LeftTriangleBar",
      "LeftTriangleEqual",
      "LeftUpDownVector",
      "LeftUpTeeVector",
      "LeftUpVector",
      "LeftUpVectorBar",
      "LeftVector",
      "LeftVectorBar",
      "LegendAppearance",
      "Legended",
      "LegendFunction",
      "LegendLabel",
      "LegendLayout",
      "LegendMargins",
      "LegendMarkers",
      "LegendMarkerSize",
      "LegendreP",
      "LegendreQ",
      "LegendreType",
      "Length",
      "LengthWhile",
      "LerchPhi",
      "Less",
      "LessEqual",
      "LessEqualGreater",
      "LessEqualThan",
      "LessFullEqual",
      "LessGreater",
      "LessLess",
      "LessSlantEqual",
      "LessThan",
      "LessTilde",
      "LetterCharacter",
      "LetterCounts",
      "LetterNumber",
      "LetterQ",
      "Level",
      "LeveneTest",
      "LeviCivitaTensor",
      "LevyDistribution",
      "Lexicographic",
      "LibraryDataType",
      "LibraryFunction",
      "LibraryFunctionError",
      "LibraryFunctionInformation",
      "LibraryFunctionLoad",
      "LibraryFunctionUnload",
      "LibraryLoad",
      "LibraryUnload",
      "LicenseID",
      "LiftingFilterData",
      "LiftingWaveletTransform",
      "LightBlue",
      "LightBrown",
      "LightCyan",
      "Lighter",
      "LightGray",
      "LightGreen",
      "Lighting",
      "LightingAngle",
      "LightMagenta",
      "LightOrange",
      "LightPink",
      "LightPurple",
      "LightRed",
      "LightSources",
      "LightYellow",
      "Likelihood",
      "Limit",
      "LimitsPositioning",
      "LimitsPositioningTokens",
      "LindleyDistribution",
      "Line",
      "Line3DBox",
      "Line3DBoxOptions",
      "LinearFilter",
      "LinearFractionalOptimization",
      "LinearFractionalTransform",
      "LinearGradientImage",
      "LinearizingTransformationData",
      "LinearLayer",
      "LinearModelFit",
      "LinearOffsetFunction",
      "LinearOptimization",
      "LinearProgramming",
      "LinearRecurrence",
      "LinearSolve",
      "LinearSolveFunction",
      "LineBox",
      "LineBoxOptions",
      "LineBreak",
      "LinebreakAdjustments",
      "LineBreakChart",
      "LinebreakSemicolonWeighting",
      "LineBreakWithin",
      "LineColor",
      "LineGraph",
      "LineIndent",
      "LineIndentMaxFraction",
      "LineIntegralConvolutionPlot",
      "LineIntegralConvolutionScale",
      "LineLegend",
      "LineOpacity",
      "LineSpacing",
      "LineWrapParts",
      "LinkActivate",
      "LinkClose",
      "LinkConnect",
      "LinkConnectedQ",
      "LinkCreate",
      "LinkError",
      "LinkFlush",
      "LinkFunction",
      "LinkHost",
      "LinkInterrupt",
      "LinkLaunch",
      "LinkMode",
      "LinkObject",
      "LinkOpen",
      "LinkOptions",
      "LinkPatterns",
      "LinkProtocol",
      "LinkRankCentrality",
      "LinkRead",
      "LinkReadHeld",
      "LinkReadyQ",
      "Links",
      "LinkService",
      "LinkWrite",
      "LinkWriteHeld",
      "LiouvilleLambda",
      "List",
      "Listable",
      "ListAnimate",
      "ListContourPlot",
      "ListContourPlot3D",
      "ListConvolve",
      "ListCorrelate",
      "ListCurvePathPlot",
      "ListDeconvolve",
      "ListDensityPlot",
      "ListDensityPlot3D",
      "Listen",
      "ListFormat",
      "ListFourierSequenceTransform",
      "ListInterpolation",
      "ListLineIntegralConvolutionPlot",
      "ListLinePlot",
      "ListLogLinearPlot",
      "ListLogLogPlot",
      "ListLogPlot",
      "ListPicker",
      "ListPickerBox",
      "ListPickerBoxBackground",
      "ListPickerBoxOptions",
      "ListPlay",
      "ListPlot",
      "ListPlot3D",
      "ListPointPlot3D",
      "ListPolarPlot",
      "ListQ",
      "ListSliceContourPlot3D",
      "ListSliceDensityPlot3D",
      "ListSliceVectorPlot3D",
      "ListStepPlot",
      "ListStreamDensityPlot",
      "ListStreamPlot",
      "ListSurfacePlot3D",
      "ListVectorDensityPlot",
      "ListVectorPlot",
      "ListVectorPlot3D",
      "ListZTransform",
      "Literal",
      "LiteralSearch",
      "LocalAdaptiveBinarize",
      "LocalCache",
      "LocalClusteringCoefficient",
      "LocalizeDefinitions",
      "LocalizeVariables",
      "LocalObject",
      "LocalObjects",
      "LocalResponseNormalizationLayer",
      "LocalSubmit",
      "LocalSymbol",
      "LocalTime",
      "LocalTimeZone",
      "LocationEquivalenceTest",
      "LocationTest",
      "Locator",
      "LocatorAutoCreate",
      "LocatorBox",
      "LocatorBoxOptions",
      "LocatorCentering",
      "LocatorPane",
      "LocatorPaneBox",
      "LocatorPaneBoxOptions",
      "LocatorRegion",
      "Locked",
      "Log",
      "Log10",
      "Log2",
      "LogBarnesG",
      "LogGamma",
      "LogGammaDistribution",
      "LogicalExpand",
      "LogIntegral",
      "LogisticDistribution",
      "LogisticSigmoid",
      "LogitModelFit",
      "LogLikelihood",
      "LogLinearPlot",
      "LogLogisticDistribution",
      "LogLogPlot",
      "LogMultinormalDistribution",
      "LogNormalDistribution",
      "LogPlot",
      "LogRankTest",
      "LogSeriesDistribution",
      "LongEqual",
      "Longest",
      "LongestCommonSequence",
      "LongestCommonSequencePositions",
      "LongestCommonSubsequence",
      "LongestCommonSubsequencePositions",
      "LongestMatch",
      "LongestOrderedSequence",
      "LongForm",
      "Longitude",
      "LongLeftArrow",
      "LongLeftRightArrow",
      "LongRightArrow",
      "LongShortTermMemoryLayer",
      "Lookup",
      "Loopback",
      "LoopFreeGraphQ",
      "Looping",
      "LossFunction",
      "LowerCaseQ",
      "LowerLeftArrow",
      "LowerRightArrow",
      "LowerTriangularize",
      "LowerTriangularMatrixQ",
      "LowpassFilter",
      "LQEstimatorGains",
      "LQGRegulator",
      "LQOutputRegulatorGains",
      "LQRegulatorGains",
      "LUBackSubstitution",
      "LucasL",
      "LuccioSamiComponents",
      "LUDecomposition",
      "LunarEclipse",
      "LUVColor",
      "LyapunovSolve",
      "LyonsGroupLy",
      "MachineID",
      "MachineName",
      "MachineNumberQ",
      "MachinePrecision",
      "MacintoshSystemPageSetup",
      "Magenta",
      "Magnification",
      "Magnify",
      "MailAddressValidation",
      "MailExecute",
      "MailFolder",
      "MailItem",
      "MailReceiverFunction",
      "MailResponseFunction",
      "MailSearch",
      "MailServerConnect",
      "MailServerConnection",
      "MailSettings",
      "MainSolve",
      "MaintainDynamicCaches",
      "Majority",
      "MakeBoxes",
      "MakeExpression",
      "MakeRules",
      "ManagedLibraryExpressionID",
      "ManagedLibraryExpressionQ",
      "MandelbrotSetBoettcher",
      "MandelbrotSetDistance",
      "MandelbrotSetIterationCount",
      "MandelbrotSetMemberQ",
      "MandelbrotSetPlot",
      "MangoldtLambda",
      "ManhattanDistance",
      "Manipulate",
      "Manipulator",
      "MannedSpaceMissionData",
      "MannWhitneyTest",
      "MantissaExponent",
      "Manual",
      "Map",
      "MapAll",
      "MapAt",
      "MapIndexed",
      "MAProcess",
      "MapThread",
      "MarchenkoPasturDistribution",
      "MarcumQ",
      "MardiaCombinedTest",
      "MardiaKurtosisTest",
      "MardiaSkewnessTest",
      "MarginalDistribution",
      "MarkovProcessProperties",
      "Masking",
      "MatchingDissimilarity",
      "MatchLocalNameQ",
      "MatchLocalNames",
      "MatchQ",
      "Material",
      "MathematicalFunctionData",
      "MathematicaNotation",
      "MathieuC",
      "MathieuCharacteristicA",
      "MathieuCharacteristicB",
      "MathieuCharacteristicExponent",
      "MathieuCPrime",
      "MathieuGroupM11",
      "MathieuGroupM12",
      "MathieuGroupM22",
      "MathieuGroupM23",
      "MathieuGroupM24",
      "MathieuS",
      "MathieuSPrime",
      "MathMLForm",
      "MathMLText",
      "Matrices",
      "MatrixExp",
      "MatrixForm",
      "MatrixFunction",
      "MatrixLog",
      "MatrixNormalDistribution",
      "MatrixPlot",
      "MatrixPower",
      "MatrixPropertyDistribution",
      "MatrixQ",
      "MatrixRank",
      "MatrixTDistribution",
      "Max",
      "MaxBend",
      "MaxCellMeasure",
      "MaxColorDistance",
      "MaxDate",
      "MaxDetect",
      "MaxDuration",
      "MaxExtraBandwidths",
      "MaxExtraConditions",
      "MaxFeatureDisplacement",
      "MaxFeatures",
      "MaxFilter",
      "MaximalBy",
      "Maximize",
      "MaxItems",
      "MaxIterations",
      "MaxLimit",
      "MaxMemoryUsed",
      "MaxMixtureKernels",
      "MaxOverlapFraction",
      "MaxPlotPoints",
      "MaxPoints",
      "MaxRecursion",
      "MaxStableDistribution",
      "MaxStepFraction",
      "MaxSteps",
      "MaxStepSize",
      "MaxTrainingRounds",
      "MaxValue",
      "MaxwellDistribution",
      "MaxWordGap",
      "McLaughlinGroupMcL",
      "Mean",
      "MeanAbsoluteLossLayer",
      "MeanAround",
      "MeanClusteringCoefficient",
      "MeanDegreeConnectivity",
      "MeanDeviation",
      "MeanFilter",
      "MeanGraphDistance",
      "MeanNeighborDegree",
      "MeanShift",
      "MeanShiftFilter",
      "MeanSquaredLossLayer",
      "Median",
      "MedianDeviation",
      "MedianFilter",
      "MedicalTestData",
      "Medium",
      "MeijerG",
      "MeijerGReduce",
      "MeixnerDistribution",
      "MellinConvolve",
      "MellinTransform",
      "MemberQ",
      "MemoryAvailable",
      "MemoryConstrained",
      "MemoryConstraint",
      "MemoryInUse",
      "MengerMesh",
      "Menu",
      "MenuAppearance",
      "MenuCommandKey",
      "MenuEvaluator",
      "MenuItem",
      "MenuList",
      "MenuPacket",
      "MenuSortingValue",
      "MenuStyle",
      "MenuView",
      "Merge",
      "MergeDifferences",
      "MergingFunction",
      "MersennePrimeExponent",
      "MersennePrimeExponentQ",
      "Mesh",
      "MeshCellCentroid",
      "MeshCellCount",
      "MeshCellHighlight",
      "MeshCellIndex",
      "MeshCellLabel",
      "MeshCellMarker",
      "MeshCellMeasure",
      "MeshCellQuality",
      "MeshCells",
      "MeshCellShapeFunction",
      "MeshCellStyle",
      "MeshConnectivityGraph",
      "MeshCoordinates",
      "MeshFunctions",
      "MeshPrimitives",
      "MeshQualityGoal",
      "MeshRange",
      "MeshRefinementFunction",
      "MeshRegion",
      "MeshRegionQ",
      "MeshShading",
      "MeshStyle",
      "Message",
      "MessageDialog",
      "MessageList",
      "MessageName",
      "MessageObject",
      "MessageOptions",
      "MessagePacket",
      "Messages",
      "MessagesNotebook",
      "MetaCharacters",
      "MetaInformation",
      "MeteorShowerData",
      "Method",
      "MethodOptions",
      "MexicanHatWavelet",
      "MeyerWavelet",
      "Midpoint",
      "Min",
      "MinColorDistance",
      "MinDate",
      "MinDetect",
      "MineralData",
      "MinFilter",
      "MinimalBy",
      "MinimalPolynomial",
      "MinimalStateSpaceModel",
      "Minimize",
      "MinimumTimeIncrement",
      "MinIntervalSize",
      "MinkowskiQuestionMark",
      "MinLimit",
      "MinMax",
      "MinorPlanetData",
      "Minors",
      "MinRecursion",
      "MinSize",
      "MinStableDistribution",
      "Minus",
      "MinusPlus",
      "MinValue",
      "Missing",
      "MissingBehavior",
      "MissingDataMethod",
      "MissingDataRules",
      "MissingQ",
      "MissingString",
      "MissingStyle",
      "MissingValuePattern",
      "MittagLefflerE",
      "MixedFractionParts",
      "MixedGraphQ",
      "MixedMagnitude",
      "MixedRadix",
      "MixedRadixQuantity",
      "MixedUnit",
      "MixtureDistribution",
      "Mod",
      "Modal",
      "Mode",
      "Modular",
      "ModularInverse",
      "ModularLambda",
      "Module",
      "Modulus",
      "MoebiusMu",
      "Molecule",
      "MoleculeContainsQ",
      "MoleculeEquivalentQ",
      "MoleculeGraph",
      "MoleculeModify",
      "MoleculePattern",
      "MoleculePlot",
      "MoleculePlot3D",
      "MoleculeProperty",
      "MoleculeQ",
      "MoleculeRecognize",
      "MoleculeValue",
      "Moment",
      "Momentary",
      "MomentConvert",
      "MomentEvaluate",
      "MomentGeneratingFunction",
      "MomentOfInertia",
      "Monday",
      "Monitor",
      "MonomialList",
      "MonomialOrder",
      "MonsterGroupM",
      "MoonPhase",
      "MoonPosition",
      "MorletWavelet",
      "MorphologicalBinarize",
      "MorphologicalBranchPoints",
      "MorphologicalComponents",
      "MorphologicalEulerNumber",
      "MorphologicalGraph",
      "MorphologicalPerimeter",
      "MorphologicalTransform",
      "MortalityData",
      "Most",
      "MountainData",
      "MouseAnnotation",
      "MouseAppearance",
      "MouseAppearanceTag",
      "MouseButtons",
      "Mouseover",
      "MousePointerNote",
      "MousePosition",
      "MovieData",
      "MovingAverage",
      "MovingMap",
      "MovingMedian",
      "MoyalDistribution",
      "Multicolumn",
      "MultiedgeStyle",
      "MultigraphQ",
      "MultilaunchWarning",
      "MultiLetterItalics",
      "MultiLetterStyle",
      "MultilineFunction",
      "Multinomial",
      "MultinomialDistribution",
      "MultinormalDistribution",
      "MultiplicativeOrder",
      "Multiplicity",
      "MultiplySides",
      "Multiselection",
      "MultivariateHypergeometricDistribution",
      "MultivariatePoissonDistribution",
      "MultivariateTDistribution",
      "N",
      "NakagamiDistribution",
      "NameQ",
      "Names",
      "NamespaceBox",
      "NamespaceBoxOptions",
      "Nand",
      "NArgMax",
      "NArgMin",
      "NBernoulliB",
      "NBodySimulation",
      "NBodySimulationData",
      "NCache",
      "NDEigensystem",
      "NDEigenvalues",
      "NDSolve",
      "NDSolveValue",
      "Nearest",
      "NearestFunction",
      "NearestMeshCells",
      "NearestNeighborGraph",
      "NearestTo",
      "NebulaData",
      "NeedCurrentFrontEndPackagePacket",
      "NeedCurrentFrontEndSymbolsPacket",
      "NeedlemanWunschSimilarity",
      "Needs",
      "Negative",
      "NegativeBinomialDistribution",
      "NegativeDefiniteMatrixQ",
      "NegativeIntegers",
      "NegativeMultinomialDistribution",
      "NegativeRationals",
      "NegativeReals",
      "NegativeSemidefiniteMatrixQ",
      "NeighborhoodData",
      "NeighborhoodGraph",
      "Nest",
      "NestedGreaterGreater",
      "NestedLessLess",
      "NestedScriptRules",
      "NestGraph",
      "NestList",
      "NestWhile",
      "NestWhileList",
      "NetAppend",
      "NetBidirectionalOperator",
      "NetChain",
      "NetDecoder",
      "NetDelete",
      "NetDrop",
      "NetEncoder",
      "NetEvaluationMode",
      "NetExtract",
      "NetFlatten",
      "NetFoldOperator",
      "NetGANOperator",
      "NetGraph",
      "NetInformation",
      "NetInitialize",
      "NetInsert",
      "NetInsertSharedArrays",
      "NetJoin",
      "NetMapOperator",
      "NetMapThreadOperator",
      "NetMeasurements",
      "NetModel",
      "NetNestOperator",
      "NetPairEmbeddingOperator",
      "NetPort",
      "NetPortGradient",
      "NetPrepend",
      "NetRename",
      "NetReplace",
      "NetReplacePart",
      "NetSharedArray",
      "NetStateObject",
      "NetTake",
      "NetTrain",
      "NetTrainResultsObject",
      "NetworkPacketCapture",
      "NetworkPacketRecording",
      "NetworkPacketRecordingDuring",
      "NetworkPacketTrace",
      "NeumannValue",
      "NevilleThetaC",
      "NevilleThetaD",
      "NevilleThetaN",
      "NevilleThetaS",
      "NewPrimitiveStyle",
      "NExpectation",
      "Next",
      "NextCell",
      "NextDate",
      "NextPrime",
      "NextScheduledTaskTime",
      "NHoldAll",
      "NHoldFirst",
      "NHoldRest",
      "NicholsGridLines",
      "NicholsPlot",
      "NightHemisphere",
      "NIntegrate",
      "NMaximize",
      "NMaxValue",
      "NMinimize",
      "NMinValue",
      "NominalVariables",
      "NonAssociative",
      "NoncentralBetaDistribution",
      "NoncentralChiSquareDistribution",
      "NoncentralFRatioDistribution",
      "NoncentralStudentTDistribution",
      "NonCommutativeMultiply",
      "NonConstants",
      "NondimensionalizationTransform",
      "None",
      "NoneTrue",
      "NonlinearModelFit",
      "NonlinearStateSpaceModel",
      "NonlocalMeansFilter",
      "NonNegative",
      "NonNegativeIntegers",
      "NonNegativeRationals",
      "NonNegativeReals",
      "NonPositive",
      "NonPositiveIntegers",
      "NonPositiveRationals",
      "NonPositiveReals",
      "Nor",
      "NorlundB",
      "Norm",
      "Normal",
      "NormalDistribution",
      "NormalGrouping",
      "NormalizationLayer",
      "Normalize",
      "Normalized",
      "NormalizedSquaredEuclideanDistance",
      "NormalMatrixQ",
      "NormalsFunction",
      "NormFunction",
      "Not",
      "NotCongruent",
      "NotCupCap",
      "NotDoubleVerticalBar",
      "Notebook",
      "NotebookApply",
      "NotebookAutoSave",
      "NotebookClose",
      "NotebookConvertSettings",
      "NotebookCreate",
      "NotebookCreateReturnObject",
      "NotebookDefault",
      "NotebookDelete",
      "NotebookDirectory",
      "NotebookDynamicExpression",
      "NotebookEvaluate",
      "NotebookEventActions",
      "NotebookFileName",
      "NotebookFind",
      "NotebookFindReturnObject",
      "NotebookGet",
      "NotebookGetLayoutInformationPacket",
      "NotebookGetMisspellingsPacket",
      "NotebookImport",
      "NotebookInformation",
      "NotebookInterfaceObject",
      "NotebookLocate",
      "NotebookObject",
      "NotebookOpen",
      "NotebookOpenReturnObject",
      "NotebookPath",
      "NotebookPrint",
      "NotebookPut",
      "NotebookPutReturnObject",
      "NotebookRead",
      "NotebookResetGeneratedCells",
      "Notebooks",
      "NotebookSave",
      "NotebookSaveAs",
      "NotebookSelection",
      "NotebookSetupLayoutInformationPacket",
      "NotebooksMenu",
      "NotebookTemplate",
      "NotebookWrite",
      "NotElement",
      "NotEqualTilde",
      "NotExists",
      "NotGreater",
      "NotGreaterEqual",
      "NotGreaterFullEqual",
      "NotGreaterGreater",
      "NotGreaterLess",
      "NotGreaterSlantEqual",
      "NotGreaterTilde",
      "Nothing",
      "NotHumpDownHump",
      "NotHumpEqual",
      "NotificationFunction",
      "NotLeftTriangle",
      "NotLeftTriangleBar",
      "NotLeftTriangleEqual",
      "NotLess",
      "NotLessEqual",
      "NotLessFullEqual",
      "NotLessGreater",
      "NotLessLess",
      "NotLessSlantEqual",
      "NotLessTilde",
      "NotNestedGreaterGreater",
      "NotNestedLessLess",
      "NotPrecedes",
      "NotPrecedesEqual",
      "NotPrecedesSlantEqual",
      "NotPrecedesTilde",
      "NotReverseElement",
      "NotRightTriangle",
      "NotRightTriangleBar",
      "NotRightTriangleEqual",
      "NotSquareSubset",
      "NotSquareSubsetEqual",
      "NotSquareSuperset",
      "NotSquareSupersetEqual",
      "NotSubset",
      "NotSubsetEqual",
      "NotSucceeds",
      "NotSucceedsEqual",
      "NotSucceedsSlantEqual",
      "NotSucceedsTilde",
      "NotSuperset",
      "NotSupersetEqual",
      "NotTilde",
      "NotTildeEqual",
      "NotTildeFullEqual",
      "NotTildeTilde",
      "NotVerticalBar",
      "Now",
      "NoWhitespace",
      "NProbability",
      "NProduct",
      "NProductFactors",
      "NRoots",
      "NSolve",
      "NSum",
      "NSumTerms",
      "NuclearExplosionData",
      "NuclearReactorData",
      "Null",
      "NullRecords",
      "NullSpace",
      "NullWords",
      "Number",
      "NumberCompose",
      "NumberDecompose",
      "NumberExpand",
      "NumberFieldClassNumber",
      "NumberFieldDiscriminant",
      "NumberFieldFundamentalUnits",
      "NumberFieldIntegralBasis",
      "NumberFieldNormRepresentatives",
      "NumberFieldRegulator",
      "NumberFieldRootsOfUnity",
      "NumberFieldSignature",
      "NumberForm",
      "NumberFormat",
      "NumberLinePlot",
      "NumberMarks",
      "NumberMultiplier",
      "NumberPadding",
      "NumberPoint",
      "NumberQ",
      "NumberSeparator",
      "NumberSigns",
      "NumberString",
      "Numerator",
      "NumeratorDenominator",
      "NumericalOrder",
      "NumericalSort",
      "NumericArray",
      "NumericArrayQ",
      "NumericArrayType",
      "NumericFunction",
      "NumericQ",
      "NuttallWindow",
      "NValues",
      "NyquistGridLines",
      "NyquistPlot",
      "O",
      "ObservabilityGramian",
      "ObservabilityMatrix",
      "ObservableDecomposition",
      "ObservableModelQ",
      "OceanData",
      "Octahedron",
      "OddQ",
      "Off",
      "Offset",
      "OLEData",
      "On",
      "ONanGroupON",
      "Once",
      "OneIdentity",
      "Opacity",
      "OpacityFunction",
      "OpacityFunctionScaling",
      "Open",
      "OpenAppend",
      "Opener",
      "OpenerBox",
      "OpenerBoxOptions",
      "OpenerView",
      "OpenFunctionInspectorPacket",
      "Opening",
      "OpenRead",
      "OpenSpecialOptions",
      "OpenTemporary",
      "OpenWrite",
      "Operate",
      "OperatingSystem",
      "OperatorApplied",
      "OptimumFlowData",
      "Optional",
      "OptionalElement",
      "OptionInspectorSettings",
      "OptionQ",
      "Options",
      "OptionsPacket",
      "OptionsPattern",
      "OptionValue",
      "OptionValueBox",
      "OptionValueBoxOptions",
      "Or",
      "Orange",
      "Order",
      "OrderDistribution",
      "OrderedQ",
      "Ordering",
      "OrderingBy",
      "OrderingLayer",
      "Orderless",
      "OrderlessPatternSequence",
      "OrnsteinUhlenbeckProcess",
      "Orthogonalize",
      "OrthogonalMatrixQ",
      "Out",
      "Outer",
      "OuterPolygon",
      "OuterPolyhedron",
      "OutputAutoOverwrite",
      "OutputControllabilityMatrix",
      "OutputControllableModelQ",
      "OutputForm",
      "OutputFormData",
      "OutputGrouping",
      "OutputMathEditExpression",
      "OutputNamePacket",
      "OutputResponse",
      "OutputSizeLimit",
      "OutputStream",
      "Over",
      "OverBar",
      "OverDot",
      "Overflow",
      "OverHat",
      "Overlaps",
      "Overlay",
      "OverlayBox",
      "OverlayBoxOptions",
      "Overscript",
      "OverscriptBox",
      "OverscriptBoxOptions",
      "OverTilde",
      "OverVector",
      "OverwriteTarget",
      "OwenT",
      "OwnValues",
      "Package",
      "PackingMethod",
      "PackPaclet",
      "PacletDataRebuild",
      "PacletDirectoryAdd",
      "PacletDirectoryLoad",
      "PacletDirectoryRemove",
      "PacletDirectoryUnload",
      "PacletDisable",
      "PacletEnable",
      "PacletFind",
      "PacletFindRemote",
      "PacletInformation",
      "PacletInstall",
      "PacletInstallSubmit",
      "PacletNewerQ",
      "PacletObject",
      "PacletObjectQ",
      "PacletSite",
      "PacletSiteObject",
      "PacletSiteRegister",
      "PacletSites",
      "PacletSiteUnregister",
      "PacletSiteUpdate",
      "PacletUninstall",
      "PacletUpdate",
      "PaddedForm",
      "Padding",
      "PaddingLayer",
      "PaddingSize",
      "PadeApproximant",
      "PadLeft",
      "PadRight",
      "PageBreakAbove",
      "PageBreakBelow",
      "PageBreakWithin",
      "PageFooterLines",
      "PageFooters",
      "PageHeaderLines",
      "PageHeaders",
      "PageHeight",
      "PageRankCentrality",
      "PageTheme",
      "PageWidth",
      "Pagination",
      "PairedBarChart",
      "PairedHistogram",
      "PairedSmoothHistogram",
      "PairedTTest",
      "PairedZTest",
      "PaletteNotebook",
      "PalettePath",
      "PalindromeQ",
      "Pane",
      "PaneBox",
      "PaneBoxOptions",
      "Panel",
      "PanelBox",
      "PanelBoxOptions",
      "Paneled",
      "PaneSelector",
      "PaneSelectorBox",
      "PaneSelectorBoxOptions",
      "PaperWidth",
      "ParabolicCylinderD",
      "ParagraphIndent",
      "ParagraphSpacing",
      "ParallelArray",
      "ParallelCombine",
      "ParallelDo",
      "Parallelepiped",
      "ParallelEvaluate",
      "Parallelization",
      "Parallelize",
      "ParallelMap",
      "ParallelNeeds",
      "Parallelogram",
      "ParallelProduct",
      "ParallelSubmit",
      "ParallelSum",
      "ParallelTable",
      "ParallelTry",
      "Parameter",
      "ParameterEstimator",
      "ParameterMixtureDistribution",
      "ParameterVariables",
      "ParametricFunction",
      "ParametricNDSolve",
      "ParametricNDSolveValue",
      "ParametricPlot",
      "ParametricPlot3D",
      "ParametricRampLayer",
      "ParametricRegion",
      "ParentBox",
      "ParentCell",
      "ParentConnect",
      "ParentDirectory",
      "ParentForm",
      "Parenthesize",
      "ParentList",
      "ParentNotebook",
      "ParetoDistribution",
      "ParetoPickandsDistribution",
      "ParkData",
      "Part",
      "PartBehavior",
      "PartialCorrelationFunction",
      "PartialD",
      "ParticleAcceleratorData",
      "ParticleData",
      "Partition",
      "PartitionGranularity",
      "PartitionsP",
      "PartitionsQ",
      "PartLayer",
      "PartOfSpeech",
      "PartProtection",
      "ParzenWindow",
      "PascalDistribution",
      "PassEventsDown",
      "PassEventsUp",
      "Paste",
      "PasteAutoQuoteCharacters",
      "PasteBoxFormInlineCells",
      "PasteButton",
      "Path",
      "PathGraph",
      "PathGraphQ",
      "Pattern",
      "PatternFilling",
      "PatternSequence",
      "PatternTest",
      "PauliMatrix",
      "PaulWavelet",
      "Pause",
      "PausedTime",
      "PDF",
      "PeakDetect",
      "PeanoCurve",
      "PearsonChiSquareTest",
      "PearsonCorrelationTest",
      "PearsonDistribution",
      "PercentForm",
      "PerfectNumber",
      "PerfectNumberQ",
      "PerformanceGoal",
      "Perimeter",
      "PeriodicBoundaryCondition",
      "PeriodicInterpolation",
      "Periodogram",
      "PeriodogramArray",
      "Permanent",
      "Permissions",
      "PermissionsGroup",
      "PermissionsGroupMemberQ",
      "PermissionsGroups",
      "PermissionsKey",
      "PermissionsKeys",
      "PermutationCycles",
      "PermutationCyclesQ",
      "PermutationGroup",
      "PermutationLength",
      "PermutationList",
      "PermutationListQ",
      "PermutationMax",
      "PermutationMin",
      "PermutationOrder",
      "PermutationPower",
      "PermutationProduct",
      "PermutationReplace",
      "Permutations",
      "PermutationSupport",
      "Permute",
      "PeronaMalikFilter",
      "Perpendicular",
      "PerpendicularBisector",
      "PersistenceLocation",
      "PersistenceTime",
      "PersistentObject",
      "PersistentObjects",
      "PersistentValue",
      "PersonData",
      "PERTDistribution",
      "PetersenGraph",
      "PhaseMargins",
      "PhaseRange",
      "PhysicalSystemData",
      "Pi",
      "Pick",
      "PIDData",
      "PIDDerivativeFilter",
      "PIDFeedforward",
      "PIDTune",
      "Piecewise",
      "PiecewiseExpand",
      "PieChart",
      "PieChart3D",
      "PillaiTrace",
      "PillaiTraceTest",
      "PingTime",
      "Pink",
      "PitchRecognize",
      "Pivoting",
      "PixelConstrained",
      "PixelValue",
      "PixelValuePositions",
      "Placed",
      "Placeholder",
      "PlaceholderReplace",
      "Plain",
      "PlanarAngle",
      "PlanarGraph",
      "PlanarGraphQ",
      "PlanckRadiationLaw",
      "PlaneCurveData",
      "PlanetaryMoonData",
      "PlanetData",
      "PlantData",
      "Play",
      "PlayRange",
      "Plot",
      "Plot3D",
      "Plot3Matrix",
      "PlotDivision",
      "PlotJoined",
      "PlotLabel",
      "PlotLabels",
      "PlotLayout",
      "PlotLegends",
      "PlotMarkers",
      "PlotPoints",
      "PlotRange",
      "PlotRangeClipping",
      "PlotRangeClipPlanesStyle",
      "PlotRangePadding",
      "PlotRegion",
      "PlotStyle",
      "PlotTheme",
      "Pluralize",
      "Plus",
      "PlusMinus",
      "Pochhammer",
      "PodStates",
      "PodWidth",
      "Point",
      "Point3DBox",
      "Point3DBoxOptions",
      "PointBox",
      "PointBoxOptions",
      "PointFigureChart",
      "PointLegend",
      "PointSize",
      "PoissonConsulDistribution",
      "PoissonDistribution",
      "PoissonProcess",
      "PoissonWindow",
      "PolarAxes",
      "PolarAxesOrigin",
      "PolarGridLines",
      "PolarPlot",
      "PolarTicks",
      "PoleZeroMarkers",
      "PolyaAeppliDistribution",
      "PolyGamma",
      "Polygon",
      "Polygon3DBox",
      "Polygon3DBoxOptions",
      "PolygonalNumber",
      "PolygonAngle",
      "PolygonBox",
      "PolygonBoxOptions",
      "PolygonCoordinates",
      "PolygonDecomposition",
      "PolygonHoleScale",
      "PolygonIntersections",
      "PolygonScale",
      "Polyhedron",
      "PolyhedronAngle",
      "PolyhedronCoordinates",
      "PolyhedronData",
      "PolyhedronDecomposition",
      "PolyhedronGenus",
      "PolyLog",
      "PolynomialExtendedGCD",
      "PolynomialForm",
      "PolynomialGCD",
      "PolynomialLCM",
      "PolynomialMod",
      "PolynomialQ",
      "PolynomialQuotient",
      "PolynomialQuotientRemainder",
      "PolynomialReduce",
      "PolynomialRemainder",
      "Polynomials",
      "PoolingLayer",
      "PopupMenu",
      "PopupMenuBox",
      "PopupMenuBoxOptions",
      "PopupView",
      "PopupWindow",
      "Position",
      "PositionIndex",
      "Positive",
      "PositiveDefiniteMatrixQ",
      "PositiveIntegers",
      "PositiveRationals",
      "PositiveReals",
      "PositiveSemidefiniteMatrixQ",
      "PossibleZeroQ",
      "Postfix",
      "PostScript",
      "Power",
      "PowerDistribution",
      "PowerExpand",
      "PowerMod",
      "PowerModList",
      "PowerRange",
      "PowerSpectralDensity",
      "PowersRepresentations",
      "PowerSymmetricPolynomial",
      "Precedence",
      "PrecedenceForm",
      "Precedes",
      "PrecedesEqual",
      "PrecedesSlantEqual",
      "PrecedesTilde",
      "Precision",
      "PrecisionGoal",
      "PreDecrement",
      "Predict",
      "PredictionRoot",
      "PredictorFunction",
      "PredictorInformation",
      "PredictorMeasurements",
      "PredictorMeasurementsObject",
      "PreemptProtect",
      "PreferencesPath",
      "Prefix",
      "PreIncrement",
      "Prepend",
      "PrependLayer",
      "PrependTo",
      "PreprocessingRules",
      "PreserveColor",
      "PreserveImageOptions",
      "Previous",
      "PreviousCell",
      "PreviousDate",
      "PriceGraphDistribution",
      "PrimaryPlaceholder",
      "Prime",
      "PrimeNu",
      "PrimeOmega",
      "PrimePi",
      "PrimePowerQ",
      "PrimeQ",
      "Primes",
      "PrimeZetaP",
      "PrimitivePolynomialQ",
      "PrimitiveRoot",
      "PrimitiveRootList",
      "PrincipalComponents",
      "PrincipalValue",
      "Print",
      "PrintableASCIIQ",
      "PrintAction",
      "PrintForm",
      "PrintingCopies",
      "PrintingOptions",
      "PrintingPageRange",
      "PrintingStartingPageNumber",
      "PrintingStyleEnvironment",
      "Printout3D",
      "Printout3DPreviewer",
      "PrintPrecision",
      "PrintTemporary",
      "Prism",
      "PrismBox",
      "PrismBoxOptions",
      "PrivateCellOptions",
      "PrivateEvaluationOptions",
      "PrivateFontOptions",
      "PrivateFrontEndOptions",
      "PrivateKey",
      "PrivateNotebookOptions",
      "PrivatePaths",
      "Probability",
      "ProbabilityDistribution",
      "ProbabilityPlot",
      "ProbabilityPr",
      "ProbabilityScalePlot",
      "ProbitModelFit",
      "ProcessConnection",
      "ProcessDirectory",
      "ProcessEnvironment",
      "Processes",
      "ProcessEstimator",
      "ProcessInformation",
      "ProcessObject",
      "ProcessParameterAssumptions",
      "ProcessParameterQ",
      "ProcessStateDomain",
      "ProcessStatus",
      "ProcessTimeDomain",
      "Product",
      "ProductDistribution",
      "ProductLog",
      "ProgressIndicator",
      "ProgressIndicatorBox",
      "ProgressIndicatorBoxOptions",
      "Projection",
      "Prolog",
      "PromptForm",
      "ProofObject",
      "Properties",
      "Property",
      "PropertyList",
      "PropertyValue",
      "Proportion",
      "Proportional",
      "Protect",
      "Protected",
      "ProteinData",
      "Pruning",
      "PseudoInverse",
      "PsychrometricPropertyData",
      "PublicKey",
      "PublisherID",
      "PulsarData",
      "PunctuationCharacter",
      "Purple",
      "Put",
      "PutAppend",
      "Pyramid",
      "PyramidBox",
      "PyramidBoxOptions",
      "QBinomial",
      "QFactorial",
      "QGamma",
      "QHypergeometricPFQ",
      "QnDispersion",
      "QPochhammer",
      "QPolyGamma",
      "QRDecomposition",
      "QuadraticIrrationalQ",
      "QuadraticOptimization",
      "Quantile",
      "QuantilePlot",
      "Quantity",
      "QuantityArray",
      "QuantityDistribution",
      "QuantityForm",
      "QuantityMagnitude",
      "QuantityQ",
      "QuantityUnit",
      "QuantityVariable",
      "QuantityVariableCanonicalUnit",
      "QuantityVariableDimensions",
      "QuantityVariableIdentifier",
      "QuantityVariablePhysicalQuantity",
      "Quartics",
      "QuartileDeviation",
      "Quartiles",
      "QuartileSkewness",
      "Query",
      "QueueingNetworkProcess",
      "QueueingProcess",
      "QueueProperties",
      "Quiet",
      "Quit",
      "Quotient",
      "QuotientRemainder",
      "RadialGradientImage",
      "RadialityCentrality",
      "RadicalBox",
      "RadicalBoxOptions",
      "RadioButton",
      "RadioButtonBar",
      "RadioButtonBox",
      "RadioButtonBoxOptions",
      "Radon",
      "RadonTransform",
      "RamanujanTau",
      "RamanujanTauL",
      "RamanujanTauTheta",
      "RamanujanTauZ",
      "Ramp",
      "Random",
      "RandomChoice",
      "RandomColor",
      "RandomComplex",
      "RandomEntity",
      "RandomFunction",
      "RandomGeoPosition",
      "RandomGraph",
      "RandomImage",
      "RandomInstance",
      "RandomInteger",
      "RandomPermutation",
      "RandomPoint",
      "RandomPolygon",
      "RandomPolyhedron",
      "RandomPrime",
      "RandomReal",
      "RandomSample",
      "RandomSeed",
      "RandomSeeding",
      "RandomVariate",
      "RandomWalkProcess",
      "RandomWord",
      "Range",
      "RangeFilter",
      "RangeSpecification",
      "RankedMax",
      "RankedMin",
      "RarerProbability",
      "Raster",
      "Raster3D",
      "Raster3DBox",
      "Raster3DBoxOptions",
      "RasterArray",
      "RasterBox",
      "RasterBoxOptions",
      "Rasterize",
      "RasterSize",
      "Rational",
      "RationalFunctions",
      "Rationalize",
      "Rationals",
      "Ratios",
      "RawArray",
      "RawBoxes",
      "RawData",
      "RawMedium",
      "RayleighDistribution",
      "Re",
      "Read",
      "ReadByteArray",
      "ReadLine",
      "ReadList",
      "ReadProtected",
      "ReadString",
      "Real",
      "RealAbs",
      "RealBlockDiagonalForm",
      "RealDigits",
      "RealExponent",
      "Reals",
      "RealSign",
      "Reap",
      "RebuildPacletData",
      "RecognitionPrior",
      "RecognitionThreshold",
      "Record",
      "RecordLists",
      "RecordSeparators",
      "Rectangle",
      "RectangleBox",
      "RectangleBoxOptions",
      "RectangleChart",
      "RectangleChart3D",
      "RectangularRepeatingElement",
      "RecurrenceFilter",
      "RecurrenceTable",
      "RecurringDigitsForm",
      "Red",
      "Reduce",
      "RefBox",
      "ReferenceLineStyle",
      "ReferenceMarkers",
      "ReferenceMarkerStyle",
      "Refine",
      "ReflectionMatrix",
      "ReflectionTransform",
      "Refresh",
      "RefreshRate",
      "Region",
      "RegionBinarize",
      "RegionBoundary",
      "RegionBoundaryStyle",
      "RegionBounds",
      "RegionCentroid",
      "RegionDifference",
      "RegionDimension",
      "RegionDisjoint",
      "RegionDistance",
      "RegionDistanceFunction",
      "RegionEmbeddingDimension",
      "RegionEqual",
      "RegionFillingStyle",
      "RegionFunction",
      "RegionImage",
      "RegionIntersection",
      "RegionMeasure",
      "RegionMember",
      "RegionMemberFunction",
      "RegionMoment",
      "RegionNearest",
      "RegionNearestFunction",
      "RegionPlot",
      "RegionPlot3D",
      "RegionProduct",
      "RegionQ",
      "RegionResize",
      "RegionSize",
      "RegionSymmetricDifference",
      "RegionUnion",
      "RegionWithin",
      "RegisterExternalEvaluator",
      "RegularExpression",
      "Regularization",
      "RegularlySampledQ",
      "RegularPolygon",
      "ReIm",
      "ReImLabels",
      "ReImPlot",
      "ReImStyle",
      "Reinstall",
      "RelationalDatabase",
      "RelationGraph",
      "Release",
      "ReleaseHold",
      "ReliabilityDistribution",
      "ReliefImage",
      "ReliefPlot",
      "RemoteAuthorizationCaching",
      "RemoteConnect",
      "RemoteConnectionObject",
      "RemoteFile",
      "RemoteRun",
      "RemoteRunProcess",
      "Remove",
      "RemoveAlphaChannel",
      "RemoveAsynchronousTask",
      "RemoveAudioStream",
      "RemoveBackground",
      "RemoveChannelListener",
      "RemoveChannelSubscribers",
      "Removed",
      "RemoveDiacritics",
      "RemoveInputStreamMethod",
      "RemoveOutputStreamMethod",
      "RemoveProperty",
      "RemoveScheduledTask",
      "RemoveUsers",
      "RemoveVideoStream",
      "RenameDirectory",
      "RenameFile",
      "RenderAll",
      "RenderingOptions",
      "RenewalProcess",
      "RenkoChart",
      "RepairMesh",
      "Repeated",
      "RepeatedNull",
      "RepeatedString",
      "RepeatedTiming",
      "RepeatingElement",
      "Replace",
      "ReplaceAll",
      "ReplaceHeldPart",
      "ReplaceImageValue",
      "ReplaceList",
      "ReplacePart",
      "ReplacePixelValue",
      "ReplaceRepeated",
      "ReplicateLayer",
      "RequiredPhysicalQuantities",
      "Resampling",
      "ResamplingAlgorithmData",
      "ResamplingMethod",
      "Rescale",
      "RescalingTransform",
      "ResetDirectory",
      "ResetMenusPacket",
      "ResetScheduledTask",
      "ReshapeLayer",
      "Residue",
      "ResizeLayer",
      "Resolve",
      "ResourceAcquire",
      "ResourceData",
      "ResourceFunction",
      "ResourceObject",
      "ResourceRegister",
      "ResourceRemove",
      "ResourceSearch",
      "ResourceSubmissionObject",
      "ResourceSubmit",
      "ResourceSystemBase",
      "ResourceSystemPath",
      "ResourceUpdate",
      "ResourceVersion",
      "ResponseForm",
      "Rest",
      "RestartInterval",
      "Restricted",
      "Resultant",
      "ResumePacket",
      "Return",
      "ReturnEntersInput",
      "ReturnExpressionPacket",
      "ReturnInputFormPacket",
      "ReturnPacket",
      "ReturnReceiptFunction",
      "ReturnTextPacket",
      "Reverse",
      "ReverseApplied",
      "ReverseBiorthogonalSplineWavelet",
      "ReverseElement",
      "ReverseEquilibrium",
      "ReverseGraph",
      "ReverseSort",
      "ReverseSortBy",
      "ReverseUpEquilibrium",
      "RevolutionAxis",
      "RevolutionPlot3D",
      "RGBColor",
      "RiccatiSolve",
      "RiceDistribution",
      "RidgeFilter",
      "RiemannR",
      "RiemannSiegelTheta",
      "RiemannSiegelZ",
      "RiemannXi",
      "Riffle",
      "Right",
      "RightArrow",
      "RightArrowBar",
      "RightArrowLeftArrow",
      "RightComposition",
      "RightCosetRepresentative",
      "RightDownTeeVector",
      "RightDownVector",
      "RightDownVectorBar",
      "RightTee",
      "RightTeeArrow",
      "RightTeeVector",
      "RightTriangle",
      "RightTriangleBar",
      "RightTriangleEqual",
      "RightUpDownVector",
      "RightUpTeeVector",
      "RightUpVector",
      "RightUpVectorBar",
      "RightVector",
      "RightVectorBar",
      "RiskAchievementImportance",
      "RiskReductionImportance",
      "RogersTanimotoDissimilarity",
      "RollPitchYawAngles",
      "RollPitchYawMatrix",
      "RomanNumeral",
      "Root",
      "RootApproximant",
      "RootIntervals",
      "RootLocusPlot",
      "RootMeanSquare",
      "RootOfUnityQ",
      "RootReduce",
      "Roots",
      "RootSum",
      "Rotate",
      "RotateLabel",
      "RotateLeft",
      "RotateRight",
      "RotationAction",
      "RotationBox",
      "RotationBoxOptions",
      "RotationMatrix",
      "RotationTransform",
      "Round",
      "RoundImplies",
      "RoundingRadius",
      "Row",
      "RowAlignments",
      "RowBackgrounds",
      "RowBox",
      "RowHeights",
      "RowLines",
      "RowMinHeight",
      "RowReduce",
      "RowsEqual",
      "RowSpacings",
      "RSolve",
      "RSolveValue",
      "RudinShapiro",
      "RudvalisGroupRu",
      "Rule",
      "RuleCondition",
      "RuleDelayed",
      "RuleForm",
      "RulePlot",
      "RulerUnits",
      "Run",
      "RunProcess",
      "RunScheduledTask",
      "RunThrough",
      "RuntimeAttributes",
      "RuntimeOptions",
      "RussellRaoDissimilarity",
      "SameQ",
      "SameTest",
      "SameTestProperties",
      "SampledEntityClass",
      "SampleDepth",
      "SampledSoundFunction",
      "SampledSoundList",
      "SampleRate",
      "SamplingPeriod",
      "SARIMAProcess",
      "SARMAProcess",
      "SASTriangle",
      "SatelliteData",
      "SatisfiabilityCount",
      "SatisfiabilityInstances",
      "SatisfiableQ",
      "Saturday",
      "Save",
      "Saveable",
      "SaveAutoDelete",
      "SaveConnection",
      "SaveDefinitions",
      "SavitzkyGolayMatrix",
      "SawtoothWave",
      "Scale",
      "Scaled",
      "ScaleDivisions",
      "ScaledMousePosition",
      "ScaleOrigin",
      "ScalePadding",
      "ScaleRanges",
      "ScaleRangeStyle",
      "ScalingFunctions",
      "ScalingMatrix",
      "ScalingTransform",
      "Scan",
      "ScheduledTask",
      "ScheduledTaskActiveQ",
      "ScheduledTaskInformation",
      "ScheduledTaskInformationData",
      "ScheduledTaskObject",
      "ScheduledTasks",
      "SchurDecomposition",
      "ScientificForm",
      "ScientificNotationThreshold",
      "ScorerGi",
      "ScorerGiPrime",
      "ScorerHi",
      "ScorerHiPrime",
      "ScreenRectangle",
      "ScreenStyleEnvironment",
      "ScriptBaselineShifts",
      "ScriptForm",
      "ScriptLevel",
      "ScriptMinSize",
      "ScriptRules",
      "ScriptSizeMultipliers",
      "Scrollbars",
      "ScrollingOptions",
      "ScrollPosition",
      "SearchAdjustment",
      "SearchIndexObject",
      "SearchIndices",
      "SearchQueryString",
      "SearchResultObject",
      "Sec",
      "Sech",
      "SechDistribution",
      "SecondOrderConeOptimization",
      "SectionGrouping",
      "SectorChart",
      "SectorChart3D",
      "SectorOrigin",
      "SectorSpacing",
      "SecuredAuthenticationKey",
      "SecuredAuthenticationKeys",
      "SeedRandom",
      "Select",
      "Selectable",
      "SelectComponents",
      "SelectedCells",
      "SelectedNotebook",
      "SelectFirst",
      "Selection",
      "SelectionAnimate",
      "SelectionCell",
      "SelectionCellCreateCell",
      "SelectionCellDefaultStyle",
      "SelectionCellParentStyle",
      "SelectionCreateCell",
      "SelectionDebuggerTag",
      "SelectionDuplicateCell",
      "SelectionEvaluate",
      "SelectionEvaluateCreateCell",
      "SelectionMove",
      "SelectionPlaceholder",
      "SelectionSetStyle",
      "SelectWithContents",
      "SelfLoops",
      "SelfLoopStyle",
      "SemanticImport",
      "SemanticImportString",
      "SemanticInterpretation",
      "SemialgebraicComponentInstances",
      "SemidefiniteOptimization",
      "SendMail",
      "SendMessage",
      "Sequence",
      "SequenceAlignment",
      "SequenceAttentionLayer",
      "SequenceCases",
      "SequenceCount",
      "SequenceFold",
      "SequenceFoldList",
      "SequenceForm",
      "SequenceHold",
      "SequenceLastLayer",
      "SequenceMostLayer",
      "SequencePosition",
      "SequencePredict",
      "SequencePredictorFunction",
      "SequenceReplace",
      "SequenceRestLayer",
      "SequenceReverseLayer",
      "SequenceSplit",
      "Series",
      "SeriesCoefficient",
      "SeriesData",
      "SeriesTermGoal",
      "ServiceConnect",
      "ServiceDisconnect",
      "ServiceExecute",
      "ServiceObject",
      "ServiceRequest",
      "ServiceResponse",
      "ServiceSubmit",
      "SessionSubmit",
      "SessionTime",
      "Set",
      "SetAccuracy",
      "SetAlphaChannel",
      "SetAttributes",
      "Setbacks",
      "SetBoxFormNamesPacket",
      "SetCloudDirectory",
      "SetCookies",
      "SetDelayed",
      "SetDirectory",
      "SetEnvironment",
      "SetEvaluationNotebook",
      "SetFileDate",
      "SetFileLoadingContext",
      "SetNotebookStatusLine",
      "SetOptions",
      "SetOptionsPacket",
      "SetPermissions",
      "SetPrecision",
      "SetProperty",
      "SetSecuredAuthenticationKey",
      "SetSelectedNotebook",
      "SetSharedFunction",
      "SetSharedVariable",
      "SetSpeechParametersPacket",
      "SetStreamPosition",
      "SetSystemModel",
      "SetSystemOptions",
      "Setter",
      "SetterBar",
      "SetterBox",
      "SetterBoxOptions",
      "Setting",
      "SetUsers",
      "SetValue",
      "Shading",
      "Shallow",
      "ShannonWavelet",
      "ShapiroWilkTest",
      "Share",
      "SharingList",
      "Sharpen",
      "ShearingMatrix",
      "ShearingTransform",
      "ShellRegion",
      "ShenCastanMatrix",
      "ShiftedGompertzDistribution",
      "ShiftRegisterSequence",
      "Short",
      "ShortDownArrow",
      "Shortest",
      "ShortestMatch",
      "ShortestPathFunction",
      "ShortLeftArrow",
      "ShortRightArrow",
      "ShortTimeFourier",
      "ShortTimeFourierData",
      "ShortUpArrow",
      "Show",
      "ShowAutoConvert",
      "ShowAutoSpellCheck",
      "ShowAutoStyles",
      "ShowCellBracket",
      "ShowCellLabel",
      "ShowCellTags",
      "ShowClosedCellArea",
      "ShowCodeAssist",
      "ShowContents",
      "ShowControls",
      "ShowCursorTracker",
      "ShowGroupOpenCloseIcon",
      "ShowGroupOpener",
      "ShowInvisibleCharacters",
      "ShowPageBreaks",
      "ShowPredictiveInterface",
      "ShowSelection",
      "ShowShortBoxForm",
      "ShowSpecialCharacters",
      "ShowStringCharacters",
      "ShowSyntaxStyles",
      "ShrinkingDelay",
      "ShrinkWrapBoundingBox",
      "SiderealTime",
      "SiegelTheta",
      "SiegelTukeyTest",
      "SierpinskiCurve",
      "SierpinskiMesh",
      "Sign",
      "Signature",
      "SignedRankTest",
      "SignedRegionDistance",
      "SignificanceLevel",
      "SignPadding",
      "SignTest",
      "SimilarityRules",
      "SimpleGraph",
      "SimpleGraphQ",
      "SimplePolygonQ",
      "SimplePolyhedronQ",
      "Simplex",
      "Simplify",
      "Sin",
      "Sinc",
      "SinghMaddalaDistribution",
      "SingleEvaluation",
      "SingleLetterItalics",
      "SingleLetterStyle",
      "SingularValueDecomposition",
      "SingularValueList",
      "SingularValuePlot",
      "SingularValues",
      "Sinh",
      "SinhIntegral",
      "SinIntegral",
      "SixJSymbol",
      "Skeleton",
      "SkeletonTransform",
      "SkellamDistribution",
      "Skewness",
      "SkewNormalDistribution",
      "SkinStyle",
      "Skip",
      "SliceContourPlot3D",
      "SliceDensityPlot3D",
      "SliceDistribution",
      "SliceVectorPlot3D",
      "Slider",
      "Slider2D",
      "Slider2DBox",
      "Slider2DBoxOptions",
      "SliderBox",
      "SliderBoxOptions",
      "SlideView",
      "Slot",
      "SlotSequence",
      "Small",
      "SmallCircle",
      "Smaller",
      "SmithDecomposition",
      "SmithDelayCompensator",
      "SmithWatermanSimilarity",
      "SmoothDensityHistogram",
      "SmoothHistogram",
      "SmoothHistogram3D",
      "SmoothKernelDistribution",
      "SnDispersion",
      "Snippet",
      "SnubPolyhedron",
      "SocialMediaData",
      "Socket",
      "SocketConnect",
      "SocketListen",
      "SocketListener",
      "SocketObject",
      "SocketOpen",
      "SocketReadMessage",
      "SocketReadyQ",
      "Sockets",
      "SocketWaitAll",
      "SocketWaitNext",
      "SoftmaxLayer",
      "SokalSneathDissimilarity",
      "SolarEclipse",
      "SolarSystemFeatureData",
      "SolidAngle",
      "SolidData",
      "SolidRegionQ",
      "Solve",
      "SolveAlways",
      "SolveDelayed",
      "Sort",
      "SortBy",
      "SortedBy",
      "SortedEntityClass",
      "Sound",
      "SoundAndGraphics",
      "SoundNote",
      "SoundVolume",
      "SourceLink",
      "Sow",
      "Space",
      "SpaceCurveData",
      "SpaceForm",
      "Spacer",
      "Spacings",
      "Span",
      "SpanAdjustments",
      "SpanCharacterRounding",
      "SpanFromAbove",
      "SpanFromBoth",
      "SpanFromLeft",
      "SpanLineThickness",
      "SpanMaxSize",
      "SpanMinSize",
      "SpanningCharacters",
      "SpanSymmetric",
      "SparseArray",
      "SpatialGraphDistribution",
      "SpatialMedian",
      "SpatialTransformationLayer",
      "Speak",
      "SpeakerMatchQ",
      "SpeakTextPacket",
      "SpearmanRankTest",
      "SpearmanRho",
      "SpeciesData",
      "SpecificityGoal",
      "SpectralLineData",
      "Spectrogram",
      "SpectrogramArray",
      "Specularity",
      "SpeechCases",
      "SpeechInterpreter",
      "SpeechRecognize",
      "SpeechSynthesize",
      "SpellingCorrection",
      "SpellingCorrectionList",
      "SpellingDictionaries",
      "SpellingDictionariesPath",
      "SpellingOptions",
      "SpellingSuggestionsPacket",
      "Sphere",
      "SphereBox",
      "SpherePoints",
      "SphericalBesselJ",
      "SphericalBesselY",
      "SphericalHankelH1",
      "SphericalHankelH2",
      "SphericalHarmonicY",
      "SphericalPlot3D",
      "SphericalRegion",
      "SphericalShell",
      "SpheroidalEigenvalue",
      "SpheroidalJoiningFactor",
      "SpheroidalPS",
      "SpheroidalPSPrime",
      "SpheroidalQS",
      "SpheroidalQSPrime",
      "SpheroidalRadialFactor",
      "SpheroidalS1",
      "SpheroidalS1Prime",
      "SpheroidalS2",
      "SpheroidalS2Prime",
      "Splice",
      "SplicedDistribution",
      "SplineClosed",
      "SplineDegree",
      "SplineKnots",
      "SplineWeights",
      "Split",
      "SplitBy",
      "SpokenString",
      "Sqrt",
      "SqrtBox",
      "SqrtBoxOptions",
      "Square",
      "SquaredEuclideanDistance",
      "SquareFreeQ",
      "SquareIntersection",
      "SquareMatrixQ",
      "SquareRepeatingElement",
      "SquaresR",
      "SquareSubset",
      "SquareSubsetEqual",
      "SquareSuperset",
      "SquareSupersetEqual",
      "SquareUnion",
      "SquareWave",
      "SSSTriangle",
      "StabilityMargins",
      "StabilityMarginsStyle",
      "StableDistribution",
      "Stack",
      "StackBegin",
      "StackComplete",
      "StackedDateListPlot",
      "StackedListPlot",
      "StackInhibit",
      "StadiumShape",
      "StandardAtmosphereData",
      "StandardDeviation",
      "StandardDeviationFilter",
      "StandardForm",
      "Standardize",
      "Standardized",
      "StandardOceanData",
      "StandbyDistribution",
      "Star",
      "StarClusterData",
      "StarData",
      "StarGraph",
      "StartAsynchronousTask",
      "StartExternalSession",
      "StartingStepSize",
      "StartOfLine",
      "StartOfString",
      "StartProcess",
      "StartScheduledTask",
      "StartupSound",
      "StartWebSession",
      "StateDimensions",
      "StateFeedbackGains",
      "StateOutputEstimator",
      "StateResponse",
      "StateSpaceModel",
      "StateSpaceRealization",
      "StateSpaceTransform",
      "StateTransformationLinearize",
      "StationaryDistribution",
      "StationaryWaveletPacketTransform",
      "StationaryWaveletTransform",
      "StatusArea",
      "StatusCentrality",
      "StepMonitor",
      "StereochemistryElements",
      "StieltjesGamma",
      "StippleShading",
      "StirlingS1",
      "StirlingS2",
      "StopAsynchronousTask",
      "StoppingPowerData",
      "StopScheduledTask",
      "StrataVariables",
      "StratonovichProcess",
      "StreamColorFunction",
      "StreamColorFunctionScaling",
      "StreamDensityPlot",
      "StreamMarkers",
      "StreamPlot",
      "StreamPoints",
      "StreamPosition",
      "Streams",
      "StreamScale",
      "StreamStyle",
      "String",
      "StringBreak",
      "StringByteCount",
      "StringCases",
      "StringContainsQ",
      "StringCount",
      "StringDelete",
      "StringDrop",
      "StringEndsQ",
      "StringExpression",
      "StringExtract",
      "StringForm",
      "StringFormat",
      "StringFreeQ",
      "StringInsert",
      "StringJoin",
      "StringLength",
      "StringMatchQ",
      "StringPadLeft",
      "StringPadRight",
      "StringPart",
      "StringPartition",
      "StringPosition",
      "StringQ",
      "StringRepeat",
      "StringReplace",
      "StringReplaceList",
      "StringReplacePart",
      "StringReverse",
      "StringRiffle",
      "StringRotateLeft",
      "StringRotateRight",
      "StringSkeleton",
      "StringSplit",
      "StringStartsQ",
      "StringTake",
      "StringTemplate",
      "StringToByteArray",
      "StringToStream",
      "StringTrim",
      "StripBoxes",
      "StripOnInput",
      "StripWrapperBoxes",
      "StrokeForm",
      "StructuralImportance",
      "StructuredArray",
      "StructuredArrayHeadQ",
      "StructuredSelection",
      "StruveH",
      "StruveL",
      "Stub",
      "StudentTDistribution",
      "Style",
      "StyleBox",
      "StyleBoxAutoDelete",
      "StyleData",
      "StyleDefinitions",
      "StyleForm",
      "StyleHints",
      "StyleKeyMapping",
      "StyleMenuListing",
      "StyleNameDialogSettings",
      "StyleNames",
      "StylePrint",
      "StyleSheetPath",
      "Subdivide",
      "Subfactorial",
      "Subgraph",
      "SubMinus",
      "SubPlus",
      "SubresultantPolynomialRemainders",
      "SubresultantPolynomials",
      "Subresultants",
      "Subscript",
      "SubscriptBox",
      "SubscriptBoxOptions",
      "Subscripted",
      "Subsequences",
      "Subset",
      "SubsetCases",
      "SubsetCount",
      "SubsetEqual",
      "SubsetMap",
      "SubsetPosition",
      "SubsetQ",
      "SubsetReplace",
      "Subsets",
      "SubStar",
      "SubstitutionSystem",
      "Subsuperscript",
      "SubsuperscriptBox",
      "SubsuperscriptBoxOptions",
      "SubtitleEncoding",
      "SubtitleTracks",
      "Subtract",
      "SubtractFrom",
      "SubtractSides",
      "SubValues",
      "Succeeds",
      "SucceedsEqual",
      "SucceedsSlantEqual",
      "SucceedsTilde",
      "Success",
      "SuchThat",
      "Sum",
      "SumConvergence",
      "SummationLayer",
      "Sunday",
      "SunPosition",
      "Sunrise",
      "Sunset",
      "SuperDagger",
      "SuperMinus",
      "SupernovaData",
      "SuperPlus",
      "Superscript",
      "SuperscriptBox",
      "SuperscriptBoxOptions",
      "Superset",
      "SupersetEqual",
      "SuperStar",
      "Surd",
      "SurdForm",
      "SurfaceAppearance",
      "SurfaceArea",
      "SurfaceColor",
      "SurfaceData",
      "SurfaceGraphics",
      "SurvivalDistribution",
      "SurvivalFunction",
      "SurvivalModel",
      "SurvivalModelFit",
      "SuspendPacket",
      "SuzukiDistribution",
      "SuzukiGroupSuz",
      "SwatchLegend",
      "Switch",
      "Symbol",
      "SymbolName",
      "SymletWavelet",
      "Symmetric",
      "SymmetricGroup",
      "SymmetricKey",
      "SymmetricMatrixQ",
      "SymmetricPolynomial",
      "SymmetricReduction",
      "Symmetrize",
      "SymmetrizedArray",
      "SymmetrizedArrayRules",
      "SymmetrizedDependentComponents",
      "SymmetrizedIndependentComponents",
      "SymmetrizedReplacePart",
      "SynchronousInitialization",
      "SynchronousUpdating",
      "Synonyms",
      "Syntax",
      "SyntaxForm",
      "SyntaxInformation",
      "SyntaxLength",
      "SyntaxPacket",
      "SyntaxQ",
      "SynthesizeMissingValues",
      "SystemCredential",
      "SystemCredentialData",
      "SystemCredentialKey",
      "SystemCredentialKeys",
      "SystemCredentialStoreObject",
      "SystemDialogInput",
      "SystemException",
      "SystemGet",
      "SystemHelpPath",
      "SystemInformation",
      "SystemInformationData",
      "SystemInstall",
      "SystemModel",
      "SystemModeler",
      "SystemModelExamples",
      "SystemModelLinearize",
      "SystemModelParametricSimulate",
      "SystemModelPlot",
      "SystemModelProgressReporting",
      "SystemModelReliability",
      "SystemModels",
      "SystemModelSimulate",
      "SystemModelSimulateSensitivity",
      "SystemModelSimulationData",
      "SystemOpen",
      "SystemOptions",
      "SystemProcessData",
      "SystemProcesses",
      "SystemsConnectionsModel",
      "SystemsModelDelay",
      "SystemsModelDelayApproximate",
      "SystemsModelDelete",
      "SystemsModelDimensions",
      "SystemsModelExtract",
      "SystemsModelFeedbackConnect",
      "SystemsModelLabels",
      "SystemsModelLinearity",
      "SystemsModelMerge",
      "SystemsModelOrder",
      "SystemsModelParallelConnect",
      "SystemsModelSeriesConnect",
      "SystemsModelStateFeedbackConnect",
      "SystemsModelVectorRelativeOrders",
      "SystemStub",
      "SystemTest",
      "Tab",
      "TabFilling",
      "Table",
      "TableAlignments",
      "TableDepth",
      "TableDirections",
      "TableForm",
      "TableHeadings",
      "TableSpacing",
      "TableView",
      "TableViewBox",
      "TableViewBoxBackground",
      "TableViewBoxItemSize",
      "TableViewBoxOptions",
      "TabSpacings",
      "TabView",
      "TabViewBox",
      "TabViewBoxOptions",
      "TagBox",
      "TagBoxNote",
      "TagBoxOptions",
      "TaggingRules",
      "TagSet",
      "TagSetDelayed",
      "TagStyle",
      "TagUnset",
      "Take",
      "TakeDrop",
      "TakeLargest",
      "TakeLargestBy",
      "TakeList",
      "TakeSmallest",
      "TakeSmallestBy",
      "TakeWhile",
      "Tally",
      "Tan",
      "Tanh",
      "TargetDevice",
      "TargetFunctions",
      "TargetSystem",
      "TargetUnits",
      "TaskAbort",
      "TaskExecute",
      "TaskObject",
      "TaskRemove",
      "TaskResume",
      "Tasks",
      "TaskSuspend",
      "TaskWait",
      "TautologyQ",
      "TelegraphProcess",
      "TemplateApply",
      "TemplateArgBox",
      "TemplateBox",
      "TemplateBoxOptions",
      "TemplateEvaluate",
      "TemplateExpression",
      "TemplateIf",
      "TemplateObject",
      "TemplateSequence",
      "TemplateSlot",
      "TemplateSlotSequence",
      "TemplateUnevaluated",
      "TemplateVerbatim",
      "TemplateWith",
      "TemporalData",
      "TemporalRegularity",
      "Temporary",
      "TemporaryVariable",
      "TensorContract",
      "TensorDimensions",
      "TensorExpand",
      "TensorProduct",
      "TensorQ",
      "TensorRank",
      "TensorReduce",
      "TensorSymmetry",
      "TensorTranspose",
      "TensorWedge",
      "TestID",
      "TestReport",
      "TestReportObject",
      "TestResultObject",
      "Tetrahedron",
      "TetrahedronBox",
      "TetrahedronBoxOptions",
      "TeXForm",
      "TeXSave",
      "Text",
      "Text3DBox",
      "Text3DBoxOptions",
      "TextAlignment",
      "TextBand",
      "TextBoundingBox",
      "TextBox",
      "TextCases",
      "TextCell",
      "TextClipboardType",
      "TextContents",
      "TextData",
      "TextElement",
      "TextForm",
      "TextGrid",
      "TextJustification",
      "TextLine",
      "TextPacket",
      "TextParagraph",
      "TextPosition",
      "TextRecognize",
      "TextSearch",
      "TextSearchReport",
      "TextSentences",
      "TextString",
      "TextStructure",
      "TextStyle",
      "TextTranslation",
      "Texture",
      "TextureCoordinateFunction",
      "TextureCoordinateScaling",
      "TextWords",
      "Therefore",
      "ThermodynamicData",
      "ThermometerGauge",
      "Thick",
      "Thickness",
      "Thin",
      "Thinning",
      "ThisLink",
      "ThompsonGroupTh",
      "Thread",
      "ThreadingLayer",
      "ThreeJSymbol",
      "Threshold",
      "Through",
      "Throw",
      "ThueMorse",
      "Thumbnail",
      "Thursday",
      "Ticks",
      "TicksStyle",
      "TideData",
      "Tilde",
      "TildeEqual",
      "TildeFullEqual",
      "TildeTilde",
      "TimeConstrained",
      "TimeConstraint",
      "TimeDirection",
      "TimeFormat",
      "TimeGoal",
      "TimelinePlot",
      "TimeObject",
      "TimeObjectQ",
      "TimeRemaining",
      "Times",
      "TimesBy",
      "TimeSeries",
      "TimeSeriesAggregate",
      "TimeSeriesForecast",
      "TimeSeriesInsert",
      "TimeSeriesInvertibility",
      "TimeSeriesMap",
      "TimeSeriesMapThread",
      "TimeSeriesModel",
      "TimeSeriesModelFit",
      "TimeSeriesResample",
      "TimeSeriesRescale",
      "TimeSeriesShift",
      "TimeSeriesThread",
      "TimeSeriesWindow",
      "TimeUsed",
      "TimeValue",
      "TimeWarpingCorrespondence",
      "TimeWarpingDistance",
      "TimeZone",
      "TimeZoneConvert",
      "TimeZoneOffset",
      "Timing",
      "Tiny",
      "TitleGrouping",
      "TitsGroupT",
      "ToBoxes",
      "ToCharacterCode",
      "ToColor",
      "ToContinuousTimeModel",
      "ToDate",
      "Today",
      "ToDiscreteTimeModel",
      "ToEntity",
      "ToeplitzMatrix",
      "ToExpression",
      "ToFileName",
      "Together",
      "Toggle",
      "ToggleFalse",
      "Toggler",
      "TogglerBar",
      "TogglerBox",
      "TogglerBoxOptions",
      "ToHeldExpression",
      "ToInvertibleTimeSeries",
      "TokenWords",
      "Tolerance",
      "ToLowerCase",
      "Tomorrow",
      "ToNumberField",
      "TooBig",
      "Tooltip",
      "TooltipBox",
      "TooltipBoxOptions",
      "TooltipDelay",
      "TooltipStyle",
      "ToonShading",
      "Top",
      "TopHatTransform",
      "ToPolarCoordinates",
      "TopologicalSort",
      "ToRadicals",
      "ToRules",
      "ToSphericalCoordinates",
      "ToString",
      "Total",
      "TotalHeight",
      "TotalLayer",
      "TotalVariationFilter",
      "TotalWidth",
      "TouchPosition",
      "TouchscreenAutoZoom",
      "TouchscreenControlPlacement",
      "ToUpperCase",
      "Tr",
      "Trace",
      "TraceAbove",
      "TraceAction",
      "TraceBackward",
      "TraceDepth",
      "TraceDialog",
      "TraceForward",
      "TraceInternal",
      "TraceLevel",
      "TraceOff",
      "TraceOn",
      "TraceOriginal",
      "TracePrint",
      "TraceScan",
      "TrackedSymbols",
      "TrackingFunction",
      "TracyWidomDistribution",
      "TradingChart",
      "TraditionalForm",
      "TraditionalFunctionNotation",
      "TraditionalNotation",
      "TraditionalOrder",
      "TrainingProgressCheckpointing",
      "TrainingProgressFunction",
      "TrainingProgressMeasurements",
      "TrainingProgressReporting",
      "TrainingStoppingCriterion",
      "TrainingUpdateSchedule",
      "TransferFunctionCancel",
      "TransferFunctionExpand",
      "TransferFunctionFactor",
      "TransferFunctionModel",
      "TransferFunctionPoles",
      "TransferFunctionTransform",
      "TransferFunctionZeros",
      "TransformationClass",
      "TransformationFunction",
      "TransformationFunctions",
      "TransformationMatrix",
      "TransformedDistribution",
      "TransformedField",
      "TransformedProcess",
      "TransformedRegion",
      "TransitionDirection",
      "TransitionDuration",
      "TransitionEffect",
      "TransitiveClosureGraph",
      "TransitiveReductionGraph",
      "Translate",
      "TranslationOptions",
      "TranslationTransform",
      "Transliterate",
      "Transparent",
      "TransparentColor",
      "Transpose",
      "TransposeLayer",
      "TrapSelection",
      "TravelDirections",
      "TravelDirectionsData",
      "TravelDistance",
      "TravelDistanceList",
      "TravelMethod",
      "TravelTime",
      "TreeForm",
      "TreeGraph",
      "TreeGraphQ",
      "TreePlot",
      "TrendStyle",
      "Triangle",
      "TriangleCenter",
      "TriangleConstruct",
      "TriangleMeasurement",
      "TriangleWave",
      "TriangularDistribution",
      "TriangulateMesh",
      "Trig",
      "TrigExpand",
      "TrigFactor",
      "TrigFactorList",
      "Trigger",
      "TrigReduce",
      "TrigToExp",
      "TrimmedMean",
      "TrimmedVariance",
      "TropicalStormData",
      "True",
      "TrueQ",
      "TruncatedDistribution",
      "TruncatedPolyhedron",
      "TsallisQExponentialDistribution",
      "TsallisQGaussianDistribution",
      "TTest",
      "Tube",
      "TubeBezierCurveBox",
      "TubeBezierCurveBoxOptions",
      "TubeBox",
      "TubeBoxOptions",
      "TubeBSplineCurveBox",
      "TubeBSplineCurveBoxOptions",
      "Tuesday",
      "TukeyLambdaDistribution",
      "TukeyWindow",
      "TunnelData",
      "Tuples",
      "TuranGraph",
      "TuringMachine",
      "TuttePolynomial",
      "TwoWayRule",
      "Typed",
      "TypeSpecifier",
      "UnateQ",
      "Uncompress",
      "UnconstrainedParameters",
      "Undefined",
      "UnderBar",
      "Underflow",
      "Underlined",
      "Underoverscript",
      "UnderoverscriptBox",
      "UnderoverscriptBoxOptions",
      "Underscript",
      "UnderscriptBox",
      "UnderscriptBoxOptions",
      "UnderseaFeatureData",
      "UndirectedEdge",
      "UndirectedGraph",
      "UndirectedGraphQ",
      "UndoOptions",
      "UndoTrackedVariables",
      "Unequal",
      "UnequalTo",
      "Unevaluated",
      "UniformDistribution",
      "UniformGraphDistribution",
      "UniformPolyhedron",
      "UniformSumDistribution",
      "Uninstall",
      "Union",
      "UnionedEntityClass",
      "UnionPlus",
      "Unique",
      "UnitaryMatrixQ",
      "UnitBox",
      "UnitConvert",
      "UnitDimensions",
      "Unitize",
      "UnitRootTest",
      "UnitSimplify",
      "UnitStep",
      "UnitSystem",
      "UnitTriangle",
      "UnitVector",
      "UnitVectorLayer",
      "UnityDimensions",
      "UniverseModelData",
      "UniversityData",
      "UnixTime",
      "Unprotect",
      "UnregisterExternalEvaluator",
      "UnsameQ",
      "UnsavedVariables",
      "Unset",
      "UnsetShared",
      "UntrackedVariables",
      "Up",
      "UpArrow",
      "UpArrowBar",
      "UpArrowDownArrow",
      "Update",
      "UpdateDynamicObjects",
      "UpdateDynamicObjectsSynchronous",
      "UpdateInterval",
      "UpdatePacletSites",
      "UpdateSearchIndex",
      "UpDownArrow",
      "UpEquilibrium",
      "UpperCaseQ",
      "UpperLeftArrow",
      "UpperRightArrow",
      "UpperTriangularize",
      "UpperTriangularMatrixQ",
      "Upsample",
      "UpSet",
      "UpSetDelayed",
      "UpTee",
      "UpTeeArrow",
      "UpTo",
      "UpValues",
      "URL",
      "URLBuild",
      "URLDecode",
      "URLDispatcher",
      "URLDownload",
      "URLDownloadSubmit",
      "URLEncode",
      "URLExecute",
      "URLExpand",
      "URLFetch",
      "URLFetchAsynchronous",
      "URLParse",
      "URLQueryDecode",
      "URLQueryEncode",
      "URLRead",
      "URLResponseTime",
      "URLSave",
      "URLSaveAsynchronous",
      "URLShorten",
      "URLSubmit",
      "UseGraphicsRange",
      "UserDefinedWavelet",
      "Using",
      "UsingFrontEnd",
      "UtilityFunction",
      "V2Get",
      "ValenceErrorHandling",
      "ValidationLength",
      "ValidationSet",
      "Value",
      "ValueBox",
      "ValueBoxOptions",
      "ValueDimensions",
      "ValueForm",
      "ValuePreprocessingFunction",
      "ValueQ",
      "Values",
      "ValuesData",
      "Variables",
      "Variance",
      "VarianceEquivalenceTest",
      "VarianceEstimatorFunction",
      "VarianceGammaDistribution",
      "VarianceTest",
      "VectorAngle",
      "VectorAround",
      "VectorAspectRatio",
      "VectorColorFunction",
      "VectorColorFunctionScaling",
      "VectorDensityPlot",
      "VectorGlyphData",
      "VectorGreater",
      "VectorGreaterEqual",
      "VectorLess",
      "VectorLessEqual",
      "VectorMarkers",
      "VectorPlot",
      "VectorPlot3D",
      "VectorPoints",
      "VectorQ",
      "VectorRange",
      "Vectors",
      "VectorScale",
      "VectorScaling",
      "VectorSizes",
      "VectorStyle",
      "Vee",
      "Verbatim",
      "Verbose",
      "VerboseConvertToPostScriptPacket",
      "VerificationTest",
      "VerifyConvergence",
      "VerifyDerivedKey",
      "VerifyDigitalSignature",
      "VerifyFileSignature",
      "VerifyInterpretation",
      "VerifySecurityCertificates",
      "VerifySolutions",
      "VerifyTestAssumptions",
      "Version",
      "VersionedPreferences",
      "VersionNumber",
      "VertexAdd",
      "VertexCapacity",
      "VertexColors",
      "VertexComponent",
      "VertexConnectivity",
      "VertexContract",
      "VertexCoordinateRules",
      "VertexCoordinates",
      "VertexCorrelationSimilarity",
      "VertexCosineSimilarity",
      "VertexCount",
      "VertexCoverQ",
      "VertexDataCoordinates",
      "VertexDegree",
      "VertexDelete",
      "VertexDiceSimilarity",
      "VertexEccentricity",
      "VertexInComponent",
      "VertexInDegree",
      "VertexIndex",
      "VertexJaccardSimilarity",
      "VertexLabeling",
      "VertexLabels",
      "VertexLabelStyle",
      "VertexList",
      "VertexNormals",
      "VertexOutComponent",
      "VertexOutDegree",
      "VertexQ",
      "VertexRenderingFunction",
      "VertexReplace",
      "VertexShape",
      "VertexShapeFunction",
      "VertexSize",
      "VertexStyle",
      "VertexTextureCoordinates",
      "VertexWeight",
      "VertexWeightedGraphQ",
      "Vertical",
      "VerticalBar",
      "VerticalForm",
      "VerticalGauge",
      "VerticalSeparator",
      "VerticalSlider",
      "VerticalTilde",
      "Video",
      "VideoEncoding",
      "VideoExtractFrames",
      "VideoFrameList",
      "VideoFrameMap",
      "VideoPause",
      "VideoPlay",
      "VideoQ",
      "VideoStop",
      "VideoStream",
      "VideoStreams",
      "VideoTimeSeries",
      "VideoTracks",
      "VideoTrim",
      "ViewAngle",
      "ViewCenter",
      "ViewMatrix",
      "ViewPoint",
      "ViewPointSelectorSettings",
      "ViewPort",
      "ViewProjection",
      "ViewRange",
      "ViewVector",
      "ViewVertical",
      "VirtualGroupData",
      "Visible",
      "VisibleCell",
      "VoiceStyleData",
      "VoigtDistribution",
      "VolcanoData",
      "Volume",
      "VonMisesDistribution",
      "VoronoiMesh",
      "WaitAll",
      "WaitAsynchronousTask",
      "WaitNext",
      "WaitUntil",
      "WakebyDistribution",
      "WalleniusHypergeometricDistribution",
      "WaringYuleDistribution",
      "WarpingCorrespondence",
      "WarpingDistance",
      "WatershedComponents",
      "WatsonUSquareTest",
      "WattsStrogatzGraphDistribution",
      "WaveletBestBasis",
      "WaveletFilterCoefficients",
      "WaveletImagePlot",
      "WaveletListPlot",
      "WaveletMapIndexed",
      "WaveletMatrixPlot",
      "WaveletPhi",
      "WaveletPsi",
      "WaveletScale",
      "WaveletScalogram",
      "WaveletThreshold",
      "WeaklyConnectedComponents",
      "WeaklyConnectedGraphComponents",
      "WeaklyConnectedGraphQ",
      "WeakStationarity",
      "WeatherData",
      "WeatherForecastData",
      "WebAudioSearch",
      "WebElementObject",
      "WeberE",
      "WebExecute",
      "WebImage",
      "WebImageSearch",
      "WebSearch",
      "WebSessionObject",
      "WebSessions",
      "WebWindowObject",
      "Wedge",
      "Wednesday",
      "WeibullDistribution",
      "WeierstrassE1",
      "WeierstrassE2",
      "WeierstrassE3",
      "WeierstrassEta1",
      "WeierstrassEta2",
      "WeierstrassEta3",
      "WeierstrassHalfPeriods",
      "WeierstrassHalfPeriodW1",
      "WeierstrassHalfPeriodW2",
      "WeierstrassHalfPeriodW3",
      "WeierstrassInvariantG2",
      "WeierstrassInvariantG3",
      "WeierstrassInvariants",
      "WeierstrassP",
      "WeierstrassPPrime",
      "WeierstrassSigma",
      "WeierstrassZeta",
      "WeightedAdjacencyGraph",
      "WeightedAdjacencyMatrix",
      "WeightedData",
      "WeightedGraphQ",
      "Weights",
      "WelchWindow",
      "WheelGraph",
      "WhenEvent",
      "Which",
      "While",
      "White",
      "WhiteNoiseProcess",
      "WhitePoint",
      "Whitespace",
      "WhitespaceCharacter",
      "WhittakerM",
      "WhittakerW",
      "WienerFilter",
      "WienerProcess",
      "WignerD",
      "WignerSemicircleDistribution",
      "WikidataData",
      "WikidataSearch",
      "WikipediaData",
      "WikipediaSearch",
      "WilksW",
      "WilksWTest",
      "WindDirectionData",
      "WindingCount",
      "WindingPolygon",
      "WindowClickSelect",
      "WindowElements",
      "WindowFloating",
      "WindowFrame",
      "WindowFrameElements",
      "WindowMargins",
      "WindowMovable",
      "WindowOpacity",
      "WindowPersistentStyles",
      "WindowSelected",
      "WindowSize",
      "WindowStatusArea",
      "WindowTitle",
      "WindowToolbars",
      "WindowWidth",
      "WindSpeedData",
      "WindVectorData",
      "WinsorizedMean",
      "WinsorizedVariance",
      "WishartMatrixDistribution",
      "With",
      "WolframAlpha",
      "WolframAlphaDate",
      "WolframAlphaQuantity",
      "WolframAlphaResult",
      "WolframLanguageData",
      "Word",
      "WordBoundary",
      "WordCharacter",
      "WordCloud",
      "WordCount",
      "WordCounts",
      "WordData",
      "WordDefinition",
      "WordFrequency",
      "WordFrequencyData",
      "WordList",
      "WordOrientation",
      "WordSearch",
      "WordSelectionFunction",
      "WordSeparators",
      "WordSpacings",
      "WordStem",
      "WordTranslation",
      "WorkingPrecision",
      "WrapAround",
      "Write",
      "WriteLine",
      "WriteString",
      "Wronskian",
      "XMLElement",
      "XMLObject",
      "XMLTemplate",
      "Xnor",
      "Xor",
      "XYZColor",
      "Yellow",
      "Yesterday",
      "YuleDissimilarity",
      "ZernikeR",
      "ZeroSymmetric",
      "ZeroTest",
      "ZeroWidthTimes",
      "Zeta",
      "ZetaZero",
      "ZIPCodeData",
      "ZipfDistribution",
      "ZoomCenter",
      "ZoomFactor",
      "ZTest",
      "ZTransform",
      "$Aborted",
      "$ActivationGroupID",
      "$ActivationKey",
      "$ActivationUserRegistered",
      "$AddOnsDirectory",
      "$AllowDataUpdates",
      "$AllowExternalChannelFunctions",
      "$AllowInternet",
      "$AssertFunction",
      "$Assumptions",
      "$AsynchronousTask",
      "$AudioDecoders",
      "$AudioEncoders",
      "$AudioInputDevices",
      "$AudioOutputDevices",
      "$BaseDirectory",
      "$BasePacletsDirectory",
      "$BatchInput",
      "$BatchOutput",
      "$BlockchainBase",
      "$BoxForms",
      "$ByteOrdering",
      "$CacheBaseDirectory",
      "$Canceled",
      "$ChannelBase",
      "$CharacterEncoding",
      "$CharacterEncodings",
      "$CloudAccountName",
      "$CloudBase",
      "$CloudConnected",
      "$CloudConnection",
      "$CloudCreditsAvailable",
      "$CloudEvaluation",
      "$CloudExpressionBase",
      "$CloudObjectNameFormat",
      "$CloudObjectURLType",
      "$CloudRootDirectory",
      "$CloudSymbolBase",
      "$CloudUserID",
      "$CloudUserUUID",
      "$CloudVersion",
      "$CloudVersionNumber",
      "$CloudWolframEngineVersionNumber",
      "$CommandLine",
      "$CompilationTarget",
      "$ConditionHold",
      "$ConfiguredKernels",
      "$Context",
      "$ContextPath",
      "$ControlActiveSetting",
      "$Cookies",
      "$CookieStore",
      "$CreationDate",
      "$CurrentLink",
      "$CurrentTask",
      "$CurrentWebSession",
      "$DataStructures",
      "$DateStringFormat",
      "$DefaultAudioInputDevice",
      "$DefaultAudioOutputDevice",
      "$DefaultFont",
      "$DefaultFrontEnd",
      "$DefaultImagingDevice",
      "$DefaultLocalBase",
      "$DefaultMailbox",
      "$DefaultNetworkInterface",
      "$DefaultPath",
      "$DefaultProxyRules",
      "$DefaultSystemCredentialStore",
      "$Display",
      "$DisplayFunction",
      "$DistributedContexts",
      "$DynamicEvaluation",
      "$Echo",
      "$EmbedCodeEnvironments",
      "$EmbeddableServices",
      "$EntityStores",
      "$Epilog",
      "$EvaluationCloudBase",
      "$EvaluationCloudObject",
      "$EvaluationEnvironment",
      "$ExportFormats",
      "$ExternalIdentifierTypes",
      "$ExternalStorageBase",
      "$Failed",
      "$FinancialDataSource",
      "$FontFamilies",
      "$FormatType",
      "$FrontEnd",
      "$FrontEndSession",
      "$GeoEntityTypes",
      "$GeoLocation",
      "$GeoLocationCity",
      "$GeoLocationCountry",
      "$GeoLocationPrecision",
      "$GeoLocationSource",
      "$HistoryLength",
      "$HomeDirectory",
      "$HTMLExportRules",
      "$HTTPCookies",
      "$HTTPRequest",
      "$IgnoreEOF",
      "$ImageFormattingWidth",
      "$ImageResolution",
      "$ImagingDevice",
      "$ImagingDevices",
      "$ImportFormats",
      "$IncomingMailSettings",
      "$InitialDirectory",
      "$Initialization",
      "$InitializationContexts",
      "$Input",
      "$InputFileName",
      "$InputStreamMethods",
      "$Inspector",
      "$InstallationDate",
      "$InstallationDirectory",
      "$InterfaceEnvironment",
      "$InterpreterTypes",
      "$IterationLimit",
      "$KernelCount",
      "$KernelID",
      "$Language",
      "$LaunchDirectory",
      "$LibraryPath",
      "$LicenseExpirationDate",
      "$LicenseID",
      "$LicenseProcesses",
      "$LicenseServer",
      "$LicenseSubprocesses",
      "$LicenseType",
      "$Line",
      "$Linked",
      "$LinkSupported",
      "$LoadedFiles",
      "$LocalBase",
      "$LocalSymbolBase",
      "$MachineAddresses",
      "$MachineDomain",
      "$MachineDomains",
      "$MachineEpsilon",
      "$MachineID",
      "$MachineName",
      "$MachinePrecision",
      "$MachineType",
      "$MaxExtraPrecision",
      "$MaxLicenseProcesses",
      "$MaxLicenseSubprocesses",
      "$MaxMachineNumber",
      "$MaxNumber",
      "$MaxPiecewiseCases",
      "$MaxPrecision",
      "$MaxRootDegree",
      "$MessageGroups",
      "$MessageList",
      "$MessagePrePrint",
      "$Messages",
      "$MinMachineNumber",
      "$MinNumber",
      "$MinorReleaseNumber",
      "$MinPrecision",
      "$MobilePhone",
      "$ModuleNumber",
      "$NetworkConnected",
      "$NetworkInterfaces",
      "$NetworkLicense",
      "$NewMessage",
      "$NewSymbol",
      "$NotebookInlineStorageLimit",
      "$Notebooks",
      "$NoValue",
      "$NumberMarks",
      "$Off",
      "$OperatingSystem",
      "$Output",
      "$OutputForms",
      "$OutputSizeLimit",
      "$OutputStreamMethods",
      "$Packages",
      "$ParentLink",
      "$ParentProcessID",
      "$PasswordFile",
      "$PatchLevelID",
      "$Path",
      "$PathnameSeparator",
      "$PerformanceGoal",
      "$Permissions",
      "$PermissionsGroupBase",
      "$PersistenceBase",
      "$PersistencePath",
      "$PipeSupported",
      "$PlotTheme",
      "$Post",
      "$Pre",
      "$PreferencesDirectory",
      "$PreInitialization",
      "$PrePrint",
      "$PreRead",
      "$PrintForms",
      "$PrintLiteral",
      "$Printout3DPreviewer",
      "$ProcessID",
      "$ProcessorCount",
      "$ProcessorType",
      "$ProductInformation",
      "$ProgramName",
      "$PublisherID",
      "$RandomState",
      "$RecursionLimit",
      "$RegisteredDeviceClasses",
      "$RegisteredUserName",
      "$ReleaseNumber",
      "$RequesterAddress",
      "$RequesterWolframID",
      "$RequesterWolframUUID",
      "$RootDirectory",
      "$ScheduledTask",
      "$ScriptCommandLine",
      "$ScriptInputString",
      "$SecuredAuthenticationKeyTokens",
      "$ServiceCreditsAvailable",
      "$Services",
      "$SessionID",
      "$SetParentLink",
      "$SharedFunctions",
      "$SharedVariables",
      "$SoundDisplay",
      "$SoundDisplayFunction",
      "$SourceLink",
      "$SSHAuthentication",
      "$SubtitleDecoders",
      "$SubtitleEncoders",
      "$SummaryBoxDataSizeLimit",
      "$SuppressInputFormHeads",
      "$SynchronousEvaluation",
      "$SyntaxHandler",
      "$System",
      "$SystemCharacterEncoding",
      "$SystemCredentialStore",
      "$SystemID",
      "$SystemMemory",
      "$SystemShell",
      "$SystemTimeZone",
      "$SystemWordLength",
      "$TemplatePath",
      "$TemporaryDirectory",
      "$TemporaryPrefix",
      "$TestFileName",
      "$TextStyle",
      "$TimedOut",
      "$TimeUnit",
      "$TimeZone",
      "$TimeZoneEntity",
      "$TopDirectory",
      "$TraceOff",
      "$TraceOn",
      "$TracePattern",
      "$TracePostAction",
      "$TracePreAction",
      "$UnitSystem",
      "$Urgent",
      "$UserAddOnsDirectory",
      "$UserAgentLanguages",
      "$UserAgentMachine",
      "$UserAgentName",
      "$UserAgentOperatingSystem",
      "$UserAgentString",
      "$UserAgentVersion",
      "$UserBaseDirectory",
      "$UserBasePacletsDirectory",
      "$UserDocumentsDirectory",
      "$Username",
      "$UserName",
      "$UserURLBase",
      "$Version",
      "$VersionNumber",
      "$VideoDecoders",
      "$VideoEncoders",
      "$VoiceStyles",
      "$WolframDocumentsDirectory",
      "$WolframID",
      "$WolframUUID"
    ];
    function source(re2) {
      if (!re2) return null;
      if (typeof re2 === "string") return re2;
      return re2.source;
    }
    function optional(re2) {
      return concat("(", re2, ")?");
    }
    function concat(...args) {
      const joined = args.map((x2) => source(x2)).join("");
      return joined;
    }
    function either(...args) {
      const joined = "(" + args.map((x2) => source(x2)).join("|") + ")";
      return joined;
    }
    function mathematica(hljs5) {
      const BASE_RE = /([2-9]|[1-2]\d|[3][0-5])\^\^/;
      const BASE_DIGITS_RE = /(\w*\.\w+|\w+\.\w*|\w+)/;
      const NUMBER_RE = /(\d*\.\d+|\d+\.\d*|\d+)/;
      const BASE_NUMBER_RE = either(concat(BASE_RE, BASE_DIGITS_RE), NUMBER_RE);
      const ACCURACY_RE = /``[+-]?(\d*\.\d+|\d+\.\d*|\d+)/;
      const PRECISION_RE = /`([+-]?(\d*\.\d+|\d+\.\d*|\d+))?/;
      const APPROXIMATE_NUMBER_RE = either(ACCURACY_RE, PRECISION_RE);
      const SCIENTIFIC_NOTATION_RE = /\*\^[+-]?\d+/;
      const MATHEMATICA_NUMBER_RE = concat(
        BASE_NUMBER_RE,
        optional(APPROXIMATE_NUMBER_RE),
        optional(SCIENTIFIC_NOTATION_RE)
      );
      const NUMBERS = {
        className: "number",
        relevance: 0,
        begin: MATHEMATICA_NUMBER_RE
      };
      const SYMBOL_RE = /[a-zA-Z$][a-zA-Z0-9$]*/;
      const SYSTEM_SYMBOLS_SET = new Set(SYSTEM_SYMBOLS);
      const SYMBOLS = {
        variants: [
          {
            className: "builtin-symbol",
            begin: SYMBOL_RE,
            // for performance out of fear of regex.either(...Mathematica.SYSTEM_SYMBOLS)
            "on:begin": (match2, response) => {
              if (!SYSTEM_SYMBOLS_SET.has(match2[0])) response.ignoreMatch();
            }
          },
          {
            className: "symbol",
            relevance: 0,
            begin: SYMBOL_RE
          }
        ]
      };
      const NAMED_CHARACTER = {
        className: "named-character",
        begin: /\\\[[$a-zA-Z][$a-zA-Z0-9]+\]/
      };
      const OPERATORS = {
        className: "operator",
        relevance: 0,
        begin: /[+\-*/,;.:@~=><&|_`'^?!%]+/
      };
      const PATTERNS = {
        className: "pattern",
        relevance: 0,
        begin: /([a-zA-Z$][a-zA-Z0-9$]*)?_+([a-zA-Z$][a-zA-Z0-9$]*)?/
      };
      const SLOTS = {
        className: "slot",
        relevance: 0,
        begin: /#[a-zA-Z$][a-zA-Z0-9$]*|#+[0-9]?/
      };
      const BRACES = {
        className: "brace",
        relevance: 0,
        begin: /[[\](){}]/
      };
      const MESSAGES = {
        className: "message-name",
        relevance: 0,
        begin: concat("::", SYMBOL_RE)
      };
      return {
        name: "Mathematica",
        aliases: [
          "mma",
          "wl"
        ],
        classNameAliases: {
          brace: "punctuation",
          pattern: "type",
          slot: "type",
          symbol: "variable",
          "named-character": "variable",
          "builtin-symbol": "built_in",
          "message-name": "string"
        },
        contains: [
          hljs5.COMMENT(/\(\*/, /\*\)/, {
            contains: ["self"]
          }),
          PATTERNS,
          SLOTS,
          MESSAGES,
          SYMBOLS,
          NAMED_CHARACTER,
          hljs5.QUOTE_STRING_MODE,
          NUMBERS,
          OPERATORS,
          BRACES
        ]
      };
    }
    module.exports = mathematica;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/matlab.js
var require_matlab = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/matlab.js"(exports, module) {
    init_process_shim();
    function matlab(hljs5) {
      var TRANSPOSE_RE = "('|\\.')+";
      var TRANSPOSE = {
        relevance: 0,
        contains: [
          { begin: TRANSPOSE_RE }
        ]
      };
      return {
        name: "Matlab",
        keywords: {
          keyword: "arguments break case catch classdef continue else elseif end enumeration events for function global if methods otherwise parfor persistent properties return spmd switch try while",
          built_in: "sin sind sinh asin asind asinh cos cosd cosh acos acosd acosh tan tand tanh atan atand atan2 atanh sec secd sech asec asecd asech csc cscd csch acsc acscd acsch cot cotd coth acot acotd acoth hypot exp expm1 log log1p log10 log2 pow2 realpow reallog realsqrt sqrt nthroot nextpow2 abs angle complex conj imag real unwrap isreal cplxpair fix floor ceil round mod rem sign airy besselj bessely besselh besseli besselk beta betainc betaln ellipj ellipke erf erfc erfcx erfinv expint gamma gammainc gammaln psi legendre cross dot factor isprime primes gcd lcm rat rats perms nchoosek factorial cart2sph cart2pol pol2cart sph2cart hsv2rgb rgb2hsv zeros ones eye repmat rand randn linspace logspace freqspace meshgrid accumarray size length ndims numel disp isempty isequal isequalwithequalnans cat reshape diag blkdiag tril triu fliplr flipud flipdim rot90 find sub2ind ind2sub bsxfun ndgrid permute ipermute shiftdim circshift squeeze isscalar isvector ans eps realmax realmin pi i|0 inf nan isnan isinf isfinite j|0 why compan gallery hadamard hankel hilb invhilb magic pascal rosser toeplitz vander wilkinson max min nanmax nanmin mean nanmean type table readtable writetable sortrows sort figure plot plot3 scatter scatter3 cellfun legend intersect ismember procrustes hold num2cell "
        },
        illegal: '(//|"|#|/\\*|\\s+/\\w+)',
        contains: [
          {
            className: "function",
            beginKeywords: "function",
            end: "$",
            contains: [
              hljs5.UNDERSCORE_TITLE_MODE,
              {
                className: "params",
                variants: [
                  { begin: "\\(", end: "\\)" },
                  { begin: "\\[", end: "\\]" }
                ]
              }
            ]
          },
          {
            className: "built_in",
            begin: /true|false/,
            relevance: 0,
            starts: TRANSPOSE
          },
          {
            begin: "[a-zA-Z][a-zA-Z_0-9]*" + TRANSPOSE_RE,
            relevance: 0
          },
          {
            className: "number",
            begin: hljs5.C_NUMBER_RE,
            relevance: 0,
            starts: TRANSPOSE
          },
          {
            className: "string",
            begin: "'",
            end: "'",
            contains: [
              hljs5.BACKSLASH_ESCAPE,
              { begin: "''" }
            ]
          },
          {
            begin: /\]|\}|\)/,
            relevance: 0,
            starts: TRANSPOSE
          },
          {
            className: "string",
            begin: '"',
            end: '"',
            contains: [
              hljs5.BACKSLASH_ESCAPE,
              { begin: '""' }
            ],
            starts: TRANSPOSE
          },
          hljs5.COMMENT("^\\s*%\\{\\s*$", "^\\s*%\\}\\s*$"),
          hljs5.COMMENT("%", "$")
        ]
      };
    }
    module.exports = matlab;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/maxima.js
var require_maxima = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/maxima.js"(exports, module) {
    init_process_shim();
    function maxima(hljs5) {
      const KEYWORDS3 = "if then else elseif for thru do while unless step in and or not";
      const LITERALS3 = "true false unknown inf minf ind und %e %i %pi %phi %gamma";
      const BUILTIN_FUNCTIONS = " abasep abs absint absolute_real_time acos acosh acot acoth acsc acsch activate addcol add_edge add_edges addmatrices addrow add_vertex add_vertices adjacency_matrix adjoin adjoint af agd airy airy_ai airy_bi airy_dai airy_dbi algsys alg_type alias allroots alphacharp alphanumericp amortization %and annuity_fv annuity_pv antid antidiff AntiDifference append appendfile apply apply1 apply2 applyb1 apropos args arit_amortization arithmetic arithsum array arrayapply arrayinfo arraymake arraysetapply ascii asec asech asin asinh askinteger asksign assoc assoc_legendre_p assoc_legendre_q assume assume_external_byte_order asympa at atan atan2 atanh atensimp atom atvalue augcoefmatrix augmented_lagrangian_method av average_degree backtrace bars barsplot barsplot_description base64 base64_decode bashindices batch batchload bc2 bdvac belln benefit_cost bern bernpoly bernstein_approx bernstein_expand bernstein_poly bessel bessel_i bessel_j bessel_k bessel_simplify bessel_y beta beta_incomplete beta_incomplete_generalized beta_incomplete_regularized bezout bfallroots bffac bf_find_root bf_fmin_cobyla bfhzeta bfloat bfloatp bfpsi bfpsi0 bfzeta biconnected_components bimetric binomial bipartition block blockmatrixp bode_gain bode_phase bothcoef box boxplot boxplot_description break bug_report build_info|10 buildq build_sample burn cabs canform canten cardinality carg cartan cartesian_product catch cauchy_matrix cbffac cdf_bernoulli cdf_beta cdf_binomial cdf_cauchy cdf_chi2 cdf_continuous_uniform cdf_discrete_uniform cdf_exp cdf_f cdf_gamma cdf_general_finite_discrete cdf_geometric cdf_gumbel cdf_hypergeometric cdf_laplace cdf_logistic cdf_lognormal cdf_negative_binomial cdf_noncentral_chi2 cdf_noncentral_student_t cdf_normal cdf_pareto cdf_poisson cdf_rank_sum cdf_rayleigh cdf_signed_rank cdf_student_t cdf_weibull cdisplay ceiling central_moment cequal cequalignore cf cfdisrep cfexpand cgeodesic cgreaterp cgreaterpignore changename changevar chaosgame charat charfun charfun2 charlist charp charpoly chdir chebyshev_t chebyshev_u checkdiv check_overlaps chinese cholesky christof chromatic_index chromatic_number cint circulant_graph clear_edge_weight clear_rules clear_vertex_label clebsch_gordan clebsch_graph clessp clesspignore close closefile cmetric coeff coefmatrix cograd col collapse collectterms columnop columnspace columnswap columnvector combination combine comp2pui compare compfile compile compile_file complement_graph complete_bipartite_graph complete_graph complex_number_p components compose_functions concan concat conjugate conmetderiv connected_components connect_vertices cons constant constantp constituent constvalue cont2part content continuous_freq contortion contour_plot contract contract_edge contragrad contrib_ode convert coord copy copy_file copy_graph copylist copymatrix cor cos cosh cot coth cov cov1 covdiff covect covers crc24sum create_graph create_list csc csch csetup cspline ctaylor ct_coordsys ctransform ctranspose cube_graph cuboctahedron_graph cunlisp cv cycle_digraph cycle_graph cylindrical days360 dblint deactivate declare declare_constvalue declare_dimensions declare_fundamental_dimensions declare_fundamental_units declare_qty declare_translated declare_unit_conversion declare_units declare_weights decsym defcon define define_alt_display define_variable defint defmatch defrule defstruct deftaylor degree_sequence del delete deleten delta demo demoivre denom depends derivdegree derivlist describe desolve determinant dfloat dgauss_a dgauss_b dgeev dgemm dgeqrf dgesv dgesvd diag diagmatrix diag_matrix diagmatrixp diameter diff digitcharp dimacs_export dimacs_import dimension dimensionless dimensions dimensions_as_list direct directory discrete_freq disjoin disjointp disolate disp dispcon dispform dispfun dispJordan display disprule dispterms distrib divide divisors divsum dkummer_m dkummer_u dlange dodecahedron_graph dotproduct dotsimp dpart draw draw2d draw3d drawdf draw_file draw_graph dscalar echelon edge_coloring edge_connectivity edges eigens_by_jacobi eigenvalues eigenvectors eighth einstein eivals eivects elapsed_real_time elapsed_run_time ele2comp ele2polynome ele2pui elem elementp elevation_grid elim elim_allbut eliminate eliminate_using ellipse elliptic_e elliptic_ec elliptic_eu elliptic_f elliptic_kc elliptic_pi ematrix empty_graph emptyp endcons entermatrix entertensor entier equal equalp equiv_classes erf erfc erf_generalized erfi errcatch error errormsg errors euler ev eval_string evenp every evolution evolution2d evundiff example exp expand expandwrt expandwrt_factored expint expintegral_chi expintegral_ci expintegral_e expintegral_e1 expintegral_ei expintegral_e_simplify expintegral_li expintegral_shi expintegral_si explicit explose exponentialize express expt exsec extdiff extract_linear_equations extremal_subset ezgcd %f f90 facsum factcomb factor factorfacsum factorial factorout factorsum facts fast_central_elements fast_linsolve fasttimes featurep fernfale fft fib fibtophi fifth filename_merge file_search file_type fillarray findde find_root find_root_abs find_root_error find_root_rel first fix flatten flength float floatnump floor flower_snark flush flush1deriv flushd flushnd flush_output fmin_cobyla forget fortran fourcos fourexpand fourier fourier_elim fourint fourintcos fourintsin foursimp foursin fourth fposition frame_bracket freeof freshline fresnel_c fresnel_s from_adjacency_matrix frucht_graph full_listify fullmap fullmapl fullratsimp fullratsubst fullsetify funcsolve fundamental_dimensions fundamental_units fundef funmake funp fv g0 g1 gamma gamma_greek gamma_incomplete gamma_incomplete_generalized gamma_incomplete_regularized gauss gauss_a gauss_b gaussprob gcd gcdex gcdivide gcfac gcfactor gd generalized_lambert_w genfact gen_laguerre genmatrix gensym geo_amortization geo_annuity_fv geo_annuity_pv geomap geometric geometric_mean geosum get getcurrentdirectory get_edge_weight getenv get_lu_factors get_output_stream_string get_pixel get_plot_option get_tex_environment get_tex_environment_default get_vertex_label gfactor gfactorsum ggf girth global_variances gn gnuplot_close gnuplot_replot gnuplot_reset gnuplot_restart gnuplot_start go Gosper GosperSum gr2d gr3d gradef gramschmidt graph6_decode graph6_encode graph6_export graph6_import graph_center graph_charpoly graph_eigenvalues graph_flow graph_order graph_periphery graph_product graph_size graph_union great_rhombicosidodecahedron_graph great_rhombicuboctahedron_graph grid_graph grind grobner_basis grotzch_graph hamilton_cycle hamilton_path hankel hankel_1 hankel_2 harmonic harmonic_mean hav heawood_graph hermite hessian hgfred hilbertmap hilbert_matrix hipow histogram histogram_description hodge horner hypergeometric i0 i1 %ibes ic1 ic2 ic_convert ichr1 ichr2 icosahedron_graph icosidodecahedron_graph icurvature ident identfor identity idiff idim idummy ieqn %if ifactors iframes ifs igcdex igeodesic_coords ilt image imagpart imetric implicit implicit_derivative implicit_plot indexed_tensor indices induced_subgraph inferencep inference_result infix info_display init_atensor init_ctensor in_neighbors innerproduct inpart inprod inrt integerp integer_partitions integrate intersect intersection intervalp intopois intosum invariant1 invariant2 inverse_fft inverse_jacobi_cd inverse_jacobi_cn inverse_jacobi_cs inverse_jacobi_dc inverse_jacobi_dn inverse_jacobi_ds inverse_jacobi_nc inverse_jacobi_nd inverse_jacobi_ns inverse_jacobi_sc inverse_jacobi_sd inverse_jacobi_sn invert invert_by_adjoint invert_by_lu inv_mod irr is is_biconnected is_bipartite is_connected is_digraph is_edge_in_graph is_graph is_graph_or_digraph ishow is_isomorphic isolate isomorphism is_planar isqrt isreal_p is_sconnected is_tree is_vertex_in_graph items_inference %j j0 j1 jacobi jacobian jacobi_cd jacobi_cn jacobi_cs jacobi_dc jacobi_dn jacobi_ds jacobi_nc jacobi_nd jacobi_ns jacobi_p jacobi_sc jacobi_sd jacobi_sn JF jn join jordan julia julia_set julia_sin %k kdels kdelta kill killcontext kostka kron_delta kronecker_product kummer_m kummer_u kurtosis kurtosis_bernoulli kurtosis_beta kurtosis_binomial kurtosis_chi2 kurtosis_continuous_uniform kurtosis_discrete_uniform kurtosis_exp kurtosis_f kurtosis_gamma kurtosis_general_finite_discrete kurtosis_geometric kurtosis_gumbel kurtosis_hypergeometric kurtosis_laplace kurtosis_logistic kurtosis_lognormal kurtosis_negative_binomial kurtosis_noncentral_chi2 kurtosis_noncentral_student_t kurtosis_normal kurtosis_pareto kurtosis_poisson kurtosis_rayleigh kurtosis_student_t kurtosis_weibull label labels lagrange laguerre lambda lambert_w laplace laplacian_matrix last lbfgs lc2kdt lcharp lc_l lcm lc_u ldefint ldisp ldisplay legendre_p legendre_q leinstein length let letrules letsimp levi_civita lfreeof lgtreillis lhs li liediff limit Lindstedt linear linearinterpol linear_program linear_regression line_graph linsolve listarray list_correlations listify list_matrix_entries list_nc_monomials listoftens listofvars listp lmax lmin load loadfile local locate_matrix_entry log logcontract log_gamma lopow lorentz_gauge lowercasep lpart lratsubst lreduce lriemann lsquares_estimates lsquares_estimates_approximate lsquares_estimates_exact lsquares_mse lsquares_residual_mse lsquares_residuals lsum ltreillis lu_backsub lucas lu_factor %m macroexpand macroexpand1 make_array makebox makefact makegamma make_graph make_level_picture makelist makeOrders make_poly_continent make_poly_country make_polygon make_random_state make_rgb_picture makeset make_string_input_stream make_string_output_stream make_transform mandelbrot mandelbrot_set map mapatom maplist matchdeclare matchfix mat_cond mat_fullunblocker mat_function mathml_display mat_norm matrix matrixmap matrixp matrix_size mattrace mat_trace mat_unblocker max max_clique max_degree max_flow maximize_lp max_independent_set max_matching maybe md5sum mean mean_bernoulli mean_beta mean_binomial mean_chi2 mean_continuous_uniform mean_deviation mean_discrete_uniform mean_exp mean_f mean_gamma mean_general_finite_discrete mean_geometric mean_gumbel mean_hypergeometric mean_laplace mean_logistic mean_lognormal mean_negative_binomial mean_noncentral_chi2 mean_noncentral_student_t mean_normal mean_pareto mean_poisson mean_rayleigh mean_student_t mean_weibull median median_deviation member mesh metricexpandall mgf1_sha1 min min_degree min_edge_cut minfactorial minimalPoly minimize_lp minimum_spanning_tree minor minpack_lsquares minpack_solve min_vertex_cover min_vertex_cut mkdir mnewton mod mode_declare mode_identity ModeMatrix moebius mon2schur mono monomial_dimensions multibernstein_poly multi_display_for_texinfo multi_elem multinomial multinomial_coeff multi_orbit multiplot_mode multi_pui multsym multthru mycielski_graph nary natural_unit nc_degree ncexpt ncharpoly negative_picture neighbors new newcontext newdet new_graph newline newton new_variable next_prime nicedummies niceindices ninth nofix nonarray noncentral_moment nonmetricity nonnegintegerp nonscalarp nonzeroandfreeof notequal nounify nptetrad npv nroots nterms ntermst nthroot nullity nullspace num numbered_boundaries numberp number_to_octets num_distinct_partitions numerval numfactor num_partitions nusum nzeta nzetai nzetar octets_to_number octets_to_oid odd_girth oddp ode2 ode_check odelin oid_to_octets op opena opena_binary openr openr_binary openw openw_binary operatorp opsubst optimize %or orbit orbits ordergreat ordergreatp orderless orderlessp orthogonal_complement orthopoly_recur orthopoly_weight outermap out_neighbors outofpois pade parabolic_cylinder_d parametric parametric_surface parg parGosper parse_string parse_timedate part part2cont partfrac partition partition_set partpol path_digraph path_graph pathname_directory pathname_name pathname_type pdf_bernoulli pdf_beta pdf_binomial pdf_cauchy pdf_chi2 pdf_continuous_uniform pdf_discrete_uniform pdf_exp pdf_f pdf_gamma pdf_general_finite_discrete pdf_geometric pdf_gumbel pdf_hypergeometric pdf_laplace pdf_logistic pdf_lognormal pdf_negative_binomial pdf_noncentral_chi2 pdf_noncentral_student_t pdf_normal pdf_pareto pdf_poisson pdf_rank_sum pdf_rayleigh pdf_signed_rank pdf_student_t pdf_weibull pearson_skewness permanent permut permutation permutations petersen_graph petrov pickapart picture_equalp picturep piechart piechart_description planar_embedding playback plog plot2d plot3d plotdf ploteq plsquares pochhammer points poisdiff poisexpt poisint poismap poisplus poissimp poissubst poistimes poistrim polar polarform polartorect polar_to_xy poly_add poly_buchberger poly_buchberger_criterion poly_colon_ideal poly_content polydecomp poly_depends_p poly_elimination_ideal poly_exact_divide poly_expand poly_expt poly_gcd polygon poly_grobner poly_grobner_equal poly_grobner_member poly_grobner_subsetp poly_ideal_intersection poly_ideal_polysaturation poly_ideal_polysaturation1 poly_ideal_saturation poly_ideal_saturation1 poly_lcm poly_minimization polymod poly_multiply polynome2ele polynomialp poly_normal_form poly_normalize poly_normalize_list poly_polysaturation_extension poly_primitive_part poly_pseudo_divide poly_reduced_grobner poly_reduction poly_saturation_extension poly_s_polynomial poly_subtract polytocompanion pop postfix potential power_mod powerseries powerset prefix prev_prime primep primes principal_components print printf printfile print_graph printpois printprops prodrac product properties propvars psi psubst ptriangularize pui pui2comp pui2ele pui2polynome pui_direct puireduc push put pv qput qrange qty quad_control quad_qag quad_qagi quad_qagp quad_qags quad_qawc quad_qawf quad_qawo quad_qaws quadrilateral quantile quantile_bernoulli quantile_beta quantile_binomial quantile_cauchy quantile_chi2 quantile_continuous_uniform quantile_discrete_uniform quantile_exp quantile_f quantile_gamma quantile_general_finite_discrete quantile_geometric quantile_gumbel quantile_hypergeometric quantile_laplace quantile_logistic quantile_lognormal quantile_negative_binomial quantile_noncentral_chi2 quantile_noncentral_student_t quantile_normal quantile_pareto quantile_poisson quantile_rayleigh quantile_student_t quantile_weibull quartile_skewness quit qunit quotient racah_v racah_w radcan radius random random_bernoulli random_beta random_binomial random_bipartite_graph random_cauchy random_chi2 random_continuous_uniform random_digraph random_discrete_uniform random_exp random_f random_gamma random_general_finite_discrete random_geometric random_graph random_graph1 random_gumbel random_hypergeometric random_laplace random_logistic random_lognormal random_negative_binomial random_network random_noncentral_chi2 random_noncentral_student_t random_normal random_pareto random_permutation random_poisson random_rayleigh random_regular_graph random_student_t random_tournament random_tree random_weibull range rank rat ratcoef ratdenom ratdiff ratdisrep ratexpand ratinterpol rational rationalize ratnumer ratnump ratp ratsimp ratsubst ratvars ratweight read read_array read_binary_array read_binary_list read_binary_matrix readbyte readchar read_hashed_array readline read_list read_matrix read_nested_list readonly read_xpm real_imagpart_to_conjugate realpart realroots rearray rectangle rectform rectform_log_if_constant recttopolar rediff reduce_consts reduce_order region region_boundaries region_boundaries_plus rem remainder remarray rembox remcomps remcon remcoord remfun remfunction remlet remove remove_constvalue remove_dimensions remove_edge remove_fundamental_dimensions remove_fundamental_units remove_plot_option remove_vertex rempart remrule remsym remvalue rename rename_file reset reset_displays residue resolvante resolvante_alternee1 resolvante_bipartite resolvante_diedrale resolvante_klein resolvante_klein3 resolvante_produit_sym resolvante_unitaire resolvante_vierer rest resultant return reveal reverse revert revert2 rgb2level rhs ricci riemann rinvariant risch rk rmdir rncombine romberg room rootscontract round row rowop rowswap rreduce run_testsuite %s save saving scalarp scaled_bessel_i scaled_bessel_i0 scaled_bessel_i1 scalefactors scanmap scatterplot scatterplot_description scene schur2comp sconcat scopy scsimp scurvature sdowncase sec sech second sequal sequalignore set_alt_display setdifference set_draw_defaults set_edge_weight setelmx setequalp setify setp set_partitions set_plot_option set_prompt set_random_state set_tex_environment set_tex_environment_default setunits setup_autoload set_up_dot_simplifications set_vertex_label seventh sexplode sf sha1sum sha256sum shortest_path shortest_weighted_path show showcomps showratvars sierpinskiale sierpinskimap sign signum similaritytransform simp_inequality simplify_sum simplode simpmetderiv simtran sin sinh sinsert sinvertcase sixth skewness skewness_bernoulli skewness_beta skewness_binomial skewness_chi2 skewness_continuous_uniform skewness_discrete_uniform skewness_exp skewness_f skewness_gamma skewness_general_finite_discrete skewness_geometric skewness_gumbel skewness_hypergeometric skewness_laplace skewness_logistic skewness_lognormal skewness_negative_binomial skewness_noncentral_chi2 skewness_noncentral_student_t skewness_normal skewness_pareto skewness_poisson skewness_rayleigh skewness_student_t skewness_weibull slength smake small_rhombicosidodecahedron_graph small_rhombicuboctahedron_graph smax smin smismatch snowmap snub_cube_graph snub_dodecahedron_graph solve solve_rec solve_rec_rat some somrac sort sparse6_decode sparse6_encode sparse6_export sparse6_import specint spherical spherical_bessel_j spherical_bessel_y spherical_hankel1 spherical_hankel2 spherical_harmonic spherical_to_xyz splice split sposition sprint sqfr sqrt sqrtdenest sremove sremovefirst sreverse ssearch ssort sstatus ssubst ssubstfirst staircase standardize standardize_inverse_trig starplot starplot_description status std std1 std_bernoulli std_beta std_binomial std_chi2 std_continuous_uniform std_discrete_uniform std_exp std_f std_gamma std_general_finite_discrete std_geometric std_gumbel std_hypergeometric std_laplace std_logistic std_lognormal std_negative_binomial std_noncentral_chi2 std_noncentral_student_t std_normal std_pareto std_poisson std_rayleigh std_student_t std_weibull stemplot stirling stirling1 stirling2 strim striml strimr string stringout stringp strong_components struve_h struve_l sublis sublist sublist_indices submatrix subsample subset subsetp subst substinpart subst_parallel substpart substring subvar subvarp sum sumcontract summand_to_rec supcase supcontext symbolp symmdifference symmetricp system take_channel take_inference tan tanh taylor taylorinfo taylorp taylor_simplifier taytorat tcl_output tcontract tellrat tellsimp tellsimpafter tentex tenth test_mean test_means_difference test_normality test_proportion test_proportions_difference test_rank_sum test_sign test_signed_rank test_variance test_variance_ratio tex tex1 tex_display texput %th third throw time timedate timer timer_info tldefint tlimit todd_coxeter toeplitz tokens to_lisp topological_sort to_poly to_poly_solve totaldisrep totalfourier totient tpartpol trace tracematrix trace_options transform_sample translate translate_file transpose treefale tree_reduce treillis treinat triangle triangularize trigexpand trigrat trigreduce trigsimp trunc truncate truncated_cube_graph truncated_dodecahedron_graph truncated_icosahedron_graph truncated_tetrahedron_graph tr_warnings_get tube tutte_graph ueivects uforget ultraspherical underlying_graph undiff union unique uniteigenvectors unitp units unit_step unitvector unorder unsum untellrat untimer untrace uppercasep uricci uriemann uvect vandermonde_matrix var var1 var_bernoulli var_beta var_binomial var_chi2 var_continuous_uniform var_discrete_uniform var_exp var_f var_gamma var_general_finite_discrete var_geometric var_gumbel var_hypergeometric var_laplace var_logistic var_lognormal var_negative_binomial var_noncentral_chi2 var_noncentral_student_t var_normal var_pareto var_poisson var_rayleigh var_student_t var_weibull vector vectorpotential vectorsimp verbify vers vertex_coloring vertex_connectivity vertex_degree vertex_distance vertex_eccentricity vertex_in_degree vertex_out_degree vertices vertices_to_cycle vertices_to_path %w weyl wheel_graph wiener_index wigner_3j wigner_6j wigner_9j with_stdout write_binary_data writebyte write_data writefile wronskian xreduce xthru %y Zeilberger zeroequiv zerofor zeromatrix zeromatrixp zeta zgeev zheev zlange zn_add_table zn_carmichael_lambda zn_characteristic_factors zn_determinant zn_factor_generators zn_invert_by_lu zn_log zn_mult_table absboxchar activecontexts adapt_depth additive adim aform algebraic algepsilon algexact aliases allbut all_dotsimp_denoms allocation allsym alphabetic animation antisymmetric arrays askexp assume_pos assume_pos_pred assumescalar asymbol atomgrad atrig1 axes axis_3d axis_bottom axis_left axis_right axis_top azimuth background background_color backsubst berlefact bernstein_explicit besselexpand beta_args_sum_to_integer beta_expand bftorat bftrunc bindtest border boundaries_array box boxchar breakup %c capping cauchysum cbrange cbtics center cflength cframe_flag cnonmet_flag color color_bar color_bar_tics colorbox columns commutative complex cone context contexts contour contour_levels cosnpiflag ctaypov ctaypt ctayswitch ctayvar ct_coords ctorsion_flag ctrgsimp cube current_let_rule_package cylinder data_file_name debugmode decreasing default_let_rule_package delay dependencies derivabbrev derivsubst detout diagmetric diff dim dimensions dispflag display2d|10 display_format_internal distribute_over doallmxops domain domxexpt domxmxops domxnctimes dontfactor doscmxops doscmxplus dot0nscsimp dot0simp dot1simp dotassoc dotconstrules dotdistrib dotexptsimp dotident dotscrules draw_graph_program draw_realpart edge_color edge_coloring edge_partition edge_type edge_width %edispflag elevation %emode endphi endtheta engineering_format_floats enhanced3d %enumer epsilon_lp erfflag erf_representation errormsg error_size error_syms error_type %e_to_numlog eval even evenfun evflag evfun ev_point expandwrt_denom expintexpand expintrep expon expop exptdispflag exptisolate exptsubst facexpand facsum_combine factlim factorflag factorial_expand factors_only fb feature features file_name file_output_append file_search_demo file_search_lisp file_search_maxima|10 file_search_tests file_search_usage file_type_lisp file_type_maxima|10 fill_color fill_density filled_func fixed_vertices flipflag float2bf font font_size fortindent fortspaces fpprec fpprintprec functions gamma_expand gammalim gdet genindex gensumnum GGFCFMAX GGFINFINITY globalsolve gnuplot_command gnuplot_curve_styles gnuplot_curve_titles gnuplot_default_term_command gnuplot_dumb_term_command gnuplot_file_args gnuplot_file_name gnuplot_out_file gnuplot_pdf_term_command gnuplot_pm3d gnuplot_png_term_command gnuplot_postamble gnuplot_preamble gnuplot_ps_term_command gnuplot_svg_term_command gnuplot_term gnuplot_view_args Gosper_in_Zeilberger gradefs grid grid2d grind halfangles head_angle head_both head_length head_type height hypergeometric_representation %iargs ibase icc1 icc2 icounter idummyx ieqnprint ifb ifc1 ifc2 ifg ifgi ifr iframe_bracket_form ifri igeowedge_flag ikt1 ikt2 imaginary inchar increasing infeval infinity inflag infolists inm inmc1 inmc2 intanalysis integer integervalued integrate_use_rootsof integration_constant integration_constant_counter interpolate_color intfaclim ip_grid ip_grid_in irrational isolate_wrt_times iterations itr julia_parameter %k1 %k2 keepfloat key key_pos kinvariant kt label label_alignment label_orientation labels lassociative lbfgs_ncorrections lbfgs_nfeval_max leftjust legend letrat let_rule_packages lfg lg lhospitallim limsubst linear linear_solver linechar linel|10 linenum line_type linewidth line_width linsolve_params linsolvewarn lispdisp listarith listconstvars listdummyvars lmxchar load_pathname loadprint logabs logarc logcb logconcoeffp logexpand lognegint logsimp logx logx_secondary logy logy_secondary logz lriem m1pbranch macroexpansion macros mainvar manual_demo maperror mapprint matrix_element_add matrix_element_mult matrix_element_transpose maxapplydepth maxapplyheight maxima_tempdir|10 maxima_userdir|10 maxnegex MAX_ORD maxposex maxpsifracdenom maxpsifracnum maxpsinegint maxpsiposint maxtayorder mesh_lines_color method mod_big_prime mode_check_errorp mode_checkp mode_check_warnp mod_test mod_threshold modular_linear_solver modulus multiplicative multiplicities myoptions nary negdistrib negsumdispflag newline newtonepsilon newtonmaxiter nextlayerfactor niceindicespref nm nmc noeval nolabels nonegative_lp noninteger nonscalar noun noundisp nouns np npi nticks ntrig numer numer_pbranch obase odd oddfun opacity opproperties opsubst optimprefix optionset orientation origin orthopoly_returns_intervals outative outchar packagefile palette partswitch pdf_file pfeformat phiresolution %piargs piece pivot_count_sx pivot_max_sx plot_format plot_options plot_realpart png_file pochhammer_max_index points pointsize point_size points_joined point_type poislim poisson poly_coefficient_ring poly_elimination_order polyfactor poly_grobner_algorithm poly_grobner_debug poly_monomial_order poly_primary_elimination_order poly_return_term_list poly_secondary_elimination_order poly_top_reduction_only posfun position powerdisp pred prederror primep_number_of_tests product_use_gamma program programmode promote_float_to_bigfloat prompt proportional_axes props psexpand ps_file radexpand radius radsubstflag rassociative ratalgdenom ratchristof ratdenomdivide rateinstein ratepsilon ratfac rational ratmx ratprint ratriemann ratsimpexpons ratvarswitch ratweights ratweyl ratwtlvl real realonly redraw refcheck resolution restart resultant ric riem rmxchar %rnum_list rombergabs rombergit rombergmin rombergtol rootsconmode rootsepsilon run_viewer same_xy same_xyz savedef savefactors scalar scalarmatrixp scale scale_lp setcheck setcheckbreak setval show_edge_color show_edges show_edge_type show_edge_width show_id show_label showtime show_vertex_color show_vertex_size show_vertex_type show_vertices show_weight simp simplified_output simplify_products simpproduct simpsum sinnpiflag solvedecomposes solveexplicit solvefactors solvenullwarn solveradcan solvetrigwarn space sparse sphere spring_embedding_depth sqrtdispflag stardisp startphi starttheta stats_numer stringdisp structures style sublis_apply_lambda subnumsimp sumexpand sumsplitfact surface surface_hide svg_file symmetric tab taylordepth taylor_logexpand taylor_order_coefficients taylor_truncate_polynomials tensorkill terminal testsuite_files thetaresolution timer_devalue title tlimswitch tr track transcompile transform transform_xy translate_fast_arrays transparent transrun tr_array_as_ref tr_bound_function_applyp tr_file_tty_messagesp tr_float_can_branch_complex tr_function_call_default trigexpandplus trigexpandtimes triginverses trigsign trivial_solutions tr_numer tr_optimize_max_loop tr_semicompile tr_state_vars tr_warn_bad_function_calls tr_warn_fexpr tr_warn_meval tr_warn_mode tr_warn_undeclared tr_warn_undefined_variable tstep ttyoff tube_extremes ufg ug %unitexpand unit_vectors uric uriem use_fast_arrays user_preamble usersetunits values vect_cross verbose vertex_color vertex_coloring vertex_partition vertex_size vertex_type view warnings weyl width windowname windowtitle wired_surface wireframe xaxis xaxis_color xaxis_secondary xaxis_type xaxis_width xlabel xlabel_secondary xlength xrange xrange_secondary xtics xtics_axis xtics_rotate xtics_rotate_secondary xtics_secondary xtics_secondary_axis xu_grid x_voxel xy_file xyplane xy_scale yaxis yaxis_color yaxis_secondary yaxis_type yaxis_width ylabel ylabel_secondary ylength yrange yrange_secondary ytics ytics_axis ytics_rotate ytics_rotate_secondary ytics_secondary ytics_secondary_axis yv_grid y_voxel yx_ratio zaxis zaxis_color zaxis_type zaxis_width zeroa zerob zerobern zeta%pi zlabel zlabel_rotate zlength zmin zn_primroot_limit zn_primroot_pretest";
      const SYMBOLS = "_ __ %|0 %%|0";
      return {
        name: "Maxima",
        keywords: {
          $pattern: "[A-Za-z_%][0-9A-Za-z_%]*",
          keyword: KEYWORDS3,
          literal: LITERALS3,
          built_in: BUILTIN_FUNCTIONS,
          symbol: SYMBOLS
        },
        contains: [
          {
            className: "comment",
            begin: "/\\*",
            end: "\\*/",
            contains: ["self"]
          },
          hljs5.QUOTE_STRING_MODE,
          {
            className: "number",
            relevance: 0,
            variants: [
              {
                // float number w/ exponent
                // hmm, I wonder if we ought to include other exponent markers?
                begin: "\\b(\\d+|\\d+\\.|\\.\\d+|\\d+\\.\\d+)[Ee][-+]?\\d+\\b"
              },
              {
                // bigfloat number
                begin: "\\b(\\d+|\\d+\\.|\\.\\d+|\\d+\\.\\d+)[Bb][-+]?\\d+\\b",
                relevance: 10
              },
              {
                // float number w/out exponent
                // Doesn't seem to recognize floats which start with '.'
                begin: "\\b(\\.\\d+|\\d+\\.\\d+)\\b"
              },
              {
                // integer in base up to 36
                // Doesn't seem to recognize integers which end with '.'
                begin: "\\b(\\d+|0[0-9A-Za-z]+)\\.?\\b"
              }
            ]
          }
        ],
        illegal: /@/
      };
    }
    module.exports = maxima;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/mel.js
var require_mel = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/mel.js"(exports, module) {
    init_process_shim();
    function mel(hljs5) {
      return {
        name: "MEL",
        keywords: "int float string vector matrix if else switch case default while do for in break continue global proc return about abs addAttr addAttributeEditorNodeHelp addDynamic addNewShelfTab addPP addPanelCategory addPrefixToName advanceToNextDrivenKey affectedNet affects aimConstraint air alias aliasAttr align alignCtx alignCurve alignSurface allViewFit ambientLight angle angleBetween animCone animCurveEditor animDisplay animView annotate appendStringArray applicationName applyAttrPreset applyTake arcLenDimContext arcLengthDimension arclen arrayMapper art3dPaintCtx artAttrCtx artAttrPaintVertexCtx artAttrSkinPaintCtx artAttrTool artBuildPaintMenu artFluidAttrCtx artPuttyCtx artSelectCtx artSetPaintCtx artUserPaintCtx assignCommand assignInputDevice assignViewportFactories attachCurve attachDeviceAttr attachSurface attrColorSliderGrp attrCompatibility attrControlGrp attrEnumOptionMenu attrEnumOptionMenuGrp attrFieldGrp attrFieldSliderGrp attrNavigationControlGrp attrPresetEditWin attributeExists attributeInfo attributeMenu attributeQuery autoKeyframe autoPlace bakeClip bakeFluidShading bakePartialHistory bakeResults bakeSimulation basename basenameEx batchRender bessel bevel bevelPlus binMembership bindSkin blend2 blendShape blendShapeEditor blendShapePanel blendTwoAttr blindDataType boneLattice boundary boxDollyCtx boxZoomCtx bufferCurve buildBookmarkMenu buildKeyframeMenu button buttonManip CBG cacheFile cacheFileCombine cacheFileMerge cacheFileTrack camera cameraView canCreateManip canvas capitalizeString catch catchQuiet ceil changeSubdivComponentDisplayLevel changeSubdivRegion channelBox character characterMap characterOutlineEditor characterize chdir checkBox checkBoxGrp checkDefaultRenderGlobals choice circle circularFillet clamp clear clearCache clip clipEditor clipEditorCurrentTimeCtx clipSchedule clipSchedulerOutliner clipTrimBefore closeCurve closeSurface cluster cmdFileOutput cmdScrollFieldExecuter cmdScrollFieldReporter cmdShell coarsenSubdivSelectionList collision color colorAtPoint colorEditor colorIndex colorIndexSliderGrp colorSliderButtonGrp colorSliderGrp columnLayout commandEcho commandLine commandPort compactHairSystem componentEditor compositingInterop computePolysetVolume condition cone confirmDialog connectAttr connectControl connectDynamic connectJoint connectionInfo constrain constrainValue constructionHistory container containsMultibyte contextInfo control convertFromOldLayers convertIffToPsd convertLightmap convertSolidTx convertTessellation convertUnit copyArray copyFlexor copyKey copySkinWeights cos cpButton cpCache cpClothSet cpCollision cpConstraint cpConvClothToMesh cpForces cpGetSolverAttr cpPanel cpProperty cpRigidCollisionFilter cpSeam cpSetEdit cpSetSolverAttr cpSolver cpSolverTypes cpTool cpUpdateClothUVs createDisplayLayer createDrawCtx createEditor createLayeredPsdFile createMotionField createNewShelf createNode createRenderLayer createSubdivRegion cross crossProduct ctxAbort ctxCompletion ctxEditMode ctxTraverse currentCtx currentTime currentTimeCtx currentUnit curve curveAddPtCtx curveCVCtx curveEPCtx curveEditorCtx curveIntersect curveMoveEPCtx curveOnSurface curveSketchCtx cutKey cycleCheck cylinder dagPose date defaultLightListCheckBox defaultNavigation defineDataServer defineVirtualDevice deformer deg_to_rad delete deleteAttr deleteShadingGroupsAndMaterials deleteShelfTab deleteUI deleteUnusedBrushes delrandstr detachCurve detachDeviceAttr detachSurface deviceEditor devicePanel dgInfo dgdirty dgeval dgtimer dimWhen directKeyCtx directionalLight dirmap dirname disable disconnectAttr disconnectJoint diskCache displacementToPoly displayAffected displayColor displayCull displayLevelOfDetail displayPref displayRGBColor displaySmoothness displayStats displayString displaySurface distanceDimContext distanceDimension doBlur dolly dollyCtx dopeSheetEditor dot dotProduct doubleProfileBirailSurface drag dragAttrContext draggerContext dropoffLocator duplicate duplicateCurve duplicateSurface dynCache dynControl dynExport dynExpression dynGlobals dynPaintEditor dynParticleCtx dynPref dynRelEdPanel dynRelEditor dynamicLoad editAttrLimits editDisplayLayerGlobals editDisplayLayerMembers editRenderLayerAdjustment editRenderLayerGlobals editRenderLayerMembers editor editorTemplate effector emit emitter enableDevice encodeString endString endsWith env equivalent equivalentTol erf error eval evalDeferred evalEcho event exactWorldBoundingBox exclusiveLightCheckBox exec executeForEachObject exists exp expression expressionEditorListen extendCurve extendSurface extrude fcheck fclose feof fflush fgetline fgetword file fileBrowserDialog fileDialog fileExtension fileInfo filetest filletCurve filter filterCurve filterExpand filterStudioImport findAllIntersections findAnimCurves findKeyframe findMenuItem findRelatedSkinCluster finder firstParentOf fitBspline flexor floatEq floatField floatFieldGrp floatScrollBar floatSlider floatSlider2 floatSliderButtonGrp floatSliderGrp floor flow fluidCacheInfo fluidEmitter fluidVoxelInfo flushUndo fmod fontDialog fopen formLayout format fprint frameLayout fread freeFormFillet frewind fromNativePath fwrite gamma gauss geometryConstraint getApplicationVersionAsFloat getAttr getClassification getDefaultBrush getFileList getFluidAttr getInputDeviceRange getMayaPanelTypes getModifiers getPanel getParticleAttr getPluginResource getenv getpid glRender glRenderEditor globalStitch gmatch goal gotoBindPose grabColor gradientControl gradientControlNoAttr graphDollyCtx graphSelectContext graphTrackCtx gravity grid gridLayout group groupObjectsByName HfAddAttractorToAS HfAssignAS HfBuildEqualMap HfBuildFurFiles HfBuildFurImages HfCancelAFR HfConnectASToHF HfCreateAttractor HfDeleteAS HfEditAS HfPerformCreateAS HfRemoveAttractorFromAS HfSelectAttached HfSelectAttractors HfUnAssignAS hardenPointCurve hardware hardwareRenderPanel headsUpDisplay headsUpMessage help helpLine hermite hide hilite hitTest hotBox hotkey hotkeyCheck hsv_to_rgb hudButton hudSlider hudSliderButton hwReflectionMap hwRender hwRenderLoad hyperGraph hyperPanel hyperShade hypot iconTextButton iconTextCheckBox iconTextRadioButton iconTextRadioCollection iconTextScrollList iconTextStaticLabel ikHandle ikHandleCtx ikHandleDisplayScale ikSolver ikSplineHandleCtx ikSystem ikSystemInfo ikfkDisplayMethod illustratorCurves image imfPlugins inheritTransform insertJoint insertJointCtx insertKeyCtx insertKnotCurve insertKnotSurface instance instanceable instancer intField intFieldGrp intScrollBar intSlider intSliderGrp interToUI internalVar intersect iprEngine isAnimCurve isConnected isDirty isParentOf isSameObject isTrue isValidObjectName isValidString isValidUiName isolateSelect itemFilter itemFilterAttr itemFilterRender itemFilterType joint jointCluster jointCtx jointDisplayScale jointLattice keyTangent keyframe keyframeOutliner keyframeRegionCurrentTimeCtx keyframeRegionDirectKeyCtx keyframeRegionDollyCtx keyframeRegionInsertKeyCtx keyframeRegionMoveKeyCtx keyframeRegionScaleKeyCtx keyframeRegionSelectKeyCtx keyframeRegionSetKeyCtx keyframeRegionTrackCtx keyframeStats lassoContext lattice latticeDeformKeyCtx launch launchImageEditor layerButton layeredShaderPort layeredTexturePort layout layoutDialog lightList lightListEditor lightListPanel lightlink lineIntersection linearPrecision linstep listAnimatable listAttr listCameras listConnections listDeviceAttachments listHistory listInputDeviceAxes listInputDeviceButtons listInputDevices listMenuAnnotation listNodeTypes listPanelCategories listRelatives listSets listTransforms listUnselected listerEditor loadFluid loadNewShelf loadPlugin loadPluginLanguageResources loadPrefObjects localizedPanelLabel lockNode loft log longNameOf lookThru ls lsThroughFilter lsType lsUI Mayatomr mag makeIdentity makeLive makePaintable makeRoll makeSingleSurface makeTubeOn makebot manipMoveContext manipMoveLimitsCtx manipOptions manipRotateContext manipRotateLimitsCtx manipScaleContext manipScaleLimitsCtx marker match max memory menu menuBarLayout menuEditor menuItem menuItemToShelf menuSet menuSetPref messageLine min minimizeApp mirrorJoint modelCurrentTimeCtx modelEditor modelPanel mouse movIn movOut move moveIKtoFK moveKeyCtx moveVertexAlongDirection multiProfileBirailSurface mute nParticle nameCommand nameField namespace namespaceInfo newPanelItems newton nodeCast nodeIconButton nodeOutliner nodePreset nodeType noise nonLinear normalConstraint normalize nurbsBoolean nurbsCopyUVSet nurbsCube nurbsEditUV nurbsPlane nurbsSelect nurbsSquare nurbsToPoly nurbsToPolygonsPref nurbsToSubdiv nurbsToSubdivPref nurbsUVSet nurbsViewDirectionVector objExists objectCenter objectLayer objectType objectTypeUI obsoleteProc oceanNurbsPreviewPlane offsetCurve offsetCurveOnSurface offsetSurface openGLExtension openMayaPref optionMenu optionMenuGrp optionVar orbit orbitCtx orientConstraint outlinerEditor outlinerPanel overrideModifier paintEffectsDisplay pairBlend palettePort paneLayout panel panelConfiguration panelHistory paramDimContext paramDimension paramLocator parent parentConstraint particle particleExists particleInstancer particleRenderInfo partition pasteKey pathAnimation pause pclose percent performanceOptions pfxstrokes pickWalk picture pixelMove planarSrf plane play playbackOptions playblast plugAttr plugNode pluginInfo pluginResourceUtil pointConstraint pointCurveConstraint pointLight pointMatrixMult pointOnCurve pointOnSurface pointPosition poleVectorConstraint polyAppend polyAppendFacetCtx polyAppendVertex polyAutoProjection polyAverageNormal polyAverageVertex polyBevel polyBlendColor polyBlindData polyBoolOp polyBridgeEdge polyCacheMonitor polyCheck polyChipOff polyClipboard polyCloseBorder polyCollapseEdge polyCollapseFacet polyColorBlindData polyColorDel polyColorPerVertex polyColorSet polyCompare polyCone polyCopyUV polyCrease polyCreaseCtx polyCreateFacet polyCreateFacetCtx polyCube polyCut polyCutCtx polyCylinder polyCylindricalProjection polyDelEdge polyDelFacet polyDelVertex polyDuplicateAndConnect polyDuplicateEdge polyEditUV polyEditUVShell polyEvaluate polyExtrudeEdge polyExtrudeFacet polyExtrudeVertex polyFlipEdge polyFlipUV polyForceUV polyGeoSampler polyHelix polyInfo polyInstallAction polyLayoutUV polyListComponentConversion polyMapCut polyMapDel polyMapSew polyMapSewMove polyMergeEdge polyMergeEdgeCtx polyMergeFacet polyMergeFacetCtx polyMergeUV polyMergeVertex polyMirrorFace polyMoveEdge polyMoveFacet polyMoveFacetUV polyMoveUV polyMoveVertex polyNormal polyNormalPerVertex polyNormalizeUV polyOptUvs polyOptions polyOutput polyPipe polyPlanarProjection polyPlane polyPlatonicSolid polyPoke polyPrimitive polyPrism polyProjection polyPyramid polyQuad polyQueryBlindData polyReduce polySelect polySelectConstraint polySelectConstraintMonitor polySelectCtx polySelectEditCtx polySeparate polySetToFaceNormal polySewEdge polyShortestPathCtx polySmooth polySoftEdge polySphere polySphericalProjection polySplit polySplitCtx polySplitEdge polySplitRing polySplitVertex polyStraightenUVBorder polySubdivideEdge polySubdivideFacet polyToSubdiv polyTorus polyTransfer polyTriangulate polyUVSet polyUnite polyWedgeFace popen popupMenu pose pow preloadRefEd print progressBar progressWindow projFileViewer projectCurve projectTangent projectionContext projectionManip promptDialog propModCtx propMove psdChannelOutliner psdEditTextureFile psdExport psdTextureFile putenv pwd python querySubdiv quit rad_to_deg radial radioButton radioButtonGrp radioCollection radioMenuItemCollection rampColorPort rand randomizeFollicles randstate rangeControl readTake rebuildCurve rebuildSurface recordAttr recordDevice redo reference referenceEdit referenceQuery refineSubdivSelectionList refresh refreshAE registerPluginResource rehash reloadImage removeJoint removeMultiInstance removePanelCategory rename renameAttr renameSelectionList renameUI render renderGlobalsNode renderInfo renderLayerButton renderLayerParent renderLayerPostProcess renderLayerUnparent renderManip renderPartition renderQualityNode renderSettings renderThumbnailUpdate renderWindowEditor renderWindowSelectContext renderer reorder reorderDeformers requires reroot resampleFluid resetAE resetPfxToPolyCamera resetTool resolutionNode retarget reverseCurve reverseSurface revolve rgb_to_hsv rigidBody rigidSolver roll rollCtx rootOf rot rotate rotationInterpolation roundConstantRadius rowColumnLayout rowLayout runTimeCommand runup sampleImage saveAllShelves saveAttrPreset saveFluid saveImage saveInitialState saveMenu savePrefObjects savePrefs saveShelf saveToolSettings scale scaleBrushBrightness scaleComponents scaleConstraint scaleKey scaleKeyCtx sceneEditor sceneUIReplacement scmh scriptCtx scriptEditorInfo scriptJob scriptNode scriptTable scriptToShelf scriptedPanel scriptedPanelType scrollField scrollLayout sculpt searchPathArray seed selLoadSettings select selectContext selectCurveCV selectKey selectKeyCtx selectKeyframeRegionCtx selectMode selectPref selectPriority selectType selectedNodes selectionConnection separator setAttr setAttrEnumResource setAttrMapping setAttrNiceNameResource setConstraintRestPosition setDefaultShadingGroup setDrivenKeyframe setDynamic setEditCtx setEditor setFluidAttr setFocus setInfinity setInputDeviceMapping setKeyCtx setKeyPath setKeyframe setKeyframeBlendshapeTargetWts setMenuMode setNodeNiceNameResource setNodeTypeFlag setParent setParticleAttr setPfxToPolyCamera setPluginResource setProject setStampDensity setStartupMessage setState setToolTo setUITemplate setXformManip sets shadingConnection shadingGeometryRelCtx shadingLightRelCtx shadingNetworkCompare shadingNode shapeCompare shelfButton shelfLayout shelfTabLayout shellField shortNameOf showHelp showHidden showManipCtx showSelectionInTitle showShadingGroupAttrEditor showWindow sign simplify sin singleProfileBirailSurface size sizeBytes skinCluster skinPercent smoothCurve smoothTangentSurface smoothstep snap2to2 snapKey snapMode snapTogetherCtx snapshot soft softMod softModCtx sort sound soundControl source spaceLocator sphere sphrand spotLight spotLightPreviewPort spreadSheetEditor spring sqrt squareSurface srtContext stackTrace startString startsWith stitchAndExplodeShell stitchSurface stitchSurfacePoints strcmp stringArrayCatenate stringArrayContains stringArrayCount stringArrayInsertAtIndex stringArrayIntersector stringArrayRemove stringArrayRemoveAtIndex stringArrayRemoveDuplicates stringArrayRemoveExact stringArrayToString stringToStringArray strip stripPrefixFromName stroke subdAutoProjection subdCleanTopology subdCollapse subdDuplicateAndConnect subdEditUV subdListComponentConversion subdMapCut subdMapSewMove subdMatchTopology subdMirror subdToBlind subdToPoly subdTransferUVsToCache subdiv subdivCrease subdivDisplaySmoothness substitute substituteAllString substituteGeometry substring surface surfaceSampler surfaceShaderList swatchDisplayPort switchTable symbolButton symbolCheckBox sysFile system tabLayout tan tangentConstraint texLatticeDeformContext texManipContext texMoveContext texMoveUVShellContext texRotateContext texScaleContext texSelectContext texSelectShortestPathCtx texSmudgeUVContext texWinToolCtx text textCurves textField textFieldButtonGrp textFieldGrp textManip textScrollList textToShelf textureDisplacePlane textureHairColor texturePlacementContext textureWindow threadCount threePointArcCtx timeControl timePort timerX toNativePath toggle toggleAxis toggleWindowVisibility tokenize tokenizeList tolerance tolower toolButton toolCollection toolDropped toolHasOptions toolPropertyWindow torus toupper trace track trackCtx transferAttributes transformCompare transformLimits translator trim trunc truncateFluidCache truncateHairCache tumble tumbleCtx turbulence twoPointArcCtx uiRes uiTemplate unassignInputDevice undo undoInfo ungroup uniform unit unloadPlugin untangleUV untitledFileName untrim upAxis updateAE userCtx uvLink uvSnapshot validateShelfName vectorize view2dToolCtx viewCamera viewClipPlane viewFit viewHeadOn viewLookAt viewManip viewPlace viewSet visor volumeAxis vortex waitCursor warning webBrowser webBrowserPrefs whatIs window windowPref wire wireContext workspace wrinkle wrinkleContext writeTake xbmLangPathList xform",
        illegal: "</",
        contains: [
          hljs5.C_NUMBER_MODE,
          hljs5.APOS_STRING_MODE,
          hljs5.QUOTE_STRING_MODE,
          {
            className: "string",
            begin: "`",
            end: "`",
            contains: [hljs5.BACKSLASH_ESCAPE]
          },
          {
            // eats variables
            begin: /[$%@](\^\w\b|#\w+|[^\s\w{]|\{\w+\}|\w+)/
          },
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE
        ]
      };
    }
    module.exports = mel;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/mercury.js
var require_mercury = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/mercury.js"(exports, module) {
    init_process_shim();
    function mercury(hljs5) {
      const KEYWORDS3 = {
        keyword: "module use_module import_module include_module end_module initialise mutable initialize finalize finalise interface implementation pred mode func type inst solver any_pred any_func is semidet det nondet multi erroneous failure cc_nondet cc_multi typeclass instance where pragma promise external trace atomic or_else require_complete_switch require_det require_semidet require_multi require_nondet require_cc_multi require_cc_nondet require_erroneous require_failure",
        meta: (
          // pragma
          "inline no_inline type_spec source_file fact_table obsolete memo loop_check minimal_model terminates does_not_terminate check_termination promise_equivalent_clauses foreign_proc foreign_decl foreign_code foreign_type foreign_import_module foreign_export_enum foreign_export foreign_enum may_call_mercury will_not_call_mercury thread_safe not_thread_safe maybe_thread_safe promise_pure promise_semipure tabled_for_io local untrailed trailed attach_to_io_state can_pass_as_mercury_type stable will_not_throw_exception may_modify_trail will_not_modify_trail may_duplicate may_not_duplicate affects_liveness does_not_affect_liveness doesnt_affect_liveness no_sharing unknown_sharing sharing"
        ),
        built_in: "some all not if then else true fail false try catch catch_any semidet_true semidet_false semidet_fail impure_true impure semipure"
      };
      const COMMENT = hljs5.COMMENT("%", "$");
      const NUMCODE = {
        className: "number",
        begin: "0'.\\|0[box][0-9a-fA-F]*"
      };
      const ATOM2 = hljs5.inherit(hljs5.APOS_STRING_MODE, {
        relevance: 0
      });
      const STRING = hljs5.inherit(hljs5.QUOTE_STRING_MODE, {
        relevance: 0
      });
      const STRING_FMT = {
        className: "subst",
        begin: "\\\\[abfnrtv]\\|\\\\x[0-9a-fA-F]*\\\\\\|%[-+# *.0-9]*[dioxXucsfeEgGp]",
        relevance: 0
      };
      STRING.contains = STRING.contains.slice();
      STRING.contains.push(STRING_FMT);
      const IMPLICATION = {
        className: "built_in",
        variants: [
          {
            begin: "<=>"
          },
          {
            begin: "<=",
            relevance: 0
          },
          {
            begin: "=>",
            relevance: 0
          },
          {
            begin: "/\\\\"
          },
          {
            begin: "\\\\/"
          }
        ]
      };
      const HEAD_BODY_CONJUNCTION = {
        className: "built_in",
        variants: [
          {
            begin: ":-\\|-->"
          },
          {
            begin: "=",
            relevance: 0
          }
        ]
      };
      return {
        name: "Mercury",
        aliases: [
          "m",
          "moo"
        ],
        keywords: KEYWORDS3,
        contains: [
          IMPLICATION,
          HEAD_BODY_CONJUNCTION,
          COMMENT,
          hljs5.C_BLOCK_COMMENT_MODE,
          NUMCODE,
          hljs5.NUMBER_MODE,
          ATOM2,
          STRING,
          {
            // relevance booster
            begin: /:-/
          },
          {
            // relevance booster
            begin: /\.$/
          }
        ]
      };
    }
    module.exports = mercury;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/mipsasm.js
var require_mipsasm = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/mipsasm.js"(exports, module) {
    init_process_shim();
    function mipsasm(hljs5) {
      return {
        name: "MIPS Assembly",
        case_insensitive: true,
        aliases: ["mips"],
        keywords: {
          $pattern: "\\.?" + hljs5.IDENT_RE,
          meta: (
            // GNU preprocs
            ".2byte .4byte .align .ascii .asciz .balign .byte .code .data .else .end .endif .endm .endr .equ .err .exitm .extern .global .hword .if .ifdef .ifndef .include .irp .long .macro .rept .req .section .set .skip .space .text .word .ltorg "
          ),
          built_in: "$0 $1 $2 $3 $4 $5 $6 $7 $8 $9 $10 $11 $12 $13 $14 $15 $16 $17 $18 $19 $20 $21 $22 $23 $24 $25 $26 $27 $28 $29 $30 $31 zero at v0 v1 a0 a1 a2 a3 a4 a5 a6 a7 t0 t1 t2 t3 t4 t5 t6 t7 t8 t9 s0 s1 s2 s3 s4 s5 s6 s7 s8 k0 k1 gp sp fp ra $f0 $f1 $f2 $f2 $f4 $f5 $f6 $f7 $f8 $f9 $f10 $f11 $f12 $f13 $f14 $f15 $f16 $f17 $f18 $f19 $f20 $f21 $f22 $f23 $f24 $f25 $f26 $f27 $f28 $f29 $f30 $f31 Context Random EntryLo0 EntryLo1 Context PageMask Wired EntryHi HWREna BadVAddr Count Compare SR IntCtl SRSCtl SRSMap Cause EPC PRId EBase Config Config1 Config2 Config3 LLAddr Debug DEPC DESAVE CacheErr ECC ErrorEPC TagLo DataLo TagHi DataHi WatchLo WatchHi PerfCtl PerfCnt "
          // Coprocessor 0 registers
        },
        contains: [
          {
            className: "keyword",
            begin: "\\b(addi?u?|andi?|b(al)?|beql?|bgez(al)?l?|bgtzl?|blezl?|bltz(al)?l?|bnel?|cl[oz]|divu?|ext|ins|j(al)?|jalr(\\.hb)?|jr(\\.hb)?|lbu?|lhu?|ll|lui|lw[lr]?|maddu?|mfhi|mflo|movn|movz|move|msubu?|mthi|mtlo|mul|multu?|nop|nor|ori?|rotrv?|sb|sc|se[bh]|sh|sllv?|slti?u?|srav?|srlv?|subu?|sw[lr]?|xori?|wsbh|abs\\.[sd]|add\\.[sd]|alnv.ps|bc1[ft]l?|c\\.(s?f|un|u?eq|[ou]lt|[ou]le|ngle?|seq|l[et]|ng[et])\\.[sd]|(ceil|floor|round|trunc)\\.[lw]\\.[sd]|cfc1|cvt\\.d\\.[lsw]|cvt\\.l\\.[dsw]|cvt\\.ps\\.s|cvt\\.s\\.[dlw]|cvt\\.s\\.p[lu]|cvt\\.w\\.[dls]|div\\.[ds]|ldx?c1|luxc1|lwx?c1|madd\\.[sd]|mfc1|mov[fntz]?\\.[ds]|msub\\.[sd]|mth?c1|mul\\.[ds]|neg\\.[ds]|nmadd\\.[ds]|nmsub\\.[ds]|p[lu][lu]\\.ps|recip\\.fmt|r?sqrt\\.[ds]|sdx?c1|sub\\.[ds]|suxc1|swx?c1|break|cache|d?eret|[de]i|ehb|mfc0|mtc0|pause|prefx?|rdhwr|rdpgpr|sdbbp|ssnop|synci?|syscall|teqi?|tgei?u?|tlb(p|r|w[ir])|tlti?u?|tnei?|wait|wrpgpr)",
            end: "\\s"
          },
          // lines ending with ; or # aren't really comments, probably auto-detect fail
          hljs5.COMMENT("[;#](?!\\s*$)", "$"),
          hljs5.C_BLOCK_COMMENT_MODE,
          hljs5.QUOTE_STRING_MODE,
          {
            className: "string",
            begin: "'",
            end: "[^\\\\]'",
            relevance: 0
          },
          {
            className: "title",
            begin: "\\|",
            end: "\\|",
            illegal: "\\n",
            relevance: 0
          },
          {
            className: "number",
            variants: [
              {
                // hex
                begin: "0x[0-9a-f]+"
              },
              {
                // bare number
                begin: "\\b-?\\d+"
              }
            ],
            relevance: 0
          },
          {
            className: "symbol",
            variants: [
              {
                // GNU MIPS syntax
                begin: "^\\s*[a-z_\\.\\$][a-z0-9_\\.\\$]+:"
              },
              {
                // numbered local labels
                begin: "^\\s*[0-9]+:"
              },
              {
                // number local label reference (backwards, forwards)
                begin: "[0-9]+[bf]"
              }
            ],
            relevance: 0
          }
        ],
        // forward slashes are not allowed
        illegal: /\//
      };
    }
    module.exports = mipsasm;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/mizar.js
var require_mizar = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/mizar.js"(exports, module) {
    init_process_shim();
    function mizar(hljs5) {
      return {
        name: "Mizar",
        keywords: "environ vocabularies notations constructors definitions registrations theorems schemes requirements begin end definition registration cluster existence pred func defpred deffunc theorem proof let take assume then thus hence ex for st holds consider reconsider such that and in provided of as from be being by means equals implies iff redefine define now not or attr is mode suppose per cases set thesis contradiction scheme reserve struct correctness compatibility coherence symmetry assymetry reflexivity irreflexivity connectedness uniqueness commutativity idempotence involutiveness projectivity",
        contains: [
          hljs5.COMMENT("::", "$")
        ]
      };
    }
    module.exports = mizar;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/perl.js
var require_perl = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/perl.js"(exports, module) {
    init_process_shim();
    function source(re2) {
      if (!re2) return null;
      if (typeof re2 === "string") return re2;
      return re2.source;
    }
    function concat(...args) {
      const joined = args.map((x2) => source(x2)).join("");
      return joined;
    }
    function either(...args) {
      const joined = "(" + args.map((x2) => source(x2)).join("|") + ")";
      return joined;
    }
    function perl(hljs5) {
      const KEYWORDS3 = [
        "abs",
        "accept",
        "alarm",
        "and",
        "atan2",
        "bind",
        "binmode",
        "bless",
        "break",
        "caller",
        "chdir",
        "chmod",
        "chomp",
        "chop",
        "chown",
        "chr",
        "chroot",
        "close",
        "closedir",
        "connect",
        "continue",
        "cos",
        "crypt",
        "dbmclose",
        "dbmopen",
        "defined",
        "delete",
        "die",
        "do",
        "dump",
        "each",
        "else",
        "elsif",
        "endgrent",
        "endhostent",
        "endnetent",
        "endprotoent",
        "endpwent",
        "endservent",
        "eof",
        "eval",
        "exec",
        "exists",
        "exit",
        "exp",
        "fcntl",
        "fileno",
        "flock",
        "for",
        "foreach",
        "fork",
        "format",
        "formline",
        "getc",
        "getgrent",
        "getgrgid",
        "getgrnam",
        "gethostbyaddr",
        "gethostbyname",
        "gethostent",
        "getlogin",
        "getnetbyaddr",
        "getnetbyname",
        "getnetent",
        "getpeername",
        "getpgrp",
        "getpriority",
        "getprotobyname",
        "getprotobynumber",
        "getprotoent",
        "getpwent",
        "getpwnam",
        "getpwuid",
        "getservbyname",
        "getservbyport",
        "getservent",
        "getsockname",
        "getsockopt",
        "given",
        "glob",
        "gmtime",
        "goto",
        "grep",
        "gt",
        "hex",
        "if",
        "index",
        "int",
        "ioctl",
        "join",
        "keys",
        "kill",
        "last",
        "lc",
        "lcfirst",
        "length",
        "link",
        "listen",
        "local",
        "localtime",
        "log",
        "lstat",
        "lt",
        "ma",
        "map",
        "mkdir",
        "msgctl",
        "msgget",
        "msgrcv",
        "msgsnd",
        "my",
        "ne",
        "next",
        "no",
        "not",
        "oct",
        "open",
        "opendir",
        "or",
        "ord",
        "our",
        "pack",
        "package",
        "pipe",
        "pop",
        "pos",
        "print",
        "printf",
        "prototype",
        "push",
        "q|0",
        "qq",
        "quotemeta",
        "qw",
        "qx",
        "rand",
        "read",
        "readdir",
        "readline",
        "readlink",
        "readpipe",
        "recv",
        "redo",
        "ref",
        "rename",
        "require",
        "reset",
        "return",
        "reverse",
        "rewinddir",
        "rindex",
        "rmdir",
        "say",
        "scalar",
        "seek",
        "seekdir",
        "select",
        "semctl",
        "semget",
        "semop",
        "send",
        "setgrent",
        "sethostent",
        "setnetent",
        "setpgrp",
        "setpriority",
        "setprotoent",
        "setpwent",
        "setservent",
        "setsockopt",
        "shift",
        "shmctl",
        "shmget",
        "shmread",
        "shmwrite",
        "shutdown",
        "sin",
        "sleep",
        "socket",
        "socketpair",
        "sort",
        "splice",
        "split",
        "sprintf",
        "sqrt",
        "srand",
        "stat",
        "state",
        "study",
        "sub",
        "substr",
        "symlink",
        "syscall",
        "sysopen",
        "sysread",
        "sysseek",
        "system",
        "syswrite",
        "tell",
        "telldir",
        "tie",
        "tied",
        "time",
        "times",
        "tr",
        "truncate",
        "uc",
        "ucfirst",
        "umask",
        "undef",
        "unless",
        "unlink",
        "unpack",
        "unshift",
        "untie",
        "until",
        "use",
        "utime",
        "values",
        "vec",
        "wait",
        "waitpid",
        "wantarray",
        "warn",
        "when",
        "while",
        "write",
        "x|0",
        "xor",
        "y|0"
      ];
      const REGEX_MODIFIERS = /[dualxmsipngr]{0,12}/;
      const PERL_KEYWORDS = {
        $pattern: /[\w.]+/,
        keyword: KEYWORDS3.join(" ")
      };
      const SUBST = {
        className: "subst",
        begin: "[$@]\\{",
        end: "\\}",
        keywords: PERL_KEYWORDS
      };
      const METHOD = {
        begin: /->\{/,
        end: /\}/
        // contains defined later
      };
      const VAR = {
        variants: [
          {
            begin: /\$\d/
          },
          {
            begin: concat(
              /[$%@](\^\w\b|#\w+(::\w+)*|\{\w+\}|\w+(::\w*)*)/,
              // negative look-ahead tries to avoid matching patterns that are not
              // Perl at all like $ident$, @ident@, etc.
              `(?![A-Za-z])(?![@$%])`
            )
          },
          {
            begin: /[$%@][^\s\w{]/,
            relevance: 0
          }
        ]
      };
      const STRING_CONTAINS = [
        hljs5.BACKSLASH_ESCAPE,
        SUBST,
        VAR
      ];
      const REGEX_DELIMS = [
        /!/,
        /\//,
        /\|/,
        /\?/,
        /'/,
        /"/,
        // valid but infrequent and weird
        /#/
        // valid but infrequent and weird
      ];
      const PAIRED_DOUBLE_RE = (prefix, open2, close2 = "\\1") => {
        const middle = close2 === "\\1" ? close2 : concat(close2, open2);
        return concat(
          concat("(?:", prefix, ")"),
          open2,
          /(?:\\.|[^\\\/])*?/,
          middle,
          /(?:\\.|[^\\\/])*?/,
          close2,
          REGEX_MODIFIERS
        );
      };
      const PAIRED_RE = (prefix, open2, close2) => {
        return concat(
          concat("(?:", prefix, ")"),
          open2,
          /(?:\\.|[^\\\/])*?/,
          close2,
          REGEX_MODIFIERS
        );
      };
      const PERL_DEFAULT_CONTAINS = [
        VAR,
        hljs5.HASH_COMMENT_MODE,
        hljs5.COMMENT(
          /^=\w/,
          /=cut/,
          {
            endsWithParent: true
          }
        ),
        METHOD,
        {
          className: "string",
          contains: STRING_CONTAINS,
          variants: [
            {
              begin: "q[qwxr]?\\s*\\(",
              end: "\\)",
              relevance: 5
            },
            {
              begin: "q[qwxr]?\\s*\\[",
              end: "\\]",
              relevance: 5
            },
            {
              begin: "q[qwxr]?\\s*\\{",
              end: "\\}",
              relevance: 5
            },
            {
              begin: "q[qwxr]?\\s*\\|",
              end: "\\|",
              relevance: 5
            },
            {
              begin: "q[qwxr]?\\s*<",
              end: ">",
              relevance: 5
            },
            {
              begin: "qw\\s+q",
              end: "q",
              relevance: 5
            },
            {
              begin: "'",
              end: "'",
              contains: [hljs5.BACKSLASH_ESCAPE]
            },
            {
              begin: '"',
              end: '"'
            },
            {
              begin: "`",
              end: "`",
              contains: [hljs5.BACKSLASH_ESCAPE]
            },
            {
              begin: /\{\w+\}/,
              relevance: 0
            },
            {
              begin: "-?\\w+\\s*=>",
              relevance: 0
            }
          ]
        },
        {
          className: "number",
          begin: "(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b",
          relevance: 0
        },
        {
          // regexp container
          begin: "(\\/\\/|" + hljs5.RE_STARTERS_RE + "|\\b(split|return|print|reverse|grep)\\b)\\s*",
          keywords: "split return print reverse grep",
          relevance: 0,
          contains: [
            hljs5.HASH_COMMENT_MODE,
            {
              className: "regexp",
              variants: [
                // allow matching common delimiters
                { begin: PAIRED_DOUBLE_RE("s|tr|y", either(...REGEX_DELIMS)) },
                // and then paired delmis
                { begin: PAIRED_DOUBLE_RE("s|tr|y", "\\(", "\\)") },
                { begin: PAIRED_DOUBLE_RE("s|tr|y", "\\[", "\\]") },
                { begin: PAIRED_DOUBLE_RE("s|tr|y", "\\{", "\\}") }
              ],
              relevance: 2
            },
            {
              className: "regexp",
              variants: [
                {
                  // could be a comment in many languages so do not count
                  // as relevant
                  begin: /(m|qr)\/\//,
                  relevance: 0
                },
                // prefix is optional with /regex/
                { begin: PAIRED_RE("(?:m|qr)?", /\//, /\//) },
                // allow matching common delimiters
                { begin: PAIRED_RE("m|qr", either(...REGEX_DELIMS), /\1/) },
                // allow common paired delmins
                { begin: PAIRED_RE("m|qr", /\(/, /\)/) },
                { begin: PAIRED_RE("m|qr", /\[/, /\]/) },
                { begin: PAIRED_RE("m|qr", /\{/, /\}/) }
              ]
            }
          ]
        },
        {
          className: "function",
          beginKeywords: "sub",
          end: "(\\s*\\(.*?\\))?[;{]",
          excludeEnd: true,
          relevance: 5,
          contains: [hljs5.TITLE_MODE]
        },
        {
          begin: "-\\w\\b",
          relevance: 0
        },
        {
          begin: "^__DATA__$",
          end: "^__END__$",
          subLanguage: "mojolicious",
          contains: [
            {
              begin: "^@@.*",
              end: "$",
              className: "comment"
            }
          ]
        }
      ];
      SUBST.contains = PERL_DEFAULT_CONTAINS;
      METHOD.contains = PERL_DEFAULT_CONTAINS;
      return {
        name: "Perl",
        aliases: [
          "pl",
          "pm"
        ],
        keywords: PERL_KEYWORDS,
        contains: PERL_DEFAULT_CONTAINS
      };
    }
    module.exports = perl;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/mojolicious.js
var require_mojolicious = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/mojolicious.js"(exports, module) {
    init_process_shim();
    function mojolicious(hljs5) {
      return {
        name: "Mojolicious",
        subLanguage: "xml",
        contains: [
          {
            className: "meta",
            begin: "^__(END|DATA)__$"
          },
          // mojolicious line
          {
            begin: "^\\s*%{1,2}={0,2}",
            end: "$",
            subLanguage: "perl"
          },
          // mojolicious block
          {
            begin: "<%{1,2}={0,2}",
            end: "={0,1}%>",
            subLanguage: "perl",
            excludeBegin: true,
            excludeEnd: true
          }
        ]
      };
    }
    module.exports = mojolicious;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/monkey.js
var require_monkey = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/monkey.js"(exports, module) {
    init_process_shim();
    function monkey(hljs5) {
      const NUMBER = {
        className: "number",
        relevance: 0,
        variants: [
          {
            begin: "[$][a-fA-F0-9]+"
          },
          hljs5.NUMBER_MODE
        ]
      };
      return {
        name: "Monkey",
        case_insensitive: true,
        keywords: {
          keyword: "public private property continue exit extern new try catch eachin not abstract final select case default const local global field end if then else elseif endif while wend repeat until forever for to step next return module inline throw import",
          built_in: "DebugLog DebugStop Error Print ACos ACosr ASin ASinr ATan ATan2 ATan2r ATanr Abs Abs Ceil Clamp Clamp Cos Cosr Exp Floor Log Max Max Min Min Pow Sgn Sgn Sin Sinr Sqrt Tan Tanr Seed PI HALFPI TWOPI",
          literal: "true false null and or shl shr mod"
        },
        illegal: /\/\*/,
        contains: [
          hljs5.COMMENT("#rem", "#end"),
          hljs5.COMMENT(
            "'",
            "$",
            {
              relevance: 0
            }
          ),
          {
            className: "function",
            beginKeywords: "function method",
            end: "[(=:]|$",
            illegal: /\n/,
            contains: [hljs5.UNDERSCORE_TITLE_MODE]
          },
          {
            className: "class",
            beginKeywords: "class interface",
            end: "$",
            contains: [
              {
                beginKeywords: "extends implements"
              },
              hljs5.UNDERSCORE_TITLE_MODE
            ]
          },
          {
            className: "built_in",
            begin: "\\b(self|super)\\b"
          },
          {
            className: "meta",
            begin: "\\s*#",
            end: "$",
            keywords: {
              "meta-keyword": "if else elseif endif end then"
            }
          },
          {
            className: "meta",
            begin: "^\\s*strict\\b"
          },
          {
            beginKeywords: "alias",
            end: "=",
            contains: [hljs5.UNDERSCORE_TITLE_MODE]
          },
          hljs5.QUOTE_STRING_MODE,
          NUMBER
        ]
      };
    }
    module.exports = monkey;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/moonscript.js
var require_moonscript = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/moonscript.js"(exports, module) {
    init_process_shim();
    function moonscript(hljs5) {
      const KEYWORDS3 = {
        keyword: (
          // Moonscript keywords
          "if then not for in while do return else elseif break continue switch and or unless when class extends super local import export from using"
        ),
        literal: "true false nil",
        built_in: "_G _VERSION assert collectgarbage dofile error getfenv getmetatable ipairs load loadfile loadstring module next pairs pcall print rawequal rawget rawset require select setfenv setmetatable tonumber tostring type unpack xpcall coroutine debug io math os package string table"
      };
      const JS_IDENT_RE = "[A-Za-z$_][0-9A-Za-z$_]*";
      const SUBST = {
        className: "subst",
        begin: /#\{/,
        end: /\}/,
        keywords: KEYWORDS3
      };
      const EXPRESSIONS = [
        hljs5.inherit(
          hljs5.C_NUMBER_MODE,
          {
            starts: {
              end: "(\\s*/)?",
              relevance: 0
            }
          }
        ),
        // a number tries to eat the following slash to prevent treating it as a regexp
        {
          className: "string",
          variants: [
            {
              begin: /'/,
              end: /'/,
              contains: [hljs5.BACKSLASH_ESCAPE]
            },
            {
              begin: /"/,
              end: /"/,
              contains: [
                hljs5.BACKSLASH_ESCAPE,
                SUBST
              ]
            }
          ]
        },
        {
          className: "built_in",
          begin: "@__" + hljs5.IDENT_RE
        },
        {
          begin: "@" + hljs5.IDENT_RE
          // relevance booster on par with CoffeeScript
        },
        {
          begin: hljs5.IDENT_RE + "\\\\" + hljs5.IDENT_RE
          // inst\method
        }
      ];
      SUBST.contains = EXPRESSIONS;
      const TITLE = hljs5.inherit(hljs5.TITLE_MODE, {
        begin: JS_IDENT_RE
      });
      const POSSIBLE_PARAMS_RE = "(\\(.*\\)\\s*)?\\B[-=]>";
      const PARAMS = {
        className: "params",
        begin: "\\([^\\(]",
        returnBegin: true,
        /* We need another contained nameless mode to not have every nested
        pair of parens to be called "params" */
        contains: [
          {
            begin: /\(/,
            end: /\)/,
            keywords: KEYWORDS3,
            contains: ["self"].concat(EXPRESSIONS)
          }
        ]
      };
      return {
        name: "MoonScript",
        aliases: ["moon"],
        keywords: KEYWORDS3,
        illegal: /\/\*/,
        contains: EXPRESSIONS.concat([
          hljs5.COMMENT("--", "$"),
          {
            className: "function",
            // function: -> =>
            begin: "^\\s*" + JS_IDENT_RE + "\\s*=\\s*" + POSSIBLE_PARAMS_RE,
            end: "[-=]>",
            returnBegin: true,
            contains: [
              TITLE,
              PARAMS
            ]
          },
          {
            begin: /[\(,:=]\s*/,
            // anonymous function start
            relevance: 0,
            contains: [
              {
                className: "function",
                begin: POSSIBLE_PARAMS_RE,
                end: "[-=]>",
                returnBegin: true,
                contains: [PARAMS]
              }
            ]
          },
          {
            className: "class",
            beginKeywords: "class",
            end: "$",
            illegal: /[:="\[\]]/,
            contains: [
              {
                beginKeywords: "extends",
                endsWithParent: true,
                illegal: /[:="\[\]]/,
                contains: [TITLE]
              },
              TITLE
            ]
          },
          {
            className: "name",
            // table
            begin: JS_IDENT_RE + ":",
            end: ":",
            returnBegin: true,
            returnEnd: true,
            relevance: 0
          }
        ])
      };
    }
    module.exports = moonscript;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/n1ql.js
var require_n1ql = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/n1ql.js"(exports, module) {
    init_process_shim();
    function n1ql(hljs5) {
      return {
        name: "N1QL",
        case_insensitive: true,
        contains: [
          {
            beginKeywords: "build create index delete drop explain infer|10 insert merge prepare select update upsert|10",
            end: /;/,
            endsWithParent: true,
            keywords: {
              // Taken from http://developer.couchbase.com/documentation/server/current/n1ql/n1ql-language-reference/reservedwords.html
              keyword: "all alter analyze and any array as asc begin between binary boolean break bucket build by call case cast cluster collate collection commit connect continue correlate cover create database dataset datastore declare decrement delete derived desc describe distinct do drop each element else end every except exclude execute exists explain fetch first flatten for force from function grant group gsi having if ignore ilike in include increment index infer inline inner insert intersect into is join key keys keyspace known last left let letting like limit lsm map mapping matched materialized merge minus namespace nest not number object offset on option or order outer over parse partition password path pool prepare primary private privilege procedure public raw realm reduce rename return returning revoke right role rollback satisfies schema select self semi set show some start statistics string system then to transaction trigger truncate under union unique unknown unnest unset update upsert use user using validate value valued values via view when where while with within work xor",
              // Taken from http://developer.couchbase.com/documentation/server/4.5/n1ql/n1ql-language-reference/literals.html
              literal: "true false null missing|5",
              // Taken from http://developer.couchbase.com/documentation/server/4.5/n1ql/n1ql-language-reference/functions.html
              built_in: "array_agg array_append array_concat array_contains array_count array_distinct array_ifnull array_length array_max array_min array_position array_prepend array_put array_range array_remove array_repeat array_replace array_reverse array_sort array_sum avg count max min sum greatest least ifmissing ifmissingornull ifnull missingif nullif ifinf ifnan ifnanorinf naninf neginfif posinfif clock_millis clock_str date_add_millis date_add_str date_diff_millis date_diff_str date_part_millis date_part_str date_trunc_millis date_trunc_str duration_to_str millis str_to_millis millis_to_str millis_to_utc millis_to_zone_name now_millis now_str str_to_duration str_to_utc str_to_zone_name decode_json encode_json encoded_size poly_length base64 base64_encode base64_decode meta uuid abs acos asin atan atan2 ceil cos degrees e exp ln log floor pi power radians random round sign sin sqrt tan trunc object_length object_names object_pairs object_inner_pairs object_values object_inner_values object_add object_put object_remove object_unwrap regexp_contains regexp_like regexp_position regexp_replace contains initcap length lower ltrim position repeat replace rtrim split substr title trim upper isarray isatom isboolean isnumber isobject isstring type toarray toatom toboolean tonumber toobject tostring"
            },
            contains: [
              {
                className: "string",
                begin: "'",
                end: "'",
                contains: [hljs5.BACKSLASH_ESCAPE]
              },
              {
                className: "string",
                begin: '"',
                end: '"',
                contains: [hljs5.BACKSLASH_ESCAPE]
              },
              {
                className: "symbol",
                begin: "`",
                end: "`",
                contains: [hljs5.BACKSLASH_ESCAPE],
                relevance: 2
              },
              hljs5.C_NUMBER_MODE,
              hljs5.C_BLOCK_COMMENT_MODE
            ]
          },
          hljs5.C_BLOCK_COMMENT_MODE
        ]
      };
    }
    module.exports = n1ql;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/nginx.js
var require_nginx = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/nginx.js"(exports, module) {
    init_process_shim();
    function nginx(hljs5) {
      const VAR = {
        className: "variable",
        variants: [
          {
            begin: /\$\d+/
          },
          {
            begin: /\$\{/,
            end: /\}/
          },
          {
            begin: /[$@]/ + hljs5.UNDERSCORE_IDENT_RE
          }
        ]
      };
      const DEFAULT = {
        endsWithParent: true,
        keywords: {
          $pattern: "[a-z/_]+",
          literal: "on off yes no true false none blocked debug info notice warn error crit select break last permanent redirect kqueue rtsig epoll poll /dev/poll"
        },
        relevance: 0,
        illegal: "=>",
        contains: [
          hljs5.HASH_COMMENT_MODE,
          {
            className: "string",
            contains: [
              hljs5.BACKSLASH_ESCAPE,
              VAR
            ],
            variants: [
              {
                begin: /"/,
                end: /"/
              },
              {
                begin: /'/,
                end: /'/
              }
            ]
          },
          // this swallows entire URLs to avoid detecting numbers within
          {
            begin: "([a-z]+):/",
            end: "\\s",
            endsWithParent: true,
            excludeEnd: true,
            contains: [VAR]
          },
          {
            className: "regexp",
            contains: [
              hljs5.BACKSLASH_ESCAPE,
              VAR
            ],
            variants: [
              {
                begin: "\\s\\^",
                end: "\\s|\\{|;",
                returnEnd: true
              },
              // regexp locations (~, ~*)
              {
                begin: "~\\*?\\s+",
                end: "\\s|\\{|;",
                returnEnd: true
              },
              // *.example.com
              {
                begin: "\\*(\\.[a-z\\-]+)+"
              },
              // sub.example.*
              {
                begin: "([a-z\\-]+\\.)+\\*"
              }
            ]
          },
          // IP
          {
            className: "number",
            begin: "\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}(:\\d{1,5})?\\b"
          },
          // units
          {
            className: "number",
            begin: "\\b\\d+[kKmMgGdshdwy]*\\b",
            relevance: 0
          },
          VAR
        ]
      };
      return {
        name: "Nginx config",
        aliases: ["nginxconf"],
        contains: [
          hljs5.HASH_COMMENT_MODE,
          {
            begin: hljs5.UNDERSCORE_IDENT_RE + "\\s+\\{",
            returnBegin: true,
            end: /\{/,
            contains: [
              {
                className: "section",
                begin: hljs5.UNDERSCORE_IDENT_RE
              }
            ],
            relevance: 0
          },
          {
            begin: hljs5.UNDERSCORE_IDENT_RE + "\\s",
            end: ";|\\{",
            returnBegin: true,
            contains: [
              {
                className: "attribute",
                begin: hljs5.UNDERSCORE_IDENT_RE,
                starts: DEFAULT
              }
            ],
            relevance: 0
          }
        ],
        illegal: "[^\\s\\}]"
      };
    }
    module.exports = nginx;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/nim.js
var require_nim = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/nim.js"(exports, module) {
    init_process_shim();
    function nim(hljs5) {
      return {
        name: "Nim",
        keywords: {
          keyword: "addr and as asm bind block break case cast const continue converter discard distinct div do elif else end enum except export finally for from func generic if import in include interface is isnot iterator let macro method mixin mod nil not notin object of or out proc ptr raise ref return shl shr static template try tuple type using var when while with without xor yield",
          literal: "shared guarded stdin stdout stderr result true false",
          built_in: "int int8 int16 int32 int64 uint uint8 uint16 uint32 uint64 float float32 float64 bool char string cstring pointer expr stmt void auto any range array openarray varargs seq set clong culong cchar cschar cshort cint csize clonglong cfloat cdouble clongdouble cuchar cushort cuint culonglong cstringarray semistatic"
        },
        contains: [
          {
            className: "meta",
            // Actually pragma
            begin: /\{\./,
            end: /\.\}/,
            relevance: 10
          },
          {
            className: "string",
            begin: /[a-zA-Z]\w*"/,
            end: /"/,
            contains: [
              {
                begin: /""/
              }
            ]
          },
          {
            className: "string",
            begin: /([a-zA-Z]\w*)?"""/,
            end: /"""/
          },
          hljs5.QUOTE_STRING_MODE,
          {
            className: "type",
            begin: /\b[A-Z]\w+\b/,
            relevance: 0
          },
          {
            className: "number",
            relevance: 0,
            variants: [
              {
                begin: /\b(0[xX][0-9a-fA-F][_0-9a-fA-F]*)('?[iIuU](8|16|32|64))?/
              },
              {
                begin: /\b(0o[0-7][_0-7]*)('?[iIuUfF](8|16|32|64))?/
              },
              {
                begin: /\b(0(b|B)[01][_01]*)('?[iIuUfF](8|16|32|64))?/
              },
              {
                begin: /\b(\d[_\d]*)('?[iIuUfF](8|16|32|64))?/
              }
            ]
          },
          hljs5.HASH_COMMENT_MODE
        ]
      };
    }
    module.exports = nim;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/nix.js
var require_nix = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/nix.js"(exports, module) {
    init_process_shim();
    function nix(hljs5) {
      const NIX_KEYWORDS = {
        keyword: "rec with let in inherit assert if else then",
        literal: "true false or and null",
        built_in: "import abort baseNameOf dirOf isNull builtins map removeAttrs throw toString derivation"
      };
      const ANTIQUOTE = {
        className: "subst",
        begin: /\$\{/,
        end: /\}/,
        keywords: NIX_KEYWORDS
      };
      const ATTRS = {
        begin: /[a-zA-Z0-9-_]+(\s*=)/,
        returnBegin: true,
        relevance: 0,
        contains: [
          {
            className: "attr",
            begin: /\S+/
          }
        ]
      };
      const STRING = {
        className: "string",
        contains: [ANTIQUOTE],
        variants: [
          {
            begin: "''",
            end: "''"
          },
          {
            begin: '"',
            end: '"'
          }
        ]
      };
      const EXPRESSIONS = [
        hljs5.NUMBER_MODE,
        hljs5.HASH_COMMENT_MODE,
        hljs5.C_BLOCK_COMMENT_MODE,
        STRING,
        ATTRS
      ];
      ANTIQUOTE.contains = EXPRESSIONS;
      return {
        name: "Nix",
        aliases: ["nixos"],
        keywords: NIX_KEYWORDS,
        contains: EXPRESSIONS
      };
    }
    module.exports = nix;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/node-repl.js
var require_node_repl = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/node-repl.js"(exports, module) {
    init_process_shim();
    function nodeRepl(hljs5) {
      return {
        name: "Node REPL",
        contains: [
          {
            className: "meta",
            starts: {
              // a space separates the REPL prefix from the actual code
              // this is purely for cleaner HTML output
              end: / |$/,
              starts: {
                end: "$",
                subLanguage: "javascript"
              }
            },
            variants: [
              {
                begin: /^>(?=[ ]|$)/
              },
              {
                begin: /^\.\.\.(?=[ ]|$)/
              }
            ]
          }
        ]
      };
    }
    module.exports = nodeRepl;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/nsis.js
var require_nsis = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/nsis.js"(exports, module) {
    init_process_shim();
    function nsis(hljs5) {
      const CONSTANTS = {
        className: "variable",
        begin: /\$(ADMINTOOLS|APPDATA|CDBURN_AREA|CMDLINE|COMMONFILES32|COMMONFILES64|COMMONFILES|COOKIES|DESKTOP|DOCUMENTS|EXEDIR|EXEFILE|EXEPATH|FAVORITES|FONTS|HISTORY|HWNDPARENT|INSTDIR|INTERNET_CACHE|LANGUAGE|LOCALAPPDATA|MUSIC|NETHOOD|OUTDIR|PICTURES|PLUGINSDIR|PRINTHOOD|PROFILE|PROGRAMFILES32|PROGRAMFILES64|PROGRAMFILES|QUICKLAUNCH|RECENT|RESOURCES_LOCALIZED|RESOURCES|SENDTO|SMPROGRAMS|SMSTARTUP|STARTMENU|SYSDIR|TEMP|TEMPLATES|VIDEOS|WINDIR)/
      };
      const DEFINES = {
        // ${defines}
        className: "variable",
        begin: /\$+\{[\w.:-]+\}/
      };
      const VARIABLES = {
        // $variables
        className: "variable",
        begin: /\$+\w+/,
        illegal: /\(\)\{\}/
      };
      const LANGUAGES = {
        // $(language_strings)
        className: "variable",
        begin: /\$+\([\w^.:-]+\)/
      };
      const PARAMETERS = {
        // command parameters
        className: "params",
        begin: "(ARCHIVE|FILE_ATTRIBUTE_ARCHIVE|FILE_ATTRIBUTE_NORMAL|FILE_ATTRIBUTE_OFFLINE|FILE_ATTRIBUTE_READONLY|FILE_ATTRIBUTE_SYSTEM|FILE_ATTRIBUTE_TEMPORARY|HKCR|HKCU|HKDD|HKEY_CLASSES_ROOT|HKEY_CURRENT_CONFIG|HKEY_CURRENT_USER|HKEY_DYN_DATA|HKEY_LOCAL_MACHINE|HKEY_PERFORMANCE_DATA|HKEY_USERS|HKLM|HKPD|HKU|IDABORT|IDCANCEL|IDIGNORE|IDNO|IDOK|IDRETRY|IDYES|MB_ABORTRETRYIGNORE|MB_DEFBUTTON1|MB_DEFBUTTON2|MB_DEFBUTTON3|MB_DEFBUTTON4|MB_ICONEXCLAMATION|MB_ICONINFORMATION|MB_ICONQUESTION|MB_ICONSTOP|MB_OK|MB_OKCANCEL|MB_RETRYCANCEL|MB_RIGHT|MB_RTLREADING|MB_SETFOREGROUND|MB_TOPMOST|MB_USERICON|MB_YESNO|NORMAL|OFFLINE|READONLY|SHCTX|SHELL_CONTEXT|SYSTEM|TEMPORARY)"
      };
      const COMPILER = {
        // !compiler_flags
        className: "keyword",
        begin: /!(addincludedir|addplugindir|appendfile|cd|define|delfile|echo|else|endif|error|execute|finalize|getdllversion|gettlbversion|if|ifdef|ifmacrodef|ifmacrondef|ifndef|include|insertmacro|macro|macroend|makensis|packhdr|searchparse|searchreplace|system|tempfile|undef|verbose|warning)/
      };
      const METACHARS = {
        // $\n, $\r, $\t, $$
        className: "meta",
        begin: /\$(\\[nrt]|\$)/
      };
      const PLUGINS = {
        // plug::ins
        className: "class",
        begin: /\w+::\w+/
      };
      const STRING = {
        className: "string",
        variants: [
          {
            begin: '"',
            end: '"'
          },
          {
            begin: "'",
            end: "'"
          },
          {
            begin: "`",
            end: "`"
          }
        ],
        illegal: /\n/,
        contains: [
          METACHARS,
          CONSTANTS,
          DEFINES,
          VARIABLES,
          LANGUAGES
        ]
      };
      return {
        name: "NSIS",
        case_insensitive: false,
        keywords: {
          keyword: "Abort AddBrandingImage AddSize AllowRootDirInstall AllowSkipFiles AutoCloseWindow BGFont BGGradient BrandingText BringToFront Call CallInstDLL Caption ChangeUI CheckBitmap ClearErrors CompletedText ComponentText CopyFiles CRCCheck CreateDirectory CreateFont CreateShortCut Delete DeleteINISec DeleteINIStr DeleteRegKey DeleteRegValue DetailPrint DetailsButtonText DirText DirVar DirVerify EnableWindow EnumRegKey EnumRegValue Exch Exec ExecShell ExecShellWait ExecWait ExpandEnvStrings File FileBufSize FileClose FileErrorText FileOpen FileRead FileReadByte FileReadUTF16LE FileReadWord FileWriteUTF16LE FileSeek FileWrite FileWriteByte FileWriteWord FindClose FindFirst FindNext FindWindow FlushINI GetCurInstType GetCurrentAddress GetDlgItem GetDLLVersion GetDLLVersionLocal GetErrorLevel GetFileTime GetFileTimeLocal GetFullPathName GetFunctionAddress GetInstDirError GetKnownFolderPath GetLabelAddress GetTempFileName Goto HideWindow Icon IfAbort IfErrors IfFileExists IfRebootFlag IfRtlLanguage IfShellVarContextAll IfSilent InitPluginsDir InstallButtonText InstallColors InstallDir InstallDirRegKey InstProgressFlags InstType InstTypeGetText InstTypeSetText Int64Cmp Int64CmpU Int64Fmt IntCmp IntCmpU IntFmt IntOp IntPtrCmp IntPtrCmpU IntPtrOp IsWindow LangString LicenseBkColor LicenseData LicenseForceSelection LicenseLangString LicenseText LoadAndSetImage LoadLanguageFile LockWindow LogSet LogText ManifestDPIAware ManifestLongPathAware ManifestMaxVersionTested ManifestSupportedOS MessageBox MiscButtonText Name Nop OutFile Page PageCallbacks PEAddResource PEDllCharacteristics PERemoveResource PESubsysVer Pop Push Quit ReadEnvStr ReadINIStr ReadRegDWORD ReadRegStr Reboot RegDLL Rename RequestExecutionLevel ReserveFile Return RMDir SearchPath SectionGetFlags SectionGetInstTypes SectionGetSize SectionGetText SectionIn SectionSetFlags SectionSetInstTypes SectionSetSize SectionSetText SendMessage SetAutoClose SetBrandingImage SetCompress SetCompressor SetCompressorDictSize SetCtlColors SetCurInstType SetDatablockOptimize SetDateSave SetDetailsPrint SetDetailsView SetErrorLevel SetErrors SetFileAttributes SetFont SetOutPath SetOverwrite SetRebootFlag SetRegView SetShellVarContext SetSilent ShowInstDetails ShowUninstDetails ShowWindow SilentInstall SilentUnInstall Sleep SpaceTexts StrCmp StrCmpS StrCpy StrLen SubCaption Unicode UninstallButtonText UninstallCaption UninstallIcon UninstallSubCaption UninstallText UninstPage UnRegDLL Var VIAddVersionKey VIFileVersion VIProductVersion WindowIcon WriteINIStr WriteRegBin WriteRegDWORD WriteRegExpandStr WriteRegMultiStr WriteRegNone WriteRegStr WriteUninstaller XPStyle",
          literal: "admin all auto both bottom bzip2 colored components current custom directory false force hide highest ifdiff ifnewer instfiles lastused leave left license listonly lzma nevershow none normal notset off on open print right show silent silentlog smooth textonly top true try un.components un.custom un.directory un.instfiles un.license uninstConfirm user Win10 Win7 Win8 WinVista zlib"
        },
        contains: [
          hljs5.HASH_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          hljs5.COMMENT(
            ";",
            "$",
            {
              relevance: 0
            }
          ),
          {
            className: "function",
            beginKeywords: "Function PageEx Section SectionGroup",
            end: "$"
          },
          STRING,
          COMPILER,
          DEFINES,
          VARIABLES,
          LANGUAGES,
          PARAMETERS,
          PLUGINS,
          hljs5.NUMBER_MODE
        ]
      };
    }
    module.exports = nsis;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/objectivec.js
var require_objectivec = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/objectivec.js"(exports, module) {
    init_process_shim();
    function objectivec(hljs5) {
      const API_CLASS = {
        className: "built_in",
        begin: "\\b(AV|CA|CF|CG|CI|CL|CM|CN|CT|MK|MP|MTK|MTL|NS|SCN|SK|UI|WK|XC)\\w+"
      };
      const IDENTIFIER_RE = /[a-zA-Z@][a-zA-Z0-9_]*/;
      const OBJC_KEYWORDS = {
        $pattern: IDENTIFIER_RE,
        keyword: "int float while char export sizeof typedef const struct for union unsigned long volatile static bool mutable if do return goto void enum else break extern asm case short default double register explicit signed typename this switch continue wchar_t inline readonly assign readwrite self @synchronized id typeof nonatomic super unichar IBOutlet IBAction strong weak copy in out inout bycopy byref oneway __strong __weak __block __autoreleasing @private @protected @public @try @property @end @throw @catch @finally @autoreleasepool @synthesize @dynamic @selector @optional @required @encode @package @import @defs @compatibility_alias __bridge __bridge_transfer __bridge_retained __bridge_retain __covariant __contravariant __kindof _Nonnull _Nullable _Null_unspecified __FUNCTION__ __PRETTY_FUNCTION__ __attribute__ getter setter retain unsafe_unretained nonnull nullable null_unspecified null_resettable class instancetype NS_DESIGNATED_INITIALIZER NS_UNAVAILABLE NS_REQUIRES_SUPER NS_RETURNS_INNER_POINTER NS_INLINE NS_AVAILABLE NS_DEPRECATED NS_ENUM NS_OPTIONS NS_SWIFT_UNAVAILABLE NS_ASSUME_NONNULL_BEGIN NS_ASSUME_NONNULL_END NS_REFINED_FOR_SWIFT NS_SWIFT_NAME NS_SWIFT_NOTHROW NS_DURING NS_HANDLER NS_ENDHANDLER NS_VALUERETURN NS_VOIDRETURN",
        literal: "false true FALSE TRUE nil YES NO NULL",
        built_in: "BOOL dispatch_once_t dispatch_queue_t dispatch_sync dispatch_async dispatch_once"
      };
      const CLASS_KEYWORDS = {
        $pattern: IDENTIFIER_RE,
        keyword: "@interface @class @protocol @implementation"
      };
      return {
        name: "Objective-C",
        aliases: [
          "mm",
          "objc",
          "obj-c",
          "obj-c++",
          "objective-c++"
        ],
        keywords: OBJC_KEYWORDS,
        illegal: "</",
        contains: [
          API_CLASS,
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          hljs5.C_NUMBER_MODE,
          hljs5.QUOTE_STRING_MODE,
          hljs5.APOS_STRING_MODE,
          {
            className: "string",
            variants: [
              {
                begin: '@"',
                end: '"',
                illegal: "\\n",
                contains: [hljs5.BACKSLASH_ESCAPE]
              }
            ]
          },
          {
            className: "meta",
            begin: /#\s*[a-z]+\b/,
            end: /$/,
            keywords: {
              "meta-keyword": "if else elif endif define undef warning error line pragma ifdef ifndef include"
            },
            contains: [
              {
                begin: /\\\n/,
                relevance: 0
              },
              hljs5.inherit(hljs5.QUOTE_STRING_MODE, {
                className: "meta-string"
              }),
              {
                className: "meta-string",
                begin: /<.*?>/,
                end: /$/,
                illegal: "\\n"
              },
              hljs5.C_LINE_COMMENT_MODE,
              hljs5.C_BLOCK_COMMENT_MODE
            ]
          },
          {
            className: "class",
            begin: "(" + CLASS_KEYWORDS.keyword.split(" ").join("|") + ")\\b",
            end: /(\{|$)/,
            excludeEnd: true,
            keywords: CLASS_KEYWORDS,
            contains: [hljs5.UNDERSCORE_TITLE_MODE]
          },
          {
            begin: "\\." + hljs5.UNDERSCORE_IDENT_RE,
            relevance: 0
          }
        ]
      };
    }
    module.exports = objectivec;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/ocaml.js
var require_ocaml = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/ocaml.js"(exports, module) {
    init_process_shim();
    function ocaml(hljs5) {
      return {
        name: "OCaml",
        aliases: ["ml"],
        keywords: {
          $pattern: "[a-z_]\\w*!?",
          keyword: "and as assert asr begin class constraint do done downto else end exception external for fun function functor if in include inherit! inherit initializer land lazy let lor lsl lsr lxor match method!|10 method mod module mutable new object of open! open or private rec sig struct then to try type val! val virtual when while with parser value",
          built_in: (
            /* built-in types */
            "array bool bytes char exn|5 float int int32 int64 list lazy_t|5 nativeint|5 string unit in_channel out_channel ref"
          ),
          literal: "true false"
        },
        illegal: /\/\/|>>/,
        contains: [
          {
            className: "literal",
            begin: "\\[(\\|\\|)?\\]|\\(\\)",
            relevance: 0
          },
          hljs5.COMMENT(
            "\\(\\*",
            "\\*\\)",
            {
              contains: ["self"]
            }
          ),
          {
            /* type variable */
            className: "symbol",
            begin: "'[A-Za-z_](?!')[\\w']*"
            /* the grammar is ambiguous on how 'a'b should be interpreted but not the compiler */
          },
          {
            /* polymorphic variant */
            className: "type",
            begin: "`[A-Z][\\w']*"
          },
          {
            /* module or constructor */
            className: "type",
            begin: "\\b[A-Z][\\w']*",
            relevance: 0
          },
          {
            /* don't color identifiers, but safely catch all identifiers with '*/
            begin: "[a-z_]\\w*'[\\w']*",
            relevance: 0
          },
          hljs5.inherit(hljs5.APOS_STRING_MODE, { className: "string", relevance: 0 }),
          hljs5.inherit(hljs5.QUOTE_STRING_MODE, { illegal: null }),
          {
            className: "number",
            begin: "\\b(0[xX][a-fA-F0-9_]+[Lln]?|0[oO][0-7_]+[Lln]?|0[bB][01_]+[Lln]?|[0-9][0-9_]*([Lln]|(\\.[0-9_]*)?([eE][-+]?[0-9_]+)?)?)",
            relevance: 0
          },
          {
            begin: /->/
            // relevance booster
          }
        ]
      };
    }
    module.exports = ocaml;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/openscad.js
var require_openscad = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/openscad.js"(exports, module) {
    init_process_shim();
    function openscad(hljs5) {
      const SPECIAL_VARS = {
        className: "keyword",
        begin: "\\$(f[asn]|t|vp[rtd]|children)"
      };
      const LITERALS3 = {
        className: "literal",
        begin: "false|true|PI|undef"
      };
      const NUMBERS = {
        className: "number",
        begin: "\\b\\d+(\\.\\d+)?(e-?\\d+)?",
        // adds 1e5, 1e-10
        relevance: 0
      };
      const STRING = hljs5.inherit(hljs5.QUOTE_STRING_MODE, {
        illegal: null
      });
      const PREPRO = {
        className: "meta",
        keywords: {
          "meta-keyword": "include use"
        },
        begin: "include|use <",
        end: ">"
      };
      const PARAMS = {
        className: "params",
        begin: "\\(",
        end: "\\)",
        contains: [
          "self",
          NUMBERS,
          STRING,
          SPECIAL_VARS,
          LITERALS3
        ]
      };
      const MODIFIERS = {
        begin: "[*!#%]",
        relevance: 0
      };
      const FUNCTIONS = {
        className: "function",
        beginKeywords: "module function",
        end: /=|\{/,
        contains: [
          PARAMS,
          hljs5.UNDERSCORE_TITLE_MODE
        ]
      };
      return {
        name: "OpenSCAD",
        aliases: ["scad"],
        keywords: {
          keyword: "function module include use for intersection_for if else \\%",
          literal: "false true PI undef",
          built_in: "circle square polygon text sphere cube cylinder polyhedron translate rotate scale resize mirror multmatrix color offset hull minkowski union difference intersection abs sign sin cos tan acos asin atan atan2 floor round ceil ln log pow sqrt exp rands min max concat lookup str chr search version version_num norm cross parent_module echo import import_dxf dxf_linear_extrude linear_extrude rotate_extrude surface projection render children dxf_cross dxf_dim let assign"
        },
        contains: [
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          NUMBERS,
          PREPRO,
          STRING,
          SPECIAL_VARS,
          MODIFIERS,
          FUNCTIONS
        ]
      };
    }
    module.exports = openscad;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/oxygene.js
var require_oxygene = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/oxygene.js"(exports, module) {
    init_process_shim();
    function oxygene(hljs5) {
      const OXYGENE_KEYWORDS = {
        $pattern: /\.?\w+/,
        keyword: "abstract add and array as asc aspect assembly async begin break block by case class concat const copy constructor continue create default delegate desc distinct div do downto dynamic each else empty end ensure enum equals event except exit extension external false final finalize finalizer finally flags for forward from function future global group has if implementation implements implies in index inherited inline interface into invariants is iterator join locked locking loop matching method mod module namespace nested new nil not notify nullable of old on operator or order out override parallel params partial pinned private procedure property protected public queryable raise read readonly record reintroduce remove repeat require result reverse sealed select self sequence set shl shr skip static step soft take then to true try tuple type union unit unsafe until uses using var virtual raises volatile where while with write xor yield await mapped deprecated stdcall cdecl pascal register safecall overload library platform reference packed strict published autoreleasepool selector strong weak unretained"
      };
      const CURLY_COMMENT = hljs5.COMMENT(
        /\{/,
        /\}/,
        {
          relevance: 0
        }
      );
      const PAREN_COMMENT = hljs5.COMMENT(
        "\\(\\*",
        "\\*\\)",
        {
          relevance: 10
        }
      );
      const STRING = {
        className: "string",
        begin: "'",
        end: "'",
        contains: [
          {
            begin: "''"
          }
        ]
      };
      const CHAR_STRING = {
        className: "string",
        begin: "(#\\d+)+"
      };
      const FUNCTION = {
        className: "function",
        beginKeywords: "function constructor destructor procedure method",
        end: "[:;]",
        keywords: "function constructor|10 destructor|10 procedure|10 method|10",
        contains: [
          hljs5.TITLE_MODE,
          {
            className: "params",
            begin: "\\(",
            end: "\\)",
            keywords: OXYGENE_KEYWORDS,
            contains: [
              STRING,
              CHAR_STRING
            ]
          },
          CURLY_COMMENT,
          PAREN_COMMENT
        ]
      };
      return {
        name: "Oxygene",
        case_insensitive: true,
        keywords: OXYGENE_KEYWORDS,
        illegal: '("|\\$[G-Zg-z]|\\/\\*|</|=>|->)',
        contains: [
          CURLY_COMMENT,
          PAREN_COMMENT,
          hljs5.C_LINE_COMMENT_MODE,
          STRING,
          CHAR_STRING,
          hljs5.NUMBER_MODE,
          FUNCTION,
          {
            className: "class",
            begin: "=\\bclass\\b",
            end: "end;",
            keywords: OXYGENE_KEYWORDS,
            contains: [
              STRING,
              CHAR_STRING,
              CURLY_COMMENT,
              PAREN_COMMENT,
              hljs5.C_LINE_COMMENT_MODE,
              FUNCTION
            ]
          }
        ]
      };
    }
    module.exports = oxygene;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/parser3.js
var require_parser3 = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/parser3.js"(exports, module) {
    init_process_shim();
    function parser3(hljs5) {
      const CURLY_SUBCOMMENT = hljs5.COMMENT(
        /\{/,
        /\}/,
        {
          contains: ["self"]
        }
      );
      return {
        name: "Parser3",
        subLanguage: "xml",
        relevance: 0,
        contains: [
          hljs5.COMMENT("^#", "$"),
          hljs5.COMMENT(
            /\^rem\{/,
            /\}/,
            {
              relevance: 10,
              contains: [CURLY_SUBCOMMENT]
            }
          ),
          {
            className: "meta",
            begin: "^@(?:BASE|USE|CLASS|OPTIONS)$",
            relevance: 10
          },
          {
            className: "title",
            begin: "@[\\w\\-]+\\[[\\w^;\\-]*\\](?:\\[[\\w^;\\-]*\\])?(?:.*)$"
          },
          {
            className: "variable",
            begin: /\$\{?[\w\-.:]+\}?/
          },
          {
            className: "keyword",
            begin: /\^[\w\-.:]+/
          },
          {
            className: "number",
            begin: "\\^#[0-9a-fA-F]+"
          },
          hljs5.C_NUMBER_MODE
        ]
      };
    }
    module.exports = parser3;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/pf.js
var require_pf = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/pf.js"(exports, module) {
    init_process_shim();
    function pf(hljs5) {
      const MACRO = {
        className: "variable",
        begin: /\$[\w\d#@][\w\d_]*/
      };
      const TABLE = {
        className: "variable",
        begin: /<(?!\/)/,
        end: />/
      };
      return {
        name: "Packet Filter config",
        aliases: ["pf.conf"],
        keywords: {
          $pattern: /[a-z0-9_<>-]+/,
          built_in: (
            /* block match pass are "actions" in pf.conf(5), the rest are
             * lexically similar top-level commands.
             */
            "block match pass load anchor|5 antispoof|10 set table"
          ),
          keyword: "in out log quick on rdomain inet inet6 proto from port os to route allow-opts divert-packet divert-reply divert-to flags group icmp-type icmp6-type label once probability recieved-on rtable prio queue tos tag tagged user keep fragment for os drop af-to|10 binat-to|10 nat-to|10 rdr-to|10 bitmask least-stats random round-robin source-hash static-port dup-to reply-to route-to parent bandwidth default min max qlimit block-policy debug fingerprints hostid limit loginterface optimization reassemble ruleset-optimization basic none profile skip state-defaults state-policy timeout const counters persist no modulate synproxy state|5 floating if-bound no-sync pflow|10 sloppy source-track global rule max-src-nodes max-src-states max-src-conn max-src-conn-rate overload flush scrub|5 max-mss min-ttl no-df|10 random-id",
          literal: "all any no-route self urpf-failed egress|5 unknown"
        },
        contains: [
          hljs5.HASH_COMMENT_MODE,
          hljs5.NUMBER_MODE,
          hljs5.QUOTE_STRING_MODE,
          MACRO,
          TABLE
        ]
      };
    }
    module.exports = pf;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/pgsql.js
var require_pgsql = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/pgsql.js"(exports, module) {
    init_process_shim();
    function pgsql(hljs5) {
      const COMMENT_MODE = hljs5.COMMENT("--", "$");
      const UNQUOTED_IDENT = "[a-zA-Z_][a-zA-Z_0-9$]*";
      const DOLLAR_STRING = "\\$([a-zA-Z_]?|[a-zA-Z_][a-zA-Z_0-9]*)\\$";
      const LABEL = "<<\\s*" + UNQUOTED_IDENT + "\\s*>>";
      const SQL_KW = (
        // https://www.postgresql.org/docs/11/static/sql-keywords-appendix.html
        // https://www.postgresql.org/docs/11/static/sql-commands.html
        // SQL commands (starting words)
        "ABORT ALTER ANALYZE BEGIN CALL CHECKPOINT|10 CLOSE CLUSTER COMMENT COMMIT COPY CREATE DEALLOCATE DECLARE DELETE DISCARD DO DROP END EXECUTE EXPLAIN FETCH GRANT IMPORT INSERT LISTEN LOAD LOCK MOVE NOTIFY PREPARE REASSIGN|10 REFRESH REINDEX RELEASE RESET REVOKE ROLLBACK SAVEPOINT SECURITY SELECT SET SHOW START TRUNCATE UNLISTEN|10 UPDATE VACUUM|10 VALUES AGGREGATE COLLATION CONVERSION|10 DATABASE DEFAULT PRIVILEGES DOMAIN TRIGGER EXTENSION FOREIGN WRAPPER|10 TABLE FUNCTION GROUP LANGUAGE LARGE OBJECT MATERIALIZED VIEW OPERATOR CLASS FAMILY POLICY PUBLICATION|10 ROLE RULE SCHEMA SEQUENCE SERVER STATISTICS SUBSCRIPTION SYSTEM TABLESPACE CONFIGURATION DICTIONARY PARSER TEMPLATE TYPE USER MAPPING PREPARED ACCESS METHOD CAST AS TRANSFORM TRANSACTION OWNED TO INTO SESSION AUTHORIZATION INDEX PROCEDURE ASSERTION ALL ANALYSE AND ANY ARRAY ASC ASYMMETRIC|10 BOTH CASE CHECK COLLATE COLUMN CONCURRENTLY|10 CONSTRAINT CROSS DEFERRABLE RANGE DESC DISTINCT ELSE EXCEPT FOR FREEZE|10 FROM FULL HAVING ILIKE IN INITIALLY INNER INTERSECT IS ISNULL JOIN LATERAL LEADING LIKE LIMIT NATURAL NOT NOTNULL NULL OFFSET ON ONLY OR ORDER OUTER OVERLAPS PLACING PRIMARY REFERENCES RETURNING SIMILAR SOME SYMMETRIC TABLESAMPLE THEN TRAILING UNION UNIQUE USING VARIADIC|10 VERBOSE WHEN WHERE WINDOW WITH BY RETURNS INOUT OUT SETOF|10 IF STRICT CURRENT CONTINUE OWNER LOCATION OVER PARTITION WITHIN BETWEEN ESCAPE EXTERNAL INVOKER DEFINER WORK RENAME VERSION CONNECTION CONNECT TABLES TEMP TEMPORARY FUNCTIONS SEQUENCES TYPES SCHEMAS OPTION CASCADE RESTRICT ADD ADMIN EXISTS VALID VALIDATE ENABLE DISABLE REPLICA|10 ALWAYS PASSING COLUMNS PATH REF VALUE OVERRIDING IMMUTABLE STABLE VOLATILE BEFORE AFTER EACH ROW PROCEDURAL ROUTINE NO HANDLER VALIDATOR OPTIONS STORAGE OIDS|10 WITHOUT INHERIT DEPENDS CALLED INPUT LEAKPROOF|10 COST ROWS NOWAIT SEARCH UNTIL ENCRYPTED|10 PASSWORD CONFLICT|10 INSTEAD INHERITS CHARACTERISTICS WRITE CURSOR ALSO STATEMENT SHARE EXCLUSIVE INLINE ISOLATION REPEATABLE READ COMMITTED SERIALIZABLE UNCOMMITTED LOCAL GLOBAL SQL PROCEDURES RECURSIVE SNAPSHOT ROLLUP CUBE TRUSTED|10 INCLUDE FOLLOWING PRECEDING UNBOUNDED RANGE GROUPS UNENCRYPTED|10 SYSID FORMAT DELIMITER HEADER QUOTE ENCODING FILTER OFF FORCE_QUOTE FORCE_NOT_NULL FORCE_NULL COSTS BUFFERS TIMING SUMMARY DISABLE_PAGE_SKIPPING RESTART CYCLE GENERATED IDENTITY DEFERRED IMMEDIATE LEVEL LOGGED UNLOGGED OF NOTHING NONE EXCLUDE ATTRIBUTE USAGE ROUTINES TRUE FALSE NAN INFINITY "
      );
      const ROLE_ATTRS = (
        // only those not in keywrods already
        "SUPERUSER NOSUPERUSER CREATEDB NOCREATEDB CREATEROLE NOCREATEROLE INHERIT NOINHERIT LOGIN NOLOGIN REPLICATION NOREPLICATION BYPASSRLS NOBYPASSRLS "
      );
      const PLPGSQL_KW = "ALIAS BEGIN CONSTANT DECLARE END EXCEPTION RETURN PERFORM|10 RAISE GET DIAGNOSTICS STACKED|10 FOREACH LOOP ELSIF EXIT WHILE REVERSE SLICE DEBUG LOG INFO NOTICE WARNING ASSERT OPEN ";
      const TYPES3 = (
        // https://www.postgresql.org/docs/11/static/datatype.html
        "BIGINT INT8 BIGSERIAL SERIAL8 BIT VARYING VARBIT BOOLEAN BOOL BOX BYTEA CHARACTER CHAR VARCHAR CIDR CIRCLE DATE DOUBLE PRECISION FLOAT8 FLOAT INET INTEGER INT INT4 INTERVAL JSON JSONB LINE LSEG|10 MACADDR MACADDR8 MONEY NUMERIC DEC DECIMAL PATH POINT POLYGON REAL FLOAT4 SMALLINT INT2 SMALLSERIAL|10 SERIAL2|10 SERIAL|10 SERIAL4|10 TEXT TIME ZONE TIMETZ|10 TIMESTAMP TIMESTAMPTZ|10 TSQUERY|10 TSVECTOR|10 TXID_SNAPSHOT|10 UUID XML NATIONAL NCHAR INT4RANGE|10 INT8RANGE|10 NUMRANGE|10 TSRANGE|10 TSTZRANGE|10 DATERANGE|10 ANYELEMENT ANYARRAY ANYNONARRAY ANYENUM ANYRANGE CSTRING INTERNAL RECORD PG_DDL_COMMAND VOID UNKNOWN OPAQUE REFCURSOR NAME OID REGPROC|10 REGPROCEDURE|10 REGOPER|10 REGOPERATOR|10 REGCLASS|10 REGTYPE|10 REGROLE|10 REGNAMESPACE|10 REGCONFIG|10 REGDICTIONARY|10 "
      );
      const TYPES_RE = TYPES3.trim().split(" ").map(function(val2) {
        return val2.split("|")[0];
      }).join("|");
      const SQL_BI = "CURRENT_TIME CURRENT_TIMESTAMP CURRENT_USER CURRENT_CATALOG|10 CURRENT_DATE LOCALTIME LOCALTIMESTAMP CURRENT_ROLE|10 CURRENT_SCHEMA|10 SESSION_USER PUBLIC ";
      const PLPGSQL_BI = "FOUND NEW OLD TG_NAME|10 TG_WHEN|10 TG_LEVEL|10 TG_OP|10 TG_RELID|10 TG_RELNAME|10 TG_TABLE_NAME|10 TG_TABLE_SCHEMA|10 TG_NARGS|10 TG_ARGV|10 TG_EVENT|10 TG_TAG|10 ROW_COUNT RESULT_OID|10 PG_CONTEXT|10 RETURNED_SQLSTATE COLUMN_NAME CONSTRAINT_NAME PG_DATATYPE_NAME|10 MESSAGE_TEXT TABLE_NAME SCHEMA_NAME PG_EXCEPTION_DETAIL|10 PG_EXCEPTION_HINT|10 PG_EXCEPTION_CONTEXT|10 ";
      const PLPGSQL_EXCEPTIONS = (
        // exceptions https://www.postgresql.org/docs/current/static/errcodes-appendix.html
        "SQLSTATE SQLERRM|10 SUCCESSFUL_COMPLETION WARNING DYNAMIC_RESULT_SETS_RETURNED IMPLICIT_ZERO_BIT_PADDING NULL_VALUE_ELIMINATED_IN_SET_FUNCTION PRIVILEGE_NOT_GRANTED PRIVILEGE_NOT_REVOKED STRING_DATA_RIGHT_TRUNCATION DEPRECATED_FEATURE NO_DATA NO_ADDITIONAL_DYNAMIC_RESULT_SETS_RETURNED SQL_STATEMENT_NOT_YET_COMPLETE CONNECTION_EXCEPTION CONNECTION_DOES_NOT_EXIST CONNECTION_FAILURE SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION SQLSERVER_REJECTED_ESTABLISHMENT_OF_SQLCONNECTION TRANSACTION_RESOLUTION_UNKNOWN PROTOCOL_VIOLATION TRIGGERED_ACTION_EXCEPTION FEATURE_NOT_SUPPORTED INVALID_TRANSACTION_INITIATION LOCATOR_EXCEPTION INVALID_LOCATOR_SPECIFICATION INVALID_GRANTOR INVALID_GRANT_OPERATION INVALID_ROLE_SPECIFICATION DIAGNOSTICS_EXCEPTION STACKED_DIAGNOSTICS_ACCESSED_WITHOUT_ACTIVE_HANDLER CASE_NOT_FOUND CARDINALITY_VIOLATION DATA_EXCEPTION ARRAY_SUBSCRIPT_ERROR CHARACTER_NOT_IN_REPERTOIRE DATETIME_FIELD_OVERFLOW DIVISION_BY_ZERO ERROR_IN_ASSIGNMENT ESCAPE_CHARACTER_CONFLICT INDICATOR_OVERFLOW INTERVAL_FIELD_OVERFLOW INVALID_ARGUMENT_FOR_LOGARITHM INVALID_ARGUMENT_FOR_NTILE_FUNCTION INVALID_ARGUMENT_FOR_NTH_VALUE_FUNCTION INVALID_ARGUMENT_FOR_POWER_FUNCTION INVALID_ARGUMENT_FOR_WIDTH_BUCKET_FUNCTION INVALID_CHARACTER_VALUE_FOR_CAST INVALID_DATETIME_FORMAT INVALID_ESCAPE_CHARACTER INVALID_ESCAPE_OCTET INVALID_ESCAPE_SEQUENCE NONSTANDARD_USE_OF_ESCAPE_CHARACTER INVALID_INDICATOR_PARAMETER_VALUE INVALID_PARAMETER_VALUE INVALID_REGULAR_EXPRESSION INVALID_ROW_COUNT_IN_LIMIT_CLAUSE INVALID_ROW_COUNT_IN_RESULT_OFFSET_CLAUSE INVALID_TABLESAMPLE_ARGUMENT INVALID_TABLESAMPLE_REPEAT INVALID_TIME_ZONE_DISPLACEMENT_VALUE INVALID_USE_OF_ESCAPE_CHARACTER MOST_SPECIFIC_TYPE_MISMATCH NULL_VALUE_NOT_ALLOWED NULL_VALUE_NO_INDICATOR_PARAMETER NUMERIC_VALUE_OUT_OF_RANGE SEQUENCE_GENERATOR_LIMIT_EXCEEDED STRING_DATA_LENGTH_MISMATCH STRING_DATA_RIGHT_TRUNCATION SUBSTRING_ERROR TRIM_ERROR UNTERMINATED_C_STRING ZERO_LENGTH_CHARACTER_STRING FLOATING_POINT_EXCEPTION INVALID_TEXT_REPRESENTATION INVALID_BINARY_REPRESENTATION BAD_COPY_FILE_FORMAT UNTRANSLATABLE_CHARACTER NOT_AN_XML_DOCUMENT INVALID_XML_DOCUMENT INVALID_XML_CONTENT INVALID_XML_COMMENT INVALID_XML_PROCESSING_INSTRUCTION INTEGRITY_CONSTRAINT_VIOLATION RESTRICT_VIOLATION NOT_NULL_VIOLATION FOREIGN_KEY_VIOLATION UNIQUE_VIOLATION CHECK_VIOLATION EXCLUSION_VIOLATION INVALID_CURSOR_STATE INVALID_TRANSACTION_STATE ACTIVE_SQL_TRANSACTION BRANCH_TRANSACTION_ALREADY_ACTIVE HELD_CURSOR_REQUIRES_SAME_ISOLATION_LEVEL INAPPROPRIATE_ACCESS_MODE_FOR_BRANCH_TRANSACTION INAPPROPRIATE_ISOLATION_LEVEL_FOR_BRANCH_TRANSACTION NO_ACTIVE_SQL_TRANSACTION_FOR_BRANCH_TRANSACTION READ_ONLY_SQL_TRANSACTION SCHEMA_AND_DATA_STATEMENT_MIXING_NOT_SUPPORTED NO_ACTIVE_SQL_TRANSACTION IN_FAILED_SQL_TRANSACTION IDLE_IN_TRANSACTION_SESSION_TIMEOUT INVALID_SQL_STATEMENT_NAME TRIGGERED_DATA_CHANGE_VIOLATION INVALID_AUTHORIZATION_SPECIFICATION INVALID_PASSWORD DEPENDENT_PRIVILEGE_DESCRIPTORS_STILL_EXIST DEPENDENT_OBJECTS_STILL_EXIST INVALID_TRANSACTION_TERMINATION SQL_ROUTINE_EXCEPTION FUNCTION_EXECUTED_NO_RETURN_STATEMENT MODIFYING_SQL_DATA_NOT_PERMITTED PROHIBITED_SQL_STATEMENT_ATTEMPTED READING_SQL_DATA_NOT_PERMITTED INVALID_CURSOR_NAME EXTERNAL_ROUTINE_EXCEPTION CONTAINING_SQL_NOT_PERMITTED MODIFYING_SQL_DATA_NOT_PERMITTED PROHIBITED_SQL_STATEMENT_ATTEMPTED READING_SQL_DATA_NOT_PERMITTED EXTERNAL_ROUTINE_INVOCATION_EXCEPTION INVALID_SQLSTATE_RETURNED NULL_VALUE_NOT_ALLOWED TRIGGER_PROTOCOL_VIOLATED SRF_PROTOCOL_VIOLATED EVENT_TRIGGER_PROTOCOL_VIOLATED SAVEPOINT_EXCEPTION INVALID_SAVEPOINT_SPECIFICATION INVALID_CATALOG_NAME INVALID_SCHEMA_NAME TRANSACTION_ROLLBACK TRANSACTION_INTEGRITY_CONSTRAINT_VIOLATION SERIALIZATION_FAILURE STATEMENT_COMPLETION_UNKNOWN DEADLOCK_DETECTED SYNTAX_ERROR_OR_ACCESS_RULE_VIOLATION SYNTAX_ERROR INSUFFICIENT_PRIVILEGE CANNOT_COERCE GROUPING_ERROR WINDOWING_ERROR INVALID_RECURSION INVALID_FOREIGN_KEY INVALID_NAME NAME_TOO_LONG RESERVED_NAME DATATYPE_MISMATCH INDETERMINATE_DATATYPE COLLATION_MISMATCH INDETERMINATE_COLLATION WRONG_OBJECT_TYPE GENERATED_ALWAYS UNDEFINED_COLUMN UNDEFINED_FUNCTION UNDEFINED_TABLE UNDEFINED_PARAMETER UNDEFINED_OBJECT DUPLICATE_COLUMN DUPLICATE_CURSOR DUPLICATE_DATABASE DUPLICATE_FUNCTION DUPLICATE_PREPARED_STATEMENT DUPLICATE_SCHEMA DUPLICATE_TABLE DUPLICATE_ALIAS DUPLICATE_OBJECT AMBIGUOUS_COLUMN AMBIGUOUS_FUNCTION AMBIGUOUS_PARAMETER AMBIGUOUS_ALIAS INVALID_COLUMN_REFERENCE INVALID_COLUMN_DEFINITION INVALID_CURSOR_DEFINITION INVALID_DATABASE_DEFINITION INVALID_FUNCTION_DEFINITION INVALID_PREPARED_STATEMENT_DEFINITION INVALID_SCHEMA_DEFINITION INVALID_TABLE_DEFINITION INVALID_OBJECT_DEFINITION WITH_CHECK_OPTION_VIOLATION INSUFFICIENT_RESOURCES DISK_FULL OUT_OF_MEMORY TOO_MANY_CONNECTIONS CONFIGURATION_LIMIT_EXCEEDED PROGRAM_LIMIT_EXCEEDED STATEMENT_TOO_COMPLEX TOO_MANY_COLUMNS TOO_MANY_ARGUMENTS OBJECT_NOT_IN_PREREQUISITE_STATE OBJECT_IN_USE CANT_CHANGE_RUNTIME_PARAM LOCK_NOT_AVAILABLE OPERATOR_INTERVENTION QUERY_CANCELED ADMIN_SHUTDOWN CRASH_SHUTDOWN CANNOT_CONNECT_NOW DATABASE_DROPPED SYSTEM_ERROR IO_ERROR UNDEFINED_FILE DUPLICATE_FILE SNAPSHOT_TOO_OLD CONFIG_FILE_ERROR LOCK_FILE_EXISTS FDW_ERROR FDW_COLUMN_NAME_NOT_FOUND FDW_DYNAMIC_PARAMETER_VALUE_NEEDED FDW_FUNCTION_SEQUENCE_ERROR FDW_INCONSISTENT_DESCRIPTOR_INFORMATION FDW_INVALID_ATTRIBUTE_VALUE FDW_INVALID_COLUMN_NAME FDW_INVALID_COLUMN_NUMBER FDW_INVALID_DATA_TYPE FDW_INVALID_DATA_TYPE_DESCRIPTORS FDW_INVALID_DESCRIPTOR_FIELD_IDENTIFIER FDW_INVALID_HANDLE FDW_INVALID_OPTION_INDEX FDW_INVALID_OPTION_NAME FDW_INVALID_STRING_LENGTH_OR_BUFFER_LENGTH FDW_INVALID_STRING_FORMAT FDW_INVALID_USE_OF_NULL_POINTER FDW_TOO_MANY_HANDLES FDW_OUT_OF_MEMORY FDW_NO_SCHEMAS FDW_OPTION_NAME_NOT_FOUND FDW_REPLY_HANDLE FDW_SCHEMA_NOT_FOUND FDW_TABLE_NOT_FOUND FDW_UNABLE_TO_CREATE_EXECUTION FDW_UNABLE_TO_CREATE_REPLY FDW_UNABLE_TO_ESTABLISH_CONNECTION PLPGSQL_ERROR RAISE_EXCEPTION NO_DATA_FOUND TOO_MANY_ROWS ASSERT_FAILURE INTERNAL_ERROR DATA_CORRUPTED INDEX_CORRUPTED "
      );
      const FUNCTIONS = (
        // https://www.postgresql.org/docs/11/static/functions-aggregate.html
        "ARRAY_AGG AVG BIT_AND BIT_OR BOOL_AND BOOL_OR COUNT EVERY JSON_AGG JSONB_AGG JSON_OBJECT_AGG JSONB_OBJECT_AGG MAX MIN MODE STRING_AGG SUM XMLAGG CORR COVAR_POP COVAR_SAMP REGR_AVGX REGR_AVGY REGR_COUNT REGR_INTERCEPT REGR_R2 REGR_SLOPE REGR_SXX REGR_SXY REGR_SYY STDDEV STDDEV_POP STDDEV_SAMP VARIANCE VAR_POP VAR_SAMP PERCENTILE_CONT PERCENTILE_DISC ROW_NUMBER RANK DENSE_RANK PERCENT_RANK CUME_DIST NTILE LAG LEAD FIRST_VALUE LAST_VALUE NTH_VALUE NUM_NONNULLS NUM_NULLS ABS CBRT CEIL CEILING DEGREES DIV EXP FLOOR LN LOG MOD PI POWER RADIANS ROUND SCALE SIGN SQRT TRUNC WIDTH_BUCKET RANDOM SETSEED ACOS ACOSD ASIN ASIND ATAN ATAND ATAN2 ATAN2D COS COSD COT COTD SIN SIND TAN TAND BIT_LENGTH CHAR_LENGTH CHARACTER_LENGTH LOWER OCTET_LENGTH OVERLAY POSITION SUBSTRING TREAT TRIM UPPER ASCII BTRIM CHR CONCAT CONCAT_WS CONVERT CONVERT_FROM CONVERT_TO DECODE ENCODE INITCAP LEFT LENGTH LPAD LTRIM MD5 PARSE_IDENT PG_CLIENT_ENCODING QUOTE_IDENT|10 QUOTE_LITERAL|10 QUOTE_NULLABLE|10 REGEXP_MATCH REGEXP_MATCHES REGEXP_REPLACE REGEXP_SPLIT_TO_ARRAY REGEXP_SPLIT_TO_TABLE REPEAT REPLACE REVERSE RIGHT RPAD RTRIM SPLIT_PART STRPOS SUBSTR TO_ASCII TO_HEX TRANSLATE OCTET_LENGTH GET_BIT GET_BYTE SET_BIT SET_BYTE TO_CHAR TO_DATE TO_NUMBER TO_TIMESTAMP AGE CLOCK_TIMESTAMP|10 DATE_PART DATE_TRUNC ISFINITE JUSTIFY_DAYS JUSTIFY_HOURS JUSTIFY_INTERVAL MAKE_DATE MAKE_INTERVAL|10 MAKE_TIME MAKE_TIMESTAMP|10 MAKE_TIMESTAMPTZ|10 NOW STATEMENT_TIMESTAMP|10 TIMEOFDAY TRANSACTION_TIMESTAMP|10 ENUM_FIRST ENUM_LAST ENUM_RANGE AREA CENTER DIAMETER HEIGHT ISCLOSED ISOPEN NPOINTS PCLOSE POPEN RADIUS WIDTH BOX BOUND_BOX CIRCLE LINE LSEG PATH POLYGON ABBREV BROADCAST HOST HOSTMASK MASKLEN NETMASK NETWORK SET_MASKLEN TEXT INET_SAME_FAMILY INET_MERGE MACADDR8_SET7BIT ARRAY_TO_TSVECTOR GET_CURRENT_TS_CONFIG NUMNODE PLAINTO_TSQUERY PHRASETO_TSQUERY WEBSEARCH_TO_TSQUERY QUERYTREE SETWEIGHT STRIP TO_TSQUERY TO_TSVECTOR JSON_TO_TSVECTOR JSONB_TO_TSVECTOR TS_DELETE TS_FILTER TS_HEADLINE TS_RANK TS_RANK_CD TS_REWRITE TSQUERY_PHRASE TSVECTOR_TO_ARRAY TSVECTOR_UPDATE_TRIGGER TSVECTOR_UPDATE_TRIGGER_COLUMN XMLCOMMENT XMLCONCAT XMLELEMENT XMLFOREST XMLPI XMLROOT XMLEXISTS XML_IS_WELL_FORMED XML_IS_WELL_FORMED_DOCUMENT XML_IS_WELL_FORMED_CONTENT XPATH XPATH_EXISTS XMLTABLE XMLNAMESPACES TABLE_TO_XML TABLE_TO_XMLSCHEMA TABLE_TO_XML_AND_XMLSCHEMA QUERY_TO_XML QUERY_TO_XMLSCHEMA QUERY_TO_XML_AND_XMLSCHEMA CURSOR_TO_XML CURSOR_TO_XMLSCHEMA SCHEMA_TO_XML SCHEMA_TO_XMLSCHEMA SCHEMA_TO_XML_AND_XMLSCHEMA DATABASE_TO_XML DATABASE_TO_XMLSCHEMA DATABASE_TO_XML_AND_XMLSCHEMA XMLATTRIBUTES TO_JSON TO_JSONB ARRAY_TO_JSON ROW_TO_JSON JSON_BUILD_ARRAY JSONB_BUILD_ARRAY JSON_BUILD_OBJECT JSONB_BUILD_OBJECT JSON_OBJECT JSONB_OBJECT JSON_ARRAY_LENGTH JSONB_ARRAY_LENGTH JSON_EACH JSONB_EACH JSON_EACH_TEXT JSONB_EACH_TEXT JSON_EXTRACT_PATH JSONB_EXTRACT_PATH JSON_OBJECT_KEYS JSONB_OBJECT_KEYS JSON_POPULATE_RECORD JSONB_POPULATE_RECORD JSON_POPULATE_RECORDSET JSONB_POPULATE_RECORDSET JSON_ARRAY_ELEMENTS JSONB_ARRAY_ELEMENTS JSON_ARRAY_ELEMENTS_TEXT JSONB_ARRAY_ELEMENTS_TEXT JSON_TYPEOF JSONB_TYPEOF JSON_TO_RECORD JSONB_TO_RECORD JSON_TO_RECORDSET JSONB_TO_RECORDSET JSON_STRIP_NULLS JSONB_STRIP_NULLS JSONB_SET JSONB_INSERT JSONB_PRETTY CURRVAL LASTVAL NEXTVAL SETVAL COALESCE NULLIF GREATEST LEAST ARRAY_APPEND ARRAY_CAT ARRAY_NDIMS ARRAY_DIMS ARRAY_FILL ARRAY_LENGTH ARRAY_LOWER ARRAY_POSITION ARRAY_POSITIONS ARRAY_PREPEND ARRAY_REMOVE ARRAY_REPLACE ARRAY_TO_STRING ARRAY_UPPER CARDINALITY STRING_TO_ARRAY UNNEST ISEMPTY LOWER_INC UPPER_INC LOWER_INF UPPER_INF RANGE_MERGE GENERATE_SERIES GENERATE_SUBSCRIPTS CURRENT_DATABASE CURRENT_QUERY CURRENT_SCHEMA|10 CURRENT_SCHEMAS|10 INET_CLIENT_ADDR INET_CLIENT_PORT INET_SERVER_ADDR INET_SERVER_PORT ROW_SECURITY_ACTIVE FORMAT_TYPE TO_REGCLASS TO_REGPROC TO_REGPROCEDURE TO_REGOPER TO_REGOPERATOR TO_REGTYPE TO_REGNAMESPACE TO_REGROLE COL_DESCRIPTION OBJ_DESCRIPTION SHOBJ_DESCRIPTION TXID_CURRENT TXID_CURRENT_IF_ASSIGNED TXID_CURRENT_SNAPSHOT TXID_SNAPSHOT_XIP TXID_SNAPSHOT_XMAX TXID_SNAPSHOT_XMIN TXID_VISIBLE_IN_SNAPSHOT TXID_STATUS CURRENT_SETTING SET_CONFIG BRIN_SUMMARIZE_NEW_VALUES BRIN_SUMMARIZE_RANGE BRIN_DESUMMARIZE_RANGE GIN_CLEAN_PENDING_LIST SUPPRESS_REDUNDANT_UPDATES_TRIGGER LO_FROM_BYTEA LO_PUT LO_GET LO_CREAT LO_CREATE LO_UNLINK LO_IMPORT LO_EXPORT LOREAD LOWRITE GROUPING CAST "
      );
      const FUNCTIONS_RE = FUNCTIONS.trim().split(" ").map(function(val2) {
        return val2.split("|")[0];
      }).join("|");
      return {
        name: "PostgreSQL",
        aliases: [
          "postgres",
          "postgresql"
        ],
        case_insensitive: true,
        keywords: {
          keyword: SQL_KW + PLPGSQL_KW + ROLE_ATTRS,
          built_in: SQL_BI + PLPGSQL_BI + PLPGSQL_EXCEPTIONS
        },
        // Forbid some cunstructs from other languages to improve autodetect. In fact
        // "[a-z]:" is legal (as part of array slice), but improbabal.
        illegal: /:==|\W\s*\(\*|(^|\s)\$[a-z]|\{\{|[a-z]:\s*$|\.\.\.|TO:|DO:/,
        contains: [
          // special handling of some words, which are reserved only in some contexts
          {
            className: "keyword",
            variants: [
              {
                begin: /\bTEXT\s*SEARCH\b/
              },
              {
                begin: /\b(PRIMARY|FOREIGN|FOR(\s+NO)?)\s+KEY\b/
              },
              {
                begin: /\bPARALLEL\s+(UNSAFE|RESTRICTED|SAFE)\b/
              },
              {
                begin: /\bSTORAGE\s+(PLAIN|EXTERNAL|EXTENDED|MAIN)\b/
              },
              {
                begin: /\bMATCH\s+(FULL|PARTIAL|SIMPLE)\b/
              },
              {
                begin: /\bNULLS\s+(FIRST|LAST)\b/
              },
              {
                begin: /\bEVENT\s+TRIGGER\b/
              },
              {
                begin: /\b(MAPPING|OR)\s+REPLACE\b/
              },
              {
                begin: /\b(FROM|TO)\s+(PROGRAM|STDIN|STDOUT)\b/
              },
              {
                begin: /\b(SHARE|EXCLUSIVE)\s+MODE\b/
              },
              {
                begin: /\b(LEFT|RIGHT)\s+(OUTER\s+)?JOIN\b/
              },
              {
                begin: /\b(FETCH|MOVE)\s+(NEXT|PRIOR|FIRST|LAST|ABSOLUTE|RELATIVE|FORWARD|BACKWARD)\b/
              },
              {
                begin: /\bPRESERVE\s+ROWS\b/
              },
              {
                begin: /\bDISCARD\s+PLANS\b/
              },
              {
                begin: /\bREFERENCING\s+(OLD|NEW)\b/
              },
              {
                begin: /\bSKIP\s+LOCKED\b/
              },
              {
                begin: /\bGROUPING\s+SETS\b/
              },
              {
                begin: /\b(BINARY|INSENSITIVE|SCROLL|NO\s+SCROLL)\s+(CURSOR|FOR)\b/
              },
              {
                begin: /\b(WITH|WITHOUT)\s+HOLD\b/
              },
              {
                begin: /\bWITH\s+(CASCADED|LOCAL)\s+CHECK\s+OPTION\b/
              },
              {
                begin: /\bEXCLUDE\s+(TIES|NO\s+OTHERS)\b/
              },
              {
                begin: /\bFORMAT\s+(TEXT|XML|JSON|YAML)\b/
              },
              {
                begin: /\bSET\s+((SESSION|LOCAL)\s+)?NAMES\b/
              },
              {
                begin: /\bIS\s+(NOT\s+)?UNKNOWN\b/
              },
              {
                begin: /\bSECURITY\s+LABEL\b/
              },
              {
                begin: /\bSTANDALONE\s+(YES|NO|NO\s+VALUE)\b/
              },
              {
                begin: /\bWITH\s+(NO\s+)?DATA\b/
              },
              {
                begin: /\b(FOREIGN|SET)\s+DATA\b/
              },
              {
                begin: /\bSET\s+(CATALOG|CONSTRAINTS)\b/
              },
              {
                begin: /\b(WITH|FOR)\s+ORDINALITY\b/
              },
              {
                begin: /\bIS\s+(NOT\s+)?DOCUMENT\b/
              },
              {
                begin: /\bXML\s+OPTION\s+(DOCUMENT|CONTENT)\b/
              },
              {
                begin: /\b(STRIP|PRESERVE)\s+WHITESPACE\b/
              },
              {
                begin: /\bNO\s+(ACTION|MAXVALUE|MINVALUE)\b/
              },
              {
                begin: /\bPARTITION\s+BY\s+(RANGE|LIST|HASH)\b/
              },
              {
                begin: /\bAT\s+TIME\s+ZONE\b/
              },
              {
                begin: /\bGRANTED\s+BY\b/
              },
              {
                begin: /\bRETURN\s+(QUERY|NEXT)\b/
              },
              {
                begin: /\b(ATTACH|DETACH)\s+PARTITION\b/
              },
              {
                begin: /\bFORCE\s+ROW\s+LEVEL\s+SECURITY\b/
              },
              {
                begin: /\b(INCLUDING|EXCLUDING)\s+(COMMENTS|CONSTRAINTS|DEFAULTS|IDENTITY|INDEXES|STATISTICS|STORAGE|ALL)\b/
              },
              {
                begin: /\bAS\s+(ASSIGNMENT|IMPLICIT|PERMISSIVE|RESTRICTIVE|ENUM|RANGE)\b/
              }
            ]
          },
          // functions named as keywords, followed by '('
          {
            begin: /\b(FORMAT|FAMILY|VERSION)\s*\(/
            // keywords: { built_in: 'FORMAT FAMILY VERSION' }
          },
          // INCLUDE ( ... ) in index_parameters in CREATE TABLE
          {
            begin: /\bINCLUDE\s*\(/,
            keywords: "INCLUDE"
          },
          // not highlight RANGE if not in frame_clause (not 100% correct, but seems satisfactory)
          {
            begin: /\bRANGE(?!\s*(BETWEEN|UNBOUNDED|CURRENT|[-0-9]+))/
          },
          // disable highlighting in commands CREATE AGGREGATE/COLLATION/DATABASE/OPERTOR/TEXT SEARCH .../TYPE
          // and in PL/pgSQL RAISE ... USING
          {
            begin: /\b(VERSION|OWNER|TEMPLATE|TABLESPACE|CONNECTION\s+LIMIT|PROCEDURE|RESTRICT|JOIN|PARSER|COPY|START|END|COLLATION|INPUT|ANALYZE|STORAGE|LIKE|DEFAULT|DELIMITER|ENCODING|COLUMN|CONSTRAINT|TABLE|SCHEMA)\s*=/
          },
          // PG_smth; HAS_some_PRIVILEGE
          {
            // className: 'built_in',
            begin: /\b(PG_\w+?|HAS_[A-Z_]+_PRIVILEGE)\b/,
            relevance: 10
          },
          // extract
          {
            begin: /\bEXTRACT\s*\(/,
            end: /\bFROM\b/,
            returnEnd: true,
            keywords: {
              // built_in: 'EXTRACT',
              type: "CENTURY DAY DECADE DOW DOY EPOCH HOUR ISODOW ISOYEAR MICROSECONDS MILLENNIUM MILLISECONDS MINUTE MONTH QUARTER SECOND TIMEZONE TIMEZONE_HOUR TIMEZONE_MINUTE WEEK YEAR"
            }
          },
          // xmlelement, xmlpi - special NAME
          {
            begin: /\b(XMLELEMENT|XMLPI)\s*\(\s*NAME/,
            keywords: {
              // built_in: 'XMLELEMENT XMLPI',
              keyword: "NAME"
            }
          },
          // xmlparse, xmlserialize
          {
            begin: /\b(XMLPARSE|XMLSERIALIZE)\s*\(\s*(DOCUMENT|CONTENT)/,
            keywords: {
              // built_in: 'XMLPARSE XMLSERIALIZE',
              keyword: "DOCUMENT CONTENT"
            }
          },
          // Sequences. We actually skip everything between CACHE|INCREMENT|MAXVALUE|MINVALUE and
          // nearest following numeric constant. Without with trick we find a lot of "keywords"
          // in 'avrasm' autodetection test...
          {
            beginKeywords: "CACHE INCREMENT MAXVALUE MINVALUE",
            end: hljs5.C_NUMBER_RE,
            returnEnd: true,
            keywords: "BY CACHE INCREMENT MAXVALUE MINVALUE"
          },
          // WITH|WITHOUT TIME ZONE as part of datatype
          {
            className: "type",
            begin: /\b(WITH|WITHOUT)\s+TIME\s+ZONE\b/
          },
          // INTERVAL optional fields
          {
            className: "type",
            begin: /\bINTERVAL\s+(YEAR|MONTH|DAY|HOUR|MINUTE|SECOND)(\s+TO\s+(MONTH|HOUR|MINUTE|SECOND))?\b/
          },
          // Pseudo-types which allowed only as return type
          {
            begin: /\bRETURNS\s+(LANGUAGE_HANDLER|TRIGGER|EVENT_TRIGGER|FDW_HANDLER|INDEX_AM_HANDLER|TSM_HANDLER)\b/,
            keywords: {
              keyword: "RETURNS",
              type: "LANGUAGE_HANDLER TRIGGER EVENT_TRIGGER FDW_HANDLER INDEX_AM_HANDLER TSM_HANDLER"
            }
          },
          // Known functions - only when followed by '('
          {
            begin: "\\b(" + FUNCTIONS_RE + ")\\s*\\("
            // keywords: { built_in: FUNCTIONS }
          },
          // Types
          {
            begin: "\\.(" + TYPES_RE + ")\\b"
            // prevent highlight as type, say, 'oid' in 'pgclass.oid'
          },
          {
            begin: "\\b(" + TYPES_RE + ")\\s+PATH\\b",
            // in XMLTABLE
            keywords: {
              keyword: "PATH",
              // hopefully no one would use PATH type in XMLTABLE...
              type: TYPES3.replace("PATH ", "")
            }
          },
          {
            className: "type",
            begin: "\\b(" + TYPES_RE + ")\\b"
          },
          // Strings, see https://www.postgresql.org/docs/11/static/sql-syntax-lexical.html#SQL-SYNTAX-CONSTANTS
          {
            className: "string",
            begin: "'",
            end: "'",
            contains: [
              {
                begin: "''"
              }
            ]
          },
          {
            className: "string",
            begin: "(e|E|u&|U&)'",
            end: "'",
            contains: [
              {
                begin: "\\\\."
              }
            ],
            relevance: 10
          },
          hljs5.END_SAME_AS_BEGIN({
            begin: DOLLAR_STRING,
            end: DOLLAR_STRING,
            contains: [
              {
                // actually we want them all except SQL; listed are those with known implementations
                // and XML + JSON just in case
                subLanguage: [
                  "pgsql",
                  "perl",
                  "python",
                  "tcl",
                  "r",
                  "lua",
                  "java",
                  "php",
                  "ruby",
                  "bash",
                  "scheme",
                  "xml",
                  "json"
                ],
                endsWithParent: true
              }
            ]
          }),
          // identifiers in quotes
          {
            begin: '"',
            end: '"',
            contains: [
              {
                begin: '""'
              }
            ]
          },
          // numbers
          hljs5.C_NUMBER_MODE,
          // comments
          hljs5.C_BLOCK_COMMENT_MODE,
          COMMENT_MODE,
          // PL/pgSQL staff
          // %ROWTYPE, %TYPE, $n
          {
            className: "meta",
            variants: [
              {
                // %TYPE, %ROWTYPE
                begin: "%(ROW)?TYPE",
                relevance: 10
              },
              {
                // $n
                begin: "\\$\\d+"
              },
              {
                // #compiler option
                begin: "^#\\w",
                end: "$"
              }
            ]
          },
          // <<labeles>>
          {
            className: "symbol",
            begin: LABEL,
            relevance: 10
          }
        ]
      };
    }
    module.exports = pgsql;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/php.js
var require_php = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/php.js"(exports, module) {
    init_process_shim();
    function php(hljs5) {
      const VARIABLE = {
        className: "variable",
        begin: `\\$+[a-zA-Z_\x7F-\xFF][a-zA-Z0-9_\x7F-\xFF]*(?![A-Za-z0-9])(?![$])`
      };
      const PREPROCESSOR = {
        className: "meta",
        variants: [
          { begin: /<\?php/, relevance: 10 },
          // boost for obvious PHP
          { begin: /<\?[=]?/ },
          { begin: /\?>/ }
          // end php tag
        ]
      };
      const SUBST = {
        className: "subst",
        variants: [
          { begin: /\$\w+/ },
          { begin: /\{\$/, end: /\}/ }
        ]
      };
      const SINGLE_QUOTED = hljs5.inherit(hljs5.APOS_STRING_MODE, {
        illegal: null
      });
      const DOUBLE_QUOTED = hljs5.inherit(hljs5.QUOTE_STRING_MODE, {
        illegal: null,
        contains: hljs5.QUOTE_STRING_MODE.contains.concat(SUBST)
      });
      const HEREDOC = hljs5.END_SAME_AS_BEGIN({
        begin: /<<<[ \t]*(\w+)\n/,
        end: /[ \t]*(\w+)\b/,
        contains: hljs5.QUOTE_STRING_MODE.contains.concat(SUBST)
      });
      const STRING = {
        className: "string",
        contains: [hljs5.BACKSLASH_ESCAPE, PREPROCESSOR],
        variants: [
          hljs5.inherit(SINGLE_QUOTED, {
            begin: "b'",
            end: "'"
          }),
          hljs5.inherit(DOUBLE_QUOTED, {
            begin: 'b"',
            end: '"'
          }),
          DOUBLE_QUOTED,
          SINGLE_QUOTED,
          HEREDOC
        ]
      };
      const NUMBER = {
        className: "number",
        variants: [
          { begin: `\\b0b[01]+(?:_[01]+)*\\b` },
          // Binary w/ underscore support
          { begin: `\\b0o[0-7]+(?:_[0-7]+)*\\b` },
          // Octals w/ underscore support
          { begin: `\\b0x[\\da-f]+(?:_[\\da-f]+)*\\b` },
          // Hex w/ underscore support
          // Decimals w/ underscore support, with optional fragments and scientific exponent (e) suffix.
          { begin: `(?:\\b\\d+(?:_\\d+)*(\\.(?:\\d+(?:_\\d+)*))?|\\B\\.\\d+)(?:e[+-]?\\d+)?` }
        ],
        relevance: 0
      };
      const KEYWORDS3 = {
        keyword: (
          // Magic constants:
          // <https://www.php.net/manual/en/language.constants.predefined.php>
          "__CLASS__ __DIR__ __FILE__ __FUNCTION__ __LINE__ __METHOD__ __NAMESPACE__ __TRAIT__ die echo exit include include_once print require require_once array abstract and as binary bool boolean break callable case catch class clone const continue declare default do double else elseif empty enddeclare endfor endforeach endif endswitch endwhile enum eval extends final finally float for foreach from global goto if implements instanceof insteadof int integer interface isset iterable list match|0 mixed new object or private protected public real return string switch throw trait try unset use var void while xor yield"
        ),
        literal: "false null true",
        built_in: (
          // Standard PHP library:
          // <https://www.php.net/manual/en/book.spl.php>
          "Error|0 AppendIterator ArgumentCountError ArithmeticError ArrayIterator ArrayObject AssertionError BadFunctionCallException BadMethodCallException CachingIterator CallbackFilterIterator CompileError Countable DirectoryIterator DivisionByZeroError DomainException EmptyIterator ErrorException Exception FilesystemIterator FilterIterator GlobIterator InfiniteIterator InvalidArgumentException IteratorIterator LengthException LimitIterator LogicException MultipleIterator NoRewindIterator OutOfBoundsException OutOfRangeException OuterIterator OverflowException ParentIterator ParseError RangeException RecursiveArrayIterator RecursiveCachingIterator RecursiveCallbackFilterIterator RecursiveDirectoryIterator RecursiveFilterIterator RecursiveIterator RecursiveIteratorIterator RecursiveRegexIterator RecursiveTreeIterator RegexIterator RuntimeException SeekableIterator SplDoublyLinkedList SplFileInfo SplFileObject SplFixedArray SplHeap SplMaxHeap SplMinHeap SplObjectStorage SplObserver SplObserver SplPriorityQueue SplQueue SplStack SplSubject SplSubject SplTempFileObject TypeError UnderflowException UnexpectedValueException UnhandledMatchError ArrayAccess Closure Generator Iterator IteratorAggregate Serializable Stringable Throwable Traversable WeakReference WeakMap Directory __PHP_Incomplete_Class parent php_user_filter self static stdClass"
        )
      };
      return {
        aliases: ["php3", "php4", "php5", "php6", "php7", "php8"],
        case_insensitive: true,
        keywords: KEYWORDS3,
        contains: [
          hljs5.HASH_COMMENT_MODE,
          hljs5.COMMENT("//", "$", { contains: [PREPROCESSOR] }),
          hljs5.COMMENT(
            "/\\*",
            "\\*/",
            {
              contains: [
                {
                  className: "doctag",
                  begin: "@[A-Za-z]+"
                }
              ]
            }
          ),
          hljs5.COMMENT(
            "__halt_compiler.+?;",
            false,
            {
              endsWithParent: true,
              keywords: "__halt_compiler"
            }
          ),
          PREPROCESSOR,
          {
            className: "keyword",
            begin: /\$this\b/
          },
          VARIABLE,
          {
            // swallow composed identifiers to avoid parsing them as keywords
            begin: /(::|->)+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/
          },
          {
            className: "function",
            relevance: 0,
            beginKeywords: "fn function",
            end: /[;{]/,
            excludeEnd: true,
            illegal: "[$%\\[]",
            contains: [
              {
                beginKeywords: "use"
              },
              hljs5.UNDERSCORE_TITLE_MODE,
              {
                begin: "=>",
                // No markup, just a relevance booster
                endsParent: true
              },
              {
                className: "params",
                begin: "\\(",
                end: "\\)",
                excludeBegin: true,
                excludeEnd: true,
                keywords: KEYWORDS3,
                contains: [
                  "self",
                  VARIABLE,
                  hljs5.C_BLOCK_COMMENT_MODE,
                  STRING,
                  NUMBER
                ]
              }
            ]
          },
          {
            className: "class",
            variants: [
              { beginKeywords: "enum", illegal: /[($"]/ },
              { beginKeywords: "class interface trait", illegal: /[:($"]/ }
            ],
            relevance: 0,
            end: /\{/,
            excludeEnd: true,
            contains: [
              { beginKeywords: "extends implements" },
              hljs5.UNDERSCORE_TITLE_MODE
            ]
          },
          {
            beginKeywords: "namespace",
            relevance: 0,
            end: ";",
            illegal: /[.']/,
            contains: [hljs5.UNDERSCORE_TITLE_MODE]
          },
          {
            beginKeywords: "use",
            relevance: 0,
            end: ";",
            contains: [hljs5.UNDERSCORE_TITLE_MODE]
          },
          STRING,
          NUMBER
        ]
      };
    }
    module.exports = php;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/php-template.js
var require_php_template = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/php-template.js"(exports, module) {
    init_process_shim();
    function phpTemplate(hljs5) {
      return {
        name: "PHP template",
        subLanguage: "xml",
        contains: [
          {
            begin: /<\?(php|=)?/,
            end: /\?>/,
            subLanguage: "php",
            contains: [
              // We don't want the php closing tag ?> to close the PHP block when
              // inside any of the following blocks:
              {
                begin: "/\\*",
                end: "\\*/",
                skip: true
              },
              {
                begin: 'b"',
                end: '"',
                skip: true
              },
              {
                begin: "b'",
                end: "'",
                skip: true
              },
              hljs5.inherit(hljs5.APOS_STRING_MODE, {
                illegal: null,
                className: null,
                contains: null,
                skip: true
              }),
              hljs5.inherit(hljs5.QUOTE_STRING_MODE, {
                illegal: null,
                className: null,
                contains: null,
                skip: true
              })
            ]
          }
        ]
      };
    }
    module.exports = phpTemplate;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/plaintext.js
var require_plaintext = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/plaintext.js"(exports, module) {
    init_process_shim();
    function plaintext(hljs5) {
      return {
        name: "Plain text",
        aliases: [
          "text",
          "txt"
        ],
        disableAutodetect: true
      };
    }
    module.exports = plaintext;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/pony.js
var require_pony = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/pony.js"(exports, module) {
    init_process_shim();
    function pony(hljs5) {
      const KEYWORDS3 = {
        keyword: "actor addressof and as be break class compile_error compile_intrinsic consume continue delegate digestof do else elseif embed end error for fun if ifdef in interface is isnt lambda let match new not object or primitive recover repeat return struct then trait try type until use var where while with xor",
        meta: "iso val tag trn box ref",
        literal: "this false true"
      };
      const TRIPLE_QUOTE_STRING_MODE = {
        className: "string",
        begin: '"""',
        end: '"""',
        relevance: 10
      };
      const QUOTE_STRING_MODE = {
        className: "string",
        begin: '"',
        end: '"',
        contains: [hljs5.BACKSLASH_ESCAPE]
      };
      const SINGLE_QUOTE_CHAR_MODE = {
        className: "string",
        begin: "'",
        end: "'",
        contains: [hljs5.BACKSLASH_ESCAPE],
        relevance: 0
      };
      const TYPE_NAME = {
        className: "type",
        begin: "\\b_?[A-Z][\\w]*",
        relevance: 0
      };
      const PRIMED_NAME = {
        begin: hljs5.IDENT_RE + "'",
        relevance: 0
      };
      const NUMBER_MODE = {
        className: "number",
        begin: "(-?)(\\b0[xX][a-fA-F0-9]+|\\b0[bB][01]+|(\\b\\d+(_\\d+)?(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",
        relevance: 0
      };
      return {
        name: "Pony",
        keywords: KEYWORDS3,
        contains: [
          TYPE_NAME,
          TRIPLE_QUOTE_STRING_MODE,
          QUOTE_STRING_MODE,
          SINGLE_QUOTE_CHAR_MODE,
          PRIMED_NAME,
          NUMBER_MODE,
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE
        ]
      };
    }
    module.exports = pony;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/powershell.js
var require_powershell = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/powershell.js"(exports, module) {
    init_process_shim();
    function powershell(hljs5) {
      const TYPES3 = [
        "string",
        "char",
        "byte",
        "int",
        "long",
        "bool",
        "decimal",
        "single",
        "double",
        "DateTime",
        "xml",
        "array",
        "hashtable",
        "void"
      ];
      const VALID_VERBS = "Add|Clear|Close|Copy|Enter|Exit|Find|Format|Get|Hide|Join|Lock|Move|New|Open|Optimize|Pop|Push|Redo|Remove|Rename|Reset|Resize|Search|Select|Set|Show|Skip|Split|Step|Switch|Undo|Unlock|Watch|Backup|Checkpoint|Compare|Compress|Convert|ConvertFrom|ConvertTo|Dismount|Edit|Expand|Export|Group|Import|Initialize|Limit|Merge|Mount|Out|Publish|Restore|Save|Sync|Unpublish|Update|Approve|Assert|Build|Complete|Confirm|Deny|Deploy|Disable|Enable|Install|Invoke|Register|Request|Restart|Resume|Start|Stop|Submit|Suspend|Uninstall|Unregister|Wait|Debug|Measure|Ping|Repair|Resolve|Test|Trace|Connect|Disconnect|Read|Receive|Send|Write|Block|Grant|Protect|Revoke|Unblock|Unprotect|Use|ForEach|Sort|Tee|Where";
      const COMPARISON_OPERATORS = "-and|-as|-band|-bnot|-bor|-bxor|-casesensitive|-ccontains|-ceq|-cge|-cgt|-cle|-clike|-clt|-cmatch|-cne|-cnotcontains|-cnotlike|-cnotmatch|-contains|-creplace|-csplit|-eq|-exact|-f|-file|-ge|-gt|-icontains|-ieq|-ige|-igt|-ile|-ilike|-ilt|-imatch|-in|-ine|-inotcontains|-inotlike|-inotmatch|-ireplace|-is|-isnot|-isplit|-join|-le|-like|-lt|-match|-ne|-not|-notcontains|-notin|-notlike|-notmatch|-or|-regex|-replace|-shl|-shr|-split|-wildcard|-xor";
      const KEYWORDS3 = {
        $pattern: /-?[A-z\.\-]+\b/,
        keyword: "if else foreach return do while until elseif begin for trap data dynamicparam end break throw param continue finally in switch exit filter try process catch hidden static parameter",
        // "echo" relevance has been set to 0 to avoid auto-detect conflicts with shell transcripts
        built_in: "ac asnp cat cd CFS chdir clc clear clhy cli clp cls clv cnsn compare copy cp cpi cpp curl cvpa dbp del diff dir dnsn ebp echo|0 epal epcsv epsn erase etsn exsn fc fhx fl ft fw gal gbp gc gcb gci gcm gcs gdr gerr ghy gi gin gjb gl gm gmo gp gps gpv group gsn gsnp gsv gtz gu gv gwmi h history icm iex ihy ii ipal ipcsv ipmo ipsn irm ise iwmi iwr kill lp ls man md measure mi mount move mp mv nal ndr ni nmo npssc nsn nv ogv oh popd ps pushd pwd r rbp rcjb rcsn rd rdr ren ri rjb rm rmdir rmo rni rnp rp rsn rsnp rujb rv rvpa rwmi sajb sal saps sasv sbp sc scb select set shcm si sl sleep sls sort sp spjb spps spsv start stz sujb sv swmi tee trcm type wget where wjb write"
        // TODO: 'validate[A-Z]+' can't work in keywords
      };
      const TITLE_NAME_RE = /\w[\w\d]*((-)[\w\d]+)*/;
      const BACKTICK_ESCAPE = {
        begin: "`[\\s\\S]",
        relevance: 0
      };
      const VAR = {
        className: "variable",
        variants: [
          {
            begin: /\$\B/
          },
          {
            className: "keyword",
            begin: /\$this/
          },
          {
            begin: /\$[\w\d][\w\d_:]*/
          }
        ]
      };
      const LITERAL = {
        className: "literal",
        begin: /\$(null|true|false)\b/
      };
      const QUOTE_STRING = {
        className: "string",
        variants: [
          {
            begin: /"/,
            end: /"/
          },
          {
            begin: /@"/,
            end: /^"@/
          }
        ],
        contains: [
          BACKTICK_ESCAPE,
          VAR,
          {
            className: "variable",
            begin: /\$[A-z]/,
            end: /[^A-z]/
          }
        ]
      };
      const APOS_STRING = {
        className: "string",
        variants: [
          {
            begin: /'/,
            end: /'/
          },
          {
            begin: /@'/,
            end: /^'@/
          }
        ]
      };
      const PS_HELPTAGS = {
        className: "doctag",
        variants: [
          /* no paramater help tags */
          {
            begin: /\.(synopsis|description|example|inputs|outputs|notes|link|component|role|functionality)/
          },
          /* one parameter help tags */
          {
            begin: /\.(parameter|forwardhelptargetname|forwardhelpcategory|remotehelprunspace|externalhelp)\s+\S+/
          }
        ]
      };
      const PS_COMMENT = hljs5.inherit(
        hljs5.COMMENT(null, null),
        {
          variants: [
            /* single-line comment */
            {
              begin: /#/,
              end: /$/
            },
            /* multi-line comment */
            {
              begin: /<#/,
              end: /#>/
            }
          ],
          contains: [PS_HELPTAGS]
        }
      );
      const CMDLETS = {
        className: "built_in",
        variants: [
          {
            begin: "(".concat(VALID_VERBS, ")+(-)[\\w\\d]+")
          }
        ]
      };
      const PS_CLASS = {
        className: "class",
        beginKeywords: "class enum",
        end: /\s*[{]/,
        excludeEnd: true,
        relevance: 0,
        contains: [hljs5.TITLE_MODE]
      };
      const PS_FUNCTION = {
        className: "function",
        begin: /function\s+/,
        end: /\s*\{|$/,
        excludeEnd: true,
        returnBegin: true,
        relevance: 0,
        contains: [
          {
            begin: "function",
            relevance: 0,
            className: "keyword"
          },
          {
            className: "title",
            begin: TITLE_NAME_RE,
            relevance: 0
          },
          {
            begin: /\(/,
            end: /\)/,
            className: "params",
            relevance: 0,
            contains: [VAR]
          }
          // CMDLETS
        ]
      };
      const PS_USING = {
        begin: /using\s/,
        end: /$/,
        returnBegin: true,
        contains: [
          QUOTE_STRING,
          APOS_STRING,
          {
            className: "keyword",
            begin: /(using|assembly|command|module|namespace|type)/
          }
        ]
      };
      const PS_ARGUMENTS = {
        variants: [
          // PS literals are pretty verbose so it's a good idea to accent them a bit.
          {
            className: "operator",
            begin: "(".concat(COMPARISON_OPERATORS, ")\\b")
          },
          {
            className: "literal",
            begin: /(-)[\w\d]+/,
            relevance: 0
          }
        ]
      };
      const HASH_SIGNS = {
        className: "selector-tag",
        begin: /@\B/,
        relevance: 0
      };
      const PS_METHODS = {
        className: "function",
        begin: /\[.*\]\s*[\w]+[ ]??\(/,
        end: /$/,
        returnBegin: true,
        relevance: 0,
        contains: [
          {
            className: "keyword",
            begin: "(".concat(
              KEYWORDS3.keyword.toString().replace(
                /\s/g,
                "|"
              ),
              ")\\b"
            ),
            endsParent: true,
            relevance: 0
          },
          hljs5.inherit(hljs5.TITLE_MODE, {
            endsParent: true
          })
        ]
      };
      const GENTLEMANS_SET = [
        // STATIC_MEMBER,
        PS_METHODS,
        PS_COMMENT,
        BACKTICK_ESCAPE,
        hljs5.NUMBER_MODE,
        QUOTE_STRING,
        APOS_STRING,
        // PS_NEW_OBJECT_TYPE,
        CMDLETS,
        VAR,
        LITERAL,
        HASH_SIGNS
      ];
      const PS_TYPE = {
        begin: /\[/,
        end: /\]/,
        excludeBegin: true,
        excludeEnd: true,
        relevance: 0,
        contains: [].concat(
          "self",
          GENTLEMANS_SET,
          {
            begin: "(" + TYPES3.join("|") + ")",
            className: "built_in",
            relevance: 0
          },
          {
            className: "type",
            begin: /[\.\w\d]+/,
            relevance: 0
          }
        )
      };
      PS_METHODS.contains.unshift(PS_TYPE);
      return {
        name: "PowerShell",
        aliases: [
          "ps",
          "ps1"
        ],
        case_insensitive: true,
        keywords: KEYWORDS3,
        contains: GENTLEMANS_SET.concat(
          PS_CLASS,
          PS_FUNCTION,
          PS_USING,
          PS_ARGUMENTS,
          PS_TYPE
        )
      };
    }
    module.exports = powershell;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/processing.js
var require_processing = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/processing.js"(exports, module) {
    init_process_shim();
    function processing(hljs5) {
      return {
        name: "Processing",
        keywords: {
          keyword: "BufferedReader PVector PFont PImage PGraphics HashMap boolean byte char color double float int long String Array FloatDict FloatList IntDict IntList JSONArray JSONObject Object StringDict StringList Table TableRow XML false synchronized int abstract float private char boolean static null if const for true while long throw strictfp finally protected import native final return void enum else break transient new catch instanceof byte super volatile case assert short package default double public try this switch continue throws protected public private",
          literal: "P2D P3D HALF_PI PI QUARTER_PI TAU TWO_PI",
          title: "setup draw",
          built_in: "displayHeight displayWidth mouseY mouseX mousePressed pmouseX pmouseY key keyCode pixels focused frameCount frameRate height width size createGraphics beginDraw createShape loadShape PShape arc ellipse line point quad rect triangle bezier bezierDetail bezierPoint bezierTangent curve curveDetail curvePoint curveTangent curveTightness shape shapeMode beginContour beginShape bezierVertex curveVertex endContour endShape quadraticVertex vertex ellipseMode noSmooth rectMode smooth strokeCap strokeJoin strokeWeight mouseClicked mouseDragged mouseMoved mousePressed mouseReleased mouseWheel keyPressed keyPressedkeyReleased keyTyped print println save saveFrame day hour millis minute month second year background clear colorMode fill noFill noStroke stroke alpha blue brightness color green hue lerpColor red saturation modelX modelY modelZ screenX screenY screenZ ambient emissive shininess specular add createImage beginCamera camera endCamera frustum ortho perspective printCamera printProjection cursor frameRate noCursor exit loop noLoop popStyle pushStyle redraw binary boolean byte char float hex int str unbinary unhex join match matchAll nf nfc nfp nfs split splitTokens trim append arrayCopy concat expand reverse shorten sort splice subset box sphere sphereDetail createInput createReader loadBytes loadJSONArray loadJSONObject loadStrings loadTable loadXML open parseXML saveTable selectFolder selectInput beginRaw beginRecord createOutput createWriter endRaw endRecord PrintWritersaveBytes saveJSONArray saveJSONObject saveStream saveStrings saveXML selectOutput popMatrix printMatrix pushMatrix resetMatrix rotate rotateX rotateY rotateZ scale shearX shearY translate ambientLight directionalLight lightFalloff lights lightSpecular noLights normal pointLight spotLight image imageMode loadImage noTint requestImage tint texture textureMode textureWrap blend copy filter get loadPixels set updatePixels blendMode loadShader PShaderresetShader shader createFont loadFont text textFont textAlign textLeading textMode textSize textWidth textAscent textDescent abs ceil constrain dist exp floor lerp log mag map max min norm pow round sq sqrt acos asin atan atan2 cos degrees radians sin tan noise noiseDetail noiseSeed random randomGaussian randomSeed"
        },
        contains: [
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          hljs5.APOS_STRING_MODE,
          hljs5.QUOTE_STRING_MODE,
          hljs5.C_NUMBER_MODE
        ]
      };
    }
    module.exports = processing;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/profile.js
var require_profile = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/profile.js"(exports, module) {
    init_process_shim();
    function profile(hljs5) {
      return {
        name: "Python profiler",
        contains: [
          hljs5.C_NUMBER_MODE,
          {
            begin: "[a-zA-Z_][\\da-zA-Z_]+\\.[\\da-zA-Z_]{1,3}",
            end: ":",
            excludeEnd: true
          },
          {
            begin: "(ncalls|tottime|cumtime)",
            end: "$",
            keywords: "ncalls tottime|10 cumtime|10 filename",
            relevance: 10
          },
          {
            begin: "function calls",
            end: "$",
            contains: [hljs5.C_NUMBER_MODE],
            relevance: 10
          },
          hljs5.APOS_STRING_MODE,
          hljs5.QUOTE_STRING_MODE,
          {
            className: "string",
            begin: "\\(",
            end: "\\)$",
            excludeBegin: true,
            excludeEnd: true,
            relevance: 0
          }
        ]
      };
    }
    module.exports = profile;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/prolog.js
var require_prolog = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/prolog.js"(exports, module) {
    init_process_shim();
    function prolog(hljs5) {
      const ATOM2 = {
        begin: /[a-z][A-Za-z0-9_]*/,
        relevance: 0
      };
      const VAR = {
        className: "symbol",
        variants: [
          {
            begin: /[A-Z][a-zA-Z0-9_]*/
          },
          {
            begin: /_[A-Za-z0-9_]*/
          }
        ],
        relevance: 0
      };
      const PARENTED = {
        begin: /\(/,
        end: /\)/,
        relevance: 0
      };
      const LIST = {
        begin: /\[/,
        end: /\]/
      };
      const LINE_COMMENT = {
        className: "comment",
        begin: /%/,
        end: /$/,
        contains: [hljs5.PHRASAL_WORDS_MODE]
      };
      const BACKTICK_STRING = {
        className: "string",
        begin: /`/,
        end: /`/,
        contains: [hljs5.BACKSLASH_ESCAPE]
      };
      const CHAR_CODE = {
        className: "string",
        // 0'a etc.
        begin: /0'(\\'|.)/
      };
      const SPACE_CODE = {
        className: "string",
        begin: /0'\\s/
        // 0'\s
      };
      const PRED_OP = {
        // relevance booster
        begin: /:-/
      };
      const inner2 = [
        ATOM2,
        VAR,
        PARENTED,
        PRED_OP,
        LIST,
        LINE_COMMENT,
        hljs5.C_BLOCK_COMMENT_MODE,
        hljs5.QUOTE_STRING_MODE,
        hljs5.APOS_STRING_MODE,
        BACKTICK_STRING,
        CHAR_CODE,
        SPACE_CODE,
        hljs5.C_NUMBER_MODE
      ];
      PARENTED.contains = inner2;
      LIST.contains = inner2;
      return {
        name: "Prolog",
        contains: inner2.concat([
          {
            // relevance booster
            begin: /\.$/
          }
        ])
      };
    }
    module.exports = prolog;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/properties.js
var require_properties2 = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/properties.js"(exports, module) {
    init_process_shim();
    function properties(hljs5) {
      var WS0 = "[ \\t\\f]*";
      var WS1 = "[ \\t\\f]+";
      var EQUAL_DELIM = WS0 + "[:=]" + WS0;
      var WS_DELIM = WS1;
      var DELIM = "(" + EQUAL_DELIM + "|" + WS_DELIM + ")";
      var KEY_ALPHANUM = "([^\\\\\\W:= \\t\\f\\n]|\\\\.)+";
      var KEY_OTHER = "([^\\\\:= \\t\\f\\n]|\\\\.)+";
      var DELIM_AND_VALUE = {
        // skip DELIM
        end: DELIM,
        relevance: 0,
        starts: {
          // value: everything until end of line (again, taking into account backslashes)
          className: "string",
          end: /$/,
          relevance: 0,
          contains: [
            { begin: "\\\\\\\\" },
            { begin: "\\\\\\n" }
          ]
        }
      };
      return {
        name: ".properties",
        case_insensitive: true,
        illegal: /\S/,
        contains: [
          hljs5.COMMENT("^\\s*[!#]", "$"),
          // key: everything until whitespace or = or : (taking into account backslashes)
          // case of a "normal" key
          {
            returnBegin: true,
            variants: [
              { begin: KEY_ALPHANUM + EQUAL_DELIM, relevance: 1 },
              { begin: KEY_ALPHANUM + WS_DELIM, relevance: 0 }
            ],
            contains: [
              {
                className: "attr",
                begin: KEY_ALPHANUM,
                endsParent: true,
                relevance: 0
              }
            ],
            starts: DELIM_AND_VALUE
          },
          // case of key containing non-alphanumeric chars => relevance = 0
          {
            begin: KEY_OTHER + DELIM,
            returnBegin: true,
            relevance: 0,
            contains: [
              {
                className: "meta",
                begin: KEY_OTHER,
                endsParent: true,
                relevance: 0
              }
            ],
            starts: DELIM_AND_VALUE
          },
          // case of an empty key
          {
            className: "attr",
            relevance: 0,
            begin: KEY_OTHER + WS0 + "$"
          }
        ]
      };
    }
    module.exports = properties;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/protobuf.js
var require_protobuf = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/protobuf.js"(exports, module) {
    init_process_shim();
    function protobuf(hljs5) {
      return {
        name: "Protocol Buffers",
        keywords: {
          keyword: "package import option optional required repeated group oneof",
          built_in: "double float int32 int64 uint32 uint64 sint32 sint64 fixed32 fixed64 sfixed32 sfixed64 bool string bytes",
          literal: "true false"
        },
        contains: [
          hljs5.QUOTE_STRING_MODE,
          hljs5.NUMBER_MODE,
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          {
            className: "class",
            beginKeywords: "message enum service",
            end: /\{/,
            illegal: /\n/,
            contains: [
              hljs5.inherit(hljs5.TITLE_MODE, {
                starts: { endsWithParent: true, excludeEnd: true }
                // hack: eating everything after the first title
              })
            ]
          },
          {
            className: "function",
            beginKeywords: "rpc",
            end: /[{;]/,
            excludeEnd: true,
            keywords: "rpc returns"
          },
          {
            // match enum items (relevance)
            // BLAH = ...;
            begin: /^\s*[A-Z_]+(?=\s*=[^\n]+;$)/
          }
        ]
      };
    }
    module.exports = protobuf;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/puppet.js
var require_puppet = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/puppet.js"(exports, module) {
    init_process_shim();
    function puppet(hljs5) {
      const PUPPET_KEYWORDS = {
        keyword: (
          /* language keywords */
          "and case default else elsif false if in import enherits node or true undef unless main settings $string "
        ),
        literal: (
          /* metaparameters */
          "alias audit before loglevel noop require subscribe tag owner ensure group mode name|0 changes context force incl lens load_path onlyif provider returns root show_diff type_check en_address ip_address realname command environment hour monute month monthday special target weekday creates cwd ogoutput refresh refreshonly tries try_sleep umask backup checksum content ctime force ignore links mtime purge recurse recurselimit replace selinux_ignore_defaults selrange selrole seltype seluser source souirce_permissions sourceselect validate_cmd validate_replacement allowdupe attribute_membership auth_membership forcelocal gid ia_load_module members system host_aliases ip allowed_trunk_vlans description device_url duplex encapsulation etherchannel native_vlan speed principals allow_root auth_class auth_type authenticate_user k_of_n mechanisms rule session_owner shared options device fstype enable hasrestart directory present absent link atboot blockdevice device dump pass remounts poller_tag use message withpath adminfile allow_virtual allowcdrom category configfiles flavor install_options instance package_settings platform responsefile status uninstall_options vendor unless_system_user unless_uid binary control flags hasstatus manifest pattern restart running start stop allowdupe auths expiry gid groups home iterations key_membership keys managehome membership password password_max_age password_min_age profile_membership profiles project purge_ssh_keys role_membership roles salt shell uid baseurl cost descr enabled enablegroups exclude failovermethod gpgcheck gpgkey http_caching include includepkgs keepalive metadata_expire metalink mirrorlist priority protect proxy proxy_password proxy_username repo_gpgcheck s3_enabled skip_if_unavailable sslcacert sslclientcert sslclientkey sslverify mounted"
        ),
        built_in: (
          /* core facts */
          "architecture augeasversion blockdevices boardmanufacturer boardproductname boardserialnumber cfkey dhcp_servers domain ec2_ ec2_userdata facterversion filesystems ldom fqdn gid hardwareisa hardwaremodel hostname id|0 interfaces ipaddress ipaddress_ ipaddress6 ipaddress6_ iphostnumber is_virtual kernel kernelmajversion kernelrelease kernelversion kernelrelease kernelversion lsbdistcodename lsbdistdescription lsbdistid lsbdistrelease lsbmajdistrelease lsbminordistrelease lsbrelease macaddress macaddress_ macosx_buildversion macosx_productname macosx_productversion macosx_productverson_major macosx_productversion_minor manufacturer memoryfree memorysize netmask metmask_ network_ operatingsystem operatingsystemmajrelease operatingsystemrelease osfamily partitions path physicalprocessorcount processor processorcount productname ps puppetversion rubysitedir rubyversion selinux selinux_config_mode selinux_config_policy selinux_current_mode selinux_current_mode selinux_enforced selinux_policyversion serialnumber sp_ sshdsakey sshecdsakey sshrsakey swapencrypted swapfree swapsize timezone type uniqueid uptime uptime_days uptime_hours uptime_seconds uuid virtual vlans xendomains zfs_version zonenae zones zpool_version"
        )
      };
      const COMMENT = hljs5.COMMENT("#", "$");
      const IDENT_RE3 = "([A-Za-z_]|::)(\\w|::)*";
      const TITLE = hljs5.inherit(hljs5.TITLE_MODE, {
        begin: IDENT_RE3
      });
      const VARIABLE = {
        className: "variable",
        begin: "\\$" + IDENT_RE3
      };
      const STRING = {
        className: "string",
        contains: [
          hljs5.BACKSLASH_ESCAPE,
          VARIABLE
        ],
        variants: [
          {
            begin: /'/,
            end: /'/
          },
          {
            begin: /"/,
            end: /"/
          }
        ]
      };
      return {
        name: "Puppet",
        aliases: ["pp"],
        contains: [
          COMMENT,
          VARIABLE,
          STRING,
          {
            beginKeywords: "class",
            end: "\\{|;",
            illegal: /=/,
            contains: [
              TITLE,
              COMMENT
            ]
          },
          {
            beginKeywords: "define",
            end: /\{/,
            contains: [
              {
                className: "section",
                begin: hljs5.IDENT_RE,
                endsParent: true
              }
            ]
          },
          {
            begin: hljs5.IDENT_RE + "\\s+\\{",
            returnBegin: true,
            end: /\S/,
            contains: [
              {
                className: "keyword",
                begin: hljs5.IDENT_RE
              },
              {
                begin: /\{/,
                end: /\}/,
                keywords: PUPPET_KEYWORDS,
                relevance: 0,
                contains: [
                  STRING,
                  COMMENT,
                  {
                    begin: "[a-zA-Z_]+\\s*=>",
                    returnBegin: true,
                    end: "=>",
                    contains: [
                      {
                        className: "attr",
                        begin: hljs5.IDENT_RE
                      }
                    ]
                  },
                  {
                    className: "number",
                    begin: "(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b",
                    relevance: 0
                  },
                  VARIABLE
                ]
              }
            ],
            relevance: 0
          }
        ]
      };
    }
    module.exports = puppet;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/purebasic.js
var require_purebasic = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/purebasic.js"(exports, module) {
    init_process_shim();
    function purebasic(hljs5) {
      const STRINGS = {
        // PB IDE color: #0080FF (Azure Radiance)
        className: "string",
        begin: '(~)?"',
        end: '"',
        illegal: "\\n"
      };
      const CONSTANTS = {
        // PB IDE color: #924B72 (Cannon Pink)
        //  "#" + a letter or underscore + letters, digits or underscores + (optional) "$"
        className: "symbol",
        begin: "#[a-zA-Z_]\\w*\\$?"
      };
      return {
        name: "PureBASIC",
        aliases: [
          "pb",
          "pbi"
        ],
        keywords: (
          // PB IDE color: #006666 (Blue Stone) + Bold
          // Keywords from all version of PureBASIC 5.00 upward ...
          "Align And Array As Break CallDebugger Case CompilerCase CompilerDefault CompilerElse CompilerElseIf CompilerEndIf CompilerEndSelect CompilerError CompilerIf CompilerSelect CompilerWarning Continue Data DataSection Debug DebugLevel Declare DeclareC DeclareCDLL DeclareDLL DeclareModule Default Define Dim DisableASM DisableDebugger DisableExplicit Else ElseIf EnableASM EnableDebugger EnableExplicit End EndDataSection EndDeclareModule EndEnumeration EndIf EndImport EndInterface EndMacro EndModule EndProcedure EndSelect EndStructure EndStructureUnion EndWith Enumeration EnumerationBinary Extends FakeReturn For ForEach ForEver Global Gosub Goto If Import ImportC IncludeBinary IncludeFile IncludePath Interface List Macro MacroExpandedCount Map Module NewList NewMap Next Not Or Procedure ProcedureC ProcedureCDLL ProcedureDLL ProcedureReturn Protected Prototype PrototypeC ReDim Read Repeat Restore Return Runtime Select Shared Static Step Structure StructureUnion Swap Threaded To UndefineMacro Until Until  UnuseModule UseModule Wend While With XIncludeFile XOr"
        ),
        contains: [
          // COMMENTS | PB IDE color: #00AAAA (Persian Green)
          hljs5.COMMENT(";", "$", {
            relevance: 0
          }),
          {
            // PROCEDURES DEFINITIONS
            className: "function",
            begin: "\\b(Procedure|Declare)(C|CDLL|DLL)?\\b",
            end: "\\(",
            excludeEnd: true,
            returnBegin: true,
            contains: [
              {
                // PROCEDURE KEYWORDS | PB IDE color: #006666 (Blue Stone) + Bold
                className: "keyword",
                begin: "(Procedure|Declare)(C|CDLL|DLL)?",
                excludeEnd: true
              },
              {
                // PROCEDURE RETURN TYPE SETTING | PB IDE color: #000000 (Black)
                className: "type",
                begin: "\\.\\w*"
                // end: ' ',
              },
              hljs5.UNDERSCORE_TITLE_MODE
              // PROCEDURE NAME | PB IDE color: #006666 (Blue Stone)
            ]
          },
          STRINGS,
          CONSTANTS
        ]
      };
    }
    module.exports = purebasic;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/python.js
var require_python = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/python.js"(exports, module) {
    init_process_shim();
    function source(re2) {
      if (!re2) return null;
      if (typeof re2 === "string") return re2;
      return re2.source;
    }
    function lookahead(re2) {
      return concat("(?=", re2, ")");
    }
    function concat(...args) {
      const joined = args.map((x2) => source(x2)).join("");
      return joined;
    }
    function python2(hljs5) {
      const RESERVED_WORDS = [
        "and",
        "as",
        "assert",
        "async",
        "await",
        "break",
        "class",
        "continue",
        "def",
        "del",
        "elif",
        "else",
        "except",
        "finally",
        "for",
        "from",
        "global",
        "if",
        "import",
        "in",
        "is",
        "lambda",
        "nonlocal|10",
        "not",
        "or",
        "pass",
        "raise",
        "return",
        "try",
        "while",
        "with",
        "yield"
      ];
      const BUILT_INS3 = [
        "__import__",
        "abs",
        "all",
        "any",
        "ascii",
        "bin",
        "bool",
        "breakpoint",
        "bytearray",
        "bytes",
        "callable",
        "chr",
        "classmethod",
        "compile",
        "complex",
        "delattr",
        "dict",
        "dir",
        "divmod",
        "enumerate",
        "eval",
        "exec",
        "filter",
        "float",
        "format",
        "frozenset",
        "getattr",
        "globals",
        "hasattr",
        "hash",
        "help",
        "hex",
        "id",
        "input",
        "int",
        "isinstance",
        "issubclass",
        "iter",
        "len",
        "list",
        "locals",
        "map",
        "max",
        "memoryview",
        "min",
        "next",
        "object",
        "oct",
        "open",
        "ord",
        "pow",
        "print",
        "property",
        "range",
        "repr",
        "reversed",
        "round",
        "set",
        "setattr",
        "slice",
        "sorted",
        "staticmethod",
        "str",
        "sum",
        "super",
        "tuple",
        "type",
        "vars",
        "zip"
      ];
      const LITERALS3 = [
        "__debug__",
        "Ellipsis",
        "False",
        "None",
        "NotImplemented",
        "True"
      ];
      const TYPES3 = [
        "Any",
        "Callable",
        "Coroutine",
        "Dict",
        "List",
        "Literal",
        "Generic",
        "Optional",
        "Sequence",
        "Set",
        "Tuple",
        "Type",
        "Union"
      ];
      const KEYWORDS3 = {
        $pattern: /[A-Za-z]\w+|__\w+__/,
        keyword: RESERVED_WORDS,
        built_in: BUILT_INS3,
        literal: LITERALS3,
        type: TYPES3
      };
      const PROMPT = {
        className: "meta",
        begin: /^(>>>|\.\.\.) /
      };
      const SUBST = {
        className: "subst",
        begin: /\{/,
        end: /\}/,
        keywords: KEYWORDS3,
        illegal: /#/
      };
      const LITERAL_BRACKET = {
        begin: /\{\{/,
        relevance: 0
      };
      const STRING = {
        className: "string",
        contains: [hljs5.BACKSLASH_ESCAPE],
        variants: [
          {
            begin: /([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?'''/,
            end: /'''/,
            contains: [
              hljs5.BACKSLASH_ESCAPE,
              PROMPT
            ],
            relevance: 10
          },
          {
            begin: /([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?"""/,
            end: /"""/,
            contains: [
              hljs5.BACKSLASH_ESCAPE,
              PROMPT
            ],
            relevance: 10
          },
          {
            begin: /([fF][rR]|[rR][fF]|[fF])'''/,
            end: /'''/,
            contains: [
              hljs5.BACKSLASH_ESCAPE,
              PROMPT,
              LITERAL_BRACKET,
              SUBST
            ]
          },
          {
            begin: /([fF][rR]|[rR][fF]|[fF])"""/,
            end: /"""/,
            contains: [
              hljs5.BACKSLASH_ESCAPE,
              PROMPT,
              LITERAL_BRACKET,
              SUBST
            ]
          },
          {
            begin: /([uU]|[rR])'/,
            end: /'/,
            relevance: 10
          },
          {
            begin: /([uU]|[rR])"/,
            end: /"/,
            relevance: 10
          },
          {
            begin: /([bB]|[bB][rR]|[rR][bB])'/,
            end: /'/
          },
          {
            begin: /([bB]|[bB][rR]|[rR][bB])"/,
            end: /"/
          },
          {
            begin: /([fF][rR]|[rR][fF]|[fF])'/,
            end: /'/,
            contains: [
              hljs5.BACKSLASH_ESCAPE,
              LITERAL_BRACKET,
              SUBST
            ]
          },
          {
            begin: /([fF][rR]|[rR][fF]|[fF])"/,
            end: /"/,
            contains: [
              hljs5.BACKSLASH_ESCAPE,
              LITERAL_BRACKET,
              SUBST
            ]
          },
          hljs5.APOS_STRING_MODE,
          hljs5.QUOTE_STRING_MODE
        ]
      };
      const digitpart = "[0-9](_?[0-9])*";
      const pointfloat = `(\\b(${digitpart}))?\\.(${digitpart})|\\b(${digitpart})\\.`;
      const NUMBER = {
        className: "number",
        relevance: 0,
        variants: [
          // exponentfloat, pointfloat
          // https://docs.python.org/3.9/reference/lexical_analysis.html#floating-point-literals
          // optionally imaginary
          // https://docs.python.org/3.9/reference/lexical_analysis.html#imaginary-literals
          // Note: no leading \b because floats can start with a decimal point
          // and we don't want to mishandle e.g. `fn(.5)`,
          // no trailing \b for pointfloat because it can end with a decimal point
          // and we don't want to mishandle e.g. `0..hex()`; this should be safe
          // because both MUST contain a decimal point and so cannot be confused with
          // the interior part of an identifier
          {
            begin: `(\\b(${digitpart})|(${pointfloat}))[eE][+-]?(${digitpart})[jJ]?\\b`
          },
          {
            begin: `(${pointfloat})[jJ]?`
          },
          // decinteger, bininteger, octinteger, hexinteger
          // https://docs.python.org/3.9/reference/lexical_analysis.html#integer-literals
          // optionally "long" in Python 2
          // https://docs.python.org/2.7/reference/lexical_analysis.html#integer-and-long-integer-literals
          // decinteger is optionally imaginary
          // https://docs.python.org/3.9/reference/lexical_analysis.html#imaginary-literals
          {
            begin: "\\b([1-9](_?[0-9])*|0+(_?0)*)[lLjJ]?\\b"
          },
          {
            begin: "\\b0[bB](_?[01])+[lL]?\\b"
          },
          {
            begin: "\\b0[oO](_?[0-7])+[lL]?\\b"
          },
          {
            begin: "\\b0[xX](_?[0-9a-fA-F])+[lL]?\\b"
          },
          // imagnumber (digitpart-based)
          // https://docs.python.org/3.9/reference/lexical_analysis.html#imaginary-literals
          {
            begin: `\\b(${digitpart})[jJ]\\b`
          }
        ]
      };
      const COMMENT_TYPE = {
        className: "comment",
        begin: lookahead(/# type:/),
        end: /$/,
        keywords: KEYWORDS3,
        contains: [
          {
            // prevent keywords from coloring `type`
            begin: /# type:/
          },
          // comment within a datatype comment includes no keywords
          {
            begin: /#/,
            end: /\b\B/,
            endsWithParent: true
          }
        ]
      };
      const PARAMS = {
        className: "params",
        variants: [
          // Exclude params in functions without params
          {
            className: "",
            begin: /\(\s*\)/,
            skip: true
          },
          {
            begin: /\(/,
            end: /\)/,
            excludeBegin: true,
            excludeEnd: true,
            keywords: KEYWORDS3,
            contains: [
              "self",
              PROMPT,
              NUMBER,
              STRING,
              hljs5.HASH_COMMENT_MODE
            ]
          }
        ]
      };
      SUBST.contains = [
        STRING,
        NUMBER,
        PROMPT
      ];
      return {
        name: "Python",
        aliases: [
          "py",
          "gyp",
          "ipython"
        ],
        keywords: KEYWORDS3,
        illegal: /(<\/|->|\?)|=>/,
        contains: [
          PROMPT,
          NUMBER,
          {
            // very common convention
            begin: /\bself\b/
          },
          {
            // eat "if" prior to string so that it won't accidentally be
            // labeled as an f-string
            beginKeywords: "if",
            relevance: 0
          },
          STRING,
          COMMENT_TYPE,
          hljs5.HASH_COMMENT_MODE,
          {
            variants: [
              {
                className: "function",
                beginKeywords: "def"
              },
              {
                className: "class",
                beginKeywords: "class"
              }
            ],
            end: /:/,
            illegal: /[${=;\n,]/,
            contains: [
              hljs5.UNDERSCORE_TITLE_MODE,
              PARAMS,
              {
                begin: /->/,
                endsWithParent: true,
                keywords: KEYWORDS3
              }
            ]
          },
          {
            className: "meta",
            begin: /^[\t ]*@/,
            end: /(?=#)|$/,
            contains: [
              NUMBER,
              PARAMS,
              STRING
            ]
          }
        ]
      };
    }
    module.exports = python2;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/python-repl.js
var require_python_repl = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/python-repl.js"(exports, module) {
    init_process_shim();
    function pythonRepl(hljs5) {
      return {
        aliases: ["pycon"],
        contains: [
          {
            className: "meta",
            starts: {
              // a space separates the REPL prefix from the actual code
              // this is purely for cleaner HTML output
              end: / |$/,
              starts: {
                end: "$",
                subLanguage: "python"
              }
            },
            variants: [
              {
                begin: /^>>>(?=[ ]|$)/
              },
              {
                begin: /^\.\.\.(?=[ ]|$)/
              }
            ]
          }
        ]
      };
    }
    module.exports = pythonRepl;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/q.js
var require_q = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/q.js"(exports, module) {
    init_process_shim();
    function q2(hljs5) {
      const KEYWORDS3 = {
        $pattern: /(`?)[A-Za-z0-9_]+\b/,
        keyword: "do while select delete by update from",
        literal: "0b 1b",
        built_in: "neg not null string reciprocal floor ceiling signum mod xbar xlog and or each scan over prior mmu lsq inv md5 ltime gtime count first var dev med cov cor all any rand sums prds mins maxs fills deltas ratios avgs differ prev next rank reverse iasc idesc asc desc msum mcount mavg mdev xrank mmin mmax xprev rotate distinct group where flip type key til get value attr cut set upsert raze union inter except cross sv vs sublist enlist read0 read1 hopen hclose hdel hsym hcount peach system ltrim rtrim trim lower upper ssr view tables views cols xcols keys xkey xcol xasc xdesc fkeys meta lj aj aj0 ij pj asof uj ww wj wj1 fby xgroup ungroup ej save load rsave rload show csv parse eval min max avg wavg wsum sin cos tan sum",
        type: "`float `double int `timestamp `timespan `datetime `time `boolean `symbol `char `byte `short `long `real `month `date `minute `second `guid"
      };
      return {
        name: "Q",
        aliases: [
          "k",
          "kdb"
        ],
        keywords: KEYWORDS3,
        contains: [
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.QUOTE_STRING_MODE,
          hljs5.C_NUMBER_MODE
        ]
      };
    }
    module.exports = q2;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/qml.js
var require_qml = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/qml.js"(exports, module) {
    init_process_shim();
    function source(re2) {
      if (!re2) return null;
      if (typeof re2 === "string") return re2;
      return re2.source;
    }
    function concat(...args) {
      const joined = args.map((x2) => source(x2)).join("");
      return joined;
    }
    function qml(hljs5) {
      const KEYWORDS3 = {
        keyword: "in of on if for while finally var new function do return void else break catch instanceof with throw case default try this switch continue typeof delete let yield const export super debugger as async await import",
        literal: "true false null undefined NaN Infinity",
        built_in: "eval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Error EvalError InternalError RangeError ReferenceError StopIteration SyntaxError TypeError URIError Number Math Date String RegExp Array Float32Array Float64Array Int16Array Int32Array Int8Array Uint16Array Uint32Array Uint8Array Uint8ClampedArray ArrayBuffer DataView JSON Intl arguments require module console window document Symbol Set Map WeakSet WeakMap Proxy Reflect Behavior bool color coordinate date double enumeration font geocircle georectangle geoshape int list matrix4x4 parent point quaternion real rect size string url variant vector2d vector3d vector4d Promise"
      };
      const QML_IDENT_RE = "[a-zA-Z_][a-zA-Z0-9\\._]*";
      const PROPERTY = {
        className: "keyword",
        begin: "\\bproperty\\b",
        starts: {
          className: "string",
          end: "(:|=|;|,|//|/\\*|$)",
          returnEnd: true
        }
      };
      const SIGNAL = {
        className: "keyword",
        begin: "\\bsignal\\b",
        starts: {
          className: "string",
          end: "(\\(|:|=|;|,|//|/\\*|$)",
          returnEnd: true
        }
      };
      const ID_ID = {
        className: "attribute",
        begin: "\\bid\\s*:",
        starts: {
          className: "string",
          end: QML_IDENT_RE,
          returnEnd: false
        }
      };
      const QML_ATTRIBUTE = {
        begin: QML_IDENT_RE + "\\s*:",
        returnBegin: true,
        contains: [
          {
            className: "attribute",
            begin: QML_IDENT_RE,
            end: "\\s*:",
            excludeEnd: true,
            relevance: 0
          }
        ],
        relevance: 0
      };
      const QML_OBJECT = {
        begin: concat(QML_IDENT_RE, /\s*\{/),
        end: /\{/,
        returnBegin: true,
        relevance: 0,
        contains: [
          hljs5.inherit(hljs5.TITLE_MODE, {
            begin: QML_IDENT_RE
          })
        ]
      };
      return {
        name: "QML",
        aliases: ["qt"],
        case_insensitive: false,
        keywords: KEYWORDS3,
        contains: [
          {
            className: "meta",
            begin: /^\s*['"]use (strict|asm)['"]/
          },
          hljs5.APOS_STRING_MODE,
          hljs5.QUOTE_STRING_MODE,
          {
            // template string
            className: "string",
            begin: "`",
            end: "`",
            contains: [
              hljs5.BACKSLASH_ESCAPE,
              {
                className: "subst",
                begin: "\\$\\{",
                end: "\\}"
              }
            ]
          },
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          {
            className: "number",
            variants: [
              {
                begin: "\\b(0[bB][01]+)"
              },
              {
                begin: "\\b(0[oO][0-7]+)"
              },
              {
                begin: hljs5.C_NUMBER_RE
              }
            ],
            relevance: 0
          },
          {
            // "value" container
            begin: "(" + hljs5.RE_STARTERS_RE + "|\\b(case|return|throw)\\b)\\s*",
            keywords: "return throw case",
            contains: [
              hljs5.C_LINE_COMMENT_MODE,
              hljs5.C_BLOCK_COMMENT_MODE,
              hljs5.REGEXP_MODE,
              {
                // E4X / JSX
                begin: /</,
                end: />\s*[);\]]/,
                relevance: 0,
                subLanguage: "xml"
              }
            ],
            relevance: 0
          },
          SIGNAL,
          PROPERTY,
          {
            className: "function",
            beginKeywords: "function",
            end: /\{/,
            excludeEnd: true,
            contains: [
              hljs5.inherit(hljs5.TITLE_MODE, {
                begin: /[A-Za-z$_][0-9A-Za-z$_]*/
              }),
              {
                className: "params",
                begin: /\(/,
                end: /\)/,
                excludeBegin: true,
                excludeEnd: true,
                contains: [
                  hljs5.C_LINE_COMMENT_MODE,
                  hljs5.C_BLOCK_COMMENT_MODE
                ]
              }
            ],
            illegal: /\[|%/
          },
          {
            // hack: prevents detection of keywords after dots
            begin: "\\." + hljs5.IDENT_RE,
            relevance: 0
          },
          ID_ID,
          QML_ATTRIBUTE,
          QML_OBJECT
        ],
        illegal: /#/
      };
    }
    module.exports = qml;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/r.js
var require_r = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/r.js"(exports, module) {
    init_process_shim();
    function source(re2) {
      if (!re2) return null;
      if (typeof re2 === "string") return re2;
      return re2.source;
    }
    function lookahead(re2) {
      return concat("(?=", re2, ")");
    }
    function concat(...args) {
      const joined = args.map((x2) => source(x2)).join("");
      return joined;
    }
    function r8(hljs5) {
      const IDENT_RE3 = /(?:(?:[a-zA-Z]|\.[._a-zA-Z])[._a-zA-Z0-9]*)|\.(?!\d)/;
      const SIMPLE_IDENT = /[a-zA-Z][a-zA-Z_0-9]*/;
      return {
        name: "R",
        // only in Haskell, not R
        illegal: /->/,
        keywords: {
          $pattern: IDENT_RE3,
          keyword: "function if in break next repeat else for while",
          literal: "NULL NA TRUE FALSE Inf NaN NA_integer_|10 NA_real_|10 NA_character_|10 NA_complex_|10",
          built_in: (
            // Builtin constants
            "LETTERS letters month.abb month.name pi T F abs acos acosh all any anyNA Arg as.call as.character as.complex as.double as.environment as.integer as.logical as.null.default as.numeric as.raw asin asinh atan atanh attr attributes baseenv browser c call ceiling class Conj cos cosh cospi cummax cummin cumprod cumsum digamma dim dimnames emptyenv exp expression floor forceAndCall gamma gc.time globalenv Im interactive invisible is.array is.atomic is.call is.character is.complex is.double is.environment is.expression is.finite is.function is.infinite is.integer is.language is.list is.logical is.matrix is.na is.name is.nan is.null is.numeric is.object is.pairlist is.raw is.recursive is.single is.symbol lazyLoadDBfetch length lgamma list log max min missing Mod names nargs nzchar oldClass on.exit pos.to.env proc.time prod quote range Re rep retracemem return round seq_along seq_len seq.int sign signif sin sinh sinpi sqrt standardGeneric substitute sum switch tan tanh tanpi tracemem trigamma trunc unclass untracemem UseMethod xtfrm"
          )
        },
        compilerExtensions: [
          // allow beforeMatch to act as a "qualifier" for the match
          // the full match begin must be [beforeMatch][begin]
          (mode, parent) => {
            if (!mode.beforeMatch) return;
            if (mode.starts) throw new Error("beforeMatch cannot be used with starts");
            const originalMode = Object.assign({}, mode);
            Object.keys(mode).forEach((key) => {
              delete mode[key];
            });
            mode.begin = concat(originalMode.beforeMatch, lookahead(originalMode.begin));
            mode.starts = {
              relevance: 0,
              contains: [
                Object.assign(originalMode, { endsParent: true })
              ]
            };
            mode.relevance = 0;
            delete originalMode.beforeMatch;
          }
        ],
        contains: [
          // Roxygen comments
          hljs5.COMMENT(
            /#'/,
            /$/,
            {
              contains: [
                {
                  // Handle `@examples` separately to cause all subsequent code
                  // until the next `@`-tag on its own line to be kept as-is,
                  // preventing highlighting. This code is example R code, so nested
                  // doctags shouldn’t be treated as such. See
                  // `test/markup/r/roxygen.txt` for an example.
                  className: "doctag",
                  begin: "@examples",
                  starts: {
                    contains: [
                      { begin: /\n/ },
                      {
                        begin: /#'\s*(?=@[a-zA-Z]+)/,
                        endsParent: true
                      },
                      {
                        begin: /#'/,
                        end: /$/,
                        excludeBegin: true
                      }
                    ]
                  }
                },
                {
                  // Handle `@param` to highlight the parameter name following
                  // after.
                  className: "doctag",
                  begin: "@param",
                  end: /$/,
                  contains: [
                    {
                      className: "variable",
                      variants: [
                        { begin: IDENT_RE3 },
                        { begin: /`(?:\\.|[^`\\])+`/ }
                      ],
                      endsParent: true
                    }
                  ]
                },
                {
                  className: "doctag",
                  begin: /@[a-zA-Z]+/
                },
                {
                  className: "meta-keyword",
                  begin: /\\[a-zA-Z]+/
                }
              ]
            }
          ),
          hljs5.HASH_COMMENT_MODE,
          {
            className: "string",
            contains: [hljs5.BACKSLASH_ESCAPE],
            variants: [
              hljs5.END_SAME_AS_BEGIN({ begin: /[rR]"(-*)\(/, end: /\)(-*)"/ }),
              hljs5.END_SAME_AS_BEGIN({ begin: /[rR]"(-*)\{/, end: /\}(-*)"/ }),
              hljs5.END_SAME_AS_BEGIN({ begin: /[rR]"(-*)\[/, end: /\](-*)"/ }),
              hljs5.END_SAME_AS_BEGIN({ begin: /[rR]'(-*)\(/, end: /\)(-*)'/ }),
              hljs5.END_SAME_AS_BEGIN({ begin: /[rR]'(-*)\{/, end: /\}(-*)'/ }),
              hljs5.END_SAME_AS_BEGIN({ begin: /[rR]'(-*)\[/, end: /\](-*)'/ }),
              { begin: '"', end: '"', relevance: 0 },
              { begin: "'", end: "'", relevance: 0 }
            ]
          },
          {
            className: "number",
            relevance: 0,
            beforeMatch: /([^a-zA-Z0-9._])/,
            // not part of an identifier
            variants: [
              // TODO: replace with negative look-behind when available
              // { begin: /(?<![a-zA-Z0-9._])0[xX][0-9a-fA-F]+\.[0-9a-fA-F]*[pP][+-]?\d+i?/ },
              // { begin: /(?<![a-zA-Z0-9._])0[xX][0-9a-fA-F]+([pP][+-]?\d+)?[Li]?/ },
              // { begin: /(?<![a-zA-Z0-9._])(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?[Li]?/ }
              {
                // Special case: only hexadecimal binary powers can contain fractions.
                match: /0[xX][0-9a-fA-F]+\.[0-9a-fA-F]*[pP][+-]?\d+i?/
              },
              {
                match: /0[xX][0-9a-fA-F]+([pP][+-]?\d+)?[Li]?/
              },
              {
                match: /(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?[Li]?/
              }
            ]
          },
          {
            // infix operator
            begin: "%",
            end: "%"
          },
          // relevance boost for assignment
          {
            begin: concat(SIMPLE_IDENT, "\\s+<-\\s+")
          },
          {
            // escaped identifier
            begin: "`",
            end: "`",
            contains: [
              { begin: /\\./ }
            ]
          }
        ]
      };
    }
    module.exports = r8;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/reasonml.js
var require_reasonml = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/reasonml.js"(exports, module) {
    init_process_shim();
    function reasonml(hljs5) {
      function orReValues(ops) {
        return ops.map(function(op2) {
          return op2.split("").map(function(char) {
            return "\\" + char;
          }).join("");
        }).join("|");
      }
      const RE_IDENT = "~?[a-z$_][0-9a-zA-Z$_]*";
      const RE_MODULE_IDENT = "`?[A-Z$_][0-9a-zA-Z$_]*";
      const RE_PARAM_TYPEPARAM = "'?[a-z$_][0-9a-z$_]*";
      const RE_PARAM_TYPE = "\\s*:\\s*[a-z$_][0-9a-z$_]*(\\(\\s*(" + RE_PARAM_TYPEPARAM + "\\s*(," + RE_PARAM_TYPEPARAM + "\\s*)*)?\\))?";
      const RE_PARAM = RE_IDENT + "(" + RE_PARAM_TYPE + "){0,2}";
      const RE_OPERATOR = "(" + orReValues([
        "||",
        "++",
        "**",
        "+.",
        "*",
        "/",
        "*.",
        "/.",
        "..."
      ]) + "|\\|>|&&|==|===)";
      const RE_OPERATOR_SPACED = "\\s+" + RE_OPERATOR + "\\s+";
      const KEYWORDS3 = {
        keyword: "and as asr assert begin class constraint do done downto else end exception external for fun function functor if in include inherit initializer land lazy let lor lsl lsr lxor match method mod module mutable new nonrec object of open or private rec sig struct then to try type val virtual when while with",
        built_in: "array bool bytes char exn|5 float int int32 int64 list lazy_t|5 nativeint|5 ref string unit ",
        literal: "true false"
      };
      const RE_NUMBER = "\\b(0[xX][a-fA-F0-9_]+[Lln]?|0[oO][0-7_]+[Lln]?|0[bB][01_]+[Lln]?|[0-9][0-9_]*([Lln]|(\\.[0-9_]*)?([eE][-+]?[0-9_]+)?)?)";
      const NUMBER_MODE = {
        className: "number",
        relevance: 0,
        variants: [
          {
            begin: RE_NUMBER
          },
          {
            begin: "\\(-" + RE_NUMBER + "\\)"
          }
        ]
      };
      const OPERATOR_MODE = {
        className: "operator",
        relevance: 0,
        begin: RE_OPERATOR
      };
      const LIST_CONTENTS_MODES = [
        {
          className: "identifier",
          relevance: 0,
          begin: RE_IDENT
        },
        OPERATOR_MODE,
        NUMBER_MODE
      ];
      const MODULE_ACCESS_CONTENTS = [
        hljs5.QUOTE_STRING_MODE,
        OPERATOR_MODE,
        {
          className: "module",
          begin: "\\b" + RE_MODULE_IDENT,
          returnBegin: true,
          end: ".",
          contains: [
            {
              className: "identifier",
              begin: RE_MODULE_IDENT,
              relevance: 0
            }
          ]
        }
      ];
      const PARAMS_CONTENTS = [
        {
          className: "module",
          begin: "\\b" + RE_MODULE_IDENT,
          returnBegin: true,
          end: ".",
          relevance: 0,
          contains: [
            {
              className: "identifier",
              begin: RE_MODULE_IDENT,
              relevance: 0
            }
          ]
        }
      ];
      const PARAMS_MODE = {
        begin: RE_IDENT,
        end: "(,|\\n|\\))",
        relevance: 0,
        contains: [
          OPERATOR_MODE,
          {
            className: "typing",
            begin: ":",
            end: "(,|\\n)",
            returnBegin: true,
            relevance: 0,
            contains: PARAMS_CONTENTS
          }
        ]
      };
      const FUNCTION_BLOCK_MODE = {
        className: "function",
        relevance: 0,
        keywords: KEYWORDS3,
        variants: [
          {
            begin: "\\s(\\(\\.?.*?\\)|" + RE_IDENT + ")\\s*=>",
            end: "\\s*=>",
            returnBegin: true,
            relevance: 0,
            contains: [
              {
                className: "params",
                variants: [
                  {
                    begin: RE_IDENT
                  },
                  {
                    begin: RE_PARAM
                  },
                  {
                    begin: /\(\s*\)/
                  }
                ]
              }
            ]
          },
          {
            begin: "\\s\\(\\.?[^;\\|]*\\)\\s*=>",
            end: "\\s=>",
            returnBegin: true,
            relevance: 0,
            contains: [
              {
                className: "params",
                relevance: 0,
                variants: [PARAMS_MODE]
              }
            ]
          },
          {
            begin: "\\(\\.\\s" + RE_IDENT + "\\)\\s*=>"
          }
        ]
      };
      MODULE_ACCESS_CONTENTS.push(FUNCTION_BLOCK_MODE);
      const CONSTRUCTOR_MODE = {
        className: "constructor",
        begin: RE_MODULE_IDENT + "\\(",
        end: "\\)",
        illegal: "\\n",
        keywords: KEYWORDS3,
        contains: [
          hljs5.QUOTE_STRING_MODE,
          OPERATOR_MODE,
          {
            className: "params",
            begin: "\\b" + RE_IDENT
          }
        ]
      };
      const PATTERN_MATCH_BLOCK_MODE = {
        className: "pattern-match",
        begin: "\\|",
        returnBegin: true,
        keywords: KEYWORDS3,
        end: "=>",
        relevance: 0,
        contains: [
          CONSTRUCTOR_MODE,
          OPERATOR_MODE,
          {
            relevance: 0,
            className: "constructor",
            begin: RE_MODULE_IDENT
          }
        ]
      };
      const MODULE_ACCESS_MODE = {
        className: "module-access",
        keywords: KEYWORDS3,
        returnBegin: true,
        variants: [
          {
            begin: "\\b(" + RE_MODULE_IDENT + "\\.)+" + RE_IDENT
          },
          {
            begin: "\\b(" + RE_MODULE_IDENT + "\\.)+\\(",
            end: "\\)",
            returnBegin: true,
            contains: [
              FUNCTION_BLOCK_MODE,
              {
                begin: "\\(",
                end: "\\)",
                skip: true
              }
            ].concat(MODULE_ACCESS_CONTENTS)
          },
          {
            begin: "\\b(" + RE_MODULE_IDENT + "\\.)+\\{",
            end: /\}/
          }
        ],
        contains: MODULE_ACCESS_CONTENTS
      };
      PARAMS_CONTENTS.push(MODULE_ACCESS_MODE);
      return {
        name: "ReasonML",
        aliases: ["re"],
        keywords: KEYWORDS3,
        illegal: "(:-|:=|\\$\\{|\\+=)",
        contains: [
          hljs5.COMMENT("/\\*", "\\*/", {
            illegal: "^(#,\\/\\/)"
          }),
          {
            className: "character",
            begin: "'(\\\\[^']+|[^'])'",
            illegal: "\\n",
            relevance: 0
          },
          hljs5.QUOTE_STRING_MODE,
          {
            className: "literal",
            begin: "\\(\\)",
            relevance: 0
          },
          {
            className: "literal",
            begin: "\\[\\|",
            end: "\\|\\]",
            relevance: 0,
            contains: LIST_CONTENTS_MODES
          },
          {
            className: "literal",
            begin: "\\[",
            end: "\\]",
            relevance: 0,
            contains: LIST_CONTENTS_MODES
          },
          CONSTRUCTOR_MODE,
          {
            className: "operator",
            begin: RE_OPERATOR_SPACED,
            illegal: "-->",
            relevance: 0
          },
          NUMBER_MODE,
          hljs5.C_LINE_COMMENT_MODE,
          PATTERN_MATCH_BLOCK_MODE,
          FUNCTION_BLOCK_MODE,
          {
            className: "module-def",
            begin: "\\bmodule\\s+" + RE_IDENT + "\\s+" + RE_MODULE_IDENT + "\\s+=\\s+\\{",
            end: /\}/,
            returnBegin: true,
            keywords: KEYWORDS3,
            relevance: 0,
            contains: [
              {
                className: "module",
                relevance: 0,
                begin: RE_MODULE_IDENT
              },
              {
                begin: /\{/,
                end: /\}/,
                skip: true
              }
            ].concat(MODULE_ACCESS_CONTENTS)
          },
          MODULE_ACCESS_MODE
        ]
      };
    }
    module.exports = reasonml;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/rib.js
var require_rib = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/rib.js"(exports, module) {
    init_process_shim();
    function rib(hljs5) {
      return {
        name: "RenderMan RIB",
        keywords: "ArchiveRecord AreaLightSource Atmosphere Attribute AttributeBegin AttributeEnd Basis Begin Blobby Bound Clipping ClippingPlane Color ColorSamples ConcatTransform Cone CoordinateSystem CoordSysTransform CropWindow Curves Cylinder DepthOfField Detail DetailRange Disk Displacement Display End ErrorHandler Exposure Exterior Format FrameAspectRatio FrameBegin FrameEnd GeneralPolygon GeometricApproximation Geometry Hider Hyperboloid Identity Illuminate Imager Interior LightSource MakeCubeFaceEnvironment MakeLatLongEnvironment MakeShadow MakeTexture Matte MotionBegin MotionEnd NuPatch ObjectBegin ObjectEnd ObjectInstance Opacity Option Orientation Paraboloid Patch PatchMesh Perspective PixelFilter PixelSamples PixelVariance Points PointsGeneralPolygons PointsPolygons Polygon Procedural Projection Quantize ReadArchive RelativeDetail ReverseOrientation Rotate Scale ScreenWindow ShadingInterpolation ShadingRate Shutter Sides Skew SolidBegin SolidEnd Sphere SubdivisionMesh Surface TextureCoordinates Torus Transform TransformBegin TransformEnd TransformPoints Translate TrimCurve WorldBegin WorldEnd",
        illegal: "</",
        contains: [
          hljs5.HASH_COMMENT_MODE,
          hljs5.C_NUMBER_MODE,
          hljs5.APOS_STRING_MODE,
          hljs5.QUOTE_STRING_MODE
        ]
      };
    }
    module.exports = rib;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/roboconf.js
var require_roboconf = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/roboconf.js"(exports, module) {
    init_process_shim();
    function roboconf(hljs5) {
      const IDENTIFIER = "[a-zA-Z-_][^\\n{]+\\{";
      const PROPERTY = {
        className: "attribute",
        begin: /[a-zA-Z-_]+/,
        end: /\s*:/,
        excludeEnd: true,
        starts: {
          end: ";",
          relevance: 0,
          contains: [
            {
              className: "variable",
              begin: /\.[a-zA-Z-_]+/
            },
            {
              className: "keyword",
              begin: /\(optional\)/
            }
          ]
        }
      };
      return {
        name: "Roboconf",
        aliases: [
          "graph",
          "instances"
        ],
        case_insensitive: true,
        keywords: "import",
        contains: [
          // Facet sections
          {
            begin: "^facet " + IDENTIFIER,
            end: /\}/,
            keywords: "facet",
            contains: [
              PROPERTY,
              hljs5.HASH_COMMENT_MODE
            ]
          },
          // Instance sections
          {
            begin: "^\\s*instance of " + IDENTIFIER,
            end: /\}/,
            keywords: "name count channels instance-data instance-state instance of",
            illegal: /\S/,
            contains: [
              "self",
              PROPERTY,
              hljs5.HASH_COMMENT_MODE
            ]
          },
          // Component sections
          {
            begin: "^" + IDENTIFIER,
            end: /\}/,
            contains: [
              PROPERTY,
              hljs5.HASH_COMMENT_MODE
            ]
          },
          // Comments
          hljs5.HASH_COMMENT_MODE
        ]
      };
    }
    module.exports = roboconf;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/routeros.js
var require_routeros = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/routeros.js"(exports, module) {
    init_process_shim();
    function routeros(hljs5) {
      const STATEMENTS = "foreach do while for if from to step else on-error and or not in";
      const GLOBAL_COMMANDS = "global local beep delay put len typeof pick log time set find environment terminal error execute parse resolve toarray tobool toid toip toip6 tonum tostr totime";
      const COMMON_COMMANDS = "add remove enable disable set get print export edit find run debug error info warning";
      const LITERALS3 = "true false yes no nothing nil null";
      const OBJECTS = "traffic-flow traffic-generator firewall scheduler aaa accounting address-list address align area bandwidth-server bfd bgp bridge client clock community config connection console customer default dhcp-client dhcp-server discovery dns e-mail ethernet filter firmware gps graphing group hardware health hotspot identity igmp-proxy incoming instance interface ip ipsec ipv6 irq l2tp-server lcd ldp logging mac-server mac-winbox mangle manual mirror mme mpls nat nd neighbor network note ntp ospf ospf-v3 ovpn-server page peer pim ping policy pool port ppp pppoe-client pptp-server prefix profile proposal proxy queue radius resource rip ripng route routing screen script security-profiles server service service-port settings shares smb sms sniffer snmp snooper socks sstp-server system tool tracking type upgrade upnp user-manager users user vlan secret vrrp watchdog web-access wireless pptp pppoe lan wan layer7-protocol lease simple raw";
      const VAR = {
        className: "variable",
        variants: [
          {
            begin: /\$[\w\d#@][\w\d_]*/
          },
          {
            begin: /\$\{(.*?)\}/
          }
        ]
      };
      const QUOTE_STRING = {
        className: "string",
        begin: /"/,
        end: /"/,
        contains: [
          hljs5.BACKSLASH_ESCAPE,
          VAR,
          {
            className: "variable",
            begin: /\$\(/,
            end: /\)/,
            contains: [hljs5.BACKSLASH_ESCAPE]
          }
        ]
      };
      const APOS_STRING = {
        className: "string",
        begin: /'/,
        end: /'/
      };
      return {
        name: "Microtik RouterOS script",
        aliases: [
          "mikrotik"
        ],
        case_insensitive: true,
        keywords: {
          $pattern: /:?[\w-]+/,
          literal: LITERALS3,
          keyword: STATEMENTS + " :" + STATEMENTS.split(" ").join(" :") + " :" + GLOBAL_COMMANDS.split(" ").join(" :")
        },
        contains: [
          {
            // illegal syntax
            variants: [
              {
                // -- comment
                begin: /\/\*/,
                end: /\*\//
              },
              {
                // Stan comment
                begin: /\/\//,
                end: /$/
              },
              {
                // HTML tags
                begin: /<\//,
                end: />/
              }
            ],
            illegal: /./
          },
          hljs5.COMMENT("^#", "$"),
          QUOTE_STRING,
          APOS_STRING,
          VAR,
          // attribute=value
          {
            // > is to avoid matches with => in other grammars
            begin: /[\w-]+=([^\s{}[\]()>]+)/,
            relevance: 0,
            returnBegin: true,
            contains: [
              {
                className: "attribute",
                begin: /[^=]+/
              },
              {
                begin: /=/,
                endsWithParent: true,
                relevance: 0,
                contains: [
                  QUOTE_STRING,
                  APOS_STRING,
                  VAR,
                  {
                    className: "literal",
                    begin: "\\b(" + LITERALS3.split(" ").join("|") + ")\\b"
                  },
                  {
                    // Do not format unclassified values. Needed to exclude highlighting of values as built_in.
                    begin: /("[^"]*"|[^\s{}[\]]+)/
                  }
                  /*
                  {
                    // IPv4 addresses and subnets
                    className: 'number',
                    variants: [
                      {begin: IPADDR_wBITMASK+'(,'+IPADDR_wBITMASK+')*'}, //192.168.0.0/24,1.2.3.0/24
                      {begin: IPADDR+'-'+IPADDR},       // 192.168.0.1-192.168.0.3
                      {begin: IPADDR+'(,'+IPADDR+')*'}, // 192.168.0.1,192.168.0.34,192.168.24.1,192.168.0.1
                    ]
                  },
                  {
                    // MAC addresses and DHCP Client IDs
                    className: 'number',
                    begin: /\b(1:)?([0-9A-Fa-f]{1,2}[:-]){5}([0-9A-Fa-f]){1,2}\b/,
                  },
                  */
                ]
              }
            ]
          },
          {
            // HEX values
            className: "number",
            begin: /\*[0-9a-fA-F]+/
          },
          {
            begin: "\\b(" + COMMON_COMMANDS.split(" ").join("|") + ")([\\s[(\\]|])",
            returnBegin: true,
            contains: [
              {
                className: "builtin-name",
                // 'function',
                begin: /\w+/
              }
            ]
          },
          {
            className: "built_in",
            variants: [
              {
                begin: "(\\.\\./|/|\\s)((" + OBJECTS.split(" ").join("|") + ");?\\s)+"
              },
              {
                begin: /\.\./,
                relevance: 0
              }
            ]
          }
        ]
      };
    }
    module.exports = routeros;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/rsl.js
var require_rsl = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/rsl.js"(exports, module) {
    init_process_shim();
    function rsl(hljs5) {
      return {
        name: "RenderMan RSL",
        keywords: {
          keyword: "float color point normal vector matrix while for if do return else break extern continue",
          built_in: "abs acos ambient area asin atan atmosphere attribute calculatenormal ceil cellnoise clamp comp concat cos degrees depth Deriv diffuse distance Du Dv environment exp faceforward filterstep floor format fresnel incident length lightsource log match max min mod noise normalize ntransform opposite option phong pnoise pow printf ptlined radians random reflect refract renderinfo round setcomp setxcomp setycomp setzcomp shadow sign sin smoothstep specular specularbrdf spline sqrt step tan texture textureinfo trace transform vtransform xcomp ycomp zcomp"
        },
        illegal: "</",
        contains: [
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          hljs5.QUOTE_STRING_MODE,
          hljs5.APOS_STRING_MODE,
          hljs5.C_NUMBER_MODE,
          {
            className: "meta",
            begin: "#",
            end: "$"
          },
          {
            className: "class",
            beginKeywords: "surface displacement light volume imager",
            end: "\\("
          },
          {
            beginKeywords: "illuminate illuminance gather",
            end: "\\("
          }
        ]
      };
    }
    module.exports = rsl;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/ruleslanguage.js
var require_ruleslanguage = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/ruleslanguage.js"(exports, module) {
    init_process_shim();
    function ruleslanguage(hljs5) {
      return {
        name: "Oracle Rules Language",
        keywords: {
          keyword: "BILL_PERIOD BILL_START BILL_STOP RS_EFFECTIVE_START RS_EFFECTIVE_STOP RS_JURIS_CODE RS_OPCO_CODE INTDADDATTRIBUTE|5 INTDADDVMSG|5 INTDBLOCKOP|5 INTDBLOCKOPNA|5 INTDCLOSE|5 INTDCOUNT|5 INTDCOUNTSTATUSCODE|5 INTDCREATEMASK|5 INTDCREATEDAYMASK|5 INTDCREATEFACTORMASK|5 INTDCREATEHANDLE|5 INTDCREATEOVERRIDEDAYMASK|5 INTDCREATEOVERRIDEMASK|5 INTDCREATESTATUSCODEMASK|5 INTDCREATETOUPERIOD|5 INTDDELETE|5 INTDDIPTEST|5 INTDEXPORT|5 INTDGETERRORCODE|5 INTDGETERRORMESSAGE|5 INTDISEQUAL|5 INTDJOIN|5 INTDLOAD|5 INTDLOADACTUALCUT|5 INTDLOADDATES|5 INTDLOADHIST|5 INTDLOADLIST|5 INTDLOADLISTDATES|5 INTDLOADLISTENERGY|5 INTDLOADLISTHIST|5 INTDLOADRELATEDCHANNEL|5 INTDLOADSP|5 INTDLOADSTAGING|5 INTDLOADUOM|5 INTDLOADUOMDATES|5 INTDLOADUOMHIST|5 INTDLOADVERSION|5 INTDOPEN|5 INTDREADFIRST|5 INTDREADNEXT|5 INTDRECCOUNT|5 INTDRELEASE|5 INTDREPLACE|5 INTDROLLAVG|5 INTDROLLPEAK|5 INTDSCALAROP|5 INTDSCALE|5 INTDSETATTRIBUTE|5 INTDSETDSTPARTICIPANT|5 INTDSETSTRING|5 INTDSETVALUE|5 INTDSETVALUESTATUS|5 INTDSHIFTSTARTTIME|5 INTDSMOOTH|5 INTDSORT|5 INTDSPIKETEST|5 INTDSUBSET|5 INTDTOU|5 INTDTOURELEASE|5 INTDTOUVALUE|5 INTDUPDATESTATS|5 INTDVALUE|5 STDEV INTDDELETEEX|5 INTDLOADEXACTUAL|5 INTDLOADEXCUT|5 INTDLOADEXDATES|5 INTDLOADEX|5 INTDLOADEXRELATEDCHANNEL|5 INTDSAVEEX|5 MVLOAD|5 MVLOADACCT|5 MVLOADACCTDATES|5 MVLOADACCTHIST|5 MVLOADDATES|5 MVLOADHIST|5 MVLOADLIST|5 MVLOADLISTDATES|5 MVLOADLISTHIST|5 IF FOR NEXT DONE SELECT END CALL ABORT CLEAR CHANNEL FACTOR LIST NUMBER OVERRIDE SET WEEK DISTRIBUTIONNODE ELSE WHEN THEN OTHERWISE IENUM CSV INCLUDE LEAVE RIDER SAVE DELETE NOVALUE SECTION WARN SAVE_UPDATE DETERMINANT LABEL REPORT REVENUE EACH IN FROM TOTAL CHARGE BLOCK AND OR CSV_FILE RATE_CODE AUXILIARY_DEMAND UIDACCOUNT RS BILL_PERIOD_SELECT HOURS_PER_MONTH INTD_ERROR_STOP SEASON_SCHEDULE_NAME ACCOUNTFACTOR ARRAYUPPERBOUND CALLSTOREDPROC GETADOCONNECTION GETCONNECT GETDATASOURCE GETQUALIFIER GETUSERID HASVALUE LISTCOUNT LISTOP LISTUPDATE LISTVALUE PRORATEFACTOR RSPRORATE SETBINPATH SETDBMONITOR WQ_OPEN BILLINGHOURS DATE DATEFROMFLOAT DATETIMEFROMSTRING DATETIMETOSTRING DATETOFLOAT DAY DAYDIFF DAYNAME DBDATETIME HOUR MINUTE MONTH MONTHDIFF MONTHHOURS MONTHNAME ROUNDDATE SAMEWEEKDAYLASTYEAR SECOND WEEKDAY WEEKDIFF YEAR YEARDAY YEARSTR COMPSUM HISTCOUNT HISTMAX HISTMIN HISTMINNZ HISTVALUE MAXNRANGE MAXRANGE MINRANGE COMPIKVA COMPKVA COMPKVARFROMKQKW COMPLF IDATTR FLAG LF2KW LF2KWH MAXKW POWERFACTOR READING2USAGE AVGSEASON MAXSEASON MONTHLYMERGE SEASONVALUE SUMSEASON ACCTREADDATES ACCTTABLELOAD CONFIGADD CONFIGGET CREATEOBJECT CREATEREPORT EMAILCLIENT EXPBLKMDMUSAGE EXPMDMUSAGE EXPORT_USAGE FACTORINEFFECT GETUSERSPECIFIEDSTOP INEFFECT ISHOLIDAY RUNRATE SAVE_PROFILE SETREPORTTITLE USEREXIT WATFORRUNRATE TO TABLE ACOS ASIN ATAN ATAN2 BITAND CEIL COS COSECANT COSH COTANGENT DIVQUOT DIVREM EXP FABS FLOOR FMOD FREPM FREXPN LOG LOG10 MAX MAXN MIN MINNZ MODF POW ROUND ROUND2VALUE ROUNDINT SECANT SIN SINH SQROOT TAN TANH FLOAT2STRING FLOAT2STRINGNC INSTR LEFT LEN LTRIM MID RIGHT RTRIM STRING STRINGNC TOLOWER TOUPPER TRIM NUMDAYS READ_DATE STAGING",
          built_in: "IDENTIFIER OPTIONS XML_ELEMENT XML_OP XML_ELEMENT_OF DOMDOCCREATE DOMDOCLOADFILE DOMDOCLOADXML DOMDOCSAVEFILE DOMDOCGETROOT DOMDOCADDPI DOMNODEGETNAME DOMNODEGETTYPE DOMNODEGETVALUE DOMNODEGETCHILDCT DOMNODEGETFIRSTCHILD DOMNODEGETSIBLING DOMNODECREATECHILDELEMENT DOMNODESETATTRIBUTE DOMNODEGETCHILDELEMENTCT DOMNODEGETFIRSTCHILDELEMENT DOMNODEGETSIBLINGELEMENT DOMNODEGETATTRIBUTECT DOMNODEGETATTRIBUTEI DOMNODEGETATTRIBUTEBYNAME DOMNODEGETBYNAME"
        },
        contains: [
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          hljs5.APOS_STRING_MODE,
          hljs5.QUOTE_STRING_MODE,
          hljs5.C_NUMBER_MODE,
          {
            className: "literal",
            variants: [
              {
                // looks like #-comment
                begin: "#\\s+",
                relevance: 0
              },
              {
                begin: "#[a-zA-Z .]+"
              }
            ]
          }
        ]
      };
    }
    module.exports = ruleslanguage;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/rust.js
var require_rust = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/rust.js"(exports, module) {
    init_process_shim();
    function rust(hljs5) {
      const NUM_SUFFIX = "([ui](8|16|32|64|128|size)|f(32|64))?";
      const KEYWORDS3 = "abstract as async await become box break const continue crate do dyn else enum extern false final fn for if impl in let loop macro match mod move mut override priv pub ref return self Self static struct super trait true try type typeof unsafe unsized use virtual where while yield";
      const BUILTINS = (
        // functions
        "drop i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize f32 f64 str char bool Box Option Result String Vec Copy Send Sized Sync Drop Fn FnMut FnOnce ToOwned Clone Debug PartialEq PartialOrd Eq Ord AsRef AsMut Into From Default Iterator Extend IntoIterator DoubleEndedIterator ExactSizeIterator SliceConcatExt ToString assert! assert_eq! bitflags! bytes! cfg! col! concat! concat_idents! debug_assert! debug_assert_eq! env! panic! file! format! format_args! include_bin! include_str! line! local_data_key! module_path! option_env! print! println! select! stringify! try! unimplemented! unreachable! vec! write! writeln! macro_rules! assert_ne! debug_assert_ne!"
      );
      return {
        name: "Rust",
        aliases: ["rs"],
        keywords: {
          $pattern: hljs5.IDENT_RE + "!?",
          keyword: KEYWORDS3,
          literal: "true false Some None Ok Err",
          built_in: BUILTINS
        },
        illegal: "</",
        contains: [
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.COMMENT("/\\*", "\\*/", {
            contains: ["self"]
          }),
          hljs5.inherit(hljs5.QUOTE_STRING_MODE, {
            begin: /b?"/,
            illegal: null
          }),
          {
            className: "string",
            variants: [
              {
                begin: /r(#*)"(.|\n)*?"\1(?!#)/
              },
              {
                begin: /b?'\\?(x\w{2}|u\w{4}|U\w{8}|.)'/
              }
            ]
          },
          {
            className: "symbol",
            begin: /'[a-zA-Z_][a-zA-Z0-9_]*/
          },
          {
            className: "number",
            variants: [
              {
                begin: "\\b0b([01_]+)" + NUM_SUFFIX
              },
              {
                begin: "\\b0o([0-7_]+)" + NUM_SUFFIX
              },
              {
                begin: "\\b0x([A-Fa-f0-9_]+)" + NUM_SUFFIX
              },
              {
                begin: "\\b(\\d[\\d_]*(\\.[0-9_]+)?([eE][+-]?[0-9_]+)?)" + NUM_SUFFIX
              }
            ],
            relevance: 0
          },
          {
            className: "function",
            beginKeywords: "fn",
            end: "(\\(|<)",
            excludeEnd: true,
            contains: [hljs5.UNDERSCORE_TITLE_MODE]
          },
          {
            className: "meta",
            begin: "#!?\\[",
            end: "\\]",
            contains: [
              {
                className: "meta-string",
                begin: /"/,
                end: /"/
              }
            ]
          },
          {
            className: "class",
            beginKeywords: "type",
            end: ";",
            contains: [
              hljs5.inherit(hljs5.UNDERSCORE_TITLE_MODE, {
                endsParent: true
              })
            ],
            illegal: "\\S"
          },
          {
            className: "class",
            beginKeywords: "trait enum struct union",
            end: /\{/,
            contains: [
              hljs5.inherit(hljs5.UNDERSCORE_TITLE_MODE, {
                endsParent: true
              })
            ],
            illegal: "[\\w\\d]"
          },
          {
            begin: hljs5.IDENT_RE + "::",
            keywords: {
              built_in: BUILTINS
            }
          },
          {
            begin: "->"
          }
        ]
      };
    }
    module.exports = rust;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/sas.js
var require_sas = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/sas.js"(exports, module) {
    init_process_shim();
    function sas(hljs5) {
      const SAS_KEYWORDS = "do if then else end until while abort array attrib by call cards cards4 catname continue datalines datalines4 delete delim delimiter display dm drop endsas error file filename footnote format goto in infile informat input keep label leave length libname link list lostcard merge missing modify options output out page put redirect remove rename replace retain return select set skip startsas stop title update waitsas where window x systask add and alter as cascade check create delete describe distinct drop foreign from group having index insert into in key like message modify msgtype not null on or order primary references reset restrict select set table unique update validate view where";
      const SAS_FUN = "abs|addr|airy|arcos|arsin|atan|attrc|attrn|band|betainv|blshift|bnot|bor|brshift|bxor|byte|cdf|ceil|cexist|cinv|close|cnonct|collate|compbl|compound|compress|cos|cosh|css|curobs|cv|daccdb|daccdbsl|daccsl|daccsyd|dacctab|dairy|date|datejul|datepart|datetime|day|dclose|depdb|depdbsl|depdbsl|depsl|depsl|depsyd|depsyd|deptab|deptab|dequote|dhms|dif|digamma|dim|dinfo|dnum|dopen|doptname|doptnum|dread|dropnote|dsname|erf|erfc|exist|exp|fappend|fclose|fcol|fdelete|fetch|fetchobs|fexist|fget|fileexist|filename|fileref|finfo|finv|fipname|fipnamel|fipstate|floor|fnonct|fnote|fopen|foptname|foptnum|fpoint|fpos|fput|fread|frewind|frlen|fsep|fuzz|fwrite|gaminv|gamma|getoption|getvarc|getvarn|hbound|hms|hosthelp|hour|ibessel|index|indexc|indexw|input|inputc|inputn|int|intck|intnx|intrr|irr|jbessel|juldate|kurtosis|lag|lbound|left|length|lgamma|libname|libref|log|log10|log2|logpdf|logpmf|logsdf|lowcase|max|mdy|mean|min|minute|mod|month|mopen|mort|n|netpv|nmiss|normal|note|npv|open|ordinal|pathname|pdf|peek|peekc|pmf|point|poisson|poke|probbeta|probbnml|probchi|probf|probgam|probhypr|probit|probnegb|probnorm|probt|put|putc|putn|qtr|quote|ranbin|rancau|ranexp|rangam|range|rank|rannor|ranpoi|rantbl|rantri|ranuni|repeat|resolve|reverse|rewind|right|round|saving|scan|sdf|second|sign|sin|sinh|skewness|soundex|spedis|sqrt|std|stderr|stfips|stname|stnamel|substr|sum|symget|sysget|sysmsg|sysprod|sysrc|system|tan|tanh|time|timepart|tinv|tnonct|today|translate|tranwrd|trigamma|trim|trimn|trunc|uniform|upcase|uss|var|varfmt|varinfmt|varlabel|varlen|varname|varnum|varray|varrayx|vartype|verify|vformat|vformatd|vformatdx|vformatn|vformatnx|vformatw|vformatwx|vformatx|vinarray|vinarrayx|vinformat|vinformatd|vinformatdx|vinformatn|vinformatnx|vinformatw|vinformatwx|vinformatx|vlabel|vlabelx|vlength|vlengthx|vname|vnamex|vtype|vtypex|weekday|year|yyq|zipfips|zipname|zipnamel|zipstate";
      const SAS_MACRO_FUN = "bquote|nrbquote|cmpres|qcmpres|compstor|datatyp|display|do|else|end|eval|global|goto|if|index|input|keydef|label|left|length|let|local|lowcase|macro|mend|nrbquote|nrquote|nrstr|put|qcmpres|qleft|qlowcase|qscan|qsubstr|qsysfunc|qtrim|quote|qupcase|scan|str|substr|superq|syscall|sysevalf|sysexec|sysfunc|sysget|syslput|sysprod|sysrc|sysrput|then|to|trim|unquote|until|upcase|verify|while|window";
      return {
        name: "SAS",
        case_insensitive: true,
        // SAS is case-insensitive
        keywords: {
          literal: "null missing _all_ _automatic_ _character_ _infile_ _n_ _name_ _null_ _numeric_ _user_ _webout_",
          meta: SAS_KEYWORDS
        },
        contains: [
          {
            // Distinct highlight for proc <proc>, data, run, quit
            className: "keyword",
            begin: /^\s*(proc [\w\d_]+|data|run|quit)[\s;]/
          },
          {
            // Macro variables
            className: "variable",
            begin: /&[a-zA-Z_&][a-zA-Z0-9_]*\.?/
          },
          {
            // Special emphasis for datalines|cards
            className: "emphasis",
            begin: /^\s*datalines|cards.*;/,
            end: /^\s*;\s*$/
          },
          {
            // Built-in macro variables take precedence
            className: "built_in",
            begin: "%(" + SAS_MACRO_FUN + ")"
          },
          {
            // User-defined macro functions highlighted after
            className: "name",
            begin: /%[a-zA-Z_][a-zA-Z_0-9]*/
          },
          {
            className: "meta",
            begin: "[^%](" + SAS_FUN + ")[(]"
          },
          {
            className: "string",
            variants: [
              hljs5.APOS_STRING_MODE,
              hljs5.QUOTE_STRING_MODE
            ]
          },
          hljs5.COMMENT("\\*", ";"),
          hljs5.C_BLOCK_COMMENT_MODE
        ]
      };
    }
    module.exports = sas;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/scala.js
var require_scala = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/scala.js"(exports, module) {
    init_process_shim();
    function scala(hljs5) {
      const ANNOTATION = {
        className: "meta",
        begin: "@[A-Za-z]+"
      };
      const SUBST = {
        className: "subst",
        variants: [
          {
            begin: "\\$[A-Za-z0-9_]+"
          },
          {
            begin: /\$\{/,
            end: /\}/
          }
        ]
      };
      const STRING = {
        className: "string",
        variants: [
          {
            begin: '"""',
            end: '"""'
          },
          {
            begin: '"',
            end: '"',
            illegal: "\\n",
            contains: [hljs5.BACKSLASH_ESCAPE]
          },
          {
            begin: '[a-z]+"',
            end: '"',
            illegal: "\\n",
            contains: [
              hljs5.BACKSLASH_ESCAPE,
              SUBST
            ]
          },
          {
            className: "string",
            begin: '[a-z]+"""',
            end: '"""',
            contains: [SUBST],
            relevance: 10
          }
        ]
      };
      const SYMBOL = {
        className: "symbol",
        begin: "'\\w[\\w\\d_]*(?!')"
      };
      const TYPE = {
        className: "type",
        begin: "\\b[A-Z][A-Za-z0-9_]*",
        relevance: 0
      };
      const NAME = {
        className: "title",
        begin: /[^0-9\n\t "'(),.`{}\[\]:;][^\n\t "'(),.`{}\[\]:;]+|[^0-9\n\t "'(),.`{}\[\]:;=]/,
        relevance: 0
      };
      const CLASS = {
        className: "class",
        beginKeywords: "class object trait type",
        end: /[:={\[\n;]/,
        excludeEnd: true,
        contains: [
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          {
            beginKeywords: "extends with",
            relevance: 10
          },
          {
            begin: /\[/,
            end: /\]/,
            excludeBegin: true,
            excludeEnd: true,
            relevance: 0,
            contains: [TYPE]
          },
          {
            className: "params",
            begin: /\(/,
            end: /\)/,
            excludeBegin: true,
            excludeEnd: true,
            relevance: 0,
            contains: [TYPE]
          },
          NAME
        ]
      };
      const METHOD = {
        className: "function",
        beginKeywords: "def",
        end: /[:={\[(\n;]/,
        excludeEnd: true,
        contains: [NAME]
      };
      return {
        name: "Scala",
        keywords: {
          literal: "true false null",
          keyword: "type yield lazy override def with val var sealed abstract private trait object if forSome for while throw finally protected extends import final return else break new catch super class case package default try this match continue throws implicit"
        },
        contains: [
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          STRING,
          SYMBOL,
          TYPE,
          METHOD,
          CLASS,
          hljs5.C_NUMBER_MODE,
          ANNOTATION
        ]
      };
    }
    module.exports = scala;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/scheme.js
var require_scheme = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/scheme.js"(exports, module) {
    init_process_shim();
    function scheme(hljs5) {
      const SCHEME_IDENT_RE = "[^\\(\\)\\[\\]\\{\\}\",'`;#|\\\\\\s]+";
      const SCHEME_SIMPLE_NUMBER_RE = "(-|\\+)?\\d+([./]\\d+)?";
      const SCHEME_COMPLEX_NUMBER_RE = SCHEME_SIMPLE_NUMBER_RE + "[+\\-]" + SCHEME_SIMPLE_NUMBER_RE + "i";
      const KEYWORDS3 = {
        $pattern: SCHEME_IDENT_RE,
        "builtin-name": "case-lambda call/cc class define-class exit-handler field import inherit init-field interface let*-values let-values let/ec mixin opt-lambda override protect provide public rename require require-for-syntax syntax syntax-case syntax-error unit/sig unless when with-syntax and begin call-with-current-continuation call-with-input-file call-with-output-file case cond define define-syntax delay do dynamic-wind else for-each if lambda let let* let-syntax letrec letrec-syntax map or syntax-rules ' * + , ,@ - ... / ; < <= = => > >= ` abs acos angle append apply asin assoc assq assv atan boolean? caar cadr call-with-input-file call-with-output-file call-with-values car cdddar cddddr cdr ceiling char->integer char-alphabetic? char-ci<=? char-ci<? char-ci=? char-ci>=? char-ci>? char-downcase char-lower-case? char-numeric? char-ready? char-upcase char-upper-case? char-whitespace? char<=? char<? char=? char>=? char>? char? close-input-port close-output-port complex? cons cos current-input-port current-output-port denominator display eof-object? eq? equal? eqv? eval even? exact->inexact exact? exp expt floor force gcd imag-part inexact->exact inexact? input-port? integer->char integer? interaction-environment lcm length list list->string list->vector list-ref list-tail list? load log magnitude make-polar make-rectangular make-string make-vector max member memq memv min modulo negative? newline not null-environment null? number->string number? numerator odd? open-input-file open-output-file output-port? pair? peek-char port? positive? procedure? quasiquote quote quotient rational? rationalize read read-char real-part real? remainder reverse round scheme-report-environment set! set-car! set-cdr! sin sqrt string string->list string->number string->symbol string-append string-ci<=? string-ci<? string-ci=? string-ci>=? string-ci>? string-copy string-fill! string-length string-ref string-set! string<=? string<? string=? string>=? string>? string? substring symbol->string symbol? tan transcript-off transcript-on truncate values vector vector->list vector-fill! vector-length vector-ref vector-set! with-input-from-file with-output-to-file write write-char zero?"
      };
      const LITERAL = {
        className: "literal",
        begin: "(#t|#f|#\\\\" + SCHEME_IDENT_RE + "|#\\\\.)"
      };
      const NUMBER = {
        className: "number",
        variants: [
          {
            begin: SCHEME_SIMPLE_NUMBER_RE,
            relevance: 0
          },
          {
            begin: SCHEME_COMPLEX_NUMBER_RE,
            relevance: 0
          },
          {
            begin: "#b[0-1]+(/[0-1]+)?"
          },
          {
            begin: "#o[0-7]+(/[0-7]+)?"
          },
          {
            begin: "#x[0-9a-f]+(/[0-9a-f]+)?"
          }
        ]
      };
      const STRING = hljs5.QUOTE_STRING_MODE;
      const COMMENT_MODES = [
        hljs5.COMMENT(
          ";",
          "$",
          {
            relevance: 0
          }
        ),
        hljs5.COMMENT("#\\|", "\\|#")
      ];
      const IDENT = {
        begin: SCHEME_IDENT_RE,
        relevance: 0
      };
      const QUOTED_IDENT = {
        className: "symbol",
        begin: "'" + SCHEME_IDENT_RE
      };
      const BODY = {
        endsWithParent: true,
        relevance: 0
      };
      const QUOTED_LIST = {
        variants: [
          {
            begin: /'/
          },
          {
            begin: "`"
          }
        ],
        contains: [
          {
            begin: "\\(",
            end: "\\)",
            contains: [
              "self",
              LITERAL,
              STRING,
              NUMBER,
              IDENT,
              QUOTED_IDENT
            ]
          }
        ]
      };
      const NAME = {
        className: "name",
        relevance: 0,
        begin: SCHEME_IDENT_RE,
        keywords: KEYWORDS3
      };
      const LAMBDA = {
        begin: /lambda/,
        endsWithParent: true,
        returnBegin: true,
        contains: [
          NAME,
          {
            endsParent: true,
            variants: [
              {
                begin: /\(/,
                end: /\)/
              },
              {
                begin: /\[/,
                end: /\]/
              }
            ],
            contains: [IDENT]
          }
        ]
      };
      const LIST = {
        variants: [
          {
            begin: "\\(",
            end: "\\)"
          },
          {
            begin: "\\[",
            end: "\\]"
          }
        ],
        contains: [
          LAMBDA,
          NAME,
          BODY
        ]
      };
      BODY.contains = [
        LITERAL,
        NUMBER,
        STRING,
        IDENT,
        QUOTED_IDENT,
        QUOTED_LIST,
        LIST
      ].concat(COMMENT_MODES);
      return {
        name: "Scheme",
        illegal: /\S/,
        contains: [
          hljs5.SHEBANG(),
          NUMBER,
          STRING,
          QUOTED_IDENT,
          QUOTED_LIST,
          LIST
        ].concat(COMMENT_MODES)
      };
    }
    module.exports = scheme;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/scilab.js
var require_scilab = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/scilab.js"(exports, module) {
    init_process_shim();
    function scilab(hljs5) {
      const COMMON_CONTAINS = [
        hljs5.C_NUMBER_MODE,
        {
          className: "string",
          begin: `'|"`,
          end: `'|"`,
          contains: [
            hljs5.BACKSLASH_ESCAPE,
            {
              begin: "''"
            }
          ]
        }
      ];
      return {
        name: "Scilab",
        aliases: ["sci"],
        keywords: {
          $pattern: /%?\w+/,
          keyword: "abort break case clear catch continue do elseif else endfunction end for function global if pause return resume select try then while",
          literal: "%f %F %t %T %pi %eps %inf %nan %e %i %z %s",
          built_in: (
            // Scilab has more than 2000 functions. Just list the most commons
            "abs and acos asin atan ceil cd chdir clearglobal cosh cos cumprod deff disp error exec execstr exists exp eye gettext floor fprintf fread fsolve imag isdef isempty isinfisnan isvector lasterror length load linspace list listfiles log10 log2 log max min msprintf mclose mopen ones or pathconvert poly printf prod pwd rand real round sinh sin size gsort sprintf sqrt strcat strcmps tring sum system tanh tan type typename warning zeros matrix"
          )
        },
        illegal: '("|#|/\\*|\\s+/\\w+)',
        contains: [
          {
            className: "function",
            beginKeywords: "function",
            end: "$",
            contains: [
              hljs5.UNDERSCORE_TITLE_MODE,
              {
                className: "params",
                begin: "\\(",
                end: "\\)"
              }
            ]
          },
          // seems to be a guard against [ident]' or [ident].
          // perhaps to prevent attributes from flagging as keywords?
          {
            begin: "[a-zA-Z_][a-zA-Z_0-9]*[\\.']+",
            relevance: 0
          },
          {
            begin: "\\[",
            end: "\\][\\.']*",
            relevance: 0,
            contains: COMMON_CONTAINS
          },
          hljs5.COMMENT("//", "$")
        ].concat(COMMON_CONTAINS)
      };
    }
    module.exports = scilab;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/scss.js
var require_scss = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/scss.js"(exports, module) {
    init_process_shim();
    var MODES2 = (hljs5) => {
      return {
        IMPORTANT: {
          className: "meta",
          begin: "!important"
        },
        HEXCOLOR: {
          className: "number",
          begin: "#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})"
        },
        ATTRIBUTE_SELECTOR_MODE: {
          className: "selector-attr",
          begin: /\[/,
          end: /\]/,
          illegal: "$",
          contains: [
            hljs5.APOS_STRING_MODE,
            hljs5.QUOTE_STRING_MODE
          ]
        }
      };
    };
    var TAGS2 = [
      "a",
      "abbr",
      "address",
      "article",
      "aside",
      "audio",
      "b",
      "blockquote",
      "body",
      "button",
      "canvas",
      "caption",
      "cite",
      "code",
      "dd",
      "del",
      "details",
      "dfn",
      "div",
      "dl",
      "dt",
      "em",
      "fieldset",
      "figcaption",
      "figure",
      "footer",
      "form",
      "h1",
      "h2",
      "h3",
      "h4",
      "h5",
      "h6",
      "header",
      "hgroup",
      "html",
      "i",
      "iframe",
      "img",
      "input",
      "ins",
      "kbd",
      "label",
      "legend",
      "li",
      "main",
      "mark",
      "menu",
      "nav",
      "object",
      "ol",
      "p",
      "q",
      "quote",
      "samp",
      "section",
      "span",
      "strong",
      "summary",
      "sup",
      "table",
      "tbody",
      "td",
      "textarea",
      "tfoot",
      "th",
      "thead",
      "time",
      "tr",
      "ul",
      "var",
      "video"
    ];
    var MEDIA_FEATURES2 = [
      "any-hover",
      "any-pointer",
      "aspect-ratio",
      "color",
      "color-gamut",
      "color-index",
      "device-aspect-ratio",
      "device-height",
      "device-width",
      "display-mode",
      "forced-colors",
      "grid",
      "height",
      "hover",
      "inverted-colors",
      "monochrome",
      "orientation",
      "overflow-block",
      "overflow-inline",
      "pointer",
      "prefers-color-scheme",
      "prefers-contrast",
      "prefers-reduced-motion",
      "prefers-reduced-transparency",
      "resolution",
      "scan",
      "scripting",
      "update",
      "width",
      // TODO: find a better solution?
      "min-width",
      "max-width",
      "min-height",
      "max-height"
    ];
    var PSEUDO_CLASSES2 = [
      "active",
      "any-link",
      "blank",
      "checked",
      "current",
      "default",
      "defined",
      "dir",
      // dir()
      "disabled",
      "drop",
      "empty",
      "enabled",
      "first",
      "first-child",
      "first-of-type",
      "fullscreen",
      "future",
      "focus",
      "focus-visible",
      "focus-within",
      "has",
      // has()
      "host",
      // host or host()
      "host-context",
      // host-context()
      "hover",
      "indeterminate",
      "in-range",
      "invalid",
      "is",
      // is()
      "lang",
      // lang()
      "last-child",
      "last-of-type",
      "left",
      "link",
      "local-link",
      "not",
      // not()
      "nth-child",
      // nth-child()
      "nth-col",
      // nth-col()
      "nth-last-child",
      // nth-last-child()
      "nth-last-col",
      // nth-last-col()
      "nth-last-of-type",
      //nth-last-of-type()
      "nth-of-type",
      //nth-of-type()
      "only-child",
      "only-of-type",
      "optional",
      "out-of-range",
      "past",
      "placeholder-shown",
      "read-only",
      "read-write",
      "required",
      "right",
      "root",
      "scope",
      "target",
      "target-within",
      "user-invalid",
      "valid",
      "visited",
      "where"
      // where()
    ];
    var PSEUDO_ELEMENTS2 = [
      "after",
      "backdrop",
      "before",
      "cue",
      "cue-region",
      "first-letter",
      "first-line",
      "grammar-error",
      "marker",
      "part",
      "placeholder",
      "selection",
      "slotted",
      "spelling-error"
    ];
    var ATTRIBUTES2 = [
      "align-content",
      "align-items",
      "align-self",
      "animation",
      "animation-delay",
      "animation-direction",
      "animation-duration",
      "animation-fill-mode",
      "animation-iteration-count",
      "animation-name",
      "animation-play-state",
      "animation-timing-function",
      "auto",
      "backface-visibility",
      "background",
      "background-attachment",
      "background-clip",
      "background-color",
      "background-image",
      "background-origin",
      "background-position",
      "background-repeat",
      "background-size",
      "border",
      "border-bottom",
      "border-bottom-color",
      "border-bottom-left-radius",
      "border-bottom-right-radius",
      "border-bottom-style",
      "border-bottom-width",
      "border-collapse",
      "border-color",
      "border-image",
      "border-image-outset",
      "border-image-repeat",
      "border-image-slice",
      "border-image-source",
      "border-image-width",
      "border-left",
      "border-left-color",
      "border-left-style",
      "border-left-width",
      "border-radius",
      "border-right",
      "border-right-color",
      "border-right-style",
      "border-right-width",
      "border-spacing",
      "border-style",
      "border-top",
      "border-top-color",
      "border-top-left-radius",
      "border-top-right-radius",
      "border-top-style",
      "border-top-width",
      "border-width",
      "bottom",
      "box-decoration-break",
      "box-shadow",
      "box-sizing",
      "break-after",
      "break-before",
      "break-inside",
      "caption-side",
      "clear",
      "clip",
      "clip-path",
      "color",
      "column-count",
      "column-fill",
      "column-gap",
      "column-rule",
      "column-rule-color",
      "column-rule-style",
      "column-rule-width",
      "column-span",
      "column-width",
      "columns",
      "content",
      "counter-increment",
      "counter-reset",
      "cursor",
      "direction",
      "display",
      "empty-cells",
      "filter",
      "flex",
      "flex-basis",
      "flex-direction",
      "flex-flow",
      "flex-grow",
      "flex-shrink",
      "flex-wrap",
      "float",
      "font",
      "font-display",
      "font-family",
      "font-feature-settings",
      "font-kerning",
      "font-language-override",
      "font-size",
      "font-size-adjust",
      "font-smoothing",
      "font-stretch",
      "font-style",
      "font-variant",
      "font-variant-ligatures",
      "font-variation-settings",
      "font-weight",
      "height",
      "hyphens",
      "icon",
      "image-orientation",
      "image-rendering",
      "image-resolution",
      "ime-mode",
      "inherit",
      "initial",
      "justify-content",
      "left",
      "letter-spacing",
      "line-height",
      "list-style",
      "list-style-image",
      "list-style-position",
      "list-style-type",
      "margin",
      "margin-bottom",
      "margin-left",
      "margin-right",
      "margin-top",
      "marks",
      "mask",
      "max-height",
      "max-width",
      "min-height",
      "min-width",
      "nav-down",
      "nav-index",
      "nav-left",
      "nav-right",
      "nav-up",
      "none",
      "normal",
      "object-fit",
      "object-position",
      "opacity",
      "order",
      "orphans",
      "outline",
      "outline-color",
      "outline-offset",
      "outline-style",
      "outline-width",
      "overflow",
      "overflow-wrap",
      "overflow-x",
      "overflow-y",
      "padding",
      "padding-bottom",
      "padding-left",
      "padding-right",
      "padding-top",
      "page-break-after",
      "page-break-before",
      "page-break-inside",
      "perspective",
      "perspective-origin",
      "pointer-events",
      "position",
      "quotes",
      "resize",
      "right",
      "src",
      // @font-face
      "tab-size",
      "table-layout",
      "text-align",
      "text-align-last",
      "text-decoration",
      "text-decoration-color",
      "text-decoration-line",
      "text-decoration-style",
      "text-indent",
      "text-overflow",
      "text-rendering",
      "text-shadow",
      "text-transform",
      "text-underline-position",
      "top",
      "transform",
      "transform-origin",
      "transform-style",
      "transition",
      "transition-delay",
      "transition-duration",
      "transition-property",
      "transition-timing-function",
      "unicode-bidi",
      "vertical-align",
      "visibility",
      "white-space",
      "widows",
      "width",
      "word-break",
      "word-spacing",
      "word-wrap",
      "z-index"
      // reverse makes sure longer attributes `font-weight` are matched fully
      // instead of getting false positives on say `font`
    ].reverse();
    function scss(hljs5) {
      const modes = MODES2(hljs5);
      const PSEUDO_ELEMENTS$1 = PSEUDO_ELEMENTS2;
      const PSEUDO_CLASSES$1 = PSEUDO_CLASSES2;
      const AT_IDENTIFIER = "@[a-z-]+";
      const AT_MODIFIERS = "and or not only";
      const IDENT_RE3 = "[a-zA-Z-][a-zA-Z0-9_-]*";
      const VARIABLE = {
        className: "variable",
        begin: "(\\$" + IDENT_RE3 + ")\\b"
      };
      return {
        name: "SCSS",
        case_insensitive: true,
        illegal: "[=/|']",
        contains: [
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          {
            className: "selector-id",
            begin: "#[A-Za-z0-9_-]+",
            relevance: 0
          },
          {
            className: "selector-class",
            begin: "\\.[A-Za-z0-9_-]+",
            relevance: 0
          },
          modes.ATTRIBUTE_SELECTOR_MODE,
          {
            className: "selector-tag",
            begin: "\\b(" + TAGS2.join("|") + ")\\b",
            // was there, before, but why?
            relevance: 0
          },
          {
            className: "selector-pseudo",
            begin: ":(" + PSEUDO_CLASSES$1.join("|") + ")"
          },
          {
            className: "selector-pseudo",
            begin: "::(" + PSEUDO_ELEMENTS$1.join("|") + ")"
          },
          VARIABLE,
          {
            // pseudo-selector params
            begin: /\(/,
            end: /\)/,
            contains: [hljs5.CSS_NUMBER_MODE]
          },
          {
            className: "attribute",
            begin: "\\b(" + ATTRIBUTES2.join("|") + ")\\b"
          },
          {
            begin: "\\b(whitespace|wait|w-resize|visible|vertical-text|vertical-ideographic|uppercase|upper-roman|upper-alpha|underline|transparent|top|thin|thick|text|text-top|text-bottom|tb-rl|table-header-group|table-footer-group|sw-resize|super|strict|static|square|solid|small-caps|separate|se-resize|scroll|s-resize|rtl|row-resize|ridge|right|repeat|repeat-y|repeat-x|relative|progress|pointer|overline|outside|outset|oblique|nowrap|not-allowed|normal|none|nw-resize|no-repeat|no-drop|newspaper|ne-resize|n-resize|move|middle|medium|ltr|lr-tb|lowercase|lower-roman|lower-alpha|loose|list-item|line|line-through|line-edge|lighter|left|keep-all|justify|italic|inter-word|inter-ideograph|inside|inset|inline|inline-block|inherit|inactive|ideograph-space|ideograph-parenthesis|ideograph-numeric|ideograph-alpha|horizontal|hidden|help|hand|groove|fixed|ellipsis|e-resize|double|dotted|distribute|distribute-space|distribute-letter|distribute-all-lines|disc|disabled|default|decimal|dashed|crosshair|collapse|col-resize|circle|char|center|capitalize|break-word|break-all|bottom|both|bolder|bold|block|bidi-override|below|baseline|auto|always|all-scroll|absolute|table|table-cell)\\b"
          },
          {
            begin: ":",
            end: ";",
            contains: [
              VARIABLE,
              modes.HEXCOLOR,
              hljs5.CSS_NUMBER_MODE,
              hljs5.QUOTE_STRING_MODE,
              hljs5.APOS_STRING_MODE,
              modes.IMPORTANT
            ]
          },
          // matching these here allows us to treat them more like regular CSS
          // rules so everything between the {} gets regular rule highlighting,
          // which is what we want for page and font-face
          {
            begin: "@(page|font-face)",
            lexemes: AT_IDENTIFIER,
            keywords: "@page @font-face"
          },
          {
            begin: "@",
            end: "[{;]",
            returnBegin: true,
            keywords: {
              $pattern: /[a-z-]+/,
              keyword: AT_MODIFIERS,
              attribute: MEDIA_FEATURES2.join(" ")
            },
            contains: [
              {
                begin: AT_IDENTIFIER,
                className: "keyword"
              },
              {
                begin: /[a-z-]+(?=:)/,
                className: "attribute"
              },
              VARIABLE,
              hljs5.QUOTE_STRING_MODE,
              hljs5.APOS_STRING_MODE,
              modes.HEXCOLOR,
              hljs5.CSS_NUMBER_MODE
            ]
          }
        ]
      };
    }
    module.exports = scss;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/shell.js
var require_shell = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/shell.js"(exports, module) {
    init_process_shim();
    function shell(hljs5) {
      return {
        name: "Shell Session",
        aliases: ["console"],
        contains: [
          {
            className: "meta",
            // We cannot add \s (spaces) in the regular expression otherwise it will be too broad and produce unexpected result.
            // For instance, in the following example, it would match "echo /path/to/home >" as a prompt:
            // echo /path/to/home > t.exe
            begin: /^\s{0,3}[/~\w\d[\]()@-]*[>%$#]/,
            starts: {
              end: /[^\\](?=\s*$)/,
              subLanguage: "bash"
            }
          }
        ]
      };
    }
    module.exports = shell;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/smali.js
var require_smali = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/smali.js"(exports, module) {
    init_process_shim();
    function smali(hljs5) {
      const smali_instr_low_prio = [
        "add",
        "and",
        "cmp",
        "cmpg",
        "cmpl",
        "const",
        "div",
        "double",
        "float",
        "goto",
        "if",
        "int",
        "long",
        "move",
        "mul",
        "neg",
        "new",
        "nop",
        "not",
        "or",
        "rem",
        "return",
        "shl",
        "shr",
        "sput",
        "sub",
        "throw",
        "ushr",
        "xor"
      ];
      const smali_instr_high_prio = [
        "aget",
        "aput",
        "array",
        "check",
        "execute",
        "fill",
        "filled",
        "goto/16",
        "goto/32",
        "iget",
        "instance",
        "invoke",
        "iput",
        "monitor",
        "packed",
        "sget",
        "sparse"
      ];
      const smali_keywords = [
        "transient",
        "constructor",
        "abstract",
        "final",
        "synthetic",
        "public",
        "private",
        "protected",
        "static",
        "bridge",
        "system"
      ];
      return {
        name: "Smali",
        contains: [
          {
            className: "string",
            begin: '"',
            end: '"',
            relevance: 0
          },
          hljs5.COMMENT(
            "#",
            "$",
            {
              relevance: 0
            }
          ),
          {
            className: "keyword",
            variants: [
              {
                begin: "\\s*\\.end\\s[a-zA-Z0-9]*"
              },
              {
                begin: "^[ ]*\\.[a-zA-Z]*",
                relevance: 0
              },
              {
                begin: "\\s:[a-zA-Z_0-9]*",
                relevance: 0
              },
              {
                begin: "\\s(" + smali_keywords.join("|") + ")"
              }
            ]
          },
          {
            className: "built_in",
            variants: [
              {
                begin: "\\s(" + smali_instr_low_prio.join("|") + ")\\s"
              },
              {
                begin: "\\s(" + smali_instr_low_prio.join("|") + ")((-|/)[a-zA-Z0-9]+)+\\s",
                relevance: 10
              },
              {
                begin: "\\s(" + smali_instr_high_prio.join("|") + ")((-|/)[a-zA-Z0-9]+)*\\s",
                relevance: 10
              }
            ]
          },
          {
            className: "class",
            begin: "L[^(;:\n]*;",
            relevance: 0
          },
          {
            begin: "[vp][0-9]+"
          }
        ]
      };
    }
    module.exports = smali;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/smalltalk.js
var require_smalltalk = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/smalltalk.js"(exports, module) {
    init_process_shim();
    function smalltalk(hljs5) {
      const VAR_IDENT_RE = "[a-z][a-zA-Z0-9_]*";
      const CHAR = {
        className: "string",
        begin: "\\$.{1}"
      };
      const SYMBOL = {
        className: "symbol",
        begin: "#" + hljs5.UNDERSCORE_IDENT_RE
      };
      return {
        name: "Smalltalk",
        aliases: ["st"],
        keywords: "self super nil true false thisContext",
        // only 6
        contains: [
          hljs5.COMMENT('"', '"'),
          hljs5.APOS_STRING_MODE,
          {
            className: "type",
            begin: "\\b[A-Z][A-Za-z0-9_]*",
            relevance: 0
          },
          {
            begin: VAR_IDENT_RE + ":",
            relevance: 0
          },
          hljs5.C_NUMBER_MODE,
          SYMBOL,
          CHAR,
          {
            // This looks more complicated than needed to avoid combinatorial
            // explosion under V8. It effectively means `| var1 var2 ... |` with
            // whitespace adjacent to `|` being optional.
            begin: "\\|[ ]*" + VAR_IDENT_RE + "([ ]+" + VAR_IDENT_RE + ")*[ ]*\\|",
            returnBegin: true,
            end: /\|/,
            illegal: /\S/,
            contains: [{
              begin: "(\\|[ ]*)?" + VAR_IDENT_RE
            }]
          },
          {
            begin: "#\\(",
            end: "\\)",
            contains: [
              hljs5.APOS_STRING_MODE,
              CHAR,
              hljs5.C_NUMBER_MODE,
              SYMBOL
            ]
          }
        ]
      };
    }
    module.exports = smalltalk;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/sml.js
var require_sml = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/sml.js"(exports, module) {
    init_process_shim();
    function sml(hljs5) {
      return {
        name: "SML (Standard ML)",
        aliases: ["ml"],
        keywords: {
          $pattern: "[a-z_]\\w*!?",
          keyword: (
            /* according to Definition of Standard ML 97  */
            "abstype and andalso as case datatype do else end eqtype exception fn fun functor handle if in include infix infixr let local nonfix of op open orelse raise rec sharing sig signature struct structure then type val with withtype where while"
          ),
          built_in: (
            /* built-in types according to basis library */
            "array bool char exn int list option order real ref string substring vector unit word"
          ),
          literal: "true false NONE SOME LESS EQUAL GREATER nil"
        },
        illegal: /\/\/|>>/,
        contains: [
          {
            className: "literal",
            begin: /\[(\|\|)?\]|\(\)/,
            relevance: 0
          },
          hljs5.COMMENT(
            "\\(\\*",
            "\\*\\)",
            {
              contains: ["self"]
            }
          ),
          {
            /* type variable */
            className: "symbol",
            begin: "'[A-Za-z_](?!')[\\w']*"
            /* the grammar is ambiguous on how 'a'b should be interpreted but not the compiler */
          },
          {
            /* polymorphic variant */
            className: "type",
            begin: "`[A-Z][\\w']*"
          },
          {
            /* module or constructor */
            className: "type",
            begin: "\\b[A-Z][\\w']*",
            relevance: 0
          },
          {
            /* don't color identifiers, but safely catch all identifiers with ' */
            begin: "[a-z_]\\w*'[\\w']*"
          },
          hljs5.inherit(hljs5.APOS_STRING_MODE, {
            className: "string",
            relevance: 0
          }),
          hljs5.inherit(hljs5.QUOTE_STRING_MODE, {
            illegal: null
          }),
          {
            className: "number",
            begin: "\\b(0[xX][a-fA-F0-9_]+[Lln]?|0[oO][0-7_]+[Lln]?|0[bB][01_]+[Lln]?|[0-9][0-9_]*([Lln]|(\\.[0-9_]*)?([eE][-+]?[0-9_]+)?)?)",
            relevance: 0
          },
          {
            begin: /[-=]>/
            // relevance booster
          }
        ]
      };
    }
    module.exports = sml;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/sqf.js
var require_sqf = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/sqf.js"(exports, module) {
    init_process_shim();
    function sqf(hljs5) {
      const VARIABLE = {
        className: "variable",
        begin: /\b_+[a-zA-Z]\w*/
      };
      const FUNCTION = {
        className: "title",
        begin: /[a-zA-Z][a-zA-Z0-9]+_fnc_\w*/
      };
      const STRINGS = {
        className: "string",
        variants: [
          {
            begin: '"',
            end: '"',
            contains: [{
              begin: '""',
              relevance: 0
            }]
          },
          {
            begin: "'",
            end: "'",
            contains: [{
              begin: "''",
              relevance: 0
            }]
          }
        ]
      };
      const PREPROCESSOR = {
        className: "meta",
        begin: /#\s*[a-z]+\b/,
        end: /$/,
        keywords: {
          "meta-keyword": "define undef ifdef ifndef else endif include"
        },
        contains: [
          {
            begin: /\\\n/,
            relevance: 0
          },
          hljs5.inherit(STRINGS, {
            className: "meta-string"
          }),
          {
            className: "meta-string",
            begin: /<[^\n>]*>/,
            end: /$/,
            illegal: "\\n"
          },
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE
        ]
      };
      return {
        name: "SQF",
        case_insensitive: true,
        keywords: {
          keyword: "case catch default do else exit exitWith for forEach from if private switch then throw to try waitUntil while with",
          built_in: "abs accTime acos action actionIDs actionKeys actionKeysImages actionKeysNames actionKeysNamesArray actionName actionParams activateAddons activatedAddons activateKey add3DENConnection add3DENEventHandler add3DENLayer addAction addBackpack addBackpackCargo addBackpackCargoGlobal addBackpackGlobal addCamShake addCuratorAddons addCuratorCameraArea addCuratorEditableObjects addCuratorEditingArea addCuratorPoints addEditorObject addEventHandler addForce addGoggles addGroupIcon addHandgunItem addHeadgear addItem addItemCargo addItemCargoGlobal addItemPool addItemToBackpack addItemToUniform addItemToVest addLiveStats addMagazine addMagazineAmmoCargo addMagazineCargo addMagazineCargoGlobal addMagazineGlobal addMagazinePool addMagazines addMagazineTurret addMenu addMenuItem addMissionEventHandler addMPEventHandler addMusicEventHandler addOwnedMine addPlayerScores addPrimaryWeaponItem addPublicVariableEventHandler addRating addResources addScore addScoreSide addSecondaryWeaponItem addSwitchableUnit addTeamMember addToRemainsCollector addTorque addUniform addVehicle addVest addWaypoint addWeapon addWeaponCargo addWeaponCargoGlobal addWeaponGlobal addWeaponItem addWeaponPool addWeaponTurret admin agent agents AGLToASL aimedAtTarget aimPos airDensityRTD airplaneThrottle airportSide AISFinishHeal alive all3DENEntities allAirports allControls allCurators allCutLayers allDead allDeadMen allDisplays allGroups allMapMarkers allMines allMissionObjects allow3DMode allowCrewInImmobile allowCuratorLogicIgnoreAreas allowDamage allowDammage allowFileOperations allowFleeing allowGetIn allowSprint allPlayers allSimpleObjects allSites allTurrets allUnits allUnitsUAV allVariables ammo ammoOnPylon and animate animateBay animateDoor animatePylon animateSource animationNames animationPhase animationSourcePhase animationState append apply armoryPoints arrayIntersect asin ASLToAGL ASLToATL assert assignAsCargo assignAsCargoIndex assignAsCommander assignAsDriver assignAsGunner assignAsTurret assignCurator assignedCargo assignedCommander assignedDriver assignedGunner assignedItems assignedTarget assignedTeam assignedVehicle assignedVehicleRole assignItem assignTeam assignToAirport atan atan2 atg ATLToASL attachedObject attachedObjects attachedTo attachObject attachTo attackEnabled backpack backpackCargo backpackContainer backpackItems backpackMagazines backpackSpaceFor behaviour benchmark binocular boundingBox boundingBoxReal boundingCenter breakOut breakTo briefingName buildingExit buildingPos buttonAction buttonSetAction cadetMode call callExtension camCommand camCommit camCommitPrepared camCommitted camConstuctionSetParams camCreate camDestroy cameraEffect cameraEffectEnableHUD cameraInterest cameraOn cameraView campaignConfigFile camPreload camPreloaded camPrepareBank camPrepareDir camPrepareDive camPrepareFocus camPrepareFov camPrepareFovRange camPreparePos camPrepareRelPos camPrepareTarget camSetBank camSetDir camSetDive camSetFocus camSetFov camSetFovRange camSetPos camSetRelPos camSetTarget camTarget camUseNVG canAdd canAddItemToBackpack canAddItemToUniform canAddItemToVest cancelSimpleTaskDestination canFire canMove canSlingLoad canStand canSuspend canTriggerDynamicSimulation canUnloadInCombat canVehicleCargo captive captiveNum cbChecked cbSetChecked ceil channelEnabled cheatsEnabled checkAIFeature checkVisibility className clearAllItemsFromBackpack clearBackpackCargo clearBackpackCargoGlobal clearGroupIcons clearItemCargo clearItemCargoGlobal clearItemPool clearMagazineCargo clearMagazineCargoGlobal clearMagazinePool clearOverlay clearRadio clearWeaponCargo clearWeaponCargoGlobal clearWeaponPool clientOwner closeDialog closeDisplay closeOverlay collapseObjectTree collect3DENHistory collectiveRTD combatMode commandArtilleryFire commandChat commander commandFire commandFollow commandFSM commandGetOut commandingMenu commandMove commandRadio commandStop commandSuppressiveFire commandTarget commandWatch comment commitOverlay compile compileFinal completedFSM composeText configClasses configFile configHierarchy configName configProperties configSourceAddonList configSourceMod configSourceModList confirmSensorTarget connectTerminalToUAV controlsGroupCtrl copyFromClipboard copyToClipboard copyWaypoints cos count countEnemy countFriendly countSide countType countUnknown create3DENComposition create3DENEntity createAgent createCenter createDialog createDiaryLink createDiaryRecord createDiarySubject createDisplay createGearDialog createGroup createGuardedPoint createLocation createMarker createMarkerLocal createMenu createMine createMissionDisplay createMPCampaignDisplay createSimpleObject createSimpleTask createSite createSoundSource createTask createTeam createTrigger createUnit createVehicle createVehicleCrew createVehicleLocal crew ctAddHeader ctAddRow ctClear ctCurSel ctData ctFindHeaderRows ctFindRowHeader ctHeaderControls ctHeaderCount ctRemoveHeaders ctRemoveRows ctrlActivate ctrlAddEventHandler ctrlAngle ctrlAutoScrollDelay ctrlAutoScrollRewind ctrlAutoScrollSpeed ctrlChecked ctrlClassName ctrlCommit ctrlCommitted ctrlCreate ctrlDelete ctrlEnable ctrlEnabled ctrlFade ctrlHTMLLoaded ctrlIDC ctrlIDD ctrlMapAnimAdd ctrlMapAnimClear ctrlMapAnimCommit ctrlMapAnimDone ctrlMapCursor ctrlMapMouseOver ctrlMapScale ctrlMapScreenToWorld ctrlMapWorldToScreen ctrlModel ctrlModelDirAndUp ctrlModelScale ctrlParent ctrlParentControlsGroup ctrlPosition ctrlRemoveAllEventHandlers ctrlRemoveEventHandler ctrlScale ctrlSetActiveColor ctrlSetAngle ctrlSetAutoScrollDelay ctrlSetAutoScrollRewind ctrlSetAutoScrollSpeed ctrlSetBackgroundColor ctrlSetChecked ctrlSetEventHandler ctrlSetFade ctrlSetFocus ctrlSetFont ctrlSetFontH1 ctrlSetFontH1B ctrlSetFontH2 ctrlSetFontH2B ctrlSetFontH3 ctrlSetFontH3B ctrlSetFontH4 ctrlSetFontH4B ctrlSetFontH5 ctrlSetFontH5B ctrlSetFontH6 ctrlSetFontH6B ctrlSetFontHeight ctrlSetFontHeightH1 ctrlSetFontHeightH2 ctrlSetFontHeightH3 ctrlSetFontHeightH4 ctrlSetFontHeightH5 ctrlSetFontHeightH6 ctrlSetFontHeightSecondary ctrlSetFontP ctrlSetFontPB ctrlSetFontSecondary ctrlSetForegroundColor ctrlSetModel ctrlSetModelDirAndUp ctrlSetModelScale ctrlSetPixelPrecision ctrlSetPosition ctrlSetScale ctrlSetStructuredText ctrlSetText ctrlSetTextColor ctrlSetTooltip ctrlSetTooltipColorBox ctrlSetTooltipColorShade ctrlSetTooltipColorText ctrlShow ctrlShown ctrlText ctrlTextHeight ctrlTextWidth ctrlType ctrlVisible ctRowControls ctRowCount ctSetCurSel ctSetData ctSetHeaderTemplate ctSetRowTemplate ctSetValue ctValue curatorAddons curatorCamera curatorCameraArea curatorCameraAreaCeiling curatorCoef curatorEditableObjects curatorEditingArea curatorEditingAreaType curatorMouseOver curatorPoints curatorRegisteredObjects curatorSelected curatorWaypointCost current3DENOperation currentChannel currentCommand currentMagazine currentMagazineDetail currentMagazineDetailTurret currentMagazineTurret currentMuzzle currentNamespace currentTask currentTasks currentThrowable currentVisionMode currentWaypoint currentWeapon currentWeaponMode currentWeaponTurret currentZeroing cursorObject cursorTarget customChat customRadio cutFadeOut cutObj cutRsc cutText damage date dateToNumber daytime deActivateKey debriefingText debugFSM debugLog deg delete3DENEntities deleteAt deleteCenter deleteCollection deleteEditorObject deleteGroup deleteGroupWhenEmpty deleteIdentity deleteLocation deleteMarker deleteMarkerLocal deleteRange deleteResources deleteSite deleteStatus deleteTeam deleteVehicle deleteVehicleCrew deleteWaypoint detach detectedMines diag_activeMissionFSMs diag_activeScripts diag_activeSQFScripts diag_activeSQSScripts diag_captureFrame diag_captureFrameToFile diag_captureSlowFrame diag_codePerformance diag_drawMode diag_enable diag_enabled diag_fps diag_fpsMin diag_frameNo diag_lightNewLoad diag_list diag_log diag_logSlowFrame diag_mergeConfigFile diag_recordTurretLimits diag_setLightNew diag_tickTime diag_toggle dialog diarySubjectExists didJIP didJIPOwner difficulty difficultyEnabled difficultyEnabledRTD difficultyOption direction directSay disableAI disableCollisionWith disableConversation disableDebriefingStats disableMapIndicators disableNVGEquipment disableRemoteSensors disableSerialization disableTIEquipment disableUAVConnectability disableUserInput displayAddEventHandler displayCtrl displayParent displayRemoveAllEventHandlers displayRemoveEventHandler displaySetEventHandler dissolveTeam distance distance2D distanceSqr distributionRegion do3DENAction doArtilleryFire doFire doFollow doFSM doGetOut doMove doorPhase doStop doSuppressiveFire doTarget doWatch drawArrow drawEllipse drawIcon drawIcon3D drawLine drawLine3D drawLink drawLocation drawPolygon drawRectangle drawTriangle driver drop dynamicSimulationDistance dynamicSimulationDistanceCoef dynamicSimulationEnabled dynamicSimulationSystemEnabled echo edit3DENMissionAttributes editObject editorSetEventHandler effectiveCommander emptyPositions enableAI enableAIFeature enableAimPrecision enableAttack enableAudioFeature enableAutoStartUpRTD enableAutoTrimRTD enableCamShake enableCaustics enableChannel enableCollisionWith enableCopilot enableDebriefingStats enableDiagLegend enableDynamicSimulation enableDynamicSimulationSystem enableEndDialog enableEngineArtillery enableEnvironment enableFatigue enableGunLights enableInfoPanelComponent enableIRLasers enableMimics enablePersonTurret enableRadio enableReload enableRopeAttach enableSatNormalOnDetail enableSaving enableSentences enableSimulation enableSimulationGlobal enableStamina enableTeamSwitch enableTraffic enableUAVConnectability enableUAVWaypoints enableVehicleCargo enableVehicleSensor enableWeaponDisassembly endLoadingScreen endMission engineOn enginesIsOnRTD enginesRpmRTD enginesTorqueRTD entities environmentEnabled estimatedEndServerTime estimatedTimeLeft evalObjectArgument everyBackpack everyContainer exec execEditorScript execFSM execVM exp expectedDestination exportJIPMessages eyeDirection eyePos face faction fadeMusic fadeRadio fadeSound fadeSpeech failMission fillWeaponsFromPool find findCover findDisplay findEditorObject findEmptyPosition findEmptyPositionReady findIf findNearestEnemy finishMissionInit finite fire fireAtTarget firstBackpack flag flagAnimationPhase flagOwner flagSide flagTexture fleeing floor flyInHeight flyInHeightASL fog fogForecast fogParams forceAddUniform forcedMap forceEnd forceFlagTexture forceFollowRoad forceMap forceRespawn forceSpeed forceWalk forceWeaponFire forceWeatherChange forEachMember forEachMemberAgent forEachMemberTeam forgetTarget format formation formationDirection formationLeader formationMembers formationPosition formationTask formatText formLeader freeLook fromEditor fuel fullCrew gearIDCAmmoCount gearSlotAmmoCount gearSlotData get3DENActionState get3DENAttribute get3DENCamera get3DENConnections get3DENEntity get3DENEntityID get3DENGrid get3DENIconsVisible get3DENLayerEntities get3DENLinesVisible get3DENMissionAttribute get3DENMouseOver get3DENSelected getAimingCoef getAllEnvSoundControllers getAllHitPointsDamage getAllOwnedMines getAllSoundControllers getAmmoCargo getAnimAimPrecision getAnimSpeedCoef getArray getArtilleryAmmo getArtilleryComputerSettings getArtilleryETA getAssignedCuratorLogic getAssignedCuratorUnit getBackpackCargo getBleedingRemaining getBurningValue getCameraViewDirection getCargoIndex getCenterOfMass getClientState getClientStateNumber getCompatiblePylonMagazines getConnectedUAV getContainerMaxLoad getCursorObjectParams getCustomAimCoef getDammage getDescription getDir getDirVisual getDLCAssetsUsage getDLCAssetsUsageByName getDLCs getEditorCamera getEditorMode getEditorObjectScope getElevationOffset getEnvSoundController getFatigue getForcedFlagTexture getFriend getFSMVariable getFuelCargo getGroupIcon getGroupIconParams getGroupIcons getHideFrom getHit getHitIndex getHitPointDamage getItemCargo getMagazineCargo getMarkerColor getMarkerPos getMarkerSize getMarkerType getMass getMissionConfig getMissionConfigValue getMissionDLCs getMissionLayerEntities getModelInfo getMousePosition getMusicPlayedTime getNumber getObjectArgument getObjectChildren getObjectDLC getObjectMaterials getObjectProxy getObjectTextures getObjectType getObjectViewDistance getOxygenRemaining getPersonUsedDLCs getPilotCameraDirection getPilotCameraPosition getPilotCameraRotation getPilotCameraTarget getPlateNumber getPlayerChannel getPlayerScores getPlayerUID getPos getPosASL getPosASLVisual getPosASLW getPosATL getPosATLVisual getPosVisual getPosWorld getPylonMagazines getRelDir getRelPos getRemoteSensorsDisabled getRepairCargo getResolution getShadowDistance getShotParents getSlingLoad getSoundController getSoundControllerResult getSpeed getStamina getStatValue getSuppression getTerrainGrid getTerrainHeightASL getText getTotalDLCUsageTime getUnitLoadout getUnitTrait getUserMFDText getUserMFDvalue getVariable getVehicleCargo getWeaponCargo getWeaponSway getWingsOrientationRTD getWingsPositionRTD getWPPos glanceAt globalChat globalRadio goggles goto group groupChat groupFromNetId groupIconSelectable groupIconsVisible groupId groupOwner groupRadio groupSelectedUnits groupSelectUnit gunner gusts halt handgunItems handgunMagazine handgunWeapon handsHit hasInterface hasPilotCamera hasWeapon hcAllGroups hcGroupParams hcLeader hcRemoveAllGroups hcRemoveGroup hcSelected hcSelectGroup hcSetGroup hcShowBar hcShownBar headgear hideBody hideObject hideObjectGlobal hideSelection hint hintC hintCadet hintSilent hmd hostMission htmlLoad HUDMovementLevels humidity image importAllGroups importance in inArea inAreaArray incapacitatedState inflame inflamed infoPanel infoPanelComponentEnabled infoPanelComponents infoPanels inGameUISetEventHandler inheritsFrom initAmbientLife inPolygon inputAction inRangeOfArtillery insertEditorObject intersect is3DEN is3DENMultiplayer isAbleToBreathe isAgent isArray isAutoHoverOn isAutonomous isAutotest isBleeding isBurning isClass isCollisionLightOn isCopilotEnabled isDamageAllowed isDedicated isDLCAvailable isEngineOn isEqualTo isEqualType isEqualTypeAll isEqualTypeAny isEqualTypeArray isEqualTypeParams isFilePatchingEnabled isFlashlightOn isFlatEmpty isForcedWalk isFormationLeader isGroupDeletedWhenEmpty isHidden isInRemainsCollector isInstructorFigureEnabled isIRLaserOn isKeyActive isKindOf isLaserOn isLightOn isLocalized isManualFire isMarkedForCollection isMultiplayer isMultiplayerSolo isNil isNull isNumber isObjectHidden isObjectRTD isOnRoad isPipEnabled isPlayer isRealTime isRemoteExecuted isRemoteExecutedJIP isServer isShowing3DIcons isSimpleObject isSprintAllowed isStaminaEnabled isSteamMission isStreamFriendlyUIEnabled isText isTouchingGround isTurnedOut isTutHintsEnabled isUAVConnectable isUAVConnected isUIContext isUniformAllowed isVehicleCargo isVehicleRadarOn isVehicleSensorEnabled isWalking isWeaponDeployed isWeaponRested itemCargo items itemsWithMagazines join joinAs joinAsSilent joinSilent joinString kbAddDatabase kbAddDatabaseTargets kbAddTopic kbHasTopic kbReact kbRemoveTopic kbTell kbWasSaid keyImage keyName knowsAbout land landAt landResult language laserTarget lbAdd lbClear lbColor lbColorRight lbCurSel lbData lbDelete lbIsSelected lbPicture lbPictureRight lbSelection lbSetColor lbSetColorRight lbSetCurSel lbSetData lbSetPicture lbSetPictureColor lbSetPictureColorDisabled lbSetPictureColorSelected lbSetPictureRight lbSetPictureRightColor lbSetPictureRightColorDisabled lbSetPictureRightColorSelected lbSetSelectColor lbSetSelectColorRight lbSetSelected lbSetText lbSetTextRight lbSetTooltip lbSetValue lbSize lbSort lbSortByValue lbText lbTextRight lbValue leader leaderboardDeInit leaderboardGetRows leaderboardInit leaderboardRequestRowsFriends leaderboardsRequestUploadScore leaderboardsRequestUploadScoreKeepBest leaderboardState leaveVehicle libraryCredits libraryDisclaimers lifeState lightAttachObject lightDetachObject lightIsOn lightnings limitSpeed linearConversion lineIntersects lineIntersectsObjs lineIntersectsSurfaces lineIntersectsWith linkItem list listObjects listRemoteTargets listVehicleSensors ln lnbAddArray lnbAddColumn lnbAddRow lnbClear lnbColor lnbCurSelRow lnbData lnbDeleteColumn lnbDeleteRow lnbGetColumnsPosition lnbPicture lnbSetColor lnbSetColumnsPos lnbSetCurSelRow lnbSetData lnbSetPicture lnbSetText lnbSetValue lnbSize lnbSort lnbSortByValue lnbText lnbValue load loadAbs loadBackpack loadFile loadGame loadIdentity loadMagazine loadOverlay loadStatus loadUniform loadVest local localize locationPosition lock lockCameraTo lockCargo lockDriver locked lockedCargo lockedDriver lockedTurret lockIdentity lockTurret lockWP log logEntities logNetwork logNetworkTerminate lookAt lookAtPos magazineCargo magazines magazinesAllTurrets magazinesAmmo magazinesAmmoCargo magazinesAmmoFull magazinesDetail magazinesDetailBackpack magazinesDetailUniform magazinesDetailVest magazinesTurret magazineTurretAmmo mapAnimAdd mapAnimClear mapAnimCommit mapAnimDone mapCenterOnCamera mapGridPosition markAsFinishedOnSteam markerAlpha markerBrush markerColor markerDir markerPos markerShape markerSize markerText markerType max members menuAction menuAdd menuChecked menuClear menuCollapse menuData menuDelete menuEnable menuEnabled menuExpand menuHover menuPicture menuSetAction menuSetCheck menuSetData menuSetPicture menuSetValue menuShortcut menuShortcutText menuSize menuSort menuText menuURL menuValue min mineActive mineDetectedBy missionConfigFile missionDifficulty missionName missionNamespace missionStart missionVersion mod modelToWorld modelToWorldVisual modelToWorldVisualWorld modelToWorldWorld modParams moonIntensity moonPhase morale move move3DENCamera moveInAny moveInCargo moveInCommander moveInDriver moveInGunner moveInTurret moveObjectToEnd moveOut moveTime moveTo moveToCompleted moveToFailed musicVolume name nameSound nearEntities nearestBuilding nearestLocation nearestLocations nearestLocationWithDubbing nearestObject nearestObjects nearestTerrainObjects nearObjects nearObjectsReady nearRoads nearSupplies nearTargets needReload netId netObjNull newOverlay nextMenuItemIndex nextWeatherChange nMenuItems not numberOfEnginesRTD numberToDate objectCurators objectFromNetId objectParent objStatus onBriefingGroup onBriefingNotes onBriefingPlan onBriefingTeamSwitch onCommandModeChanged onDoubleClick onEachFrame onGroupIconClick onGroupIconOverEnter onGroupIconOverLeave onHCGroupSelectionChanged onMapSingleClick onPlayerConnected onPlayerDisconnected onPreloadFinished onPreloadStarted onShowNewObject onTeamSwitch openCuratorInterface openDLCPage openMap openSteamApp openYoutubeVideo or orderGetIn overcast overcastForecast owner param params parseNumber parseSimpleArray parseText parsingNamespace particlesQuality pickWeaponPool pitch pixelGrid pixelGridBase pixelGridNoUIScale pixelH pixelW playableSlotsNumber playableUnits playAction playActionNow player playerRespawnTime playerSide playersNumber playGesture playMission playMove playMoveNow playMusic playScriptedMission playSound playSound3D position positionCameraToWorld posScreenToWorld posWorldToScreen ppEffectAdjust ppEffectCommit ppEffectCommitted ppEffectCreate ppEffectDestroy ppEffectEnable ppEffectEnabled ppEffectForceInNVG precision preloadCamera preloadObject preloadSound preloadTitleObj preloadTitleRsc preprocessFile preprocessFileLineNumbers primaryWeapon primaryWeaponItems primaryWeaponMagazine priority processDiaryLink productVersion profileName profileNamespace profileNameSteam progressLoadingScreen progressPosition progressSetPosition publicVariable publicVariableClient publicVariableServer pushBack pushBackUnique putWeaponPool queryItemsPool queryMagazinePool queryWeaponPool rad radioChannelAdd radioChannelCreate radioChannelRemove radioChannelSetCallSign radioChannelSetLabel radioVolume rain rainbow random rank rankId rating rectangular registeredTasks registerTask reload reloadEnabled remoteControl remoteExec remoteExecCall remoteExecutedOwner remove3DENConnection remove3DENEventHandler remove3DENLayer removeAction removeAll3DENEventHandlers removeAllActions removeAllAssignedItems removeAllContainers removeAllCuratorAddons removeAllCuratorCameraAreas removeAllCuratorEditingAreas removeAllEventHandlers removeAllHandgunItems removeAllItems removeAllItemsWithMagazines removeAllMissionEventHandlers removeAllMPEventHandlers removeAllMusicEventHandlers removeAllOwnedMines removeAllPrimaryWeaponItems removeAllWeapons removeBackpack removeBackpackGlobal removeCuratorAddons removeCuratorCameraArea removeCuratorEditableObjects removeCuratorEditingArea removeDrawIcon removeDrawLinks removeEventHandler removeFromRemainsCollector removeGoggles removeGroupIcon removeHandgunItem removeHeadgear removeItem removeItemFromBackpack removeItemFromUniform removeItemFromVest removeItems removeMagazine removeMagazineGlobal removeMagazines removeMagazinesTurret removeMagazineTurret removeMenuItem removeMissionEventHandler removeMPEventHandler removeMusicEventHandler removeOwnedMine removePrimaryWeaponItem removeSecondaryWeaponItem removeSimpleTask removeSwitchableUnit removeTeamMember removeUniform removeVest removeWeapon removeWeaponAttachmentCargo removeWeaponCargo removeWeaponGlobal removeWeaponTurret reportRemoteTarget requiredVersion resetCamShake resetSubgroupDirection resize resources respawnVehicle restartEditorCamera reveal revealMine reverse reversedMouseY roadAt roadsConnectedTo roleDescription ropeAttachedObjects ropeAttachedTo ropeAttachEnabled ropeAttachTo ropeCreate ropeCut ropeDestroy ropeDetach ropeEndPosition ropeLength ropes ropeUnwind ropeUnwound rotorsForcesRTD rotorsRpmRTD round runInitScript safeZoneH safeZoneW safeZoneWAbs safeZoneX safeZoneXAbs safeZoneY save3DENInventory saveGame saveIdentity saveJoysticks saveOverlay saveProfileNamespace saveStatus saveVar savingEnabled say say2D say3D scopeName score scoreSide screenshot screenToWorld scriptDone scriptName scudState secondaryWeapon secondaryWeaponItems secondaryWeaponMagazine select selectBestPlaces selectDiarySubject selectedEditorObjects selectEditorObject selectionNames selectionPosition selectLeader selectMax selectMin selectNoPlayer selectPlayer selectRandom selectRandomWeighted selectWeapon selectWeaponTurret sendAUMessage sendSimpleCommand sendTask sendTaskResult sendUDPMessage serverCommand serverCommandAvailable serverCommandExecutable serverName serverTime set set3DENAttribute set3DENAttributes set3DENGrid set3DENIconsVisible set3DENLayer set3DENLinesVisible set3DENLogicType set3DENMissionAttribute set3DENMissionAttributes set3DENModelsVisible set3DENObjectType set3DENSelected setAccTime setActualCollectiveRTD setAirplaneThrottle setAirportSide setAmmo setAmmoCargo setAmmoOnPylon setAnimSpeedCoef setAperture setApertureNew setArmoryPoints setAttributes setAutonomous setBehaviour setBleedingRemaining setBrakesRTD setCameraInterest setCamShakeDefParams setCamShakeParams setCamUseTI setCaptive setCenterOfMass setCollisionLight setCombatMode setCompassOscillation setConvoySeparation setCuratorCameraAreaCeiling setCuratorCoef setCuratorEditingAreaType setCuratorWaypointCost setCurrentChannel setCurrentTask setCurrentWaypoint setCustomAimCoef setCustomWeightRTD setDamage setDammage setDate setDebriefingText setDefaultCamera setDestination setDetailMapBlendPars setDir setDirection setDrawIcon setDriveOnPath setDropInterval setDynamicSimulationDistance setDynamicSimulationDistanceCoef setEditorMode setEditorObjectScope setEffectCondition setEngineRPMRTD setFace setFaceAnimation setFatigue setFeatureType setFlagAnimationPhase setFlagOwner setFlagSide setFlagTexture setFog setFormation setFormationTask setFormDir setFriend setFromEditor setFSMVariable setFuel setFuelCargo setGroupIcon setGroupIconParams setGroupIconsSelectable setGroupIconsVisible setGroupId setGroupIdGlobal setGroupOwner setGusts setHideBehind setHit setHitIndex setHitPointDamage setHorizonParallaxCoef setHUDMovementLevels setIdentity setImportance setInfoPanel setLeader setLightAmbient setLightAttenuation setLightBrightness setLightColor setLightDayLight setLightFlareMaxDistance setLightFlareSize setLightIntensity setLightnings setLightUseFlare setLocalWindParams setMagazineTurretAmmo setMarkerAlpha setMarkerAlphaLocal setMarkerBrush setMarkerBrushLocal setMarkerColor setMarkerColorLocal setMarkerDir setMarkerDirLocal setMarkerPos setMarkerPosLocal setMarkerShape setMarkerShapeLocal setMarkerSize setMarkerSizeLocal setMarkerText setMarkerTextLocal setMarkerType setMarkerTypeLocal setMass setMimic setMousePosition setMusicEffect setMusicEventHandler setName setNameSound setObjectArguments setObjectMaterial setObjectMaterialGlobal setObjectProxy setObjectTexture setObjectTextureGlobal setObjectViewDistance setOvercast setOwner setOxygenRemaining setParticleCircle setParticleClass setParticleFire setParticleParams setParticleRandom setPilotCameraDirection setPilotCameraRotation setPilotCameraTarget setPilotLight setPiPEffect setPitch setPlateNumber setPlayable setPlayerRespawnTime setPos setPosASL setPosASL2 setPosASLW setPosATL setPosition setPosWorld setPylonLoadOut setPylonsPriority setRadioMsg setRain setRainbow setRandomLip setRank setRectangular setRepairCargo setRotorBrakeRTD setShadowDistance setShotParents setSide setSimpleTaskAlwaysVisible setSimpleTaskCustomData setSimpleTaskDescription setSimpleTaskDestination setSimpleTaskTarget setSimpleTaskType setSimulWeatherLayers setSize setSkill setSlingLoad setSoundEffect setSpeaker setSpeech setSpeedMode setStamina setStaminaScheme setStatValue setSuppression setSystemOfUnits setTargetAge setTaskMarkerOffset setTaskResult setTaskState setTerrainGrid setText setTimeMultiplier setTitleEffect setTrafficDensity setTrafficDistance setTrafficGap setTrafficSpeed setTriggerActivation setTriggerArea setTriggerStatements setTriggerText setTriggerTimeout setTriggerType setType setUnconscious setUnitAbility setUnitLoadout setUnitPos setUnitPosWeak setUnitRank setUnitRecoilCoefficient setUnitTrait setUnloadInCombat setUserActionText setUserMFDText setUserMFDvalue setVariable setVectorDir setVectorDirAndUp setVectorUp setVehicleAmmo setVehicleAmmoDef setVehicleArmor setVehicleCargo setVehicleId setVehicleLock setVehiclePosition setVehicleRadar setVehicleReceiveRemoteTargets setVehicleReportOwnPosition setVehicleReportRemoteTargets setVehicleTIPars setVehicleVarName setVelocity setVelocityModelSpace setVelocityTransformation setViewDistance setVisibleIfTreeCollapsed setWantedRPMRTD setWaves setWaypointBehaviour setWaypointCombatMode setWaypointCompletionRadius setWaypointDescription setWaypointForceBehaviour setWaypointFormation setWaypointHousePosition setWaypointLoiterRadius setWaypointLoiterType setWaypointName setWaypointPosition setWaypointScript setWaypointSpeed setWaypointStatements setWaypointTimeout setWaypointType setWaypointVisible setWeaponReloadingTime setWind setWindDir setWindForce setWindStr setWingForceScaleRTD setWPPos show3DIcons showChat showCinemaBorder showCommandingMenu showCompass showCuratorCompass showGPS showHUD showLegend showMap shownArtilleryComputer shownChat shownCompass shownCuratorCompass showNewEditorObject shownGPS shownHUD shownMap shownPad shownRadio shownScoretable shownUAVFeed shownWarrant shownWatch showPad showRadio showScoretable showSubtitles showUAVFeed showWarrant showWatch showWaypoint showWaypoints side sideChat sideEnemy sideFriendly sideRadio simpleTasks simulationEnabled simulCloudDensity simulCloudOcclusion simulInClouds simulWeatherSync sin size sizeOf skill skillFinal skipTime sleep sliderPosition sliderRange sliderSetPosition sliderSetRange sliderSetSpeed sliderSpeed slingLoadAssistantShown soldierMagazines someAmmo sort soundVolume spawn speaker speed speedMode splitString sqrt squadParams stance startLoadingScreen step stop stopEngineRTD stopped str sunOrMoon supportInfo suppressFor surfaceIsWater surfaceNormal surfaceType swimInDepth switchableUnits switchAction switchCamera switchGesture switchLight switchMove synchronizedObjects synchronizedTriggers synchronizedWaypoints synchronizeObjectsAdd synchronizeObjectsRemove synchronizeTrigger synchronizeWaypoint systemChat systemOfUnits tan targetKnowledge targets targetsAggregate targetsQuery taskAlwaysVisible taskChildren taskCompleted taskCustomData taskDescription taskDestination taskHint taskMarkerOffset taskParent taskResult taskState taskType teamMember teamName teams teamSwitch teamSwitchEnabled teamType terminate terrainIntersect terrainIntersectASL terrainIntersectAtASL text textLog textLogFormat tg time timeMultiplier titleCut titleFadeOut titleObj titleRsc titleText toArray toFixed toLower toString toUpper triggerActivated triggerActivation triggerArea triggerAttachedVehicle triggerAttachObject triggerAttachVehicle triggerDynamicSimulation triggerStatements triggerText triggerTimeout triggerTimeoutCurrent triggerType turretLocal turretOwner turretUnit tvAdd tvClear tvCollapse tvCollapseAll tvCount tvCurSel tvData tvDelete tvExpand tvExpandAll tvPicture tvSetColor tvSetCurSel tvSetData tvSetPicture tvSetPictureColor tvSetPictureColorDisabled tvSetPictureColorSelected tvSetPictureRight tvSetPictureRightColor tvSetPictureRightColorDisabled tvSetPictureRightColorSelected tvSetText tvSetTooltip tvSetValue tvSort tvSortByValue tvText tvTooltip tvValue type typeName typeOf UAVControl uiNamespace uiSleep unassignCurator unassignItem unassignTeam unassignVehicle underwater uniform uniformContainer uniformItems uniformMagazines unitAddons unitAimPosition unitAimPositionVisual unitBackpack unitIsUAV unitPos unitReady unitRecoilCoefficient units unitsBelowHeight unlinkItem unlockAchievement unregisterTask updateDrawIcon updateMenuItem updateObjectTree useAISteeringComponent useAudioTimeForMoves userInputDisabled vectorAdd vectorCos vectorCrossProduct vectorDiff vectorDir vectorDirVisual vectorDistance vectorDistanceSqr vectorDotProduct vectorFromTo vectorMagnitude vectorMagnitudeSqr vectorModelToWorld vectorModelToWorldVisual vectorMultiply vectorNormalized vectorUp vectorUpVisual vectorWorldToModel vectorWorldToModelVisual vehicle vehicleCargoEnabled vehicleChat vehicleRadio vehicleReceiveRemoteTargets vehicleReportOwnPosition vehicleReportRemoteTargets vehicles vehicleVarName velocity velocityModelSpace verifySignature vest vestContainer vestItems vestMagazines viewDistance visibleCompass visibleGPS visibleMap visiblePosition visiblePositionASL visibleScoretable visibleWatch waves waypointAttachedObject waypointAttachedVehicle waypointAttachObject waypointAttachVehicle waypointBehaviour waypointCombatMode waypointCompletionRadius waypointDescription waypointForceBehaviour waypointFormation waypointHousePosition waypointLoiterRadius waypointLoiterType waypointName waypointPosition waypoints waypointScript waypointsEnabledUAV waypointShow waypointSpeed waypointStatements waypointTimeout waypointTimeoutCurrent waypointType waypointVisible weaponAccessories weaponAccessoriesCargo weaponCargo weaponDirection weaponInertia weaponLowered weapons weaponsItems weaponsItemsCargo weaponState weaponsTurret weightRTD WFSideText wind ",
          literal: "blufor civilian configNull controlNull displayNull east endl false grpNull independent lineBreak locationNull nil objNull opfor pi resistance scriptNull sideAmbientLife sideEmpty sideLogic sideUnknown taskNull teamMemberNull true west"
        },
        contains: [
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          hljs5.NUMBER_MODE,
          VARIABLE,
          FUNCTION,
          STRINGS,
          PREPROCESSOR
        ],
        illegal: /#|^\$ /
      };
    }
    module.exports = sqf;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/sql_more.js
var require_sql_more = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/sql_more.js"(exports, module) {
    init_process_shim();
    function sql_more(hljs5) {
      var COMMENT_MODE = hljs5.COMMENT("--", "$");
      return {
        name: "SQL (more)",
        aliases: ["mysql", "oracle"],
        disableAutodetect: true,
        case_insensitive: true,
        illegal: /[<>{}*]/,
        contains: [
          {
            beginKeywords: "begin end start commit rollback savepoint lock alter create drop rename call delete do handler insert load replace select truncate update set show pragma grant merge describe use explain help declare prepare execute deallocate release unlock purge reset change stop analyze cache flush optimize repair kill install uninstall checksum restore check backup revoke comment values with",
            end: /;/,
            endsWithParent: true,
            keywords: {
              $pattern: /[\w\.]+/,
              keyword: "as abort abs absolute acc acce accep accept access accessed accessible account acos action activate add addtime admin administer advanced advise aes_decrypt aes_encrypt after agent aggregate ali alia alias all allocate allow alter always analyze ancillary and anti any anydata anydataset anyschema anytype apply archive archived archivelog are as asc ascii asin assembly assertion associate asynchronous at atan atn2 attr attri attrib attribu attribut attribute attributes audit authenticated authentication authid authors auto autoallocate autodblink autoextend automatic availability avg backup badfile basicfile before begin beginning benchmark between bfile bfile_base big bigfile bin binary_double binary_float binlog bit_and bit_count bit_length bit_or bit_xor bitmap blob_base block blocksize body both bound bucket buffer_cache buffer_pool build bulk by byte byteordermark bytes cache caching call calling cancel capacity cascade cascaded case cast catalog category ceil ceiling chain change changed char_base char_length character_length characters characterset charindex charset charsetform charsetid check checksum checksum_agg child choose chr chunk class cleanup clear client clob clob_base clone close cluster_id cluster_probability cluster_set clustering coalesce coercibility col collate collation collect colu colum column column_value columns columns_updated comment commit compact compatibility compiled complete composite_limit compound compress compute concat concat_ws concurrent confirm conn connec connect connect_by_iscycle connect_by_isleaf connect_by_root connect_time connection consider consistent constant constraint constraints constructor container content contents context contributors controlfile conv convert convert_tz corr corr_k corr_s corresponding corruption cos cost count count_big counted covar_pop covar_samp cpu_per_call cpu_per_session crc32 create creation critical cross cube cume_dist curdate current current_date current_time current_timestamp current_user cursor curtime customdatum cycle data database databases datafile datafiles datalength date_add date_cache date_format date_sub dateadd datediff datefromparts datename datepart datetime2fromparts day day_to_second dayname dayofmonth dayofweek dayofyear days db_role_change dbtimezone ddl deallocate declare decode decompose decrement decrypt deduplicate def defa defau defaul default defaults deferred defi defin define degrees delayed delegate delete delete_all delimited demand dense_rank depth dequeue des_decrypt des_encrypt des_key_file desc descr descri describ describe descriptor deterministic diagnostics difference dimension direct_load directory disable disable_all disallow disassociate discardfile disconnect diskgroup distinct distinctrow distribute distributed div do document domain dotnet double downgrade drop dumpfile duplicate duration each edition editionable editions element ellipsis else elsif elt empty enable enable_all enclosed encode encoding encrypt end end-exec endian enforced engine engines enqueue enterprise entityescaping eomonth error errors escaped evalname evaluate event eventdata events except exception exceptions exchange exclude excluding execu execut execute exempt exists exit exp expire explain explode export export_set extended extent external external_1 external_2 externally extract failed failed_login_attempts failover failure far fast feature_set feature_value fetch field fields file file_name_convert filesystem_like_logging final finish first first_value fixed flash_cache flashback floor flush following follows for forall force foreign form forma format found found_rows freelist freelists freepools fresh from from_base64 from_days ftp full function general generated get get_format get_lock getdate getutcdate global global_name globally go goto grant grants greatest group group_concat group_id grouping grouping_id groups gtid_subtract guarantee guard handler hash hashkeys having hea head headi headin heading heap help hex hierarchy high high_priority hosts hour hours http id ident_current ident_incr ident_seed identified identity idle_time if ifnull ignore iif ilike ilm immediate import in include including increment index indexes indexing indextype indicator indices inet6_aton inet6_ntoa inet_aton inet_ntoa infile initial initialized initially initrans inmemory inner innodb input insert install instance instantiable instr interface interleaved intersect into invalidate invisible is is_free_lock is_ipv4 is_ipv4_compat is_not is_not_null is_used_lock isdate isnull isolation iterate java join json json_exists keep keep_duplicates key keys kill language large last last_day last_insert_id last_value lateral lax lcase lead leading least leaves left len lenght length less level levels library like like2 like4 likec limit lines link list listagg little ln load load_file lob lobs local localtime localtimestamp locate locator lock locked log log10 log2 logfile logfiles logging logical logical_reads_per_call logoff logon logs long loop low low_priority lower lpad lrtrim ltrim main make_set makedate maketime managed management manual map mapping mask master master_pos_wait match matched materialized max maxextents maximize maxinstances maxlen maxlogfiles maxloghistory maxlogmembers maxsize maxtrans md5 measures median medium member memcompress memory merge microsecond mid migration min minextents minimum mining minus minute minutes minvalue missing mod mode model modification modify module monitoring month months mount move movement multiset mutex name name_const names nan national native natural nav nchar nclob nested never new newline next nextval no no_write_to_binlog noarchivelog noaudit nobadfile nocheck nocompress nocopy nocycle nodelay nodiscardfile noentityescaping noguarantee nokeep nologfile nomapping nomaxvalue nominimize nominvalue nomonitoring none noneditionable nonschema noorder nopr nopro noprom nopromp noprompt norely noresetlogs noreverse normal norowdependencies noschemacheck noswitch not nothing notice notnull notrim novalidate now nowait nth_value nullif nulls num numb numbe nvarchar nvarchar2 object ocicoll ocidate ocidatetime ociduration ociinterval ociloblocator ocinumber ociref ocirefcursor ocirowid ocistring ocitype oct octet_length of off offline offset oid oidindex old on online only opaque open operations operator optimal optimize option optionally or oracle oracle_date oradata ord ordaudio orddicom orddoc order ordimage ordinality ordvideo organization orlany orlvary out outer outfile outline output over overflow overriding package pad parallel parallel_enable parameters parent parse partial partition partitions pascal passing password password_grace_time password_lock_time password_reuse_max password_reuse_time password_verify_function patch path patindex pctincrease pctthreshold pctused pctversion percent percent_rank percentile_cont percentile_disc performance period period_add period_diff permanent physical pi pipe pipelined pivot pluggable plugin policy position post_transaction pow power pragma prebuilt precedes preceding precision prediction prediction_cost prediction_details prediction_probability prediction_set prepare present preserve prior priority private private_sga privileges procedural procedure procedure_analyze processlist profiles project prompt protection public publishingservername purge quarter query quick quiesce quota quotename radians raise rand range rank raw read reads readsize rebuild record records recover recovery recursive recycle redo reduced ref reference referenced references referencing refresh regexp_like register regr_avgx regr_avgy regr_count regr_intercept regr_r2 regr_slope regr_sxx regr_sxy reject rekey relational relative relaylog release release_lock relies_on relocate rely rem remainder rename repair repeat replace replicate replication required reset resetlogs resize resource respect restore restricted result result_cache resumable resume retention return returning returns reuse reverse revoke right rlike role roles rollback rolling rollup round row row_count rowdependencies rowid rownum rows rtrim rules safe salt sample save savepoint sb1 sb2 sb4 scan schema schemacheck scn scope scroll sdo_georaster sdo_topo_geometry search sec_to_time second seconds section securefile security seed segment select self semi sequence sequential serializable server servererror session session_user sessions_per_user set sets settings sha sha1 sha2 share shared shared_pool short show shrink shutdown si_averagecolor si_colorhistogram si_featurelist si_positionalcolor si_stillimage si_texture siblings sid sign sin size size_t sizes skip slave sleep smalldatetimefromparts smallfile snapshot some soname sort soundex source space sparse spfile split sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_small_result sql_variant_property sqlcode sqldata sqlerror sqlname sqlstate sqrt square standalone standby start starting startup statement static statistics stats_binomial_test stats_crosstab stats_ks_test stats_mode stats_mw_test stats_one_way_anova stats_t_test_ stats_t_test_indep stats_t_test_one stats_t_test_paired stats_wsr_test status std stddev stddev_pop stddev_samp stdev stop storage store stored str str_to_date straight_join strcmp strict string struct stuff style subdate subpartition subpartitions substitutable substr substring subtime subtring_index subtype success sum suspend switch switchoffset switchover sync synchronous synonym sys sys_xmlagg sysasm sysaux sysdate sysdatetimeoffset sysdba sysoper system system_user sysutcdatetime table tables tablespace tablesample tan tdo template temporary terminated tertiary_weights test than then thread through tier ties time time_format time_zone timediff timefromparts timeout timestamp timestampadd timestampdiff timezone_abbr timezone_minute timezone_region to to_base64 to_date to_days to_seconds todatetimeoffset trace tracking transaction transactional translate translation treat trigger trigger_nestlevel triggers trim truncate try_cast try_convert try_parse type ub1 ub2 ub4 ucase unarchived unbounded uncompress under undo unhex unicode uniform uninstall union unique unix_timestamp unknown unlimited unlock unnest unpivot unrecoverable unsafe unsigned until untrusted unusable unused update updated upgrade upped upper upsert url urowid usable usage use use_stored_outlines user user_data user_resources users using utc_date utc_timestamp uuid uuid_short validate validate_password_strength validation valist value values var var_samp varcharc vari varia variab variabl variable variables variance varp varraw varrawc varray verify version versions view virtual visible void wait wallet warning warnings week weekday weekofyear wellformed when whene whenev wheneve whenever where while whitespace window with within without work wrapped xdb xml xmlagg xmlattributes xmlcast xmlcolattval xmlelement xmlexists xmlforest xmlindex xmlnamespaces xmlpi xmlquery xmlroot xmlschema xmlserialize xmltable xmltype xor year year_to_month years yearweek",
              literal: "true false null unknown",
              built_in: "array bigint binary bit blob bool boolean char character date dec decimal float int int8 integer interval number numeric real record serial serial8 smallint text time timestamp tinyint varchar varchar2 varying void"
            },
            contains: [
              {
                className: "string",
                begin: "'",
                end: "'",
                contains: [{ begin: "''" }]
              },
              {
                className: "string",
                begin: '"',
                end: '"',
                contains: [{ begin: '""' }]
              },
              {
                className: "string",
                begin: "`",
                end: "`"
              },
              hljs5.C_NUMBER_MODE,
              hljs5.C_BLOCK_COMMENT_MODE,
              COMMENT_MODE,
              hljs5.HASH_COMMENT_MODE
            ]
          },
          hljs5.C_BLOCK_COMMENT_MODE,
          COMMENT_MODE,
          hljs5.HASH_COMMENT_MODE
        ]
      };
    }
    module.exports = sql_more;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/sql.js
var require_sql = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/sql.js"(exports, module) {
    init_process_shim();
    function source(re2) {
      if (!re2) return null;
      if (typeof re2 === "string") return re2;
      return re2.source;
    }
    function concat(...args) {
      const joined = args.map((x2) => source(x2)).join("");
      return joined;
    }
    function either(...args) {
      const joined = "(" + args.map((x2) => source(x2)).join("|") + ")";
      return joined;
    }
    function sql2(hljs5) {
      const COMMENT_MODE = hljs5.COMMENT("--", "$");
      const STRING = {
        className: "string",
        variants: [
          {
            begin: /'/,
            end: /'/,
            contains: [
              { begin: /''/ }
            ]
          }
        ]
      };
      const QUOTED_IDENTIFIER = {
        begin: /"/,
        end: /"/,
        contains: [{ begin: /""/ }]
      };
      const LITERALS3 = [
        "true",
        "false",
        // Not sure it's correct to call NULL literal, and clauses like IS [NOT] NULL look strange that way.
        // "null",
        "unknown"
      ];
      const MULTI_WORD_TYPES = [
        "double precision",
        "large object",
        "with timezone",
        "without timezone"
      ];
      const TYPES3 = [
        "bigint",
        "binary",
        "blob",
        "boolean",
        "char",
        "character",
        "clob",
        "date",
        "dec",
        "decfloat",
        "decimal",
        "float",
        "int",
        "integer",
        "interval",
        "nchar",
        "nclob",
        "national",
        "numeric",
        "real",
        "row",
        "smallint",
        "time",
        "timestamp",
        "varchar",
        "varying",
        // modifier (character varying)
        "varbinary"
      ];
      const NON_RESERVED_WORDS = [
        "add",
        "asc",
        "collation",
        "desc",
        "final",
        "first",
        "last",
        "view"
      ];
      const RESERVED_WORDS = [
        "abs",
        "acos",
        "all",
        "allocate",
        "alter",
        "and",
        "any",
        "are",
        "array",
        "array_agg",
        "array_max_cardinality",
        "as",
        "asensitive",
        "asin",
        "asymmetric",
        "at",
        "atan",
        "atomic",
        "authorization",
        "avg",
        "begin",
        "begin_frame",
        "begin_partition",
        "between",
        "bigint",
        "binary",
        "blob",
        "boolean",
        "both",
        "by",
        "call",
        "called",
        "cardinality",
        "cascaded",
        "case",
        "cast",
        "ceil",
        "ceiling",
        "char",
        "char_length",
        "character",
        "character_length",
        "check",
        "classifier",
        "clob",
        "close",
        "coalesce",
        "collate",
        "collect",
        "column",
        "commit",
        "condition",
        "connect",
        "constraint",
        "contains",
        "convert",
        "copy",
        "corr",
        "corresponding",
        "cos",
        "cosh",
        "count",
        "covar_pop",
        "covar_samp",
        "create",
        "cross",
        "cube",
        "cume_dist",
        "current",
        "current_catalog",
        "current_date",
        "current_default_transform_group",
        "current_path",
        "current_role",
        "current_row",
        "current_schema",
        "current_time",
        "current_timestamp",
        "current_path",
        "current_role",
        "current_transform_group_for_type",
        "current_user",
        "cursor",
        "cycle",
        "date",
        "day",
        "deallocate",
        "dec",
        "decimal",
        "decfloat",
        "declare",
        "default",
        "define",
        "delete",
        "dense_rank",
        "deref",
        "describe",
        "deterministic",
        "disconnect",
        "distinct",
        "double",
        "drop",
        "dynamic",
        "each",
        "element",
        "else",
        "empty",
        "end",
        "end_frame",
        "end_partition",
        "end-exec",
        "equals",
        "escape",
        "every",
        "except",
        "exec",
        "execute",
        "exists",
        "exp",
        "external",
        "extract",
        "false",
        "fetch",
        "filter",
        "first_value",
        "float",
        "floor",
        "for",
        "foreign",
        "frame_row",
        "free",
        "from",
        "full",
        "function",
        "fusion",
        "get",
        "global",
        "grant",
        "group",
        "grouping",
        "groups",
        "having",
        "hold",
        "hour",
        "identity",
        "in",
        "indicator",
        "initial",
        "inner",
        "inout",
        "insensitive",
        "insert",
        "int",
        "integer",
        "intersect",
        "intersection",
        "interval",
        "into",
        "is",
        "join",
        "json_array",
        "json_arrayagg",
        "json_exists",
        "json_object",
        "json_objectagg",
        "json_query",
        "json_table",
        "json_table_primitive",
        "json_value",
        "lag",
        "language",
        "large",
        "last_value",
        "lateral",
        "lead",
        "leading",
        "left",
        "like",
        "like_regex",
        "listagg",
        "ln",
        "local",
        "localtime",
        "localtimestamp",
        "log",
        "log10",
        "lower",
        "match",
        "match_number",
        "match_recognize",
        "matches",
        "max",
        "member",
        "merge",
        "method",
        "min",
        "minute",
        "mod",
        "modifies",
        "module",
        "month",
        "multiset",
        "national",
        "natural",
        "nchar",
        "nclob",
        "new",
        "no",
        "none",
        "normalize",
        "not",
        "nth_value",
        "ntile",
        "null",
        "nullif",
        "numeric",
        "octet_length",
        "occurrences_regex",
        "of",
        "offset",
        "old",
        "omit",
        "on",
        "one",
        "only",
        "open",
        "or",
        "order",
        "out",
        "outer",
        "over",
        "overlaps",
        "overlay",
        "parameter",
        "partition",
        "pattern",
        "per",
        "percent",
        "percent_rank",
        "percentile_cont",
        "percentile_disc",
        "period",
        "portion",
        "position",
        "position_regex",
        "power",
        "precedes",
        "precision",
        "prepare",
        "primary",
        "procedure",
        "ptf",
        "range",
        "rank",
        "reads",
        "real",
        "recursive",
        "ref",
        "references",
        "referencing",
        "regr_avgx",
        "regr_avgy",
        "regr_count",
        "regr_intercept",
        "regr_r2",
        "regr_slope",
        "regr_sxx",
        "regr_sxy",
        "regr_syy",
        "release",
        "result",
        "return",
        "returns",
        "revoke",
        "right",
        "rollback",
        "rollup",
        "row",
        "row_number",
        "rows",
        "running",
        "savepoint",
        "scope",
        "scroll",
        "search",
        "second",
        "seek",
        "select",
        "sensitive",
        "session_user",
        "set",
        "show",
        "similar",
        "sin",
        "sinh",
        "skip",
        "smallint",
        "some",
        "specific",
        "specifictype",
        "sql",
        "sqlexception",
        "sqlstate",
        "sqlwarning",
        "sqrt",
        "start",
        "static",
        "stddev_pop",
        "stddev_samp",
        "submultiset",
        "subset",
        "substring",
        "substring_regex",
        "succeeds",
        "sum",
        "symmetric",
        "system",
        "system_time",
        "system_user",
        "table",
        "tablesample",
        "tan",
        "tanh",
        "then",
        "time",
        "timestamp",
        "timezone_hour",
        "timezone_minute",
        "to",
        "trailing",
        "translate",
        "translate_regex",
        "translation",
        "treat",
        "trigger",
        "trim",
        "trim_array",
        "true",
        "truncate",
        "uescape",
        "union",
        "unique",
        "unknown",
        "unnest",
        "update   ",
        "upper",
        "user",
        "using",
        "value",
        "values",
        "value_of",
        "var_pop",
        "var_samp",
        "varbinary",
        "varchar",
        "varying",
        "versioning",
        "when",
        "whenever",
        "where",
        "width_bucket",
        "window",
        "with",
        "within",
        "without",
        "year"
      ];
      const RESERVED_FUNCTIONS = [
        "abs",
        "acos",
        "array_agg",
        "asin",
        "atan",
        "avg",
        "cast",
        "ceil",
        "ceiling",
        "coalesce",
        "corr",
        "cos",
        "cosh",
        "count",
        "covar_pop",
        "covar_samp",
        "cume_dist",
        "dense_rank",
        "deref",
        "element",
        "exp",
        "extract",
        "first_value",
        "floor",
        "json_array",
        "json_arrayagg",
        "json_exists",
        "json_object",
        "json_objectagg",
        "json_query",
        "json_table",
        "json_table_primitive",
        "json_value",
        "lag",
        "last_value",
        "lead",
        "listagg",
        "ln",
        "log",
        "log10",
        "lower",
        "max",
        "min",
        "mod",
        "nth_value",
        "ntile",
        "nullif",
        "percent_rank",
        "percentile_cont",
        "percentile_disc",
        "position",
        "position_regex",
        "power",
        "rank",
        "regr_avgx",
        "regr_avgy",
        "regr_count",
        "regr_intercept",
        "regr_r2",
        "regr_slope",
        "regr_sxx",
        "regr_sxy",
        "regr_syy",
        "row_number",
        "sin",
        "sinh",
        "sqrt",
        "stddev_pop",
        "stddev_samp",
        "substring",
        "substring_regex",
        "sum",
        "tan",
        "tanh",
        "translate",
        "translate_regex",
        "treat",
        "trim",
        "trim_array",
        "unnest",
        "upper",
        "value_of",
        "var_pop",
        "var_samp",
        "width_bucket"
      ];
      const POSSIBLE_WITHOUT_PARENS = [
        "current_catalog",
        "current_date",
        "current_default_transform_group",
        "current_path",
        "current_role",
        "current_schema",
        "current_transform_group_for_type",
        "current_user",
        "session_user",
        "system_time",
        "system_user",
        "current_time",
        "localtime",
        "current_timestamp",
        "localtimestamp"
      ];
      const COMBOS = [
        "create table",
        "insert into",
        "primary key",
        "foreign key",
        "not null",
        "alter table",
        "add constraint",
        "grouping sets",
        "on overflow",
        "character set",
        "respect nulls",
        "ignore nulls",
        "nulls first",
        "nulls last",
        "depth first",
        "breadth first"
      ];
      const FUNCTIONS = RESERVED_FUNCTIONS;
      const KEYWORDS3 = [...RESERVED_WORDS, ...NON_RESERVED_WORDS].filter((keyword) => {
        return !RESERVED_FUNCTIONS.includes(keyword);
      });
      const VARIABLE = {
        className: "variable",
        begin: /@[a-z0-9]+/
      };
      const OPERATOR = {
        className: "operator",
        begin: /[-+*/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?/,
        relevance: 0
      };
      const FUNCTION_CALL = {
        begin: concat(/\b/, either(...FUNCTIONS), /\s*\(/),
        keywords: {
          built_in: FUNCTIONS
        }
      };
      function reduceRelevancy(list, { exceptions, when } = {}) {
        const qualifyFn = when;
        exceptions = exceptions || [];
        return list.map((item) => {
          if (item.match(/\|\d+$/) || exceptions.includes(item)) {
            return item;
          } else if (qualifyFn(item)) {
            return `${item}|0`;
          } else {
            return item;
          }
        });
      }
      return {
        name: "SQL",
        case_insensitive: true,
        // does not include {} or HTML tags `</`
        illegal: /[{}]|<\//,
        keywords: {
          $pattern: /\b[\w\.]+/,
          keyword: reduceRelevancy(KEYWORDS3, { when: (x2) => x2.length < 3 }),
          literal: LITERALS3,
          type: TYPES3,
          built_in: POSSIBLE_WITHOUT_PARENS
        },
        contains: [
          {
            begin: either(...COMBOS),
            keywords: {
              $pattern: /[\w\.]+/,
              keyword: KEYWORDS3.concat(COMBOS),
              literal: LITERALS3,
              type: TYPES3
            }
          },
          {
            className: "type",
            begin: either(...MULTI_WORD_TYPES)
          },
          FUNCTION_CALL,
          VARIABLE,
          STRING,
          QUOTED_IDENTIFIER,
          hljs5.C_NUMBER_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          COMMENT_MODE,
          OPERATOR
        ]
      };
    }
    module.exports = sql2;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/stan.js
var require_stan = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/stan.js"(exports, module) {
    init_process_shim();
    function stan(hljs5) {
      const BLOCKS = [
        "functions",
        "model",
        "data",
        "parameters",
        "quantities",
        "transformed",
        "generated"
      ];
      const STATEMENTS = [
        "for",
        "in",
        "if",
        "else",
        "while",
        "break",
        "continue",
        "return"
      ];
      const SPECIAL_FUNCTIONS = [
        "print",
        "reject",
        "increment_log_prob|10",
        "integrate_ode|10",
        "integrate_ode_rk45|10",
        "integrate_ode_bdf|10",
        "algebra_solver"
      ];
      const VAR_TYPES = [
        "int",
        "real",
        "vector",
        "ordered",
        "positive_ordered",
        "simplex",
        "unit_vector",
        "row_vector",
        "matrix",
        "cholesky_factor_corr|10",
        "cholesky_factor_cov|10",
        "corr_matrix|10",
        "cov_matrix|10",
        "void"
      ];
      const FUNCTIONS = [
        "Phi",
        "Phi_approx",
        "abs",
        "acos",
        "acosh",
        "algebra_solver",
        "append_array",
        "append_col",
        "append_row",
        "asin",
        "asinh",
        "atan",
        "atan2",
        "atanh",
        "bernoulli_cdf",
        "bernoulli_lccdf",
        "bernoulli_lcdf",
        "bernoulli_logit_lpmf",
        "bernoulli_logit_rng",
        "bernoulli_lpmf",
        "bernoulli_rng",
        "bessel_first_kind",
        "bessel_second_kind",
        "beta_binomial_cdf",
        "beta_binomial_lccdf",
        "beta_binomial_lcdf",
        "beta_binomial_lpmf",
        "beta_binomial_rng",
        "beta_cdf",
        "beta_lccdf",
        "beta_lcdf",
        "beta_lpdf",
        "beta_rng",
        "binary_log_loss",
        "binomial_cdf",
        "binomial_coefficient_log",
        "binomial_lccdf",
        "binomial_lcdf",
        "binomial_logit_lpmf",
        "binomial_lpmf",
        "binomial_rng",
        "block",
        "categorical_logit_lpmf",
        "categorical_logit_rng",
        "categorical_lpmf",
        "categorical_rng",
        "cauchy_cdf",
        "cauchy_lccdf",
        "cauchy_lcdf",
        "cauchy_lpdf",
        "cauchy_rng",
        "cbrt",
        "ceil",
        "chi_square_cdf",
        "chi_square_lccdf",
        "chi_square_lcdf",
        "chi_square_lpdf",
        "chi_square_rng",
        "cholesky_decompose",
        "choose",
        "col",
        "cols",
        "columns_dot_product",
        "columns_dot_self",
        "cos",
        "cosh",
        "cov_exp_quad",
        "crossprod",
        "csr_extract_u",
        "csr_extract_v",
        "csr_extract_w",
        "csr_matrix_times_vector",
        "csr_to_dense_matrix",
        "cumulative_sum",
        "determinant",
        "diag_matrix",
        "diag_post_multiply",
        "diag_pre_multiply",
        "diagonal",
        "digamma",
        "dims",
        "dirichlet_lpdf",
        "dirichlet_rng",
        "distance",
        "dot_product",
        "dot_self",
        "double_exponential_cdf",
        "double_exponential_lccdf",
        "double_exponential_lcdf",
        "double_exponential_lpdf",
        "double_exponential_rng",
        "e",
        "eigenvalues_sym",
        "eigenvectors_sym",
        "erf",
        "erfc",
        "exp",
        "exp2",
        "exp_mod_normal_cdf",
        "exp_mod_normal_lccdf",
        "exp_mod_normal_lcdf",
        "exp_mod_normal_lpdf",
        "exp_mod_normal_rng",
        "expm1",
        "exponential_cdf",
        "exponential_lccdf",
        "exponential_lcdf",
        "exponential_lpdf",
        "exponential_rng",
        "fabs",
        "falling_factorial",
        "fdim",
        "floor",
        "fma",
        "fmax",
        "fmin",
        "fmod",
        "frechet_cdf",
        "frechet_lccdf",
        "frechet_lcdf",
        "frechet_lpdf",
        "frechet_rng",
        "gamma_cdf",
        "gamma_lccdf",
        "gamma_lcdf",
        "gamma_lpdf",
        "gamma_p",
        "gamma_q",
        "gamma_rng",
        "gaussian_dlm_obs_lpdf",
        "get_lp",
        "gumbel_cdf",
        "gumbel_lccdf",
        "gumbel_lcdf",
        "gumbel_lpdf",
        "gumbel_rng",
        "head",
        "hypergeometric_lpmf",
        "hypergeometric_rng",
        "hypot",
        "inc_beta",
        "int_step",
        "integrate_ode",
        "integrate_ode_bdf",
        "integrate_ode_rk45",
        "inv",
        "inv_Phi",
        "inv_chi_square_cdf",
        "inv_chi_square_lccdf",
        "inv_chi_square_lcdf",
        "inv_chi_square_lpdf",
        "inv_chi_square_rng",
        "inv_cloglog",
        "inv_gamma_cdf",
        "inv_gamma_lccdf",
        "inv_gamma_lcdf",
        "inv_gamma_lpdf",
        "inv_gamma_rng",
        "inv_logit",
        "inv_sqrt",
        "inv_square",
        "inv_wishart_lpdf",
        "inv_wishart_rng",
        "inverse",
        "inverse_spd",
        "is_inf",
        "is_nan",
        "lbeta",
        "lchoose",
        "lgamma",
        "lkj_corr_cholesky_lpdf",
        "lkj_corr_cholesky_rng",
        "lkj_corr_lpdf",
        "lkj_corr_rng",
        "lmgamma",
        "lmultiply",
        "log",
        "log10",
        "log1m",
        "log1m_exp",
        "log1m_inv_logit",
        "log1p",
        "log1p_exp",
        "log2",
        "log_determinant",
        "log_diff_exp",
        "log_falling_factorial",
        "log_inv_logit",
        "log_mix",
        "log_rising_factorial",
        "log_softmax",
        "log_sum_exp",
        "logistic_cdf",
        "logistic_lccdf",
        "logistic_lcdf",
        "logistic_lpdf",
        "logistic_rng",
        "logit",
        "lognormal_cdf",
        "lognormal_lccdf",
        "lognormal_lcdf",
        "lognormal_lpdf",
        "lognormal_rng",
        "machine_precision",
        "matrix_exp",
        "max",
        "mdivide_left_spd",
        "mdivide_left_tri_low",
        "mdivide_right_spd",
        "mdivide_right_tri_low",
        "mean",
        "min",
        "modified_bessel_first_kind",
        "modified_bessel_second_kind",
        "multi_gp_cholesky_lpdf",
        "multi_gp_lpdf",
        "multi_normal_cholesky_lpdf",
        "multi_normal_cholesky_rng",
        "multi_normal_lpdf",
        "multi_normal_prec_lpdf",
        "multi_normal_rng",
        "multi_student_t_lpdf",
        "multi_student_t_rng",
        "multinomial_lpmf",
        "multinomial_rng",
        "multiply_log",
        "multiply_lower_tri_self_transpose",
        "neg_binomial_2_cdf",
        "neg_binomial_2_lccdf",
        "neg_binomial_2_lcdf",
        "neg_binomial_2_log_lpmf",
        "neg_binomial_2_log_rng",
        "neg_binomial_2_lpmf",
        "neg_binomial_2_rng",
        "neg_binomial_cdf",
        "neg_binomial_lccdf",
        "neg_binomial_lcdf",
        "neg_binomial_lpmf",
        "neg_binomial_rng",
        "negative_infinity",
        "normal_cdf",
        "normal_lccdf",
        "normal_lcdf",
        "normal_lpdf",
        "normal_rng",
        "not_a_number",
        "num_elements",
        "ordered_logistic_lpmf",
        "ordered_logistic_rng",
        "owens_t",
        "pareto_cdf",
        "pareto_lccdf",
        "pareto_lcdf",
        "pareto_lpdf",
        "pareto_rng",
        "pareto_type_2_cdf",
        "pareto_type_2_lccdf",
        "pareto_type_2_lcdf",
        "pareto_type_2_lpdf",
        "pareto_type_2_rng",
        "pi",
        "poisson_cdf",
        "poisson_lccdf",
        "poisson_lcdf",
        "poisson_log_lpmf",
        "poisson_log_rng",
        "poisson_lpmf",
        "poisson_rng",
        "positive_infinity",
        "pow",
        "print",
        "prod",
        "qr_Q",
        "qr_R",
        "quad_form",
        "quad_form_diag",
        "quad_form_sym",
        "rank",
        "rayleigh_cdf",
        "rayleigh_lccdf",
        "rayleigh_lcdf",
        "rayleigh_lpdf",
        "rayleigh_rng",
        "reject",
        "rep_array",
        "rep_matrix",
        "rep_row_vector",
        "rep_vector",
        "rising_factorial",
        "round",
        "row",
        "rows",
        "rows_dot_product",
        "rows_dot_self",
        "scaled_inv_chi_square_cdf",
        "scaled_inv_chi_square_lccdf",
        "scaled_inv_chi_square_lcdf",
        "scaled_inv_chi_square_lpdf",
        "scaled_inv_chi_square_rng",
        "sd",
        "segment",
        "sin",
        "singular_values",
        "sinh",
        "size",
        "skew_normal_cdf",
        "skew_normal_lccdf",
        "skew_normal_lcdf",
        "skew_normal_lpdf",
        "skew_normal_rng",
        "softmax",
        "sort_asc",
        "sort_desc",
        "sort_indices_asc",
        "sort_indices_desc",
        "sqrt",
        "sqrt2",
        "square",
        "squared_distance",
        "step",
        "student_t_cdf",
        "student_t_lccdf",
        "student_t_lcdf",
        "student_t_lpdf",
        "student_t_rng",
        "sub_col",
        "sub_row",
        "sum",
        "tail",
        "tan",
        "tanh",
        "target",
        "tcrossprod",
        "tgamma",
        "to_array_1d",
        "to_array_2d",
        "to_matrix",
        "to_row_vector",
        "to_vector",
        "trace",
        "trace_gen_quad_form",
        "trace_quad_form",
        "trigamma",
        "trunc",
        "uniform_cdf",
        "uniform_lccdf",
        "uniform_lcdf",
        "uniform_lpdf",
        "uniform_rng",
        "variance",
        "von_mises_lpdf",
        "von_mises_rng",
        "weibull_cdf",
        "weibull_lccdf",
        "weibull_lcdf",
        "weibull_lpdf",
        "weibull_rng",
        "wiener_lpdf",
        "wishart_lpdf",
        "wishart_rng"
      ];
      const DISTRIBUTIONS = [
        "bernoulli",
        "bernoulli_logit",
        "beta",
        "beta_binomial",
        "binomial",
        "binomial_logit",
        "categorical",
        "categorical_logit",
        "cauchy",
        "chi_square",
        "dirichlet",
        "double_exponential",
        "exp_mod_normal",
        "exponential",
        "frechet",
        "gamma",
        "gaussian_dlm_obs",
        "gumbel",
        "hypergeometric",
        "inv_chi_square",
        "inv_gamma",
        "inv_wishart",
        "lkj_corr",
        "lkj_corr_cholesky",
        "logistic",
        "lognormal",
        "multi_gp",
        "multi_gp_cholesky",
        "multi_normal",
        "multi_normal_cholesky",
        "multi_normal_prec",
        "multi_student_t",
        "multinomial",
        "neg_binomial",
        "neg_binomial_2",
        "neg_binomial_2_log",
        "normal",
        "ordered_logistic",
        "pareto",
        "pareto_type_2",
        "poisson",
        "poisson_log",
        "rayleigh",
        "scaled_inv_chi_square",
        "skew_normal",
        "student_t",
        "uniform",
        "von_mises",
        "weibull",
        "wiener",
        "wishart"
      ];
      return {
        name: "Stan",
        aliases: ["stanfuncs"],
        keywords: {
          $pattern: hljs5.IDENT_RE,
          title: BLOCKS,
          keyword: STATEMENTS.concat(VAR_TYPES).concat(SPECIAL_FUNCTIONS),
          built_in: FUNCTIONS
        },
        contains: [
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.COMMENT(
            /#/,
            /$/,
            {
              relevance: 0,
              keywords: {
                "meta-keyword": "include"
              }
            }
          ),
          hljs5.COMMENT(
            /\/\*/,
            /\*\//,
            {
              relevance: 0,
              // highlight doc strings mentioned in Stan reference
              contains: [
                {
                  className: "doctag",
                  begin: /@(return|param)/
                }
              ]
            }
          ),
          {
            // hack: in range constraints, lower must follow "<"
            begin: /<\s*lower\s*=/,
            keywords: "lower"
          },
          {
            // hack: in range constraints, upper must follow either , or <
            // <lower = ..., upper = ...> or <upper = ...>
            begin: /[<,]\s*upper\s*=/,
            keywords: "upper"
          },
          {
            className: "keyword",
            begin: /\btarget\s*\+=/,
            relevance: 10
          },
          {
            begin: "~\\s*(" + hljs5.IDENT_RE + ")\\s*\\(",
            keywords: DISTRIBUTIONS
          },
          {
            className: "number",
            variants: [
              {
                begin: /\b\d+(?:\.\d*)?(?:[eE][+-]?\d+)?/
              },
              {
                begin: /\.\d+(?:[eE][+-]?\d+)?\b/
              }
            ],
            relevance: 0
          },
          {
            className: "string",
            begin: '"',
            end: '"',
            relevance: 0
          }
        ]
      };
    }
    module.exports = stan;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/stata.js
var require_stata = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/stata.js"(exports, module) {
    init_process_shim();
    function stata(hljs5) {
      return {
        name: "Stata",
        aliases: [
          "do",
          "ado"
        ],
        case_insensitive: true,
        keywords: "if else in foreach for forv forva forval forvalu forvalue forvalues by bys bysort xi quietly qui capture about ac ac_7 acprplot acprplot_7 adjust ado adopath adoupdate alpha ameans an ano anov anova anova_estat anova_terms anovadef aorder ap app appe appen append arch arch_dr arch_estat arch_p archlm areg areg_p args arima arima_dr arima_estat arima_p as asmprobit asmprobit_estat asmprobit_lf asmprobit_mfx__dlg asmprobit_p ass asse asser assert avplot avplot_7 avplots avplots_7 bcskew0 bgodfrey bias binreg bip0_lf biplot bipp_lf bipr_lf bipr_p biprobit bitest bitesti bitowt blogit bmemsize boot bootsamp bootstrap bootstrap_8 boxco_l boxco_p boxcox boxcox_6 boxcox_p bprobit br break brier bro brow brows browse brr brrstat bs bs_7 bsampl_w bsample bsample_7 bsqreg bstat bstat_7 bstat_8 bstrap bstrap_7 bubble bubbleplot ca ca_estat ca_p cabiplot camat canon canon_8 canon_8_p canon_estat canon_p cap caprojection capt captu captur capture cat cc cchart cchart_7 cci cd censobs_table centile cf char chdir checkdlgfiles checkestimationsample checkhlpfiles checksum chelp ci cii cl class classutil clear cli clis clist clo clog clog_lf clog_p clogi clogi_sw clogit clogit_lf clogit_p clogitp clogl_sw cloglog clonevar clslistarray cluster cluster_measures cluster_stop cluster_tree cluster_tree_8 clustermat cmdlog cnr cnre cnreg cnreg_p cnreg_sw cnsreg codebook collaps4 collapse colormult_nb colormult_nw compare compress conf confi confir confirm conren cons const constr constra constrai constrain constraint continue contract copy copyright copysource cor corc corr corr2data corr_anti corr_kmo corr_smc corre correl correla correlat correlate corrgram cou coun count cox cox_p cox_sw coxbase coxhaz coxvar cprplot cprplot_7 crc cret cretu cretur creturn cross cs cscript cscript_log csi ct ct_is ctset ctst_5 ctst_st cttost cumsp cumsp_7 cumul cusum cusum_7 cutil d|0 datasig datasign datasigna datasignat datasignatu datasignatur datasignature datetof db dbeta de dec deco decod decode deff des desc descr descri describ describe destring dfbeta dfgls dfuller di di_g dir dirstats dis discard disp disp_res disp_s displ displa display distinct do doe doed doedi doedit dotplot dotplot_7 dprobit drawnorm drop ds ds_util dstdize duplicates durbina dwstat dydx e|0 ed edi edit egen eivreg emdef en enc enco encod encode eq erase ereg ereg_lf ereg_p ereg_sw ereghet ereghet_glf ereghet_glf_sh ereghet_gp ereghet_ilf ereghet_ilf_sh ereghet_ip eret eretu eretur ereturn err erro error esize est est_cfexist est_cfname est_clickable est_expand est_hold est_table est_unhold est_unholdok estat estat_default estat_summ estat_vce_only esti estimates etodow etof etomdy ex exi exit expand expandcl fac fact facto factor factor_estat factor_p factor_pca_rotated factor_rotate factormat fcast fcast_compute fcast_graph fdades fdadesc fdadescr fdadescri fdadescrib fdadescribe fdasav fdasave fdause fh_st file open file read file close file filefilter fillin find_hlp_file findfile findit findit_7 fit fl fli flis flist for5_0 forest forestplot form forma format fpredict frac_154 frac_adj frac_chk frac_cox frac_ddp frac_dis frac_dv frac_in frac_mun frac_pp frac_pq frac_pv frac_wgt frac_xo fracgen fracplot fracplot_7 fracpoly fracpred fron_ex fron_hn fron_p fron_tn fron_tn2 frontier ftodate ftoe ftomdy ftowdate funnel funnelplot g|0 gamhet_glf gamhet_gp gamhet_ilf gamhet_ip gamma gamma_d2 gamma_p gamma_sw gammahet gdi_hexagon gdi_spokes ge gen gene gener genera generat generate genrank genstd genvmean gettoken gl gladder gladder_7 glim_l01 glim_l02 glim_l03 glim_l04 glim_l05 glim_l06 glim_l07 glim_l08 glim_l09 glim_l10 glim_l11 glim_l12 glim_lf glim_mu glim_nw1 glim_nw2 glim_nw3 glim_p glim_v1 glim_v2 glim_v3 glim_v4 glim_v5 glim_v6 glim_v7 glm glm_6 glm_p glm_sw glmpred glo glob globa global glogit glogit_8 glogit_p gmeans gnbre_lf gnbreg gnbreg_5 gnbreg_p gomp_lf gompe_sw gomper_p gompertz gompertzhet gomphet_glf gomphet_glf_sh gomphet_gp gomphet_ilf gomphet_ilf_sh gomphet_ip gphdot gphpen gphprint gprefs gprobi_p gprobit gprobit_8 gr gr7 gr_copy gr_current gr_db gr_describe gr_dir gr_draw gr_draw_replay gr_drop gr_edit gr_editviewopts gr_example gr_example2 gr_export gr_print gr_qscheme gr_query gr_read gr_rename gr_replay gr_save gr_set gr_setscheme gr_table gr_undo gr_use graph graph7 grebar greigen greigen_7 greigen_8 grmeanby grmeanby_7 gs_fileinfo gs_filetype gs_graphinfo gs_stat gsort gwood h|0 hadimvo hareg hausman haver he heck_d2 heckma_p heckman heckp_lf heckpr_p heckprob hel help hereg hetpr_lf hetpr_p hetprob hettest hexdump hilite hist hist_7 histogram hlogit hlu hmeans hotel hotelling hprobit hreg hsearch icd9 icd9_ff icd9p iis impute imtest inbase include inf infi infil infile infix inp inpu input ins insheet insp inspe inspec inspect integ inten intreg intreg_7 intreg_p intrg2_ll intrg_ll intrg_ll2 ipolate iqreg ir irf irf_create irfm iri is_svy is_svysum isid istdize ivprob_1_lf ivprob_lf ivprobit ivprobit_p ivreg ivreg_footnote ivtob_1_lf ivtob_lf ivtobit ivtobit_p jackknife jacknife jknife jknife_6 jknife_8 jkstat joinby kalarma1 kap kap_3 kapmeier kappa kapwgt kdensity kdensity_7 keep ksm ksmirnov ktau kwallis l|0 la lab labbe labbeplot labe label labelbook ladder levels levelsof leverage lfit lfit_p li lincom line linktest lis list lloghet_glf lloghet_glf_sh lloghet_gp lloghet_ilf lloghet_ilf_sh lloghet_ip llogi_sw llogis_p llogist llogistic llogistichet lnorm_lf lnorm_sw lnorma_p lnormal lnormalhet lnormhet_glf lnormhet_glf_sh lnormhet_gp lnormhet_ilf lnormhet_ilf_sh lnormhet_ip lnskew0 loadingplot loc loca local log logi logis_lf logistic logistic_p logit logit_estat logit_p loglogs logrank loneway lookfor lookup lowess lowess_7 lpredict lrecomp lroc lroc_7 lrtest ls lsens lsens_7 lsens_x lstat ltable ltable_7 ltriang lv lvr2plot lvr2plot_7 m|0 ma mac macr macro makecns man manova manova_estat manova_p manovatest mantel mark markin markout marksample mat mat_capp mat_order mat_put_rr mat_rapp mata mata_clear mata_describe mata_drop mata_matdescribe mata_matsave mata_matuse mata_memory mata_mlib mata_mosave mata_rename mata_which matalabel matcproc matlist matname matr matri matrix matrix_input__dlg matstrik mcc mcci md0_ md1_ md1debug_ md2_ md2debug_ mds mds_estat mds_p mdsconfig mdslong mdsmat mdsshepard mdytoe mdytof me_derd mean means median memory memsize menl meqparse mer merg merge meta mfp mfx mhelp mhodds minbound mixed_ll mixed_ll_reparm mkassert mkdir mkmat mkspline ml ml_5 ml_adjs ml_bhhhs ml_c_d ml_check ml_clear ml_cnt ml_debug ml_defd ml_e0 ml_e0_bfgs ml_e0_cycle ml_e0_dfp ml_e0i ml_e1 ml_e1_bfgs ml_e1_bhhh ml_e1_cycle ml_e1_dfp ml_e2 ml_e2_cycle ml_ebfg0 ml_ebfr0 ml_ebfr1 ml_ebh0q ml_ebhh0 ml_ebhr0 ml_ebr0i ml_ecr0i ml_edfp0 ml_edfr0 ml_edfr1 ml_edr0i ml_eds ml_eer0i ml_egr0i ml_elf ml_elf_bfgs ml_elf_bhhh ml_elf_cycle ml_elf_dfp ml_elfi ml_elfs ml_enr0i ml_enrr0 ml_erdu0 ml_erdu0_bfgs ml_erdu0_bhhh ml_erdu0_bhhhq ml_erdu0_cycle ml_erdu0_dfp ml_erdu0_nrbfgs ml_exde ml_footnote ml_geqnr ml_grad0 ml_graph ml_hbhhh ml_hd0 ml_hold ml_init ml_inv ml_log ml_max ml_mlout ml_mlout_8 ml_model ml_nb0 ml_opt ml_p ml_plot ml_query ml_rdgrd ml_repor ml_s_e ml_score ml_searc ml_technique ml_unhold mleval mlf_ mlmatbysum mlmatsum mlog mlogi mlogit mlogit_footnote mlogit_p mlopts mlsum mlvecsum mnl0_ mor more mov move mprobit mprobit_lf mprobit_p mrdu0_ mrdu1_ mvdecode mvencode mvreg mvreg_estat n|0 nbreg nbreg_al nbreg_lf nbreg_p nbreg_sw nestreg net newey newey_7 newey_p news nl nl_7 nl_9 nl_9_p nl_p nl_p_7 nlcom nlcom_p nlexp2 nlexp2_7 nlexp2a nlexp2a_7 nlexp3 nlexp3_7 nlgom3 nlgom3_7 nlgom4 nlgom4_7 nlinit nllog3 nllog3_7 nllog4 nllog4_7 nlog_rd nlogit nlogit_p nlogitgen nlogittree nlpred no nobreak noi nois noisi noisil noisily note notes notes_dlg nptrend numlabel numlist odbc old_ver olo olog ologi ologi_sw ologit ologit_p ologitp on one onew onewa oneway op_colnm op_comp op_diff op_inv op_str opr opro oprob oprob_sw oprobi oprobi_p oprobit oprobitp opts_exclusive order orthog orthpoly ou out outf outfi outfil outfile outs outsh outshe outshee outsheet ovtest pac pac_7 palette parse parse_dissim pause pca pca_8 pca_display pca_estat pca_p pca_rotate pcamat pchart pchart_7 pchi pchi_7 pcorr pctile pentium pergram pergram_7 permute permute_8 personal peto_st pkcollapse pkcross pkequiv pkexamine pkexamine_7 pkshape pksumm pksumm_7 pl plo plot plugin pnorm pnorm_7 poisgof poiss_lf poiss_sw poisso_p poisson poisson_estat post postclose postfile postutil pperron pr prais prais_e prais_e2 prais_p predict predictnl preserve print pro prob probi probit probit_estat probit_p proc_time procoverlay procrustes procrustes_estat procrustes_p profiler prog progr progra program prop proportion prtest prtesti pwcorr pwd q\\s qby qbys qchi qchi_7 qladder qladder_7 qnorm qnorm_7 qqplot qqplot_7 qreg qreg_c qreg_p qreg_sw qu quadchk quantile quantile_7 que quer query range ranksum ratio rchart rchart_7 rcof recast reclink recode reg reg3 reg3_p regdw regr regre regre_p2 regres regres_p regress regress_estat regriv_p remap ren rena renam rename renpfix repeat replace report reshape restore ret retu retur return rm rmdir robvar roccomp roccomp_7 roccomp_8 rocf_lf rocfit rocfit_8 rocgold rocplot rocplot_7 roctab roctab_7 rolling rologit rologit_p rot rota rotat rotate rotatemat rreg rreg_p ru run runtest rvfplot rvfplot_7 rvpplot rvpplot_7 sa safesum sample sampsi sav save savedresults saveold sc sca scal scala scalar scatter scm_mine sco scob_lf scob_p scobi_sw scobit scor score scoreplot scoreplot_help scree screeplot screeplot_help sdtest sdtesti se search separate seperate serrbar serrbar_7 serset set set_defaults sfrancia sh she shel shell shewhart shewhart_7 signestimationsample signrank signtest simul simul_7 simulate simulate_8 sktest sleep slogit slogit_d2 slogit_p smooth snapspan so sor sort spearman spikeplot spikeplot_7 spikeplt spline_x split sqreg sqreg_p sret sretu sretur sreturn ssc st st_ct st_hc st_hcd st_hcd_sh st_is st_issys st_note st_promo st_set st_show st_smpl st_subid stack statsby statsby_8 stbase stci stci_7 stcox stcox_estat stcox_fr stcox_fr_ll stcox_p stcox_sw stcoxkm stcoxkm_7 stcstat stcurv stcurve stcurve_7 stdes stem stepwise stereg stfill stgen stir stjoin stmc stmh stphplot stphplot_7 stphtest stphtest_7 stptime strate strate_7 streg streg_sw streset sts sts_7 stset stsplit stsum sttocc sttoct stvary stweib su suest suest_8 sum summ summa summar summari summariz summarize sunflower sureg survcurv survsum svar svar_p svmat svy svy_disp svy_dreg svy_est svy_est_7 svy_estat svy_get svy_gnbreg_p svy_head svy_header svy_heckman_p svy_heckprob_p svy_intreg_p svy_ivreg_p svy_logistic_p svy_logit_p svy_mlogit_p svy_nbreg_p svy_ologit_p svy_oprobit_p svy_poisson_p svy_probit_p svy_regress_p svy_sub svy_sub_7 svy_x svy_x_7 svy_x_p svydes svydes_8 svygen svygnbreg svyheckman svyheckprob svyintreg svyintreg_7 svyintrg svyivreg svylc svylog_p svylogit svymarkout svymarkout_8 svymean svymlog svymlogit svynbreg svyolog svyologit svyoprob svyoprobit svyopts svypois svypois_7 svypoisson svyprobit svyprobt svyprop svyprop_7 svyratio svyreg svyreg_p svyregress svyset svyset_7 svyset_8 svytab svytab_7 svytest svytotal sw sw_8 swcnreg swcox swereg swilk swlogis swlogit swologit swoprbt swpois swprobit swqreg swtobit swweib symmetry symmi symplot symplot_7 syntax sysdescribe sysdir sysuse szroeter ta tab tab1 tab2 tab_or tabd tabdi tabdis tabdisp tabi table tabodds tabodds_7 tabstat tabu tabul tabula tabulat tabulate te tempfile tempname tempvar tes test testnl testparm teststd tetrachoric time_it timer tis tob tobi tobit tobit_p tobit_sw token tokeni tokeniz tokenize tostring total translate translator transmap treat_ll treatr_p treatreg trim trimfill trnb_cons trnb_mean trpoiss_d2 trunc_ll truncr_p truncreg tsappend tset tsfill tsline tsline_ex tsreport tsrevar tsrline tsset tssmooth tsunab ttest ttesti tut_chk tut_wait tutorial tw tware_st two twoway twoway__fpfit_serset twoway__function_gen twoway__histogram_gen twoway__ipoint_serset twoway__ipoints_serset twoway__kdensity_gen twoway__lfit_serset twoway__normgen_gen twoway__pci_serset twoway__qfit_serset twoway__scatteri_serset twoway__sunflower_gen twoway_ksm_serset ty typ type typeof u|0 unab unabbrev unabcmd update us use uselabel var var_mkcompanion var_p varbasic varfcast vargranger varirf varirf_add varirf_cgraph varirf_create varirf_ctable varirf_describe varirf_dir varirf_drop varirf_erase varirf_graph varirf_ograph varirf_rename varirf_set varirf_table varlist varlmar varnorm varsoc varstable varstable_w varstable_w2 varwle vce vec vec_fevd vec_mkphi vec_p vec_p_w vecirf_create veclmar veclmar_w vecnorm vecnorm_w vecrank vecstable verinst vers versi versio version view viewsource vif vwls wdatetof webdescribe webseek webuse weib1_lf weib2_lf weib_lf weib_lf0 weibhet_glf weibhet_glf_sh weibhet_glfa weibhet_glfa_sh weibhet_gp weibhet_ilf weibhet_ilf_sh weibhet_ilfa weibhet_ilfa_sh weibhet_ip weibu_sw weibul_p weibull weibull_c weibull_s weibullhet wh whelp whi which whil while wilc_st wilcoxon win wind windo window winexec wntestb wntestb_7 wntestq xchart xchart_7 xcorr xcorr_7 xi xi_6 xmlsav xmlsave xmluse xpose xsh xshe xshel xshell xt_iis xt_tis xtab_p xtabond xtbin_p xtclog xtcloglog xtcloglog_8 xtcloglog_d2 xtcloglog_pa_p xtcloglog_re_p xtcnt_p xtcorr xtdata xtdes xtfront_p xtfrontier xtgee xtgee_elink xtgee_estat xtgee_makeivar xtgee_p xtgee_plink xtgls xtgls_p xthaus xthausman xtht_p xthtaylor xtile xtint_p xtintreg xtintreg_8 xtintreg_d2 xtintreg_p xtivp_1 xtivp_2 xtivreg xtline xtline_ex xtlogit xtlogit_8 xtlogit_d2 xtlogit_fe_p xtlogit_pa_p xtlogit_re_p xtmixed xtmixed_estat xtmixed_p xtnb_fe xtnb_lf xtnbreg xtnbreg_pa_p xtnbreg_refe_p xtpcse xtpcse_p xtpois xtpoisson xtpoisson_d2 xtpoisson_pa_p xtpoisson_refe_p xtpred xtprobit xtprobit_8 xtprobit_d2 xtprobit_re_p xtps_fe xtps_lf xtps_ren xtps_ren_8 xtrar_p xtrc xtrc_p xtrchh xtrefe_p xtreg xtreg_be xtreg_fe xtreg_ml xtreg_pa_p xtreg_re xtregar xtrere_p xtset xtsf_ll xtsf_llti xtsum xttab xttest0 xttobit xttobit_8 xttobit_p xttrans yx yxview__barlike_draw yxview_area_draw yxview_bar_draw yxview_dot_draw yxview_dropline_draw yxview_function_draw yxview_iarrow_draw yxview_ilabels_draw yxview_normal_draw yxview_pcarrow_draw yxview_pcbarrow_draw yxview_pccapsym_draw yxview_pcscatter_draw yxview_pcspike_draw yxview_rarea_draw yxview_rbar_draw yxview_rbarm_draw yxview_rcap_draw yxview_rcapsym_draw yxview_rconnected_draw yxview_rline_draw yxview_rscatter_draw yxview_rspike_draw yxview_spike_draw yxview_sunflower_draw zap_s zinb zinb_llf zinb_plf zip zip_llf zip_p zip_plf zt_ct_5 zt_hc_5 zt_hcd_5 zt_is_5 zt_iss_5 zt_sho_5 zt_smp_5 ztbase_5 ztcox_5 ztdes_5 ztereg_5 ztfill_5 ztgen_5 ztir_5 ztjoin_5 ztnb ztnb_p ztp ztp_p zts_5 ztset_5 ztspli_5 ztsum_5 zttoct_5 ztvary_5 ztweib_5",
        contains: [
          {
            className: "symbol",
            begin: /`[a-zA-Z0-9_]+'/
          },
          {
            className: "variable",
            begin: /\$\{?[a-zA-Z0-9_]+\}?/
          },
          {
            className: "string",
            variants: [
              {
                begin: '`"[^\r\n]*?"\''
              },
              {
                begin: '"[^\r\n"]*"'
              }
            ]
          },
          {
            className: "built_in",
            variants: [
              {
                begin: "\\b(abs|acos|asin|atan|atan2|atanh|ceil|cloglog|comb|cos|digamma|exp|floor|invcloglog|invlogit|ln|lnfact|lnfactorial|lngamma|log|log10|max|min|mod|reldif|round|sign|sin|sqrt|sum|tan|tanh|trigamma|trunc|betaden|Binomial|binorm|binormal|chi2|chi2tail|dgammapda|dgammapdada|dgammapdadx|dgammapdx|dgammapdxdx|F|Fden|Ftail|gammaden|gammap|ibeta|invbinomial|invchi2|invchi2tail|invF|invFtail|invgammap|invibeta|invnchi2|invnFtail|invnibeta|invnorm|invnormal|invttail|nbetaden|nchi2|nFden|nFtail|nibeta|norm|normal|normalden|normd|npnchi2|tden|ttail|uniform|abbrev|char|index|indexnot|length|lower|ltrim|match|plural|proper|real|regexm|regexr|regexs|reverse|rtrim|string|strlen|strlower|strltrim|strmatch|strofreal|strpos|strproper|strreverse|strrtrim|strtrim|strupper|subinstr|subinword|substr|trim|upper|word|wordcount|_caller|autocode|byteorder|chop|clip|cond|e|epsdouble|epsfloat|group|inlist|inrange|irecode|matrix|maxbyte|maxdouble|maxfloat|maxint|maxlong|mi|minbyte|mindouble|minfloat|minint|minlong|missing|r|recode|replay|return|s|scalar|d|date|day|dow|doy|halfyear|mdy|month|quarter|week|year|d|daily|dofd|dofh|dofm|dofq|dofw|dofy|h|halfyearly|hofd|m|mofd|monthly|q|qofd|quarterly|tin|twithin|w|weekly|wofd|y|yearly|yh|ym|yofd|yq|yw|cholesky|colnumb|colsof|corr|det|diag|diag0cnt|el|get|hadamard|I|inv|invsym|issym|issymmetric|J|matmissing|matuniform|mreldif|nullmat|rownumb|rowsof|sweep|syminv|trace|vec|vecdiag)(?=\\()"
              }
            ]
          },
          hljs5.COMMENT("^[ 	]*\\*.*$", false),
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE
        ]
      };
    }
    module.exports = stata;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/step21.js
var require_step21 = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/step21.js"(exports, module) {
    init_process_shim();
    function step21(hljs5) {
      const STEP21_IDENT_RE = "[A-Z_][A-Z0-9_.]*";
      const STEP21_KEYWORDS = {
        $pattern: STEP21_IDENT_RE,
        keyword: "HEADER ENDSEC DATA"
      };
      const STEP21_START = {
        className: "meta",
        begin: "ISO-10303-21;",
        relevance: 10
      };
      const STEP21_CLOSE = {
        className: "meta",
        begin: "END-ISO-10303-21;",
        relevance: 10
      };
      return {
        name: "STEP Part 21",
        aliases: [
          "p21",
          "step",
          "stp"
        ],
        case_insensitive: true,
        // STEP 21 is case insensitive in theory, in practice all non-comments are capitalized.
        keywords: STEP21_KEYWORDS,
        contains: [
          STEP21_START,
          STEP21_CLOSE,
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          hljs5.COMMENT("/\\*\\*!", "\\*/"),
          hljs5.C_NUMBER_MODE,
          hljs5.inherit(hljs5.APOS_STRING_MODE, {
            illegal: null
          }),
          hljs5.inherit(hljs5.QUOTE_STRING_MODE, {
            illegal: null
          }),
          {
            className: "string",
            begin: "'",
            end: "'"
          },
          {
            className: "symbol",
            variants: [
              {
                begin: "#",
                end: "\\d+",
                illegal: "\\W"
              }
            ]
          }
        ]
      };
    }
    module.exports = step21;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/stylus.js
var require_stylus = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/stylus.js"(exports, module) {
    init_process_shim();
    var MODES2 = (hljs5) => {
      return {
        IMPORTANT: {
          className: "meta",
          begin: "!important"
        },
        HEXCOLOR: {
          className: "number",
          begin: "#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})"
        },
        ATTRIBUTE_SELECTOR_MODE: {
          className: "selector-attr",
          begin: /\[/,
          end: /\]/,
          illegal: "$",
          contains: [
            hljs5.APOS_STRING_MODE,
            hljs5.QUOTE_STRING_MODE
          ]
        }
      };
    };
    var TAGS2 = [
      "a",
      "abbr",
      "address",
      "article",
      "aside",
      "audio",
      "b",
      "blockquote",
      "body",
      "button",
      "canvas",
      "caption",
      "cite",
      "code",
      "dd",
      "del",
      "details",
      "dfn",
      "div",
      "dl",
      "dt",
      "em",
      "fieldset",
      "figcaption",
      "figure",
      "footer",
      "form",
      "h1",
      "h2",
      "h3",
      "h4",
      "h5",
      "h6",
      "header",
      "hgroup",
      "html",
      "i",
      "iframe",
      "img",
      "input",
      "ins",
      "kbd",
      "label",
      "legend",
      "li",
      "main",
      "mark",
      "menu",
      "nav",
      "object",
      "ol",
      "p",
      "q",
      "quote",
      "samp",
      "section",
      "span",
      "strong",
      "summary",
      "sup",
      "table",
      "tbody",
      "td",
      "textarea",
      "tfoot",
      "th",
      "thead",
      "time",
      "tr",
      "ul",
      "var",
      "video"
    ];
    var MEDIA_FEATURES2 = [
      "any-hover",
      "any-pointer",
      "aspect-ratio",
      "color",
      "color-gamut",
      "color-index",
      "device-aspect-ratio",
      "device-height",
      "device-width",
      "display-mode",
      "forced-colors",
      "grid",
      "height",
      "hover",
      "inverted-colors",
      "monochrome",
      "orientation",
      "overflow-block",
      "overflow-inline",
      "pointer",
      "prefers-color-scheme",
      "prefers-contrast",
      "prefers-reduced-motion",
      "prefers-reduced-transparency",
      "resolution",
      "scan",
      "scripting",
      "update",
      "width",
      // TODO: find a better solution?
      "min-width",
      "max-width",
      "min-height",
      "max-height"
    ];
    var PSEUDO_CLASSES2 = [
      "active",
      "any-link",
      "blank",
      "checked",
      "current",
      "default",
      "defined",
      "dir",
      // dir()
      "disabled",
      "drop",
      "empty",
      "enabled",
      "first",
      "first-child",
      "first-of-type",
      "fullscreen",
      "future",
      "focus",
      "focus-visible",
      "focus-within",
      "has",
      // has()
      "host",
      // host or host()
      "host-context",
      // host-context()
      "hover",
      "indeterminate",
      "in-range",
      "invalid",
      "is",
      // is()
      "lang",
      // lang()
      "last-child",
      "last-of-type",
      "left",
      "link",
      "local-link",
      "not",
      // not()
      "nth-child",
      // nth-child()
      "nth-col",
      // nth-col()
      "nth-last-child",
      // nth-last-child()
      "nth-last-col",
      // nth-last-col()
      "nth-last-of-type",
      //nth-last-of-type()
      "nth-of-type",
      //nth-of-type()
      "only-child",
      "only-of-type",
      "optional",
      "out-of-range",
      "past",
      "placeholder-shown",
      "read-only",
      "read-write",
      "required",
      "right",
      "root",
      "scope",
      "target",
      "target-within",
      "user-invalid",
      "valid",
      "visited",
      "where"
      // where()
    ];
    var PSEUDO_ELEMENTS2 = [
      "after",
      "backdrop",
      "before",
      "cue",
      "cue-region",
      "first-letter",
      "first-line",
      "grammar-error",
      "marker",
      "part",
      "placeholder",
      "selection",
      "slotted",
      "spelling-error"
    ];
    var ATTRIBUTES2 = [
      "align-content",
      "align-items",
      "align-self",
      "animation",
      "animation-delay",
      "animation-direction",
      "animation-duration",
      "animation-fill-mode",
      "animation-iteration-count",
      "animation-name",
      "animation-play-state",
      "animation-timing-function",
      "auto",
      "backface-visibility",
      "background",
      "background-attachment",
      "background-clip",
      "background-color",
      "background-image",
      "background-origin",
      "background-position",
      "background-repeat",
      "background-size",
      "border",
      "border-bottom",
      "border-bottom-color",
      "border-bottom-left-radius",
      "border-bottom-right-radius",
      "border-bottom-style",
      "border-bottom-width",
      "border-collapse",
      "border-color",
      "border-image",
      "border-image-outset",
      "border-image-repeat",
      "border-image-slice",
      "border-image-source",
      "border-image-width",
      "border-left",
      "border-left-color",
      "border-left-style",
      "border-left-width",
      "border-radius",
      "border-right",
      "border-right-color",
      "border-right-style",
      "border-right-width",
      "border-spacing",
      "border-style",
      "border-top",
      "border-top-color",
      "border-top-left-radius",
      "border-top-right-radius",
      "border-top-style",
      "border-top-width",
      "border-width",
      "bottom",
      "box-decoration-break",
      "box-shadow",
      "box-sizing",
      "break-after",
      "break-before",
      "break-inside",
      "caption-side",
      "clear",
      "clip",
      "clip-path",
      "color",
      "column-count",
      "column-fill",
      "column-gap",
      "column-rule",
      "column-rule-color",
      "column-rule-style",
      "column-rule-width",
      "column-span",
      "column-width",
      "columns",
      "content",
      "counter-increment",
      "counter-reset",
      "cursor",
      "direction",
      "display",
      "empty-cells",
      "filter",
      "flex",
      "flex-basis",
      "flex-direction",
      "flex-flow",
      "flex-grow",
      "flex-shrink",
      "flex-wrap",
      "float",
      "font",
      "font-display",
      "font-family",
      "font-feature-settings",
      "font-kerning",
      "font-language-override",
      "font-size",
      "font-size-adjust",
      "font-smoothing",
      "font-stretch",
      "font-style",
      "font-variant",
      "font-variant-ligatures",
      "font-variation-settings",
      "font-weight",
      "height",
      "hyphens",
      "icon",
      "image-orientation",
      "image-rendering",
      "image-resolution",
      "ime-mode",
      "inherit",
      "initial",
      "justify-content",
      "left",
      "letter-spacing",
      "line-height",
      "list-style",
      "list-style-image",
      "list-style-position",
      "list-style-type",
      "margin",
      "margin-bottom",
      "margin-left",
      "margin-right",
      "margin-top",
      "marks",
      "mask",
      "max-height",
      "max-width",
      "min-height",
      "min-width",
      "nav-down",
      "nav-index",
      "nav-left",
      "nav-right",
      "nav-up",
      "none",
      "normal",
      "object-fit",
      "object-position",
      "opacity",
      "order",
      "orphans",
      "outline",
      "outline-color",
      "outline-offset",
      "outline-style",
      "outline-width",
      "overflow",
      "overflow-wrap",
      "overflow-x",
      "overflow-y",
      "padding",
      "padding-bottom",
      "padding-left",
      "padding-right",
      "padding-top",
      "page-break-after",
      "page-break-before",
      "page-break-inside",
      "perspective",
      "perspective-origin",
      "pointer-events",
      "position",
      "quotes",
      "resize",
      "right",
      "src",
      // @font-face
      "tab-size",
      "table-layout",
      "text-align",
      "text-align-last",
      "text-decoration",
      "text-decoration-color",
      "text-decoration-line",
      "text-decoration-style",
      "text-indent",
      "text-overflow",
      "text-rendering",
      "text-shadow",
      "text-transform",
      "text-underline-position",
      "top",
      "transform",
      "transform-origin",
      "transform-style",
      "transition",
      "transition-delay",
      "transition-duration",
      "transition-property",
      "transition-timing-function",
      "unicode-bidi",
      "vertical-align",
      "visibility",
      "white-space",
      "widows",
      "width",
      "word-break",
      "word-spacing",
      "word-wrap",
      "z-index"
      // reverse makes sure longer attributes `font-weight` are matched fully
      // instead of getting false positives on say `font`
    ].reverse();
    function stylus(hljs5) {
      const modes = MODES2(hljs5);
      const AT_MODIFIERS = "and or not only";
      const VARIABLE = {
        className: "variable",
        begin: "\\$" + hljs5.IDENT_RE
      };
      const AT_KEYWORDS = [
        "charset",
        "css",
        "debug",
        "extend",
        "font-face",
        "for",
        "import",
        "include",
        "keyframes",
        "media",
        "mixin",
        "page",
        "warn",
        "while"
      ];
      const LOOKAHEAD_TAG_END = "(?=[.\\s\\n[:,(])";
      const ILLEGAL = [
        "\\?",
        "(\\bReturn\\b)",
        // monkey
        "(\\bEnd\\b)",
        // monkey
        "(\\bend\\b)",
        // vbscript
        "(\\bdef\\b)",
        // gradle
        ";",
        // a whole lot of languages
        "#\\s",
        // markdown
        "\\*\\s",
        // markdown
        "===\\s",
        // markdown
        "\\|",
        "%"
        // prolog
      ];
      return {
        name: "Stylus",
        aliases: ["styl"],
        case_insensitive: false,
        keywords: "if else for in",
        illegal: "(" + ILLEGAL.join("|") + ")",
        contains: [
          // strings
          hljs5.QUOTE_STRING_MODE,
          hljs5.APOS_STRING_MODE,
          // comments
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          // hex colors
          modes.HEXCOLOR,
          // class tag
          {
            begin: "\\.[a-zA-Z][a-zA-Z0-9_-]*" + LOOKAHEAD_TAG_END,
            className: "selector-class"
          },
          // id tag
          {
            begin: "#[a-zA-Z][a-zA-Z0-9_-]*" + LOOKAHEAD_TAG_END,
            className: "selector-id"
          },
          // tags
          {
            begin: "\\b(" + TAGS2.join("|") + ")" + LOOKAHEAD_TAG_END,
            className: "selector-tag"
          },
          // psuedo selectors
          {
            className: "selector-pseudo",
            begin: "&?:(" + PSEUDO_CLASSES2.join("|") + ")" + LOOKAHEAD_TAG_END
          },
          {
            className: "selector-pseudo",
            begin: "&?::(" + PSEUDO_ELEMENTS2.join("|") + ")" + LOOKAHEAD_TAG_END
          },
          modes.ATTRIBUTE_SELECTOR_MODE,
          {
            className: "keyword",
            begin: /@media/,
            starts: {
              end: /[{;}]/,
              keywords: {
                $pattern: /[a-z-]+/,
                keyword: AT_MODIFIERS,
                attribute: MEDIA_FEATURES2.join(" ")
              },
              contains: [hljs5.CSS_NUMBER_MODE]
            }
          },
          // @ keywords
          {
            className: "keyword",
            begin: "@((-(o|moz|ms|webkit)-)?(" + AT_KEYWORDS.join("|") + "))\\b"
          },
          // variables
          VARIABLE,
          // dimension
          hljs5.CSS_NUMBER_MODE,
          // functions
          //  - only from beginning of line + whitespace
          {
            className: "function",
            begin: "^[a-zA-Z][a-zA-Z0-9_-]*\\(.*\\)",
            illegal: "[\\n]",
            returnBegin: true,
            contains: [
              {
                className: "title",
                begin: "\\b[a-zA-Z][a-zA-Z0-9_-]*"
              },
              {
                className: "params",
                begin: /\(/,
                end: /\)/,
                contains: [
                  modes.HEXCOLOR,
                  VARIABLE,
                  hljs5.APOS_STRING_MODE,
                  hljs5.CSS_NUMBER_MODE,
                  hljs5.QUOTE_STRING_MODE
                ]
              }
            ]
          },
          // attributes
          //  - only from beginning of line + whitespace
          //  - must have whitespace after it
          {
            className: "attribute",
            begin: "\\b(" + ATTRIBUTES2.join("|") + ")\\b",
            starts: {
              // value container
              end: /;|$/,
              contains: [
                modes.HEXCOLOR,
                VARIABLE,
                hljs5.APOS_STRING_MODE,
                hljs5.QUOTE_STRING_MODE,
                hljs5.CSS_NUMBER_MODE,
                hljs5.C_BLOCK_COMMENT_MODE,
                modes.IMPORTANT
              ],
              illegal: /\./,
              relevance: 0
            }
          }
        ]
      };
    }
    module.exports = stylus;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/subunit.js
var require_subunit = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/subunit.js"(exports, module) {
    init_process_shim();
    function subunit(hljs5) {
      const DETAILS = {
        className: "string",
        begin: "\\[\n(multipart)?",
        end: "\\]\n"
      };
      const TIME = {
        className: "string",
        begin: "\\d{4}-\\d{2}-\\d{2}(\\s+)\\d{2}:\\d{2}:\\d{2}.\\d+Z"
      };
      const PROGRESSVALUE = {
        className: "string",
        begin: "(\\+|-)\\d+"
      };
      const KEYWORDS3 = {
        className: "keyword",
        relevance: 10,
        variants: [
          {
            begin: "^(test|testing|success|successful|failure|error|skip|xfail|uxsuccess)(:?)\\s+(test)?"
          },
          {
            begin: "^progress(:?)(\\s+)?(pop|push)?"
          },
          {
            begin: "^tags:"
          },
          {
            begin: "^time:"
          }
        ]
      };
      return {
        name: "SubUnit",
        case_insensitive: true,
        contains: [
          DETAILS,
          TIME,
          PROGRESSVALUE,
          KEYWORDS3
        ]
      };
    }
    module.exports = subunit;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/swift.js
var require_swift = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/swift.js"(exports, module) {
    init_process_shim();
    function source(re2) {
      if (!re2) return null;
      if (typeof re2 === "string") return re2;
      return re2.source;
    }
    function lookahead(re2) {
      return concat("(?=", re2, ")");
    }
    function concat(...args) {
      const joined = args.map((x2) => source(x2)).join("");
      return joined;
    }
    function either(...args) {
      const joined = "(" + args.map((x2) => source(x2)).join("|") + ")";
      return joined;
    }
    var keywordWrapper = (keyword) => concat(
      /\b/,
      keyword,
      /\w$/.test(keyword) ? /\b/ : /\B/
    );
    var dotKeywords = [
      "Protocol",
      // contextual
      "Type"
      // contextual
    ].map(keywordWrapper);
    var optionalDotKeywords = [
      "init",
      "self"
    ].map(keywordWrapper);
    var keywordTypes = [
      "Any",
      "Self"
    ];
    var keywords = [
      // strings below will be fed into the regular `keywords` engine while regex
      // will result in additional modes being created to scan for those keywords to
      // avoid conflicts with other rules
      "associatedtype",
      "async",
      "await",
      /as\?/,
      // operator
      /as!/,
      // operator
      "as",
      // operator
      "break",
      "case",
      "catch",
      "class",
      "continue",
      "convenience",
      // contextual
      "default",
      "defer",
      "deinit",
      "didSet",
      // contextual
      "do",
      "dynamic",
      // contextual
      "else",
      "enum",
      "extension",
      "fallthrough",
      /fileprivate\(set\)/,
      "fileprivate",
      "final",
      // contextual
      "for",
      "func",
      "get",
      // contextual
      "guard",
      "if",
      "import",
      "indirect",
      // contextual
      "infix",
      // contextual
      /init\?/,
      /init!/,
      "inout",
      /internal\(set\)/,
      "internal",
      "in",
      "is",
      // operator
      "lazy",
      // contextual
      "let",
      "mutating",
      // contextual
      "nonmutating",
      // contextual
      /open\(set\)/,
      // contextual
      "open",
      // contextual
      "operator",
      "optional",
      // contextual
      "override",
      // contextual
      "postfix",
      // contextual
      "precedencegroup",
      "prefix",
      // contextual
      /private\(set\)/,
      "private",
      "protocol",
      /public\(set\)/,
      "public",
      "repeat",
      "required",
      // contextual
      "rethrows",
      "return",
      "set",
      // contextual
      "some",
      // contextual
      "static",
      "struct",
      "subscript",
      "super",
      "switch",
      "throws",
      "throw",
      /try\?/,
      // operator
      /try!/,
      // operator
      "try",
      // operator
      "typealias",
      /unowned\(safe\)/,
      // contextual
      /unowned\(unsafe\)/,
      // contextual
      "unowned",
      // contextual
      "var",
      "weak",
      // contextual
      "where",
      "while",
      "willSet"
      // contextual
    ];
    var literals = [
      "false",
      "nil",
      "true"
    ];
    var precedencegroupKeywords = [
      "assignment",
      "associativity",
      "higherThan",
      "left",
      "lowerThan",
      "none",
      "right"
    ];
    var numberSignKeywords = [
      "#colorLiteral",
      "#column",
      "#dsohandle",
      "#else",
      "#elseif",
      "#endif",
      "#error",
      "#file",
      "#fileID",
      "#fileLiteral",
      "#filePath",
      "#function",
      "#if",
      "#imageLiteral",
      "#keyPath",
      "#line",
      "#selector",
      "#sourceLocation",
      "#warn_unqualified_access",
      "#warning"
    ];
    var builtIns = [
      "abs",
      "all",
      "any",
      "assert",
      "assertionFailure",
      "debugPrint",
      "dump",
      "fatalError",
      "getVaList",
      "isKnownUniquelyReferenced",
      "max",
      "min",
      "numericCast",
      "pointwiseMax",
      "pointwiseMin",
      "precondition",
      "preconditionFailure",
      "print",
      "readLine",
      "repeatElement",
      "sequence",
      "stride",
      "swap",
      "swift_unboxFromSwiftValueWithType",
      "transcode",
      "type",
      "unsafeBitCast",
      "unsafeDowncast",
      "withExtendedLifetime",
      "withUnsafeMutablePointer",
      "withUnsafePointer",
      "withVaList",
      "withoutActuallyEscaping",
      "zip"
    ];
    var operatorHead = either(
      /[/=\-+!*%<>&|^~?]/,
      /[\u00A1-\u00A7]/,
      /[\u00A9\u00AB]/,
      /[\u00AC\u00AE]/,
      /[\u00B0\u00B1]/,
      /[\u00B6\u00BB\u00BF\u00D7\u00F7]/,
      /[\u2016-\u2017]/,
      /[\u2020-\u2027]/,
      /[\u2030-\u203E]/,
      /[\u2041-\u2053]/,
      /[\u2055-\u205E]/,
      /[\u2190-\u23FF]/,
      /[\u2500-\u2775]/,
      /[\u2794-\u2BFF]/,
      /[\u2E00-\u2E7F]/,
      /[\u3001-\u3003]/,
      /[\u3008-\u3020]/,
      /[\u3030]/
    );
    var operatorCharacter = either(
      operatorHead,
      /[\u0300-\u036F]/,
      /[\u1DC0-\u1DFF]/,
      /[\u20D0-\u20FF]/,
      /[\uFE00-\uFE0F]/,
      /[\uFE20-\uFE2F]/
      // TODO: The following characters are also allowed, but the regex isn't supported yet.
      // /[\u{E0100}-\u{E01EF}]/u
    );
    var operator = concat(operatorHead, operatorCharacter, "*");
    var identifierHead = either(
      /[a-zA-Z_]/,
      /[\u00A8\u00AA\u00AD\u00AF\u00B2-\u00B5\u00B7-\u00BA]/,
      /[\u00BC-\u00BE\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF]/,
      /[\u0100-\u02FF\u0370-\u167F\u1681-\u180D\u180F-\u1DBF]/,
      /[\u1E00-\u1FFF]/,
      /[\u200B-\u200D\u202A-\u202E\u203F-\u2040\u2054\u2060-\u206F]/,
      /[\u2070-\u20CF\u2100-\u218F\u2460-\u24FF\u2776-\u2793]/,
      /[\u2C00-\u2DFF\u2E80-\u2FFF]/,
      /[\u3004-\u3007\u3021-\u302F\u3031-\u303F\u3040-\uD7FF]/,
      /[\uF900-\uFD3D\uFD40-\uFDCF\uFDF0-\uFE1F\uFE30-\uFE44]/,
      /[\uFE47-\uFEFE\uFF00-\uFFFD]/
      // Should be /[\uFE47-\uFFFD]/, but we have to exclude FEFF.
      // The following characters are also allowed, but the regexes aren't supported yet.
      // /[\u{10000}-\u{1FFFD}\u{20000-\u{2FFFD}\u{30000}-\u{3FFFD}\u{40000}-\u{4FFFD}]/u,
      // /[\u{50000}-\u{5FFFD}\u{60000-\u{6FFFD}\u{70000}-\u{7FFFD}\u{80000}-\u{8FFFD}]/u,
      // /[\u{90000}-\u{9FFFD}\u{A0000-\u{AFFFD}\u{B0000}-\u{BFFFD}\u{C0000}-\u{CFFFD}]/u,
      // /[\u{D0000}-\u{DFFFD}\u{E0000-\u{EFFFD}]/u
    );
    var identifierCharacter = either(
      identifierHead,
      /\d/,
      /[\u0300-\u036F\u1DC0-\u1DFF\u20D0-\u20FF\uFE20-\uFE2F]/
    );
    var identifier = concat(identifierHead, identifierCharacter, "*");
    var typeIdentifier = concat(/[A-Z]/, identifierCharacter, "*");
    var keywordAttributes = [
      "autoclosure",
      concat(/convention\(/, either("swift", "block", "c"), /\)/),
      "discardableResult",
      "dynamicCallable",
      "dynamicMemberLookup",
      "escaping",
      "frozen",
      "GKInspectable",
      "IBAction",
      "IBDesignable",
      "IBInspectable",
      "IBOutlet",
      "IBSegueAction",
      "inlinable",
      "main",
      "nonobjc",
      "NSApplicationMain",
      "NSCopying",
      "NSManaged",
      concat(/objc\(/, identifier, /\)/),
      "objc",
      "objcMembers",
      "propertyWrapper",
      "requires_stored_property_inits",
      "testable",
      "UIApplicationMain",
      "unknown",
      "usableFromInline"
    ];
    var availabilityKeywords = [
      "iOS",
      "iOSApplicationExtension",
      "macOS",
      "macOSApplicationExtension",
      "macCatalyst",
      "macCatalystApplicationExtension",
      "watchOS",
      "watchOSApplicationExtension",
      "tvOS",
      "tvOSApplicationExtension",
      "swift"
    ];
    function swift(hljs5) {
      const WHITESPACE = {
        match: /\s+/,
        relevance: 0
      };
      const BLOCK_COMMENT = hljs5.COMMENT(
        "/\\*",
        "\\*/",
        {
          contains: ["self"]
        }
      );
      const COMMENTS = [
        hljs5.C_LINE_COMMENT_MODE,
        BLOCK_COMMENT
      ];
      const DOT_KEYWORD = {
        className: "keyword",
        begin: concat(/\./, lookahead(either(...dotKeywords, ...optionalDotKeywords))),
        end: either(...dotKeywords, ...optionalDotKeywords),
        excludeBegin: true
      };
      const KEYWORD_GUARD = {
        // Consume .keyword to prevent highlighting properties and methods as keywords.
        match: concat(/\./, either(...keywords)),
        relevance: 0
      };
      const PLAIN_KEYWORDS = keywords.filter((kw) => typeof kw === "string").concat(["_|0"]);
      const REGEX_KEYWORDS = keywords.filter((kw) => typeof kw !== "string").concat(keywordTypes).map(keywordWrapper);
      const KEYWORD = {
        variants: [
          {
            className: "keyword",
            match: either(...REGEX_KEYWORDS, ...optionalDotKeywords)
          }
        ]
      };
      const KEYWORDS3 = {
        $pattern: either(
          /\b\w+/,
          // regular keywords
          /#\w+/
          // number keywords
        ),
        keyword: PLAIN_KEYWORDS.concat(numberSignKeywords),
        literal: literals
      };
      const KEYWORD_MODES = [
        DOT_KEYWORD,
        KEYWORD_GUARD,
        KEYWORD
      ];
      const BUILT_IN_GUARD = {
        // Consume .built_in to prevent highlighting properties and methods.
        match: concat(/\./, either(...builtIns)),
        relevance: 0
      };
      const BUILT_IN = {
        className: "built_in",
        match: concat(/\b/, either(...builtIns), /(?=\()/)
      };
      const BUILT_INS3 = [
        BUILT_IN_GUARD,
        BUILT_IN
      ];
      const OPERATOR_GUARD = {
        // Prevent -> from being highlighting as an operator.
        match: /->/,
        relevance: 0
      };
      const OPERATOR = {
        className: "operator",
        relevance: 0,
        variants: [
          {
            match: operator
          },
          {
            // dot-operator: only operators that start with a dot are allowed to use dots as
            // characters (..., ...<, .*, etc). So there rule here is: a dot followed by one or more
            // characters that may also include dots.
            match: `\\.(\\.|${operatorCharacter})+`
          }
        ]
      };
      const OPERATORS = [
        OPERATOR_GUARD,
        OPERATOR
      ];
      const decimalDigits = "([0-9]_*)+";
      const hexDigits = "([0-9a-fA-F]_*)+";
      const NUMBER = {
        className: "number",
        relevance: 0,
        variants: [
          // decimal floating-point-literal (subsumes decimal-literal)
          {
            match: `\\b(${decimalDigits})(\\.(${decimalDigits}))?([eE][+-]?(${decimalDigits}))?\\b`
          },
          // hexadecimal floating-point-literal (subsumes hexadecimal-literal)
          {
            match: `\\b0x(${hexDigits})(\\.(${hexDigits}))?([pP][+-]?(${decimalDigits}))?\\b`
          },
          // octal-literal
          {
            match: /\b0o([0-7]_*)+\b/
          },
          // binary-literal
          {
            match: /\b0b([01]_*)+\b/
          }
        ]
      };
      const ESCAPED_CHARACTER = (rawDelimiter = "") => ({
        className: "subst",
        variants: [
          {
            match: concat(/\\/, rawDelimiter, /[0\\tnr"']/)
          },
          {
            match: concat(/\\/, rawDelimiter, /u\{[0-9a-fA-F]{1,8}\}/)
          }
        ]
      });
      const ESCAPED_NEWLINE = (rawDelimiter = "") => ({
        className: "subst",
        match: concat(/\\/, rawDelimiter, /[\t ]*(?:[\r\n]|\r\n)/)
      });
      const INTERPOLATION = (rawDelimiter = "") => ({
        className: "subst",
        label: "interpol",
        begin: concat(/\\/, rawDelimiter, /\(/),
        end: /\)/
      });
      const MULTILINE_STRING = (rawDelimiter = "") => ({
        begin: concat(rawDelimiter, /"""/),
        end: concat(/"""/, rawDelimiter),
        contains: [
          ESCAPED_CHARACTER(rawDelimiter),
          ESCAPED_NEWLINE(rawDelimiter),
          INTERPOLATION(rawDelimiter)
        ]
      });
      const SINGLE_LINE_STRING = (rawDelimiter = "") => ({
        begin: concat(rawDelimiter, /"/),
        end: concat(/"/, rawDelimiter),
        contains: [
          ESCAPED_CHARACTER(rawDelimiter),
          INTERPOLATION(rawDelimiter)
        ]
      });
      const STRING = {
        className: "string",
        variants: [
          MULTILINE_STRING(),
          MULTILINE_STRING("#"),
          MULTILINE_STRING("##"),
          MULTILINE_STRING("###"),
          SINGLE_LINE_STRING(),
          SINGLE_LINE_STRING("#"),
          SINGLE_LINE_STRING("##"),
          SINGLE_LINE_STRING("###")
        ]
      };
      const QUOTED_IDENTIFIER = {
        match: concat(/`/, identifier, /`/)
      };
      const IMPLICIT_PARAMETER = {
        className: "variable",
        match: /\$\d+/
      };
      const PROPERTY_WRAPPER_PROJECTION = {
        className: "variable",
        match: `\\$${identifierCharacter}+`
      };
      const IDENTIFIERS = [
        QUOTED_IDENTIFIER,
        IMPLICIT_PARAMETER,
        PROPERTY_WRAPPER_PROJECTION
      ];
      const AVAILABLE_ATTRIBUTE = {
        match: /(@|#)available/,
        className: "keyword",
        starts: {
          contains: [
            {
              begin: /\(/,
              end: /\)/,
              keywords: availabilityKeywords,
              contains: [
                ...OPERATORS,
                NUMBER,
                STRING
              ]
            }
          ]
        }
      };
      const KEYWORD_ATTRIBUTE = {
        className: "keyword",
        match: concat(/@/, either(...keywordAttributes))
      };
      const USER_DEFINED_ATTRIBUTE = {
        className: "meta",
        match: concat(/@/, identifier)
      };
      const ATTRIBUTES2 = [
        AVAILABLE_ATTRIBUTE,
        KEYWORD_ATTRIBUTE,
        USER_DEFINED_ATTRIBUTE
      ];
      const TYPE = {
        match: lookahead(/\b[A-Z]/),
        relevance: 0,
        contains: [
          {
            // Common Apple frameworks, for relevance boost
            className: "type",
            match: concat(/(AV|CA|CF|CG|CI|CL|CM|CN|CT|MK|MP|MTK|MTL|NS|SCN|SK|UI|WK|XC)/, identifierCharacter, "+")
          },
          {
            // Type identifier
            className: "type",
            match: typeIdentifier,
            relevance: 0
          },
          {
            // Optional type
            match: /[?!]+/,
            relevance: 0
          },
          {
            // Variadic parameter
            match: /\.\.\./,
            relevance: 0
          },
          {
            // Protocol composition
            match: concat(/\s+&\s+/, lookahead(typeIdentifier)),
            relevance: 0
          }
        ]
      };
      const GENERIC_ARGUMENTS = {
        begin: /</,
        end: />/,
        keywords: KEYWORDS3,
        contains: [
          ...COMMENTS,
          ...KEYWORD_MODES,
          ...ATTRIBUTES2,
          OPERATOR_GUARD,
          TYPE
        ]
      };
      TYPE.contains.push(GENERIC_ARGUMENTS);
      const TUPLE_ELEMENT_NAME = {
        match: concat(identifier, /\s*:/),
        keywords: "_|0",
        relevance: 0
      };
      const TUPLE = {
        begin: /\(/,
        end: /\)/,
        relevance: 0,
        keywords: KEYWORDS3,
        contains: [
          "self",
          TUPLE_ELEMENT_NAME,
          ...COMMENTS,
          ...KEYWORD_MODES,
          ...BUILT_INS3,
          ...OPERATORS,
          NUMBER,
          STRING,
          ...IDENTIFIERS,
          ...ATTRIBUTES2,
          TYPE
        ]
      };
      const FUNC_PLUS_TITLE = {
        beginKeywords: "func",
        contains: [
          {
            className: "title",
            match: either(QUOTED_IDENTIFIER.match, identifier, operator),
            // Required to make sure the opening < of the generic parameter clause
            // isn't parsed as a second title.
            endsParent: true,
            relevance: 0
          },
          WHITESPACE
        ]
      };
      const GENERIC_PARAMETERS = {
        begin: /</,
        end: />/,
        contains: [
          ...COMMENTS,
          TYPE
        ]
      };
      const FUNCTION_PARAMETER_NAME = {
        begin: either(
          lookahead(concat(identifier, /\s*:/)),
          lookahead(concat(identifier, /\s+/, identifier, /\s*:/))
        ),
        end: /:/,
        relevance: 0,
        contains: [
          {
            className: "keyword",
            match: /\b_\b/
          },
          {
            className: "params",
            match: identifier
          }
        ]
      };
      const FUNCTION_PARAMETERS = {
        begin: /\(/,
        end: /\)/,
        keywords: KEYWORDS3,
        contains: [
          FUNCTION_PARAMETER_NAME,
          ...COMMENTS,
          ...KEYWORD_MODES,
          ...OPERATORS,
          NUMBER,
          STRING,
          ...ATTRIBUTES2,
          TYPE,
          TUPLE
        ],
        endsParent: true,
        illegal: /["']/
      };
      const FUNCTION = {
        className: "function",
        match: lookahead(/\bfunc\b/),
        contains: [
          FUNC_PLUS_TITLE,
          GENERIC_PARAMETERS,
          FUNCTION_PARAMETERS,
          WHITESPACE
        ],
        illegal: [
          /\[/,
          /%/
        ]
      };
      const INIT_SUBSCRIPT = {
        className: "function",
        match: /\b(subscript|init[?!]?)\s*(?=[<(])/,
        keywords: {
          keyword: "subscript init init? init!",
          $pattern: /\w+[?!]?/
        },
        contains: [
          GENERIC_PARAMETERS,
          FUNCTION_PARAMETERS,
          WHITESPACE
        ],
        illegal: /\[|%/
      };
      const OPERATOR_DECLARATION = {
        beginKeywords: "operator",
        end: hljs5.MATCH_NOTHING_RE,
        contains: [
          {
            className: "title",
            match: operator,
            endsParent: true,
            relevance: 0
          }
        ]
      };
      const PRECEDENCEGROUP = {
        beginKeywords: "precedencegroup",
        end: hljs5.MATCH_NOTHING_RE,
        contains: [
          {
            className: "title",
            match: typeIdentifier,
            relevance: 0
          },
          {
            begin: /{/,
            end: /}/,
            relevance: 0,
            endsParent: true,
            keywords: [
              ...precedencegroupKeywords,
              ...literals
            ],
            contains: [TYPE]
          }
        ]
      };
      for (const variant of STRING.variants) {
        const interpolation = variant.contains.find((mode) => mode.label === "interpol");
        interpolation.keywords = KEYWORDS3;
        const submodes = [
          ...KEYWORD_MODES,
          ...BUILT_INS3,
          ...OPERATORS,
          NUMBER,
          STRING,
          ...IDENTIFIERS
        ];
        interpolation.contains = [
          ...submodes,
          {
            begin: /\(/,
            end: /\)/,
            contains: [
              "self",
              ...submodes
            ]
          }
        ];
      }
      return {
        name: "Swift",
        keywords: KEYWORDS3,
        contains: [
          ...COMMENTS,
          FUNCTION,
          INIT_SUBSCRIPT,
          {
            className: "class",
            beginKeywords: "struct protocol class extension enum",
            end: "\\{",
            excludeEnd: true,
            keywords: KEYWORDS3,
            contains: [
              hljs5.inherit(hljs5.TITLE_MODE, {
                begin: /[A-Za-z$_][\u00C0-\u02B80-9A-Za-z$_]*/
              }),
              ...KEYWORD_MODES
            ]
          },
          OPERATOR_DECLARATION,
          PRECEDENCEGROUP,
          {
            beginKeywords: "import",
            end: /$/,
            contains: [...COMMENTS],
            relevance: 0
          },
          ...KEYWORD_MODES,
          ...BUILT_INS3,
          ...OPERATORS,
          NUMBER,
          STRING,
          ...IDENTIFIERS,
          ...ATTRIBUTES2,
          TYPE,
          TUPLE
        ]
      };
    }
    module.exports = swift;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/taggerscript.js
var require_taggerscript = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/taggerscript.js"(exports, module) {
    init_process_shim();
    function taggerscript(hljs5) {
      const COMMENT = {
        className: "comment",
        begin: /\$noop\(/,
        end: /\)/,
        contains: [{
          begin: /\(/,
          end: /\)/,
          contains: [
            "self",
            {
              begin: /\\./
            }
          ]
        }],
        relevance: 10
      };
      const FUNCTION = {
        className: "keyword",
        begin: /\$(?!noop)[a-zA-Z][_a-zA-Z0-9]*/,
        end: /\(/,
        excludeEnd: true
      };
      const VARIABLE = {
        className: "variable",
        begin: /%[_a-zA-Z0-9:]*/,
        end: "%"
      };
      const ESCAPE_SEQUENCE = {
        className: "symbol",
        begin: /\\./
      };
      return {
        name: "Tagger Script",
        contains: [
          COMMENT,
          FUNCTION,
          VARIABLE,
          ESCAPE_SEQUENCE
        ]
      };
    }
    module.exports = taggerscript;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/yaml.js
var require_yaml = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/yaml.js"(exports, module) {
    init_process_shim();
    function yaml(hljs5) {
      var LITERALS3 = "true false yes no null";
      var URI_CHARACTERS = "[\\w#;/?:@&=+$,.~*'()[\\]]+";
      var KEY = {
        className: "attr",
        variants: [
          { begin: "\\w[\\w :\\/.-]*:(?=[ 	]|$)" },
          { begin: '"\\w[\\w :\\/.-]*":(?=[ 	]|$)' },
          // double quoted keys
          { begin: "'\\w[\\w :\\/.-]*':(?=[ 	]|$)" }
          // single quoted keys
        ]
      };
      var TEMPLATE_VARIABLES = {
        className: "template-variable",
        variants: [
          { begin: /\{\{/, end: /\}\}/ },
          // jinja templates Ansible
          { begin: /%\{/, end: /\}/ }
          // Ruby i18n
        ]
      };
      var STRING = {
        className: "string",
        relevance: 0,
        variants: [
          { begin: /'/, end: /'/ },
          { begin: /"/, end: /"/ },
          { begin: /\S+/ }
        ],
        contains: [
          hljs5.BACKSLASH_ESCAPE,
          TEMPLATE_VARIABLES
        ]
      };
      var CONTAINER_STRING = hljs5.inherit(STRING, {
        variants: [
          { begin: /'/, end: /'/ },
          { begin: /"/, end: /"/ },
          { begin: /[^\s,{}[\]]+/ }
        ]
      });
      var DATE_RE = "[0-9]{4}(-[0-9][0-9]){0,2}";
      var TIME_RE = "([Tt \\t][0-9][0-9]?(:[0-9][0-9]){2})?";
      var FRACTION_RE = "(\\.[0-9]*)?";
      var ZONE_RE = "([ \\t])*(Z|[-+][0-9][0-9]?(:[0-9][0-9])?)?";
      var TIMESTAMP = {
        className: "number",
        begin: "\\b" + DATE_RE + TIME_RE + FRACTION_RE + ZONE_RE + "\\b"
      };
      var VALUE_CONTAINER = {
        end: ",",
        endsWithParent: true,
        excludeEnd: true,
        keywords: LITERALS3,
        relevance: 0
      };
      var OBJECT = {
        begin: /\{/,
        end: /\}/,
        contains: [VALUE_CONTAINER],
        illegal: "\\n",
        relevance: 0
      };
      var ARRAY = {
        begin: "\\[",
        end: "\\]",
        contains: [VALUE_CONTAINER],
        illegal: "\\n",
        relevance: 0
      };
      var MODES2 = [
        KEY,
        {
          className: "meta",
          begin: "^---\\s*$",
          relevance: 10
        },
        {
          // multi line string
          // Blocks start with a | or > followed by a newline
          //
          // Indentation of subsequent lines must be the same to
          // be considered part of the block
          className: "string",
          begin: "[\\|>]([1-9]?[+-])?[ ]*\\n( +)[^ ][^\\n]*\\n(\\2[^\\n]+\\n?)*"
        },
        {
          // Ruby/Rails erb
          begin: "<%[%=-]?",
          end: "[%-]?%>",
          subLanguage: "ruby",
          excludeBegin: true,
          excludeEnd: true,
          relevance: 0
        },
        {
          // named tags
          className: "type",
          begin: "!\\w+!" + URI_CHARACTERS
        },
        // https://yaml.org/spec/1.2/spec.html#id2784064
        {
          // verbatim tags
          className: "type",
          begin: "!<" + URI_CHARACTERS + ">"
        },
        {
          // primary tags
          className: "type",
          begin: "!" + URI_CHARACTERS
        },
        {
          // secondary tags
          className: "type",
          begin: "!!" + URI_CHARACTERS
        },
        {
          // fragment id &ref
          className: "meta",
          begin: "&" + hljs5.UNDERSCORE_IDENT_RE + "$"
        },
        {
          // fragment reference *ref
          className: "meta",
          begin: "\\*" + hljs5.UNDERSCORE_IDENT_RE + "$"
        },
        {
          // array listing
          className: "bullet",
          // TODO: remove |$ hack when we have proper look-ahead support
          begin: "-(?=[ ]|$)",
          relevance: 0
        },
        hljs5.HASH_COMMENT_MODE,
        {
          beginKeywords: LITERALS3,
          keywords: { literal: LITERALS3 }
        },
        TIMESTAMP,
        // numbers are any valid C-style number that
        // sit isolated from other words
        {
          className: "number",
          begin: hljs5.C_NUMBER_RE + "\\b",
          relevance: 0
        },
        OBJECT,
        ARRAY,
        STRING
      ];
      var VALUE_MODES = [...MODES2];
      VALUE_MODES.pop();
      VALUE_MODES.push(CONTAINER_STRING);
      VALUE_CONTAINER.contains = VALUE_MODES;
      return {
        name: "YAML",
        case_insensitive: true,
        aliases: ["yml"],
        contains: MODES2
      };
    }
    module.exports = yaml;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/tap.js
var require_tap = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/tap.js"(exports, module) {
    init_process_shim();
    function tap(hljs5) {
      return {
        name: "Test Anything Protocol",
        case_insensitive: true,
        contains: [
          hljs5.HASH_COMMENT_MODE,
          // version of format and total amount of testcases
          {
            className: "meta",
            variants: [
              {
                begin: "^TAP version (\\d+)$"
              },
              {
                begin: "^1\\.\\.(\\d+)$"
              }
            ]
          },
          // YAML block
          {
            begin: /---$/,
            end: "\\.\\.\\.$",
            subLanguage: "yaml",
            relevance: 0
          },
          // testcase number
          {
            className: "number",
            begin: " (\\d+) "
          },
          // testcase status and description
          {
            className: "symbol",
            variants: [
              {
                begin: "^ok"
              },
              {
                begin: "^not ok"
              }
            ]
          }
        ]
      };
    }
    module.exports = tap;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/tcl.js
var require_tcl = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/tcl.js"(exports, module) {
    init_process_shim();
    function source(re2) {
      if (!re2) return null;
      if (typeof re2 === "string") return re2;
      return re2.source;
    }
    function optional(re2) {
      return concat("(", re2, ")?");
    }
    function concat(...args) {
      const joined = args.map((x2) => source(x2)).join("");
      return joined;
    }
    function tcl(hljs5) {
      const TCL_IDENT = /[a-zA-Z_][a-zA-Z0-9_]*/;
      const NUMBER = {
        className: "number",
        variants: [hljs5.BINARY_NUMBER_MODE, hljs5.C_NUMBER_MODE]
      };
      return {
        name: "Tcl",
        aliases: ["tk"],
        keywords: "after append apply array auto_execok auto_import auto_load auto_mkindex auto_mkindex_old auto_qualify auto_reset bgerror binary break catch cd chan clock close concat continue dde dict encoding eof error eval exec exit expr fblocked fconfigure fcopy file fileevent filename flush for foreach format gets glob global history http if incr info interp join lappend|10 lassign|10 lindex|10 linsert|10 list llength|10 load lrange|10 lrepeat|10 lreplace|10 lreverse|10 lsearch|10 lset|10 lsort|10 mathfunc mathop memory msgcat namespace open package parray pid pkg::create pkg_mkIndex platform platform::shell proc puts pwd read refchan regexp registry regsub|10 rename return safe scan seek set socket source split string subst switch tcl_endOfWord tcl_findLibrary tcl_startOfNextWord tcl_startOfPreviousWord tcl_wordBreakAfter tcl_wordBreakBefore tcltest tclvars tell time tm trace unknown unload unset update uplevel upvar variable vwait while",
        contains: [
          hljs5.COMMENT(";[ \\t]*#", "$"),
          hljs5.COMMENT("^[ \\t]*#", "$"),
          {
            beginKeywords: "proc",
            end: "[\\{]",
            excludeEnd: true,
            contains: [
              {
                className: "title",
                begin: "[ \\t\\n\\r]+(::)?[a-zA-Z_]((::)?[a-zA-Z0-9_])*",
                end: "[ \\t\\n\\r]",
                endsWithParent: true,
                excludeEnd: true
              }
            ]
          },
          {
            className: "variable",
            variants: [
              {
                begin: concat(
                  /\$/,
                  optional(/::/),
                  TCL_IDENT,
                  "(::",
                  TCL_IDENT,
                  ")*"
                )
              },
              {
                begin: "\\$\\{(::)?[a-zA-Z_]((::)?[a-zA-Z0-9_])*",
                end: "\\}",
                contains: [
                  NUMBER
                ]
              }
            ]
          },
          {
            className: "string",
            contains: [hljs5.BACKSLASH_ESCAPE],
            variants: [
              hljs5.inherit(hljs5.QUOTE_STRING_MODE, { illegal: null })
            ]
          },
          NUMBER
        ]
      };
    }
    module.exports = tcl;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/thrift.js
var require_thrift = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/thrift.js"(exports, module) {
    init_process_shim();
    function thrift(hljs5) {
      const BUILT_IN_TYPES = "bool byte i16 i32 i64 double string binary";
      return {
        name: "Thrift",
        keywords: {
          keyword: "namespace const typedef struct enum service exception void oneway set list map required optional",
          built_in: BUILT_IN_TYPES,
          literal: "true false"
        },
        contains: [
          hljs5.QUOTE_STRING_MODE,
          hljs5.NUMBER_MODE,
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          {
            className: "class",
            beginKeywords: "struct enum service exception",
            end: /\{/,
            illegal: /\n/,
            contains: [
              hljs5.inherit(hljs5.TITLE_MODE, {
                // hack: eating everything after the first title
                starts: {
                  endsWithParent: true,
                  excludeEnd: true
                }
              })
            ]
          },
          {
            begin: "\\b(set|list|map)\\s*<",
            end: ">",
            keywords: BUILT_IN_TYPES,
            contains: ["self"]
          }
        ]
      };
    }
    module.exports = thrift;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/tp.js
var require_tp = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/tp.js"(exports, module) {
    init_process_shim();
    function tp(hljs5) {
      const TPID = {
        className: "number",
        begin: "[1-9][0-9]*",
        /* no leading zeros */
        relevance: 0
      };
      const TPLABEL = {
        className: "symbol",
        begin: ":[^\\]]+"
      };
      const TPDATA = {
        className: "built_in",
        begin: "(AR|P|PAYLOAD|PR|R|SR|RSR|LBL|VR|UALM|MESSAGE|UTOOL|UFRAME|TIMER|TIMER_OVERFLOW|JOINT_MAX_SPEED|RESUME_PROG|DIAG_REC)\\[",
        end: "\\]",
        contains: [
          "self",
          TPID,
          TPLABEL
        ]
      };
      const TPIO = {
        className: "built_in",
        begin: "(AI|AO|DI|DO|F|RI|RO|UI|UO|GI|GO|SI|SO)\\[",
        end: "\\]",
        contains: [
          "self",
          TPID,
          hljs5.QUOTE_STRING_MODE,
          /* for pos section at bottom */
          TPLABEL
        ]
      };
      return {
        name: "TP",
        keywords: {
          keyword: "ABORT ACC ADJUST AND AP_LD BREAK CALL CNT COL CONDITION CONFIG DA DB DIV DETECT ELSE END ENDFOR ERR_NUM ERROR_PROG FINE FOR GP GUARD INC IF JMP LINEAR_MAX_SPEED LOCK MOD MONITOR OFFSET Offset OR OVERRIDE PAUSE PREG PTH RT_LD RUN SELECT SKIP Skip TA TB TO TOOL_OFFSET Tool_Offset UF UT UFRAME_NUM UTOOL_NUM UNLOCK WAIT X Y Z W P R STRLEN SUBSTR FINDSTR VOFFSET PROG ATTR MN POS",
          literal: "ON OFF max_speed LPOS JPOS ENABLE DISABLE START STOP RESET"
        },
        contains: [
          TPDATA,
          TPIO,
          {
            className: "keyword",
            begin: "/(PROG|ATTR|MN|POS|END)\\b"
          },
          {
            /* this is for cases like ,CALL */
            className: "keyword",
            begin: "(CALL|RUN|POINT_LOGIC|LBL)\\b"
          },
          {
            /* this is for cases like CNT100 where the default lexemes do not
             * separate the keyword and the number */
            className: "keyword",
            begin: "\\b(ACC|CNT|Skip|Offset|PSPD|RT_LD|AP_LD|Tool_Offset)"
          },
          {
            /* to catch numbers that do not have a word boundary on the left */
            className: "number",
            begin: "\\d+(sec|msec|mm/sec|cm/min|inch/min|deg/sec|mm|in|cm)?\\b",
            relevance: 0
          },
          hljs5.COMMENT("//", "[;$]"),
          hljs5.COMMENT("!", "[;$]"),
          hljs5.COMMENT("--eg:", "$"),
          hljs5.QUOTE_STRING_MODE,
          {
            className: "string",
            begin: "'",
            end: "'"
          },
          hljs5.C_NUMBER_MODE,
          {
            className: "variable",
            begin: "\\$[A-Za-z0-9_]+"
          }
        ]
      };
    }
    module.exports = tp;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/twig.js
var require_twig = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/twig.js"(exports, module) {
    init_process_shim();
    function twig(hljs5) {
      var PARAMS = {
        className: "params",
        begin: "\\(",
        end: "\\)"
      };
      var FUNCTION_NAMES = "attribute block constant cycle date dump include max min parent random range source template_from_string";
      var FUNCTIONS = {
        beginKeywords: FUNCTION_NAMES,
        keywords: { name: FUNCTION_NAMES },
        relevance: 0,
        contains: [
          PARAMS
        ]
      };
      var FILTER = {
        begin: /\|[A-Za-z_]+:?/,
        keywords: "abs batch capitalize column convert_encoding date date_modify default escape filter first format inky_to_html inline_css join json_encode keys last length lower map markdown merge nl2br number_format raw reduce replace reverse round slice sort spaceless split striptags title trim upper url_encode",
        contains: [
          FUNCTIONS
        ]
      };
      var TAGS2 = "apply autoescape block deprecated do embed extends filter flush for from if import include macro sandbox set use verbatim with";
      TAGS2 = TAGS2 + " " + TAGS2.split(" ").map(function(t6) {
        return "end" + t6;
      }).join(" ");
      return {
        name: "Twig",
        aliases: ["craftcms"],
        case_insensitive: true,
        subLanguage: "xml",
        contains: [
          hljs5.COMMENT(/\{#/, /#\}/),
          {
            className: "template-tag",
            begin: /\{%/,
            end: /%\}/,
            contains: [
              {
                className: "name",
                begin: /\w+/,
                keywords: TAGS2,
                starts: {
                  endsWithParent: true,
                  contains: [FILTER, FUNCTIONS],
                  relevance: 0
                }
              }
            ]
          },
          {
            className: "template-variable",
            begin: /\{\{/,
            end: /\}\}/,
            contains: ["self", FILTER, FUNCTIONS]
          }
        ]
      };
    }
    module.exports = twig;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/typescript.js
var require_typescript = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/typescript.js"(exports, module) {
    init_process_shim();
    var IDENT_RE3 = "[A-Za-z$_][0-9A-Za-z$_]*";
    var KEYWORDS3 = [
      "as",
      // for exports
      "in",
      "of",
      "if",
      "for",
      "while",
      "finally",
      "var",
      "new",
      "function",
      "do",
      "return",
      "void",
      "else",
      "break",
      "catch",
      "instanceof",
      "with",
      "throw",
      "case",
      "default",
      "try",
      "switch",
      "continue",
      "typeof",
      "delete",
      "let",
      "yield",
      "const",
      "class",
      // JS handles these with a special rule
      // "get",
      // "set",
      "debugger",
      "async",
      "await",
      "static",
      "import",
      "from",
      "export",
      "extends"
    ];
    var LITERALS3 = [
      "true",
      "false",
      "null",
      "undefined",
      "NaN",
      "Infinity"
    ];
    var TYPES3 = [
      "Intl",
      "DataView",
      "Number",
      "Math",
      "Date",
      "String",
      "RegExp",
      "Object",
      "Function",
      "Boolean",
      "Error",
      "Symbol",
      "Set",
      "Map",
      "WeakSet",
      "WeakMap",
      "Proxy",
      "Reflect",
      "JSON",
      "Promise",
      "Float64Array",
      "Int16Array",
      "Int32Array",
      "Int8Array",
      "Uint16Array",
      "Uint32Array",
      "Float32Array",
      "Array",
      "Uint8Array",
      "Uint8ClampedArray",
      "ArrayBuffer",
      "BigInt64Array",
      "BigUint64Array",
      "BigInt"
    ];
    var ERROR_TYPES3 = [
      "EvalError",
      "InternalError",
      "RangeError",
      "ReferenceError",
      "SyntaxError",
      "TypeError",
      "URIError"
    ];
    var BUILT_IN_GLOBALS3 = [
      "setInterval",
      "setTimeout",
      "clearInterval",
      "clearTimeout",
      "require",
      "exports",
      "eval",
      "isFinite",
      "isNaN",
      "parseFloat",
      "parseInt",
      "decodeURI",
      "decodeURIComponent",
      "encodeURI",
      "encodeURIComponent",
      "escape",
      "unescape"
    ];
    var BUILT_IN_VARIABLES3 = [
      "arguments",
      "this",
      "super",
      "console",
      "window",
      "document",
      "localStorage",
      "module",
      "global"
      // Node.js
    ];
    var BUILT_INS3 = [].concat(
      BUILT_IN_GLOBALS3,
      BUILT_IN_VARIABLES3,
      TYPES3,
      ERROR_TYPES3
    );
    function source(re2) {
      if (!re2) return null;
      if (typeof re2 === "string") return re2;
      return re2.source;
    }
    function lookahead(re2) {
      return concat("(?=", re2, ")");
    }
    function concat(...args) {
      const joined = args.map((x2) => source(x2)).join("");
      return joined;
    }
    function javascript3(hljs5) {
      const hasClosingTag = (match2, { after }) => {
        const tag = "</" + match2[0].slice(1);
        const pos = match2.input.indexOf(tag, after);
        return pos !== -1;
      };
      const IDENT_RE$1 = IDENT_RE3;
      const FRAGMENT = {
        begin: "<>",
        end: "</>"
      };
      const XML_TAG = {
        begin: /<[A-Za-z0-9\\._:-]+/,
        end: /\/[A-Za-z0-9\\._:-]+>|\/>/,
        /**
         * @param {RegExpMatchArray} match
         * @param {CallbackResponse} response
         */
        isTrulyOpeningTag: (match2, response) => {
          const afterMatchIndex = match2[0].length + match2.index;
          const nextChar = match2.input[afterMatchIndex];
          if (nextChar === "<") {
            response.ignoreMatch();
            return;
          }
          if (nextChar === ">") {
            if (!hasClosingTag(match2, { after: afterMatchIndex })) {
              response.ignoreMatch();
            }
          }
        }
      };
      const KEYWORDS$1 = {
        $pattern: IDENT_RE3,
        keyword: KEYWORDS3,
        literal: LITERALS3,
        built_in: BUILT_INS3
      };
      const decimalDigits = "[0-9](_?[0-9])*";
      const frac = `\\.(${decimalDigits})`;
      const decimalInteger = `0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*`;
      const NUMBER = {
        className: "number",
        variants: [
          // DecimalLiteral
          { begin: `(\\b(${decimalInteger})((${frac})|\\.)?|(${frac}))[eE][+-]?(${decimalDigits})\\b` },
          { begin: `\\b(${decimalInteger})\\b((${frac})\\b|\\.)?|(${frac})\\b` },
          // DecimalBigIntegerLiteral
          { begin: `\\b(0|[1-9](_?[0-9])*)n\\b` },
          // NonDecimalIntegerLiteral
          { begin: "\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b" },
          { begin: "\\b0[bB][0-1](_?[0-1])*n?\\b" },
          { begin: "\\b0[oO][0-7](_?[0-7])*n?\\b" },
          // LegacyOctalIntegerLiteral (does not include underscore separators)
          // https://tc39.es/ecma262/#sec-additional-syntax-numeric-literals
          { begin: "\\b0[0-7]+n?\\b" }
        ],
        relevance: 0
      };
      const SUBST = {
        className: "subst",
        begin: "\\$\\{",
        end: "\\}",
        keywords: KEYWORDS$1,
        contains: []
        // defined later
      };
      const HTML_TEMPLATE = {
        begin: "html`",
        end: "",
        starts: {
          end: "`",
          returnEnd: false,
          contains: [
            hljs5.BACKSLASH_ESCAPE,
            SUBST
          ],
          subLanguage: "xml"
        }
      };
      const CSS_TEMPLATE = {
        begin: "css`",
        end: "",
        starts: {
          end: "`",
          returnEnd: false,
          contains: [
            hljs5.BACKSLASH_ESCAPE,
            SUBST
          ],
          subLanguage: "css"
        }
      };
      const TEMPLATE_STRING = {
        className: "string",
        begin: "`",
        end: "`",
        contains: [
          hljs5.BACKSLASH_ESCAPE,
          SUBST
        ]
      };
      const JSDOC_COMMENT = hljs5.COMMENT(
        /\/\*\*(?!\/)/,
        "\\*/",
        {
          relevance: 0,
          contains: [
            {
              className: "doctag",
              begin: "@[A-Za-z]+",
              contains: [
                {
                  className: "type",
                  begin: "\\{",
                  end: "\\}",
                  relevance: 0
                },
                {
                  className: "variable",
                  begin: IDENT_RE$1 + "(?=\\s*(-)|$)",
                  endsParent: true,
                  relevance: 0
                },
                // eat spaces (not newlines) so we can find
                // types or variables
                {
                  begin: /(?=[^\n])\s/,
                  relevance: 0
                }
              ]
            }
          ]
        }
      );
      const COMMENT = {
        className: "comment",
        variants: [
          JSDOC_COMMENT,
          hljs5.C_BLOCK_COMMENT_MODE,
          hljs5.C_LINE_COMMENT_MODE
        ]
      };
      const SUBST_INTERNALS = [
        hljs5.APOS_STRING_MODE,
        hljs5.QUOTE_STRING_MODE,
        HTML_TEMPLATE,
        CSS_TEMPLATE,
        TEMPLATE_STRING,
        NUMBER,
        hljs5.REGEXP_MODE
      ];
      SUBST.contains = SUBST_INTERNALS.concat({
        // we need to pair up {} inside our subst to prevent
        // it from ending too early by matching another }
        begin: /\{/,
        end: /\}/,
        keywords: KEYWORDS$1,
        contains: [
          "self"
        ].concat(SUBST_INTERNALS)
      });
      const SUBST_AND_COMMENTS = [].concat(COMMENT, SUBST.contains);
      const PARAMS_CONTAINS = SUBST_AND_COMMENTS.concat([
        // eat recursive parens in sub expressions
        {
          begin: /\(/,
          end: /\)/,
          keywords: KEYWORDS$1,
          contains: ["self"].concat(SUBST_AND_COMMENTS)
        }
      ]);
      const PARAMS = {
        className: "params",
        begin: /\(/,
        end: /\)/,
        excludeBegin: true,
        excludeEnd: true,
        keywords: KEYWORDS$1,
        contains: PARAMS_CONTAINS
      };
      return {
        name: "Javascript",
        aliases: ["js", "jsx", "mjs", "cjs"],
        keywords: KEYWORDS$1,
        // this will be extended by TypeScript
        exports: { PARAMS_CONTAINS },
        illegal: /#(?![$_A-z])/,
        contains: [
          hljs5.SHEBANG({
            label: "shebang",
            binary: "node",
            relevance: 5
          }),
          {
            label: "use_strict",
            className: "meta",
            relevance: 10,
            begin: /^\s*['"]use (strict|asm)['"]/
          },
          hljs5.APOS_STRING_MODE,
          hljs5.QUOTE_STRING_MODE,
          HTML_TEMPLATE,
          CSS_TEMPLATE,
          TEMPLATE_STRING,
          COMMENT,
          NUMBER,
          {
            // object attr container
            begin: concat(
              /[{,\n]\s*/,
              // we need to look ahead to make sure that we actually have an
              // attribute coming up so we don't steal a comma from a potential
              // "value" container
              //
              // NOTE: this might not work how you think.  We don't actually always
              // enter this mode and stay.  Instead it might merely match `,
              // <comments up next>` and then immediately end after the , because it
              // fails to find any actual attrs. But this still does the job because
              // it prevents the value contain rule from grabbing this instead and
              // prevening this rule from firing when we actually DO have keys.
              lookahead(concat(
                // we also need to allow for multiple possible comments inbetween
                // the first key:value pairing
                /(((\/\/.*$)|(\/\*(\*[^/]|[^*])*\*\/))\s*)*/,
                IDENT_RE$1 + "\\s*:"
              ))
            ),
            relevance: 0,
            contains: [
              {
                className: "attr",
                begin: IDENT_RE$1 + lookahead("\\s*:"),
                relevance: 0
              }
            ]
          },
          {
            // "value" container
            begin: "(" + hljs5.RE_STARTERS_RE + "|\\b(case|return|throw)\\b)\\s*",
            keywords: "return throw case",
            contains: [
              COMMENT,
              hljs5.REGEXP_MODE,
              {
                className: "function",
                // we have to count the parens to make sure we actually have the
                // correct bounding ( ) before the =>.  There could be any number of
                // sub-expressions inside also surrounded by parens.
                begin: "(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|" + hljs5.UNDERSCORE_IDENT_RE + ")\\s*=>",
                returnBegin: true,
                end: "\\s*=>",
                contains: [
                  {
                    className: "params",
                    variants: [
                      {
                        begin: hljs5.UNDERSCORE_IDENT_RE,
                        relevance: 0
                      },
                      {
                        className: null,
                        begin: /\(\s*\)/,
                        skip: true
                      },
                      {
                        begin: /\(/,
                        end: /\)/,
                        excludeBegin: true,
                        excludeEnd: true,
                        keywords: KEYWORDS$1,
                        contains: PARAMS_CONTAINS
                      }
                    ]
                  }
                ]
              },
              {
                // could be a comma delimited list of params to a function call
                begin: /,/,
                relevance: 0
              },
              {
                className: "",
                begin: /\s/,
                end: /\s*/,
                skip: true
              },
              {
                // JSX
                variants: [
                  { begin: FRAGMENT.begin, end: FRAGMENT.end },
                  {
                    begin: XML_TAG.begin,
                    // we carefully check the opening tag to see if it truly
                    // is a tag and not a false positive
                    "on:begin": XML_TAG.isTrulyOpeningTag,
                    end: XML_TAG.end
                  }
                ],
                subLanguage: "xml",
                contains: [
                  {
                    begin: XML_TAG.begin,
                    end: XML_TAG.end,
                    skip: true,
                    contains: ["self"]
                  }
                ]
              }
            ],
            relevance: 0
          },
          {
            className: "function",
            beginKeywords: "function",
            end: /[{;]/,
            excludeEnd: true,
            keywords: KEYWORDS$1,
            contains: [
              "self",
              hljs5.inherit(hljs5.TITLE_MODE, { begin: IDENT_RE$1 }),
              PARAMS
            ],
            illegal: /%/
          },
          {
            // prevent this from getting swallowed up by function
            // since they appear "function like"
            beginKeywords: "while if switch catch for"
          },
          {
            className: "function",
            // we have to count the parens to make sure we actually have the correct
            // bounding ( ).  There could be any number of sub-expressions inside
            // also surrounded by parens.
            begin: hljs5.UNDERSCORE_IDENT_RE + "\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",
            // end parens
            returnBegin: true,
            contains: [
              PARAMS,
              hljs5.inherit(hljs5.TITLE_MODE, { begin: IDENT_RE$1 })
            ]
          },
          // hack: prevents detection of keywords in some circumstances
          // .keyword()
          // $keyword = x
          {
            variants: [
              { begin: "\\." + IDENT_RE$1 },
              { begin: "\\$" + IDENT_RE$1 }
            ],
            relevance: 0
          },
          {
            // ES6 class
            className: "class",
            beginKeywords: "class",
            end: /[{;=]/,
            excludeEnd: true,
            illegal: /[:"[\]]/,
            contains: [
              { beginKeywords: "extends" },
              hljs5.UNDERSCORE_TITLE_MODE
            ]
          },
          {
            begin: /\b(?=constructor)/,
            end: /[{;]/,
            excludeEnd: true,
            contains: [
              hljs5.inherit(hljs5.TITLE_MODE, { begin: IDENT_RE$1 }),
              "self",
              PARAMS
            ]
          },
          {
            begin: "(get|set)\\s+(?=" + IDENT_RE$1 + "\\()",
            end: /\{/,
            keywords: "get set",
            contains: [
              hljs5.inherit(hljs5.TITLE_MODE, { begin: IDENT_RE$1 }),
              { begin: /\(\)/ },
              // eat to avoid empty params
              PARAMS
            ]
          },
          {
            begin: /\$[(.]/
            // relevance booster for a pattern common to JS libs: `$(something)` and `$.something`
          }
        ]
      };
    }
    function typescript2(hljs5) {
      const IDENT_RE$1 = IDENT_RE3;
      const NAMESPACE = {
        beginKeywords: "namespace",
        end: /\{/,
        excludeEnd: true
      };
      const INTERFACE = {
        beginKeywords: "interface",
        end: /\{/,
        excludeEnd: true,
        keywords: "interface extends"
      };
      const USE_STRICT = {
        className: "meta",
        relevance: 10,
        begin: /^\s*['"]use strict['"]/
      };
      const TYPES4 = [
        "any",
        "void",
        "number",
        "boolean",
        "string",
        "object",
        "never",
        "enum"
      ];
      const TS_SPECIFIC_KEYWORDS = [
        "type",
        "namespace",
        "typedef",
        "interface",
        "public",
        "private",
        "protected",
        "implements",
        "declare",
        "abstract",
        "readonly"
      ];
      const KEYWORDS$1 = {
        $pattern: IDENT_RE3,
        keyword: KEYWORDS3.concat(TS_SPECIFIC_KEYWORDS),
        literal: LITERALS3,
        built_in: BUILT_INS3.concat(TYPES4)
      };
      const DECORATOR = {
        className: "meta",
        begin: "@" + IDENT_RE$1
      };
      const swapMode = (mode, label, replacement) => {
        const indx = mode.contains.findIndex((m4) => m4.label === label);
        if (indx === -1) {
          throw new Error("can not find mode to replace");
        }
        mode.contains.splice(indx, 1, replacement);
      };
      const tsLanguage = javascript3(hljs5);
      Object.assign(tsLanguage.keywords, KEYWORDS$1);
      tsLanguage.exports.PARAMS_CONTAINS.push(DECORATOR);
      tsLanguage.contains = tsLanguage.contains.concat([
        DECORATOR,
        NAMESPACE,
        INTERFACE
      ]);
      swapMode(tsLanguage, "shebang", hljs5.SHEBANG());
      swapMode(tsLanguage, "use_strict", USE_STRICT);
      const functionDeclaration = tsLanguage.contains.find((m4) => m4.className === "function");
      functionDeclaration.relevance = 0;
      Object.assign(tsLanguage, {
        name: "TypeScript",
        aliases: ["ts", "tsx"]
      });
      return tsLanguage;
    }
    module.exports = typescript2;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/vala.js
var require_vala = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/vala.js"(exports, module) {
    init_process_shim();
    function vala(hljs5) {
      return {
        name: "Vala",
        keywords: {
          keyword: (
            // Value types
            "char uchar unichar int uint long ulong short ushort int8 int16 int32 int64 uint8 uint16 uint32 uint64 float double bool struct enum string void weak unowned owned async signal static abstract interface override virtual delegate if while do for foreach else switch case break default return try catch public private protected internal using new this get set const stdout stdin stderr var"
          ),
          built_in: "DBus GLib CCode Gee Object Gtk Posix",
          literal: "false true null"
        },
        contains: [
          {
            className: "class",
            beginKeywords: "class interface namespace",
            end: /\{/,
            excludeEnd: true,
            illegal: "[^,:\\n\\s\\.]",
            contains: [hljs5.UNDERSCORE_TITLE_MODE]
          },
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          {
            className: "string",
            begin: '"""',
            end: '"""',
            relevance: 5
          },
          hljs5.APOS_STRING_MODE,
          hljs5.QUOTE_STRING_MODE,
          hljs5.C_NUMBER_MODE,
          {
            className: "meta",
            begin: "^#",
            end: "$",
            relevance: 2
          }
        ]
      };
    }
    module.exports = vala;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/vbnet.js
var require_vbnet = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/vbnet.js"(exports, module) {
    init_process_shim();
    function source(re2) {
      if (!re2) return null;
      if (typeof re2 === "string") return re2;
      return re2.source;
    }
    function concat(...args) {
      const joined = args.map((x2) => source(x2)).join("");
      return joined;
    }
    function either(...args) {
      const joined = "(" + args.map((x2) => source(x2)).join("|") + ")";
      return joined;
    }
    function vbnet(hljs5) {
      const CHARACTER = {
        className: "string",
        begin: /"(""|[^/n])"C\b/
      };
      const STRING = {
        className: "string",
        begin: /"/,
        end: /"/,
        illegal: /\n/,
        contains: [
          {
            // double quote escape
            begin: /""/
          }
        ]
      };
      const MM_DD_YYYY = /\d{1,2}\/\d{1,2}\/\d{4}/;
      const YYYY_MM_DD = /\d{4}-\d{1,2}-\d{1,2}/;
      const TIME_12H = /(\d|1[012])(:\d+){0,2} *(AM|PM)/;
      const TIME_24H = /\d{1,2}(:\d{1,2}){1,2}/;
      const DATE = {
        className: "literal",
        variants: [
          {
            // #YYYY-MM-DD# (ISO-Date) or #M/D/YYYY# (US-Date)
            begin: concat(/# */, either(YYYY_MM_DD, MM_DD_YYYY), / *#/)
          },
          {
            // #H:mm[:ss]# (24h Time)
            begin: concat(/# */, TIME_24H, / *#/)
          },
          {
            // #h[:mm[:ss]] A# (12h Time)
            begin: concat(/# */, TIME_12H, / *#/)
          },
          {
            // date plus time
            begin: concat(
              /# */,
              either(YYYY_MM_DD, MM_DD_YYYY),
              / +/,
              either(TIME_12H, TIME_24H),
              / *#/
            )
          }
        ]
      };
      const NUMBER = {
        className: "number",
        relevance: 0,
        variants: [
          {
            // Float
            begin: /\b\d[\d_]*((\.[\d_]+(E[+-]?[\d_]+)?)|(E[+-]?[\d_]+))[RFD@!#]?/
          },
          {
            // Integer (base 10)
            begin: /\b\d[\d_]*((U?[SIL])|[%&])?/
          },
          {
            // Integer (base 16)
            begin: /&H[\dA-F_]+((U?[SIL])|[%&])?/
          },
          {
            // Integer (base 8)
            begin: /&O[0-7_]+((U?[SIL])|[%&])?/
          },
          {
            // Integer (base 2)
            begin: /&B[01_]+((U?[SIL])|[%&])?/
          }
        ]
      };
      const LABEL = {
        className: "label",
        begin: /^\w+:/
      };
      const DOC_COMMENT = hljs5.COMMENT(/'''/, /$/, {
        contains: [
          {
            className: "doctag",
            begin: /<\/?/,
            end: />/
          }
        ]
      });
      const COMMENT = hljs5.COMMENT(null, /$/, {
        variants: [
          {
            begin: /'/
          },
          {
            // TODO: Use `beforeMatch:` for leading spaces
            begin: /([\t ]|^)REM(?=\s)/
          }
        ]
      });
      const DIRECTIVES = {
        className: "meta",
        // TODO: Use `beforeMatch:` for indentation once available
        begin: /[\t ]*#(const|disable|else|elseif|enable|end|externalsource|if|region)\b/,
        end: /$/,
        keywords: {
          "meta-keyword": "const disable else elseif enable end externalsource if region then"
        },
        contains: [COMMENT]
      };
      return {
        name: "Visual Basic .NET",
        aliases: ["vb"],
        case_insensitive: true,
        classNameAliases: {
          label: "symbol"
        },
        keywords: {
          keyword: "addhandler alias aggregate ansi as async assembly auto binary by byref byval call case catch class compare const continue custom declare default delegate dim distinct do each equals else elseif end enum erase error event exit explicit finally for friend from function get global goto group handles if implements imports in inherits interface into iterator join key let lib loop me mid module mustinherit mustoverride mybase myclass namespace narrowing new next notinheritable notoverridable of off on operator option optional order overloads overridable overrides paramarray partial preserve private property protected public raiseevent readonly redim removehandler resume return select set shadows shared skip static step stop structure strict sub synclock take text then throw to try unicode until using when where while widening with withevents writeonly yield",
          built_in: (
            // Operators https://docs.microsoft.com/dotnet/visual-basic/language-reference/operators
            "addressof and andalso await directcast gettype getxmlnamespace is isfalse isnot istrue like mod nameof new not or orelse trycast typeof xor cbool cbyte cchar cdate cdbl cdec cint clng cobj csbyte cshort csng cstr cuint culng cushort"
          ),
          type: (
            // Data types https://docs.microsoft.com/dotnet/visual-basic/language-reference/data-types
            "boolean byte char date decimal double integer long object sbyte short single string uinteger ulong ushort"
          ),
          literal: "true false nothing"
        },
        illegal: "//|\\{|\\}|endif|gosub|variant|wend|^\\$ ",
        contains: [
          CHARACTER,
          STRING,
          DATE,
          NUMBER,
          LABEL,
          DOC_COMMENT,
          COMMENT,
          DIRECTIVES
        ]
      };
    }
    module.exports = vbnet;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/vbscript.js
var require_vbscript = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/vbscript.js"(exports, module) {
    init_process_shim();
    function source(re2) {
      if (!re2) return null;
      if (typeof re2 === "string") return re2;
      return re2.source;
    }
    function concat(...args) {
      const joined = args.map((x2) => source(x2)).join("");
      return joined;
    }
    function either(...args) {
      const joined = "(" + args.map((x2) => source(x2)).join("|") + ")";
      return joined;
    }
    function vbscript(hljs5) {
      const BUILT_IN_FUNCTIONS = "lcase month vartype instrrev ubound setlocale getobject rgb getref string weekdayname rnd dateadd monthname now day minute isarray cbool round formatcurrency conversions csng timevalue second year space abs clng timeserial fixs len asc isempty maths dateserial atn timer isobject filter weekday datevalue ccur isdate instr datediff formatdatetime replace isnull right sgn array snumeric log cdbl hex chr lbound msgbox ucase getlocale cos cdate cbyte rtrim join hour oct typename trim strcomp int createobject loadpicture tan formatnumber mid split  cint sin datepart ltrim sqr time derived eval date formatpercent exp inputbox left ascw chrw regexp cstr err".split(" ");
      const BUILT_IN_OBJECTS = [
        "server",
        "response",
        "request",
        // take no arguments so can be called without ()
        "scriptengine",
        "scriptenginebuildversion",
        "scriptengineminorversion",
        "scriptenginemajorversion"
      ];
      const BUILT_IN_CALL = {
        begin: concat(either(...BUILT_IN_FUNCTIONS), "\\s*\\("),
        // relevance 0 because this is acting as a beginKeywords really
        relevance: 0,
        keywords: {
          built_in: BUILT_IN_FUNCTIONS
        }
      };
      return {
        name: "VBScript",
        aliases: ["vbs"],
        case_insensitive: true,
        keywords: {
          keyword: "call class const dim do loop erase execute executeglobal exit for each next function if then else on error option explicit new private property let get public randomize redim rem select case set stop sub while wend with end to elseif is or xor and not class_initialize class_terminate default preserve in me byval byref step resume goto",
          built_in: BUILT_IN_OBJECTS,
          literal: "true false null nothing empty"
        },
        illegal: "//",
        contains: [
          BUILT_IN_CALL,
          hljs5.inherit(hljs5.QUOTE_STRING_MODE, { contains: [{ begin: '""' }] }),
          hljs5.COMMENT(
            /'/,
            /$/,
            {
              relevance: 0
            }
          ),
          hljs5.C_NUMBER_MODE
        ]
      };
    }
    module.exports = vbscript;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/vbscript-html.js
var require_vbscript_html = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/vbscript-html.js"(exports, module) {
    init_process_shim();
    function vbscriptHtml(hljs5) {
      return {
        name: "VBScript in HTML",
        subLanguage: "xml",
        contains: [
          {
            begin: "<%",
            end: "%>",
            subLanguage: "vbscript"
          }
        ]
      };
    }
    module.exports = vbscriptHtml;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/verilog.js
var require_verilog = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/verilog.js"(exports, module) {
    init_process_shim();
    function verilog(hljs5) {
      const SV_KEYWORDS = {
        $pattern: /[\w\$]+/,
        keyword: "accept_on alias always always_comb always_ff always_latch and assert assign assume automatic before begin bind bins binsof bit break buf|0 bufif0 bufif1 byte case casex casez cell chandle checker class clocking cmos config const constraint context continue cover covergroup coverpoint cross deassign default defparam design disable dist do edge else end endcase endchecker endclass endclocking endconfig endfunction endgenerate endgroup endinterface endmodule endpackage endprimitive endprogram endproperty endspecify endsequence endtable endtask enum event eventually expect export extends extern final first_match for force foreach forever fork forkjoin function generate|5 genvar global highz0 highz1 if iff ifnone ignore_bins illegal_bins implements implies import incdir include initial inout input inside instance int integer interconnect interface intersect join join_any join_none large let liblist library local localparam logic longint macromodule matches medium modport module nand negedge nettype new nexttime nmos nor noshowcancelled not notif0 notif1 or output package packed parameter pmos posedge primitive priority program property protected pull0 pull1 pulldown pullup pulsestyle_ondetect pulsestyle_onevent pure rand randc randcase randsequence rcmos real realtime ref reg reject_on release repeat restrict return rnmos rpmos rtran rtranif0 rtranif1 s_always s_eventually s_nexttime s_until s_until_with scalared sequence shortint shortreal showcancelled signed small soft solve specify specparam static string strong strong0 strong1 struct super supply0 supply1 sync_accept_on sync_reject_on table tagged task this throughout time timeprecision timeunit tran tranif0 tranif1 tri tri0 tri1 triand trior trireg type typedef union unique unique0 unsigned until until_with untyped use uwire var vectored virtual void wait wait_order wand weak weak0 weak1 while wildcard wire with within wor xnor xor",
        literal: "null",
        built_in: "$finish $stop $exit $fatal $error $warning $info $realtime $time $printtimescale $bitstoreal $bitstoshortreal $itor $signed $cast $bits $stime $timeformat $realtobits $shortrealtobits $rtoi $unsigned $asserton $assertkill $assertpasson $assertfailon $assertnonvacuouson $assertoff $assertcontrol $assertpassoff $assertfailoff $assertvacuousoff $isunbounded $sampled $fell $changed $past_gclk $fell_gclk $changed_gclk $rising_gclk $steady_gclk $coverage_control $coverage_get $coverage_save $set_coverage_db_name $rose $stable $past $rose_gclk $stable_gclk $future_gclk $falling_gclk $changing_gclk $display $coverage_get_max $coverage_merge $get_coverage $load_coverage_db $typename $unpacked_dimensions $left $low $increment $clog2 $ln $log10 $exp $sqrt $pow $floor $ceil $sin $cos $tan $countbits $onehot $isunknown $fatal $warning $dimensions $right $high $size $asin $acos $atan $atan2 $hypot $sinh $cosh $tanh $asinh $acosh $atanh $countones $onehot0 $error $info $random $dist_chi_square $dist_erlang $dist_exponential $dist_normal $dist_poisson $dist_t $dist_uniform $q_initialize $q_remove $q_exam $async$and$array $async$nand$array $async$or$array $async$nor$array $sync$and$array $sync$nand$array $sync$or$array $sync$nor$array $q_add $q_full $psprintf $async$and$plane $async$nand$plane $async$or$plane $async$nor$plane $sync$and$plane $sync$nand$plane $sync$or$plane $sync$nor$plane $system $display $displayb $displayh $displayo $strobe $strobeb $strobeh $strobeo $write $readmemb $readmemh $writememh $value$plusargs $dumpvars $dumpon $dumplimit $dumpports $dumpportson $dumpportslimit $writeb $writeh $writeo $monitor $monitorb $monitorh $monitoro $writememb $dumpfile $dumpoff $dumpall $dumpflush $dumpportsoff $dumpportsall $dumpportsflush $fclose $fdisplay $fdisplayb $fdisplayh $fdisplayo $fstrobe $fstrobeb $fstrobeh $fstrobeo $swrite $swriteb $swriteh $swriteo $fscanf $fread $fseek $fflush $feof $fopen $fwrite $fwriteb $fwriteh $fwriteo $fmonitor $fmonitorb $fmonitorh $fmonitoro $sformat $sformatf $fgetc $ungetc $fgets $sscanf $rewind $ftell $ferror"
      };
      return {
        name: "Verilog",
        aliases: [
          "v",
          "sv",
          "svh"
        ],
        case_insensitive: false,
        keywords: SV_KEYWORDS,
        contains: [
          hljs5.C_BLOCK_COMMENT_MODE,
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.QUOTE_STRING_MODE,
          {
            className: "number",
            contains: [hljs5.BACKSLASH_ESCAPE],
            variants: [
              {
                begin: "\\b((\\d+'(b|h|o|d|B|H|O|D))[0-9xzXZa-fA-F_]+)"
              },
              {
                begin: "\\B(('(b|h|o|d|B|H|O|D))[0-9xzXZa-fA-F_]+)"
              },
              {
                begin: "\\b([0-9_])+",
                relevance: 0
              }
            ]
          },
          /* parameters to instances */
          {
            className: "variable",
            variants: [
              {
                begin: "#\\((?!parameter).+\\)"
              },
              {
                begin: "\\.\\w+",
                relevance: 0
              }
            ]
          },
          {
            className: "meta",
            begin: "`",
            end: "$",
            keywords: {
              "meta-keyword": "define __FILE__ __LINE__ begin_keywords celldefine default_nettype define else elsif end_keywords endcelldefine endif ifdef ifndef include line nounconnected_drive pragma resetall timescale unconnected_drive undef undefineall"
            },
            relevance: 0
          }
        ]
      };
    }
    module.exports = verilog;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/vhdl.js
var require_vhdl = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/vhdl.js"(exports, module) {
    init_process_shim();
    function vhdl(hljs5) {
      const INTEGER_RE = "\\d(_|\\d)*";
      const EXPONENT_RE = "[eE][-+]?" + INTEGER_RE;
      const DECIMAL_LITERAL_RE = INTEGER_RE + "(\\." + INTEGER_RE + ")?(" + EXPONENT_RE + ")?";
      const BASED_INTEGER_RE = "\\w+";
      const BASED_LITERAL_RE = INTEGER_RE + "#" + BASED_INTEGER_RE + "(\\." + BASED_INTEGER_RE + ")?#(" + EXPONENT_RE + ")?";
      const NUMBER_RE = "\\b(" + BASED_LITERAL_RE + "|" + DECIMAL_LITERAL_RE + ")";
      return {
        name: "VHDL",
        case_insensitive: true,
        keywords: {
          keyword: "abs access after alias all and architecture array assert assume assume_guarantee attribute begin block body buffer bus case component configuration constant context cover disconnect downto default else elsif end entity exit fairness file for force function generate generic group guarded if impure in inertial inout is label library linkage literal loop map mod nand new next nor not null of on open or others out package parameter port postponed procedure process property protected pure range record register reject release rem report restrict restrict_guarantee return rol ror select sequence severity shared signal sla sll sra srl strong subtype then to transport type unaffected units until use variable view vmode vprop vunit wait when while with xnor xor",
          built_in: "boolean bit character integer time delay_length natural positive string bit_vector file_open_kind file_open_status std_logic std_logic_vector unsigned signed boolean_vector integer_vector std_ulogic std_ulogic_vector unresolved_unsigned u_unsigned unresolved_signed u_signed real_vector time_vector",
          literal: "false true note warning error failure line text side width"
          // textio
        },
        illegal: /\{/,
        contains: [
          hljs5.C_BLOCK_COMMENT_MODE,
          // VHDL-2008 block commenting.
          hljs5.COMMENT("--", "$"),
          hljs5.QUOTE_STRING_MODE,
          {
            className: "number",
            begin: NUMBER_RE,
            relevance: 0
          },
          {
            className: "string",
            begin: "'(U|X|0|1|Z|W|L|H|-)'",
            contains: [hljs5.BACKSLASH_ESCAPE]
          },
          {
            className: "symbol",
            begin: "'[A-Za-z](_?[A-Za-z0-9])*",
            contains: [hljs5.BACKSLASH_ESCAPE]
          }
        ]
      };
    }
    module.exports = vhdl;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/vim.js
var require_vim = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/vim.js"(exports, module) {
    init_process_shim();
    function vim(hljs5) {
      return {
        name: "Vim Script",
        keywords: {
          $pattern: /[!#@\w]+/,
          keyword: (
            // express version except: ! & * < = > !! # @ @@
            "N|0 P|0 X|0 a|0 ab abc abo al am an|0 ar arga argd arge argdo argg argl argu as au aug aun b|0 bN ba bad bd be bel bf bl bm bn bo bp br brea breaka breakd breakl bro bufdo buffers bun bw c|0 cN cNf ca cabc caddb cad caddf cal cat cb cc ccl cd ce cex cf cfir cgetb cgete cg changes chd che checkt cl cla clo cm cmapc cme cn cnew cnf cno cnorea cnoreme co col colo com comc comp con conf cope cp cpf cq cr cs cst cu cuna cunme cw delm deb debugg delc delf dif diffg diffo diffp diffpu diffs diffthis dig di dl dell dj dli do doautoa dp dr ds dsp e|0 ea ec echoe echoh echom echon el elsei em en endfo endf endt endw ene ex exe exi exu f|0 files filet fin fina fini fir fix fo foldc foldd folddoc foldo for fu go gr grepa gu gv ha helpf helpg helpt hi hid his ia iabc if ij il im imapc ime ino inorea inoreme int is isp iu iuna iunme j|0 ju k|0 keepa kee keepj lN lNf l|0 lad laddb laddf la lan lat lb lc lch lcl lcs le lefta let lex lf lfir lgetb lgete lg lgr lgrepa lh ll lla lli lmak lm lmapc lne lnew lnf ln loadk lo loc lockv lol lope lp lpf lr ls lt lu lua luad luaf lv lvimgrepa lw m|0 ma mak map mapc marks mat me menut mes mk mks mksp mkv mkvie mod mz mzf nbc nb nbs new nm nmapc nme nn nnoreme noa no noh norea noreme norm nu nun nunme ol o|0 om omapc ome on ono onoreme opt ou ounme ow p|0 profd prof pro promptr pc ped pe perld po popu pp pre prev ps pt ptN ptf ptj ptl ptn ptp ptr pts pu pw py3 python3 py3d py3f py pyd pyf quita qa rec red redi redr redraws reg res ret retu rew ri rightb rub rubyd rubyf rund ru rv sN san sa sal sav sb sbN sba sbf sbl sbm sbn sbp sbr scrip scripte scs se setf setg setl sf sfir sh sim sig sil sl sla sm smap smapc sme sn sni sno snor snoreme sor so spelld spe spelli spellr spellu spellw sp spr sre st sta startg startr star stopi stj sts sun sunm sunme sus sv sw sy synti sync tN tabN tabc tabdo tabe tabf tabfir tabl tabm tabnew tabn tabo tabp tabr tabs tab ta tags tc tcld tclf te tf th tj tl tm tn to tp tr try ts tu u|0 undoj undol una unh unl unlo unm unme uns up ve verb vert vim vimgrepa vi viu vie vm vmapc vme vne vn vnoreme vs vu vunme windo w|0 wN wa wh wi winc winp wn wp wq wqa ws wu wv x|0 xa xmapc xm xme xn xnoreme xu xunme y|0 z|0 ~ Next Print append abbreviate abclear aboveleft all amenu anoremenu args argadd argdelete argedit argglobal arglocal argument ascii autocmd augroup aunmenu buffer bNext ball badd bdelete behave belowright bfirst blast bmodified bnext botright bprevious brewind break breakadd breakdel breaklist browse bunload bwipeout change cNext cNfile cabbrev cabclear caddbuffer caddexpr caddfile call catch cbuffer cclose center cexpr cfile cfirst cgetbuffer cgetexpr cgetfile chdir checkpath checktime clist clast close cmap cmapclear cmenu cnext cnewer cnfile cnoremap cnoreabbrev cnoremenu copy colder colorscheme command comclear compiler continue confirm copen cprevious cpfile cquit crewind cscope cstag cunmap cunabbrev cunmenu cwindow delete delmarks debug debuggreedy delcommand delfunction diffupdate diffget diffoff diffpatch diffput diffsplit digraphs display deletel djump dlist doautocmd doautoall deletep drop dsearch dsplit edit earlier echo echoerr echohl echomsg else elseif emenu endif endfor endfunction endtry endwhile enew execute exit exusage file filetype find finally finish first fixdel fold foldclose folddoopen folddoclosed foldopen function global goto grep grepadd gui gvim hardcopy help helpfind helpgrep helptags highlight hide history insert iabbrev iabclear ijump ilist imap imapclear imenu inoremap inoreabbrev inoremenu intro isearch isplit iunmap iunabbrev iunmenu join jumps keepalt keepmarks keepjumps lNext lNfile list laddexpr laddbuffer laddfile last language later lbuffer lcd lchdir lclose lcscope left leftabove lexpr lfile lfirst lgetbuffer lgetexpr lgetfile lgrep lgrepadd lhelpgrep llast llist lmake lmap lmapclear lnext lnewer lnfile lnoremap loadkeymap loadview lockmarks lockvar lolder lopen lprevious lpfile lrewind ltag lunmap luado luafile lvimgrep lvimgrepadd lwindow move mark make mapclear match menu menutranslate messages mkexrc mksession mkspell mkvimrc mkview mode mzscheme mzfile nbclose nbkey nbsart next nmap nmapclear nmenu nnoremap nnoremenu noautocmd noremap nohlsearch noreabbrev noremenu normal number nunmap nunmenu oldfiles open omap omapclear omenu only onoremap onoremenu options ounmap ounmenu ownsyntax print profdel profile promptfind promptrepl pclose pedit perl perldo pop popup ppop preserve previous psearch ptag ptNext ptfirst ptjump ptlast ptnext ptprevious ptrewind ptselect put pwd py3do py3file python pydo pyfile quit quitall qall read recover redo redir redraw redrawstatus registers resize retab return rewind right rightbelow ruby rubydo rubyfile rundo runtime rviminfo substitute sNext sandbox sargument sall saveas sbuffer sbNext sball sbfirst sblast sbmodified sbnext sbprevious sbrewind scriptnames scriptencoding scscope set setfiletype setglobal setlocal sfind sfirst shell simalt sign silent sleep slast smagic smapclear smenu snext sniff snomagic snoremap snoremenu sort source spelldump spellgood spellinfo spellrepall spellundo spellwrong split sprevious srewind stop stag startgreplace startreplace startinsert stopinsert stjump stselect sunhide sunmap sunmenu suspend sview swapname syntax syntime syncbind tNext tabNext tabclose tabedit tabfind tabfirst tablast tabmove tabnext tabonly tabprevious tabrewind tag tcl tcldo tclfile tearoff tfirst throw tjump tlast tmenu tnext topleft tprevious trewind tselect tunmenu undo undojoin undolist unabbreviate unhide unlet unlockvar unmap unmenu unsilent update vglobal version verbose vertical vimgrep vimgrepadd visual viusage view vmap vmapclear vmenu vnew vnoremap vnoremenu vsplit vunmap vunmenu write wNext wall while winsize wincmd winpos wnext wprevious wqall wsverb wundo wviminfo xit xall xmapclear xmap xmenu xnoremap xnoremenu xunmap xunmenu yank"
          ),
          built_in: (
            // built in func
            "synIDtrans atan2 range matcharg did_filetype asin feedkeys xor argv complete_check add getwinposx getqflist getwinposy screencol clearmatches empty extend getcmdpos mzeval garbagecollect setreg ceil sqrt diff_hlID inputsecret get getfperm getpid filewritable shiftwidth max sinh isdirectory synID system inputrestore winline atan visualmode inputlist tabpagewinnr round getregtype mapcheck hasmapto histdel argidx findfile sha256 exists toupper getcmdline taglist string getmatches bufnr strftime winwidth bufexists strtrans tabpagebuflist setcmdpos remote_read printf setloclist getpos getline bufwinnr float2nr len getcmdtype diff_filler luaeval resolve libcallnr foldclosedend reverse filter has_key bufname str2float strlen setline getcharmod setbufvar index searchpos shellescape undofile foldclosed setqflist buflisted strchars str2nr virtcol floor remove undotree remote_expr winheight gettabwinvar reltime cursor tabpagenr finddir localtime acos getloclist search tanh matchend rename gettabvar strdisplaywidth type abs py3eval setwinvar tolower wildmenumode log10 spellsuggest bufloaded synconcealed nextnonblank server2client complete settabwinvar executable input wincol setmatches getftype hlID inputsave searchpair or screenrow line settabvar histadd deepcopy strpart remote_peek and eval getftime submatch screenchar winsaveview matchadd mkdir screenattr getfontname libcall reltimestr getfsize winnr invert pow getbufline byte2line soundfold repeat fnameescape tagfiles sin strwidth spellbadword trunc maparg log lispindent hostname setpos globpath remote_foreground getchar synIDattr fnamemodify cscope_connection stridx winbufnr indent min complete_add nr2char searchpairpos inputdialog values matchlist items hlexists strridx browsedir expand fmod pathshorten line2byte argc count getwinvar glob foldtextresult getreg foreground cosh matchdelete has char2nr simplify histget searchdecl iconv winrestcmd pumvisible writefile foldlevel haslocaldir keys cos matchstr foldtext histnr tan tempname getcwd byteidx getbufvar islocked escape eventhandler remote_send serverlist winrestview synstack pyeval prevnonblank readfile cindent filereadable changenr exp"
          )
        },
        illegal: /;/,
        contains: [
          hljs5.NUMBER_MODE,
          {
            className: "string",
            begin: "'",
            end: "'",
            illegal: "\\n"
          },
          /*
                A double quote can start either a string or a line comment. Strings are
                ended before the end of a line by another double quote and can contain
                escaped double-quotes and post-escaped line breaks.
          
                Also, any double quote at the beginning of a line is a comment but we
                don't handle that properly at the moment: any double quote inside will
                turn them into a string. Handling it properly will require a smarter
                parser.
                */
          {
            className: "string",
            begin: /"(\\"|\n\\|[^"\n])*"/
          },
          hljs5.COMMENT('"', "$"),
          {
            className: "variable",
            begin: /[bwtglsav]:[\w\d_]*/
          },
          {
            className: "function",
            beginKeywords: "function function!",
            end: "$",
            relevance: 0,
            contains: [
              hljs5.TITLE_MODE,
              {
                className: "params",
                begin: "\\(",
                end: "\\)"
              }
            ]
          },
          {
            className: "symbol",
            begin: /<[\w-]+>/
          }
        ]
      };
    }
    module.exports = vim;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/x86asm.js
var require_x86asm = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/x86asm.js"(exports, module) {
    init_process_shim();
    function x86asm(hljs5) {
      return {
        name: "Intel x86 Assembly",
        case_insensitive: true,
        keywords: {
          $pattern: "[.%]?" + hljs5.IDENT_RE,
          keyword: "lock rep repe repz repne repnz xaquire xrelease bnd nobnd aaa aad aam aas adc add and arpl bb0_reset bb1_reset bound bsf bsr bswap bt btc btr bts call cbw cdq cdqe clc cld cli clts cmc cmp cmpsb cmpsd cmpsq cmpsw cmpxchg cmpxchg486 cmpxchg8b cmpxchg16b cpuid cpu_read cpu_write cqo cwd cwde daa das dec div dmint emms enter equ f2xm1 fabs fadd faddp fbld fbstp fchs fclex fcmovb fcmovbe fcmove fcmovnb fcmovnbe fcmovne fcmovnu fcmovu fcom fcomi fcomip fcomp fcompp fcos fdecstp fdisi fdiv fdivp fdivr fdivrp femms feni ffree ffreep fiadd ficom ficomp fidiv fidivr fild fimul fincstp finit fist fistp fisttp fisub fisubr fld fld1 fldcw fldenv fldl2e fldl2t fldlg2 fldln2 fldpi fldz fmul fmulp fnclex fndisi fneni fninit fnop fnsave fnstcw fnstenv fnstsw fpatan fprem fprem1 fptan frndint frstor fsave fscale fsetpm fsin fsincos fsqrt fst fstcw fstenv fstp fstsw fsub fsubp fsubr fsubrp ftst fucom fucomi fucomip fucomp fucompp fxam fxch fxtract fyl2x fyl2xp1 hlt ibts icebp idiv imul in inc incbin insb insd insw int int01 int1 int03 int3 into invd invpcid invlpg invlpga iret iretd iretq iretw jcxz jecxz jrcxz jmp jmpe lahf lar lds lea leave les lfence lfs lgdt lgs lidt lldt lmsw loadall loadall286 lodsb lodsd lodsq lodsw loop loope loopne loopnz loopz lsl lss ltr mfence monitor mov movd movq movsb movsd movsq movsw movsx movsxd movzx mul mwait neg nop not or out outsb outsd outsw packssdw packsswb packuswb paddb paddd paddsb paddsiw paddsw paddusb paddusw paddw pand pandn pause paveb pavgusb pcmpeqb pcmpeqd pcmpeqw pcmpgtb pcmpgtd pcmpgtw pdistib pf2id pfacc pfadd pfcmpeq pfcmpge pfcmpgt pfmax pfmin pfmul pfrcp pfrcpit1 pfrcpit2 pfrsqit1 pfrsqrt pfsub pfsubr pi2fd pmachriw pmaddwd pmagw pmulhriw pmulhrwa pmulhrwc pmulhw pmullw pmvgezb pmvlzb pmvnzb pmvzb pop popa popad popaw popf popfd popfq popfw por prefetch prefetchw pslld psllq psllw psrad psraw psrld psrlq psrlw psubb psubd psubsb psubsiw psubsw psubusb psubusw psubw punpckhbw punpckhdq punpckhwd punpcklbw punpckldq punpcklwd push pusha pushad pushaw pushf pushfd pushfq pushfw pxor rcl rcr rdshr rdmsr rdpmc rdtsc rdtscp ret retf retn rol ror rdm rsdc rsldt rsm rsts sahf sal salc sar sbb scasb scasd scasq scasw sfence sgdt shl shld shr shrd sidt sldt skinit smi smint smintold smsw stc std sti stosb stosd stosq stosw str sub svdc svldt svts swapgs syscall sysenter sysexit sysret test ud0 ud1 ud2b ud2 ud2a umov verr verw fwait wbinvd wrshr wrmsr xadd xbts xchg xlatb xlat xor cmove cmovz cmovne cmovnz cmova cmovnbe cmovae cmovnb cmovb cmovnae cmovbe cmovna cmovg cmovnle cmovge cmovnl cmovl cmovnge cmovle cmovng cmovc cmovnc cmovo cmovno cmovs cmovns cmovp cmovpe cmovnp cmovpo je jz jne jnz ja jnbe jae jnb jb jnae jbe jna jg jnle jge jnl jl jnge jle jng jc jnc jo jno js jns jpo jnp jpe jp sete setz setne setnz seta setnbe setae setnb setnc setb setnae setcset setbe setna setg setnle setge setnl setl setnge setle setng sets setns seto setno setpe setp setpo setnp addps addss andnps andps cmpeqps cmpeqss cmpleps cmpless cmpltps cmpltss cmpneqps cmpneqss cmpnleps cmpnless cmpnltps cmpnltss cmpordps cmpordss cmpunordps cmpunordss cmpps cmpss comiss cvtpi2ps cvtps2pi cvtsi2ss cvtss2si cvttps2pi cvttss2si divps divss ldmxcsr maxps maxss minps minss movaps movhps movlhps movlps movhlps movmskps movntps movss movups mulps mulss orps rcpps rcpss rsqrtps rsqrtss shufps sqrtps sqrtss stmxcsr subps subss ucomiss unpckhps unpcklps xorps fxrstor fxrstor64 fxsave fxsave64 xgetbv xsetbv xsave xsave64 xsaveopt xsaveopt64 xrstor xrstor64 prefetchnta prefetcht0 prefetcht1 prefetcht2 maskmovq movntq pavgb pavgw pextrw pinsrw pmaxsw pmaxub pminsw pminub pmovmskb pmulhuw psadbw pshufw pf2iw pfnacc pfpnacc pi2fw pswapd maskmovdqu clflush movntdq movnti movntpd movdqa movdqu movdq2q movq2dq paddq pmuludq pshufd pshufhw pshuflw pslldq psrldq psubq punpckhqdq punpcklqdq addpd addsd andnpd andpd cmpeqpd cmpeqsd cmplepd cmplesd cmpltpd cmpltsd cmpneqpd cmpneqsd cmpnlepd cmpnlesd cmpnltpd cmpnltsd cmpordpd cmpordsd cmpunordpd cmpunordsd cmppd comisd cvtdq2pd cvtdq2ps cvtpd2dq cvtpd2pi cvtpd2ps cvtpi2pd cvtps2dq cvtps2pd cvtsd2si cvtsd2ss cvtsi2sd cvtss2sd cvttpd2pi cvttpd2dq cvttps2dq cvttsd2si divpd divsd maxpd maxsd minpd minsd movapd movhpd movlpd movmskpd movupd mulpd mulsd orpd shufpd sqrtpd sqrtsd subpd subsd ucomisd unpckhpd unpcklpd xorpd addsubpd addsubps haddpd haddps hsubpd hsubps lddqu movddup movshdup movsldup clgi stgi vmcall vmclear vmfunc vmlaunch vmload vmmcall vmptrld vmptrst vmread vmresume vmrun vmsave vmwrite vmxoff vmxon invept invvpid pabsb pabsw pabsd palignr phaddw phaddd phaddsw phsubw phsubd phsubsw pmaddubsw pmulhrsw pshufb psignb psignw psignd extrq insertq movntsd movntss lzcnt blendpd blendps blendvpd blendvps dppd dpps extractps insertps movntdqa mpsadbw packusdw pblendvb pblendw pcmpeqq pextrb pextrd pextrq phminposuw pinsrb pinsrd pinsrq pmaxsb pmaxsd pmaxud pmaxuw pminsb pminsd pminud pminuw pmovsxbw pmovsxbd pmovsxbq pmovsxwd pmovsxwq pmovsxdq pmovzxbw pmovzxbd pmovzxbq pmovzxwd pmovzxwq pmovzxdq pmuldq pmulld ptest roundpd roundps roundsd roundss crc32 pcmpestri pcmpestrm pcmpistri pcmpistrm pcmpgtq popcnt getsec pfrcpv pfrsqrtv movbe aesenc aesenclast aesdec aesdeclast aesimc aeskeygenassist vaesenc vaesenclast vaesdec vaesdeclast vaesimc vaeskeygenassist vaddpd vaddps vaddsd vaddss vaddsubpd vaddsubps vandpd vandps vandnpd vandnps vblendpd vblendps vblendvpd vblendvps vbroadcastss vbroadcastsd vbroadcastf128 vcmpeq_ospd vcmpeqpd vcmplt_ospd vcmpltpd vcmple_ospd vcmplepd vcmpunord_qpd vcmpunordpd vcmpneq_uqpd vcmpneqpd vcmpnlt_uspd vcmpnltpd vcmpnle_uspd vcmpnlepd vcmpord_qpd vcmpordpd vcmpeq_uqpd vcmpnge_uspd vcmpngepd vcmpngt_uspd vcmpngtpd vcmpfalse_oqpd vcmpfalsepd vcmpneq_oqpd vcmpge_ospd vcmpgepd vcmpgt_ospd vcmpgtpd vcmptrue_uqpd vcmptruepd vcmplt_oqpd vcmple_oqpd vcmpunord_spd vcmpneq_uspd vcmpnlt_uqpd vcmpnle_uqpd vcmpord_spd vcmpeq_uspd vcmpnge_uqpd vcmpngt_uqpd vcmpfalse_ospd vcmpneq_ospd vcmpge_oqpd vcmpgt_oqpd vcmptrue_uspd vcmppd vcmpeq_osps vcmpeqps vcmplt_osps vcmpltps vcmple_osps vcmpleps vcmpunord_qps vcmpunordps vcmpneq_uqps vcmpneqps vcmpnlt_usps vcmpnltps vcmpnle_usps vcmpnleps vcmpord_qps vcmpordps vcmpeq_uqps vcmpnge_usps vcmpngeps vcmpngt_usps vcmpngtps vcmpfalse_oqps vcmpfalseps vcmpneq_oqps vcmpge_osps vcmpgeps vcmpgt_osps vcmpgtps vcmptrue_uqps vcmptrueps vcmplt_oqps vcmple_oqps vcmpunord_sps vcmpneq_usps vcmpnlt_uqps vcmpnle_uqps vcmpord_sps vcmpeq_usps vcmpnge_uqps vcmpngt_uqps vcmpfalse_osps vcmpneq_osps vcmpge_oqps vcmpgt_oqps vcmptrue_usps vcmpps vcmpeq_ossd vcmpeqsd vcmplt_ossd vcmpltsd vcmple_ossd vcmplesd vcmpunord_qsd vcmpunordsd vcmpneq_uqsd vcmpneqsd vcmpnlt_ussd vcmpnltsd vcmpnle_ussd vcmpnlesd vcmpord_qsd vcmpordsd vcmpeq_uqsd vcmpnge_ussd vcmpngesd vcmpngt_ussd vcmpngtsd vcmpfalse_oqsd vcmpfalsesd vcmpneq_oqsd vcmpge_ossd vcmpgesd vcmpgt_ossd vcmpgtsd vcmptrue_uqsd vcmptruesd vcmplt_oqsd vcmple_oqsd vcmpunord_ssd vcmpneq_ussd vcmpnlt_uqsd vcmpnle_uqsd vcmpord_ssd vcmpeq_ussd vcmpnge_uqsd vcmpngt_uqsd vcmpfalse_ossd vcmpneq_ossd vcmpge_oqsd vcmpgt_oqsd vcmptrue_ussd vcmpsd vcmpeq_osss vcmpeqss vcmplt_osss vcmpltss vcmple_osss vcmpless vcmpunord_qss vcmpunordss vcmpneq_uqss vcmpneqss vcmpnlt_usss vcmpnltss vcmpnle_usss vcmpnless vcmpord_qss vcmpordss vcmpeq_uqss vcmpnge_usss vcmpngess vcmpngt_usss vcmpngtss vcmpfalse_oqss vcmpfalsess vcmpneq_oqss vcmpge_osss vcmpgess vcmpgt_osss vcmpgtss vcmptrue_uqss vcmptruess vcmplt_oqss vcmple_oqss vcmpunord_sss vcmpneq_usss vcmpnlt_uqss vcmpnle_uqss vcmpord_sss vcmpeq_usss vcmpnge_uqss vcmpngt_uqss vcmpfalse_osss vcmpneq_osss vcmpge_oqss vcmpgt_oqss vcmptrue_usss vcmpss vcomisd vcomiss vcvtdq2pd vcvtdq2ps vcvtpd2dq vcvtpd2ps vcvtps2dq vcvtps2pd vcvtsd2si vcvtsd2ss vcvtsi2sd vcvtsi2ss vcvtss2sd vcvtss2si vcvttpd2dq vcvttps2dq vcvttsd2si vcvttss2si vdivpd vdivps vdivsd vdivss vdppd vdpps vextractf128 vextractps vhaddpd vhaddps vhsubpd vhsubps vinsertf128 vinsertps vlddqu vldqqu vldmxcsr vmaskmovdqu vmaskmovps vmaskmovpd vmaxpd vmaxps vmaxsd vmaxss vminpd vminps vminsd vminss vmovapd vmovaps vmovd vmovq vmovddup vmovdqa vmovqqa vmovdqu vmovqqu vmovhlps vmovhpd vmovhps vmovlhps vmovlpd vmovlps vmovmskpd vmovmskps vmovntdq vmovntqq vmovntdqa vmovntpd vmovntps vmovsd vmovshdup vmovsldup vmovss vmovupd vmovups vmpsadbw vmulpd vmulps vmulsd vmulss vorpd vorps vpabsb vpabsw vpabsd vpacksswb vpackssdw vpackuswb vpackusdw vpaddb vpaddw vpaddd vpaddq vpaddsb vpaddsw vpaddusb vpaddusw vpalignr vpand vpandn vpavgb vpavgw vpblendvb vpblendw vpcmpestri vpcmpestrm vpcmpistri vpcmpistrm vpcmpeqb vpcmpeqw vpcmpeqd vpcmpeqq vpcmpgtb vpcmpgtw vpcmpgtd vpcmpgtq vpermilpd vpermilps vperm2f128 vpextrb vpextrw vpextrd vpextrq vphaddw vphaddd vphaddsw vphminposuw vphsubw vphsubd vphsubsw vpinsrb vpinsrw vpinsrd vpinsrq vpmaddwd vpmaddubsw vpmaxsb vpmaxsw vpmaxsd vpmaxub vpmaxuw vpmaxud vpminsb vpminsw vpminsd vpminub vpminuw vpminud vpmovmskb vpmovsxbw vpmovsxbd vpmovsxbq vpmovsxwd vpmovsxwq vpmovsxdq vpmovzxbw vpmovzxbd vpmovzxbq vpmovzxwd vpmovzxwq vpmovzxdq vpmulhuw vpmulhrsw vpmulhw vpmullw vpmulld vpmuludq vpmuldq vpor vpsadbw vpshufb vpshufd vpshufhw vpshuflw vpsignb vpsignw vpsignd vpslldq vpsrldq vpsllw vpslld vpsllq vpsraw vpsrad vpsrlw vpsrld vpsrlq vptest vpsubb vpsubw vpsubd vpsubq vpsubsb vpsubsw vpsubusb vpsubusw vpunpckhbw vpunpckhwd vpunpckhdq vpunpckhqdq vpunpcklbw vpunpcklwd vpunpckldq vpunpcklqdq vpxor vrcpps vrcpss vrsqrtps vrsqrtss vroundpd vroundps vroundsd vroundss vshufpd vshufps vsqrtpd vsqrtps vsqrtsd vsqrtss vstmxcsr vsubpd vsubps vsubsd vsubss vtestps vtestpd vucomisd vucomiss vunpckhpd vunpckhps vunpcklpd vunpcklps vxorpd vxorps vzeroall vzeroupper pclmullqlqdq pclmulhqlqdq pclmullqhqdq pclmulhqhqdq pclmulqdq vpclmullqlqdq vpclmulhqlqdq vpclmullqhqdq vpclmulhqhqdq vpclmulqdq vfmadd132ps vfmadd132pd vfmadd312ps vfmadd312pd vfmadd213ps vfmadd213pd vfmadd123ps vfmadd123pd vfmadd231ps vfmadd231pd vfmadd321ps vfmadd321pd vfmaddsub132ps vfmaddsub132pd vfmaddsub312ps vfmaddsub312pd vfmaddsub213ps vfmaddsub213pd vfmaddsub123ps vfmaddsub123pd vfmaddsub231ps vfmaddsub231pd vfmaddsub321ps vfmaddsub321pd vfmsub132ps vfmsub132pd vfmsub312ps vfmsub312pd vfmsub213ps vfmsub213pd vfmsub123ps vfmsub123pd vfmsub231ps vfmsub231pd vfmsub321ps vfmsub321pd vfmsubadd132ps vfmsubadd132pd vfmsubadd312ps vfmsubadd312pd vfmsubadd213ps vfmsubadd213pd vfmsubadd123ps vfmsubadd123pd vfmsubadd231ps vfmsubadd231pd vfmsubadd321ps vfmsubadd321pd vfnmadd132ps vfnmadd132pd vfnmadd312ps vfnmadd312pd vfnmadd213ps vfnmadd213pd vfnmadd123ps vfnmadd123pd vfnmadd231ps vfnmadd231pd vfnmadd321ps vfnmadd321pd vfnmsub132ps vfnmsub132pd vfnmsub312ps vfnmsub312pd vfnmsub213ps vfnmsub213pd vfnmsub123ps vfnmsub123pd vfnmsub231ps vfnmsub231pd vfnmsub321ps vfnmsub321pd vfmadd132ss vfmadd132sd vfmadd312ss vfmadd312sd vfmadd213ss vfmadd213sd vfmadd123ss vfmadd123sd vfmadd231ss vfmadd231sd vfmadd321ss vfmadd321sd vfmsub132ss vfmsub132sd vfmsub312ss vfmsub312sd vfmsub213ss vfmsub213sd vfmsub123ss vfmsub123sd vfmsub231ss vfmsub231sd vfmsub321ss vfmsub321sd vfnmadd132ss vfnmadd132sd vfnmadd312ss vfnmadd312sd vfnmadd213ss vfnmadd213sd vfnmadd123ss vfnmadd123sd vfnmadd231ss vfnmadd231sd vfnmadd321ss vfnmadd321sd vfnmsub132ss vfnmsub132sd vfnmsub312ss vfnmsub312sd vfnmsub213ss vfnmsub213sd vfnmsub123ss vfnmsub123sd vfnmsub231ss vfnmsub231sd vfnmsub321ss vfnmsub321sd rdfsbase rdgsbase rdrand wrfsbase wrgsbase vcvtph2ps vcvtps2ph adcx adox rdseed clac stac xstore xcryptecb xcryptcbc xcryptctr xcryptcfb xcryptofb montmul xsha1 xsha256 llwpcb slwpcb lwpval lwpins vfmaddpd vfmaddps vfmaddsd vfmaddss vfmaddsubpd vfmaddsubps vfmsubaddpd vfmsubaddps vfmsubpd vfmsubps vfmsubsd vfmsubss vfnmaddpd vfnmaddps vfnmaddsd vfnmaddss vfnmsubpd vfnmsubps vfnmsubsd vfnmsubss vfrczpd vfrczps vfrczsd vfrczss vpcmov vpcomb vpcomd vpcomq vpcomub vpcomud vpcomuq vpcomuw vpcomw vphaddbd vphaddbq vphaddbw vphadddq vphaddubd vphaddubq vphaddubw vphaddudq vphadduwd vphadduwq vphaddwd vphaddwq vphsubbw vphsubdq vphsubwd vpmacsdd vpmacsdqh vpmacsdql vpmacssdd vpmacssdqh vpmacssdql vpmacsswd vpmacssww vpmacswd vpmacsww vpmadcsswd vpmadcswd vpperm vprotb vprotd vprotq vprotw vpshab vpshad vpshaq vpshaw vpshlb vpshld vpshlq vpshlw vbroadcasti128 vpblendd vpbroadcastb vpbroadcastw vpbroadcastd vpbroadcastq vpermd vpermpd vpermps vpermq vperm2i128 vextracti128 vinserti128 vpmaskmovd vpmaskmovq vpsllvd vpsllvq vpsravd vpsrlvd vpsrlvq vgatherdpd vgatherqpd vgatherdps vgatherqps vpgatherdd vpgatherqd vpgatherdq vpgatherqq xabort xbegin xend xtest andn bextr blci blcic blsi blsic blcfill blsfill blcmsk blsmsk blsr blcs bzhi mulx pdep pext rorx sarx shlx shrx tzcnt tzmsk t1mskc valignd valignq vblendmpd vblendmps vbroadcastf32x4 vbroadcastf64x4 vbroadcasti32x4 vbroadcasti64x4 vcompresspd vcompressps vcvtpd2udq vcvtps2udq vcvtsd2usi vcvtss2usi vcvttpd2udq vcvttps2udq vcvttsd2usi vcvttss2usi vcvtudq2pd vcvtudq2ps vcvtusi2sd vcvtusi2ss vexpandpd vexpandps vextractf32x4 vextractf64x4 vextracti32x4 vextracti64x4 vfixupimmpd vfixupimmps vfixupimmsd vfixupimmss vgetexppd vgetexpps vgetexpsd vgetexpss vgetmantpd vgetmantps vgetmantsd vgetmantss vinsertf32x4 vinsertf64x4 vinserti32x4 vinserti64x4 vmovdqa32 vmovdqa64 vmovdqu32 vmovdqu64 vpabsq vpandd vpandnd vpandnq vpandq vpblendmd vpblendmq vpcmpltd vpcmpled vpcmpneqd vpcmpnltd vpcmpnled vpcmpd vpcmpltq vpcmpleq vpcmpneqq vpcmpnltq vpcmpnleq vpcmpq vpcmpequd vpcmpltud vpcmpleud vpcmpnequd vpcmpnltud vpcmpnleud vpcmpud vpcmpequq vpcmpltuq vpcmpleuq vpcmpnequq vpcmpnltuq vpcmpnleuq vpcmpuq vpcompressd vpcompressq vpermi2d vpermi2pd vpermi2ps vpermi2q vpermt2d vpermt2pd vpermt2ps vpermt2q vpexpandd vpexpandq vpmaxsq vpmaxuq vpminsq vpminuq vpmovdb vpmovdw vpmovqb vpmovqd vpmovqw vpmovsdb vpmovsdw vpmovsqb vpmovsqd vpmovsqw vpmovusdb vpmovusdw vpmovusqb vpmovusqd vpmovusqw vpord vporq vprold vprolq vprolvd vprolvq vprord vprorq vprorvd vprorvq vpscatterdd vpscatterdq vpscatterqd vpscatterqq vpsraq vpsravq vpternlogd vpternlogq vptestmd vptestmq vptestnmd vptestnmq vpxord vpxorq vrcp14pd vrcp14ps vrcp14sd vrcp14ss vrndscalepd vrndscaleps vrndscalesd vrndscaless vrsqrt14pd vrsqrt14ps vrsqrt14sd vrsqrt14ss vscalefpd vscalefps vscalefsd vscalefss vscatterdpd vscatterdps vscatterqpd vscatterqps vshuff32x4 vshuff64x2 vshufi32x4 vshufi64x2 kandnw kandw kmovw knotw kortestw korw kshiftlw kshiftrw kunpckbw kxnorw kxorw vpbroadcastmb2q vpbroadcastmw2d vpconflictd vpconflictq vplzcntd vplzcntq vexp2pd vexp2ps vrcp28pd vrcp28ps vrcp28sd vrcp28ss vrsqrt28pd vrsqrt28ps vrsqrt28sd vrsqrt28ss vgatherpf0dpd vgatherpf0dps vgatherpf0qpd vgatherpf0qps vgatherpf1dpd vgatherpf1dps vgatherpf1qpd vgatherpf1qps vscatterpf0dpd vscatterpf0dps vscatterpf0qpd vscatterpf0qps vscatterpf1dpd vscatterpf1dps vscatterpf1qpd vscatterpf1qps prefetchwt1 bndmk bndcl bndcu bndcn bndmov bndldx bndstx sha1rnds4 sha1nexte sha1msg1 sha1msg2 sha256rnds2 sha256msg1 sha256msg2 hint_nop0 hint_nop1 hint_nop2 hint_nop3 hint_nop4 hint_nop5 hint_nop6 hint_nop7 hint_nop8 hint_nop9 hint_nop10 hint_nop11 hint_nop12 hint_nop13 hint_nop14 hint_nop15 hint_nop16 hint_nop17 hint_nop18 hint_nop19 hint_nop20 hint_nop21 hint_nop22 hint_nop23 hint_nop24 hint_nop25 hint_nop26 hint_nop27 hint_nop28 hint_nop29 hint_nop30 hint_nop31 hint_nop32 hint_nop33 hint_nop34 hint_nop35 hint_nop36 hint_nop37 hint_nop38 hint_nop39 hint_nop40 hint_nop41 hint_nop42 hint_nop43 hint_nop44 hint_nop45 hint_nop46 hint_nop47 hint_nop48 hint_nop49 hint_nop50 hint_nop51 hint_nop52 hint_nop53 hint_nop54 hint_nop55 hint_nop56 hint_nop57 hint_nop58 hint_nop59 hint_nop60 hint_nop61 hint_nop62 hint_nop63",
          built_in: (
            // Instruction pointer
            "ip eip rip al ah bl bh cl ch dl dh sil dil bpl spl r8b r9b r10b r11b r12b r13b r14b r15b ax bx cx dx si di bp sp r8w r9w r10w r11w r12w r13w r14w r15w eax ebx ecx edx esi edi ebp esp eip r8d r9d r10d r11d r12d r13d r14d r15d rax rbx rcx rdx rsi rdi rbp rsp r8 r9 r10 r11 r12 r13 r14 r15 cs ds es fs gs ss st st0 st1 st2 st3 st4 st5 st6 st7 mm0 mm1 mm2 mm3 mm4 mm5 mm6 mm7 xmm0  xmm1  xmm2  xmm3  xmm4  xmm5  xmm6  xmm7  xmm8  xmm9 xmm10  xmm11 xmm12 xmm13 xmm14 xmm15 xmm16 xmm17 xmm18 xmm19 xmm20 xmm21 xmm22 xmm23 xmm24 xmm25 xmm26 xmm27 xmm28 xmm29 xmm30 xmm31 ymm0  ymm1  ymm2  ymm3  ymm4  ymm5  ymm6  ymm7  ymm8  ymm9 ymm10  ymm11 ymm12 ymm13 ymm14 ymm15 ymm16 ymm17 ymm18 ymm19 ymm20 ymm21 ymm22 ymm23 ymm24 ymm25 ymm26 ymm27 ymm28 ymm29 ymm30 ymm31 zmm0  zmm1  zmm2  zmm3  zmm4  zmm5  zmm6  zmm7  zmm8  zmm9 zmm10  zmm11 zmm12 zmm13 zmm14 zmm15 zmm16 zmm17 zmm18 zmm19 zmm20 zmm21 zmm22 zmm23 zmm24 zmm25 zmm26 zmm27 zmm28 zmm29 zmm30 zmm31 k0 k1 k2 k3 k4 k5 k6 k7 bnd0 bnd1 bnd2 bnd3 cr0 cr1 cr2 cr3 cr4 cr8 dr0 dr1 dr2 dr3 dr8 tr3 tr4 tr5 tr6 tr7 r0 r1 r2 r3 r4 r5 r6 r7 r0b r1b r2b r3b r4b r5b r6b r7b r0w r1w r2w r3w r4w r5w r6w r7w r0d r1d r2d r3d r4d r5d r6d r7d r0h r1h r2h r3h r0l r1l r2l r3l r4l r5l r6l r7l r8l r9l r10l r11l r12l r13l r14l r15l db dw dd dq dt ddq do dy dz resb resw resd resq rest resdq reso resy resz incbin equ times byte word dword qword nosplit rel abs seg wrt strict near far a32 ptr"
          ),
          meta: "%define %xdefine %+ %undef %defstr %deftok %assign %strcat %strlen %substr %rotate %elif %else %endif %if %ifmacro %ifctx %ifidn %ifidni %ifid %ifnum %ifstr %iftoken %ifempty %ifenv %error %warning %fatal %rep %endrep %include %push %pop %repl %pathsearch %depend %use %arg %stacksize %local %line %comment %endcomment .nolist __FILE__ __LINE__ __SECT__  __BITS__ __OUTPUT_FORMAT__ __DATE__ __TIME__ __DATE_NUM__ __TIME_NUM__ __UTC_DATE__ __UTC_TIME__ __UTC_DATE_NUM__ __UTC_TIME_NUM__  __PASS__ struc endstruc istruc at iend align alignb sectalign daz nodaz up down zero default option assume public bits use16 use32 use64 default section segment absolute extern global common cpu float __utf16__ __utf16le__ __utf16be__ __utf32__ __utf32le__ __utf32be__ __float8__ __float16__ __float32__ __float64__ __float80m__ __float80e__ __float128l__ __float128h__ __Infinity__ __QNaN__ __SNaN__ Inf NaN QNaN SNaN float8 float16 float32 float64 float80m float80e float128l float128h __FLOAT_DAZ__ __FLOAT_ROUND__ __FLOAT__"
        },
        contains: [
          hljs5.COMMENT(
            ";",
            "$",
            {
              relevance: 0
            }
          ),
          {
            className: "number",
            variants: [
              // Float number and x87 BCD
              {
                begin: "\\b(?:([0-9][0-9_]*)?\\.[0-9_]*(?:[eE][+-]?[0-9_]+)?|(0[Xx])?[0-9][0-9_]*(\\.[0-9_]*)?(?:[pP](?:[+-]?[0-9_]+)?)?)\\b",
                relevance: 0
              },
              // Hex number in $
              {
                begin: "\\$[0-9][0-9A-Fa-f]*",
                relevance: 0
              },
              // Number in H,D,T,Q,O,B,Y suffix
              {
                begin: "\\b(?:[0-9A-Fa-f][0-9A-Fa-f_]*[Hh]|[0-9][0-9_]*[DdTt]?|[0-7][0-7_]*[QqOo]|[0-1][0-1_]*[BbYy])\\b"
              },
              // Number in X,D,T,Q,O,B,Y prefix
              {
                begin: "\\b(?:0[Xx][0-9A-Fa-f_]+|0[DdTt][0-9_]+|0[QqOo][0-7_]+|0[BbYy][0-1_]+)\\b"
              }
            ]
          },
          // Double quote string
          hljs5.QUOTE_STRING_MODE,
          {
            className: "string",
            variants: [
              // Single-quoted string
              {
                begin: "'",
                end: "[^\\\\]'"
              },
              // Backquoted string
              {
                begin: "`",
                end: "[^\\\\]`"
              }
            ],
            relevance: 0
          },
          {
            className: "symbol",
            variants: [
              // Global label and local label
              {
                begin: "^\\s*[A-Za-z._?][A-Za-z0-9_$#@~.?]*(:|\\s+label)"
              },
              // Macro-local label
              {
                begin: "^\\s*%%[A-Za-z0-9_$#@~.?]*:"
              }
            ],
            relevance: 0
          },
          // Macro parameter
          {
            className: "subst",
            begin: "%[0-9]+",
            relevance: 0
          },
          // Macro parameter
          {
            className: "subst",
            begin: "%!S+",
            relevance: 0
          },
          {
            className: "meta",
            begin: /^\s*\.[\w_-]+/
          }
        ]
      };
    }
    module.exports = x86asm;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/xl.js
var require_xl = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/xl.js"(exports, module) {
    init_process_shim();
    function xl(hljs5) {
      const BUILTIN_MODULES = "ObjectLoader Animate MovieCredits Slides Filters Shading Materials LensFlare Mapping VLCAudioVideo StereoDecoder PointCloud NetworkAccess RemoteControl RegExp ChromaKey Snowfall NodeJS Speech Charts";
      const XL_KEYWORDS = {
        $pattern: /[a-zA-Z][a-zA-Z0-9_?]*/,
        keyword: "if then else do while until for loop import with is as where when by data constant integer real text name boolean symbol infix prefix postfix block tree",
        literal: "true false nil",
        built_in: "in mod rem and or xor not abs sign floor ceil sqrt sin cos tan asin acos atan exp expm1 log log2 log10 log1p pi at text_length text_range text_find text_replace contains page slide basic_slide title_slide title subtitle fade_in fade_out fade_at clear_color color line_color line_width texture_wrap texture_transform texture scale_?x scale_?y scale_?z? translate_?x translate_?y translate_?z? rotate_?x rotate_?y rotate_?z? rectangle circle ellipse sphere path line_to move_to quad_to curve_to theme background contents locally time mouse_?x mouse_?y mouse_buttons " + BUILTIN_MODULES
      };
      const DOUBLE_QUOTE_TEXT = {
        className: "string",
        begin: '"',
        end: '"',
        illegal: "\\n"
      };
      const SINGLE_QUOTE_TEXT = {
        className: "string",
        begin: "'",
        end: "'",
        illegal: "\\n"
      };
      const LONG_TEXT = {
        className: "string",
        begin: "<<",
        end: ">>"
      };
      const BASED_NUMBER = {
        className: "number",
        begin: "[0-9]+#[0-9A-Z_]+(\\.[0-9-A-Z_]+)?#?([Ee][+-]?[0-9]+)?"
      };
      const IMPORT = {
        beginKeywords: "import",
        end: "$",
        keywords: XL_KEYWORDS,
        contains: [DOUBLE_QUOTE_TEXT]
      };
      const FUNCTION_DEFINITION = {
        className: "function",
        begin: /[a-z][^\n]*->/,
        returnBegin: true,
        end: /->/,
        contains: [
          hljs5.inherit(hljs5.TITLE_MODE, {
            starts: {
              endsWithParent: true,
              keywords: XL_KEYWORDS
            }
          })
        ]
      };
      return {
        name: "XL",
        aliases: ["tao"],
        keywords: XL_KEYWORDS,
        contains: [
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.C_BLOCK_COMMENT_MODE,
          DOUBLE_QUOTE_TEXT,
          SINGLE_QUOTE_TEXT,
          LONG_TEXT,
          FUNCTION_DEFINITION,
          IMPORT,
          BASED_NUMBER,
          hljs5.NUMBER_MODE
        ]
      };
    }
    module.exports = xl;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/xquery.js
var require_xquery = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/xquery.js"(exports, module) {
    init_process_shim();
    function xquery(_hljs) {
      const KEYWORDS3 = "module schema namespace boundary-space preserve no-preserve strip default collation base-uri ordering context decimal-format decimal-separator copy-namespaces empty-sequence except exponent-separator external grouping-separator inherit no-inherit lax minus-sign per-mille percent schema-attribute schema-element strict unordered zero-digit declare import option function validate variable for at in let where order group by return if then else tumbling sliding window start when only end previous next stable ascending descending allowing empty greatest least some every satisfies switch case typeswitch try catch and or to union intersect instance of treat as castable cast map array delete insert into replace value rename copy modify update";
      const TYPE = "item document-node node attribute document element comment namespace namespace-node processing-instruction text construction xs:anyAtomicType xs:untypedAtomic xs:duration xs:time xs:decimal xs:float xs:double xs:gYearMonth xs:gYear xs:gMonthDay xs:gMonth xs:gDay xs:boolean xs:base64Binary xs:hexBinary xs:anyURI xs:QName xs:NOTATION xs:dateTime xs:dateTimeStamp xs:date xs:string xs:normalizedString xs:token xs:language xs:NMTOKEN xs:Name xs:NCName xs:ID xs:IDREF xs:ENTITY xs:integer xs:nonPositiveInteger xs:negativeInteger xs:long xs:int xs:short xs:byte xs:nonNegativeInteger xs:unisignedLong xs:unsignedInt xs:unsignedShort xs:unsignedByte xs:positiveInteger xs:yearMonthDuration xs:dayTimeDuration";
      const LITERAL = "eq ne lt le gt ge is self:: child:: descendant:: descendant-or-self:: attribute:: following:: following-sibling:: parent:: ancestor:: ancestor-or-self:: preceding:: preceding-sibling:: NaN";
      const BUILT_IN = {
        className: "built_in",
        variants: [
          {
            begin: /\barray:/,
            end: /(?:append|filter|flatten|fold-(?:left|right)|for-each(?:-pair)?|get|head|insert-before|join|put|remove|reverse|size|sort|subarray|tail)\b/
          },
          {
            begin: /\bmap:/,
            end: /(?:contains|entry|find|for-each|get|keys|merge|put|remove|size)\b/
          },
          {
            begin: /\bmath:/,
            end: /(?:a(?:cos|sin|tan[2]?)|cos|exp(?:10)?|log(?:10)?|pi|pow|sin|sqrt|tan)\b/
          },
          {
            begin: /\bop:/,
            end: /\(/,
            excludeEnd: true
          },
          {
            begin: /\bfn:/,
            end: /\(/,
            excludeEnd: true
          },
          // do not highlight inbuilt strings as variable or xml element names
          {
            begin: /[^</$:'"-]\b(?:abs|accumulator-(?:after|before)|adjust-(?:date(?:Time)?|time)-to-timezone|analyze-string|apply|available-(?:environment-variables|system-properties)|avg|base-uri|boolean|ceiling|codepoints?-(?:equal|to-string)|collation-key|collection|compare|concat|contains(?:-token)?|copy-of|count|current(?:-)?(?:date(?:Time)?|time|group(?:ing-key)?|output-uri|merge-(?:group|key))?data|dateTime|days?-from-(?:date(?:Time)?|duration)|deep-equal|default-(?:collation|language)|distinct-values|document(?:-uri)?|doc(?:-available)?|element-(?:available|with-id)|empty|encode-for-uri|ends-with|environment-variable|error|escape-html-uri|exactly-one|exists|false|filter|floor|fold-(?:left|right)|for-each(?:-pair)?|format-(?:date(?:Time)?|time|integer|number)|function-(?:arity|available|lookup|name)|generate-id|has-children|head|hours-from-(?:dateTime|duration|time)|id(?:ref)?|implicit-timezone|in-scope-prefixes|index-of|innermost|insert-before|iri-to-uri|json-(?:doc|to-xml)|key|lang|last|load-xquery-module|local-name(?:-from-QName)?|(?:lower|upper)-case|matches|max|minutes-from-(?:dateTime|duration|time)|min|months?-from-(?:date(?:Time)?|duration)|name(?:space-uri-?(?:for-prefix|from-QName)?)?|nilled|node-name|normalize-(?:space|unicode)|not|number|one-or-more|outermost|parse-(?:ietf-date|json)|path|position|(?:prefix-from-)?QName|random-number-generator|regex-group|remove|replace|resolve-(?:QName|uri)|reverse|root|round(?:-half-to-even)?|seconds-from-(?:dateTime|duration|time)|snapshot|sort|starts-with|static-base-uri|stream-available|string-?(?:join|length|to-codepoints)?|subsequence|substring-?(?:after|before)?|sum|system-property|tail|timezone-from-(?:date(?:Time)?|time)|tokenize|trace|trans(?:form|late)|true|type-available|unordered|unparsed-(?:entity|text)?-?(?:public-id|uri|available|lines)?|uri-collection|xml-to-json|years?-from-(?:date(?:Time)?|duration)|zero-or-one)\b/
          },
          {
            begin: /\blocal:/,
            end: /\(/,
            excludeEnd: true
          },
          {
            begin: /\bzip:/,
            end: /(?:zip-file|(?:xml|html|text|binary)-entry| (?:update-)?entries)\b/
          },
          {
            begin: /\b(?:util|db|functx|app|xdmp|xmldb):/,
            end: /\(/,
            excludeEnd: true
          }
        ]
      };
      const TITLE = {
        className: "title",
        begin: /\bxquery version "[13]\.[01]"\s?(?:encoding ".+")?/,
        end: /;/
      };
      const VAR = {
        className: "variable",
        begin: /[$][\w\-:]+/
      };
      const NUMBER = {
        className: "number",
        begin: /(\b0[0-7_]+)|(\b0x[0-9a-fA-F_]+)|(\b[1-9][0-9_]*(\.[0-9_]+)?)|[0_]\b/,
        relevance: 0
      };
      const STRING = {
        className: "string",
        variants: [
          {
            begin: /"/,
            end: /"/,
            contains: [
              {
                begin: /""/,
                relevance: 0
              }
            ]
          },
          {
            begin: /'/,
            end: /'/,
            contains: [
              {
                begin: /''/,
                relevance: 0
              }
            ]
          }
        ]
      };
      const ANNOTATION = {
        className: "meta",
        begin: /%[\w\-:]+/
      };
      const COMMENT = {
        className: "comment",
        begin: /\(:/,
        end: /:\)/,
        relevance: 10,
        contains: [
          {
            className: "doctag",
            begin: /@\w+/
          }
        ]
      };
      const COMPUTED = {
        beginKeywords: "element attribute comment document processing-instruction",
        end: /\{/,
        excludeEnd: true
      };
      const DIRECT = {
        begin: /<([\w._:-]+)(\s+\S*=('|").*('|"))?>/,
        end: /(\/[\w._:-]+>)/,
        subLanguage: "xml",
        contains: [
          {
            begin: /\{/,
            end: /\}/,
            subLanguage: "xquery"
          },
          "self"
        ]
      };
      const CONTAINS = [
        VAR,
        BUILT_IN,
        STRING,
        NUMBER,
        COMMENT,
        ANNOTATION,
        TITLE,
        COMPUTED,
        DIRECT
      ];
      return {
        name: "XQuery",
        aliases: [
          "xpath",
          "xq"
        ],
        case_insensitive: false,
        illegal: /(proc)|(abstract)|(extends)|(until)|(#)/,
        keywords: {
          $pattern: /[a-zA-Z$][a-zA-Z0-9_:-]*/,
          keyword: KEYWORDS3,
          type: TYPE,
          literal: LITERAL
        },
        contains: CONTAINS
      };
    }
    module.exports = xquery;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/languages/zephir.js
var require_zephir = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/languages/zephir.js"(exports, module) {
    init_process_shim();
    function zephir(hljs5) {
      const STRING = {
        className: "string",
        contains: [hljs5.BACKSLASH_ESCAPE],
        variants: [
          hljs5.inherit(hljs5.APOS_STRING_MODE, {
            illegal: null
          }),
          hljs5.inherit(hljs5.QUOTE_STRING_MODE, {
            illegal: null
          })
        ]
      };
      const TITLE_MODE = hljs5.UNDERSCORE_TITLE_MODE;
      const NUMBER = {
        variants: [
          hljs5.BINARY_NUMBER_MODE,
          hljs5.C_NUMBER_MODE
        ]
      };
      const KEYWORDS3 = (
        // classes and objects
        "namespace class interface use extends function return abstract final public protected private static deprecated throw try catch Exception echo empty isset instanceof unset let var new const self require if else elseif switch case default do while loop for continue break likely unlikely __LINE__ __FILE__ __DIR__ __FUNCTION__ __CLASS__ __TRAIT__ __METHOD__ __NAMESPACE__ array boolean float double integer object resource string char long unsigned bool int uint ulong uchar true false null undefined"
      );
      return {
        name: "Zephir",
        aliases: ["zep"],
        keywords: KEYWORDS3,
        contains: [
          hljs5.C_LINE_COMMENT_MODE,
          hljs5.COMMENT(
            /\/\*/,
            /\*\//,
            {
              contains: [
                {
                  className: "doctag",
                  begin: /@[A-Za-z]+/
                }
              ]
            }
          ),
          {
            className: "string",
            begin: /<<<['"]?\w+['"]?$/,
            end: /^\w+;/,
            contains: [hljs5.BACKSLASH_ESCAPE]
          },
          {
            // swallow composed identifiers to avoid parsing them as keywords
            begin: /(::|->)+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/
          },
          {
            className: "function",
            beginKeywords: "function fn",
            end: /[;{]/,
            excludeEnd: true,
            illegal: /\$|\[|%/,
            contains: [
              TITLE_MODE,
              {
                className: "params",
                begin: /\(/,
                end: /\)/,
                keywords: KEYWORDS3,
                contains: [
                  "self",
                  hljs5.C_BLOCK_COMMENT_MODE,
                  STRING,
                  NUMBER
                ]
              }
            ]
          },
          {
            className: "class",
            beginKeywords: "class interface",
            end: /\{/,
            excludeEnd: true,
            illegal: /[:($"]/,
            contains: [
              {
                beginKeywords: "extends implements"
              },
              TITLE_MODE
            ]
          },
          {
            beginKeywords: "namespace",
            end: /;/,
            illegal: /[.']/,
            contains: [TITLE_MODE]
          },
          {
            beginKeywords: "use",
            end: /;/,
            contains: [TITLE_MODE]
          },
          {
            begin: /=>/
            // No markup, just a relevance booster
          },
          STRING,
          NUMBER
        ]
      };
    }
    module.exports = zephir;
  }
});

// ../pi-mono/node_modules/highlight.js/lib/index.js
var require_lib = __commonJS({
  "../pi-mono/node_modules/highlight.js/lib/index.js"(exports, module) {
    init_process_shim();
    var hljs5 = require_core3();
    hljs5.registerLanguage("1c", require_c());
    hljs5.registerLanguage("abnf", require_abnf());
    hljs5.registerLanguage("accesslog", require_accesslog());
    hljs5.registerLanguage("actionscript", require_actionscript());
    hljs5.registerLanguage("ada", require_ada());
    hljs5.registerLanguage("angelscript", require_angelscript());
    hljs5.registerLanguage("apache", require_apache());
    hljs5.registerLanguage("applescript", require_applescript());
    hljs5.registerLanguage("arcade", require_arcade());
    hljs5.registerLanguage("arduino", require_arduino());
    hljs5.registerLanguage("armasm", require_armasm());
    hljs5.registerLanguage("xml", require_xml());
    hljs5.registerLanguage("asciidoc", require_asciidoc());
    hljs5.registerLanguage("aspectj", require_aspectj());
    hljs5.registerLanguage("autohotkey", require_autohotkey());
    hljs5.registerLanguage("autoit", require_autoit());
    hljs5.registerLanguage("avrasm", require_avrasm());
    hljs5.registerLanguage("awk", require_awk());
    hljs5.registerLanguage("axapta", require_axapta());
    hljs5.registerLanguage("bash", require_bash());
    hljs5.registerLanguage("basic", require_basic());
    hljs5.registerLanguage("bnf", require_bnf());
    hljs5.registerLanguage("brainfuck", require_brainfuck());
    hljs5.registerLanguage("c-like", require_c_like());
    hljs5.registerLanguage("c", require_c2());
    hljs5.registerLanguage("cal", require_cal());
    hljs5.registerLanguage("capnproto", require_capnproto());
    hljs5.registerLanguage("ceylon", require_ceylon());
    hljs5.registerLanguage("clean", require_clean());
    hljs5.registerLanguage("clojure", require_clojure());
    hljs5.registerLanguage("clojure-repl", require_clojure_repl());
    hljs5.registerLanguage("cmake", require_cmake());
    hljs5.registerLanguage("coffeescript", require_coffeescript());
    hljs5.registerLanguage("coq", require_coq());
    hljs5.registerLanguage("cos", require_cos());
    hljs5.registerLanguage("cpp", require_cpp());
    hljs5.registerLanguage("crmsh", require_crmsh());
    hljs5.registerLanguage("crystal", require_crystal());
    hljs5.registerLanguage("csharp", require_csharp());
    hljs5.registerLanguage("csp", require_csp());
    hljs5.registerLanguage("css", require_css());
    hljs5.registerLanguage("d", require_d());
    hljs5.registerLanguage("markdown", require_markdown());
    hljs5.registerLanguage("dart", require_dart());
    hljs5.registerLanguage("delphi", require_delphi());
    hljs5.registerLanguage("diff", require_diff());
    hljs5.registerLanguage("django", require_django());
    hljs5.registerLanguage("dns", require_dns());
    hljs5.registerLanguage("dockerfile", require_dockerfile());
    hljs5.registerLanguage("dos", require_dos());
    hljs5.registerLanguage("dsconfig", require_dsconfig());
    hljs5.registerLanguage("dts", require_dts());
    hljs5.registerLanguage("dust", require_dust());
    hljs5.registerLanguage("ebnf", require_ebnf());
    hljs5.registerLanguage("elixir", require_elixir());
    hljs5.registerLanguage("elm", require_elm());
    hljs5.registerLanguage("ruby", require_ruby());
    hljs5.registerLanguage("erb", require_erb());
    hljs5.registerLanguage("erlang-repl", require_erlang_repl());
    hljs5.registerLanguage("erlang", require_erlang());
    hljs5.registerLanguage("excel", require_excel());
    hljs5.registerLanguage("fix", require_fix());
    hljs5.registerLanguage("flix", require_flix());
    hljs5.registerLanguage("fortran", require_fortran());
    hljs5.registerLanguage("fsharp", require_fsharp());
    hljs5.registerLanguage("gams", require_gams());
    hljs5.registerLanguage("gauss", require_gauss());
    hljs5.registerLanguage("gcode", require_gcode());
    hljs5.registerLanguage("gherkin", require_gherkin());
    hljs5.registerLanguage("glsl", require_glsl());
    hljs5.registerLanguage("gml", require_gml());
    hljs5.registerLanguage("go", require_go());
    hljs5.registerLanguage("golo", require_golo());
    hljs5.registerLanguage("gradle", require_gradle());
    hljs5.registerLanguage("groovy", require_groovy());
    hljs5.registerLanguage("haml", require_haml());
    hljs5.registerLanguage("handlebars", require_handlebars());
    hljs5.registerLanguage("haskell", require_haskell());
    hljs5.registerLanguage("haxe", require_haxe());
    hljs5.registerLanguage("hsp", require_hsp());
    hljs5.registerLanguage("htmlbars", require_htmlbars());
    hljs5.registerLanguage("http", require_http2());
    hljs5.registerLanguage("hy", require_hy());
    hljs5.registerLanguage("inform7", require_inform7());
    hljs5.registerLanguage("ini", require_ini());
    hljs5.registerLanguage("irpf90", require_irpf90());
    hljs5.registerLanguage("isbl", require_isbl());
    hljs5.registerLanguage("java", require_java());
    hljs5.registerLanguage("javascript", require_javascript());
    hljs5.registerLanguage("jboss-cli", require_jboss_cli());
    hljs5.registerLanguage("json", require_json());
    hljs5.registerLanguage("julia", require_julia());
    hljs5.registerLanguage("julia-repl", require_julia_repl());
    hljs5.registerLanguage("kotlin", require_kotlin());
    hljs5.registerLanguage("lasso", require_lasso());
    hljs5.registerLanguage("latex", require_latex());
    hljs5.registerLanguage("ldif", require_ldif());
    hljs5.registerLanguage("leaf", require_leaf());
    hljs5.registerLanguage("less", require_less());
    hljs5.registerLanguage("lisp", require_lisp());
    hljs5.registerLanguage("livecodeserver", require_livecodeserver());
    hljs5.registerLanguage("livescript", require_livescript());
    hljs5.registerLanguage("llvm", require_llvm());
    hljs5.registerLanguage("lsl", require_lsl());
    hljs5.registerLanguage("lua", require_lua());
    hljs5.registerLanguage("makefile", require_makefile());
    hljs5.registerLanguage("mathematica", require_mathematica());
    hljs5.registerLanguage("matlab", require_matlab());
    hljs5.registerLanguage("maxima", require_maxima());
    hljs5.registerLanguage("mel", require_mel());
    hljs5.registerLanguage("mercury", require_mercury());
    hljs5.registerLanguage("mipsasm", require_mipsasm());
    hljs5.registerLanguage("mizar", require_mizar());
    hljs5.registerLanguage("perl", require_perl());
    hljs5.registerLanguage("mojolicious", require_mojolicious());
    hljs5.registerLanguage("monkey", require_monkey());
    hljs5.registerLanguage("moonscript", require_moonscript());
    hljs5.registerLanguage("n1ql", require_n1ql());
    hljs5.registerLanguage("nginx", require_nginx());
    hljs5.registerLanguage("nim", require_nim());
    hljs5.registerLanguage("nix", require_nix());
    hljs5.registerLanguage("node-repl", require_node_repl());
    hljs5.registerLanguage("nsis", require_nsis());
    hljs5.registerLanguage("objectivec", require_objectivec());
    hljs5.registerLanguage("ocaml", require_ocaml());
    hljs5.registerLanguage("openscad", require_openscad());
    hljs5.registerLanguage("oxygene", require_oxygene());
    hljs5.registerLanguage("parser3", require_parser3());
    hljs5.registerLanguage("pf", require_pf());
    hljs5.registerLanguage("pgsql", require_pgsql());
    hljs5.registerLanguage("php", require_php());
    hljs5.registerLanguage("php-template", require_php_template());
    hljs5.registerLanguage("plaintext", require_plaintext());
    hljs5.registerLanguage("pony", require_pony());
    hljs5.registerLanguage("powershell", require_powershell());
    hljs5.registerLanguage("processing", require_processing());
    hljs5.registerLanguage("profile", require_profile());
    hljs5.registerLanguage("prolog", require_prolog());
    hljs5.registerLanguage("properties", require_properties2());
    hljs5.registerLanguage("protobuf", require_protobuf());
    hljs5.registerLanguage("puppet", require_puppet());
    hljs5.registerLanguage("purebasic", require_purebasic());
    hljs5.registerLanguage("python", require_python());
    hljs5.registerLanguage("python-repl", require_python_repl());
    hljs5.registerLanguage("q", require_q());
    hljs5.registerLanguage("qml", require_qml());
    hljs5.registerLanguage("r", require_r());
    hljs5.registerLanguage("reasonml", require_reasonml());
    hljs5.registerLanguage("rib", require_rib());
    hljs5.registerLanguage("roboconf", require_roboconf());
    hljs5.registerLanguage("routeros", require_routeros());
    hljs5.registerLanguage("rsl", require_rsl());
    hljs5.registerLanguage("ruleslanguage", require_ruleslanguage());
    hljs5.registerLanguage("rust", require_rust());
    hljs5.registerLanguage("sas", require_sas());
    hljs5.registerLanguage("scala", require_scala());
    hljs5.registerLanguage("scheme", require_scheme());
    hljs5.registerLanguage("scilab", require_scilab());
    hljs5.registerLanguage("scss", require_scss());
    hljs5.registerLanguage("shell", require_shell());
    hljs5.registerLanguage("smali", require_smali());
    hljs5.registerLanguage("smalltalk", require_smalltalk());
    hljs5.registerLanguage("sml", require_sml());
    hljs5.registerLanguage("sqf", require_sqf());
    hljs5.registerLanguage("sql_more", require_sql_more());
    hljs5.registerLanguage("sql", require_sql());
    hljs5.registerLanguage("stan", require_stan());
    hljs5.registerLanguage("stata", require_stata());
    hljs5.registerLanguage("step21", require_step21());
    hljs5.registerLanguage("stylus", require_stylus());
    hljs5.registerLanguage("subunit", require_subunit());
    hljs5.registerLanguage("swift", require_swift());
    hljs5.registerLanguage("taggerscript", require_taggerscript());
    hljs5.registerLanguage("yaml", require_yaml());
    hljs5.registerLanguage("tap", require_tap());
    hljs5.registerLanguage("tcl", require_tcl());
    hljs5.registerLanguage("thrift", require_thrift());
    hljs5.registerLanguage("tp", require_tp());
    hljs5.registerLanguage("twig", require_twig());
    hljs5.registerLanguage("typescript", require_typescript());
    hljs5.registerLanguage("vala", require_vala());
    hljs5.registerLanguage("vbnet", require_vbnet());
    hljs5.registerLanguage("vbscript", require_vbscript());
    hljs5.registerLanguage("vbscript-html", require_vbscript_html());
    hljs5.registerLanguage("verilog", require_verilog());
    hljs5.registerLanguage("vhdl", require_vhdl());
    hljs5.registerLanguage("vim", require_vim());
    hljs5.registerLanguage("x86asm", require_x86asm());
    hljs5.registerLanguage("xl", require_xl());
    hljs5.registerLanguage("xquery", require_xquery());
    hljs5.registerLanguage("zephir", require_zephir());
    module.exports = hljs5;
  }
});

// ../mini-lit/node_modules/highlight.js/lib/core.js
var require_core4 = __commonJS({
  "../mini-lit/node_modules/highlight.js/lib/core.js"(exports, module) {
    init_process_shim();
    function deepFreeze(obj) {
      if (obj instanceof Map) {
        obj.clear = obj.delete = obj.set = function() {
          throw new Error("map is read-only");
        };
      } else if (obj instanceof Set) {
        obj.add = obj.clear = obj.delete = function() {
          throw new Error("set is read-only");
        };
      }
      Object.freeze(obj);
      Object.getOwnPropertyNames(obj).forEach((name) => {
        const prop = obj[name];
        const type = typeof prop;
        if ((type === "object" || type === "function") && !Object.isFrozen(prop)) {
          deepFreeze(prop);
        }
      });
      return obj;
    }
    var Response3 = class {
      /**
       * @param {CompiledMode} mode
       */
      constructor(mode) {
        if (mode.data === void 0) mode.data = {};
        this.data = mode.data;
        this.isMatchIgnored = false;
      }
      ignoreMatch() {
        this.isMatchIgnored = true;
      }
    };
    function escapeHTML(value) {
      return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#x27;");
    }
    function inherit$1(original, ...objects) {
      const result = /* @__PURE__ */ Object.create(null);
      for (const key in original) {
        result[key] = original[key];
      }
      objects.forEach(function(obj) {
        for (const key in obj) {
          result[key] = obj[key];
        }
      });
      return (
        /** @type {T} */
        result
      );
    }
    var SPAN_CLOSE = "</span>";
    var emitsWrappingTags = (node) => {
      return !!node.scope;
    };
    var scopeToCSSClass = (name, { prefix }) => {
      if (name.startsWith("language:")) {
        return name.replace("language:", "language-");
      }
      if (name.includes(".")) {
        const pieces = name.split(".");
        return [
          `${prefix}${pieces.shift()}`,
          ...pieces.map((x2, i7) => `${x2}${"_".repeat(i7 + 1)}`)
        ].join(" ");
      }
      return `${prefix}${name}`;
    };
    var HTMLRenderer = class {
      /**
       * Creates a new HTMLRenderer
       *
       * @param {Tree} parseTree - the parse tree (must support `walk` API)
       * @param {{classPrefix: string}} options
       */
      constructor(parseTree3, options) {
        this.buffer = "";
        this.classPrefix = options.classPrefix;
        parseTree3.walk(this);
      }
      /**
       * Adds texts to the output stream
       *
       * @param {string} text */
      addText(text3) {
        this.buffer += escapeHTML(text3);
      }
      /**
       * Adds a node open to the output stream (if needed)
       *
       * @param {Node} node */
      openNode(node) {
        if (!emitsWrappingTags(node)) return;
        const className = scopeToCSSClass(
          node.scope,
          { prefix: this.classPrefix }
        );
        this.span(className);
      }
      /**
       * Adds a node close to the output stream (if needed)
       *
       * @param {Node} node */
      closeNode(node) {
        if (!emitsWrappingTags(node)) return;
        this.buffer += SPAN_CLOSE;
      }
      /**
       * returns the accumulated buffer
      */
      value() {
        return this.buffer;
      }
      // helpers
      /**
       * Builds a span element
       *
       * @param {string} className */
      span(className) {
        this.buffer += `<span class="${className}">`;
      }
    };
    var newNode = (opts = {}) => {
      const result = { children: [] };
      Object.assign(result, opts);
      return result;
    };
    var TokenTree = class _TokenTree {
      constructor() {
        this.rootNode = newNode();
        this.stack = [this.rootNode];
      }
      get top() {
        return this.stack[this.stack.length - 1];
      }
      get root() {
        return this.rootNode;
      }
      /** @param {Node} node */
      add(node) {
        this.top.children.push(node);
      }
      /** @param {string} scope */
      openNode(scope) {
        const node = newNode({ scope });
        this.add(node);
        this.stack.push(node);
      }
      closeNode() {
        if (this.stack.length > 1) {
          return this.stack.pop();
        }
        return void 0;
      }
      closeAllNodes() {
        while (this.closeNode()) ;
      }
      toJSON() {
        return JSON.stringify(this.rootNode, null, 4);
      }
      /**
       * @typedef { import("./html_renderer").Renderer } Renderer
       * @param {Renderer} builder
       */
      walk(builder) {
        return this.constructor._walk(builder, this.rootNode);
      }
      /**
       * @param {Renderer} builder
       * @param {Node} node
       */
      static _walk(builder, node) {
        if (typeof node === "string") {
          builder.addText(node);
        } else if (node.children) {
          builder.openNode(node);
          node.children.forEach((child) => this._walk(builder, child));
          builder.closeNode(node);
        }
        return builder;
      }
      /**
       * @param {Node} node
       */
      static _collapse(node) {
        if (typeof node === "string") return;
        if (!node.children) return;
        if (node.children.every((el) => typeof el === "string")) {
          node.children = [node.children.join("")];
        } else {
          node.children.forEach((child) => {
            _TokenTree._collapse(child);
          });
        }
      }
    };
    var TokenTreeEmitter = class extends TokenTree {
      /**
       * @param {*} options
       */
      constructor(options) {
        super();
        this.options = options;
      }
      /**
       * @param {string} text
       */
      addText(text3) {
        if (text3 === "") {
          return;
        }
        this.add(text3);
      }
      /** @param {string} scope */
      startScope(scope) {
        this.openNode(scope);
      }
      endScope() {
        this.closeNode();
      }
      /**
       * @param {Emitter & {root: DataNode}} emitter
       * @param {string} name
       */
      __addSublanguage(emitter, name) {
        const node = emitter.root;
        if (name) node.scope = `language:${name}`;
        this.add(node);
      }
      toHTML() {
        const renderer = new HTMLRenderer(this, this.options);
        return renderer.value();
      }
      finalize() {
        this.closeAllNodes();
        return true;
      }
    };
    function source(re2) {
      if (!re2) return null;
      if (typeof re2 === "string") return re2;
      return re2.source;
    }
    function lookahead(re2) {
      return concat("(?=", re2, ")");
    }
    function anyNumberOfTimes(re2) {
      return concat("(?:", re2, ")*");
    }
    function optional(re2) {
      return concat("(?:", re2, ")?");
    }
    function concat(...args) {
      const joined = args.map((x2) => source(x2)).join("");
      return joined;
    }
    function stripOptionsFromArgs(args) {
      const opts = args[args.length - 1];
      if (typeof opts === "object" && opts.constructor === Object) {
        args.splice(args.length - 1, 1);
        return opts;
      } else {
        return {};
      }
    }
    function either(...args) {
      const opts = stripOptionsFromArgs(args);
      const joined = "(" + (opts.capture ? "" : "?:") + args.map((x2) => source(x2)).join("|") + ")";
      return joined;
    }
    function countMatchGroups(re2) {
      return new RegExp(re2.toString() + "|").exec("").length - 1;
    }
    function startsWith(re2, lexeme) {
      const match2 = re2 && re2.exec(lexeme);
      return match2 && match2.index === 0;
    }
    var BACKREF_RE = /\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./;
    function _rewriteBackreferences(regexps, { joinWith }) {
      let numCaptures = 0;
      return regexps.map((regex) => {
        numCaptures += 1;
        const offset = numCaptures;
        let re2 = source(regex);
        let out = "";
        while (re2.length > 0) {
          const match2 = BACKREF_RE.exec(re2);
          if (!match2) {
            out += re2;
            break;
          }
          out += re2.substring(0, match2.index);
          re2 = re2.substring(match2.index + match2[0].length);
          if (match2[0][0] === "\\" && match2[1]) {
            out += "\\" + String(Number(match2[1]) + offset);
          } else {
            out += match2[0];
            if (match2[0] === "(") {
              numCaptures++;
            }
          }
        }
        return out;
      }).map((re2) => `(${re2})`).join(joinWith);
    }
    var MATCH_NOTHING_RE = /\b\B/;
    var IDENT_RE3 = "[a-zA-Z]\\w*";
    var UNDERSCORE_IDENT_RE = "[a-zA-Z_]\\w*";
    var NUMBER_RE = "\\b\\d+(\\.\\d+)?";
    var C_NUMBER_RE = "(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)";
    var BINARY_NUMBER_RE = "\\b(0b[01]+)";
    var RE_STARTERS_RE = "!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~";
    var SHEBANG = (opts = {}) => {
      const beginShebang = /^#![ ]*\//;
      if (opts.binary) {
        opts.begin = concat(
          beginShebang,
          /.*\b/,
          opts.binary,
          /\b.*/
        );
      }
      return inherit$1({
        scope: "meta",
        begin: beginShebang,
        end: /$/,
        relevance: 0,
        /** @type {ModeCallback} */
        "on:begin": (m4, resp) => {
          if (m4.index !== 0) resp.ignoreMatch();
        }
      }, opts);
    };
    var BACKSLASH_ESCAPE = {
      begin: "\\\\[\\s\\S]",
      relevance: 0
    };
    var APOS_STRING_MODE = {
      scope: "string",
      begin: "'",
      end: "'",
      illegal: "\\n",
      contains: [BACKSLASH_ESCAPE]
    };
    var QUOTE_STRING_MODE = {
      scope: "string",
      begin: '"',
      end: '"',
      illegal: "\\n",
      contains: [BACKSLASH_ESCAPE]
    };
    var PHRASAL_WORDS_MODE = {
      begin: /\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/
    };
    var COMMENT = function(begin, end, modeOptions = {}) {
      const mode = inherit$1(
        {
          scope: "comment",
          begin,
          end,
          contains: []
        },
        modeOptions
      );
      mode.contains.push({
        scope: "doctag",
        // hack to avoid the space from being included. the space is necessary to
        // match here to prevent the plain text rule below from gobbling up doctags
        begin: "[ ]*(?=(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):)",
        end: /(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):/,
        excludeBegin: true,
        relevance: 0
      });
      const ENGLISH_WORD = either(
        // list of common 1 and 2 letter words in English
        "I",
        "a",
        "is",
        "so",
        "us",
        "to",
        "at",
        "if",
        "in",
        "it",
        "on",
        // note: this is not an exhaustive list of contractions, just popular ones
        /[A-Za-z]+['](d|ve|re|ll|t|s|n)/,
        // contractions - can't we'd they're let's, etc
        /[A-Za-z]+[-][a-z]+/,
        // `no-way`, etc.
        /[A-Za-z][a-z]{2,}/
        // allow capitalized words at beginning of sentences
      );
      mode.contains.push(
        {
          // TODO: how to include ", (, ) without breaking grammars that use these for
          // comment delimiters?
          // begin: /[ ]+([()"]?([A-Za-z'-]{3,}|is|a|I|so|us|[tT][oO]|at|if|in|it|on)[.]?[()":]?([.][ ]|[ ]|\))){3}/
          // ---
          // this tries to find sequences of 3 english words in a row (without any
          // "programming" type syntax) this gives us a strong signal that we've
          // TRULY found a comment - vs perhaps scanning with the wrong language.
          // It's possible to find something that LOOKS like the start of the
          // comment - but then if there is no readable text - good chance it is a
          // false match and not a comment.
          //
          // for a visual example please see:
          // https://github.com/highlightjs/highlight.js/issues/2827
          begin: concat(
            /[ ]+/,
            // necessary to prevent us gobbling up doctags like /* @author Bob Mcgill */
            "(",
            ENGLISH_WORD,
            /[.]?[:]?([.][ ]|[ ])/,
            "){3}"
          )
          // look for 3 words in a row
        }
      );
      return mode;
    };
    var C_LINE_COMMENT_MODE = COMMENT("//", "$");
    var C_BLOCK_COMMENT_MODE = COMMENT("/\\*", "\\*/");
    var HASH_COMMENT_MODE = COMMENT("#", "$");
    var NUMBER_MODE = {
      scope: "number",
      begin: NUMBER_RE,
      relevance: 0
    };
    var C_NUMBER_MODE = {
      scope: "number",
      begin: C_NUMBER_RE,
      relevance: 0
    };
    var BINARY_NUMBER_MODE = {
      scope: "number",
      begin: BINARY_NUMBER_RE,
      relevance: 0
    };
    var REGEXP_MODE = {
      scope: "regexp",
      begin: /\/(?=[^/\n]*\/)/,
      end: /\/[gimuy]*/,
      contains: [
        BACKSLASH_ESCAPE,
        {
          begin: /\[/,
          end: /\]/,
          relevance: 0,
          contains: [BACKSLASH_ESCAPE]
        }
      ]
    };
    var TITLE_MODE = {
      scope: "title",
      begin: IDENT_RE3,
      relevance: 0
    };
    var UNDERSCORE_TITLE_MODE = {
      scope: "title",
      begin: UNDERSCORE_IDENT_RE,
      relevance: 0
    };
    var METHOD_GUARD = {
      // excludes method names from keyword processing
      begin: "\\.\\s*" + UNDERSCORE_IDENT_RE,
      relevance: 0
    };
    var END_SAME_AS_BEGIN = function(mode) {
      return Object.assign(
        mode,
        {
          /** @type {ModeCallback} */
          "on:begin": (m4, resp) => {
            resp.data._beginMatch = m4[1];
          },
          /** @type {ModeCallback} */
          "on:end": (m4, resp) => {
            if (resp.data._beginMatch !== m4[1]) resp.ignoreMatch();
          }
        }
      );
    };
    var MODES2 = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      APOS_STRING_MODE,
      BACKSLASH_ESCAPE,
      BINARY_NUMBER_MODE,
      BINARY_NUMBER_RE,
      COMMENT,
      C_BLOCK_COMMENT_MODE,
      C_LINE_COMMENT_MODE,
      C_NUMBER_MODE,
      C_NUMBER_RE,
      END_SAME_AS_BEGIN,
      HASH_COMMENT_MODE,
      IDENT_RE: IDENT_RE3,
      MATCH_NOTHING_RE,
      METHOD_GUARD,
      NUMBER_MODE,
      NUMBER_RE,
      PHRASAL_WORDS_MODE,
      QUOTE_STRING_MODE,
      REGEXP_MODE,
      RE_STARTERS_RE,
      SHEBANG,
      TITLE_MODE,
      UNDERSCORE_IDENT_RE,
      UNDERSCORE_TITLE_MODE
    });
    function skipIfHasPrecedingDot(match2, response) {
      const before = match2.input[match2.index - 1];
      if (before === ".") {
        response.ignoreMatch();
      }
    }
    function scopeClassName(mode, _parent) {
      if (mode.className !== void 0) {
        mode.scope = mode.className;
        delete mode.className;
      }
    }
    function beginKeywords(mode, parent) {
      if (!parent) return;
      if (!mode.beginKeywords) return;
      mode.begin = "\\b(" + mode.beginKeywords.split(" ").join("|") + ")(?!\\.)(?=\\b|\\s)";
      mode.__beforeBegin = skipIfHasPrecedingDot;
      mode.keywords = mode.keywords || mode.beginKeywords;
      delete mode.beginKeywords;
      if (mode.relevance === void 0) mode.relevance = 0;
    }
    function compileIllegal(mode, _parent) {
      if (!Array.isArray(mode.illegal)) return;
      mode.illegal = either(...mode.illegal);
    }
    function compileMatch(mode, _parent) {
      if (!mode.match) return;
      if (mode.begin || mode.end) throw new Error("begin & end are not supported with match");
      mode.begin = mode.match;
      delete mode.match;
    }
    function compileRelevance(mode, _parent) {
      if (mode.relevance === void 0) mode.relevance = 1;
    }
    var beforeMatchExt = (mode, parent) => {
      if (!mode.beforeMatch) return;
      if (mode.starts) throw new Error("beforeMatch cannot be used with starts");
      const originalMode = Object.assign({}, mode);
      Object.keys(mode).forEach((key) => {
        delete mode[key];
      });
      mode.keywords = originalMode.keywords;
      mode.begin = concat(originalMode.beforeMatch, lookahead(originalMode.begin));
      mode.starts = {
        relevance: 0,
        contains: [
          Object.assign(originalMode, { endsParent: true })
        ]
      };
      mode.relevance = 0;
      delete originalMode.beforeMatch;
    };
    var COMMON_KEYWORDS = [
      "of",
      "and",
      "for",
      "in",
      "not",
      "or",
      "if",
      "then",
      "parent",
      // common variable name
      "list",
      // common variable name
      "value"
      // common variable name
    ];
    var DEFAULT_KEYWORD_SCOPE = "keyword";
    function compileKeywords(rawKeywords, caseInsensitive, scopeName = DEFAULT_KEYWORD_SCOPE) {
      const compiledKeywords = /* @__PURE__ */ Object.create(null);
      if (typeof rawKeywords === "string") {
        compileList(scopeName, rawKeywords.split(" "));
      } else if (Array.isArray(rawKeywords)) {
        compileList(scopeName, rawKeywords);
      } else {
        Object.keys(rawKeywords).forEach(function(scopeName2) {
          Object.assign(
            compiledKeywords,
            compileKeywords(rawKeywords[scopeName2], caseInsensitive, scopeName2)
          );
        });
      }
      return compiledKeywords;
      function compileList(scopeName2, keywordList) {
        if (caseInsensitive) {
          keywordList = keywordList.map((x2) => x2.toLowerCase());
        }
        keywordList.forEach(function(keyword) {
          const pair = keyword.split("|");
          compiledKeywords[pair[0]] = [scopeName2, scoreForKeyword(pair[0], pair[1])];
        });
      }
    }
    function scoreForKeyword(keyword, providedScore) {
      if (providedScore) {
        return Number(providedScore);
      }
      return commonKeyword(keyword) ? 0 : 1;
    }
    function commonKeyword(keyword) {
      return COMMON_KEYWORDS.includes(keyword.toLowerCase());
    }
    var seenDeprecations = {};
    var error = (message) => {
      console.error(message);
    };
    var warn2 = (message, ...args) => {
      console.log(`WARN: ${message}`, ...args);
    };
    var deprecated2 = (version6, message) => {
      if (seenDeprecations[`${version6}/${message}`]) return;
      console.log(`Deprecated as of ${version6}. ${message}`);
      seenDeprecations[`${version6}/${message}`] = true;
    };
    var MultiClassError = new Error();
    function remapScopeNames(mode, regexes, { key }) {
      let offset = 0;
      const scopeNames = mode[key];
      const emit = {};
      const positions = {};
      for (let i7 = 1; i7 <= regexes.length; i7++) {
        positions[i7 + offset] = scopeNames[i7];
        emit[i7 + offset] = true;
        offset += countMatchGroups(regexes[i7 - 1]);
      }
      mode[key] = positions;
      mode[key]._emit = emit;
      mode[key]._multi = true;
    }
    function beginMultiClass(mode) {
      if (!Array.isArray(mode.begin)) return;
      if (mode.skip || mode.excludeBegin || mode.returnBegin) {
        error("skip, excludeBegin, returnBegin not compatible with beginScope: {}");
        throw MultiClassError;
      }
      if (typeof mode.beginScope !== "object" || mode.beginScope === null) {
        error("beginScope must be object");
        throw MultiClassError;
      }
      remapScopeNames(mode, mode.begin, { key: "beginScope" });
      mode.begin = _rewriteBackreferences(mode.begin, { joinWith: "" });
    }
    function endMultiClass(mode) {
      if (!Array.isArray(mode.end)) return;
      if (mode.skip || mode.excludeEnd || mode.returnEnd) {
        error("skip, excludeEnd, returnEnd not compatible with endScope: {}");
        throw MultiClassError;
      }
      if (typeof mode.endScope !== "object" || mode.endScope === null) {
        error("endScope must be object");
        throw MultiClassError;
      }
      remapScopeNames(mode, mode.end, { key: "endScope" });
      mode.end = _rewriteBackreferences(mode.end, { joinWith: "" });
    }
    function scopeSugar(mode) {
      if (mode.scope && typeof mode.scope === "object" && mode.scope !== null) {
        mode.beginScope = mode.scope;
        delete mode.scope;
      }
    }
    function MultiClass(mode) {
      scopeSugar(mode);
      if (typeof mode.beginScope === "string") {
        mode.beginScope = { _wrap: mode.beginScope };
      }
      if (typeof mode.endScope === "string") {
        mode.endScope = { _wrap: mode.endScope };
      }
      beginMultiClass(mode);
      endMultiClass(mode);
    }
    function compileLanguage(language) {
      function langRe(value, global2) {
        return new RegExp(
          source(value),
          "m" + (language.case_insensitive ? "i" : "") + (language.unicodeRegex ? "u" : "") + (global2 ? "g" : "")
        );
      }
      class MultiRegex {
        constructor() {
          this.matchIndexes = {};
          this.regexes = [];
          this.matchAt = 1;
          this.position = 0;
        }
        // @ts-ignore
        addRule(re2, opts) {
          opts.position = this.position++;
          this.matchIndexes[this.matchAt] = opts;
          this.regexes.push([opts, re2]);
          this.matchAt += countMatchGroups(re2) + 1;
        }
        compile() {
          if (this.regexes.length === 0) {
            this.exec = () => null;
          }
          const terminators = this.regexes.map((el) => el[1]);
          this.matcherRe = langRe(_rewriteBackreferences(terminators, { joinWith: "|" }), true);
          this.lastIndex = 0;
        }
        /** @param {string} s */
        exec(s6) {
          this.matcherRe.lastIndex = this.lastIndex;
          const match2 = this.matcherRe.exec(s6);
          if (!match2) {
            return null;
          }
          const i7 = match2.findIndex((el, i8) => i8 > 0 && el !== void 0);
          const matchData = this.matchIndexes[i7];
          match2.splice(0, i7);
          return Object.assign(match2, matchData);
        }
      }
      class ResumableMultiRegex {
        constructor() {
          this.rules = [];
          this.multiRegexes = [];
          this.count = 0;
          this.lastIndex = 0;
          this.regexIndex = 0;
        }
        // @ts-ignore
        getMatcher(index) {
          if (this.multiRegexes[index]) return this.multiRegexes[index];
          const matcher = new MultiRegex();
          this.rules.slice(index).forEach(([re2, opts]) => matcher.addRule(re2, opts));
          matcher.compile();
          this.multiRegexes[index] = matcher;
          return matcher;
        }
        resumingScanAtSamePosition() {
          return this.regexIndex !== 0;
        }
        considerAll() {
          this.regexIndex = 0;
        }
        // @ts-ignore
        addRule(re2, opts) {
          this.rules.push([re2, opts]);
          if (opts.type === "begin") this.count++;
        }
        /** @param {string} s */
        exec(s6) {
          const m4 = this.getMatcher(this.regexIndex);
          m4.lastIndex = this.lastIndex;
          let result = m4.exec(s6);
          if (this.resumingScanAtSamePosition()) {
            if (result && result.index === this.lastIndex) ;
            else {
              const m22 = this.getMatcher(0);
              m22.lastIndex = this.lastIndex + 1;
              result = m22.exec(s6);
            }
          }
          if (result) {
            this.regexIndex += result.position + 1;
            if (this.regexIndex === this.count) {
              this.considerAll();
            }
          }
          return result;
        }
      }
      function buildModeRegex(mode) {
        const mm = new ResumableMultiRegex();
        mode.contains.forEach((term) => mm.addRule(term.begin, { rule: term, type: "begin" }));
        if (mode.terminatorEnd) {
          mm.addRule(mode.terminatorEnd, { type: "end" });
        }
        if (mode.illegal) {
          mm.addRule(mode.illegal, { type: "illegal" });
        }
        return mm;
      }
      function compileMode(mode, parent) {
        const cmode = (
          /** @type CompiledMode */
          mode
        );
        if (mode.isCompiled) return cmode;
        [
          scopeClassName,
          // do this early so compiler extensions generally don't have to worry about
          // the distinction between match/begin
          compileMatch,
          MultiClass,
          beforeMatchExt
        ].forEach((ext2) => ext2(mode, parent));
        language.compilerExtensions.forEach((ext2) => ext2(mode, parent));
        mode.__beforeBegin = null;
        [
          beginKeywords,
          // do this later so compiler extensions that come earlier have access to the
          // raw array if they wanted to perhaps manipulate it, etc.
          compileIllegal,
          // default to 1 relevance if not specified
          compileRelevance
        ].forEach((ext2) => ext2(mode, parent));
        mode.isCompiled = true;
        let keywordPattern = null;
        if (typeof mode.keywords === "object" && mode.keywords.$pattern) {
          mode.keywords = Object.assign({}, mode.keywords);
          keywordPattern = mode.keywords.$pattern;
          delete mode.keywords.$pattern;
        }
        keywordPattern = keywordPattern || /\w+/;
        if (mode.keywords) {
          mode.keywords = compileKeywords(mode.keywords, language.case_insensitive);
        }
        cmode.keywordPatternRe = langRe(keywordPattern, true);
        if (parent) {
          if (!mode.begin) mode.begin = /\B|\b/;
          cmode.beginRe = langRe(cmode.begin);
          if (!mode.end && !mode.endsWithParent) mode.end = /\B|\b/;
          if (mode.end) cmode.endRe = langRe(cmode.end);
          cmode.terminatorEnd = source(cmode.end) || "";
          if (mode.endsWithParent && parent.terminatorEnd) {
            cmode.terminatorEnd += (mode.end ? "|" : "") + parent.terminatorEnd;
          }
        }
        if (mode.illegal) cmode.illegalRe = langRe(
          /** @type {RegExp | string} */
          mode.illegal
        );
        if (!mode.contains) mode.contains = [];
        mode.contains = [].concat(...mode.contains.map(function(c6) {
          return expandOrCloneMode(c6 === "self" ? mode : c6);
        }));
        mode.contains.forEach(function(c6) {
          compileMode(
            /** @type Mode */
            c6,
            cmode
          );
        });
        if (mode.starts) {
          compileMode(mode.starts, parent);
        }
        cmode.matcher = buildModeRegex(cmode);
        return cmode;
      }
      if (!language.compilerExtensions) language.compilerExtensions = [];
      if (language.contains && language.contains.includes("self")) {
        throw new Error("ERR: contains `self` is not supported at the top-level of a language.  See documentation.");
      }
      language.classNameAliases = inherit$1(language.classNameAliases || {});
      return compileMode(
        /** @type Mode */
        language
      );
    }
    function dependencyOnParent(mode) {
      if (!mode) return false;
      return mode.endsWithParent || dependencyOnParent(mode.starts);
    }
    function expandOrCloneMode(mode) {
      if (mode.variants && !mode.cachedVariants) {
        mode.cachedVariants = mode.variants.map(function(variant) {
          return inherit$1(mode, { variants: null }, variant);
        });
      }
      if (mode.cachedVariants) {
        return mode.cachedVariants;
      }
      if (dependencyOnParent(mode)) {
        return inherit$1(mode, { starts: mode.starts ? inherit$1(mode.starts) : null });
      }
      if (Object.isFrozen(mode)) {
        return inherit$1(mode);
      }
      return mode;
    }
    var version5 = "11.11.1";
    var HTMLInjectionError = class extends Error {
      constructor(reason, html) {
        super(reason);
        this.name = "HTMLInjectionError";
        this.html = html;
      }
    };
    var escape4 = escapeHTML;
    var inherit = inherit$1;
    var NO_MATCH = Symbol("nomatch");
    var MAX_KEYWORD_HITS = 7;
    var HLJS = function(hljs5) {
      const languages = /* @__PURE__ */ Object.create(null);
      const aliases = /* @__PURE__ */ Object.create(null);
      const plugins2 = [];
      let SAFE_MODE = true;
      const LANGUAGE_NOT_FOUND = "Could not find the language '{}', did you forget to load/include a language module?";
      const PLAINTEXT_LANGUAGE = { disableAutodetect: true, name: "Plain text", contains: [] };
      let options = {
        ignoreUnescapedHTML: false,
        throwUnescapedHTML: false,
        noHighlightRe: /^(no-?highlight)$/i,
        languageDetectRe: /\blang(?:uage)?-([\w-]+)\b/i,
        classPrefix: "hljs-",
        cssSelector: "pre code",
        languages: null,
        // beta configuration options, subject to change, welcome to discuss
        // https://github.com/highlightjs/highlight.js/issues/1086
        __emitter: TokenTreeEmitter
      };
      function shouldNotHighlight(languageName) {
        return options.noHighlightRe.test(languageName);
      }
      function blockLanguage(block) {
        let classes = block.className + " ";
        classes += block.parentNode ? block.parentNode.className : "";
        const match2 = options.languageDetectRe.exec(classes);
        if (match2) {
          const language = getLanguage(match2[1]);
          if (!language) {
            warn2(LANGUAGE_NOT_FOUND.replace("{}", match2[1]));
            warn2("Falling back to no-highlight mode for this block.", block);
          }
          return language ? match2[1] : "no-highlight";
        }
        return classes.split(/\s+/).find((_class) => shouldNotHighlight(_class) || getLanguage(_class));
      }
      function highlight2(codeOrLanguageName, optionsOrCode, ignoreIllegals) {
        let code = "";
        let languageName = "";
        if (typeof optionsOrCode === "object") {
          code = codeOrLanguageName;
          ignoreIllegals = optionsOrCode.ignoreIllegals;
          languageName = optionsOrCode.language;
        } else {
          deprecated2("10.7.0", "highlight(lang, code, ...args) has been deprecated.");
          deprecated2("10.7.0", "Please use highlight(code, options) instead.\nhttps://github.com/highlightjs/highlight.js/issues/2277");
          languageName = codeOrLanguageName;
          code = optionsOrCode;
        }
        if (ignoreIllegals === void 0) {
          ignoreIllegals = true;
        }
        const context = {
          code,
          language: languageName
        };
        fire("before:highlight", context);
        const result = context.result ? context.result : _highlight(context.language, context.code, ignoreIllegals);
        result.code = context.code;
        fire("after:highlight", result);
        return result;
      }
      function _highlight(languageName, codeToHighlight, ignoreIllegals, continuation) {
        const keywordHits = /* @__PURE__ */ Object.create(null);
        function keywordData(mode, matchText) {
          return mode.keywords[matchText];
        }
        function processKeywords() {
          if (!top.keywords) {
            emitter.addText(modeBuffer);
            return;
          }
          let lastIndex = 0;
          top.keywordPatternRe.lastIndex = 0;
          let match2 = top.keywordPatternRe.exec(modeBuffer);
          let buf = "";
          while (match2) {
            buf += modeBuffer.substring(lastIndex, match2.index);
            const word = language.case_insensitive ? match2[0].toLowerCase() : match2[0];
            const data = keywordData(top, word);
            if (data) {
              const [kind, keywordRelevance] = data;
              emitter.addText(buf);
              buf = "";
              keywordHits[word] = (keywordHits[word] || 0) + 1;
              if (keywordHits[word] <= MAX_KEYWORD_HITS) relevance += keywordRelevance;
              if (kind.startsWith("_")) {
                buf += match2[0];
              } else {
                const cssClass = language.classNameAliases[kind] || kind;
                emitKeyword(match2[0], cssClass);
              }
            } else {
              buf += match2[0];
            }
            lastIndex = top.keywordPatternRe.lastIndex;
            match2 = top.keywordPatternRe.exec(modeBuffer);
          }
          buf += modeBuffer.substring(lastIndex);
          emitter.addText(buf);
        }
        function processSubLanguage() {
          if (modeBuffer === "") return;
          let result2 = null;
          if (typeof top.subLanguage === "string") {
            if (!languages[top.subLanguage]) {
              emitter.addText(modeBuffer);
              return;
            }
            result2 = _highlight(top.subLanguage, modeBuffer, true, continuations[top.subLanguage]);
            continuations[top.subLanguage] = /** @type {CompiledMode} */
            result2._top;
          } else {
            result2 = highlightAuto(modeBuffer, top.subLanguage.length ? top.subLanguage : null);
          }
          if (top.relevance > 0) {
            relevance += result2.relevance;
          }
          emitter.__addSublanguage(result2._emitter, result2.language);
        }
        function processBuffer() {
          if (top.subLanguage != null) {
            processSubLanguage();
          } else {
            processKeywords();
          }
          modeBuffer = "";
        }
        function emitKeyword(keyword, scope) {
          if (keyword === "") return;
          emitter.startScope(scope);
          emitter.addText(keyword);
          emitter.endScope();
        }
        function emitMultiClass(scope, match2) {
          let i7 = 1;
          const max = match2.length - 1;
          while (i7 <= max) {
            if (!scope._emit[i7]) {
              i7++;
              continue;
            }
            const klass = language.classNameAliases[scope[i7]] || scope[i7];
            const text3 = match2[i7];
            if (klass) {
              emitKeyword(text3, klass);
            } else {
              modeBuffer = text3;
              processKeywords();
              modeBuffer = "";
            }
            i7++;
          }
        }
        function startNewMode(mode, match2) {
          if (mode.scope && typeof mode.scope === "string") {
            emitter.openNode(language.classNameAliases[mode.scope] || mode.scope);
          }
          if (mode.beginScope) {
            if (mode.beginScope._wrap) {
              emitKeyword(modeBuffer, language.classNameAliases[mode.beginScope._wrap] || mode.beginScope._wrap);
              modeBuffer = "";
            } else if (mode.beginScope._multi) {
              emitMultiClass(mode.beginScope, match2);
              modeBuffer = "";
            }
          }
          top = Object.create(mode, { parent: { value: top } });
          return top;
        }
        function endOfMode(mode, match2, matchPlusRemainder) {
          let matched = startsWith(mode.endRe, matchPlusRemainder);
          if (matched) {
            if (mode["on:end"]) {
              const resp = new Response3(mode);
              mode["on:end"](match2, resp);
              if (resp.isMatchIgnored) matched = false;
            }
            if (matched) {
              while (mode.endsParent && mode.parent) {
                mode = mode.parent;
              }
              return mode;
            }
          }
          if (mode.endsWithParent) {
            return endOfMode(mode.parent, match2, matchPlusRemainder);
          }
        }
        function doIgnore(lexeme) {
          if (top.matcher.regexIndex === 0) {
            modeBuffer += lexeme[0];
            return 1;
          } else {
            resumeScanAtSamePosition = true;
            return 0;
          }
        }
        function doBeginMatch(match2) {
          const lexeme = match2[0];
          const newMode = match2.rule;
          const resp = new Response3(newMode);
          const beforeCallbacks = [newMode.__beforeBegin, newMode["on:begin"]];
          for (const cb of beforeCallbacks) {
            if (!cb) continue;
            cb(match2, resp);
            if (resp.isMatchIgnored) return doIgnore(lexeme);
          }
          if (newMode.skip) {
            modeBuffer += lexeme;
          } else {
            if (newMode.excludeBegin) {
              modeBuffer += lexeme;
            }
            processBuffer();
            if (!newMode.returnBegin && !newMode.excludeBegin) {
              modeBuffer = lexeme;
            }
          }
          startNewMode(newMode, match2);
          return newMode.returnBegin ? 0 : lexeme.length;
        }
        function doEndMatch(match2) {
          const lexeme = match2[0];
          const matchPlusRemainder = codeToHighlight.substring(match2.index);
          const endMode = endOfMode(top, match2, matchPlusRemainder);
          if (!endMode) {
            return NO_MATCH;
          }
          const origin = top;
          if (top.endScope && top.endScope._wrap) {
            processBuffer();
            emitKeyword(lexeme, top.endScope._wrap);
          } else if (top.endScope && top.endScope._multi) {
            processBuffer();
            emitMultiClass(top.endScope, match2);
          } else if (origin.skip) {
            modeBuffer += lexeme;
          } else {
            if (!(origin.returnEnd || origin.excludeEnd)) {
              modeBuffer += lexeme;
            }
            processBuffer();
            if (origin.excludeEnd) {
              modeBuffer = lexeme;
            }
          }
          do {
            if (top.scope) {
              emitter.closeNode();
            }
            if (!top.skip && !top.subLanguage) {
              relevance += top.relevance;
            }
            top = top.parent;
          } while (top !== endMode.parent);
          if (endMode.starts) {
            startNewMode(endMode.starts, match2);
          }
          return origin.returnEnd ? 0 : lexeme.length;
        }
        function processContinuations() {
          const list = [];
          for (let current2 = top; current2 !== language; current2 = current2.parent) {
            if (current2.scope) {
              list.unshift(current2.scope);
            }
          }
          list.forEach((item) => emitter.openNode(item));
        }
        let lastMatch = {};
        function processLexeme(textBeforeMatch, match2) {
          const lexeme = match2 && match2[0];
          modeBuffer += textBeforeMatch;
          if (lexeme == null) {
            processBuffer();
            return 0;
          }
          if (lastMatch.type === "begin" && match2.type === "end" && lastMatch.index === match2.index && lexeme === "") {
            modeBuffer += codeToHighlight.slice(match2.index, match2.index + 1);
            if (!SAFE_MODE) {
              const err = new Error(`0 width match regex (${languageName})`);
              err.languageName = languageName;
              err.badRule = lastMatch.rule;
              throw err;
            }
            return 1;
          }
          lastMatch = match2;
          if (match2.type === "begin") {
            return doBeginMatch(match2);
          } else if (match2.type === "illegal" && !ignoreIllegals) {
            const err = new Error('Illegal lexeme "' + lexeme + '" for mode "' + (top.scope || "<unnamed>") + '"');
            err.mode = top;
            throw err;
          } else if (match2.type === "end") {
            const processed = doEndMatch(match2);
            if (processed !== NO_MATCH) {
              return processed;
            }
          }
          if (match2.type === "illegal" && lexeme === "") {
            modeBuffer += "\n";
            return 1;
          }
          if (iterations > 1e5 && iterations > match2.index * 3) {
            const err = new Error("potential infinite loop, way more iterations than matches");
            throw err;
          }
          modeBuffer += lexeme;
          return lexeme.length;
        }
        const language = getLanguage(languageName);
        if (!language) {
          error(LANGUAGE_NOT_FOUND.replace("{}", languageName));
          throw new Error('Unknown language: "' + languageName + '"');
        }
        const md = compileLanguage(language);
        let result = "";
        let top = continuation || md;
        const continuations = {};
        const emitter = new options.__emitter(options);
        processContinuations();
        let modeBuffer = "";
        let relevance = 0;
        let index = 0;
        let iterations = 0;
        let resumeScanAtSamePosition = false;
        try {
          if (!language.__emitTokens) {
            top.matcher.considerAll();
            for (; ; ) {
              iterations++;
              if (resumeScanAtSamePosition) {
                resumeScanAtSamePosition = false;
              } else {
                top.matcher.considerAll();
              }
              top.matcher.lastIndex = index;
              const match2 = top.matcher.exec(codeToHighlight);
              if (!match2) break;
              const beforeMatch = codeToHighlight.substring(index, match2.index);
              const processedCount = processLexeme(beforeMatch, match2);
              index = match2.index + processedCount;
            }
            processLexeme(codeToHighlight.substring(index));
          } else {
            language.__emitTokens(codeToHighlight, emitter);
          }
          emitter.finalize();
          result = emitter.toHTML();
          return {
            language: languageName,
            value: result,
            relevance,
            illegal: false,
            _emitter: emitter,
            _top: top
          };
        } catch (err) {
          if (err.message && err.message.includes("Illegal")) {
            return {
              language: languageName,
              value: escape4(codeToHighlight),
              illegal: true,
              relevance: 0,
              _illegalBy: {
                message: err.message,
                index,
                context: codeToHighlight.slice(index - 100, index + 100),
                mode: err.mode,
                resultSoFar: result
              },
              _emitter: emitter
            };
          } else if (SAFE_MODE) {
            return {
              language: languageName,
              value: escape4(codeToHighlight),
              illegal: false,
              relevance: 0,
              errorRaised: err,
              _emitter: emitter,
              _top: top
            };
          } else {
            throw err;
          }
        }
      }
      function justTextHighlightResult(code) {
        const result = {
          value: escape4(code),
          illegal: false,
          relevance: 0,
          _top: PLAINTEXT_LANGUAGE,
          _emitter: new options.__emitter(options)
        };
        result._emitter.addText(code);
        return result;
      }
      function highlightAuto(code, languageSubset) {
        languageSubset = languageSubset || options.languages || Object.keys(languages);
        const plaintext = justTextHighlightResult(code);
        const results = languageSubset.filter(getLanguage).filter(autoDetection).map(
          (name) => _highlight(name, code, false)
        );
        results.unshift(plaintext);
        const sorted = results.sort((a3, b4) => {
          if (a3.relevance !== b4.relevance) return b4.relevance - a3.relevance;
          if (a3.language && b4.language) {
            if (getLanguage(a3.language).supersetOf === b4.language) {
              return 1;
            } else if (getLanguage(b4.language).supersetOf === a3.language) {
              return -1;
            }
          }
          return 0;
        });
        const [best, secondBest] = sorted;
        const result = best;
        result.secondBest = secondBest;
        return result;
      }
      function updateClassName(element, currentLang, resultLang) {
        const language = currentLang && aliases[currentLang] || resultLang;
        element.classList.add("hljs");
        element.classList.add(`language-${language}`);
      }
      function highlightElement(element) {
        let node = null;
        const language = blockLanguage(element);
        if (shouldNotHighlight(language)) return;
        fire(
          "before:highlightElement",
          { el: element, language }
        );
        if (element.dataset.highlighted) {
          console.log("Element previously highlighted. To highlight again, first unset `dataset.highlighted`.", element);
          return;
        }
        if (element.children.length > 0) {
          if (!options.ignoreUnescapedHTML) {
            console.warn("One of your code blocks includes unescaped HTML. This is a potentially serious security risk.");
            console.warn("https://github.com/highlightjs/highlight.js/wiki/security");
            console.warn("The element with unescaped HTML:");
            console.warn(element);
          }
          if (options.throwUnescapedHTML) {
            const err = new HTMLInjectionError(
              "One of your code blocks includes unescaped HTML.",
              element.innerHTML
            );
            throw err;
          }
        }
        node = element;
        const text3 = node.textContent;
        const result = language ? highlight2(text3, { language, ignoreIllegals: true }) : highlightAuto(text3);
        element.innerHTML = result.value;
        element.dataset.highlighted = "yes";
        updateClassName(element, language, result.language);
        element.result = {
          language: result.language,
          // TODO: remove with version 11.0
          re: result.relevance,
          relevance: result.relevance
        };
        if (result.secondBest) {
          element.secondBest = {
            language: result.secondBest.language,
            relevance: result.secondBest.relevance
          };
        }
        fire("after:highlightElement", { el: element, result, text: text3 });
      }
      function configure(userOptions) {
        options = inherit(options, userOptions);
      }
      const initHighlighting = () => {
        highlightAll();
        deprecated2("10.6.0", "initHighlighting() deprecated.  Use highlightAll() now.");
      };
      function initHighlightingOnLoad() {
        highlightAll();
        deprecated2("10.6.0", "initHighlightingOnLoad() deprecated.  Use highlightAll() now.");
      }
      let wantsHighlight = false;
      function highlightAll() {
        function boot() {
          highlightAll();
        }
        if (document.readyState === "loading") {
          if (!wantsHighlight) {
            window.addEventListener("DOMContentLoaded", boot, false);
          }
          wantsHighlight = true;
          return;
        }
        const blocks = document.querySelectorAll(options.cssSelector);
        blocks.forEach(highlightElement);
      }
      function registerLanguage(languageName, languageDefinition) {
        let lang = null;
        try {
          lang = languageDefinition(hljs5);
        } catch (error$1) {
          error("Language definition for '{}' could not be registered.".replace("{}", languageName));
          if (!SAFE_MODE) {
            throw error$1;
          } else {
            error(error$1);
          }
          lang = PLAINTEXT_LANGUAGE;
        }
        if (!lang.name) lang.name = languageName;
        languages[languageName] = lang;
        lang.rawDefinition = languageDefinition.bind(null, hljs5);
        if (lang.aliases) {
          registerAliases(lang.aliases, { languageName });
        }
      }
      function unregisterLanguage(languageName) {
        delete languages[languageName];
        for (const alias of Object.keys(aliases)) {
          if (aliases[alias] === languageName) {
            delete aliases[alias];
          }
        }
      }
      function listLanguages() {
        return Object.keys(languages);
      }
      function getLanguage(name) {
        name = (name || "").toLowerCase();
        return languages[name] || languages[aliases[name]];
      }
      function registerAliases(aliasList, { languageName }) {
        if (typeof aliasList === "string") {
          aliasList = [aliasList];
        }
        aliasList.forEach((alias) => {
          aliases[alias.toLowerCase()] = languageName;
        });
      }
      function autoDetection(name) {
        const lang = getLanguage(name);
        return lang && !lang.disableAutodetect;
      }
      function upgradePluginAPI(plugin) {
        if (plugin["before:highlightBlock"] && !plugin["before:highlightElement"]) {
          plugin["before:highlightElement"] = (data) => {
            plugin["before:highlightBlock"](
              Object.assign({ block: data.el }, data)
            );
          };
        }
        if (plugin["after:highlightBlock"] && !plugin["after:highlightElement"]) {
          plugin["after:highlightElement"] = (data) => {
            plugin["after:highlightBlock"](
              Object.assign({ block: data.el }, data)
            );
          };
        }
      }
      function addPlugin(plugin) {
        upgradePluginAPI(plugin);
        plugins2.push(plugin);
      }
      function removePlugin(plugin) {
        const index = plugins2.indexOf(plugin);
        if (index !== -1) {
          plugins2.splice(index, 1);
        }
      }
      function fire(event, args) {
        const cb = event;
        plugins2.forEach(function(plugin) {
          if (plugin[cb]) {
            plugin[cb](args);
          }
        });
      }
      function deprecateHighlightBlock(el) {
        deprecated2("10.7.0", "highlightBlock will be removed entirely in v12.0");
        deprecated2("10.7.0", "Please use highlightElement now.");
        return highlightElement(el);
      }
      Object.assign(hljs5, {
        highlight: highlight2,
        highlightAuto,
        highlightAll,
        highlightElement,
        // TODO: Remove with v12 API
        highlightBlock: deprecateHighlightBlock,
        configure,
        initHighlighting,
        initHighlightingOnLoad,
        registerLanguage,
        unregisterLanguage,
        listLanguages,
        getLanguage,
        registerAliases,
        autoDetection,
        inherit,
        addPlugin,
        removePlugin
      });
      hljs5.debugMode = function() {
        SAFE_MODE = false;
      };
      hljs5.safeMode = function() {
        SAFE_MODE = true;
      };
      hljs5.versionString = version5;
      hljs5.regex = {
        concat,
        lookahead,
        either,
        optional,
        anyNumberOfTimes
      };
      for (const key in MODES2) {
        if (typeof MODES2[key] === "object") {
          deepFreeze(MODES2[key]);
        }
      }
      Object.assign(hljs5, MODES2);
      return hljs5;
    };
    var highlight = HLJS({});
    highlight.newInstance = () => HLJS({});
    module.exports = highlight;
    highlight.HighlightJS = highlight;
    highlight.default = highlight;
  }
});

// src/debug.ts
init_process_shim();

// ../mini-lit/dist/Button.js
init_process_shim();

// ../mini-lit/dist/mini.js
init_process_shim();

// node_modules/lit/index.js
init_process_shim();

// node_modules/@lit/reactive-element/reactive-element.js
init_process_shim();

// node_modules/@lit/reactive-element/css-tag.js
init_process_shim();
var t = globalThis;
var e = t.ShadowRoot && (void 0 === t.ShadyCSS || t.ShadyCSS.nativeShadow) && "adoptedStyleSheets" in Document.prototype && "replace" in CSSStyleSheet.prototype;
var s = Symbol();
var o = /* @__PURE__ */ new WeakMap();
var n = class {
  constructor(t6, e9, o9) {
    if (this._$cssResult$ = true, o9 !== s) throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");
    this.cssText = t6, this.t = e9;
  }
  get styleSheet() {
    let t6 = this.o;
    const s6 = this.t;
    if (e && void 0 === t6) {
      const e9 = void 0 !== s6 && 1 === s6.length;
      e9 && (t6 = o.get(s6)), void 0 === t6 && ((this.o = t6 = new CSSStyleSheet()).replaceSync(this.cssText), e9 && o.set(s6, t6));
    }
    return t6;
  }
  toString() {
    return this.cssText;
  }
};
var r = (t6) => new n("string" == typeof t6 ? t6 : t6 + "", void 0, s);
var S = (s6, o9) => {
  if (e) s6.adoptedStyleSheets = o9.map((t6) => t6 instanceof CSSStyleSheet ? t6 : t6.styleSheet);
  else for (const e9 of o9) {
    const o10 = document.createElement("style"), n7 = t.litNonce;
    void 0 !== n7 && o10.setAttribute("nonce", n7), o10.textContent = e9.cssText, s6.appendChild(o10);
  }
};
var c = e ? (t6) => t6 : (t6) => t6 instanceof CSSStyleSheet ? ((t7) => {
  let e9 = "";
  for (const s6 of t7.cssRules) e9 += s6.cssText;
  return r(e9);
})(t6) : t6;

// node_modules/@lit/reactive-element/reactive-element.js
var { is: i2, defineProperty: e2, getOwnPropertyDescriptor: h, getOwnPropertyNames: r2, getOwnPropertySymbols: o2, getPrototypeOf: n2 } = Object;
var a = globalThis;
var c2 = a.trustedTypes;
var l = c2 ? c2.emptyScript : "";
var p = a.reactiveElementPolyfillSupport;
var d = (t6, s6) => t6;
var u = { toAttribute(t6, s6) {
  switch (s6) {
    case Boolean:
      t6 = t6 ? l : null;
      break;
    case Object:
    case Array:
      t6 = null == t6 ? t6 : JSON.stringify(t6);
  }
  return t6;
}, fromAttribute(t6, s6) {
  let i7 = t6;
  switch (s6) {
    case Boolean:
      i7 = null !== t6;
      break;
    case Number:
      i7 = null === t6 ? null : Number(t6);
      break;
    case Object:
    case Array:
      try {
        i7 = JSON.parse(t6);
      } catch (t7) {
        i7 = null;
      }
  }
  return i7;
} };
var f = (t6, s6) => !i2(t6, s6);
var b = { attribute: true, type: String, converter: u, reflect: false, useDefault: false, hasChanged: f };
Symbol.metadata ??= Symbol("metadata"), a.litPropertyMetadata ??= /* @__PURE__ */ new WeakMap();
var y = class extends HTMLElement {
  static addInitializer(t6) {
    this._$Ei(), (this.l ??= []).push(t6);
  }
  static get observedAttributes() {
    return this.finalize(), this._$Eh && [...this._$Eh.keys()];
  }
  static createProperty(t6, s6 = b) {
    if (s6.state && (s6.attribute = false), this._$Ei(), this.prototype.hasOwnProperty(t6) && ((s6 = Object.create(s6)).wrapped = true), this.elementProperties.set(t6, s6), !s6.noAccessor) {
      const i7 = Symbol(), h7 = this.getPropertyDescriptor(t6, i7, s6);
      void 0 !== h7 && e2(this.prototype, t6, h7);
    }
  }
  static getPropertyDescriptor(t6, s6, i7) {
    const { get: e9, set: r8 } = h(this.prototype, t6) ?? { get() {
      return this[s6];
    }, set(t7) {
      this[s6] = t7;
    } };
    return { get: e9, set(s7) {
      const h7 = e9?.call(this);
      r8?.call(this, s7), this.requestUpdate(t6, h7, i7);
    }, configurable: true, enumerable: true };
  }
  static getPropertyOptions(t6) {
    return this.elementProperties.get(t6) ?? b;
  }
  static _$Ei() {
    if (this.hasOwnProperty(d("elementProperties"))) return;
    const t6 = n2(this);
    t6.finalize(), void 0 !== t6.l && (this.l = [...t6.l]), this.elementProperties = new Map(t6.elementProperties);
  }
  static finalize() {
    if (this.hasOwnProperty(d("finalized"))) return;
    if (this.finalized = true, this._$Ei(), this.hasOwnProperty(d("properties"))) {
      const t7 = this.properties, s6 = [...r2(t7), ...o2(t7)];
      for (const i7 of s6) this.createProperty(i7, t7[i7]);
    }
    const t6 = this[Symbol.metadata];
    if (null !== t6) {
      const s6 = litPropertyMetadata.get(t6);
      if (void 0 !== s6) for (const [t7, i7] of s6) this.elementProperties.set(t7, i7);
    }
    this._$Eh = /* @__PURE__ */ new Map();
    for (const [t7, s6] of this.elementProperties) {
      const i7 = this._$Eu(t7, s6);
      void 0 !== i7 && this._$Eh.set(i7, t7);
    }
    this.elementStyles = this.finalizeStyles(this.styles);
  }
  static finalizeStyles(s6) {
    const i7 = [];
    if (Array.isArray(s6)) {
      const e9 = new Set(s6.flat(1 / 0).reverse());
      for (const s7 of e9) i7.unshift(c(s7));
    } else void 0 !== s6 && i7.push(c(s6));
    return i7;
  }
  static _$Eu(t6, s6) {
    const i7 = s6.attribute;
    return false === i7 ? void 0 : "string" == typeof i7 ? i7 : "string" == typeof t6 ? t6.toLowerCase() : void 0;
  }
  constructor() {
    super(), this._$Ep = void 0, this.isUpdatePending = false, this.hasUpdated = false, this._$Em = null, this._$Ev();
  }
  _$Ev() {
    this._$ES = new Promise((t6) => this.enableUpdating = t6), this._$AL = /* @__PURE__ */ new Map(), this._$E_(), this.requestUpdate(), this.constructor.l?.forEach((t6) => t6(this));
  }
  addController(t6) {
    (this._$EO ??= /* @__PURE__ */ new Set()).add(t6), void 0 !== this.renderRoot && this.isConnected && t6.hostConnected?.();
  }
  removeController(t6) {
    this._$EO?.delete(t6);
  }
  _$E_() {
    const t6 = /* @__PURE__ */ new Map(), s6 = this.constructor.elementProperties;
    for (const i7 of s6.keys()) this.hasOwnProperty(i7) && (t6.set(i7, this[i7]), delete this[i7]);
    t6.size > 0 && (this._$Ep = t6);
  }
  createRenderRoot() {
    const t6 = this.shadowRoot ?? this.attachShadow(this.constructor.shadowRootOptions);
    return S(t6, this.constructor.elementStyles), t6;
  }
  connectedCallback() {
    this.renderRoot ??= this.createRenderRoot(), this.enableUpdating(true), this._$EO?.forEach((t6) => t6.hostConnected?.());
  }
  enableUpdating(t6) {
  }
  disconnectedCallback() {
    this._$EO?.forEach((t6) => t6.hostDisconnected?.());
  }
  attributeChangedCallback(t6, s6, i7) {
    this._$AK(t6, i7);
  }
  _$ET(t6, s6) {
    const i7 = this.constructor.elementProperties.get(t6), e9 = this.constructor._$Eu(t6, i7);
    if (void 0 !== e9 && true === i7.reflect) {
      const h7 = (void 0 !== i7.converter?.toAttribute ? i7.converter : u).toAttribute(s6, i7.type);
      this._$Em = t6, null == h7 ? this.removeAttribute(e9) : this.setAttribute(e9, h7), this._$Em = null;
    }
  }
  _$AK(t6, s6) {
    const i7 = this.constructor, e9 = i7._$Eh.get(t6);
    if (void 0 !== e9 && this._$Em !== e9) {
      const t7 = i7.getPropertyOptions(e9), h7 = "function" == typeof t7.converter ? { fromAttribute: t7.converter } : void 0 !== t7.converter?.fromAttribute ? t7.converter : u;
      this._$Em = e9;
      const r8 = h7.fromAttribute(s6, t7.type);
      this[e9] = r8 ?? this._$Ej?.get(e9) ?? r8, this._$Em = null;
    }
  }
  requestUpdate(t6, s6, i7, e9 = false, h7) {
    if (void 0 !== t6) {
      const r8 = this.constructor;
      if (false === e9 && (h7 = this[t6]), i7 ??= r8.getPropertyOptions(t6), !((i7.hasChanged ?? f)(h7, s6) || i7.useDefault && i7.reflect && h7 === this._$Ej?.get(t6) && !this.hasAttribute(r8._$Eu(t6, i7)))) return;
      this.C(t6, s6, i7);
    }
    false === this.isUpdatePending && (this._$ES = this._$EP());
  }
  C(t6, s6, { useDefault: i7, reflect: e9, wrapped: h7 }, r8) {
    i7 && !(this._$Ej ??= /* @__PURE__ */ new Map()).has(t6) && (this._$Ej.set(t6, r8 ?? s6 ?? this[t6]), true !== h7 || void 0 !== r8) || (this._$AL.has(t6) || (this.hasUpdated || i7 || (s6 = void 0), this._$AL.set(t6, s6)), true === e9 && this._$Em !== t6 && (this._$Eq ??= /* @__PURE__ */ new Set()).add(t6));
  }
  async _$EP() {
    this.isUpdatePending = true;
    try {
      await this._$ES;
    } catch (t7) {
      Promise.reject(t7);
    }
    const t6 = this.scheduleUpdate();
    return null != t6 && await t6, !this.isUpdatePending;
  }
  scheduleUpdate() {
    return this.performUpdate();
  }
  performUpdate() {
    if (!this.isUpdatePending) return;
    if (!this.hasUpdated) {
      if (this.renderRoot ??= this.createRenderRoot(), this._$Ep) {
        for (const [t8, s7] of this._$Ep) this[t8] = s7;
        this._$Ep = void 0;
      }
      const t7 = this.constructor.elementProperties;
      if (t7.size > 0) for (const [s7, i7] of t7) {
        const { wrapped: t8 } = i7, e9 = this[s7];
        true !== t8 || this._$AL.has(s7) || void 0 === e9 || this.C(s7, void 0, i7, e9);
      }
    }
    let t6 = false;
    const s6 = this._$AL;
    try {
      t6 = this.shouldUpdate(s6), t6 ? (this.willUpdate(s6), this._$EO?.forEach((t7) => t7.hostUpdate?.()), this.update(s6)) : this._$EM();
    } catch (s7) {
      throw t6 = false, this._$EM(), s7;
    }
    t6 && this._$AE(s6);
  }
  willUpdate(t6) {
  }
  _$AE(t6) {
    this._$EO?.forEach((t7) => t7.hostUpdated?.()), this.hasUpdated || (this.hasUpdated = true, this.firstUpdated(t6)), this.updated(t6);
  }
  _$EM() {
    this._$AL = /* @__PURE__ */ new Map(), this.isUpdatePending = false;
  }
  get updateComplete() {
    return this.getUpdateComplete();
  }
  getUpdateComplete() {
    return this._$ES;
  }
  shouldUpdate(t6) {
    return true;
  }
  update(t6) {
    this._$Eq &&= this._$Eq.forEach((t7) => this._$ET(t7, this[t7])), this._$EM();
  }
  updated(t6) {
  }
  firstUpdated(t6) {
  }
};
y.elementStyles = [], y.shadowRootOptions = { mode: "open" }, y[d("elementProperties")] = /* @__PURE__ */ new Map(), y[d("finalized")] = /* @__PURE__ */ new Map(), p?.({ ReactiveElement: y }), (a.reactiveElementVersions ??= []).push("2.1.2");

// node_modules/lit-html/lit-html.js
init_process_shim();
var t2 = globalThis;
var i3 = (t6) => t6;
var s2 = t2.trustedTypes;
var e3 = s2 ? s2.createPolicy("lit-html", { createHTML: (t6) => t6 }) : void 0;
var h2 = "$lit$";
var o3 = `lit$${Math.random().toFixed(9).slice(2)}$`;
var n3 = "?" + o3;
var r3 = `<${n3}>`;
var l2 = document;
var c3 = () => l2.createComment("");
var a2 = (t6) => null === t6 || "object" != typeof t6 && "function" != typeof t6;
var u2 = Array.isArray;
var d2 = (t6) => u2(t6) || "function" == typeof t6?.[Symbol.iterator];
var f2 = "[ 	\n\f\r]";
var v = /<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g;
var _ = /-->/g;
var m = />/g;
var p2 = RegExp(`>|${f2}(?:([^\\s"'>=/]+)(${f2}*=${f2}*(?:[^ 	
\f\r"'\`<>=]|("|')|))|$)`, "g");
var g = /'/g;
var $2 = /"/g;
var y2 = /^(?:script|style|textarea|title)$/i;
var x = (t6) => (i7, ...s6) => ({ _$litType$: t6, strings: i7, values: s6 });
var b2 = x(1);
var w = x(2);
var T = x(3);
var E = Symbol.for("lit-noChange");
var A = Symbol.for("lit-nothing");
var C = /* @__PURE__ */ new WeakMap();
var P = l2.createTreeWalker(l2, 129);
function V(t6, i7) {
  if (!u2(t6) || !t6.hasOwnProperty("raw")) throw Error("invalid template strings array");
  return void 0 !== e3 ? e3.createHTML(i7) : i7;
}
var N = (t6, i7) => {
  const s6 = t6.length - 1, e9 = [];
  let n7, l5 = 2 === i7 ? "<svg>" : 3 === i7 ? "<math>" : "", c6 = v;
  for (let i8 = 0; i8 < s6; i8++) {
    const s7 = t6[i8];
    let a3, u5, d4 = -1, f4 = 0;
    for (; f4 < s7.length && (c6.lastIndex = f4, u5 = c6.exec(s7), null !== u5); ) f4 = c6.lastIndex, c6 === v ? "!--" === u5[1] ? c6 = _ : void 0 !== u5[1] ? c6 = m : void 0 !== u5[2] ? (y2.test(u5[2]) && (n7 = RegExp("</" + u5[2], "g")), c6 = p2) : void 0 !== u5[3] && (c6 = p2) : c6 === p2 ? ">" === u5[0] ? (c6 = n7 ?? v, d4 = -1) : void 0 === u5[1] ? d4 = -2 : (d4 = c6.lastIndex - u5[2].length, a3 = u5[1], c6 = void 0 === u5[3] ? p2 : '"' === u5[3] ? $2 : g) : c6 === $2 || c6 === g ? c6 = p2 : c6 === _ || c6 === m ? c6 = v : (c6 = p2, n7 = void 0);
    const x2 = c6 === p2 && t6[i8 + 1].startsWith("/>") ? " " : "";
    l5 += c6 === v ? s7 + r3 : d4 >= 0 ? (e9.push(a3), s7.slice(0, d4) + h2 + s7.slice(d4) + o3 + x2) : s7 + o3 + (-2 === d4 ? i8 : x2);
  }
  return [V(t6, l5 + (t6[s6] || "<?>") + (2 === i7 ? "</svg>" : 3 === i7 ? "</math>" : "")), e9];
};
var S2 = class _S {
  constructor({ strings: t6, _$litType$: i7 }, e9) {
    let r8;
    this.parts = [];
    let l5 = 0, a3 = 0;
    const u5 = t6.length - 1, d4 = this.parts, [f4, v4] = N(t6, i7);
    if (this.el = _S.createElement(f4, e9), P.currentNode = this.el.content, 2 === i7 || 3 === i7) {
      const t7 = this.el.content.firstChild;
      t7.replaceWith(...t7.childNodes);
    }
    for (; null !== (r8 = P.nextNode()) && d4.length < u5; ) {
      if (1 === r8.nodeType) {
        if (r8.hasAttributes()) for (const t7 of r8.getAttributeNames()) if (t7.endsWith(h2)) {
          const i8 = v4[a3++], s6 = r8.getAttribute(t7).split(o3), e10 = /([.?@])?(.*)/.exec(i8);
          d4.push({ type: 1, index: l5, name: e10[2], strings: s6, ctor: "." === e10[1] ? I : "?" === e10[1] ? L : "@" === e10[1] ? z : H }), r8.removeAttribute(t7);
        } else t7.startsWith(o3) && (d4.push({ type: 6, index: l5 }), r8.removeAttribute(t7));
        if (y2.test(r8.tagName)) {
          const t7 = r8.textContent.split(o3), i8 = t7.length - 1;
          if (i8 > 0) {
            r8.textContent = s2 ? s2.emptyScript : "";
            for (let s6 = 0; s6 < i8; s6++) r8.append(t7[s6], c3()), P.nextNode(), d4.push({ type: 2, index: ++l5 });
            r8.append(t7[i8], c3());
          }
        }
      } else if (8 === r8.nodeType) if (r8.data === n3) d4.push({ type: 2, index: l5 });
      else {
        let t7 = -1;
        for (; -1 !== (t7 = r8.data.indexOf(o3, t7 + 1)); ) d4.push({ type: 7, index: l5 }), t7 += o3.length - 1;
      }
      l5++;
    }
  }
  static createElement(t6, i7) {
    const s6 = l2.createElement("template");
    return s6.innerHTML = t6, s6;
  }
};
function M(t6, i7, s6 = t6, e9) {
  if (i7 === E) return i7;
  let h7 = void 0 !== e9 ? s6._$Co?.[e9] : s6._$Cl;
  const o9 = a2(i7) ? void 0 : i7._$litDirective$;
  return h7?.constructor !== o9 && (h7?._$AO?.(false), void 0 === o9 ? h7 = void 0 : (h7 = new o9(t6), h7._$AT(t6, s6, e9)), void 0 !== e9 ? (s6._$Co ??= [])[e9] = h7 : s6._$Cl = h7), void 0 !== h7 && (i7 = M(t6, h7._$AS(t6, i7.values), h7, e9)), i7;
}
var R = class {
  constructor(t6, i7) {
    this._$AV = [], this._$AN = void 0, this._$AD = t6, this._$AM = i7;
  }
  get parentNode() {
    return this._$AM.parentNode;
  }
  get _$AU() {
    return this._$AM._$AU;
  }
  u(t6) {
    const { el: { content: i7 }, parts: s6 } = this._$AD, e9 = (t6?.creationScope ?? l2).importNode(i7, true);
    P.currentNode = e9;
    let h7 = P.nextNode(), o9 = 0, n7 = 0, r8 = s6[0];
    for (; void 0 !== r8; ) {
      if (o9 === r8.index) {
        let i8;
        2 === r8.type ? i8 = new k(h7, h7.nextSibling, this, t6) : 1 === r8.type ? i8 = new r8.ctor(h7, r8.name, r8.strings, this, t6) : 6 === r8.type && (i8 = new Z(h7, this, t6)), this._$AV.push(i8), r8 = s6[++n7];
      }
      o9 !== r8?.index && (h7 = P.nextNode(), o9++);
    }
    return P.currentNode = l2, e9;
  }
  p(t6) {
    let i7 = 0;
    for (const s6 of this._$AV) void 0 !== s6 && (void 0 !== s6.strings ? (s6._$AI(t6, s6, i7), i7 += s6.strings.length - 2) : s6._$AI(t6[i7])), i7++;
  }
};
var k = class _k {
  get _$AU() {
    return this._$AM?._$AU ?? this._$Cv;
  }
  constructor(t6, i7, s6, e9) {
    this.type = 2, this._$AH = A, this._$AN = void 0, this._$AA = t6, this._$AB = i7, this._$AM = s6, this.options = e9, this._$Cv = e9?.isConnected ?? true;
  }
  get parentNode() {
    let t6 = this._$AA.parentNode;
    const i7 = this._$AM;
    return void 0 !== i7 && 11 === t6?.nodeType && (t6 = i7.parentNode), t6;
  }
  get startNode() {
    return this._$AA;
  }
  get endNode() {
    return this._$AB;
  }
  _$AI(t6, i7 = this) {
    t6 = M(this, t6, i7), a2(t6) ? t6 === A || null == t6 || "" === t6 ? (this._$AH !== A && this._$AR(), this._$AH = A) : t6 !== this._$AH && t6 !== E && this._(t6) : void 0 !== t6._$litType$ ? this.$(t6) : void 0 !== t6.nodeType ? this.T(t6) : d2(t6) ? this.k(t6) : this._(t6);
  }
  O(t6) {
    return this._$AA.parentNode.insertBefore(t6, this._$AB);
  }
  T(t6) {
    this._$AH !== t6 && (this._$AR(), this._$AH = this.O(t6));
  }
  _(t6) {
    this._$AH !== A && a2(this._$AH) ? this._$AA.nextSibling.data = t6 : this.T(l2.createTextNode(t6)), this._$AH = t6;
  }
  $(t6) {
    const { values: i7, _$litType$: s6 } = t6, e9 = "number" == typeof s6 ? this._$AC(t6) : (void 0 === s6.el && (s6.el = S2.createElement(V(s6.h, s6.h[0]), this.options)), s6);
    if (this._$AH?._$AD === e9) this._$AH.p(i7);
    else {
      const t7 = new R(e9, this), s7 = t7.u(this.options);
      t7.p(i7), this.T(s7), this._$AH = t7;
    }
  }
  _$AC(t6) {
    let i7 = C.get(t6.strings);
    return void 0 === i7 && C.set(t6.strings, i7 = new S2(t6)), i7;
  }
  k(t6) {
    u2(this._$AH) || (this._$AH = [], this._$AR());
    const i7 = this._$AH;
    let s6, e9 = 0;
    for (const h7 of t6) e9 === i7.length ? i7.push(s6 = new _k(this.O(c3()), this.O(c3()), this, this.options)) : s6 = i7[e9], s6._$AI(h7), e9++;
    e9 < i7.length && (this._$AR(s6 && s6._$AB.nextSibling, e9), i7.length = e9);
  }
  _$AR(t6 = this._$AA.nextSibling, s6) {
    for (this._$AP?.(false, true, s6); t6 !== this._$AB; ) {
      const s7 = i3(t6).nextSibling;
      i3(t6).remove(), t6 = s7;
    }
  }
  setConnected(t6) {
    void 0 === this._$AM && (this._$Cv = t6, this._$AP?.(t6));
  }
};
var H = class {
  get tagName() {
    return this.element.tagName;
  }
  get _$AU() {
    return this._$AM._$AU;
  }
  constructor(t6, i7, s6, e9, h7) {
    this.type = 1, this._$AH = A, this._$AN = void 0, this.element = t6, this.name = i7, this._$AM = e9, this.options = h7, s6.length > 2 || "" !== s6[0] || "" !== s6[1] ? (this._$AH = Array(s6.length - 1).fill(new String()), this.strings = s6) : this._$AH = A;
  }
  _$AI(t6, i7 = this, s6, e9) {
    const h7 = this.strings;
    let o9 = false;
    if (void 0 === h7) t6 = M(this, t6, i7, 0), o9 = !a2(t6) || t6 !== this._$AH && t6 !== E, o9 && (this._$AH = t6);
    else {
      const e10 = t6;
      let n7, r8;
      for (t6 = h7[0], n7 = 0; n7 < h7.length - 1; n7++) r8 = M(this, e10[s6 + n7], i7, n7), r8 === E && (r8 = this._$AH[n7]), o9 ||= !a2(r8) || r8 !== this._$AH[n7], r8 === A ? t6 = A : t6 !== A && (t6 += (r8 ?? "") + h7[n7 + 1]), this._$AH[n7] = r8;
    }
    o9 && !e9 && this.j(t6);
  }
  j(t6) {
    t6 === A ? this.element.removeAttribute(this.name) : this.element.setAttribute(this.name, t6 ?? "");
  }
};
var I = class extends H {
  constructor() {
    super(...arguments), this.type = 3;
  }
  j(t6) {
    this.element[this.name] = t6 === A ? void 0 : t6;
  }
};
var L = class extends H {
  constructor() {
    super(...arguments), this.type = 4;
  }
  j(t6) {
    this.element.toggleAttribute(this.name, !!t6 && t6 !== A);
  }
};
var z = class extends H {
  constructor(t6, i7, s6, e9, h7) {
    super(t6, i7, s6, e9, h7), this.type = 5;
  }
  _$AI(t6, i7 = this) {
    if ((t6 = M(this, t6, i7, 0) ?? A) === E) return;
    const s6 = this._$AH, e9 = t6 === A && s6 !== A || t6.capture !== s6.capture || t6.once !== s6.once || t6.passive !== s6.passive, h7 = t6 !== A && (s6 === A || e9);
    e9 && this.element.removeEventListener(this.name, this, s6), h7 && this.element.addEventListener(this.name, this, t6), this._$AH = t6;
  }
  handleEvent(t6) {
    "function" == typeof this._$AH ? this._$AH.call(this.options?.host ?? this.element, t6) : this._$AH.handleEvent(t6);
  }
};
var Z = class {
  constructor(t6, i7, s6) {
    this.element = t6, this.type = 6, this._$AN = void 0, this._$AM = i7, this.options = s6;
  }
  get _$AU() {
    return this._$AM._$AU;
  }
  _$AI(t6) {
    M(this, t6);
  }
};
var j = { M: h2, P: o3, A: n3, C: 1, L: N, R, D: d2, V: M, I: k, H, N: L, U: z, B: I, F: Z };
var B = t2.litHtmlPolyfillSupport;
B?.(S2, k), (t2.litHtmlVersions ??= []).push("3.3.2");
var D = (t6, i7, s6) => {
  const e9 = s6?.renderBefore ?? i7;
  let h7 = e9._$litPart$;
  if (void 0 === h7) {
    const t7 = s6?.renderBefore ?? null;
    e9._$litPart$ = h7 = new k(i7.insertBefore(c3(), t7), t7, void 0, s6 ?? {});
  }
  return h7._$AI(t6), h7;
};

// node_modules/lit-element/lit-element.js
init_process_shim();
var s3 = globalThis;
var i4 = class extends y {
  constructor() {
    super(...arguments), this.renderOptions = { host: this }, this._$Do = void 0;
  }
  createRenderRoot() {
    const t6 = super.createRenderRoot();
    return this.renderOptions.renderBefore ??= t6.firstChild, t6;
  }
  update(t6) {
    const r8 = this.render();
    this.hasUpdated || (this.renderOptions.isConnected = this.isConnected), super.update(t6), this._$Do = D(r8, this.renderRoot, this.renderOptions);
  }
  connectedCallback() {
    super.connectedCallback(), this._$Do?.setConnected(true);
  }
  disconnectedCallback() {
    super.disconnectedCallback(), this._$Do?.setConnected(false);
  }
  render() {
    return E;
  }
};
i4._$litElement$ = true, i4["finalized"] = true, s3.litElementHydrateSupport?.({ LitElement: i4 });
var o4 = s3.litElementPolyfillSupport;
o4?.({ LitElement: i4 });
(s3.litElementVersions ??= []).push("4.2.2");

// node_modules/lit-html/is-server.js
init_process_shim();

// node_modules/lit/directives/ref.js
init_process_shim();

// node_modules/lit-html/directives/ref.js
init_process_shim();

// node_modules/lit-html/async-directive.js
init_process_shim();

// node_modules/lit-html/directive-helpers.js
init_process_shim();
var { I: t3 } = j;
var i5 = (o9) => o9;
var r4 = (o9) => void 0 === o9.strings;
var s4 = () => document.createComment("");
var v2 = (o9, n7, e9) => {
  const l5 = o9._$AA.parentNode, d4 = void 0 === n7 ? o9._$AB : n7._$AA;
  if (void 0 === e9) {
    const i7 = l5.insertBefore(s4(), d4), n8 = l5.insertBefore(s4(), d4);
    e9 = new t3(i7, n8, o9, o9.options);
  } else {
    const t6 = e9._$AB.nextSibling, n8 = e9._$AM, c6 = n8 !== o9;
    if (c6) {
      let t7;
      e9._$AQ?.(o9), e9._$AM = o9, void 0 !== e9._$AP && (t7 = o9._$AU) !== n8._$AU && e9._$AP(t7);
    }
    if (t6 !== d4 || c6) {
      let o10 = e9._$AA;
      for (; o10 !== t6; ) {
        const t7 = i5(o10).nextSibling;
        i5(l5).insertBefore(o10, d4), o10 = t7;
      }
    }
  }
  return e9;
};
var u3 = (o9, t6, i7 = o9) => (o9._$AI(t6, i7), o9);
var m2 = {};
var p3 = (o9, t6 = m2) => o9._$AH = t6;
var M2 = (o9) => o9._$AH;
var h3 = (o9) => {
  o9._$AR(), o9._$AA.remove();
};

// node_modules/lit-html/directive.js
init_process_shim();
var t4 = { ATTRIBUTE: 1, CHILD: 2, PROPERTY: 3, BOOLEAN_ATTRIBUTE: 4, EVENT: 5, ELEMENT: 6 };
var e4 = (t6) => (...e9) => ({ _$litDirective$: t6, values: e9 });
var i6 = class {
  constructor(t6) {
  }
  get _$AU() {
    return this._$AM._$AU;
  }
  _$AT(t6, e9, i7) {
    this._$Ct = t6, this._$AM = e9, this._$Ci = i7;
  }
  _$AS(t6, e9) {
    return this.update(t6, e9);
  }
  update(t6, e9) {
    return this.render(...e9);
  }
};

// node_modules/lit-html/async-directive.js
var s5 = (i7, t6) => {
  const e9 = i7._$AN;
  if (void 0 === e9) return false;
  for (const i8 of e9) i8._$AO?.(t6, false), s5(i8, t6);
  return true;
};
var o5 = (i7) => {
  let t6, e9;
  do {
    if (void 0 === (t6 = i7._$AM)) break;
    e9 = t6._$AN, e9.delete(i7), i7 = t6;
  } while (0 === e9?.size);
};
var r5 = (i7) => {
  for (let t6; t6 = i7._$AM; i7 = t6) {
    let e9 = t6._$AN;
    if (void 0 === e9) t6._$AN = e9 = /* @__PURE__ */ new Set();
    else if (e9.has(i7)) break;
    e9.add(i7), c4(t6);
  }
};
function h4(i7) {
  void 0 !== this._$AN ? (o5(this), this._$AM = i7, r5(this)) : this._$AM = i7;
}
function n4(i7, t6 = false, e9 = 0) {
  const r8 = this._$AH, h7 = this._$AN;
  if (void 0 !== h7 && 0 !== h7.size) if (t6) if (Array.isArray(r8)) for (let i8 = e9; i8 < r8.length; i8++) s5(r8[i8], false), o5(r8[i8]);
  else null != r8 && (s5(r8, false), o5(r8));
  else s5(this, i7);
}
var c4 = (i7) => {
  i7.type == t4.CHILD && (i7._$AP ??= n4, i7._$AQ ??= h4);
};
var f3 = class extends i6 {
  constructor() {
    super(...arguments), this._$AN = void 0;
  }
  _$AT(i7, t6, e9) {
    super._$AT(i7, t6, e9), r5(this), this.isConnected = i7._$AU;
  }
  _$AO(i7, t6 = true) {
    i7 !== this.isConnected && (this.isConnected = i7, i7 ? this.reconnected?.() : this.disconnected?.()), t6 && (s5(this, i7), o5(this));
  }
  setValue(t6) {
    if (r4(this._$Ct)) this._$Ct._$AI(t6, this);
    else {
      const i7 = [...this._$Ct._$AH];
      i7[this._$Ci] = t6, this._$Ct._$AI(i7, this, 0);
    }
  }
  disconnected() {
  }
  reconnected() {
  }
};

// node_modules/lit-html/directives/ref.js
var e5 = () => new h5();
var h5 = class {
};
var o6 = /* @__PURE__ */ new WeakMap();
var n5 = e4(class extends f3 {
  render(i7) {
    return A;
  }
  update(i7, [s6]) {
    const e9 = s6 !== this.G;
    return e9 && void 0 !== this.G && this.rt(void 0), (e9 || this.lt !== this.ct) && (this.G = s6, this.ht = i7.options?.host, this.rt(this.ct = i7.element)), A;
  }
  rt(t6) {
    if (this.isConnected || (t6 = void 0), "function" == typeof this.G) {
      const i7 = this.ht ?? globalThis;
      let s6 = o6.get(i7);
      void 0 === s6 && (s6 = /* @__PURE__ */ new WeakMap(), o6.set(i7, s6)), void 0 !== s6.get(this.G) && this.G.call(this.ht, void 0), s6.set(this.G, t6), void 0 !== t6 && this.G.call(this.ht, t6);
    } else this.G.value = t6;
  }
  get lt() {
    return "function" == typeof this.G ? o6.get(this.ht ?? globalThis)?.get(this.G) : this.G?.value;
  }
  disconnected() {
    this.lt === this.ct && this.rt(void 0);
  }
  reconnected() {
    this.rt(this.ct);
  }
});

// ../mini-lit/dist/mini.js
function fc(renderFn) {
  return (props) => renderFn(props || {});
}

// ../mini-lit/dist/Button.js
var Button = fc(({ variant = "default", size = "md", disabled = false, type = "button", loading = false, onClick, title, className = "", children }) => {
  const sizeClasses2 = {
    sm: "h-8 rounded-md px-3 text-xs",
    md: "h-9 rounded-md px-4 text-sm",
    lg: "h-10 rounded-md px-8 text-sm",
    icon: "size-8 rounded-md"
  };
  const variantClasses = {
    default: "bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",
    destructive: "bg-destructive text-destructive-foreground shadow-xs hover:bg-destructive/90",
    outline: "border border-input bg-background text-foreground shadow-xs hover:bg-accent hover:text-accent-foreground",
    secondary: "bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",
    ghost: "text-foreground hover:bg-accent hover:text-accent-foreground",
    link: "text-primary underline-offset-4 hover:underline"
  };
  const baseClasses = "inline-flex items-center justify-center whitespace-nowrap text-sm font-medium transition-all cursor-pointer disabled:cursor-not-allowed disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive";
  const gapClass = size === "icon" ? "" : "gap-2";
  const paddingAdjustClass = size === "icon" ? "" : "has-[>svg]:px-2.5";
  const variantClass = variantClasses[variant] || variantClasses.default;
  const handleClick = (e9) => {
    if (disabled || loading) {
      e9.preventDefault();
      e9.stopPropagation();
      return;
    }
    onClick?.(e9);
  };
  return b2`
         <button
            type="${type}"
            class="${baseClasses} ${sizeClasses2[size]} ${variantClass} ${gapClass} ${paddingAdjustClass} ${className}"
            ?disabled=${disabled || loading}
            @click=${handleClick}
            title="${title || ""}"
         >
            ${loading ? b2`
                    <svg class="animate-spin" fill="none" viewBox="0 0 24 24">
                       <circle
                          class="opacity-25"
                          cx="12"
                          cy="12"
                          r="10"
                          stroke="currentColor"
                          stroke-width="4"
                       ></circle>
                       <path
                          class="opacity-75"
                          fill="currentColor"
                          d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                       ></path>
                    </svg>
                 ` : ""}
            ${children}
         </button>
      `;
});

// ../mini-lit/dist/icons.js
init_process_shim();

// node_modules/lit/directives/unsafe-html.js
init_process_shim();

// node_modules/lit-html/directives/unsafe-html.js
init_process_shim();
var e6 = class extends i6 {
  constructor(i7) {
    if (super(i7), this.it = A, i7.type !== t4.CHILD) throw Error(this.constructor.directiveName + "() can only be used in child bindings");
  }
  render(r8) {
    if (r8 === A || null == r8) return this._t = void 0, this.it = r8;
    if (r8 === E) return r8;
    if ("string" != typeof r8) throw Error(this.constructor.directiveName + "() called with a non-string value");
    if (r8 === this.it) return this._t;
    this.it = r8;
    const s6 = [r8];
    return s6.raw = s6, this._t = { _$litType$: this.constructor.resultType, strings: s6, values: [] };
  }
};
e6.directiveName = "unsafeHTML", e6.resultType = 1;
var o7 = e4(e6);

// ../mini-lit/node_modules/lucide/dist/esm/lucide.js
init_process_shim();

// ../mini-lit/node_modules/lucide/dist/esm/createElement.js
init_process_shim();

// ../mini-lit/node_modules/lucide/dist/esm/defaultAttributes.js
init_process_shim();
var defaultAttributes = {
  xmlns: "http://www.w3.org/2000/svg",
  width: 24,
  height: 24,
  viewBox: "0 0 24 24",
  fill: "none",
  stroke: "currentColor",
  "stroke-width": 2,
  "stroke-linecap": "round",
  "stroke-linejoin": "round"
};

// ../mini-lit/node_modules/lucide/dist/esm/createElement.js
var createSVGElement = ([tag, attrs, children]) => {
  const element = document.createElementNS("http://www.w3.org/2000/svg", tag);
  Object.keys(attrs).forEach((name) => {
    element.setAttribute(name, String(attrs[name]));
  });
  if (children?.length) {
    children.forEach((child) => {
      const childElement = createSVGElement(child);
      element.appendChild(childElement);
    });
  }
  return element;
};
var createElement = (iconNode, customAttrs = {}) => {
  const tag = "svg";
  const attrs = {
    ...defaultAttributes,
    ...customAttrs
  };
  return createSVGElement([tag, attrs, iconNode]);
};

// ../mini-lit/node_modules/lucide/dist/esm/icons/check.js
init_process_shim();
var Check = [["path", { d: "M20 6 9 17l-5-5" }]];

// ../mini-lit/node_modules/lucide/dist/esm/icons/code.js
init_process_shim();
var Code = [
  ["path", { d: "m16 18 6-6-6-6" }],
  ["path", { d: "m8 6-6 6 6 6" }]
];

// ../mini-lit/node_modules/lucide/dist/esm/icons/copy.js
init_process_shim();
var Copy = [
  ["rect", { width: "14", height: "14", x: "8", y: "8", rx: "2", ry: "2" }],
  ["path", { d: "M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2" }]
];

// ../mini-lit/node_modules/lucide/dist/esm/icons/download.js
init_process_shim();
var Download = [
  ["path", { d: "M12 15V3" }],
  ["path", { d: "M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" }],
  ["path", { d: "m7 10 5 5 5-5" }]
];

// ../mini-lit/node_modules/lucide/dist/esm/icons/eye.js
init_process_shim();
var Eye = [
  [
    "path",
    {
      d: "M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0"
    }
  ],
  ["circle", { cx: "12", cy: "12", r: "3" }]
];

// ../mini-lit/dist/icons.js
var sizeClasses = {
  xs: "w-3 h-3",
  sm: "w-4 h-4",
  md: "w-5 h-5",
  lg: "w-6 h-6",
  xl: "w-8 h-8"
};
function icon(lucideIcon, size = "md", className) {
  return b2`${o7(iconDOM(lucideIcon, size, className).outerHTML)}`;
}
function iconDOM(lucideIcon, size = "md", className) {
  const element = createElement(lucideIcon, {
    class: sizeClasses[size] + (className ? " " + className : "")
  });
  return element;
}

// ../mini-lit/dist/Switch.js
init_process_shim();
var _Switch = fc(({ checked = false, disabled = false, label = "", name = "", id = "", onChange, className = "" }) => {
  const switchId = id || (label ? `switch-${Math.random().toString(36).substr(2, 9)}` : "");
  const handleClick = () => {
    if (!disabled) {
      onChange?.(!checked);
    }
  };
  const baseClasses = "peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50";
  const checkedClasses = "data-[state=checked]:bg-primary data-[state=unchecked]:bg-input";
  const thumbClasses = "pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0";
  return b2`
         <div class="flex items-center space-x-2 ${className}">
            <button
               type="button"
               role="switch"
               id="${switchId}"
               aria-checked="${checked}"
               data-state="${checked ? "checked" : "unchecked"}"
               ?disabled=${disabled}
               class="${baseClasses} ${checkedClasses}"
               @click=${handleClick}
            >
               <span data-state="${checked ? "checked" : "unchecked"}" class="${thumbClasses}"></span>
            </button>
            ${label ? b2`
                    <label
                       for="${switchId}"
                       class="text-sm font-medium leading-none text-foreground peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer select-none"
                       @click=${handleClick}
                    >
                       ${label}
                    </label>
                 ` : ""}
            ${name ? b2` <input type="hidden" name="${name}" .value=${checked ? "on" : "off"} /> ` : ""}
         </div>
      `;
});
function Switch(propsOrChecked = false, onChange, label = "", disabled = false, className = "") {
  if (typeof propsOrChecked === "object" && propsOrChecked !== null) {
    return _Switch(propsOrChecked);
  }
  return _Switch({ checked: propsOrChecked, onChange, label, disabled, className });
}

// ../pi-mono/packages/ai/dist/index.js
init_process_shim();

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/clone/type.mjs
init_process_shim();

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/clone/value.mjs
init_process_shim();

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/guard/value.mjs
var value_exports = {};
__export(value_exports, {
  HasPropertyKey: () => HasPropertyKey,
  IsArray: () => IsArray,
  IsAsyncIterator: () => IsAsyncIterator,
  IsBigInt: () => IsBigInt,
  IsBoolean: () => IsBoolean,
  IsDate: () => IsDate,
  IsFunction: () => IsFunction,
  IsIterator: () => IsIterator,
  IsNull: () => IsNull,
  IsNumber: () => IsNumber,
  IsObject: () => IsObject,
  IsRegExp: () => IsRegExp,
  IsString: () => IsString,
  IsSymbol: () => IsSymbol,
  IsUint8Array: () => IsUint8Array,
  IsUndefined: () => IsUndefined
});
init_process_shim();
function HasPropertyKey(value, key) {
  return key in value;
}
function IsAsyncIterator(value) {
  return IsObject(value) && !IsArray(value) && !IsUint8Array(value) && Symbol.asyncIterator in value;
}
function IsArray(value) {
  return Array.isArray(value);
}
function IsBigInt(value) {
  return typeof value === "bigint";
}
function IsBoolean(value) {
  return typeof value === "boolean";
}
function IsDate(value) {
  return value instanceof globalThis.Date;
}
function IsFunction(value) {
  return typeof value === "function";
}
function IsIterator(value) {
  return IsObject(value) && !IsArray(value) && !IsUint8Array(value) && Symbol.iterator in value;
}
function IsNull(value) {
  return value === null;
}
function IsNumber(value) {
  return typeof value === "number";
}
function IsObject(value) {
  return typeof value === "object" && value !== null;
}
function IsRegExp(value) {
  return value instanceof globalThis.RegExp;
}
function IsString(value) {
  return typeof value === "string";
}
function IsSymbol(value) {
  return typeof value === "symbol";
}
function IsUint8Array(value) {
  return value instanceof globalThis.Uint8Array;
}
function IsUndefined(value) {
  return value === void 0;
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/clone/value.mjs
function ArrayType(value) {
  return value.map((value2) => Visit(value2));
}
function DateType(value) {
  return new Date(value.getTime());
}
function Uint8ArrayType(value) {
  return new Uint8Array(value);
}
function RegExpType(value) {
  return new RegExp(value.source, value.flags);
}
function ObjectType(value) {
  const result = {};
  for (const key of Object.getOwnPropertyNames(value)) {
    result[key] = Visit(value[key]);
  }
  for (const key of Object.getOwnPropertySymbols(value)) {
    result[key] = Visit(value[key]);
  }
  return result;
}
function Visit(value) {
  return IsArray(value) ? ArrayType(value) : IsDate(value) ? DateType(value) : IsUint8Array(value) ? Uint8ArrayType(value) : IsRegExp(value) ? RegExpType(value) : IsObject(value) ? ObjectType(value) : value;
}
function Clone(value) {
  return Visit(value);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/clone/type.mjs
function CloneType(schema, options) {
  return options === void 0 ? Clone(schema) : Clone({ ...options, ...schema });
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/create/type.mjs
init_process_shim();

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/system/policy.mjs
init_process_shim();

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/value/guard/guard.mjs
init_process_shim();
function IsObject2(value) {
  return value !== null && typeof value === "object";
}
function IsArray2(value) {
  return globalThis.Array.isArray(value) && !globalThis.ArrayBuffer.isView(value);
}
function IsUndefined2(value) {
  return value === void 0;
}
function IsNumber2(value) {
  return typeof value === "number";
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/system/policy.mjs
var TypeSystemPolicy;
(function(TypeSystemPolicy3) {
  TypeSystemPolicy3.InstanceMode = "default";
  TypeSystemPolicy3.ExactOptionalPropertyTypes = false;
  TypeSystemPolicy3.AllowArrayObject = false;
  TypeSystemPolicy3.AllowNaN = false;
  TypeSystemPolicy3.AllowNullVoid = false;
  function IsExactOptionalProperty(value, key) {
    return TypeSystemPolicy3.ExactOptionalPropertyTypes ? key in value : value[key] !== void 0;
  }
  TypeSystemPolicy3.IsExactOptionalProperty = IsExactOptionalProperty;
  function IsObjectLike(value) {
    const isObject2 = IsObject2(value);
    return TypeSystemPolicy3.AllowArrayObject ? isObject2 : isObject2 && !IsArray2(value);
  }
  TypeSystemPolicy3.IsObjectLike = IsObjectLike;
  function IsRecordLike(value) {
    return IsObjectLike(value) && !(value instanceof Date) && !(value instanceof Uint8Array);
  }
  TypeSystemPolicy3.IsRecordLike = IsRecordLike;
  function IsNumberLike(value) {
    return TypeSystemPolicy3.AllowNaN ? IsNumber2(value) : Number.isFinite(value);
  }
  TypeSystemPolicy3.IsNumberLike = IsNumberLike;
  function IsVoidLike(value) {
    const isUndefined2 = IsUndefined2(value);
    return TypeSystemPolicy3.AllowNullVoid ? isUndefined2 || value === null : isUndefined2;
  }
  TypeSystemPolicy3.IsVoidLike = IsVoidLike;
})(TypeSystemPolicy || (TypeSystemPolicy = {}));

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/create/immutable.mjs
init_process_shim();
function ImmutableArray(value) {
  return globalThis.Object.freeze(value).map((value2) => Immutable(value2));
}
function ImmutableDate(value) {
  return value;
}
function ImmutableUint8Array(value) {
  return value;
}
function ImmutableRegExp(value) {
  return value;
}
function ImmutableObject(value) {
  const result = {};
  for (const key of Object.getOwnPropertyNames(value)) {
    result[key] = Immutable(value[key]);
  }
  for (const key of Object.getOwnPropertySymbols(value)) {
    result[key] = Immutable(value[key]);
  }
  return globalThis.Object.freeze(result);
}
function Immutable(value) {
  return IsArray(value) ? ImmutableArray(value) : IsDate(value) ? ImmutableDate(value) : IsUint8Array(value) ? ImmutableUint8Array(value) : IsRegExp(value) ? ImmutableRegExp(value) : IsObject(value) ? ImmutableObject(value) : value;
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/create/type.mjs
function CreateType(schema, options) {
  const result = options !== void 0 ? { ...options, ...schema } : schema;
  switch (TypeSystemPolicy.InstanceMode) {
    case "freeze":
      return Immutable(result);
    case "clone":
      return Clone(result);
    default:
      return result;
  }
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/error/error.mjs
init_process_shim();
var TypeBoxError = class extends Error {
  constructor(message) {
    super(message);
  }
};

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/guard/index.mjs
init_process_shim();

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/guard/kind.mjs
init_process_shim();

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/symbols/symbols.mjs
init_process_shim();
var TransformKind = Symbol.for("TypeBox.Transform");
var ReadonlyKind = Symbol.for("TypeBox.Readonly");
var OptionalKind = Symbol.for("TypeBox.Optional");
var Hint = Symbol.for("TypeBox.Hint");
var Kind = Symbol.for("TypeBox.Kind");

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/guard/kind.mjs
function IsReadonly(value) {
  return IsObject(value) && value[ReadonlyKind] === "Readonly";
}
function IsOptional(value) {
  return IsObject(value) && value[OptionalKind] === "Optional";
}
function IsAny(value) {
  return IsKindOf(value, "Any");
}
function IsArgument(value) {
  return IsKindOf(value, "Argument");
}
function IsArray3(value) {
  return IsKindOf(value, "Array");
}
function IsAsyncIterator2(value) {
  return IsKindOf(value, "AsyncIterator");
}
function IsBigInt2(value) {
  return IsKindOf(value, "BigInt");
}
function IsBoolean2(value) {
  return IsKindOf(value, "Boolean");
}
function IsComputed(value) {
  return IsKindOf(value, "Computed");
}
function IsConstructor(value) {
  return IsKindOf(value, "Constructor");
}
function IsDate2(value) {
  return IsKindOf(value, "Date");
}
function IsFunction2(value) {
  return IsKindOf(value, "Function");
}
function IsInteger(value) {
  return IsKindOf(value, "Integer");
}
function IsIntersect(value) {
  return IsKindOf(value, "Intersect");
}
function IsIterator2(value) {
  return IsKindOf(value, "Iterator");
}
function IsKindOf(value, kind) {
  return IsObject(value) && Kind in value && value[Kind] === kind;
}
function IsLiteralValue(value) {
  return IsBoolean(value) || IsNumber(value) || IsString(value);
}
function IsLiteral(value) {
  return IsKindOf(value, "Literal");
}
function IsMappedKey(value) {
  return IsKindOf(value, "MappedKey");
}
function IsMappedResult(value) {
  return IsKindOf(value, "MappedResult");
}
function IsNever(value) {
  return IsKindOf(value, "Never");
}
function IsNot(value) {
  return IsKindOf(value, "Not");
}
function IsNull2(value) {
  return IsKindOf(value, "Null");
}
function IsNumber3(value) {
  return IsKindOf(value, "Number");
}
function IsObject3(value) {
  return IsKindOf(value, "Object");
}
function IsPromise(value) {
  return IsKindOf(value, "Promise");
}
function IsRecord(value) {
  return IsKindOf(value, "Record");
}
function IsRef(value) {
  return IsKindOf(value, "Ref");
}
function IsRegExp2(value) {
  return IsKindOf(value, "RegExp");
}
function IsString2(value) {
  return IsKindOf(value, "String");
}
function IsSymbol2(value) {
  return IsKindOf(value, "Symbol");
}
function IsTemplateLiteral(value) {
  return IsKindOf(value, "TemplateLiteral");
}
function IsThis(value) {
  return IsKindOf(value, "This");
}
function IsTransform(value) {
  return IsObject(value) && TransformKind in value;
}
function IsTuple(value) {
  return IsKindOf(value, "Tuple");
}
function IsUndefined3(value) {
  return IsKindOf(value, "Undefined");
}
function IsUnion(value) {
  return IsKindOf(value, "Union");
}
function IsUint8Array2(value) {
  return IsKindOf(value, "Uint8Array");
}
function IsUnknown(value) {
  return IsKindOf(value, "Unknown");
}
function IsUnsafe(value) {
  return IsKindOf(value, "Unsafe");
}
function IsVoid(value) {
  return IsKindOf(value, "Void");
}
function IsKind(value) {
  return IsObject(value) && Kind in value && IsString(value[Kind]);
}
function IsSchema(value) {
  return IsAny(value) || IsArgument(value) || IsArray3(value) || IsBoolean2(value) || IsBigInt2(value) || IsAsyncIterator2(value) || IsComputed(value) || IsConstructor(value) || IsDate2(value) || IsFunction2(value) || IsInteger(value) || IsIntersect(value) || IsIterator2(value) || IsLiteral(value) || IsMappedKey(value) || IsMappedResult(value) || IsNever(value) || IsNot(value) || IsNull2(value) || IsNumber3(value) || IsObject3(value) || IsPromise(value) || IsRecord(value) || IsRef(value) || IsRegExp2(value) || IsString2(value) || IsSymbol2(value) || IsTemplateLiteral(value) || IsThis(value) || IsTuple(value) || IsUndefined3(value) || IsUnion(value) || IsUint8Array2(value) || IsUnknown(value) || IsUnsafe(value) || IsVoid(value) || IsKind(value);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/guard/type.mjs
var type_exports = {};
__export(type_exports, {
  IsAny: () => IsAny2,
  IsArgument: () => IsArgument2,
  IsArray: () => IsArray4,
  IsAsyncIterator: () => IsAsyncIterator3,
  IsBigInt: () => IsBigInt3,
  IsBoolean: () => IsBoolean3,
  IsComputed: () => IsComputed2,
  IsConstructor: () => IsConstructor2,
  IsDate: () => IsDate3,
  IsFunction: () => IsFunction3,
  IsImport: () => IsImport,
  IsInteger: () => IsInteger2,
  IsIntersect: () => IsIntersect2,
  IsIterator: () => IsIterator3,
  IsKind: () => IsKind2,
  IsKindOf: () => IsKindOf2,
  IsLiteral: () => IsLiteral2,
  IsLiteralBoolean: () => IsLiteralBoolean,
  IsLiteralNumber: () => IsLiteralNumber,
  IsLiteralString: () => IsLiteralString,
  IsLiteralValue: () => IsLiteralValue2,
  IsMappedKey: () => IsMappedKey2,
  IsMappedResult: () => IsMappedResult2,
  IsNever: () => IsNever2,
  IsNot: () => IsNot2,
  IsNull: () => IsNull3,
  IsNumber: () => IsNumber4,
  IsObject: () => IsObject4,
  IsOptional: () => IsOptional2,
  IsPromise: () => IsPromise2,
  IsProperties: () => IsProperties,
  IsReadonly: () => IsReadonly2,
  IsRecord: () => IsRecord2,
  IsRecursive: () => IsRecursive,
  IsRef: () => IsRef2,
  IsRegExp: () => IsRegExp3,
  IsSchema: () => IsSchema2,
  IsString: () => IsString3,
  IsSymbol: () => IsSymbol3,
  IsTemplateLiteral: () => IsTemplateLiteral2,
  IsThis: () => IsThis2,
  IsTransform: () => IsTransform2,
  IsTuple: () => IsTuple2,
  IsUint8Array: () => IsUint8Array3,
  IsUndefined: () => IsUndefined4,
  IsUnion: () => IsUnion2,
  IsUnionLiteral: () => IsUnionLiteral,
  IsUnknown: () => IsUnknown2,
  IsUnsafe: () => IsUnsafe2,
  IsVoid: () => IsVoid2,
  TypeGuardUnknownTypeError: () => TypeGuardUnknownTypeError
});
init_process_shim();
var TypeGuardUnknownTypeError = class extends TypeBoxError {
};
var KnownTypes = [
  "Argument",
  "Any",
  "Array",
  "AsyncIterator",
  "BigInt",
  "Boolean",
  "Computed",
  "Constructor",
  "Date",
  "Enum",
  "Function",
  "Integer",
  "Intersect",
  "Iterator",
  "Literal",
  "MappedKey",
  "MappedResult",
  "Not",
  "Null",
  "Number",
  "Object",
  "Promise",
  "Record",
  "Ref",
  "RegExp",
  "String",
  "Symbol",
  "TemplateLiteral",
  "This",
  "Tuple",
  "Undefined",
  "Union",
  "Uint8Array",
  "Unknown",
  "Void"
];
function IsPattern(value) {
  try {
    new RegExp(value);
    return true;
  } catch {
    return false;
  }
}
function IsControlCharacterFree(value) {
  if (!IsString(value))
    return false;
  for (let i7 = 0; i7 < value.length; i7++) {
    const code = value.charCodeAt(i7);
    if (code >= 7 && code <= 13 || code === 27 || code === 127) {
      return false;
    }
  }
  return true;
}
function IsAdditionalProperties(value) {
  return IsOptionalBoolean(value) || IsSchema2(value);
}
function IsOptionalBigInt(value) {
  return IsUndefined(value) || IsBigInt(value);
}
function IsOptionalNumber(value) {
  return IsUndefined(value) || IsNumber(value);
}
function IsOptionalBoolean(value) {
  return IsUndefined(value) || IsBoolean(value);
}
function IsOptionalString(value) {
  return IsUndefined(value) || IsString(value);
}
function IsOptionalPattern(value) {
  return IsUndefined(value) || IsString(value) && IsControlCharacterFree(value) && IsPattern(value);
}
function IsOptionalFormat(value) {
  return IsUndefined(value) || IsString(value) && IsControlCharacterFree(value);
}
function IsOptionalSchema(value) {
  return IsUndefined(value) || IsSchema2(value);
}
function IsReadonly2(value) {
  return IsObject(value) && value[ReadonlyKind] === "Readonly";
}
function IsOptional2(value) {
  return IsObject(value) && value[OptionalKind] === "Optional";
}
function IsAny2(value) {
  return IsKindOf2(value, "Any") && IsOptionalString(value.$id);
}
function IsArgument2(value) {
  return IsKindOf2(value, "Argument") && IsNumber(value.index);
}
function IsArray4(value) {
  return IsKindOf2(value, "Array") && value.type === "array" && IsOptionalString(value.$id) && IsSchema2(value.items) && IsOptionalNumber(value.minItems) && IsOptionalNumber(value.maxItems) && IsOptionalBoolean(value.uniqueItems) && IsOptionalSchema(value.contains) && IsOptionalNumber(value.minContains) && IsOptionalNumber(value.maxContains);
}
function IsAsyncIterator3(value) {
  return IsKindOf2(value, "AsyncIterator") && value.type === "AsyncIterator" && IsOptionalString(value.$id) && IsSchema2(value.items);
}
function IsBigInt3(value) {
  return IsKindOf2(value, "BigInt") && value.type === "bigint" && IsOptionalString(value.$id) && IsOptionalBigInt(value.exclusiveMaximum) && IsOptionalBigInt(value.exclusiveMinimum) && IsOptionalBigInt(value.maximum) && IsOptionalBigInt(value.minimum) && IsOptionalBigInt(value.multipleOf);
}
function IsBoolean3(value) {
  return IsKindOf2(value, "Boolean") && value.type === "boolean" && IsOptionalString(value.$id);
}
function IsComputed2(value) {
  return IsKindOf2(value, "Computed") && IsString(value.target) && IsArray(value.parameters) && value.parameters.every((schema) => IsSchema2(schema));
}
function IsConstructor2(value) {
  return IsKindOf2(value, "Constructor") && value.type === "Constructor" && IsOptionalString(value.$id) && IsArray(value.parameters) && value.parameters.every((schema) => IsSchema2(schema)) && IsSchema2(value.returns);
}
function IsDate3(value) {
  return IsKindOf2(value, "Date") && value.type === "Date" && IsOptionalString(value.$id) && IsOptionalNumber(value.exclusiveMaximumTimestamp) && IsOptionalNumber(value.exclusiveMinimumTimestamp) && IsOptionalNumber(value.maximumTimestamp) && IsOptionalNumber(value.minimumTimestamp) && IsOptionalNumber(value.multipleOfTimestamp);
}
function IsFunction3(value) {
  return IsKindOf2(value, "Function") && value.type === "Function" && IsOptionalString(value.$id) && IsArray(value.parameters) && value.parameters.every((schema) => IsSchema2(schema)) && IsSchema2(value.returns);
}
function IsImport(value) {
  return IsKindOf2(value, "Import") && HasPropertyKey(value, "$defs") && IsObject(value.$defs) && IsProperties(value.$defs) && HasPropertyKey(value, "$ref") && IsString(value.$ref) && value.$ref in value.$defs;
}
function IsInteger2(value) {
  return IsKindOf2(value, "Integer") && value.type === "integer" && IsOptionalString(value.$id) && IsOptionalNumber(value.exclusiveMaximum) && IsOptionalNumber(value.exclusiveMinimum) && IsOptionalNumber(value.maximum) && IsOptionalNumber(value.minimum) && IsOptionalNumber(value.multipleOf);
}
function IsProperties(value) {
  return IsObject(value) && Object.entries(value).every(([key, schema]) => IsControlCharacterFree(key) && IsSchema2(schema));
}
function IsIntersect2(value) {
  return IsKindOf2(value, "Intersect") && (IsString(value.type) && value.type !== "object" ? false : true) && IsArray(value.allOf) && value.allOf.every((schema) => IsSchema2(schema) && !IsTransform2(schema)) && IsOptionalString(value.type) && (IsOptionalBoolean(value.unevaluatedProperties) || IsOptionalSchema(value.unevaluatedProperties)) && IsOptionalString(value.$id);
}
function IsIterator3(value) {
  return IsKindOf2(value, "Iterator") && value.type === "Iterator" && IsOptionalString(value.$id) && IsSchema2(value.items);
}
function IsKindOf2(value, kind) {
  return IsObject(value) && Kind in value && value[Kind] === kind;
}
function IsLiteralString(value) {
  return IsLiteral2(value) && IsString(value.const);
}
function IsLiteralNumber(value) {
  return IsLiteral2(value) && IsNumber(value.const);
}
function IsLiteralBoolean(value) {
  return IsLiteral2(value) && IsBoolean(value.const);
}
function IsLiteral2(value) {
  return IsKindOf2(value, "Literal") && IsOptionalString(value.$id) && IsLiteralValue2(value.const);
}
function IsLiteralValue2(value) {
  return IsBoolean(value) || IsNumber(value) || IsString(value);
}
function IsMappedKey2(value) {
  return IsKindOf2(value, "MappedKey") && IsArray(value.keys) && value.keys.every((key) => IsNumber(key) || IsString(key));
}
function IsMappedResult2(value) {
  return IsKindOf2(value, "MappedResult") && IsProperties(value.properties);
}
function IsNever2(value) {
  return IsKindOf2(value, "Never") && IsObject(value.not) && Object.getOwnPropertyNames(value.not).length === 0;
}
function IsNot2(value) {
  return IsKindOf2(value, "Not") && IsSchema2(value.not);
}
function IsNull3(value) {
  return IsKindOf2(value, "Null") && value.type === "null" && IsOptionalString(value.$id);
}
function IsNumber4(value) {
  return IsKindOf2(value, "Number") && value.type === "number" && IsOptionalString(value.$id) && IsOptionalNumber(value.exclusiveMaximum) && IsOptionalNumber(value.exclusiveMinimum) && IsOptionalNumber(value.maximum) && IsOptionalNumber(value.minimum) && IsOptionalNumber(value.multipleOf);
}
function IsObject4(value) {
  return IsKindOf2(value, "Object") && value.type === "object" && IsOptionalString(value.$id) && IsProperties(value.properties) && IsAdditionalProperties(value.additionalProperties) && IsOptionalNumber(value.minProperties) && IsOptionalNumber(value.maxProperties);
}
function IsPromise2(value) {
  return IsKindOf2(value, "Promise") && value.type === "Promise" && IsOptionalString(value.$id) && IsSchema2(value.item);
}
function IsRecord2(value) {
  return IsKindOf2(value, "Record") && value.type === "object" && IsOptionalString(value.$id) && IsAdditionalProperties(value.additionalProperties) && IsObject(value.patternProperties) && ((schema) => {
    const keys2 = Object.getOwnPropertyNames(schema.patternProperties);
    return keys2.length === 1 && IsPattern(keys2[0]) && IsObject(schema.patternProperties) && IsSchema2(schema.patternProperties[keys2[0]]);
  })(value);
}
function IsRecursive(value) {
  return IsObject(value) && Hint in value && value[Hint] === "Recursive";
}
function IsRef2(value) {
  return IsKindOf2(value, "Ref") && IsOptionalString(value.$id) && IsString(value.$ref);
}
function IsRegExp3(value) {
  return IsKindOf2(value, "RegExp") && IsOptionalString(value.$id) && IsString(value.source) && IsString(value.flags) && IsOptionalNumber(value.maxLength) && IsOptionalNumber(value.minLength);
}
function IsString3(value) {
  return IsKindOf2(value, "String") && value.type === "string" && IsOptionalString(value.$id) && IsOptionalNumber(value.minLength) && IsOptionalNumber(value.maxLength) && IsOptionalPattern(value.pattern) && IsOptionalFormat(value.format);
}
function IsSymbol3(value) {
  return IsKindOf2(value, "Symbol") && value.type === "symbol" && IsOptionalString(value.$id);
}
function IsTemplateLiteral2(value) {
  return IsKindOf2(value, "TemplateLiteral") && value.type === "string" && IsString(value.pattern) && value.pattern[0] === "^" && value.pattern[value.pattern.length - 1] === "$";
}
function IsThis2(value) {
  return IsKindOf2(value, "This") && IsOptionalString(value.$id) && IsString(value.$ref);
}
function IsTransform2(value) {
  return IsObject(value) && TransformKind in value;
}
function IsTuple2(value) {
  return IsKindOf2(value, "Tuple") && value.type === "array" && IsOptionalString(value.$id) && IsNumber(value.minItems) && IsNumber(value.maxItems) && value.minItems === value.maxItems && // empty
  (IsUndefined(value.items) && IsUndefined(value.additionalItems) && value.minItems === 0 || IsArray(value.items) && value.items.every((schema) => IsSchema2(schema)));
}
function IsUndefined4(value) {
  return IsKindOf2(value, "Undefined") && value.type === "undefined" && IsOptionalString(value.$id);
}
function IsUnionLiteral(value) {
  return IsUnion2(value) && value.anyOf.every((schema) => IsLiteralString(schema) || IsLiteralNumber(schema));
}
function IsUnion2(value) {
  return IsKindOf2(value, "Union") && IsOptionalString(value.$id) && IsObject(value) && IsArray(value.anyOf) && value.anyOf.every((schema) => IsSchema2(schema));
}
function IsUint8Array3(value) {
  return IsKindOf2(value, "Uint8Array") && value.type === "Uint8Array" && IsOptionalString(value.$id) && IsOptionalNumber(value.minByteLength) && IsOptionalNumber(value.maxByteLength);
}
function IsUnknown2(value) {
  return IsKindOf2(value, "Unknown") && IsOptionalString(value.$id);
}
function IsUnsafe2(value) {
  return IsKindOf2(value, "Unsafe");
}
function IsVoid2(value) {
  return IsKindOf2(value, "Void") && value.type === "void" && IsOptionalString(value.$id);
}
function IsKind2(value) {
  return IsObject(value) && Kind in value && IsString(value[Kind]) && !KnownTypes.includes(value[Kind]);
}
function IsSchema2(value) {
  return IsObject(value) && (IsAny2(value) || IsArgument2(value) || IsArray4(value) || IsBoolean3(value) || IsBigInt3(value) || IsAsyncIterator3(value) || IsComputed2(value) || IsConstructor2(value) || IsDate3(value) || IsFunction3(value) || IsInteger2(value) || IsIntersect2(value) || IsIterator3(value) || IsLiteral2(value) || IsMappedKey2(value) || IsMappedResult2(value) || IsNever2(value) || IsNot2(value) || IsNull3(value) || IsNumber4(value) || IsObject4(value) || IsPromise2(value) || IsRecord2(value) || IsRef2(value) || IsRegExp3(value) || IsString3(value) || IsSymbol3(value) || IsTemplateLiteral2(value) || IsThis2(value) || IsTuple2(value) || IsUndefined4(value) || IsUnion2(value) || IsUint8Array3(value) || IsUnknown2(value) || IsUnsafe2(value) || IsVoid2(value) || IsKind2(value));
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/patterns/patterns.mjs
init_process_shim();
var PatternBoolean = "(true|false)";
var PatternNumber = "(0|[1-9][0-9]*)";
var PatternString = "(.*)";
var PatternNever = "(?!.*)";
var PatternBooleanExact = `^${PatternBoolean}$`;
var PatternNumberExact = `^${PatternNumber}$`;
var PatternStringExact = `^${PatternString}$`;
var PatternNeverExact = `^${PatternNever}$`;

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/sets/set.mjs
init_process_shim();
function SetIncludes(T3, S5) {
  return T3.includes(S5);
}
function SetDistinct(T3) {
  return [...new Set(T3)];
}
function SetIntersect(T3, S5) {
  return T3.filter((L3) => S5.includes(L3));
}
function SetIntersectManyResolve(T3, Init) {
  return T3.reduce((Acc, L3) => {
    return SetIntersect(Acc, L3);
  }, Init);
}
function SetIntersectMany(T3) {
  return T3.length === 1 ? T3[0] : T3.length > 1 ? SetIntersectManyResolve(T3.slice(1), T3[0]) : [];
}
function SetUnionMany(T3) {
  const Acc = [];
  for (const L3 of T3)
    Acc.push(...L3);
  return Acc;
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/any/any.mjs
init_process_shim();
function Any(options) {
  return CreateType({ [Kind]: "Any" }, options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/array/array.mjs
init_process_shim();
function Array2(items, options) {
  return CreateType({ [Kind]: "Array", type: "array", items }, options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/argument/argument.mjs
init_process_shim();
function Argument(index) {
  return CreateType({ [Kind]: "Argument", index });
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/async-iterator/async-iterator.mjs
init_process_shim();
function AsyncIterator2(items, options) {
  return CreateType({ [Kind]: "AsyncIterator", type: "AsyncIterator", items }, options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/awaited/awaited.mjs
init_process_shim();

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/computed/computed.mjs
init_process_shim();
function Computed(target, parameters, options) {
  return CreateType({ [Kind]: "Computed", target, parameters }, options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/intersect/intersect-evaluated.mjs
init_process_shim();

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/discard/discard.mjs
init_process_shim();
function DiscardKey(value, key) {
  const { [key]: _3, ...rest } = value;
  return rest;
}
function Discard(value, keys2) {
  return keys2.reduce((acc, key) => DiscardKey(acc, key), value);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/never/never.mjs
init_process_shim();
function Never(options) {
  return CreateType({ [Kind]: "Never", not: {} }, options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/optional/optional-from-mapped-result.mjs
init_process_shim();

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/mapped/mapped-result.mjs
init_process_shim();
function MappedResult(properties) {
  return CreateType({
    [Kind]: "MappedResult",
    properties
  });
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/mapped/mapped.mjs
init_process_shim();

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/constructor/constructor.mjs
init_process_shim();
function Constructor(parameters, returns, options) {
  return CreateType({ [Kind]: "Constructor", type: "Constructor", parameters, returns }, options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/function/function.mjs
init_process_shim();
function Function2(parameters, returns, options) {
  return CreateType({ [Kind]: "Function", type: "Function", parameters, returns }, options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/indexed/indexed-from-mapped-key.mjs
init_process_shim();

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/indexed/indexed.mjs
init_process_shim();

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/union/union-evaluated.mjs
init_process_shim();

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/union/union-create.mjs
init_process_shim();
function UnionCreate(T3, options) {
  return CreateType({ [Kind]: "Union", anyOf: T3 }, options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/union/union-evaluated.mjs
function IsUnionOptional(types2) {
  return types2.some((type) => IsOptional(type));
}
function RemoveOptionalFromRest(types2) {
  return types2.map((left) => IsOptional(left) ? RemoveOptionalFromType(left) : left);
}
function RemoveOptionalFromType(T3) {
  return Discard(T3, [OptionalKind]);
}
function ResolveUnion(types2, options) {
  const isOptional = IsUnionOptional(types2);
  return isOptional ? Optional(UnionCreate(RemoveOptionalFromRest(types2), options)) : UnionCreate(RemoveOptionalFromRest(types2), options);
}
function UnionEvaluated(T3, options) {
  return T3.length === 1 ? CreateType(T3[0], options) : T3.length === 0 ? Never(options) : ResolveUnion(T3, options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/union/union.mjs
init_process_shim();
function Union(types2, options) {
  return types2.length === 0 ? Never(options) : types2.length === 1 ? CreateType(types2[0], options) : UnionCreate(types2, options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/indexed/indexed-property-keys.mjs
init_process_shim();

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/template-literal/finite.mjs
init_process_shim();

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/template-literal/parse.mjs
init_process_shim();
var TemplateLiteralParserError = class extends TypeBoxError {
};
function Unescape(pattern) {
  return pattern.replace(/\\\$/g, "$").replace(/\\\*/g, "*").replace(/\\\^/g, "^").replace(/\\\|/g, "|").replace(/\\\(/g, "(").replace(/\\\)/g, ")");
}
function IsNonEscaped(pattern, index, char) {
  return pattern[index] === char && pattern.charCodeAt(index - 1) !== 92;
}
function IsOpenParen(pattern, index) {
  return IsNonEscaped(pattern, index, "(");
}
function IsCloseParen(pattern, index) {
  return IsNonEscaped(pattern, index, ")");
}
function IsSeparator(pattern, index) {
  return IsNonEscaped(pattern, index, "|");
}
function IsGroup(pattern) {
  if (!(IsOpenParen(pattern, 0) && IsCloseParen(pattern, pattern.length - 1)))
    return false;
  let count = 0;
  for (let index = 0; index < pattern.length; index++) {
    if (IsOpenParen(pattern, index))
      count += 1;
    if (IsCloseParen(pattern, index))
      count -= 1;
    if (count === 0 && index !== pattern.length - 1)
      return false;
  }
  return true;
}
function InGroup(pattern) {
  return pattern.slice(1, pattern.length - 1);
}
function IsPrecedenceOr(pattern) {
  let count = 0;
  for (let index = 0; index < pattern.length; index++) {
    if (IsOpenParen(pattern, index))
      count += 1;
    if (IsCloseParen(pattern, index))
      count -= 1;
    if (IsSeparator(pattern, index) && count === 0)
      return true;
  }
  return false;
}
function IsPrecedenceAnd(pattern) {
  for (let index = 0; index < pattern.length; index++) {
    if (IsOpenParen(pattern, index))
      return true;
  }
  return false;
}
function Or(pattern) {
  let [count, start] = [0, 0];
  const expressions = [];
  for (let index = 0; index < pattern.length; index++) {
    if (IsOpenParen(pattern, index))
      count += 1;
    if (IsCloseParen(pattern, index))
      count -= 1;
    if (IsSeparator(pattern, index) && count === 0) {
      const range3 = pattern.slice(start, index);
      if (range3.length > 0)
        expressions.push(TemplateLiteralParse(range3));
      start = index + 1;
    }
  }
  const range2 = pattern.slice(start);
  if (range2.length > 0)
    expressions.push(TemplateLiteralParse(range2));
  if (expressions.length === 0)
    return { type: "const", const: "" };
  if (expressions.length === 1)
    return expressions[0];
  return { type: "or", expr: expressions };
}
function And(pattern) {
  function Group(value, index) {
    if (!IsOpenParen(value, index))
      throw new TemplateLiteralParserError(`TemplateLiteralParser: Index must point to open parens`);
    let count = 0;
    for (let scan2 = index; scan2 < value.length; scan2++) {
      if (IsOpenParen(value, scan2))
        count += 1;
      if (IsCloseParen(value, scan2))
        count -= 1;
      if (count === 0)
        return [index, scan2];
    }
    throw new TemplateLiteralParserError(`TemplateLiteralParser: Unclosed group parens in expression`);
  }
  function Range2(pattern2, index) {
    for (let scan2 = index; scan2 < pattern2.length; scan2++) {
      if (IsOpenParen(pattern2, scan2))
        return [index, scan2];
    }
    return [index, pattern2.length];
  }
  const expressions = [];
  for (let index = 0; index < pattern.length; index++) {
    if (IsOpenParen(pattern, index)) {
      const [start, end] = Group(pattern, index);
      const range2 = pattern.slice(start, end + 1);
      expressions.push(TemplateLiteralParse(range2));
      index = end;
    } else {
      const [start, end] = Range2(pattern, index);
      const range2 = pattern.slice(start, end);
      if (range2.length > 0)
        expressions.push(TemplateLiteralParse(range2));
      index = end - 1;
    }
  }
  return expressions.length === 0 ? { type: "const", const: "" } : expressions.length === 1 ? expressions[0] : { type: "and", expr: expressions };
}
function TemplateLiteralParse(pattern) {
  return IsGroup(pattern) ? TemplateLiteralParse(InGroup(pattern)) : IsPrecedenceOr(pattern) ? Or(pattern) : IsPrecedenceAnd(pattern) ? And(pattern) : { type: "const", const: Unescape(pattern) };
}
function TemplateLiteralParseExact(pattern) {
  return TemplateLiteralParse(pattern.slice(1, pattern.length - 1));
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/template-literal/finite.mjs
var TemplateLiteralFiniteError = class extends TypeBoxError {
};
function IsNumberExpression(expression) {
  return expression.type === "or" && expression.expr.length === 2 && expression.expr[0].type === "const" && expression.expr[0].const === "0" && expression.expr[1].type === "const" && expression.expr[1].const === "[1-9][0-9]*";
}
function IsBooleanExpression(expression) {
  return expression.type === "or" && expression.expr.length === 2 && expression.expr[0].type === "const" && expression.expr[0].const === "true" && expression.expr[1].type === "const" && expression.expr[1].const === "false";
}
function IsStringExpression(expression) {
  return expression.type === "const" && expression.const === ".*";
}
function IsTemplateLiteralExpressionFinite(expression) {
  return IsNumberExpression(expression) || IsStringExpression(expression) ? false : IsBooleanExpression(expression) ? true : expression.type === "and" ? expression.expr.every((expr) => IsTemplateLiteralExpressionFinite(expr)) : expression.type === "or" ? expression.expr.every((expr) => IsTemplateLiteralExpressionFinite(expr)) : expression.type === "const" ? true : (() => {
    throw new TemplateLiteralFiniteError(`Unknown expression type`);
  })();
}
function IsTemplateLiteralFinite(schema) {
  const expression = TemplateLiteralParseExact(schema.pattern);
  return IsTemplateLiteralExpressionFinite(expression);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/template-literal/generate.mjs
init_process_shim();
var TemplateLiteralGenerateError = class extends TypeBoxError {
};
function* GenerateReduce(buffer) {
  if (buffer.length === 1)
    return yield* buffer[0];
  for (const left of buffer[0]) {
    for (const right of GenerateReduce(buffer.slice(1))) {
      yield `${left}${right}`;
    }
  }
}
function* GenerateAnd(expression) {
  return yield* GenerateReduce(expression.expr.map((expr) => [...TemplateLiteralExpressionGenerate(expr)]));
}
function* GenerateOr(expression) {
  for (const expr of expression.expr)
    yield* TemplateLiteralExpressionGenerate(expr);
}
function* GenerateConst(expression) {
  return yield expression.const;
}
function* TemplateLiteralExpressionGenerate(expression) {
  return expression.type === "and" ? yield* GenerateAnd(expression) : expression.type === "or" ? yield* GenerateOr(expression) : expression.type === "const" ? yield* GenerateConst(expression) : (() => {
    throw new TemplateLiteralGenerateError("Unknown expression");
  })();
}
function TemplateLiteralGenerate(schema) {
  const expression = TemplateLiteralParseExact(schema.pattern);
  return IsTemplateLiteralExpressionFinite(expression) ? [...TemplateLiteralExpressionGenerate(expression)] : [];
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/template-literal/syntax.mjs
init_process_shim();

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/literal/literal.mjs
init_process_shim();
function Literal(value, options) {
  return CreateType({
    [Kind]: "Literal",
    const: value,
    type: typeof value
  }, options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/boolean/boolean.mjs
init_process_shim();
function Boolean2(options) {
  return CreateType({ [Kind]: "Boolean", type: "boolean" }, options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/bigint/bigint.mjs
init_process_shim();
function BigInt2(options) {
  return CreateType({ [Kind]: "BigInt", type: "bigint" }, options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/number/number.mjs
init_process_shim();
function Number2(options) {
  return CreateType({ [Kind]: "Number", type: "number" }, options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/string/string.mjs
init_process_shim();
function String2(options) {
  return CreateType({ [Kind]: "String", type: "string" }, options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/template-literal/syntax.mjs
function* FromUnion(syntax) {
  const trim = syntax.trim().replace(/"|'/g, "");
  return trim === "boolean" ? yield Boolean2() : trim === "number" ? yield Number2() : trim === "bigint" ? yield BigInt2() : trim === "string" ? yield String2() : yield (() => {
    const literals = trim.split("|").map((literal) => Literal(literal.trim()));
    return literals.length === 0 ? Never() : literals.length === 1 ? literals[0] : UnionEvaluated(literals);
  })();
}
function* FromTerminal(syntax) {
  if (syntax[1] !== "{") {
    const L3 = Literal("$");
    const R3 = FromSyntax(syntax.slice(1));
    return yield* [L3, ...R3];
  }
  for (let i7 = 2; i7 < syntax.length; i7++) {
    if (syntax[i7] === "}") {
      const L3 = FromUnion(syntax.slice(2, i7));
      const R3 = FromSyntax(syntax.slice(i7 + 1));
      return yield* [...L3, ...R3];
    }
  }
  yield Literal(syntax);
}
function* FromSyntax(syntax) {
  for (let i7 = 0; i7 < syntax.length; i7++) {
    if (syntax[i7] === "$") {
      const L3 = Literal(syntax.slice(0, i7));
      const R3 = FromTerminal(syntax.slice(i7));
      return yield* [L3, ...R3];
    }
  }
  yield Literal(syntax);
}
function TemplateLiteralSyntax(syntax) {
  return [...FromSyntax(syntax)];
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/template-literal/pattern.mjs
init_process_shim();
var TemplateLiteralPatternError = class extends TypeBoxError {
};
function Escape(value) {
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function Visit2(schema, acc) {
  return IsTemplateLiteral(schema) ? schema.pattern.slice(1, schema.pattern.length - 1) : IsUnion(schema) ? `(${schema.anyOf.map((schema2) => Visit2(schema2, acc)).join("|")})` : IsNumber3(schema) ? `${acc}${PatternNumber}` : IsInteger(schema) ? `${acc}${PatternNumber}` : IsBigInt2(schema) ? `${acc}${PatternNumber}` : IsString2(schema) ? `${acc}${PatternString}` : IsLiteral(schema) ? `${acc}${Escape(schema.const.toString())}` : IsBoolean2(schema) ? `${acc}${PatternBoolean}` : (() => {
    throw new TemplateLiteralPatternError(`Unexpected Kind '${schema[Kind]}'`);
  })();
}
function TemplateLiteralPattern(kinds) {
  return `^${kinds.map((schema) => Visit2(schema, "")).join("")}$`;
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/template-literal/union.mjs
init_process_shim();
function TemplateLiteralToUnion(schema) {
  const R3 = TemplateLiteralGenerate(schema);
  const L3 = R3.map((S5) => Literal(S5));
  return UnionEvaluated(L3);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/template-literal/template-literal.mjs
init_process_shim();
function TemplateLiteral(unresolved, options) {
  const pattern = IsString(unresolved) ? TemplateLiteralPattern(TemplateLiteralSyntax(unresolved)) : TemplateLiteralPattern(unresolved);
  return CreateType({ [Kind]: "TemplateLiteral", type: "string", pattern }, options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/indexed/indexed-property-keys.mjs
function FromTemplateLiteral(templateLiteral) {
  const keys2 = TemplateLiteralGenerate(templateLiteral);
  return keys2.map((key) => key.toString());
}
function FromUnion2(types2) {
  const result = [];
  for (const type of types2)
    result.push(...IndexPropertyKeys(type));
  return result;
}
function FromLiteral(literalValue) {
  return [literalValue.toString()];
}
function IndexPropertyKeys(type) {
  return [...new Set(IsTemplateLiteral(type) ? FromTemplateLiteral(type) : IsUnion(type) ? FromUnion2(type.anyOf) : IsLiteral(type) ? FromLiteral(type.const) : IsNumber3(type) ? ["[number]"] : IsInteger(type) ? ["[number]"] : [])];
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/indexed/indexed-from-mapped-result.mjs
init_process_shim();
function FromProperties(type, properties, options) {
  const result = {};
  for (const K2 of Object.getOwnPropertyNames(properties)) {
    result[K2] = Index(type, IndexPropertyKeys(properties[K2]), options);
  }
  return result;
}
function FromMappedResult(type, mappedResult, options) {
  return FromProperties(type, mappedResult.properties, options);
}
function IndexFromMappedResult(type, mappedResult, options) {
  const properties = FromMappedResult(type, mappedResult, options);
  return MappedResult(properties);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/indexed/indexed.mjs
function FromRest(types2, key) {
  return types2.map((type) => IndexFromPropertyKey(type, key));
}
function FromIntersectRest(types2) {
  return types2.filter((type) => !IsNever(type));
}
function FromIntersect(types2, key) {
  return IntersectEvaluated(FromIntersectRest(FromRest(types2, key)));
}
function FromUnionRest(types2) {
  return types2.some((L3) => IsNever(L3)) ? [] : types2;
}
function FromUnion3(types2, key) {
  return UnionEvaluated(FromUnionRest(FromRest(types2, key)));
}
function FromTuple(types2, key) {
  return key in types2 ? types2[key] : key === "[number]" ? UnionEvaluated(types2) : Never();
}
function FromArray(type, key) {
  return key === "[number]" ? type : Never();
}
function FromProperty(properties, propertyKey) {
  return propertyKey in properties ? properties[propertyKey] : Never();
}
function IndexFromPropertyKey(type, propertyKey) {
  return IsIntersect(type) ? FromIntersect(type.allOf, propertyKey) : IsUnion(type) ? FromUnion3(type.anyOf, propertyKey) : IsTuple(type) ? FromTuple(type.items ?? [], propertyKey) : IsArray3(type) ? FromArray(type.items, propertyKey) : IsObject3(type) ? FromProperty(type.properties, propertyKey) : Never();
}
function IndexFromPropertyKeys(type, propertyKeys) {
  return propertyKeys.map((propertyKey) => IndexFromPropertyKey(type, propertyKey));
}
function FromSchema(type, propertyKeys) {
  return UnionEvaluated(IndexFromPropertyKeys(type, propertyKeys));
}
function Index(type, key, options) {
  if (IsRef(type) || IsRef(key)) {
    const error = `Index types using Ref parameters require both Type and Key to be of TSchema`;
    if (!IsSchema(type) || !IsSchema(key))
      throw new TypeBoxError(error);
    return Computed("Index", [type, key]);
  }
  if (IsMappedResult(key))
    return IndexFromMappedResult(type, key, options);
  if (IsMappedKey(key))
    return IndexFromMappedKey(type, key, options);
  return CreateType(IsSchema(key) ? FromSchema(type, IndexPropertyKeys(key)) : FromSchema(type, key), options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/indexed/indexed-from-mapped-key.mjs
function MappedIndexPropertyKey(type, key, options) {
  return { [key]: Index(type, [key], Clone(options)) };
}
function MappedIndexPropertyKeys(type, propertyKeys, options) {
  return propertyKeys.reduce((result, left) => {
    return { ...result, ...MappedIndexPropertyKey(type, left, options) };
  }, {});
}
function MappedIndexProperties(type, mappedKey, options) {
  return MappedIndexPropertyKeys(type, mappedKey.keys, options);
}
function IndexFromMappedKey(type, mappedKey, options) {
  const properties = MappedIndexProperties(type, mappedKey, options);
  return MappedResult(properties);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/iterator/iterator.mjs
init_process_shim();
function Iterator(items, options) {
  return CreateType({ [Kind]: "Iterator", type: "Iterator", items }, options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/object/object.mjs
init_process_shim();
function RequiredArray(properties) {
  return globalThis.Object.keys(properties).filter((key) => !IsOptional(properties[key]));
}
function _Object(properties, options) {
  const required = RequiredArray(properties);
  const schema = required.length > 0 ? { [Kind]: "Object", type: "object", required, properties } : { [Kind]: "Object", type: "object", properties };
  return CreateType(schema, options);
}
var Object2 = _Object;

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/promise/promise.mjs
init_process_shim();
function Promise2(item, options) {
  return CreateType({ [Kind]: "Promise", type: "Promise", item }, options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/readonly/readonly-from-mapped-result.mjs
init_process_shim();

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/readonly/readonly.mjs
init_process_shim();
function RemoveReadonly(schema) {
  return CreateType(Discard(schema, [ReadonlyKind]));
}
function AddReadonly(schema) {
  return CreateType({ ...schema, [ReadonlyKind]: "Readonly" });
}
function ReadonlyWithFlag(schema, F2) {
  return F2 === false ? RemoveReadonly(schema) : AddReadonly(schema);
}
function Readonly(schema, enable) {
  const F2 = enable ?? true;
  return IsMappedResult(schema) ? ReadonlyFromMappedResult(schema, F2) : ReadonlyWithFlag(schema, F2);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/readonly/readonly-from-mapped-result.mjs
function FromProperties2(K2, F2) {
  const Acc = {};
  for (const K22 of globalThis.Object.getOwnPropertyNames(K2))
    Acc[K22] = Readonly(K2[K22], F2);
  return Acc;
}
function FromMappedResult2(R3, F2) {
  return FromProperties2(R3.properties, F2);
}
function ReadonlyFromMappedResult(R3, F2) {
  const P3 = FromMappedResult2(R3, F2);
  return MappedResult(P3);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/tuple/tuple.mjs
init_process_shim();
function Tuple(types2, options) {
  return CreateType(types2.length > 0 ? { [Kind]: "Tuple", type: "array", items: types2, additionalItems: false, minItems: types2.length, maxItems: types2.length } : { [Kind]: "Tuple", type: "array", minItems: types2.length, maxItems: types2.length }, options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/mapped/mapped.mjs
function FromMappedResult3(K2, P3) {
  return K2 in P3 ? FromSchemaType(K2, P3[K2]) : MappedResult(P3);
}
function MappedKeyToKnownMappedResultProperties(K2) {
  return { [K2]: Literal(K2) };
}
function MappedKeyToUnknownMappedResultProperties(P3) {
  const Acc = {};
  for (const L3 of P3)
    Acc[L3] = Literal(L3);
  return Acc;
}
function MappedKeyToMappedResultProperties(K2, P3) {
  return SetIncludes(P3, K2) ? MappedKeyToKnownMappedResultProperties(K2) : MappedKeyToUnknownMappedResultProperties(P3);
}
function FromMappedKey(K2, P3) {
  const R3 = MappedKeyToMappedResultProperties(K2, P3);
  return FromMappedResult3(K2, R3);
}
function FromRest2(K2, T3) {
  return T3.map((L3) => FromSchemaType(K2, L3));
}
function FromProperties3(K2, T3) {
  const Acc = {};
  for (const K22 of globalThis.Object.getOwnPropertyNames(T3))
    Acc[K22] = FromSchemaType(K2, T3[K22]);
  return Acc;
}
function FromSchemaType(K2, T3) {
  const options = { ...T3 };
  return (
    // unevaluated modifier types
    IsOptional(T3) ? Optional(FromSchemaType(K2, Discard(T3, [OptionalKind]))) : IsReadonly(T3) ? Readonly(FromSchemaType(K2, Discard(T3, [ReadonlyKind]))) : (
      // unevaluated mapped types
      IsMappedResult(T3) ? FromMappedResult3(K2, T3.properties) : IsMappedKey(T3) ? FromMappedKey(K2, T3.keys) : (
        // unevaluated types
        IsConstructor(T3) ? Constructor(FromRest2(K2, T3.parameters), FromSchemaType(K2, T3.returns), options) : IsFunction2(T3) ? Function2(FromRest2(K2, T3.parameters), FromSchemaType(K2, T3.returns), options) : IsAsyncIterator2(T3) ? AsyncIterator2(FromSchemaType(K2, T3.items), options) : IsIterator2(T3) ? Iterator(FromSchemaType(K2, T3.items), options) : IsIntersect(T3) ? Intersect(FromRest2(K2, T3.allOf), options) : IsUnion(T3) ? Union(FromRest2(K2, T3.anyOf), options) : IsTuple(T3) ? Tuple(FromRest2(K2, T3.items ?? []), options) : IsObject3(T3) ? Object2(FromProperties3(K2, T3.properties), options) : IsArray3(T3) ? Array2(FromSchemaType(K2, T3.items), options) : IsPromise(T3) ? Promise2(FromSchemaType(K2, T3.item), options) : T3
      )
    )
  );
}
function MappedFunctionReturnType(K2, T3) {
  const Acc = {};
  for (const L3 of K2)
    Acc[L3] = FromSchemaType(L3, T3);
  return Acc;
}
function Mapped(key, map, options) {
  const K2 = IsSchema(key) ? IndexPropertyKeys(key) : key;
  const RT = map({ [Kind]: "MappedKey", keys: K2 });
  const R3 = MappedFunctionReturnType(K2, RT);
  return Object2(R3, options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/optional/optional.mjs
init_process_shim();
function RemoveOptional(schema) {
  return CreateType(Discard(schema, [OptionalKind]));
}
function AddOptional(schema) {
  return CreateType({ ...schema, [OptionalKind]: "Optional" });
}
function OptionalWithFlag(schema, F2) {
  return F2 === false ? RemoveOptional(schema) : AddOptional(schema);
}
function Optional(schema, enable) {
  const F2 = enable ?? true;
  return IsMappedResult(schema) ? OptionalFromMappedResult(schema, F2) : OptionalWithFlag(schema, F2);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/optional/optional-from-mapped-result.mjs
function FromProperties4(P3, F2) {
  const Acc = {};
  for (const K2 of globalThis.Object.getOwnPropertyNames(P3))
    Acc[K2] = Optional(P3[K2], F2);
  return Acc;
}
function FromMappedResult4(R3, F2) {
  return FromProperties4(R3.properties, F2);
}
function OptionalFromMappedResult(R3, F2) {
  const P3 = FromMappedResult4(R3, F2);
  return MappedResult(P3);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/intersect/intersect-create.mjs
init_process_shim();
function IntersectCreate(T3, options = {}) {
  const allObjects = T3.every((schema) => IsObject3(schema));
  const clonedUnevaluatedProperties = IsSchema(options.unevaluatedProperties) ? { unevaluatedProperties: options.unevaluatedProperties } : {};
  return CreateType(options.unevaluatedProperties === false || IsSchema(options.unevaluatedProperties) || allObjects ? { ...clonedUnevaluatedProperties, [Kind]: "Intersect", type: "object", allOf: T3 } : { ...clonedUnevaluatedProperties, [Kind]: "Intersect", allOf: T3 }, options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/intersect/intersect-evaluated.mjs
function IsIntersectOptional(types2) {
  return types2.every((left) => IsOptional(left));
}
function RemoveOptionalFromType2(type) {
  return Discard(type, [OptionalKind]);
}
function RemoveOptionalFromRest2(types2) {
  return types2.map((left) => IsOptional(left) ? RemoveOptionalFromType2(left) : left);
}
function ResolveIntersect(types2, options) {
  return IsIntersectOptional(types2) ? Optional(IntersectCreate(RemoveOptionalFromRest2(types2), options)) : IntersectCreate(RemoveOptionalFromRest2(types2), options);
}
function IntersectEvaluated(types2, options = {}) {
  if (types2.length === 1)
    return CreateType(types2[0], options);
  if (types2.length === 0)
    return Never(options);
  if (types2.some((schema) => IsTransform(schema)))
    throw new Error("Cannot intersect transform types");
  return ResolveIntersect(types2, options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/intersect/intersect.mjs
init_process_shim();
function Intersect(types2, options) {
  if (types2.length === 1)
    return CreateType(types2[0], options);
  if (types2.length === 0)
    return Never(options);
  if (types2.some((schema) => IsTransform(schema)))
    throw new Error("Cannot intersect transform types");
  return IntersectCreate(types2, options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/ref/ref.mjs
init_process_shim();
function Ref(...args) {
  const [$ref, options] = typeof args[0] === "string" ? [args[0], args[1]] : [args[0].$id, args[1]];
  if (typeof $ref !== "string")
    throw new TypeBoxError("Ref: $ref must be a string");
  return CreateType({ [Kind]: "Ref", $ref }, options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/awaited/awaited.mjs
function FromComputed(target, parameters) {
  return Computed("Awaited", [Computed(target, parameters)]);
}
function FromRef($ref) {
  return Computed("Awaited", [Ref($ref)]);
}
function FromIntersect2(types2) {
  return Intersect(FromRest3(types2));
}
function FromUnion4(types2) {
  return Union(FromRest3(types2));
}
function FromPromise(type) {
  return Awaited(type);
}
function FromRest3(types2) {
  return types2.map((type) => Awaited(type));
}
function Awaited(type, options) {
  return CreateType(IsComputed(type) ? FromComputed(type.target, type.parameters) : IsIntersect(type) ? FromIntersect2(type.allOf) : IsUnion(type) ? FromUnion4(type.anyOf) : IsPromise(type) ? FromPromise(type.item) : IsRef(type) ? FromRef(type.$ref) : type, options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/composite/composite.mjs
init_process_shim();

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/keyof/keyof-from-mapped-result.mjs
init_process_shim();

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/keyof/keyof.mjs
init_process_shim();

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/keyof/keyof-property-keys.mjs
init_process_shim();
function FromRest4(types2) {
  const result = [];
  for (const L3 of types2)
    result.push(KeyOfPropertyKeys(L3));
  return result;
}
function FromIntersect3(types2) {
  const propertyKeysArray = FromRest4(types2);
  const propertyKeys = SetUnionMany(propertyKeysArray);
  return propertyKeys;
}
function FromUnion5(types2) {
  const propertyKeysArray = FromRest4(types2);
  const propertyKeys = SetIntersectMany(propertyKeysArray);
  return propertyKeys;
}
function FromTuple2(types2) {
  return types2.map((_3, indexer) => indexer.toString());
}
function FromArray2(_3) {
  return ["[number]"];
}
function FromProperties5(T3) {
  return globalThis.Object.getOwnPropertyNames(T3);
}
function FromPatternProperties(patternProperties) {
  if (!includePatternProperties)
    return [];
  const patternPropertyKeys = globalThis.Object.getOwnPropertyNames(patternProperties);
  return patternPropertyKeys.map((key) => {
    return key[0] === "^" && key[key.length - 1] === "$" ? key.slice(1, key.length - 1) : key;
  });
}
function KeyOfPropertyKeys(type) {
  return IsIntersect(type) ? FromIntersect3(type.allOf) : IsUnion(type) ? FromUnion5(type.anyOf) : IsTuple(type) ? FromTuple2(type.items ?? []) : IsArray3(type) ? FromArray2(type.items) : IsObject3(type) ? FromProperties5(type.properties) : IsRecord(type) ? FromPatternProperties(type.patternProperties) : [];
}
var includePatternProperties = false;

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/keyof/keyof.mjs
function FromComputed2(target, parameters) {
  return Computed("KeyOf", [Computed(target, parameters)]);
}
function FromRef2($ref) {
  return Computed("KeyOf", [Ref($ref)]);
}
function KeyOfFromType(type, options) {
  const propertyKeys = KeyOfPropertyKeys(type);
  const propertyKeyTypes = KeyOfPropertyKeysToRest(propertyKeys);
  const result = UnionEvaluated(propertyKeyTypes);
  return CreateType(result, options);
}
function KeyOfPropertyKeysToRest(propertyKeys) {
  return propertyKeys.map((L3) => L3 === "[number]" ? Number2() : Literal(L3));
}
function KeyOf(type, options) {
  return IsComputed(type) ? FromComputed2(type.target, type.parameters) : IsRef(type) ? FromRef2(type.$ref) : IsMappedResult(type) ? KeyOfFromMappedResult(type, options) : KeyOfFromType(type, options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/keyof/keyof-from-mapped-result.mjs
function FromProperties6(properties, options) {
  const result = {};
  for (const K2 of globalThis.Object.getOwnPropertyNames(properties))
    result[K2] = KeyOf(properties[K2], Clone(options));
  return result;
}
function FromMappedResult5(mappedResult, options) {
  return FromProperties6(mappedResult.properties, options);
}
function KeyOfFromMappedResult(mappedResult, options) {
  const properties = FromMappedResult5(mappedResult, options);
  return MappedResult(properties);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/composite/composite.mjs
function CompositeKeys(T3) {
  const Acc = [];
  for (const L3 of T3)
    Acc.push(...KeyOfPropertyKeys(L3));
  return SetDistinct(Acc);
}
function FilterNever(T3) {
  return T3.filter((L3) => !IsNever(L3));
}
function CompositeProperty(T3, K2) {
  const Acc = [];
  for (const L3 of T3)
    Acc.push(...IndexFromPropertyKeys(L3, [K2]));
  return FilterNever(Acc);
}
function CompositeProperties(T3, K2) {
  const Acc = {};
  for (const L3 of K2) {
    Acc[L3] = IntersectEvaluated(CompositeProperty(T3, L3));
  }
  return Acc;
}
function Composite(T3, options) {
  const K2 = CompositeKeys(T3);
  const P3 = CompositeProperties(T3, K2);
  const R3 = Object2(P3, options);
  return R3;
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/const/const.mjs
init_process_shim();

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/date/date.mjs
init_process_shim();
function Date2(options) {
  return CreateType({ [Kind]: "Date", type: "Date" }, options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/null/null.mjs
init_process_shim();
function Null(options) {
  return CreateType({ [Kind]: "Null", type: "null" }, options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/symbol/symbol.mjs
init_process_shim();
function Symbol2(options) {
  return CreateType({ [Kind]: "Symbol", type: "symbol" }, options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/undefined/undefined.mjs
init_process_shim();
function Undefined(options) {
  return CreateType({ [Kind]: "Undefined", type: "undefined" }, options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/uint8array/uint8array.mjs
init_process_shim();
function Uint8Array2(options) {
  return CreateType({ [Kind]: "Uint8Array", type: "Uint8Array" }, options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/unknown/unknown.mjs
init_process_shim();
function Unknown(options) {
  return CreateType({ [Kind]: "Unknown" }, options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/const/const.mjs
function FromArray3(T3) {
  return T3.map((L3) => FromValue(L3, false));
}
function FromProperties7(value) {
  const Acc = {};
  for (const K2 of globalThis.Object.getOwnPropertyNames(value))
    Acc[K2] = Readonly(FromValue(value[K2], false));
  return Acc;
}
function ConditionalReadonly(T3, root) {
  return root === true ? T3 : Readonly(T3);
}
function FromValue(value, root) {
  return IsAsyncIterator(value) ? ConditionalReadonly(Any(), root) : IsIterator(value) ? ConditionalReadonly(Any(), root) : IsArray(value) ? Readonly(Tuple(FromArray3(value))) : IsUint8Array(value) ? Uint8Array2() : IsDate(value) ? Date2() : IsObject(value) ? ConditionalReadonly(Object2(FromProperties7(value)), root) : IsFunction(value) ? ConditionalReadonly(Function2([], Unknown()), root) : IsUndefined(value) ? Undefined() : IsNull(value) ? Null() : IsSymbol(value) ? Symbol2() : IsBigInt(value) ? BigInt2() : IsNumber(value) ? Literal(value) : IsBoolean(value) ? Literal(value) : IsString(value) ? Literal(value) : Object2({});
}
function Const(T3, options) {
  return CreateType(FromValue(T3, true), options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/constructor-parameters/constructor-parameters.mjs
init_process_shim();
function ConstructorParameters(schema, options) {
  return IsConstructor(schema) ? Tuple(schema.parameters, options) : Never(options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/enum/enum.mjs
init_process_shim();
function Enum(item, options) {
  if (IsUndefined(item))
    throw new Error("Enum undefined or empty");
  const values1 = globalThis.Object.getOwnPropertyNames(item).filter((key) => isNaN(key)).map((key) => item[key]);
  const values2 = [...new Set(values1)];
  const anyOf = values2.map((value) => Literal(value));
  return Union(anyOf, { ...options, [Hint]: "Enum" });
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/exclude/exclude-from-mapped-result.mjs
init_process_shim();

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/exclude/exclude.mjs
init_process_shim();

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/extends/extends-check.mjs
init_process_shim();
var ExtendsResolverError = class extends TypeBoxError {
};
var ExtendsResult;
(function(ExtendsResult3) {
  ExtendsResult3[ExtendsResult3["Union"] = 0] = "Union";
  ExtendsResult3[ExtendsResult3["True"] = 1] = "True";
  ExtendsResult3[ExtendsResult3["False"] = 2] = "False";
})(ExtendsResult || (ExtendsResult = {}));
function IntoBooleanResult(result) {
  return result === ExtendsResult.False ? result : ExtendsResult.True;
}
function Throw(message) {
  throw new ExtendsResolverError(message);
}
function IsStructuralRight(right) {
  return type_exports.IsNever(right) || type_exports.IsIntersect(right) || type_exports.IsUnion(right) || type_exports.IsUnknown(right) || type_exports.IsAny(right);
}
function StructuralRight(left, right) {
  return type_exports.IsNever(right) ? FromNeverRight(left, right) : type_exports.IsIntersect(right) ? FromIntersectRight(left, right) : type_exports.IsUnion(right) ? FromUnionRight(left, right) : type_exports.IsUnknown(right) ? FromUnknownRight(left, right) : type_exports.IsAny(right) ? FromAnyRight(left, right) : Throw("StructuralRight");
}
function FromAnyRight(left, right) {
  return ExtendsResult.True;
}
function FromAny(left, right) {
  return type_exports.IsIntersect(right) ? FromIntersectRight(left, right) : type_exports.IsUnion(right) && right.anyOf.some((schema) => type_exports.IsAny(schema) || type_exports.IsUnknown(schema)) ? ExtendsResult.True : type_exports.IsUnion(right) ? ExtendsResult.Union : type_exports.IsUnknown(right) ? ExtendsResult.True : type_exports.IsAny(right) ? ExtendsResult.True : ExtendsResult.Union;
}
function FromArrayRight(left, right) {
  return type_exports.IsUnknown(left) ? ExtendsResult.False : type_exports.IsAny(left) ? ExtendsResult.Union : type_exports.IsNever(left) ? ExtendsResult.True : ExtendsResult.False;
}
function FromArray4(left, right) {
  return type_exports.IsObject(right) && IsObjectArrayLike(right) ? ExtendsResult.True : IsStructuralRight(right) ? StructuralRight(left, right) : !type_exports.IsArray(right) ? ExtendsResult.False : IntoBooleanResult(Visit3(left.items, right.items));
}
function FromAsyncIterator(left, right) {
  return IsStructuralRight(right) ? StructuralRight(left, right) : !type_exports.IsAsyncIterator(right) ? ExtendsResult.False : IntoBooleanResult(Visit3(left.items, right.items));
}
function FromBigInt(left, right) {
  return IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : type_exports.IsRecord(right) ? FromRecordRight(left, right) : type_exports.IsBigInt(right) ? ExtendsResult.True : ExtendsResult.False;
}
function FromBooleanRight(left, right) {
  return type_exports.IsLiteralBoolean(left) ? ExtendsResult.True : type_exports.IsBoolean(left) ? ExtendsResult.True : ExtendsResult.False;
}
function FromBoolean(left, right) {
  return IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : type_exports.IsRecord(right) ? FromRecordRight(left, right) : type_exports.IsBoolean(right) ? ExtendsResult.True : ExtendsResult.False;
}
function FromConstructor(left, right) {
  return IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : !type_exports.IsConstructor(right) ? ExtendsResult.False : left.parameters.length > right.parameters.length ? ExtendsResult.False : !left.parameters.every((schema, index) => IntoBooleanResult(Visit3(right.parameters[index], schema)) === ExtendsResult.True) ? ExtendsResult.False : IntoBooleanResult(Visit3(left.returns, right.returns));
}
function FromDate(left, right) {
  return IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : type_exports.IsRecord(right) ? FromRecordRight(left, right) : type_exports.IsDate(right) ? ExtendsResult.True : ExtendsResult.False;
}
function FromFunction(left, right) {
  return IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : !type_exports.IsFunction(right) ? ExtendsResult.False : left.parameters.length > right.parameters.length ? ExtendsResult.False : !left.parameters.every((schema, index) => IntoBooleanResult(Visit3(right.parameters[index], schema)) === ExtendsResult.True) ? ExtendsResult.False : IntoBooleanResult(Visit3(left.returns, right.returns));
}
function FromIntegerRight(left, right) {
  return type_exports.IsLiteral(left) && value_exports.IsNumber(left.const) ? ExtendsResult.True : type_exports.IsNumber(left) || type_exports.IsInteger(left) ? ExtendsResult.True : ExtendsResult.False;
}
function FromInteger(left, right) {
  return type_exports.IsInteger(right) || type_exports.IsNumber(right) ? ExtendsResult.True : IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : type_exports.IsRecord(right) ? FromRecordRight(left, right) : ExtendsResult.False;
}
function FromIntersectRight(left, right) {
  return right.allOf.every((schema) => Visit3(left, schema) === ExtendsResult.True) ? ExtendsResult.True : ExtendsResult.False;
}
function FromIntersect4(left, right) {
  return left.allOf.some((schema) => Visit3(schema, right) === ExtendsResult.True) ? ExtendsResult.True : ExtendsResult.False;
}
function FromIterator(left, right) {
  return IsStructuralRight(right) ? StructuralRight(left, right) : !type_exports.IsIterator(right) ? ExtendsResult.False : IntoBooleanResult(Visit3(left.items, right.items));
}
function FromLiteral2(left, right) {
  return type_exports.IsLiteral(right) && right.const === left.const ? ExtendsResult.True : IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : type_exports.IsRecord(right) ? FromRecordRight(left, right) : type_exports.IsString(right) ? FromStringRight(left, right) : type_exports.IsNumber(right) ? FromNumberRight(left, right) : type_exports.IsInteger(right) ? FromIntegerRight(left, right) : type_exports.IsBoolean(right) ? FromBooleanRight(left, right) : ExtendsResult.False;
}
function FromNeverRight(left, right) {
  return ExtendsResult.False;
}
function FromNever(left, right) {
  return ExtendsResult.True;
}
function UnwrapTNot(schema) {
  let [current2, depth] = [schema, 0];
  while (true) {
    if (!type_exports.IsNot(current2))
      break;
    current2 = current2.not;
    depth += 1;
  }
  return depth % 2 === 0 ? current2 : Unknown();
}
function FromNot(left, right) {
  return type_exports.IsNot(left) ? Visit3(UnwrapTNot(left), right) : type_exports.IsNot(right) ? Visit3(left, UnwrapTNot(right)) : Throw("Invalid fallthrough for Not");
}
function FromNull(left, right) {
  return IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : type_exports.IsRecord(right) ? FromRecordRight(left, right) : type_exports.IsNull(right) ? ExtendsResult.True : ExtendsResult.False;
}
function FromNumberRight(left, right) {
  return type_exports.IsLiteralNumber(left) ? ExtendsResult.True : type_exports.IsNumber(left) || type_exports.IsInteger(left) ? ExtendsResult.True : ExtendsResult.False;
}
function FromNumber(left, right) {
  return IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : type_exports.IsRecord(right) ? FromRecordRight(left, right) : type_exports.IsInteger(right) || type_exports.IsNumber(right) ? ExtendsResult.True : ExtendsResult.False;
}
function IsObjectPropertyCount(schema, count) {
  return Object.getOwnPropertyNames(schema.properties).length === count;
}
function IsObjectStringLike(schema) {
  return IsObjectArrayLike(schema);
}
function IsObjectSymbolLike(schema) {
  return IsObjectPropertyCount(schema, 0) || IsObjectPropertyCount(schema, 1) && "description" in schema.properties && type_exports.IsUnion(schema.properties.description) && schema.properties.description.anyOf.length === 2 && (type_exports.IsString(schema.properties.description.anyOf[0]) && type_exports.IsUndefined(schema.properties.description.anyOf[1]) || type_exports.IsString(schema.properties.description.anyOf[1]) && type_exports.IsUndefined(schema.properties.description.anyOf[0]));
}
function IsObjectNumberLike(schema) {
  return IsObjectPropertyCount(schema, 0);
}
function IsObjectBooleanLike(schema) {
  return IsObjectPropertyCount(schema, 0);
}
function IsObjectBigIntLike(schema) {
  return IsObjectPropertyCount(schema, 0);
}
function IsObjectDateLike(schema) {
  return IsObjectPropertyCount(schema, 0);
}
function IsObjectUint8ArrayLike(schema) {
  return IsObjectArrayLike(schema);
}
function IsObjectFunctionLike(schema) {
  const length = Number2();
  return IsObjectPropertyCount(schema, 0) || IsObjectPropertyCount(schema, 1) && "length" in schema.properties && IntoBooleanResult(Visit3(schema.properties["length"], length)) === ExtendsResult.True;
}
function IsObjectConstructorLike(schema) {
  return IsObjectPropertyCount(schema, 0);
}
function IsObjectArrayLike(schema) {
  const length = Number2();
  return IsObjectPropertyCount(schema, 0) || IsObjectPropertyCount(schema, 1) && "length" in schema.properties && IntoBooleanResult(Visit3(schema.properties["length"], length)) === ExtendsResult.True;
}
function IsObjectPromiseLike(schema) {
  const then = Function2([Any()], Any());
  return IsObjectPropertyCount(schema, 0) || IsObjectPropertyCount(schema, 1) && "then" in schema.properties && IntoBooleanResult(Visit3(schema.properties["then"], then)) === ExtendsResult.True;
}
function Property(left, right) {
  return Visit3(left, right) === ExtendsResult.False ? ExtendsResult.False : type_exports.IsOptional(left) && !type_exports.IsOptional(right) ? ExtendsResult.False : ExtendsResult.True;
}
function FromObjectRight(left, right) {
  return type_exports.IsUnknown(left) ? ExtendsResult.False : type_exports.IsAny(left) ? ExtendsResult.Union : type_exports.IsNever(left) || type_exports.IsLiteralString(left) && IsObjectStringLike(right) || type_exports.IsLiteralNumber(left) && IsObjectNumberLike(right) || type_exports.IsLiteralBoolean(left) && IsObjectBooleanLike(right) || type_exports.IsSymbol(left) && IsObjectSymbolLike(right) || type_exports.IsBigInt(left) && IsObjectBigIntLike(right) || type_exports.IsString(left) && IsObjectStringLike(right) || type_exports.IsSymbol(left) && IsObjectSymbolLike(right) || type_exports.IsNumber(left) && IsObjectNumberLike(right) || type_exports.IsInteger(left) && IsObjectNumberLike(right) || type_exports.IsBoolean(left) && IsObjectBooleanLike(right) || type_exports.IsUint8Array(left) && IsObjectUint8ArrayLike(right) || type_exports.IsDate(left) && IsObjectDateLike(right) || type_exports.IsConstructor(left) && IsObjectConstructorLike(right) || type_exports.IsFunction(left) && IsObjectFunctionLike(right) ? ExtendsResult.True : type_exports.IsRecord(left) && type_exports.IsString(RecordKey(left)) ? (() => {
    return right[Hint] === "Record" ? ExtendsResult.True : ExtendsResult.False;
  })() : type_exports.IsRecord(left) && type_exports.IsNumber(RecordKey(left)) ? (() => {
    return IsObjectPropertyCount(right, 0) ? ExtendsResult.True : ExtendsResult.False;
  })() : ExtendsResult.False;
}
function FromObject(left, right) {
  return IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsRecord(right) ? FromRecordRight(left, right) : !type_exports.IsObject(right) ? ExtendsResult.False : (() => {
    for (const key of Object.getOwnPropertyNames(right.properties)) {
      if (!(key in left.properties) && !type_exports.IsOptional(right.properties[key])) {
        return ExtendsResult.False;
      }
      if (type_exports.IsOptional(right.properties[key])) {
        return ExtendsResult.True;
      }
      if (Property(left.properties[key], right.properties[key]) === ExtendsResult.False) {
        return ExtendsResult.False;
      }
    }
    return ExtendsResult.True;
  })();
}
function FromPromise2(left, right) {
  return IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) && IsObjectPromiseLike(right) ? ExtendsResult.True : !type_exports.IsPromise(right) ? ExtendsResult.False : IntoBooleanResult(Visit3(left.item, right.item));
}
function RecordKey(schema) {
  return PatternNumberExact in schema.patternProperties ? Number2() : PatternStringExact in schema.patternProperties ? String2() : Throw("Unknown record key pattern");
}
function RecordValue(schema) {
  return PatternNumberExact in schema.patternProperties ? schema.patternProperties[PatternNumberExact] : PatternStringExact in schema.patternProperties ? schema.patternProperties[PatternStringExact] : Throw("Unable to get record value schema");
}
function FromRecordRight(left, right) {
  const [Key, Value] = [RecordKey(right), RecordValue(right)];
  return type_exports.IsLiteralString(left) && type_exports.IsNumber(Key) && IntoBooleanResult(Visit3(left, Value)) === ExtendsResult.True ? ExtendsResult.True : type_exports.IsUint8Array(left) && type_exports.IsNumber(Key) ? Visit3(left, Value) : type_exports.IsString(left) && type_exports.IsNumber(Key) ? Visit3(left, Value) : type_exports.IsArray(left) && type_exports.IsNumber(Key) ? Visit3(left, Value) : type_exports.IsObject(left) ? (() => {
    for (const key of Object.getOwnPropertyNames(left.properties)) {
      if (Property(Value, left.properties[key]) === ExtendsResult.False) {
        return ExtendsResult.False;
      }
    }
    return ExtendsResult.True;
  })() : ExtendsResult.False;
}
function FromRecord(left, right) {
  return IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : !type_exports.IsRecord(right) ? ExtendsResult.False : Visit3(RecordValue(left), RecordValue(right));
}
function FromRegExp(left, right) {
  const L3 = type_exports.IsRegExp(left) ? String2() : left;
  const R3 = type_exports.IsRegExp(right) ? String2() : right;
  return Visit3(L3, R3);
}
function FromStringRight(left, right) {
  return type_exports.IsLiteral(left) && value_exports.IsString(left.const) ? ExtendsResult.True : type_exports.IsString(left) ? ExtendsResult.True : ExtendsResult.False;
}
function FromString(left, right) {
  return IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : type_exports.IsRecord(right) ? FromRecordRight(left, right) : type_exports.IsString(right) ? ExtendsResult.True : ExtendsResult.False;
}
function FromSymbol(left, right) {
  return IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : type_exports.IsRecord(right) ? FromRecordRight(left, right) : type_exports.IsSymbol(right) ? ExtendsResult.True : ExtendsResult.False;
}
function FromTemplateLiteral2(left, right) {
  return type_exports.IsTemplateLiteral(left) ? Visit3(TemplateLiteralToUnion(left), right) : type_exports.IsTemplateLiteral(right) ? Visit3(left, TemplateLiteralToUnion(right)) : Throw("Invalid fallthrough for TemplateLiteral");
}
function IsArrayOfTuple(left, right) {
  return type_exports.IsArray(right) && left.items !== void 0 && left.items.every((schema) => Visit3(schema, right.items) === ExtendsResult.True);
}
function FromTupleRight(left, right) {
  return type_exports.IsNever(left) ? ExtendsResult.True : type_exports.IsUnknown(left) ? ExtendsResult.False : type_exports.IsAny(left) ? ExtendsResult.Union : ExtendsResult.False;
}
function FromTuple3(left, right) {
  return IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) && IsObjectArrayLike(right) ? ExtendsResult.True : type_exports.IsArray(right) && IsArrayOfTuple(left, right) ? ExtendsResult.True : !type_exports.IsTuple(right) ? ExtendsResult.False : value_exports.IsUndefined(left.items) && !value_exports.IsUndefined(right.items) || !value_exports.IsUndefined(left.items) && value_exports.IsUndefined(right.items) ? ExtendsResult.False : value_exports.IsUndefined(left.items) && !value_exports.IsUndefined(right.items) ? ExtendsResult.True : left.items.every((schema, index) => Visit3(schema, right.items[index]) === ExtendsResult.True) ? ExtendsResult.True : ExtendsResult.False;
}
function FromUint8Array(left, right) {
  return IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : type_exports.IsRecord(right) ? FromRecordRight(left, right) : type_exports.IsUint8Array(right) ? ExtendsResult.True : ExtendsResult.False;
}
function FromUndefined(left, right) {
  return IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : type_exports.IsRecord(right) ? FromRecordRight(left, right) : type_exports.IsVoid(right) ? FromVoidRight(left, right) : type_exports.IsUndefined(right) ? ExtendsResult.True : ExtendsResult.False;
}
function FromUnionRight(left, right) {
  return right.anyOf.some((schema) => Visit3(left, schema) === ExtendsResult.True) ? ExtendsResult.True : ExtendsResult.False;
}
function FromUnion6(left, right) {
  return left.anyOf.every((schema) => Visit3(schema, right) === ExtendsResult.True) ? ExtendsResult.True : ExtendsResult.False;
}
function FromUnknownRight(left, right) {
  return ExtendsResult.True;
}
function FromUnknown(left, right) {
  return type_exports.IsNever(right) ? FromNeverRight(left, right) : type_exports.IsIntersect(right) ? FromIntersectRight(left, right) : type_exports.IsUnion(right) ? FromUnionRight(left, right) : type_exports.IsAny(right) ? FromAnyRight(left, right) : type_exports.IsString(right) ? FromStringRight(left, right) : type_exports.IsNumber(right) ? FromNumberRight(left, right) : type_exports.IsInteger(right) ? FromIntegerRight(left, right) : type_exports.IsBoolean(right) ? FromBooleanRight(left, right) : type_exports.IsArray(right) ? FromArrayRight(left, right) : type_exports.IsTuple(right) ? FromTupleRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : type_exports.IsUnknown(right) ? ExtendsResult.True : ExtendsResult.False;
}
function FromVoidRight(left, right) {
  return type_exports.IsUndefined(left) ? ExtendsResult.True : type_exports.IsUndefined(left) ? ExtendsResult.True : ExtendsResult.False;
}
function FromVoid(left, right) {
  return type_exports.IsIntersect(right) ? FromIntersectRight(left, right) : type_exports.IsUnion(right) ? FromUnionRight(left, right) : type_exports.IsUnknown(right) ? FromUnknownRight(left, right) : type_exports.IsAny(right) ? FromAnyRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : type_exports.IsVoid(right) ? ExtendsResult.True : ExtendsResult.False;
}
function Visit3(left, right) {
  return (
    // resolvable
    type_exports.IsTemplateLiteral(left) || type_exports.IsTemplateLiteral(right) ? FromTemplateLiteral2(left, right) : type_exports.IsRegExp(left) || type_exports.IsRegExp(right) ? FromRegExp(left, right) : type_exports.IsNot(left) || type_exports.IsNot(right) ? FromNot(left, right) : (
      // standard
      type_exports.IsAny(left) ? FromAny(left, right) : type_exports.IsArray(left) ? FromArray4(left, right) : type_exports.IsBigInt(left) ? FromBigInt(left, right) : type_exports.IsBoolean(left) ? FromBoolean(left, right) : type_exports.IsAsyncIterator(left) ? FromAsyncIterator(left, right) : type_exports.IsConstructor(left) ? FromConstructor(left, right) : type_exports.IsDate(left) ? FromDate(left, right) : type_exports.IsFunction(left) ? FromFunction(left, right) : type_exports.IsInteger(left) ? FromInteger(left, right) : type_exports.IsIntersect(left) ? FromIntersect4(left, right) : type_exports.IsIterator(left) ? FromIterator(left, right) : type_exports.IsLiteral(left) ? FromLiteral2(left, right) : type_exports.IsNever(left) ? FromNever(left, right) : type_exports.IsNull(left) ? FromNull(left, right) : type_exports.IsNumber(left) ? FromNumber(left, right) : type_exports.IsObject(left) ? FromObject(left, right) : type_exports.IsRecord(left) ? FromRecord(left, right) : type_exports.IsString(left) ? FromString(left, right) : type_exports.IsSymbol(left) ? FromSymbol(left, right) : type_exports.IsTuple(left) ? FromTuple3(left, right) : type_exports.IsPromise(left) ? FromPromise2(left, right) : type_exports.IsUint8Array(left) ? FromUint8Array(left, right) : type_exports.IsUndefined(left) ? FromUndefined(left, right) : type_exports.IsUnion(left) ? FromUnion6(left, right) : type_exports.IsUnknown(left) ? FromUnknown(left, right) : type_exports.IsVoid(left) ? FromVoid(left, right) : Throw(`Unknown left type operand '${left[Kind]}'`)
    )
  );
}
function ExtendsCheck(left, right) {
  return Visit3(left, right);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/extends/extends-from-mapped-key.mjs
init_process_shim();

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/extends/extends.mjs
init_process_shim();

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/extends/extends-from-mapped-result.mjs
init_process_shim();
function FromProperties8(P3, Right, True, False, options) {
  const Acc = {};
  for (const K2 of globalThis.Object.getOwnPropertyNames(P3))
    Acc[K2] = Extends(P3[K2], Right, True, False, Clone(options));
  return Acc;
}
function FromMappedResult6(Left, Right, True, False, options) {
  return FromProperties8(Left.properties, Right, True, False, options);
}
function ExtendsFromMappedResult(Left, Right, True, False, options) {
  const P3 = FromMappedResult6(Left, Right, True, False, options);
  return MappedResult(P3);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/extends/extends.mjs
function ExtendsResolve(left, right, trueType, falseType) {
  const R3 = ExtendsCheck(left, right);
  return R3 === ExtendsResult.Union ? Union([trueType, falseType]) : R3 === ExtendsResult.True ? trueType : falseType;
}
function Extends(L3, R3, T3, F2, options) {
  return IsMappedResult(L3) ? ExtendsFromMappedResult(L3, R3, T3, F2, options) : IsMappedKey(L3) ? CreateType(ExtendsFromMappedKey(L3, R3, T3, F2, options)) : CreateType(ExtendsResolve(L3, R3, T3, F2), options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/extends/extends-from-mapped-key.mjs
function FromPropertyKey(K2, U2, L3, R3, options) {
  return {
    [K2]: Extends(Literal(K2), U2, L3, R3, Clone(options))
  };
}
function FromPropertyKeys(K2, U2, L3, R3, options) {
  return K2.reduce((Acc, LK) => {
    return { ...Acc, ...FromPropertyKey(LK, U2, L3, R3, options) };
  }, {});
}
function FromMappedKey2(K2, U2, L3, R3, options) {
  return FromPropertyKeys(K2.keys, U2, L3, R3, options);
}
function ExtendsFromMappedKey(T3, U2, L3, R3, options) {
  const P3 = FromMappedKey2(T3, U2, L3, R3, options);
  return MappedResult(P3);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/exclude/exclude-from-template-literal.mjs
init_process_shim();
function ExcludeFromTemplateLiteral(L3, R3) {
  return Exclude(TemplateLiteralToUnion(L3), R3);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/exclude/exclude.mjs
function ExcludeRest(L3, R3) {
  const excluded = L3.filter((inner2) => ExtendsCheck(inner2, R3) === ExtendsResult.False);
  return excluded.length === 1 ? excluded[0] : Union(excluded);
}
function Exclude(L3, R3, options = {}) {
  if (IsTemplateLiteral(L3))
    return CreateType(ExcludeFromTemplateLiteral(L3, R3), options);
  if (IsMappedResult(L3))
    return CreateType(ExcludeFromMappedResult(L3, R3), options);
  return CreateType(IsUnion(L3) ? ExcludeRest(L3.anyOf, R3) : ExtendsCheck(L3, R3) !== ExtendsResult.False ? Never() : L3, options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/exclude/exclude-from-mapped-result.mjs
function FromProperties9(P3, U2) {
  const Acc = {};
  for (const K2 of globalThis.Object.getOwnPropertyNames(P3))
    Acc[K2] = Exclude(P3[K2], U2);
  return Acc;
}
function FromMappedResult7(R3, T3) {
  return FromProperties9(R3.properties, T3);
}
function ExcludeFromMappedResult(R3, T3) {
  const P3 = FromMappedResult7(R3, T3);
  return MappedResult(P3);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/extract/extract-from-mapped-result.mjs
init_process_shim();

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/extract/extract.mjs
init_process_shim();

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/extract/extract-from-template-literal.mjs
init_process_shim();
function ExtractFromTemplateLiteral(L3, R3) {
  return Extract(TemplateLiteralToUnion(L3), R3);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/extract/extract.mjs
function ExtractRest(L3, R3) {
  const extracted = L3.filter((inner2) => ExtendsCheck(inner2, R3) !== ExtendsResult.False);
  return extracted.length === 1 ? extracted[0] : Union(extracted);
}
function Extract(L3, R3, options) {
  if (IsTemplateLiteral(L3))
    return CreateType(ExtractFromTemplateLiteral(L3, R3), options);
  if (IsMappedResult(L3))
    return CreateType(ExtractFromMappedResult(L3, R3), options);
  return CreateType(IsUnion(L3) ? ExtractRest(L3.anyOf, R3) : ExtendsCheck(L3, R3) !== ExtendsResult.False ? L3 : Never(), options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/extract/extract-from-mapped-result.mjs
function FromProperties10(P3, T3) {
  const Acc = {};
  for (const K2 of globalThis.Object.getOwnPropertyNames(P3))
    Acc[K2] = Extract(P3[K2], T3);
  return Acc;
}
function FromMappedResult8(R3, T3) {
  return FromProperties10(R3.properties, T3);
}
function ExtractFromMappedResult(R3, T3) {
  const P3 = FromMappedResult8(R3, T3);
  return MappedResult(P3);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/instance-type/instance-type.mjs
init_process_shim();
function InstanceType(schema, options) {
  return IsConstructor(schema) ? CreateType(schema.returns, options) : Never(options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/instantiate/instantiate.mjs
init_process_shim();

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/readonly-optional/readonly-optional.mjs
init_process_shim();
function ReadonlyOptional(schema) {
  return Readonly(Optional(schema));
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/record/record.mjs
init_process_shim();
function RecordCreateFromPattern(pattern, T3, options) {
  return CreateType({ [Kind]: "Record", type: "object", patternProperties: { [pattern]: T3 } }, options);
}
function RecordCreateFromKeys(K2, T3, options) {
  const result = {};
  for (const K22 of K2)
    result[K22] = T3;
  return Object2(result, { ...options, [Hint]: "Record" });
}
function FromTemplateLiteralKey(K2, T3, options) {
  return IsTemplateLiteralFinite(K2) ? RecordCreateFromKeys(IndexPropertyKeys(K2), T3, options) : RecordCreateFromPattern(K2.pattern, T3, options);
}
function FromUnionKey(key, type, options) {
  return RecordCreateFromKeys(IndexPropertyKeys(Union(key)), type, options);
}
function FromLiteralKey(key, type, options) {
  return RecordCreateFromKeys([key.toString()], type, options);
}
function FromRegExpKey(key, type, options) {
  return RecordCreateFromPattern(key.source, type, options);
}
function FromStringKey(key, type, options) {
  const pattern = IsUndefined(key.pattern) ? PatternStringExact : key.pattern;
  return RecordCreateFromPattern(pattern, type, options);
}
function FromAnyKey(_3, type, options) {
  return RecordCreateFromPattern(PatternStringExact, type, options);
}
function FromNeverKey(_key, type, options) {
  return RecordCreateFromPattern(PatternNeverExact, type, options);
}
function FromBooleanKey(_key, type, options) {
  return Object2({ true: type, false: type }, options);
}
function FromIntegerKey(_key, type, options) {
  return RecordCreateFromPattern(PatternNumberExact, type, options);
}
function FromNumberKey(_3, type, options) {
  return RecordCreateFromPattern(PatternNumberExact, type, options);
}
function Record(key, type, options = {}) {
  return IsUnion(key) ? FromUnionKey(key.anyOf, type, options) : IsTemplateLiteral(key) ? FromTemplateLiteralKey(key, type, options) : IsLiteral(key) ? FromLiteralKey(key.const, type, options) : IsBoolean2(key) ? FromBooleanKey(key, type, options) : IsInteger(key) ? FromIntegerKey(key, type, options) : IsNumber3(key) ? FromNumberKey(key, type, options) : IsRegExp2(key) ? FromRegExpKey(key, type, options) : IsString2(key) ? FromStringKey(key, type, options) : IsAny(key) ? FromAnyKey(key, type, options) : IsNever(key) ? FromNeverKey(key, type, options) : Never(options);
}
function RecordPattern(record) {
  return globalThis.Object.getOwnPropertyNames(record.patternProperties)[0];
}
function RecordKey2(type) {
  const pattern = RecordPattern(type);
  return pattern === PatternStringExact ? String2() : pattern === PatternNumberExact ? Number2() : String2({ pattern });
}
function RecordValue2(type) {
  return type.patternProperties[RecordPattern(type)];
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/instantiate/instantiate.mjs
function FromConstructor2(args, type) {
  type.parameters = FromTypes(args, type.parameters);
  type.returns = FromType(args, type.returns);
  return type;
}
function FromFunction2(args, type) {
  type.parameters = FromTypes(args, type.parameters);
  type.returns = FromType(args, type.returns);
  return type;
}
function FromIntersect5(args, type) {
  type.allOf = FromTypes(args, type.allOf);
  return type;
}
function FromUnion7(args, type) {
  type.anyOf = FromTypes(args, type.anyOf);
  return type;
}
function FromTuple4(args, type) {
  if (IsUndefined(type.items))
    return type;
  type.items = FromTypes(args, type.items);
  return type;
}
function FromArray5(args, type) {
  type.items = FromType(args, type.items);
  return type;
}
function FromAsyncIterator2(args, type) {
  type.items = FromType(args, type.items);
  return type;
}
function FromIterator2(args, type) {
  type.items = FromType(args, type.items);
  return type;
}
function FromPromise3(args, type) {
  type.item = FromType(args, type.item);
  return type;
}
function FromObject2(args, type) {
  const mappedProperties = FromProperties11(args, type.properties);
  return { ...type, ...Object2(mappedProperties) };
}
function FromRecord2(args, type) {
  const mappedKey = FromType(args, RecordKey2(type));
  const mappedValue = FromType(args, RecordValue2(type));
  const result = Record(mappedKey, mappedValue);
  return { ...type, ...result };
}
function FromArgument(args, argument) {
  return argument.index in args ? args[argument.index] : Unknown();
}
function FromProperty2(args, type) {
  const isReadonly = IsReadonly(type);
  const isOptional = IsOptional(type);
  const mapped = FromType(args, type);
  return isReadonly && isOptional ? ReadonlyOptional(mapped) : isReadonly && !isOptional ? Readonly(mapped) : !isReadonly && isOptional ? Optional(mapped) : mapped;
}
function FromProperties11(args, properties) {
  return globalThis.Object.getOwnPropertyNames(properties).reduce((result, key) => {
    return { ...result, [key]: FromProperty2(args, properties[key]) };
  }, {});
}
function FromTypes(args, types2) {
  return types2.map((type) => FromType(args, type));
}
function FromType(args, type) {
  return IsConstructor(type) ? FromConstructor2(args, type) : IsFunction2(type) ? FromFunction2(args, type) : IsIntersect(type) ? FromIntersect5(args, type) : IsUnion(type) ? FromUnion7(args, type) : IsTuple(type) ? FromTuple4(args, type) : IsArray3(type) ? FromArray5(args, type) : IsAsyncIterator2(type) ? FromAsyncIterator2(args, type) : IsIterator2(type) ? FromIterator2(args, type) : IsPromise(type) ? FromPromise3(args, type) : IsObject3(type) ? FromObject2(args, type) : IsRecord(type) ? FromRecord2(args, type) : IsArgument(type) ? FromArgument(args, type) : type;
}
function Instantiate(type, args) {
  return FromType(args, CloneType(type));
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/integer/integer.mjs
init_process_shim();
function Integer(options) {
  return CreateType({ [Kind]: "Integer", type: "integer" }, options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/intrinsic/capitalize.mjs
init_process_shim();

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/intrinsic/intrinsic.mjs
init_process_shim();

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/intrinsic/intrinsic-from-mapped-key.mjs
init_process_shim();
function MappedIntrinsicPropertyKey(K2, M4, options) {
  return {
    [K2]: Intrinsic(Literal(K2), M4, Clone(options))
  };
}
function MappedIntrinsicPropertyKeys(K2, M4, options) {
  const result = K2.reduce((Acc, L3) => {
    return { ...Acc, ...MappedIntrinsicPropertyKey(L3, M4, options) };
  }, {});
  return result;
}
function MappedIntrinsicProperties(T3, M4, options) {
  return MappedIntrinsicPropertyKeys(T3["keys"], M4, options);
}
function IntrinsicFromMappedKey(T3, M4, options) {
  const P3 = MappedIntrinsicProperties(T3, M4, options);
  return MappedResult(P3);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/intrinsic/intrinsic.mjs
function ApplyUncapitalize(value) {
  const [first, rest] = [value.slice(0, 1), value.slice(1)];
  return [first.toLowerCase(), rest].join("");
}
function ApplyCapitalize(value) {
  const [first, rest] = [value.slice(0, 1), value.slice(1)];
  return [first.toUpperCase(), rest].join("");
}
function ApplyUppercase(value) {
  return value.toUpperCase();
}
function ApplyLowercase(value) {
  return value.toLowerCase();
}
function FromTemplateLiteral3(schema, mode, options) {
  const expression = TemplateLiteralParseExact(schema.pattern);
  const finite = IsTemplateLiteralExpressionFinite(expression);
  if (!finite)
    return { ...schema, pattern: FromLiteralValue(schema.pattern, mode) };
  const strings = [...TemplateLiteralExpressionGenerate(expression)];
  const literals = strings.map((value) => Literal(value));
  const mapped = FromRest5(literals, mode);
  const union = Union(mapped);
  return TemplateLiteral([union], options);
}
function FromLiteralValue(value, mode) {
  return typeof value === "string" ? mode === "Uncapitalize" ? ApplyUncapitalize(value) : mode === "Capitalize" ? ApplyCapitalize(value) : mode === "Uppercase" ? ApplyUppercase(value) : mode === "Lowercase" ? ApplyLowercase(value) : value : value.toString();
}
function FromRest5(T3, M4) {
  return T3.map((L3) => Intrinsic(L3, M4));
}
function Intrinsic(schema, mode, options = {}) {
  return (
    // Intrinsic-Mapped-Inference
    IsMappedKey(schema) ? IntrinsicFromMappedKey(schema, mode, options) : (
      // Standard-Inference
      IsTemplateLiteral(schema) ? FromTemplateLiteral3(schema, mode, options) : IsUnion(schema) ? Union(FromRest5(schema.anyOf, mode), options) : IsLiteral(schema) ? Literal(FromLiteralValue(schema.const, mode), options) : (
        // Default Type
        CreateType(schema, options)
      )
    )
  );
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/intrinsic/capitalize.mjs
function Capitalize(T3, options = {}) {
  return Intrinsic(T3, "Capitalize", options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/intrinsic/lowercase.mjs
init_process_shim();
function Lowercase(T3, options = {}) {
  return Intrinsic(T3, "Lowercase", options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/intrinsic/uncapitalize.mjs
init_process_shim();
function Uncapitalize(T3, options = {}) {
  return Intrinsic(T3, "Uncapitalize", options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/intrinsic/uppercase.mjs
init_process_shim();
function Uppercase(T3, options = {}) {
  return Intrinsic(T3, "Uppercase", options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/module/module.mjs
init_process_shim();

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/module/compute.mjs
init_process_shim();

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/omit/omit-from-mapped-key.mjs
init_process_shim();

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/omit/omit.mjs
init_process_shim();

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/omit/omit-from-mapped-result.mjs
init_process_shim();
function FromProperties12(properties, propertyKeys, options) {
  const result = {};
  for (const K2 of globalThis.Object.getOwnPropertyNames(properties))
    result[K2] = Omit(properties[K2], propertyKeys, Clone(options));
  return result;
}
function FromMappedResult9(mappedResult, propertyKeys, options) {
  return FromProperties12(mappedResult.properties, propertyKeys, options);
}
function OmitFromMappedResult(mappedResult, propertyKeys, options) {
  const properties = FromMappedResult9(mappedResult, propertyKeys, options);
  return MappedResult(properties);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/omit/omit.mjs
function FromIntersect6(types2, propertyKeys) {
  return types2.map((type) => OmitResolve(type, propertyKeys));
}
function FromUnion8(types2, propertyKeys) {
  return types2.map((type) => OmitResolve(type, propertyKeys));
}
function FromProperty3(properties, key) {
  const { [key]: _3, ...R3 } = properties;
  return R3;
}
function FromProperties13(properties, propertyKeys) {
  return propertyKeys.reduce((T3, K2) => FromProperty3(T3, K2), properties);
}
function FromObject3(type, propertyKeys, properties) {
  const options = Discard(type, [TransformKind, "$id", "required", "properties"]);
  const mappedProperties = FromProperties13(properties, propertyKeys);
  return Object2(mappedProperties, options);
}
function UnionFromPropertyKeys(propertyKeys) {
  const result = propertyKeys.reduce((result2, key) => IsLiteralValue(key) ? [...result2, Literal(key)] : result2, []);
  return Union(result);
}
function OmitResolve(type, propertyKeys) {
  return IsIntersect(type) ? Intersect(FromIntersect6(type.allOf, propertyKeys)) : IsUnion(type) ? Union(FromUnion8(type.anyOf, propertyKeys)) : IsObject3(type) ? FromObject3(type, propertyKeys, type.properties) : Object2({});
}
function Omit(type, key, options) {
  const typeKey = IsArray(key) ? UnionFromPropertyKeys(key) : key;
  const propertyKeys = IsSchema(key) ? IndexPropertyKeys(key) : key;
  const isTypeRef = IsRef(type);
  const isKeyRef = IsRef(key);
  return IsMappedResult(type) ? OmitFromMappedResult(type, propertyKeys, options) : IsMappedKey(key) ? OmitFromMappedKey(type, key, options) : isTypeRef && isKeyRef ? Computed("Omit", [type, typeKey], options) : !isTypeRef && isKeyRef ? Computed("Omit", [type, typeKey], options) : isTypeRef && !isKeyRef ? Computed("Omit", [type, typeKey], options) : CreateType({ ...OmitResolve(type, propertyKeys), ...options });
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/omit/omit-from-mapped-key.mjs
function FromPropertyKey2(type, key, options) {
  return { [key]: Omit(type, [key], Clone(options)) };
}
function FromPropertyKeys2(type, propertyKeys, options) {
  return propertyKeys.reduce((Acc, LK) => {
    return { ...Acc, ...FromPropertyKey2(type, LK, options) };
  }, {});
}
function FromMappedKey3(type, mappedKey, options) {
  return FromPropertyKeys2(type, mappedKey.keys, options);
}
function OmitFromMappedKey(type, mappedKey, options) {
  const properties = FromMappedKey3(type, mappedKey, options);
  return MappedResult(properties);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/pick/pick-from-mapped-key.mjs
init_process_shim();

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/pick/pick.mjs
init_process_shim();

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/pick/pick-from-mapped-result.mjs
init_process_shim();
function FromProperties14(properties, propertyKeys, options) {
  const result = {};
  for (const K2 of globalThis.Object.getOwnPropertyNames(properties))
    result[K2] = Pick(properties[K2], propertyKeys, Clone(options));
  return result;
}
function FromMappedResult10(mappedResult, propertyKeys, options) {
  return FromProperties14(mappedResult.properties, propertyKeys, options);
}
function PickFromMappedResult(mappedResult, propertyKeys, options) {
  const properties = FromMappedResult10(mappedResult, propertyKeys, options);
  return MappedResult(properties);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/pick/pick.mjs
function FromIntersect7(types2, propertyKeys) {
  return types2.map((type) => PickResolve(type, propertyKeys));
}
function FromUnion9(types2, propertyKeys) {
  return types2.map((type) => PickResolve(type, propertyKeys));
}
function FromProperties15(properties, propertyKeys) {
  const result = {};
  for (const K2 of propertyKeys)
    if (K2 in properties)
      result[K2] = properties[K2];
  return result;
}
function FromObject4(Type4, keys2, properties) {
  const options = Discard(Type4, [TransformKind, "$id", "required", "properties"]);
  const mappedProperties = FromProperties15(properties, keys2);
  return Object2(mappedProperties, options);
}
function UnionFromPropertyKeys2(propertyKeys) {
  const result = propertyKeys.reduce((result2, key) => IsLiteralValue(key) ? [...result2, Literal(key)] : result2, []);
  return Union(result);
}
function PickResolve(type, propertyKeys) {
  return IsIntersect(type) ? Intersect(FromIntersect7(type.allOf, propertyKeys)) : IsUnion(type) ? Union(FromUnion9(type.anyOf, propertyKeys)) : IsObject3(type) ? FromObject4(type, propertyKeys, type.properties) : Object2({});
}
function Pick(type, key, options) {
  const typeKey = IsArray(key) ? UnionFromPropertyKeys2(key) : key;
  const propertyKeys = IsSchema(key) ? IndexPropertyKeys(key) : key;
  const isTypeRef = IsRef(type);
  const isKeyRef = IsRef(key);
  return IsMappedResult(type) ? PickFromMappedResult(type, propertyKeys, options) : IsMappedKey(key) ? PickFromMappedKey(type, key, options) : isTypeRef && isKeyRef ? Computed("Pick", [type, typeKey], options) : !isTypeRef && isKeyRef ? Computed("Pick", [type, typeKey], options) : isTypeRef && !isKeyRef ? Computed("Pick", [type, typeKey], options) : CreateType({ ...PickResolve(type, propertyKeys), ...options });
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/pick/pick-from-mapped-key.mjs
function FromPropertyKey3(type, key, options) {
  return {
    [key]: Pick(type, [key], Clone(options))
  };
}
function FromPropertyKeys3(type, propertyKeys, options) {
  return propertyKeys.reduce((result, leftKey) => {
    return { ...result, ...FromPropertyKey3(type, leftKey, options) };
  }, {});
}
function FromMappedKey4(type, mappedKey, options) {
  return FromPropertyKeys3(type, mappedKey.keys, options);
}
function PickFromMappedKey(type, mappedKey, options) {
  const properties = FromMappedKey4(type, mappedKey, options);
  return MappedResult(properties);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/partial/partial-from-mapped-result.mjs
init_process_shim();

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/partial/partial.mjs
init_process_shim();
function FromComputed3(target, parameters) {
  return Computed("Partial", [Computed(target, parameters)]);
}
function FromRef3($ref) {
  return Computed("Partial", [Ref($ref)]);
}
function FromProperties16(properties) {
  const partialProperties = {};
  for (const K2 of globalThis.Object.getOwnPropertyNames(properties))
    partialProperties[K2] = Optional(properties[K2]);
  return partialProperties;
}
function FromObject5(type, properties) {
  const options = Discard(type, [TransformKind, "$id", "required", "properties"]);
  const mappedProperties = FromProperties16(properties);
  return Object2(mappedProperties, options);
}
function FromRest6(types2) {
  return types2.map((type) => PartialResolve(type));
}
function PartialResolve(type) {
  return (
    // Mappable
    IsComputed(type) ? FromComputed3(type.target, type.parameters) : IsRef(type) ? FromRef3(type.$ref) : IsIntersect(type) ? Intersect(FromRest6(type.allOf)) : IsUnion(type) ? Union(FromRest6(type.anyOf)) : IsObject3(type) ? FromObject5(type, type.properties) : (
      // Intrinsic
      IsBigInt2(type) ? type : IsBoolean2(type) ? type : IsInteger(type) ? type : IsLiteral(type) ? type : IsNull2(type) ? type : IsNumber3(type) ? type : IsString2(type) ? type : IsSymbol2(type) ? type : IsUndefined3(type) ? type : (
        // Passthrough
        Object2({})
      )
    )
  );
}
function Partial(type, options) {
  if (IsMappedResult(type)) {
    return PartialFromMappedResult(type, options);
  } else {
    return CreateType({ ...PartialResolve(type), ...options });
  }
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/partial/partial-from-mapped-result.mjs
function FromProperties17(K2, options) {
  const Acc = {};
  for (const K22 of globalThis.Object.getOwnPropertyNames(K2))
    Acc[K22] = Partial(K2[K22], Clone(options));
  return Acc;
}
function FromMappedResult11(R3, options) {
  return FromProperties17(R3.properties, options);
}
function PartialFromMappedResult(R3, options) {
  const P3 = FromMappedResult11(R3, options);
  return MappedResult(P3);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/required/required-from-mapped-result.mjs
init_process_shim();

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/required/required.mjs
init_process_shim();
function FromComputed4(target, parameters) {
  return Computed("Required", [Computed(target, parameters)]);
}
function FromRef4($ref) {
  return Computed("Required", [Ref($ref)]);
}
function FromProperties18(properties) {
  const requiredProperties = {};
  for (const K2 of globalThis.Object.getOwnPropertyNames(properties))
    requiredProperties[K2] = Discard(properties[K2], [OptionalKind]);
  return requiredProperties;
}
function FromObject6(type, properties) {
  const options = Discard(type, [TransformKind, "$id", "required", "properties"]);
  const mappedProperties = FromProperties18(properties);
  return Object2(mappedProperties, options);
}
function FromRest7(types2) {
  return types2.map((type) => RequiredResolve(type));
}
function RequiredResolve(type) {
  return (
    // Mappable
    IsComputed(type) ? FromComputed4(type.target, type.parameters) : IsRef(type) ? FromRef4(type.$ref) : IsIntersect(type) ? Intersect(FromRest7(type.allOf)) : IsUnion(type) ? Union(FromRest7(type.anyOf)) : IsObject3(type) ? FromObject6(type, type.properties) : (
      // Intrinsic
      IsBigInt2(type) ? type : IsBoolean2(type) ? type : IsInteger(type) ? type : IsLiteral(type) ? type : IsNull2(type) ? type : IsNumber3(type) ? type : IsString2(type) ? type : IsSymbol2(type) ? type : IsUndefined3(type) ? type : (
        // Passthrough
        Object2({})
      )
    )
  );
}
function Required(type, options) {
  if (IsMappedResult(type)) {
    return RequiredFromMappedResult(type, options);
  } else {
    return CreateType({ ...RequiredResolve(type), ...options });
  }
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/required/required-from-mapped-result.mjs
function FromProperties19(P3, options) {
  const Acc = {};
  for (const K2 of globalThis.Object.getOwnPropertyNames(P3))
    Acc[K2] = Required(P3[K2], options);
  return Acc;
}
function FromMappedResult12(R3, options) {
  return FromProperties19(R3.properties, options);
}
function RequiredFromMappedResult(R3, options) {
  const P3 = FromMappedResult12(R3, options);
  return MappedResult(P3);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/module/compute.mjs
function DereferenceParameters(moduleProperties, types2) {
  return types2.map((type) => {
    return IsRef(type) ? Dereference(moduleProperties, type.$ref) : FromType2(moduleProperties, type);
  });
}
function Dereference(moduleProperties, ref) {
  return ref in moduleProperties ? IsRef(moduleProperties[ref]) ? Dereference(moduleProperties, moduleProperties[ref].$ref) : FromType2(moduleProperties, moduleProperties[ref]) : Never();
}
function FromAwaited(parameters) {
  return Awaited(parameters[0]);
}
function FromIndex(parameters) {
  return Index(parameters[0], parameters[1]);
}
function FromKeyOf(parameters) {
  return KeyOf(parameters[0]);
}
function FromPartial(parameters) {
  return Partial(parameters[0]);
}
function FromOmit(parameters) {
  return Omit(parameters[0], parameters[1]);
}
function FromPick(parameters) {
  return Pick(parameters[0], parameters[1]);
}
function FromRequired(parameters) {
  return Required(parameters[0]);
}
function FromComputed5(moduleProperties, target, parameters) {
  const dereferenced = DereferenceParameters(moduleProperties, parameters);
  return target === "Awaited" ? FromAwaited(dereferenced) : target === "Index" ? FromIndex(dereferenced) : target === "KeyOf" ? FromKeyOf(dereferenced) : target === "Partial" ? FromPartial(dereferenced) : target === "Omit" ? FromOmit(dereferenced) : target === "Pick" ? FromPick(dereferenced) : target === "Required" ? FromRequired(dereferenced) : Never();
}
function FromArray6(moduleProperties, type) {
  return Array2(FromType2(moduleProperties, type));
}
function FromAsyncIterator3(moduleProperties, type) {
  return AsyncIterator2(FromType2(moduleProperties, type));
}
function FromConstructor3(moduleProperties, parameters, instanceType) {
  return Constructor(FromTypes2(moduleProperties, parameters), FromType2(moduleProperties, instanceType));
}
function FromFunction3(moduleProperties, parameters, returnType) {
  return Function2(FromTypes2(moduleProperties, parameters), FromType2(moduleProperties, returnType));
}
function FromIntersect8(moduleProperties, types2) {
  return Intersect(FromTypes2(moduleProperties, types2));
}
function FromIterator3(moduleProperties, type) {
  return Iterator(FromType2(moduleProperties, type));
}
function FromObject7(moduleProperties, properties) {
  return Object2(globalThis.Object.keys(properties).reduce((result, key) => {
    return { ...result, [key]: FromType2(moduleProperties, properties[key]) };
  }, {}));
}
function FromRecord3(moduleProperties, type) {
  const [value, pattern] = [FromType2(moduleProperties, RecordValue2(type)), RecordPattern(type)];
  const result = CloneType(type);
  result.patternProperties[pattern] = value;
  return result;
}
function FromTransform(moduleProperties, transform) {
  return IsRef(transform) ? { ...Dereference(moduleProperties, transform.$ref), [TransformKind]: transform[TransformKind] } : transform;
}
function FromTuple5(moduleProperties, types2) {
  return Tuple(FromTypes2(moduleProperties, types2));
}
function FromUnion10(moduleProperties, types2) {
  return Union(FromTypes2(moduleProperties, types2));
}
function FromTypes2(moduleProperties, types2) {
  return types2.map((type) => FromType2(moduleProperties, type));
}
function FromType2(moduleProperties, type) {
  return (
    // Modifiers
    IsOptional(type) ? CreateType(FromType2(moduleProperties, Discard(type, [OptionalKind])), type) : IsReadonly(type) ? CreateType(FromType2(moduleProperties, Discard(type, [ReadonlyKind])), type) : (
      // Transform
      IsTransform(type) ? CreateType(FromTransform(moduleProperties, type), type) : (
        // Types
        IsArray3(type) ? CreateType(FromArray6(moduleProperties, type.items), type) : IsAsyncIterator2(type) ? CreateType(FromAsyncIterator3(moduleProperties, type.items), type) : IsComputed(type) ? CreateType(FromComputed5(moduleProperties, type.target, type.parameters)) : IsConstructor(type) ? CreateType(FromConstructor3(moduleProperties, type.parameters, type.returns), type) : IsFunction2(type) ? CreateType(FromFunction3(moduleProperties, type.parameters, type.returns), type) : IsIntersect(type) ? CreateType(FromIntersect8(moduleProperties, type.allOf), type) : IsIterator2(type) ? CreateType(FromIterator3(moduleProperties, type.items), type) : IsObject3(type) ? CreateType(FromObject7(moduleProperties, type.properties), type) : IsRecord(type) ? CreateType(FromRecord3(moduleProperties, type)) : IsTuple(type) ? CreateType(FromTuple5(moduleProperties, type.items || []), type) : IsUnion(type) ? CreateType(FromUnion10(moduleProperties, type.anyOf), type) : type
      )
    )
  );
}
function ComputeType(moduleProperties, key) {
  return key in moduleProperties ? FromType2(moduleProperties, moduleProperties[key]) : Never();
}
function ComputeModuleProperties(moduleProperties) {
  return globalThis.Object.getOwnPropertyNames(moduleProperties).reduce((result, key) => {
    return { ...result, [key]: ComputeType(moduleProperties, key) };
  }, {});
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/module/module.mjs
var TModule = class {
  constructor($defs) {
    const computed = ComputeModuleProperties($defs);
    const identified = this.WithIdentifiers(computed);
    this.$defs = identified;
  }
  /** `[Json]` Imports a Type by Key. */
  Import(key, options) {
    const $defs = { ...this.$defs, [key]: CreateType(this.$defs[key], options) };
    return CreateType({ [Kind]: "Import", $defs, $ref: key });
  }
  // prettier-ignore
  WithIdentifiers($defs) {
    return globalThis.Object.getOwnPropertyNames($defs).reduce((result, key) => {
      return { ...result, [key]: { ...$defs[key], $id: key } };
    }, {});
  }
};
function Module(properties) {
  return new TModule(properties);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/not/not.mjs
init_process_shim();
function Not(type, options) {
  return CreateType({ [Kind]: "Not", not: type }, options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/parameters/parameters.mjs
init_process_shim();
function Parameters(schema, options) {
  return IsFunction2(schema) ? Tuple(schema.parameters, options) : Never();
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/recursive/recursive.mjs
init_process_shim();
var Ordinal = 0;
function Recursive(callback, options = {}) {
  if (IsUndefined(options.$id))
    options.$id = `T${Ordinal++}`;
  const thisType = CloneType(callback({ [Kind]: "This", $ref: `${options.$id}` }));
  thisType.$id = options.$id;
  return CreateType({ [Hint]: "Recursive", ...thisType }, options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/regexp/regexp.mjs
init_process_shim();
function RegExp2(unresolved, options) {
  const expr = IsString(unresolved) ? new globalThis.RegExp(unresolved) : unresolved;
  return CreateType({ [Kind]: "RegExp", type: "RegExp", source: expr.source, flags: expr.flags }, options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/rest/rest.mjs
init_process_shim();
function RestResolve(T3) {
  return IsIntersect(T3) ? T3.allOf : IsUnion(T3) ? T3.anyOf : IsTuple(T3) ? T3.items ?? [] : [];
}
function Rest(T3) {
  return RestResolve(T3);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/return-type/return-type.mjs
init_process_shim();
function ReturnType(schema, options) {
  return IsFunction2(schema) ? CreateType(schema.returns, options) : Never(options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/transform/transform.mjs
init_process_shim();
var TransformDecodeBuilder = class {
  constructor(schema) {
    this.schema = schema;
  }
  Decode(decode2) {
    return new TransformEncodeBuilder(this.schema, decode2);
  }
};
var TransformEncodeBuilder = class {
  constructor(schema, decode2) {
    this.schema = schema;
    this.decode = decode2;
  }
  EncodeTransform(encode2, schema) {
    const Encode = (value) => schema[TransformKind].Encode(encode2(value));
    const Decode = (value) => this.decode(schema[TransformKind].Decode(value));
    const Codec = { Encode, Decode };
    return { ...schema, [TransformKind]: Codec };
  }
  EncodeSchema(encode2, schema) {
    const Codec = { Decode: this.decode, Encode: encode2 };
    return { ...schema, [TransformKind]: Codec };
  }
  Encode(encode2) {
    return IsTransform(this.schema) ? this.EncodeTransform(encode2, this.schema) : this.EncodeSchema(encode2, this.schema);
  }
};
function Transform(schema) {
  return new TransformDecodeBuilder(schema);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/unsafe/unsafe.mjs
init_process_shim();
function Unsafe(options = {}) {
  return CreateType({ [Kind]: options[Kind] ?? "Unsafe" }, options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/void/void.mjs
init_process_shim();
function Void(options) {
  return CreateType({ [Kind]: "Void", type: "void" }, options);
}

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/type/index.mjs
init_process_shim();

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/type/type.mjs
var type_exports2 = {};
__export(type_exports2, {
  Any: () => Any,
  Argument: () => Argument,
  Array: () => Array2,
  AsyncIterator: () => AsyncIterator2,
  Awaited: () => Awaited,
  BigInt: () => BigInt2,
  Boolean: () => Boolean2,
  Capitalize: () => Capitalize,
  Composite: () => Composite,
  Const: () => Const,
  Constructor: () => Constructor,
  ConstructorParameters: () => ConstructorParameters,
  Date: () => Date2,
  Enum: () => Enum,
  Exclude: () => Exclude,
  Extends: () => Extends,
  Extract: () => Extract,
  Function: () => Function2,
  Index: () => Index,
  InstanceType: () => InstanceType,
  Instantiate: () => Instantiate,
  Integer: () => Integer,
  Intersect: () => Intersect,
  Iterator: () => Iterator,
  KeyOf: () => KeyOf,
  Literal: () => Literal,
  Lowercase: () => Lowercase,
  Mapped: () => Mapped,
  Module: () => Module,
  Never: () => Never,
  Not: () => Not,
  Null: () => Null,
  Number: () => Number2,
  Object: () => Object2,
  Omit: () => Omit,
  Optional: () => Optional,
  Parameters: () => Parameters,
  Partial: () => Partial,
  Pick: () => Pick,
  Promise: () => Promise2,
  Readonly: () => Readonly,
  ReadonlyOptional: () => ReadonlyOptional,
  Record: () => Record,
  Recursive: () => Recursive,
  Ref: () => Ref,
  RegExp: () => RegExp2,
  Required: () => Required,
  Rest: () => Rest,
  ReturnType: () => ReturnType,
  String: () => String2,
  Symbol: () => Symbol2,
  TemplateLiteral: () => TemplateLiteral,
  Transform: () => Transform,
  Tuple: () => Tuple,
  Uint8Array: () => Uint8Array2,
  Uncapitalize: () => Uncapitalize,
  Undefined: () => Undefined,
  Union: () => Union,
  Unknown: () => Unknown,
  Unsafe: () => Unsafe,
  Uppercase: () => Uppercase,
  Void: () => Void
});
init_process_shim();

// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/type/index.mjs
var Type = type_exports2;

// ../pi-mono/packages/ai/dist/api-registry.js
init_process_shim();
var apiProviderRegistry = /* @__PURE__ */ new Map();
function wrapStream(api, stream2) {
  return (model, context, options) => {
    if (model.api !== api) {
      throw new Error(`Mismatched api: ${model.api} expected ${api}`);
    }
    return stream2(model, context, options);
  };
}
function wrapStreamSimple(api, streamSimple2) {
  return (model, context, options) => {
    if (model.api !== api) {
      throw new Error(`Mismatched api: ${model.api} expected ${api}`);
    }
    return streamSimple2(model, context, options);
  };
}
function registerApiProvider(provider, sourceId) {
  apiProviderRegistry.set(provider.api, {
    provider: {
      api: provider.api,
      stream: wrapStream(provider.api, provider.stream),
      streamSimple: wrapStreamSimple(provider.api, provider.streamSimple)
    },
    sourceId
  });
}
function getApiProvider(api) {
  return apiProviderRegistry.get(api)?.provider;
}

// ../pi-mono/packages/ai/dist/env-api-keys.js
init_process_shim();
var _existsSync = null;
var _homedir = null;
var _join = null;
var dynamicImport = (specifier) => import(specifier);
var NODE_FS_SPECIFIER = "node:fs";
var NODE_OS_SPECIFIER = "node:os";
var NODE_PATH_SPECIFIER = "node:path";
if (typeof process !== "undefined" && (process.versions?.node || process.versions?.bun)) {
  dynamicImport(NODE_FS_SPECIFIER).then((m4) => {
    _existsSync = m4.existsSync;
  });
  dynamicImport(NODE_OS_SPECIFIER).then((m4) => {
    _homedir = m4.homedir;
  });
  dynamicImport(NODE_PATH_SPECIFIER).then((m4) => {
    _join = m4.join;
  });
}
var cachedVertexAdcCredentialsExists = null;
function hasVertexAdcCredentials() {
  if (cachedVertexAdcCredentialsExists === null) {
    if (!_existsSync || !_homedir || !_join) {
      const isNode = typeof process !== "undefined" && (process.versions?.node || process.versions?.bun);
      if (!isNode) {
        cachedVertexAdcCredentialsExists = false;
      }
      return false;
    }
    const gacPath = process.env.GOOGLE_APPLICATION_CREDENTIALS;
    if (gacPath) {
      cachedVertexAdcCredentialsExists = _existsSync(gacPath);
    } else {
      cachedVertexAdcCredentialsExists = _existsSync(_join(_homedir(), ".config", "gcloud", "application_default_credentials.json"));
    }
  }
  return cachedVertexAdcCredentialsExists;
}
function getEnvApiKey(provider) {
  if (provider === "github-copilot") {
    return process.env.COPILOT_GITHUB_TOKEN || process.env.GH_TOKEN || process.env.GITHUB_TOKEN;
  }
  if (provider === "anthropic") {
    return process.env.ANTHROPIC_OAUTH_TOKEN || process.env.ANTHROPIC_API_KEY;
  }
  if (provider === "google-vertex") {
    if (process.env.GOOGLE_CLOUD_API_KEY) {
      return process.env.GOOGLE_CLOUD_API_KEY;
    }
    const hasCredentials = hasVertexAdcCredentials();
    const hasProject = !!(process.env.GOOGLE_CLOUD_PROJECT || process.env.GCLOUD_PROJECT);
    const hasLocation = !!process.env.GOOGLE_CLOUD_LOCATION;
    if (hasCredentials && hasProject && hasLocation) {
      return "<authenticated>";
    }
  }
  if (provider === "amazon-bedrock") {
    if (process.env.AWS_PROFILE || process.env.AWS_ACCESS_KEY_ID && process.env.AWS_SECRET_ACCESS_KEY || process.env.AWS_BEARER_TOKEN_BEDROCK || process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI || process.env.AWS_CONTAINER_CREDENTIALS_FULL_URI || process.env.AWS_WEB_IDENTITY_TOKEN_FILE) {
      return "<authenticated>";
    }
  }
  const envMap = {
    openai: "OPENAI_API_KEY",
    "azure-openai-responses": "AZURE_OPENAI_API_KEY",
    google: "GEMINI_API_KEY",
    groq: "GROQ_API_KEY",
    cerebras: "CEREBRAS_API_KEY",
    xai: "XAI_API_KEY",
    openrouter: "OPENROUTER_API_KEY",
    "vercel-ai-gateway": "AI_GATEWAY_API_KEY",
    zai: "ZAI_API_KEY",
    mistral: "MISTRAL_API_KEY",
    minimax: "MINIMAX_API_KEY",
    "minimax-cn": "MINIMAX_CN_API_KEY",
    huggingface: "HF_TOKEN",
    opencode: "OPENCODE_API_KEY",
    "opencode-go": "OPENCODE_API_KEY",
    "kimi-coding": "KIMI_API_KEY"
  };
  const envVar = envMap[provider];
  return envVar ? process.env[envVar] : void 0;
}

// ../pi-mono/packages/ai/dist/models.js
init_process_shim();

// ../pi-mono/packages/ai/dist/models.generated.js
init_process_shim();
var MODELS = {
  "amazon-bedrock": {
    "amazon.nova-2-lite-v1:0": {
      id: "amazon.nova-2-lite-v1:0",
      name: "Nova 2 Lite",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.33,
        output: 2.75,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 4096
    },
    "amazon.nova-lite-v1:0": {
      id: "amazon.nova-lite-v1:0",
      name: "Nova Lite",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.06,
        output: 0.24,
        cacheRead: 0.015,
        cacheWrite: 0
      },
      contextWindow: 3e5,
      maxTokens: 8192
    },
    "amazon.nova-micro-v1:0": {
      id: "amazon.nova-micro-v1:0",
      name: "Nova Micro",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.035,
        output: 0.14,
        cacheRead: 875e-5,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 8192
    },
    "amazon.nova-premier-v1:0": {
      id: "amazon.nova-premier-v1:0",
      name: "Nova Premier",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 2.5,
        output: 12.5,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 1e6,
      maxTokens: 16384
    },
    "amazon.nova-pro-v1:0": {
      id: "amazon.nova-pro-v1:0",
      name: "Nova Pro",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.8,
        output: 3.2,
        cacheRead: 0.2,
        cacheWrite: 0
      },
      contextWindow: 3e5,
      maxTokens: 8192
    },
    "anthropic.claude-3-5-haiku-20241022-v1:0": {
      id: "anthropic.claude-3-5-haiku-20241022-v1:0",
      name: "Claude Haiku 3.5",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.8,
        output: 4,
        cacheRead: 0.08,
        cacheWrite: 1
      },
      contextWindow: 2e5,
      maxTokens: 8192
    },
    "anthropic.claude-3-5-sonnet-20240620-v1:0": {
      id: "anthropic.claude-3-5-sonnet-20240620-v1:0",
      name: "Claude Sonnet 3.5",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.3,
        cacheWrite: 3.75
      },
      contextWindow: 2e5,
      maxTokens: 8192
    },
    "anthropic.claude-3-5-sonnet-20241022-v2:0": {
      id: "anthropic.claude-3-5-sonnet-20241022-v2:0",
      name: "Claude Sonnet 3.5 v2",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.3,
        cacheWrite: 3.75
      },
      contextWindow: 2e5,
      maxTokens: 8192
    },
    "anthropic.claude-3-7-sonnet-20250219-v1:0": {
      id: "anthropic.claude-3-7-sonnet-20250219-v1:0",
      name: "Claude Sonnet 3.7",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.3,
        cacheWrite: 3.75
      },
      contextWindow: 2e5,
      maxTokens: 8192
    },
    "anthropic.claude-3-haiku-20240307-v1:0": {
      id: "anthropic.claude-3-haiku-20240307-v1:0",
      name: "Claude Haiku 3",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.25,
        output: 1.25,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 2e5,
      maxTokens: 4096
    },
    "anthropic.claude-haiku-4-5-20251001-v1:0": {
      id: "anthropic.claude-haiku-4-5-20251001-v1:0",
      name: "Claude Haiku 4.5",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1,
        output: 5,
        cacheRead: 0.1,
        cacheWrite: 1.25
      },
      contextWindow: 2e5,
      maxTokens: 64e3
    },
    "anthropic.claude-opus-4-1-20250805-v1:0": {
      id: "anthropic.claude-opus-4-1-20250805-v1:0",
      name: "Claude Opus 4.1",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 15,
        output: 75,
        cacheRead: 1.5,
        cacheWrite: 18.75
      },
      contextWindow: 2e5,
      maxTokens: 32e3
    },
    "anthropic.claude-opus-4-20250514-v1:0": {
      id: "anthropic.claude-opus-4-20250514-v1:0",
      name: "Claude Opus 4",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 15,
        output: 75,
        cacheRead: 1.5,
        cacheWrite: 18.75
      },
      contextWindow: 2e5,
      maxTokens: 32e3
    },
    "anthropic.claude-opus-4-5-20251101-v1:0": {
      id: "anthropic.claude-opus-4-5-20251101-v1:0",
      name: "Claude Opus 4.5",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 5,
        output: 25,
        cacheRead: 0.5,
        cacheWrite: 6.25
      },
      contextWindow: 2e5,
      maxTokens: 64e3
    },
    "anthropic.claude-opus-4-6-v1": {
      id: "anthropic.claude-opus-4-6-v1",
      name: "Claude Opus 4.6",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 5,
        output: 25,
        cacheRead: 0.5,
        cacheWrite: 6.25
      },
      contextWindow: 1e6,
      maxTokens: 128e3
    },
    "anthropic.claude-sonnet-4-20250514-v1:0": {
      id: "anthropic.claude-sonnet-4-20250514-v1:0",
      name: "Claude Sonnet 4",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.3,
        cacheWrite: 3.75
      },
      contextWindow: 2e5,
      maxTokens: 64e3
    },
    "anthropic.claude-sonnet-4-5-20250929-v1:0": {
      id: "anthropic.claude-sonnet-4-5-20250929-v1:0",
      name: "Claude Sonnet 4.5",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.3,
        cacheWrite: 3.75
      },
      contextWindow: 2e5,
      maxTokens: 64e3
    },
    "anthropic.claude-sonnet-4-6": {
      id: "anthropic.claude-sonnet-4-6",
      name: "Claude Sonnet 4.6",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.3,
        cacheWrite: 3.75
      },
      contextWindow: 1e6,
      maxTokens: 64e3
    },
    "deepseek.r1-v1:0": {
      id: "deepseek.r1-v1:0",
      name: "DeepSeek-R1",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 1.35,
        output: 5.4,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 32768
    },
    "deepseek.v3-v1:0": {
      id: "deepseek.v3-v1:0",
      name: "DeepSeek-V3.1",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.58,
        output: 1.68,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 163840,
      maxTokens: 81920
    },
    "deepseek.v3.2": {
      id: "deepseek.v3.2",
      name: "DeepSeek-V3.2",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.62,
        output: 1.85,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 163840,
      maxTokens: 81920
    },
    "eu.anthropic.claude-haiku-4-5-20251001-v1:0": {
      id: "eu.anthropic.claude-haiku-4-5-20251001-v1:0",
      name: "Claude Haiku 4.5 (EU)",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1,
        output: 5,
        cacheRead: 0.1,
        cacheWrite: 1.25
      },
      contextWindow: 2e5,
      maxTokens: 64e3
    },
    "eu.anthropic.claude-opus-4-5-20251101-v1:0": {
      id: "eu.anthropic.claude-opus-4-5-20251101-v1:0",
      name: "Claude Opus 4.5 (EU)",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 5,
        output: 25,
        cacheRead: 0.5,
        cacheWrite: 6.25
      },
      contextWindow: 2e5,
      maxTokens: 64e3
    },
    "eu.anthropic.claude-opus-4-6-v1": {
      id: "eu.anthropic.claude-opus-4-6-v1",
      name: "Claude Opus 4.6 (EU)",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 5,
        output: 25,
        cacheRead: 0.5,
        cacheWrite: 6.25
      },
      contextWindow: 1e6,
      maxTokens: 128e3
    },
    "eu.anthropic.claude-sonnet-4-20250514-v1:0": {
      id: "eu.anthropic.claude-sonnet-4-20250514-v1:0",
      name: "Claude Sonnet 4 (EU)",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.3,
        cacheWrite: 3.75
      },
      contextWindow: 2e5,
      maxTokens: 64e3
    },
    "eu.anthropic.claude-sonnet-4-5-20250929-v1:0": {
      id: "eu.anthropic.claude-sonnet-4-5-20250929-v1:0",
      name: "Claude Sonnet 4.5 (EU)",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.3,
        cacheWrite: 3.75
      },
      contextWindow: 2e5,
      maxTokens: 64e3
    },
    "eu.anthropic.claude-sonnet-4-6": {
      id: "eu.anthropic.claude-sonnet-4-6",
      name: "Claude Sonnet 4.6 (EU)",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.3,
        cacheWrite: 3.75
      },
      contextWindow: 1e6,
      maxTokens: 64e3
    },
    "global.anthropic.claude-haiku-4-5-20251001-v1:0": {
      id: "global.anthropic.claude-haiku-4-5-20251001-v1:0",
      name: "Claude Haiku 4.5 (Global)",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1,
        output: 5,
        cacheRead: 0.1,
        cacheWrite: 1.25
      },
      contextWindow: 2e5,
      maxTokens: 64e3
    },
    "global.anthropic.claude-opus-4-5-20251101-v1:0": {
      id: "global.anthropic.claude-opus-4-5-20251101-v1:0",
      name: "Claude Opus 4.5 (Global)",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 5,
        output: 25,
        cacheRead: 0.5,
        cacheWrite: 6.25
      },
      contextWindow: 2e5,
      maxTokens: 64e3
    },
    "global.anthropic.claude-opus-4-6-v1": {
      id: "global.anthropic.claude-opus-4-6-v1",
      name: "Claude Opus 4.6 (Global)",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 5,
        output: 25,
        cacheRead: 0.5,
        cacheWrite: 6.25
      },
      contextWindow: 1e6,
      maxTokens: 128e3
    },
    "global.anthropic.claude-sonnet-4-20250514-v1:0": {
      id: "global.anthropic.claude-sonnet-4-20250514-v1:0",
      name: "Claude Sonnet 4 (Global)",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.3,
        cacheWrite: 3.75
      },
      contextWindow: 2e5,
      maxTokens: 64e3
    },
    "global.anthropic.claude-sonnet-4-5-20250929-v1:0": {
      id: "global.anthropic.claude-sonnet-4-5-20250929-v1:0",
      name: "Claude Sonnet 4.5 (Global)",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.3,
        cacheWrite: 3.75
      },
      contextWindow: 2e5,
      maxTokens: 64e3
    },
    "global.anthropic.claude-sonnet-4-6": {
      id: "global.anthropic.claude-sonnet-4-6",
      name: "Claude Sonnet 4.6 (Global)",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.3,
        cacheWrite: 3.75
      },
      contextWindow: 1e6,
      maxTokens: 64e3
    },
    "google.gemma-3-27b-it": {
      id: "google.gemma-3-27b-it",
      name: "Google Gemma 3 27B Instruct",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.12,
        output: 0.2,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 202752,
      maxTokens: 8192
    },
    "google.gemma-3-4b-it": {
      id: "google.gemma-3-4b-it",
      name: "Gemma 3 4B IT",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.04,
        output: 0.08,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 4096
    },
    "meta.llama3-1-405b-instruct-v1:0": {
      id: "meta.llama3-1-405b-instruct-v1:0",
      name: "Llama 3.1 405B Instruct",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 2.4,
        output: 2.4,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 4096
    },
    "meta.llama3-1-70b-instruct-v1:0": {
      id: "meta.llama3-1-70b-instruct-v1:0",
      name: "Llama 3.1 70B Instruct",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.72,
        output: 0.72,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 4096
    },
    "meta.llama3-1-8b-instruct-v1:0": {
      id: "meta.llama3-1-8b-instruct-v1:0",
      name: "Llama 3.1 8B Instruct",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.22,
        output: 0.22,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 4096
    },
    "meta.llama3-2-11b-instruct-v1:0": {
      id: "meta.llama3-2-11b-instruct-v1:0",
      name: "Llama 3.2 11B Instruct",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.16,
        output: 0.16,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 4096
    },
    "meta.llama3-2-1b-instruct-v1:0": {
      id: "meta.llama3-2-1b-instruct-v1:0",
      name: "Llama 3.2 1B Instruct",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.1,
        output: 0.1,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131e3,
      maxTokens: 4096
    },
    "meta.llama3-2-3b-instruct-v1:0": {
      id: "meta.llama3-2-3b-instruct-v1:0",
      name: "Llama 3.2 3B Instruct",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.15,
        output: 0.15,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131e3,
      maxTokens: 4096
    },
    "meta.llama3-2-90b-instruct-v1:0": {
      id: "meta.llama3-2-90b-instruct-v1:0",
      name: "Llama 3.2 90B Instruct",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.72,
        output: 0.72,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 4096
    },
    "meta.llama3-3-70b-instruct-v1:0": {
      id: "meta.llama3-3-70b-instruct-v1:0",
      name: "Llama 3.3 70B Instruct",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.72,
        output: 0.72,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 4096
    },
    "meta.llama4-maverick-17b-instruct-v1:0": {
      id: "meta.llama4-maverick-17b-instruct-v1:0",
      name: "Llama 4 Maverick 17B Instruct",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.24,
        output: 0.97,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 1e6,
      maxTokens: 16384
    },
    "meta.llama4-scout-17b-instruct-v1:0": {
      id: "meta.llama4-scout-17b-instruct-v1:0",
      name: "Llama 4 Scout 17B Instruct",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.17,
        output: 0.66,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 35e5,
      maxTokens: 16384
    },
    "minimax.minimax-m2": {
      id: "minimax.minimax-m2",
      name: "MiniMax M2",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.3,
        output: 1.2,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 204608,
      maxTokens: 128e3
    },
    "minimax.minimax-m2.1": {
      id: "minimax.minimax-m2.1",
      name: "MiniMax M2.1",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.3,
        output: 1.2,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 204800,
      maxTokens: 131072
    },
    "mistral.devstral-2-123b": {
      id: "mistral.devstral-2-123b",
      name: "Devstral 2 123B",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.4,
        output: 2,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 256e3,
      maxTokens: 8192
    },
    "mistral.magistral-small-2509": {
      id: "mistral.magistral-small-2509",
      name: "Magistral Small 1.2",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.5,
        output: 1.5,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 4e4
    },
    "mistral.ministral-3-14b-instruct": {
      id: "mistral.ministral-3-14b-instruct",
      name: "Ministral 14B 3.0",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.2,
        output: 0.2,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 4096
    },
    "mistral.ministral-3-3b-instruct": {
      id: "mistral.ministral-3-3b-instruct",
      name: "Ministral 3 3B",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.1,
        output: 0.1,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 256e3,
      maxTokens: 8192
    },
    "mistral.ministral-3-8b-instruct": {
      id: "mistral.ministral-3-8b-instruct",
      name: "Ministral 3 8B",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.15,
        output: 0.15,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 4096
    },
    "mistral.mistral-large-3-675b-instruct": {
      id: "mistral.mistral-large-3-675b-instruct",
      name: "Mistral Large 3",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.5,
        output: 1.5,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 256e3,
      maxTokens: 8192
    },
    "mistral.pixtral-large-2502-v1:0": {
      id: "mistral.pixtral-large-2502-v1:0",
      name: "Pixtral Large (25.02)",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 2,
        output: 6,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 8192
    },
    "mistral.voxtral-mini-3b-2507": {
      id: "mistral.voxtral-mini-3b-2507",
      name: "Voxtral Mini 3B 2507",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.04,
        output: 0.04,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 4096
    },
    "mistral.voxtral-small-24b-2507": {
      id: "mistral.voxtral-small-24b-2507",
      name: "Voxtral Small 24B 2507",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.15,
        output: 0.35,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 32e3,
      maxTokens: 8192
    },
    "moonshot.kimi-k2-thinking": {
      id: "moonshot.kimi-k2-thinking",
      name: "Kimi K2 Thinking",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.6,
        output: 2.5,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 256e3,
      maxTokens: 256e3
    },
    "moonshotai.kimi-k2.5": {
      id: "moonshotai.kimi-k2.5",
      name: "Kimi K2.5",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.6,
        output: 3,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 256e3,
      maxTokens: 256e3
    },
    "nvidia.nemotron-nano-12b-v2": {
      id: "nvidia.nemotron-nano-12b-v2",
      name: "NVIDIA Nemotron Nano 12B v2 VL BF16",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.2,
        output: 0.6,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 4096
    },
    "nvidia.nemotron-nano-3-30b": {
      id: "nvidia.nemotron-nano-3-30b",
      name: "NVIDIA Nemotron Nano 3 30B",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.06,
        output: 0.24,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 4096
    },
    "nvidia.nemotron-nano-9b-v2": {
      id: "nvidia.nemotron-nano-9b-v2",
      name: "NVIDIA Nemotron Nano 9B v2",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.06,
        output: 0.23,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 4096
    },
    "openai.gpt-oss-120b-1:0": {
      id: "openai.gpt-oss-120b-1:0",
      name: "gpt-oss-120b",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.15,
        output: 0.6,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 4096
    },
    "openai.gpt-oss-20b-1:0": {
      id: "openai.gpt-oss-20b-1:0",
      name: "gpt-oss-20b",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.07,
        output: 0.3,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 4096
    },
    "openai.gpt-oss-safeguard-120b": {
      id: "openai.gpt-oss-safeguard-120b",
      name: "GPT OSS Safeguard 120B",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.15,
        output: 0.6,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 4096
    },
    "openai.gpt-oss-safeguard-20b": {
      id: "openai.gpt-oss-safeguard-20b",
      name: "GPT OSS Safeguard 20B",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.07,
        output: 0.2,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 4096
    },
    "qwen.qwen3-235b-a22b-2507-v1:0": {
      id: "qwen.qwen3-235b-a22b-2507-v1:0",
      name: "Qwen3 235B A22B 2507",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.22,
        output: 0.88,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 131072
    },
    "qwen.qwen3-32b-v1:0": {
      id: "qwen.qwen3-32b-v1:0",
      name: "Qwen3 32B (dense)",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.15,
        output: 0.6,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 16384,
      maxTokens: 16384
    },
    "qwen.qwen3-coder-30b-a3b-v1:0": {
      id: "qwen.qwen3-coder-30b-a3b-v1:0",
      name: "Qwen3 Coder 30B A3B Instruct",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.15,
        output: 0.6,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 131072
    },
    "qwen.qwen3-coder-480b-a35b-v1:0": {
      id: "qwen.qwen3-coder-480b-a35b-v1:0",
      name: "Qwen3 Coder 480B A35B Instruct",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.22,
        output: 1.8,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 65536
    },
    "qwen.qwen3-next-80b-a3b": {
      id: "qwen.qwen3-next-80b-a3b",
      name: "Qwen/Qwen3-Next-80B-A3B-Instruct",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.14,
        output: 1.4,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 262e3,
      maxTokens: 262e3
    },
    "qwen.qwen3-vl-235b-a22b": {
      id: "qwen.qwen3-vl-235b-a22b",
      name: "Qwen/Qwen3-VL-235B-A22B-Instruct",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.3,
        output: 1.5,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 262e3,
      maxTokens: 262e3
    },
    "us.anthropic.claude-haiku-4-5-20251001-v1:0": {
      id: "us.anthropic.claude-haiku-4-5-20251001-v1:0",
      name: "Claude Haiku 4.5 (US)",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1,
        output: 5,
        cacheRead: 0.1,
        cacheWrite: 1.25
      },
      contextWindow: 2e5,
      maxTokens: 64e3
    },
    "us.anthropic.claude-opus-4-1-20250805-v1:0": {
      id: "us.anthropic.claude-opus-4-1-20250805-v1:0",
      name: "Claude Opus 4.1 (US)",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 15,
        output: 75,
        cacheRead: 1.5,
        cacheWrite: 18.75
      },
      contextWindow: 2e5,
      maxTokens: 32e3
    },
    "us.anthropic.claude-opus-4-20250514-v1:0": {
      id: "us.anthropic.claude-opus-4-20250514-v1:0",
      name: "Claude Opus 4 (US)",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 15,
        output: 75,
        cacheRead: 1.5,
        cacheWrite: 18.75
      },
      contextWindow: 2e5,
      maxTokens: 32e3
    },
    "us.anthropic.claude-opus-4-5-20251101-v1:0": {
      id: "us.anthropic.claude-opus-4-5-20251101-v1:0",
      name: "Claude Opus 4.5 (US)",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 5,
        output: 25,
        cacheRead: 0.5,
        cacheWrite: 6.25
      },
      contextWindow: 2e5,
      maxTokens: 64e3
    },
    "us.anthropic.claude-opus-4-6-v1": {
      id: "us.anthropic.claude-opus-4-6-v1",
      name: "Claude Opus 4.6 (US)",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 5,
        output: 25,
        cacheRead: 0.5,
        cacheWrite: 6.25
      },
      contextWindow: 1e6,
      maxTokens: 128e3
    },
    "us.anthropic.claude-sonnet-4-20250514-v1:0": {
      id: "us.anthropic.claude-sonnet-4-20250514-v1:0",
      name: "Claude Sonnet 4 (US)",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.3,
        cacheWrite: 3.75
      },
      contextWindow: 2e5,
      maxTokens: 64e3
    },
    "us.anthropic.claude-sonnet-4-5-20250929-v1:0": {
      id: "us.anthropic.claude-sonnet-4-5-20250929-v1:0",
      name: "Claude Sonnet 4.5 (US)",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.3,
        cacheWrite: 3.75
      },
      contextWindow: 2e5,
      maxTokens: 64e3
    },
    "us.anthropic.claude-sonnet-4-6": {
      id: "us.anthropic.claude-sonnet-4-6",
      name: "Claude Sonnet 4.6 (US)",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.3,
        cacheWrite: 3.75
      },
      contextWindow: 1e6,
      maxTokens: 64e3
    },
    "writer.palmyra-x4-v1:0": {
      id: "writer.palmyra-x4-v1:0",
      name: "Palmyra X4",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 2.5,
        output: 10,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 122880,
      maxTokens: 8192
    },
    "writer.palmyra-x5-v1:0": {
      id: "writer.palmyra-x5-v1:0",
      name: "Palmyra X5",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.6,
        output: 6,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 104e4,
      maxTokens: 8192
    },
    "zai.glm-4.7": {
      id: "zai.glm-4.7",
      name: "GLM-4.7",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.6,
        output: 2.2,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 204800,
      maxTokens: 131072
    },
    "zai.glm-4.7-flash": {
      id: "zai.glm-4.7-flash",
      name: "GLM-4.7-Flash",
      api: "bedrock-converse-stream",
      provider: "amazon-bedrock",
      baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.07,
        output: 0.4,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 2e5,
      maxTokens: 131072
    }
  },
  "anthropic": {
    "claude-3-5-haiku-20241022": {
      id: "claude-3-5-haiku-20241022",
      name: "Claude Haiku 3.5",
      api: "anthropic-messages",
      provider: "anthropic",
      baseUrl: "https://api.anthropic.com",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.8,
        output: 4,
        cacheRead: 0.08,
        cacheWrite: 1
      },
      contextWindow: 2e5,
      maxTokens: 8192
    },
    "claude-3-5-haiku-latest": {
      id: "claude-3-5-haiku-latest",
      name: "Claude Haiku 3.5 (latest)",
      api: "anthropic-messages",
      provider: "anthropic",
      baseUrl: "https://api.anthropic.com",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.8,
        output: 4,
        cacheRead: 0.08,
        cacheWrite: 1
      },
      contextWindow: 2e5,
      maxTokens: 8192
    },
    "claude-3-5-sonnet-20240620": {
      id: "claude-3-5-sonnet-20240620",
      name: "Claude Sonnet 3.5",
      api: "anthropic-messages",
      provider: "anthropic",
      baseUrl: "https://api.anthropic.com",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.3,
        cacheWrite: 3.75
      },
      contextWindow: 2e5,
      maxTokens: 8192
    },
    "claude-3-5-sonnet-20241022": {
      id: "claude-3-5-sonnet-20241022",
      name: "Claude Sonnet 3.5 v2",
      api: "anthropic-messages",
      provider: "anthropic",
      baseUrl: "https://api.anthropic.com",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.3,
        cacheWrite: 3.75
      },
      contextWindow: 2e5,
      maxTokens: 8192
    },
    "claude-3-7-sonnet-20250219": {
      id: "claude-3-7-sonnet-20250219",
      name: "Claude Sonnet 3.7",
      api: "anthropic-messages",
      provider: "anthropic",
      baseUrl: "https://api.anthropic.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.3,
        cacheWrite: 3.75
      },
      contextWindow: 2e5,
      maxTokens: 64e3
    },
    "claude-3-7-sonnet-latest": {
      id: "claude-3-7-sonnet-latest",
      name: "Claude Sonnet 3.7 (latest)",
      api: "anthropic-messages",
      provider: "anthropic",
      baseUrl: "https://api.anthropic.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.3,
        cacheWrite: 3.75
      },
      contextWindow: 2e5,
      maxTokens: 64e3
    },
    "claude-3-haiku-20240307": {
      id: "claude-3-haiku-20240307",
      name: "Claude Haiku 3",
      api: "anthropic-messages",
      provider: "anthropic",
      baseUrl: "https://api.anthropic.com",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.25,
        output: 1.25,
        cacheRead: 0.03,
        cacheWrite: 0.3
      },
      contextWindow: 2e5,
      maxTokens: 4096
    },
    "claude-3-opus-20240229": {
      id: "claude-3-opus-20240229",
      name: "Claude Opus 3",
      api: "anthropic-messages",
      provider: "anthropic",
      baseUrl: "https://api.anthropic.com",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 15,
        output: 75,
        cacheRead: 1.5,
        cacheWrite: 18.75
      },
      contextWindow: 2e5,
      maxTokens: 4096
    },
    "claude-3-sonnet-20240229": {
      id: "claude-3-sonnet-20240229",
      name: "Claude Sonnet 3",
      api: "anthropic-messages",
      provider: "anthropic",
      baseUrl: "https://api.anthropic.com",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.3,
        cacheWrite: 0.3
      },
      contextWindow: 2e5,
      maxTokens: 4096
    },
    "claude-haiku-4-5": {
      id: "claude-haiku-4-5",
      name: "Claude Haiku 4.5 (latest)",
      api: "anthropic-messages",
      provider: "anthropic",
      baseUrl: "https://api.anthropic.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1,
        output: 5,
        cacheRead: 0.1,
        cacheWrite: 1.25
      },
      contextWindow: 2e5,
      maxTokens: 64e3
    },
    "claude-haiku-4-5-20251001": {
      id: "claude-haiku-4-5-20251001",
      name: "Claude Haiku 4.5",
      api: "anthropic-messages",
      provider: "anthropic",
      baseUrl: "https://api.anthropic.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1,
        output: 5,
        cacheRead: 0.1,
        cacheWrite: 1.25
      },
      contextWindow: 2e5,
      maxTokens: 64e3
    },
    "claude-opus-4-0": {
      id: "claude-opus-4-0",
      name: "Claude Opus 4 (latest)",
      api: "anthropic-messages",
      provider: "anthropic",
      baseUrl: "https://api.anthropic.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 15,
        output: 75,
        cacheRead: 1.5,
        cacheWrite: 18.75
      },
      contextWindow: 2e5,
      maxTokens: 32e3
    },
    "claude-opus-4-1": {
      id: "claude-opus-4-1",
      name: "Claude Opus 4.1 (latest)",
      api: "anthropic-messages",
      provider: "anthropic",
      baseUrl: "https://api.anthropic.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 15,
        output: 75,
        cacheRead: 1.5,
        cacheWrite: 18.75
      },
      contextWindow: 2e5,
      maxTokens: 32e3
    },
    "claude-opus-4-1-20250805": {
      id: "claude-opus-4-1-20250805",
      name: "Claude Opus 4.1",
      api: "anthropic-messages",
      provider: "anthropic",
      baseUrl: "https://api.anthropic.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 15,
        output: 75,
        cacheRead: 1.5,
        cacheWrite: 18.75
      },
      contextWindow: 2e5,
      maxTokens: 32e3
    },
    "claude-opus-4-20250514": {
      id: "claude-opus-4-20250514",
      name: "Claude Opus 4",
      api: "anthropic-messages",
      provider: "anthropic",
      baseUrl: "https://api.anthropic.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 15,
        output: 75,
        cacheRead: 1.5,
        cacheWrite: 18.75
      },
      contextWindow: 2e5,
      maxTokens: 32e3
    },
    "claude-opus-4-5": {
      id: "claude-opus-4-5",
      name: "Claude Opus 4.5 (latest)",
      api: "anthropic-messages",
      provider: "anthropic",
      baseUrl: "https://api.anthropic.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 5,
        output: 25,
        cacheRead: 0.5,
        cacheWrite: 6.25
      },
      contextWindow: 2e5,
      maxTokens: 64e3
    },
    "claude-opus-4-5-20251101": {
      id: "claude-opus-4-5-20251101",
      name: "Claude Opus 4.5",
      api: "anthropic-messages",
      provider: "anthropic",
      baseUrl: "https://api.anthropic.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 5,
        output: 25,
        cacheRead: 0.5,
        cacheWrite: 6.25
      },
      contextWindow: 2e5,
      maxTokens: 64e3
    },
    "claude-opus-4-6": {
      id: "claude-opus-4-6",
      name: "Claude Opus 4.6",
      api: "anthropic-messages",
      provider: "anthropic",
      baseUrl: "https://api.anthropic.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 5,
        output: 25,
        cacheRead: 0.5,
        cacheWrite: 6.25
      },
      contextWindow: 1e6,
      maxTokens: 128e3
    },
    "claude-sonnet-4-0": {
      id: "claude-sonnet-4-0",
      name: "Claude Sonnet 4 (latest)",
      api: "anthropic-messages",
      provider: "anthropic",
      baseUrl: "https://api.anthropic.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.3,
        cacheWrite: 3.75
      },
      contextWindow: 2e5,
      maxTokens: 64e3
    },
    "claude-sonnet-4-20250514": {
      id: "claude-sonnet-4-20250514",
      name: "Claude Sonnet 4",
      api: "anthropic-messages",
      provider: "anthropic",
      baseUrl: "https://api.anthropic.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.3,
        cacheWrite: 3.75
      },
      contextWindow: 2e5,
      maxTokens: 64e3
    },
    "claude-sonnet-4-5": {
      id: "claude-sonnet-4-5",
      name: "Claude Sonnet 4.5 (latest)",
      api: "anthropic-messages",
      provider: "anthropic",
      baseUrl: "https://api.anthropic.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.3,
        cacheWrite: 3.75
      },
      contextWindow: 2e5,
      maxTokens: 64e3
    },
    "claude-sonnet-4-5-20250929": {
      id: "claude-sonnet-4-5-20250929",
      name: "Claude Sonnet 4.5",
      api: "anthropic-messages",
      provider: "anthropic",
      baseUrl: "https://api.anthropic.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.3,
        cacheWrite: 3.75
      },
      contextWindow: 2e5,
      maxTokens: 64e3
    },
    "claude-sonnet-4-6": {
      id: "claude-sonnet-4-6",
      name: "Claude Sonnet 4.6",
      api: "anthropic-messages",
      provider: "anthropic",
      baseUrl: "https://api.anthropic.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.3,
        cacheWrite: 3.75
      },
      contextWindow: 1e6,
      maxTokens: 64e3
    }
  },
  "azure-openai-responses": {
    "codex-mini-latest": {
      id: "codex-mini-latest",
      name: "Codex Mini",
      api: "azure-openai-responses",
      provider: "azure-openai-responses",
      baseUrl: "",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 1.5,
        output: 6,
        cacheRead: 0.375,
        cacheWrite: 0
      },
      contextWindow: 2e5,
      maxTokens: 1e5
    },
    "gpt-4": {
      id: "gpt-4",
      name: "GPT-4",
      api: "azure-openai-responses",
      provider: "azure-openai-responses",
      baseUrl: "",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 30,
        output: 60,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 8192,
      maxTokens: 8192
    },
    "gpt-4-turbo": {
      id: "gpt-4-turbo",
      name: "GPT-4 Turbo",
      api: "azure-openai-responses",
      provider: "azure-openai-responses",
      baseUrl: "",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 10,
        output: 30,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 4096
    },
    "gpt-4.1": {
      id: "gpt-4.1",
      name: "GPT-4.1",
      api: "azure-openai-responses",
      provider: "azure-openai-responses",
      baseUrl: "",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 2,
        output: 8,
        cacheRead: 0.5,
        cacheWrite: 0
      },
      contextWindow: 1047576,
      maxTokens: 32768
    },
    "gpt-4.1-mini": {
      id: "gpt-4.1-mini",
      name: "GPT-4.1 mini",
      api: "azure-openai-responses",
      provider: "azure-openai-responses",
      baseUrl: "",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.4,
        output: 1.6,
        cacheRead: 0.1,
        cacheWrite: 0
      },
      contextWindow: 1047576,
      maxTokens: 32768
    },
    "gpt-4.1-nano": {
      id: "gpt-4.1-nano",
      name: "GPT-4.1 nano",
      api: "azure-openai-responses",
      provider: "azure-openai-responses",
      baseUrl: "",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.1,
        output: 0.4,
        cacheRead: 0.03,
        cacheWrite: 0
      },
      contextWindow: 1047576,
      maxTokens: 32768
    },
    "gpt-4o": {
      id: "gpt-4o",
      name: "GPT-4o",
      api: "azure-openai-responses",
      provider: "azure-openai-responses",
      baseUrl: "",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 2.5,
        output: 10,
        cacheRead: 1.25,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 16384
    },
    "gpt-4o-2024-05-13": {
      id: "gpt-4o-2024-05-13",
      name: "GPT-4o (2024-05-13)",
      api: "azure-openai-responses",
      provider: "azure-openai-responses",
      baseUrl: "",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 5,
        output: 15,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 4096
    },
    "gpt-4o-2024-08-06": {
      id: "gpt-4o-2024-08-06",
      name: "GPT-4o (2024-08-06)",
      api: "azure-openai-responses",
      provider: "azure-openai-responses",
      baseUrl: "",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 2.5,
        output: 10,
        cacheRead: 1.25,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 16384
    },
    "gpt-4o-2024-11-20": {
      id: "gpt-4o-2024-11-20",
      name: "GPT-4o (2024-11-20)",
      api: "azure-openai-responses",
      provider: "azure-openai-responses",
      baseUrl: "",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 2.5,
        output: 10,
        cacheRead: 1.25,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 16384
    },
    "gpt-4o-mini": {
      id: "gpt-4o-mini",
      name: "GPT-4o mini",
      api: "azure-openai-responses",
      provider: "azure-openai-responses",
      baseUrl: "",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.15,
        output: 0.6,
        cacheRead: 0.08,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 16384
    },
    "gpt-5": {
      id: "gpt-5",
      name: "GPT-5",
      api: "azure-openai-responses",
      provider: "azure-openai-responses",
      baseUrl: "",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.25,
        output: 10,
        cacheRead: 0.125,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "gpt-5-chat-latest": {
      id: "gpt-5-chat-latest",
      name: "GPT-5 Chat Latest",
      api: "azure-openai-responses",
      provider: "azure-openai-responses",
      baseUrl: "",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 1.25,
        output: 10,
        cacheRead: 0.125,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 16384
    },
    "gpt-5-codex": {
      id: "gpt-5-codex",
      name: "GPT-5-Codex",
      api: "azure-openai-responses",
      provider: "azure-openai-responses",
      baseUrl: "",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.25,
        output: 10,
        cacheRead: 0.125,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "gpt-5-mini": {
      id: "gpt-5-mini",
      name: "GPT-5 Mini",
      api: "azure-openai-responses",
      provider: "azure-openai-responses",
      baseUrl: "",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.25,
        output: 2,
        cacheRead: 0.025,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "gpt-5-nano": {
      id: "gpt-5-nano",
      name: "GPT-5 Nano",
      api: "azure-openai-responses",
      provider: "azure-openai-responses",
      baseUrl: "",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.05,
        output: 0.4,
        cacheRead: 5e-3,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "gpt-5-pro": {
      id: "gpt-5-pro",
      name: "GPT-5 Pro",
      api: "azure-openai-responses",
      provider: "azure-openai-responses",
      baseUrl: "",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 15,
        output: 120,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 272e3
    },
    "gpt-5.1": {
      id: "gpt-5.1",
      name: "GPT-5.1",
      api: "azure-openai-responses",
      provider: "azure-openai-responses",
      baseUrl: "",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.25,
        output: 10,
        cacheRead: 0.13,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "gpt-5.1-chat-latest": {
      id: "gpt-5.1-chat-latest",
      name: "GPT-5.1 Chat",
      api: "azure-openai-responses",
      provider: "azure-openai-responses",
      baseUrl: "",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.25,
        output: 10,
        cacheRead: 0.125,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 16384
    },
    "gpt-5.1-codex": {
      id: "gpt-5.1-codex",
      name: "GPT-5.1 Codex",
      api: "azure-openai-responses",
      provider: "azure-openai-responses",
      baseUrl: "",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.25,
        output: 10,
        cacheRead: 0.125,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "gpt-5.1-codex-max": {
      id: "gpt-5.1-codex-max",
      name: "GPT-5.1 Codex Max",
      api: "azure-openai-responses",
      provider: "azure-openai-responses",
      baseUrl: "",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.25,
        output: 10,
        cacheRead: 0.125,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "gpt-5.1-codex-mini": {
      id: "gpt-5.1-codex-mini",
      name: "GPT-5.1 Codex mini",
      api: "azure-openai-responses",
      provider: "azure-openai-responses",
      baseUrl: "",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.25,
        output: 2,
        cacheRead: 0.025,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "gpt-5.2": {
      id: "gpt-5.2",
      name: "GPT-5.2",
      api: "azure-openai-responses",
      provider: "azure-openai-responses",
      baseUrl: "",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.75,
        output: 14,
        cacheRead: 0.175,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "gpt-5.2-chat-latest": {
      id: "gpt-5.2-chat-latest",
      name: "GPT-5.2 Chat",
      api: "azure-openai-responses",
      provider: "azure-openai-responses",
      baseUrl: "",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.75,
        output: 14,
        cacheRead: 0.175,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 16384
    },
    "gpt-5.2-codex": {
      id: "gpt-5.2-codex",
      name: "GPT-5.2 Codex",
      api: "azure-openai-responses",
      provider: "azure-openai-responses",
      baseUrl: "",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.75,
        output: 14,
        cacheRead: 0.175,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "gpt-5.2-pro": {
      id: "gpt-5.2-pro",
      name: "GPT-5.2 Pro",
      api: "azure-openai-responses",
      provider: "azure-openai-responses",
      baseUrl: "",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 21,
        output: 168,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "gpt-5.3-codex": {
      id: "gpt-5.3-codex",
      name: "GPT-5.3 Codex",
      api: "azure-openai-responses",
      provider: "azure-openai-responses",
      baseUrl: "",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.75,
        output: 14,
        cacheRead: 0.175,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "gpt-5.3-codex-spark": {
      id: "gpt-5.3-codex-spark",
      name: "GPT-5.3 Codex Spark",
      api: "azure-openai-responses",
      provider: "azure-openai-responses",
      baseUrl: "",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.75,
        output: 14,
        cacheRead: 0.175,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 32e3
    },
    "gpt-5.4": {
      id: "gpt-5.4",
      name: "GPT-5.4",
      api: "azure-openai-responses",
      provider: "azure-openai-responses",
      baseUrl: "",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 2.5,
        output: 15,
        cacheRead: 0.25,
        cacheWrite: 0
      },
      contextWindow: 272e3,
      maxTokens: 128e3
    },
    "gpt-5.4-pro": {
      id: "gpt-5.4-pro",
      name: "GPT-5.4 Pro",
      api: "azure-openai-responses",
      provider: "azure-openai-responses",
      baseUrl: "",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 30,
        output: 180,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 105e4,
      maxTokens: 128e3
    },
    "o1": {
      id: "o1",
      name: "o1",
      api: "azure-openai-responses",
      provider: "azure-openai-responses",
      baseUrl: "",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 15,
        output: 60,
        cacheRead: 7.5,
        cacheWrite: 0
      },
      contextWindow: 2e5,
      maxTokens: 1e5
    },
    "o1-pro": {
      id: "o1-pro",
      name: "o1-pro",
      api: "azure-openai-responses",
      provider: "azure-openai-responses",
      baseUrl: "",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 150,
        output: 600,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 2e5,
      maxTokens: 1e5
    },
    "o3": {
      id: "o3",
      name: "o3",
      api: "azure-openai-responses",
      provider: "azure-openai-responses",
      baseUrl: "",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 2,
        output: 8,
        cacheRead: 0.5,
        cacheWrite: 0
      },
      contextWindow: 2e5,
      maxTokens: 1e5
    },
    "o3-deep-research": {
      id: "o3-deep-research",
      name: "o3-deep-research",
      api: "azure-openai-responses",
      provider: "azure-openai-responses",
      baseUrl: "",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 10,
        output: 40,
        cacheRead: 2.5,
        cacheWrite: 0
      },
      contextWindow: 2e5,
      maxTokens: 1e5
    },
    "o3-mini": {
      id: "o3-mini",
      name: "o3-mini",
      api: "azure-openai-responses",
      provider: "azure-openai-responses",
      baseUrl: "",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 1.1,
        output: 4.4,
        cacheRead: 0.55,
        cacheWrite: 0
      },
      contextWindow: 2e5,
      maxTokens: 1e5
    },
    "o3-pro": {
      id: "o3-pro",
      name: "o3-pro",
      api: "azure-openai-responses",
      provider: "azure-openai-responses",
      baseUrl: "",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 20,
        output: 80,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 2e5,
      maxTokens: 1e5
    },
    "o4-mini": {
      id: "o4-mini",
      name: "o4-mini",
      api: "azure-openai-responses",
      provider: "azure-openai-responses",
      baseUrl: "",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.1,
        output: 4.4,
        cacheRead: 0.28,
        cacheWrite: 0
      },
      contextWindow: 2e5,
      maxTokens: 1e5
    },
    "o4-mini-deep-research": {
      id: "o4-mini-deep-research",
      name: "o4-mini-deep-research",
      api: "azure-openai-responses",
      provider: "azure-openai-responses",
      baseUrl: "",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 2,
        output: 8,
        cacheRead: 0.5,
        cacheWrite: 0
      },
      contextWindow: 2e5,
      maxTokens: 1e5
    }
  },
  "cerebras": {
    "gpt-oss-120b": {
      id: "gpt-oss-120b",
      name: "GPT OSS 120B",
      api: "openai-completions",
      provider: "cerebras",
      baseUrl: "https://api.cerebras.ai/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.25,
        output: 0.69,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 32768
    },
    "llama3.1-8b": {
      id: "llama3.1-8b",
      name: "Llama 3.1 8B",
      api: "openai-completions",
      provider: "cerebras",
      baseUrl: "https://api.cerebras.ai/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.1,
        output: 0.1,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 32e3,
      maxTokens: 8e3
    },
    "qwen-3-235b-a22b-instruct-2507": {
      id: "qwen-3-235b-a22b-instruct-2507",
      name: "Qwen 3 235B Instruct",
      api: "openai-completions",
      provider: "cerebras",
      baseUrl: "https://api.cerebras.ai/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.6,
        output: 1.2,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131e3,
      maxTokens: 32e3
    },
    "zai-glm-4.7": {
      id: "zai-glm-4.7",
      name: "Z.AI GLM-4.7",
      api: "openai-completions",
      provider: "cerebras",
      baseUrl: "https://api.cerebras.ai/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 2.25,
        output: 2.75,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 4e4
    }
  },
  "github-copilot": {
    "claude-haiku-4.5": {
      id: "claude-haiku-4.5",
      name: "Claude Haiku 4.5",
      api: "anthropic-messages",
      provider: "github-copilot",
      baseUrl: "https://api.individual.githubcopilot.com",
      headers: { "User-Agent": "GitHubCopilotChat/0.35.0", "Editor-Version": "vscode/1.107.0", "Editor-Plugin-Version": "copilot-chat/0.35.0", "Copilot-Integration-Id": "vscode-chat" },
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 32e3
    },
    "claude-opus-4.5": {
      id: "claude-opus-4.5",
      name: "Claude Opus 4.5",
      api: "anthropic-messages",
      provider: "github-copilot",
      baseUrl: "https://api.individual.githubcopilot.com",
      headers: { "User-Agent": "GitHubCopilotChat/0.35.0", "Editor-Version": "vscode/1.107.0", "Editor-Plugin-Version": "copilot-chat/0.35.0", "Copilot-Integration-Id": "vscode-chat" },
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 32e3
    },
    "claude-opus-4.6": {
      id: "claude-opus-4.6",
      name: "Claude Opus 4.6",
      api: "anthropic-messages",
      provider: "github-copilot",
      baseUrl: "https://api.individual.githubcopilot.com",
      headers: { "User-Agent": "GitHubCopilotChat/0.35.0", "Editor-Version": "vscode/1.107.0", "Editor-Plugin-Version": "copilot-chat/0.35.0", "Copilot-Integration-Id": "vscode-chat" },
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 64e3
    },
    "claude-sonnet-4": {
      id: "claude-sonnet-4",
      name: "Claude Sonnet 4",
      api: "anthropic-messages",
      provider: "github-copilot",
      baseUrl: "https://api.individual.githubcopilot.com",
      headers: { "User-Agent": "GitHubCopilotChat/0.35.0", "Editor-Version": "vscode/1.107.0", "Editor-Plugin-Version": "copilot-chat/0.35.0", "Copilot-Integration-Id": "vscode-chat" },
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 16e3
    },
    "claude-sonnet-4.5": {
      id: "claude-sonnet-4.5",
      name: "Claude Sonnet 4.5",
      api: "anthropic-messages",
      provider: "github-copilot",
      baseUrl: "https://api.individual.githubcopilot.com",
      headers: { "User-Agent": "GitHubCopilotChat/0.35.0", "Editor-Version": "vscode/1.107.0", "Editor-Plugin-Version": "copilot-chat/0.35.0", "Copilot-Integration-Id": "vscode-chat" },
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 32e3
    },
    "claude-sonnet-4.6": {
      id: "claude-sonnet-4.6",
      name: "Claude Sonnet 4.6",
      api: "anthropic-messages",
      provider: "github-copilot",
      baseUrl: "https://api.individual.githubcopilot.com",
      headers: { "User-Agent": "GitHubCopilotChat/0.35.0", "Editor-Version": "vscode/1.107.0", "Editor-Plugin-Version": "copilot-chat/0.35.0", "Copilot-Integration-Id": "vscode-chat" },
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 32e3
    },
    "gemini-2.5-pro": {
      id: "gemini-2.5-pro",
      name: "Gemini 2.5 Pro",
      api: "openai-completions",
      provider: "github-copilot",
      baseUrl: "https://api.individual.githubcopilot.com",
      headers: { "User-Agent": "GitHubCopilotChat/0.35.0", "Editor-Version": "vscode/1.107.0", "Editor-Plugin-Version": "copilot-chat/0.35.0", "Copilot-Integration-Id": "vscode-chat" },
      compat: { "supportsStore": false, "supportsDeveloperRole": false, "supportsReasoningEffort": false },
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 64e3
    },
    "gemini-3-flash-preview": {
      id: "gemini-3-flash-preview",
      name: "Gemini 3 Flash",
      api: "openai-completions",
      provider: "github-copilot",
      baseUrl: "https://api.individual.githubcopilot.com",
      headers: { "User-Agent": "GitHubCopilotChat/0.35.0", "Editor-Version": "vscode/1.107.0", "Editor-Plugin-Version": "copilot-chat/0.35.0", "Copilot-Integration-Id": "vscode-chat" },
      compat: { "supportsStore": false, "supportsDeveloperRole": false, "supportsReasoningEffort": false },
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 64e3
    },
    "gemini-3-pro-preview": {
      id: "gemini-3-pro-preview",
      name: "Gemini 3 Pro Preview",
      api: "openai-completions",
      provider: "github-copilot",
      baseUrl: "https://api.individual.githubcopilot.com",
      headers: { "User-Agent": "GitHubCopilotChat/0.35.0", "Editor-Version": "vscode/1.107.0", "Editor-Plugin-Version": "copilot-chat/0.35.0", "Copilot-Integration-Id": "vscode-chat" },
      compat: { "supportsStore": false, "supportsDeveloperRole": false, "supportsReasoningEffort": false },
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 64e3
    },
    "gemini-3.1-pro-preview": {
      id: "gemini-3.1-pro-preview",
      name: "Gemini 3.1 Pro Preview",
      api: "openai-completions",
      provider: "github-copilot",
      baseUrl: "https://api.individual.githubcopilot.com",
      headers: { "User-Agent": "GitHubCopilotChat/0.35.0", "Editor-Version": "vscode/1.107.0", "Editor-Plugin-Version": "copilot-chat/0.35.0", "Copilot-Integration-Id": "vscode-chat" },
      compat: { "supportsStore": false, "supportsDeveloperRole": false, "supportsReasoningEffort": false },
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 64e3
    },
    "gpt-4.1": {
      id: "gpt-4.1",
      name: "GPT-4.1",
      api: "openai-completions",
      provider: "github-copilot",
      baseUrl: "https://api.individual.githubcopilot.com",
      headers: { "User-Agent": "GitHubCopilotChat/0.35.0", "Editor-Version": "vscode/1.107.0", "Editor-Plugin-Version": "copilot-chat/0.35.0", "Copilot-Integration-Id": "vscode-chat" },
      compat: { "supportsStore": false, "supportsDeveloperRole": false, "supportsReasoningEffort": false },
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 64e3,
      maxTokens: 16384
    },
    "gpt-4o": {
      id: "gpt-4o",
      name: "GPT-4o",
      api: "openai-completions",
      provider: "github-copilot",
      baseUrl: "https://api.individual.githubcopilot.com",
      headers: { "User-Agent": "GitHubCopilotChat/0.35.0", "Editor-Version": "vscode/1.107.0", "Editor-Plugin-Version": "copilot-chat/0.35.0", "Copilot-Integration-Id": "vscode-chat" },
      compat: { "supportsStore": false, "supportsDeveloperRole": false, "supportsReasoningEffort": false },
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 64e3,
      maxTokens: 16384
    },
    "gpt-5": {
      id: "gpt-5",
      name: "GPT-5",
      api: "openai-responses",
      provider: "github-copilot",
      baseUrl: "https://api.individual.githubcopilot.com",
      headers: { "User-Agent": "GitHubCopilotChat/0.35.0", "Editor-Version": "vscode/1.107.0", "Editor-Plugin-Version": "copilot-chat/0.35.0", "Copilot-Integration-Id": "vscode-chat" },
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 128e3
    },
    "gpt-5-mini": {
      id: "gpt-5-mini",
      name: "GPT-5-mini",
      api: "openai-responses",
      provider: "github-copilot",
      baseUrl: "https://api.individual.githubcopilot.com",
      headers: { "User-Agent": "GitHubCopilotChat/0.35.0", "Editor-Version": "vscode/1.107.0", "Editor-Plugin-Version": "copilot-chat/0.35.0", "Copilot-Integration-Id": "vscode-chat" },
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 64e3
    },
    "gpt-5.1": {
      id: "gpt-5.1",
      name: "GPT-5.1",
      api: "openai-responses",
      provider: "github-copilot",
      baseUrl: "https://api.individual.githubcopilot.com",
      headers: { "User-Agent": "GitHubCopilotChat/0.35.0", "Editor-Version": "vscode/1.107.0", "Editor-Plugin-Version": "copilot-chat/0.35.0", "Copilot-Integration-Id": "vscode-chat" },
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 64e3
    },
    "gpt-5.1-codex": {
      id: "gpt-5.1-codex",
      name: "GPT-5.1-Codex",
      api: "openai-responses",
      provider: "github-copilot",
      baseUrl: "https://api.individual.githubcopilot.com",
      headers: { "User-Agent": "GitHubCopilotChat/0.35.0", "Editor-Version": "vscode/1.107.0", "Editor-Plugin-Version": "copilot-chat/0.35.0", "Copilot-Integration-Id": "vscode-chat" },
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 128e3
    },
    "gpt-5.1-codex-max": {
      id: "gpt-5.1-codex-max",
      name: "GPT-5.1-Codex-max",
      api: "openai-responses",
      provider: "github-copilot",
      baseUrl: "https://api.individual.githubcopilot.com",
      headers: { "User-Agent": "GitHubCopilotChat/0.35.0", "Editor-Version": "vscode/1.107.0", "Editor-Plugin-Version": "copilot-chat/0.35.0", "Copilot-Integration-Id": "vscode-chat" },
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 128e3
    },
    "gpt-5.1-codex-mini": {
      id: "gpt-5.1-codex-mini",
      name: "GPT-5.1-Codex-mini",
      api: "openai-responses",
      provider: "github-copilot",
      baseUrl: "https://api.individual.githubcopilot.com",
      headers: { "User-Agent": "GitHubCopilotChat/0.35.0", "Editor-Version": "vscode/1.107.0", "Editor-Plugin-Version": "copilot-chat/0.35.0", "Copilot-Integration-Id": "vscode-chat" },
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 128e3
    },
    "gpt-5.2": {
      id: "gpt-5.2",
      name: "GPT-5.2",
      api: "openai-responses",
      provider: "github-copilot",
      baseUrl: "https://api.individual.githubcopilot.com",
      headers: { "User-Agent": "GitHubCopilotChat/0.35.0", "Editor-Version": "vscode/1.107.0", "Editor-Plugin-Version": "copilot-chat/0.35.0", "Copilot-Integration-Id": "vscode-chat" },
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 264e3,
      maxTokens: 64e3
    },
    "gpt-5.2-codex": {
      id: "gpt-5.2-codex",
      name: "GPT-5.2-Codex",
      api: "openai-responses",
      provider: "github-copilot",
      baseUrl: "https://api.individual.githubcopilot.com",
      headers: { "User-Agent": "GitHubCopilotChat/0.35.0", "Editor-Version": "vscode/1.107.0", "Editor-Plugin-Version": "copilot-chat/0.35.0", "Copilot-Integration-Id": "vscode-chat" },
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "gpt-5.3-codex": {
      id: "gpt-5.3-codex",
      name: "GPT-5.3-Codex",
      api: "openai-responses",
      provider: "github-copilot",
      baseUrl: "https://api.individual.githubcopilot.com",
      headers: { "User-Agent": "GitHubCopilotChat/0.35.0", "Editor-Version": "vscode/1.107.0", "Editor-Plugin-Version": "copilot-chat/0.35.0", "Copilot-Integration-Id": "vscode-chat" },
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "gpt-5.4": {
      id: "gpt-5.4",
      name: "GPT-5.4",
      api: "openai-responses",
      provider: "github-copilot",
      baseUrl: "https://api.individual.githubcopilot.com",
      headers: { "User-Agent": "GitHubCopilotChat/0.35.0", "Editor-Version": "vscode/1.107.0", "Editor-Plugin-Version": "copilot-chat/0.35.0", "Copilot-Integration-Id": "vscode-chat" },
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "grok-code-fast-1": {
      id: "grok-code-fast-1",
      name: "Grok Code Fast 1",
      api: "openai-completions",
      provider: "github-copilot",
      baseUrl: "https://api.individual.githubcopilot.com",
      headers: { "User-Agent": "GitHubCopilotChat/0.35.0", "Editor-Version": "vscode/1.107.0", "Editor-Plugin-Version": "copilot-chat/0.35.0", "Copilot-Integration-Id": "vscode-chat" },
      compat: { "supportsStore": false, "supportsDeveloperRole": false, "supportsReasoningEffort": false },
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 64e3
    }
  },
  "google": {
    "gemini-1.5-flash": {
      id: "gemini-1.5-flash",
      name: "Gemini 1.5 Flash",
      api: "google-generative-ai",
      provider: "google",
      baseUrl: "https://generativelanguage.googleapis.com/v1beta",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.075,
        output: 0.3,
        cacheRead: 0.01875,
        cacheWrite: 0
      },
      contextWindow: 1e6,
      maxTokens: 8192
    },
    "gemini-1.5-flash-8b": {
      id: "gemini-1.5-flash-8b",
      name: "Gemini 1.5 Flash-8B",
      api: "google-generative-ai",
      provider: "google",
      baseUrl: "https://generativelanguage.googleapis.com/v1beta",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.0375,
        output: 0.15,
        cacheRead: 0.01,
        cacheWrite: 0
      },
      contextWindow: 1e6,
      maxTokens: 8192
    },
    "gemini-1.5-pro": {
      id: "gemini-1.5-pro",
      name: "Gemini 1.5 Pro",
      api: "google-generative-ai",
      provider: "google",
      baseUrl: "https://generativelanguage.googleapis.com/v1beta",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 1.25,
        output: 5,
        cacheRead: 0.3125,
        cacheWrite: 0
      },
      contextWindow: 1e6,
      maxTokens: 8192
    },
    "gemini-2.0-flash": {
      id: "gemini-2.0-flash",
      name: "Gemini 2.0 Flash",
      api: "google-generative-ai",
      provider: "google",
      baseUrl: "https://generativelanguage.googleapis.com/v1beta",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.1,
        output: 0.4,
        cacheRead: 0.025,
        cacheWrite: 0
      },
      contextWindow: 1048576,
      maxTokens: 8192
    },
    "gemini-2.0-flash-lite": {
      id: "gemini-2.0-flash-lite",
      name: "Gemini 2.0 Flash Lite",
      api: "google-generative-ai",
      provider: "google",
      baseUrl: "https://generativelanguage.googleapis.com/v1beta",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.075,
        output: 0.3,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 1048576,
      maxTokens: 8192
    },
    "gemini-2.5-flash": {
      id: "gemini-2.5-flash",
      name: "Gemini 2.5 Flash",
      api: "google-generative-ai",
      provider: "google",
      baseUrl: "https://generativelanguage.googleapis.com/v1beta",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.3,
        output: 2.5,
        cacheRead: 0.075,
        cacheWrite: 0
      },
      contextWindow: 1048576,
      maxTokens: 65536
    },
    "gemini-2.5-flash-lite": {
      id: "gemini-2.5-flash-lite",
      name: "Gemini 2.5 Flash Lite",
      api: "google-generative-ai",
      provider: "google",
      baseUrl: "https://generativelanguage.googleapis.com/v1beta",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.1,
        output: 0.4,
        cacheRead: 0.025,
        cacheWrite: 0
      },
      contextWindow: 1048576,
      maxTokens: 65536
    },
    "gemini-2.5-flash-lite-preview-06-17": {
      id: "gemini-2.5-flash-lite-preview-06-17",
      name: "Gemini 2.5 Flash Lite Preview 06-17",
      api: "google-generative-ai",
      provider: "google",
      baseUrl: "https://generativelanguage.googleapis.com/v1beta",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.1,
        output: 0.4,
        cacheRead: 0.025,
        cacheWrite: 0
      },
      contextWindow: 1048576,
      maxTokens: 65536
    },
    "gemini-2.5-flash-lite-preview-09-2025": {
      id: "gemini-2.5-flash-lite-preview-09-2025",
      name: "Gemini 2.5 Flash Lite Preview 09-25",
      api: "google-generative-ai",
      provider: "google",
      baseUrl: "https://generativelanguage.googleapis.com/v1beta",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.1,
        output: 0.4,
        cacheRead: 0.025,
        cacheWrite: 0
      },
      contextWindow: 1048576,
      maxTokens: 65536
    },
    "gemini-2.5-flash-preview-04-17": {
      id: "gemini-2.5-flash-preview-04-17",
      name: "Gemini 2.5 Flash Preview 04-17",
      api: "google-generative-ai",
      provider: "google",
      baseUrl: "https://generativelanguage.googleapis.com/v1beta",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.15,
        output: 0.6,
        cacheRead: 0.0375,
        cacheWrite: 0
      },
      contextWindow: 1048576,
      maxTokens: 65536
    },
    "gemini-2.5-flash-preview-05-20": {
      id: "gemini-2.5-flash-preview-05-20",
      name: "Gemini 2.5 Flash Preview 05-20",
      api: "google-generative-ai",
      provider: "google",
      baseUrl: "https://generativelanguage.googleapis.com/v1beta",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.15,
        output: 0.6,
        cacheRead: 0.0375,
        cacheWrite: 0
      },
      contextWindow: 1048576,
      maxTokens: 65536
    },
    "gemini-2.5-flash-preview-09-2025": {
      id: "gemini-2.5-flash-preview-09-2025",
      name: "Gemini 2.5 Flash Preview 09-25",
      api: "google-generative-ai",
      provider: "google",
      baseUrl: "https://generativelanguage.googleapis.com/v1beta",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.3,
        output: 2.5,
        cacheRead: 0.075,
        cacheWrite: 0
      },
      contextWindow: 1048576,
      maxTokens: 65536
    },
    "gemini-2.5-pro": {
      id: "gemini-2.5-pro",
      name: "Gemini 2.5 Pro",
      api: "google-generative-ai",
      provider: "google",
      baseUrl: "https://generativelanguage.googleapis.com/v1beta",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.25,
        output: 10,
        cacheRead: 0.31,
        cacheWrite: 0
      },
      contextWindow: 1048576,
      maxTokens: 65536
    },
    "gemini-2.5-pro-preview-05-06": {
      id: "gemini-2.5-pro-preview-05-06",
      name: "Gemini 2.5 Pro Preview 05-06",
      api: "google-generative-ai",
      provider: "google",
      baseUrl: "https://generativelanguage.googleapis.com/v1beta",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.25,
        output: 10,
        cacheRead: 0.31,
        cacheWrite: 0
      },
      contextWindow: 1048576,
      maxTokens: 65536
    },
    "gemini-2.5-pro-preview-06-05": {
      id: "gemini-2.5-pro-preview-06-05",
      name: "Gemini 2.5 Pro Preview 06-05",
      api: "google-generative-ai",
      provider: "google",
      baseUrl: "https://generativelanguage.googleapis.com/v1beta",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.25,
        output: 10,
        cacheRead: 0.31,
        cacheWrite: 0
      },
      contextWindow: 1048576,
      maxTokens: 65536
    },
    "gemini-3-flash-preview": {
      id: "gemini-3-flash-preview",
      name: "Gemini 3 Flash Preview",
      api: "google-generative-ai",
      provider: "google",
      baseUrl: "https://generativelanguage.googleapis.com/v1beta",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.5,
        output: 3,
        cacheRead: 0.05,
        cacheWrite: 0
      },
      contextWindow: 1048576,
      maxTokens: 65536
    },
    "gemini-3-pro-preview": {
      id: "gemini-3-pro-preview",
      name: "Gemini 3 Pro Preview",
      api: "google-generative-ai",
      provider: "google",
      baseUrl: "https://generativelanguage.googleapis.com/v1beta",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 2,
        output: 12,
        cacheRead: 0.2,
        cacheWrite: 0
      },
      contextWindow: 1e6,
      maxTokens: 64e3
    },
    "gemini-3.1-flash-lite-preview": {
      id: "gemini-3.1-flash-lite-preview",
      name: "Gemini 3.1 Flash Lite Preview",
      api: "google-generative-ai",
      provider: "google",
      baseUrl: "https://generativelanguage.googleapis.com/v1beta",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.25,
        output: 1.5,
        cacheRead: 0.025,
        cacheWrite: 1
      },
      contextWindow: 1048576,
      maxTokens: 65536
    },
    "gemini-3.1-pro-preview": {
      id: "gemini-3.1-pro-preview",
      name: "Gemini 3.1 Pro Preview",
      api: "google-generative-ai",
      provider: "google",
      baseUrl: "https://generativelanguage.googleapis.com/v1beta",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 2,
        output: 12,
        cacheRead: 0.2,
        cacheWrite: 0
      },
      contextWindow: 1048576,
      maxTokens: 65536
    },
    "gemini-3.1-pro-preview-customtools": {
      id: "gemini-3.1-pro-preview-customtools",
      name: "Gemini 3.1 Pro Preview Custom Tools",
      api: "google-generative-ai",
      provider: "google",
      baseUrl: "https://generativelanguage.googleapis.com/v1beta",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 2,
        output: 12,
        cacheRead: 0.2,
        cacheWrite: 0
      },
      contextWindow: 1048576,
      maxTokens: 65536
    },
    "gemini-flash-latest": {
      id: "gemini-flash-latest",
      name: "Gemini Flash Latest",
      api: "google-generative-ai",
      provider: "google",
      baseUrl: "https://generativelanguage.googleapis.com/v1beta",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.3,
        output: 2.5,
        cacheRead: 0.075,
        cacheWrite: 0
      },
      contextWindow: 1048576,
      maxTokens: 65536
    },
    "gemini-flash-lite-latest": {
      id: "gemini-flash-lite-latest",
      name: "Gemini Flash-Lite Latest",
      api: "google-generative-ai",
      provider: "google",
      baseUrl: "https://generativelanguage.googleapis.com/v1beta",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.1,
        output: 0.4,
        cacheRead: 0.025,
        cacheWrite: 0
      },
      contextWindow: 1048576,
      maxTokens: 65536
    },
    "gemini-live-2.5-flash": {
      id: "gemini-live-2.5-flash",
      name: "Gemini Live 2.5 Flash",
      api: "google-generative-ai",
      provider: "google",
      baseUrl: "https://generativelanguage.googleapis.com/v1beta",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.5,
        output: 2,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 8e3
    },
    "gemini-live-2.5-flash-preview-native-audio": {
      id: "gemini-live-2.5-flash-preview-native-audio",
      name: "Gemini Live 2.5 Flash Preview Native Audio",
      api: "google-generative-ai",
      provider: "google",
      baseUrl: "https://generativelanguage.googleapis.com/v1beta",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.5,
        output: 2,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 65536
    }
  },
  "google-antigravity": {
    "claude-opus-4-5-thinking": {
      id: "claude-opus-4-5-thinking",
      name: "Claude Opus 4.5 Thinking (Antigravity)",
      api: "google-gemini-cli",
      provider: "google-antigravity",
      baseUrl: "https://daily-cloudcode-pa.sandbox.googleapis.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 5,
        output: 25,
        cacheRead: 0.5,
        cacheWrite: 6.25
      },
      contextWindow: 2e5,
      maxTokens: 64e3
    },
    "claude-opus-4-6-thinking": {
      id: "claude-opus-4-6-thinking",
      name: "Claude Opus 4.6 Thinking (Antigravity)",
      api: "google-gemini-cli",
      provider: "google-antigravity",
      baseUrl: "https://daily-cloudcode-pa.sandbox.googleapis.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 5,
        output: 25,
        cacheRead: 0.5,
        cacheWrite: 6.25
      },
      contextWindow: 2e5,
      maxTokens: 128e3
    },
    "claude-sonnet-4-5": {
      id: "claude-sonnet-4-5",
      name: "Claude Sonnet 4.5 (Antigravity)",
      api: "google-gemini-cli",
      provider: "google-antigravity",
      baseUrl: "https://daily-cloudcode-pa.sandbox.googleapis.com",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.3,
        cacheWrite: 3.75
      },
      contextWindow: 2e5,
      maxTokens: 64e3
    },
    "claude-sonnet-4-5-thinking": {
      id: "claude-sonnet-4-5-thinking",
      name: "Claude Sonnet 4.5 Thinking (Antigravity)",
      api: "google-gemini-cli",
      provider: "google-antigravity",
      baseUrl: "https://daily-cloudcode-pa.sandbox.googleapis.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.3,
        cacheWrite: 3.75
      },
      contextWindow: 2e5,
      maxTokens: 64e3
    },
    "claude-sonnet-4-6": {
      id: "claude-sonnet-4-6",
      name: "Claude Sonnet 4.6 (Antigravity)",
      api: "google-gemini-cli",
      provider: "google-antigravity",
      baseUrl: "https://daily-cloudcode-pa.sandbox.googleapis.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.3,
        cacheWrite: 3.75
      },
      contextWindow: 2e5,
      maxTokens: 64e3
    },
    "gemini-3-flash": {
      id: "gemini-3-flash",
      name: "Gemini 3 Flash (Antigravity)",
      api: "google-gemini-cli",
      provider: "google-antigravity",
      baseUrl: "https://daily-cloudcode-pa.sandbox.googleapis.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.5,
        output: 3,
        cacheRead: 0.5,
        cacheWrite: 0
      },
      contextWindow: 1048576,
      maxTokens: 65535
    },
    "gemini-3.1-pro-high": {
      id: "gemini-3.1-pro-high",
      name: "Gemini 3.1 Pro High (Antigravity)",
      api: "google-gemini-cli",
      provider: "google-antigravity",
      baseUrl: "https://daily-cloudcode-pa.sandbox.googleapis.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 2,
        output: 12,
        cacheRead: 0.2,
        cacheWrite: 2.375
      },
      contextWindow: 1048576,
      maxTokens: 65535
    },
    "gemini-3.1-pro-low": {
      id: "gemini-3.1-pro-low",
      name: "Gemini 3.1 Pro Low (Antigravity)",
      api: "google-gemini-cli",
      provider: "google-antigravity",
      baseUrl: "https://daily-cloudcode-pa.sandbox.googleapis.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 2,
        output: 12,
        cacheRead: 0.2,
        cacheWrite: 2.375
      },
      contextWindow: 1048576,
      maxTokens: 65535
    },
    "gpt-oss-120b-medium": {
      id: "gpt-oss-120b-medium",
      name: "GPT-OSS 120B Medium (Antigravity)",
      api: "google-gemini-cli",
      provider: "google-antigravity",
      baseUrl: "https://daily-cloudcode-pa.sandbox.googleapis.com",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.09,
        output: 0.36,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 32768
    }
  },
  "google-gemini-cli": {
    "gemini-2.0-flash": {
      id: "gemini-2.0-flash",
      name: "Gemini 2.0 Flash (Cloud Code Assist)",
      api: "google-gemini-cli",
      provider: "google-gemini-cli",
      baseUrl: "https://cloudcode-pa.googleapis.com",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 1048576,
      maxTokens: 8192
    },
    "gemini-2.5-flash": {
      id: "gemini-2.5-flash",
      name: "Gemini 2.5 Flash (Cloud Code Assist)",
      api: "google-gemini-cli",
      provider: "google-gemini-cli",
      baseUrl: "https://cloudcode-pa.googleapis.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 1048576,
      maxTokens: 65535
    },
    "gemini-2.5-pro": {
      id: "gemini-2.5-pro",
      name: "Gemini 2.5 Pro (Cloud Code Assist)",
      api: "google-gemini-cli",
      provider: "google-gemini-cli",
      baseUrl: "https://cloudcode-pa.googleapis.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 1048576,
      maxTokens: 65535
    },
    "gemini-3-flash-preview": {
      id: "gemini-3-flash-preview",
      name: "Gemini 3 Flash Preview (Cloud Code Assist)",
      api: "google-gemini-cli",
      provider: "google-gemini-cli",
      baseUrl: "https://cloudcode-pa.googleapis.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 1048576,
      maxTokens: 65535
    },
    "gemini-3-pro-preview": {
      id: "gemini-3-pro-preview",
      name: "Gemini 3 Pro Preview (Cloud Code Assist)",
      api: "google-gemini-cli",
      provider: "google-gemini-cli",
      baseUrl: "https://cloudcode-pa.googleapis.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 1048576,
      maxTokens: 65535
    },
    "gemini-3.1-pro-preview": {
      id: "gemini-3.1-pro-preview",
      name: "Gemini 3.1 Pro Preview (Cloud Code Assist)",
      api: "google-gemini-cli",
      provider: "google-gemini-cli",
      baseUrl: "https://cloudcode-pa.googleapis.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 1048576,
      maxTokens: 65535
    }
  },
  "google-vertex": {
    "gemini-1.5-flash": {
      id: "gemini-1.5-flash",
      name: "Gemini 1.5 Flash (Vertex)",
      api: "google-vertex",
      provider: "google-vertex",
      baseUrl: "https://{location}-aiplatform.googleapis.com",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.075,
        output: 0.3,
        cacheRead: 0.01875,
        cacheWrite: 0
      },
      contextWindow: 1e6,
      maxTokens: 8192
    },
    "gemini-1.5-flash-8b": {
      id: "gemini-1.5-flash-8b",
      name: "Gemini 1.5 Flash-8B (Vertex)",
      api: "google-vertex",
      provider: "google-vertex",
      baseUrl: "https://{location}-aiplatform.googleapis.com",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.0375,
        output: 0.15,
        cacheRead: 0.01,
        cacheWrite: 0
      },
      contextWindow: 1e6,
      maxTokens: 8192
    },
    "gemini-1.5-pro": {
      id: "gemini-1.5-pro",
      name: "Gemini 1.5 Pro (Vertex)",
      api: "google-vertex",
      provider: "google-vertex",
      baseUrl: "https://{location}-aiplatform.googleapis.com",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 1.25,
        output: 5,
        cacheRead: 0.3125,
        cacheWrite: 0
      },
      contextWindow: 1e6,
      maxTokens: 8192
    },
    "gemini-2.0-flash": {
      id: "gemini-2.0-flash",
      name: "Gemini 2.0 Flash (Vertex)",
      api: "google-vertex",
      provider: "google-vertex",
      baseUrl: "https://{location}-aiplatform.googleapis.com",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.15,
        output: 0.6,
        cacheRead: 0.0375,
        cacheWrite: 0
      },
      contextWindow: 1048576,
      maxTokens: 8192
    },
    "gemini-2.0-flash-lite": {
      id: "gemini-2.0-flash-lite",
      name: "Gemini 2.0 Flash Lite (Vertex)",
      api: "google-vertex",
      provider: "google-vertex",
      baseUrl: "https://{location}-aiplatform.googleapis.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.075,
        output: 0.3,
        cacheRead: 0.01875,
        cacheWrite: 0
      },
      contextWindow: 1048576,
      maxTokens: 65536
    },
    "gemini-2.5-flash": {
      id: "gemini-2.5-flash",
      name: "Gemini 2.5 Flash (Vertex)",
      api: "google-vertex",
      provider: "google-vertex",
      baseUrl: "https://{location}-aiplatform.googleapis.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.3,
        output: 2.5,
        cacheRead: 0.03,
        cacheWrite: 0
      },
      contextWindow: 1048576,
      maxTokens: 65536
    },
    "gemini-2.5-flash-lite": {
      id: "gemini-2.5-flash-lite",
      name: "Gemini 2.5 Flash Lite (Vertex)",
      api: "google-vertex",
      provider: "google-vertex",
      baseUrl: "https://{location}-aiplatform.googleapis.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.1,
        output: 0.4,
        cacheRead: 0.01,
        cacheWrite: 0
      },
      contextWindow: 1048576,
      maxTokens: 65536
    },
    "gemini-2.5-flash-lite-preview-09-2025": {
      id: "gemini-2.5-flash-lite-preview-09-2025",
      name: "Gemini 2.5 Flash Lite Preview 09-25 (Vertex)",
      api: "google-vertex",
      provider: "google-vertex",
      baseUrl: "https://{location}-aiplatform.googleapis.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.1,
        output: 0.4,
        cacheRead: 0.01,
        cacheWrite: 0
      },
      contextWindow: 1048576,
      maxTokens: 65536
    },
    "gemini-2.5-pro": {
      id: "gemini-2.5-pro",
      name: "Gemini 2.5 Pro (Vertex)",
      api: "google-vertex",
      provider: "google-vertex",
      baseUrl: "https://{location}-aiplatform.googleapis.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.25,
        output: 10,
        cacheRead: 0.125,
        cacheWrite: 0
      },
      contextWindow: 1048576,
      maxTokens: 65536
    },
    "gemini-3-flash-preview": {
      id: "gemini-3-flash-preview",
      name: "Gemini 3 Flash Preview (Vertex)",
      api: "google-vertex",
      provider: "google-vertex",
      baseUrl: "https://{location}-aiplatform.googleapis.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.5,
        output: 3,
        cacheRead: 0.05,
        cacheWrite: 0
      },
      contextWindow: 1048576,
      maxTokens: 65536
    },
    "gemini-3-pro-preview": {
      id: "gemini-3-pro-preview",
      name: "Gemini 3 Pro Preview (Vertex)",
      api: "google-vertex",
      provider: "google-vertex",
      baseUrl: "https://{location}-aiplatform.googleapis.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 2,
        output: 12,
        cacheRead: 0.2,
        cacheWrite: 0
      },
      contextWindow: 1e6,
      maxTokens: 64e3
    },
    "gemini-3.1-pro-preview": {
      id: "gemini-3.1-pro-preview",
      name: "Gemini 3.1 Pro Preview (Vertex)",
      api: "google-vertex",
      provider: "google-vertex",
      baseUrl: "https://{location}-aiplatform.googleapis.com",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 2,
        output: 12,
        cacheRead: 0.2,
        cacheWrite: 0
      },
      contextWindow: 1048576,
      maxTokens: 65536
    }
  },
  "groq": {
    "deepseek-r1-distill-llama-70b": {
      id: "deepseek-r1-distill-llama-70b",
      name: "DeepSeek R1 Distill Llama 70B",
      api: "openai-completions",
      provider: "groq",
      baseUrl: "https://api.groq.com/openai/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.75,
        output: 0.99,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 8192
    },
    "gemma2-9b-it": {
      id: "gemma2-9b-it",
      name: "Gemma 2 9B",
      api: "openai-completions",
      provider: "groq",
      baseUrl: "https://api.groq.com/openai/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.2,
        output: 0.2,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 8192,
      maxTokens: 8192
    },
    "llama-3.1-8b-instant": {
      id: "llama-3.1-8b-instant",
      name: "Llama 3.1 8B Instant",
      api: "openai-completions",
      provider: "groq",
      baseUrl: "https://api.groq.com/openai/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.05,
        output: 0.08,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 131072
    },
    "llama-3.3-70b-versatile": {
      id: "llama-3.3-70b-versatile",
      name: "Llama 3.3 70B Versatile",
      api: "openai-completions",
      provider: "groq",
      baseUrl: "https://api.groq.com/openai/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.59,
        output: 0.79,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 32768
    },
    "llama3-70b-8192": {
      id: "llama3-70b-8192",
      name: "Llama 3 70B",
      api: "openai-completions",
      provider: "groq",
      baseUrl: "https://api.groq.com/openai/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.59,
        output: 0.79,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 8192,
      maxTokens: 8192
    },
    "llama3-8b-8192": {
      id: "llama3-8b-8192",
      name: "Llama 3 8B",
      api: "openai-completions",
      provider: "groq",
      baseUrl: "https://api.groq.com/openai/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.05,
        output: 0.08,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 8192,
      maxTokens: 8192
    },
    "meta-llama/llama-4-maverick-17b-128e-instruct": {
      id: "meta-llama/llama-4-maverick-17b-128e-instruct",
      name: "Llama 4 Maverick 17B",
      api: "openai-completions",
      provider: "groq",
      baseUrl: "https://api.groq.com/openai/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.2,
        output: 0.6,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 8192
    },
    "meta-llama/llama-4-scout-17b-16e-instruct": {
      id: "meta-llama/llama-4-scout-17b-16e-instruct",
      name: "Llama 4 Scout 17B",
      api: "openai-completions",
      provider: "groq",
      baseUrl: "https://api.groq.com/openai/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.11,
        output: 0.34,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 8192
    },
    "mistral-saba-24b": {
      id: "mistral-saba-24b",
      name: "Mistral Saba 24B",
      api: "openai-completions",
      provider: "groq",
      baseUrl: "https://api.groq.com/openai/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.79,
        output: 0.79,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 32768,
      maxTokens: 32768
    },
    "moonshotai/kimi-k2-instruct": {
      id: "moonshotai/kimi-k2-instruct",
      name: "Kimi K2 Instruct",
      api: "openai-completions",
      provider: "groq",
      baseUrl: "https://api.groq.com/openai/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 1,
        output: 3,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 16384
    },
    "moonshotai/kimi-k2-instruct-0905": {
      id: "moonshotai/kimi-k2-instruct-0905",
      name: "Kimi K2 Instruct 0905",
      api: "openai-completions",
      provider: "groq",
      baseUrl: "https://api.groq.com/openai/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 1,
        output: 3,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 16384
    },
    "openai/gpt-oss-120b": {
      id: "openai/gpt-oss-120b",
      name: "GPT OSS 120B",
      api: "openai-completions",
      provider: "groq",
      baseUrl: "https://api.groq.com/openai/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.15,
        output: 0.6,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 65536
    },
    "openai/gpt-oss-20b": {
      id: "openai/gpt-oss-20b",
      name: "GPT OSS 20B",
      api: "openai-completions",
      provider: "groq",
      baseUrl: "https://api.groq.com/openai/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.075,
        output: 0.3,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 65536
    },
    "qwen-qwq-32b": {
      id: "qwen-qwq-32b",
      name: "Qwen QwQ 32B",
      api: "openai-completions",
      provider: "groq",
      baseUrl: "https://api.groq.com/openai/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.29,
        output: 0.39,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 16384
    },
    "qwen/qwen3-32b": {
      id: "qwen/qwen3-32b",
      name: "Qwen3 32B",
      api: "openai-completions",
      provider: "groq",
      baseUrl: "https://api.groq.com/openai/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.29,
        output: 0.59,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 16384
    }
  },
  "huggingface": {
    "MiniMaxAI/MiniMax-M2.1": {
      id: "MiniMaxAI/MiniMax-M2.1",
      name: "MiniMax-M2.1",
      api: "openai-completions",
      provider: "huggingface",
      baseUrl: "https://router.huggingface.co/v1",
      compat: { "supportsDeveloperRole": false },
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.3,
        output: 1.2,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 204800,
      maxTokens: 131072
    },
    "MiniMaxAI/MiniMax-M2.5": {
      id: "MiniMaxAI/MiniMax-M2.5",
      name: "MiniMax-M2.5",
      api: "openai-completions",
      provider: "huggingface",
      baseUrl: "https://router.huggingface.co/v1",
      compat: { "supportsDeveloperRole": false },
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.3,
        output: 1.2,
        cacheRead: 0.03,
        cacheWrite: 0
      },
      contextWindow: 204800,
      maxTokens: 131072
    },
    "Qwen/Qwen3-235B-A22B-Thinking-2507": {
      id: "Qwen/Qwen3-235B-A22B-Thinking-2507",
      name: "Qwen3-235B-A22B-Thinking-2507",
      api: "openai-completions",
      provider: "huggingface",
      baseUrl: "https://router.huggingface.co/v1",
      compat: { "supportsDeveloperRole": false },
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.3,
        output: 3,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 131072
    },
    "Qwen/Qwen3-Coder-480B-A35B-Instruct": {
      id: "Qwen/Qwen3-Coder-480B-A35B-Instruct",
      name: "Qwen3-Coder-480B-A35B-Instruct",
      api: "openai-completions",
      provider: "huggingface",
      baseUrl: "https://router.huggingface.co/v1",
      compat: { "supportsDeveloperRole": false },
      reasoning: false,
      input: ["text"],
      cost: {
        input: 2,
        output: 2,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 66536
    },
    "Qwen/Qwen3-Coder-Next": {
      id: "Qwen/Qwen3-Coder-Next",
      name: "Qwen3-Coder-Next",
      api: "openai-completions",
      provider: "huggingface",
      baseUrl: "https://router.huggingface.co/v1",
      compat: { "supportsDeveloperRole": false },
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.2,
        output: 1.5,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 65536
    },
    "Qwen/Qwen3-Next-80B-A3B-Instruct": {
      id: "Qwen/Qwen3-Next-80B-A3B-Instruct",
      name: "Qwen3-Next-80B-A3B-Instruct",
      api: "openai-completions",
      provider: "huggingface",
      baseUrl: "https://router.huggingface.co/v1",
      compat: { "supportsDeveloperRole": false },
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.25,
        output: 1,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 66536
    },
    "Qwen/Qwen3-Next-80B-A3B-Thinking": {
      id: "Qwen/Qwen3-Next-80B-A3B-Thinking",
      name: "Qwen3-Next-80B-A3B-Thinking",
      api: "openai-completions",
      provider: "huggingface",
      baseUrl: "https://router.huggingface.co/v1",
      compat: { "supportsDeveloperRole": false },
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.3,
        output: 2,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 131072
    },
    "Qwen/Qwen3.5-397B-A17B": {
      id: "Qwen/Qwen3.5-397B-A17B",
      name: "Qwen3.5-397B-A17B",
      api: "openai-completions",
      provider: "huggingface",
      baseUrl: "https://router.huggingface.co/v1",
      compat: { "supportsDeveloperRole": false },
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.6,
        output: 3.6,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 32768
    },
    "XiaomiMiMo/MiMo-V2-Flash": {
      id: "XiaomiMiMo/MiMo-V2-Flash",
      name: "MiMo-V2-Flash",
      api: "openai-completions",
      provider: "huggingface",
      baseUrl: "https://router.huggingface.co/v1",
      compat: { "supportsDeveloperRole": false },
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.1,
        output: 0.3,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 4096
    },
    "deepseek-ai/DeepSeek-R1-0528": {
      id: "deepseek-ai/DeepSeek-R1-0528",
      name: "DeepSeek-R1-0528",
      api: "openai-completions",
      provider: "huggingface",
      baseUrl: "https://router.huggingface.co/v1",
      compat: { "supportsDeveloperRole": false },
      reasoning: true,
      input: ["text"],
      cost: {
        input: 3,
        output: 5,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 163840,
      maxTokens: 163840
    },
    "deepseek-ai/DeepSeek-V3.2": {
      id: "deepseek-ai/DeepSeek-V3.2",
      name: "DeepSeek-V3.2",
      api: "openai-completions",
      provider: "huggingface",
      baseUrl: "https://router.huggingface.co/v1",
      compat: { "supportsDeveloperRole": false },
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.28,
        output: 0.4,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 163840,
      maxTokens: 65536
    },
    "moonshotai/Kimi-K2-Instruct": {
      id: "moonshotai/Kimi-K2-Instruct",
      name: "Kimi-K2-Instruct",
      api: "openai-completions",
      provider: "huggingface",
      baseUrl: "https://router.huggingface.co/v1",
      compat: { "supportsDeveloperRole": false },
      reasoning: false,
      input: ["text"],
      cost: {
        input: 1,
        output: 3,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 16384
    },
    "moonshotai/Kimi-K2-Instruct-0905": {
      id: "moonshotai/Kimi-K2-Instruct-0905",
      name: "Kimi-K2-Instruct-0905",
      api: "openai-completions",
      provider: "huggingface",
      baseUrl: "https://router.huggingface.co/v1",
      compat: { "supportsDeveloperRole": false },
      reasoning: false,
      input: ["text"],
      cost: {
        input: 1,
        output: 3,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 16384
    },
    "moonshotai/Kimi-K2-Thinking": {
      id: "moonshotai/Kimi-K2-Thinking",
      name: "Kimi-K2-Thinking",
      api: "openai-completions",
      provider: "huggingface",
      baseUrl: "https://router.huggingface.co/v1",
      compat: { "supportsDeveloperRole": false },
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.6,
        output: 2.5,
        cacheRead: 0.15,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 262144
    },
    "moonshotai/Kimi-K2.5": {
      id: "moonshotai/Kimi-K2.5",
      name: "Kimi-K2.5",
      api: "openai-completions",
      provider: "huggingface",
      baseUrl: "https://router.huggingface.co/v1",
      compat: { "supportsDeveloperRole": false },
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.6,
        output: 3,
        cacheRead: 0.1,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 262144
    },
    "zai-org/GLM-4.7": {
      id: "zai-org/GLM-4.7",
      name: "GLM-4.7",
      api: "openai-completions",
      provider: "huggingface",
      baseUrl: "https://router.huggingface.co/v1",
      compat: { "supportsDeveloperRole": false },
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.6,
        output: 2.2,
        cacheRead: 0.11,
        cacheWrite: 0
      },
      contextWindow: 204800,
      maxTokens: 131072
    },
    "zai-org/GLM-4.7-Flash": {
      id: "zai-org/GLM-4.7-Flash",
      name: "GLM-4.7-Flash",
      api: "openai-completions",
      provider: "huggingface",
      baseUrl: "https://router.huggingface.co/v1",
      compat: { "supportsDeveloperRole": false },
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 2e5,
      maxTokens: 128e3
    },
    "zai-org/GLM-5": {
      id: "zai-org/GLM-5",
      name: "GLM-5",
      api: "openai-completions",
      provider: "huggingface",
      baseUrl: "https://router.huggingface.co/v1",
      compat: { "supportsDeveloperRole": false },
      reasoning: true,
      input: ["text"],
      cost: {
        input: 1,
        output: 3.2,
        cacheRead: 0.2,
        cacheWrite: 0
      },
      contextWindow: 202752,
      maxTokens: 131072
    }
  },
  "kimi-coding": {
    "k2p5": {
      id: "k2p5",
      name: "Kimi K2.5",
      api: "anthropic-messages",
      provider: "kimi-coding",
      baseUrl: "https://api.kimi.com/coding",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 32768
    },
    "kimi-k2-thinking": {
      id: "kimi-k2-thinking",
      name: "Kimi K2 Thinking",
      api: "anthropic-messages",
      provider: "kimi-coding",
      baseUrl: "https://api.kimi.com/coding",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 32768
    }
  },
  "minimax": {
    "MiniMax-M2": {
      id: "MiniMax-M2",
      name: "MiniMax-M2",
      api: "anthropic-messages",
      provider: "minimax",
      baseUrl: "https://api.minimax.io/anthropic",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.3,
        output: 1.2,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 196608,
      maxTokens: 128e3
    },
    "MiniMax-M2.1": {
      id: "MiniMax-M2.1",
      name: "MiniMax-M2.1",
      api: "anthropic-messages",
      provider: "minimax",
      baseUrl: "https://api.minimax.io/anthropic",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.3,
        output: 1.2,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 204800,
      maxTokens: 131072
    },
    "MiniMax-M2.5": {
      id: "MiniMax-M2.5",
      name: "MiniMax-M2.5",
      api: "anthropic-messages",
      provider: "minimax",
      baseUrl: "https://api.minimax.io/anthropic",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.3,
        output: 1.2,
        cacheRead: 0.03,
        cacheWrite: 0.375
      },
      contextWindow: 204800,
      maxTokens: 131072
    },
    "MiniMax-M2.5-highspeed": {
      id: "MiniMax-M2.5-highspeed",
      name: "MiniMax-M2.5-highspeed",
      api: "anthropic-messages",
      provider: "minimax",
      baseUrl: "https://api.minimax.io/anthropic",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.6,
        output: 2.4,
        cacheRead: 0.06,
        cacheWrite: 0.375
      },
      contextWindow: 204800,
      maxTokens: 131072
    }
  },
  "minimax-cn": {
    "MiniMax-M2": {
      id: "MiniMax-M2",
      name: "MiniMax-M2",
      api: "anthropic-messages",
      provider: "minimax-cn",
      baseUrl: "https://api.minimaxi.com/anthropic",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.3,
        output: 1.2,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 196608,
      maxTokens: 128e3
    },
    "MiniMax-M2.1": {
      id: "MiniMax-M2.1",
      name: "MiniMax-M2.1",
      api: "anthropic-messages",
      provider: "minimax-cn",
      baseUrl: "https://api.minimaxi.com/anthropic",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.3,
        output: 1.2,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 204800,
      maxTokens: 131072
    },
    "MiniMax-M2.5": {
      id: "MiniMax-M2.5",
      name: "MiniMax-M2.5",
      api: "anthropic-messages",
      provider: "minimax-cn",
      baseUrl: "https://api.minimaxi.com/anthropic",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.3,
        output: 1.2,
        cacheRead: 0.03,
        cacheWrite: 0.375
      },
      contextWindow: 204800,
      maxTokens: 131072
    },
    "MiniMax-M2.5-highspeed": {
      id: "MiniMax-M2.5-highspeed",
      name: "MiniMax-M2.5-highspeed",
      api: "anthropic-messages",
      provider: "minimax-cn",
      baseUrl: "https://api.minimaxi.com/anthropic",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.6,
        output: 2.4,
        cacheRead: 0.06,
        cacheWrite: 0.375
      },
      contextWindow: 204800,
      maxTokens: 131072
    }
  },
  "mistral": {
    "codestral-latest": {
      id: "codestral-latest",
      name: "Codestral (latest)",
      api: "mistral-conversations",
      provider: "mistral",
      baseUrl: "https://api.mistral.ai",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.3,
        output: 0.9,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 256e3,
      maxTokens: 4096
    },
    "devstral-2512": {
      id: "devstral-2512",
      name: "Devstral 2",
      api: "mistral-conversations",
      provider: "mistral",
      baseUrl: "https://api.mistral.ai",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.4,
        output: 2,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 262144
    },
    "devstral-medium-2507": {
      id: "devstral-medium-2507",
      name: "Devstral Medium",
      api: "mistral-conversations",
      provider: "mistral",
      baseUrl: "https://api.mistral.ai",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.4,
        output: 2,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 128e3
    },
    "devstral-medium-latest": {
      id: "devstral-medium-latest",
      name: "Devstral 2 (latest)",
      api: "mistral-conversations",
      provider: "mistral",
      baseUrl: "https://api.mistral.ai",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.4,
        output: 2,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 262144
    },
    "devstral-small-2505": {
      id: "devstral-small-2505",
      name: "Devstral Small 2505",
      api: "mistral-conversations",
      provider: "mistral",
      baseUrl: "https://api.mistral.ai",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.1,
        output: 0.3,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 128e3
    },
    "devstral-small-2507": {
      id: "devstral-small-2507",
      name: "Devstral Small",
      api: "mistral-conversations",
      provider: "mistral",
      baseUrl: "https://api.mistral.ai",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.1,
        output: 0.3,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 128e3
    },
    "labs-devstral-small-2512": {
      id: "labs-devstral-small-2512",
      name: "Devstral Small 2",
      api: "mistral-conversations",
      provider: "mistral",
      baseUrl: "https://api.mistral.ai",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 256e3,
      maxTokens: 256e3
    },
    "magistral-medium-latest": {
      id: "magistral-medium-latest",
      name: "Magistral Medium (latest)",
      api: "mistral-conversations",
      provider: "mistral",
      baseUrl: "https://api.mistral.ai",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 2,
        output: 5,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 16384
    },
    "magistral-small": {
      id: "magistral-small",
      name: "Magistral Small",
      api: "mistral-conversations",
      provider: "mistral",
      baseUrl: "https://api.mistral.ai",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.5,
        output: 1.5,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 128e3
    },
    "ministral-3b-latest": {
      id: "ministral-3b-latest",
      name: "Ministral 3B (latest)",
      api: "mistral-conversations",
      provider: "mistral",
      baseUrl: "https://api.mistral.ai",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.04,
        output: 0.04,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 128e3
    },
    "ministral-8b-latest": {
      id: "ministral-8b-latest",
      name: "Ministral 8B (latest)",
      api: "mistral-conversations",
      provider: "mistral",
      baseUrl: "https://api.mistral.ai",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.1,
        output: 0.1,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 128e3
    },
    "mistral-large-2411": {
      id: "mistral-large-2411",
      name: "Mistral Large 2.1",
      api: "mistral-conversations",
      provider: "mistral",
      baseUrl: "https://api.mistral.ai",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 2,
        output: 6,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 16384
    },
    "mistral-large-2512": {
      id: "mistral-large-2512",
      name: "Mistral Large 3",
      api: "mistral-conversations",
      provider: "mistral",
      baseUrl: "https://api.mistral.ai",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.5,
        output: 1.5,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 262144
    },
    "mistral-large-latest": {
      id: "mistral-large-latest",
      name: "Mistral Large (latest)",
      api: "mistral-conversations",
      provider: "mistral",
      baseUrl: "https://api.mistral.ai",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.5,
        output: 1.5,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 262144
    },
    "mistral-medium-2505": {
      id: "mistral-medium-2505",
      name: "Mistral Medium 3",
      api: "mistral-conversations",
      provider: "mistral",
      baseUrl: "https://api.mistral.ai",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.4,
        output: 2,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 131072
    },
    "mistral-medium-2508": {
      id: "mistral-medium-2508",
      name: "Mistral Medium 3.1",
      api: "mistral-conversations",
      provider: "mistral",
      baseUrl: "https://api.mistral.ai",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.4,
        output: 2,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 262144
    },
    "mistral-medium-latest": {
      id: "mistral-medium-latest",
      name: "Mistral Medium (latest)",
      api: "mistral-conversations",
      provider: "mistral",
      baseUrl: "https://api.mistral.ai",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.4,
        output: 2,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 16384
    },
    "mistral-nemo": {
      id: "mistral-nemo",
      name: "Mistral Nemo",
      api: "mistral-conversations",
      provider: "mistral",
      baseUrl: "https://api.mistral.ai",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.15,
        output: 0.15,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 128e3
    },
    "mistral-small-2506": {
      id: "mistral-small-2506",
      name: "Mistral Small 3.2",
      api: "mistral-conversations",
      provider: "mistral",
      baseUrl: "https://api.mistral.ai",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.1,
        output: 0.3,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 16384
    },
    "mistral-small-latest": {
      id: "mistral-small-latest",
      name: "Mistral Small (latest)",
      api: "mistral-conversations",
      provider: "mistral",
      baseUrl: "https://api.mistral.ai",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.1,
        output: 0.3,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 16384
    },
    "open-mistral-7b": {
      id: "open-mistral-7b",
      name: "Mistral 7B",
      api: "mistral-conversations",
      provider: "mistral",
      baseUrl: "https://api.mistral.ai",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.25,
        output: 0.25,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 8e3,
      maxTokens: 8e3
    },
    "open-mixtral-8x22b": {
      id: "open-mixtral-8x22b",
      name: "Mixtral 8x22B",
      api: "mistral-conversations",
      provider: "mistral",
      baseUrl: "https://api.mistral.ai",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 2,
        output: 6,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 64e3,
      maxTokens: 64e3
    },
    "open-mixtral-8x7b": {
      id: "open-mixtral-8x7b",
      name: "Mixtral 8x7B",
      api: "mistral-conversations",
      provider: "mistral",
      baseUrl: "https://api.mistral.ai",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.7,
        output: 0.7,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 32e3,
      maxTokens: 32e3
    },
    "pixtral-12b": {
      id: "pixtral-12b",
      name: "Pixtral 12B",
      api: "mistral-conversations",
      provider: "mistral",
      baseUrl: "https://api.mistral.ai",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.15,
        output: 0.15,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 128e3
    },
    "pixtral-large-latest": {
      id: "pixtral-large-latest",
      name: "Pixtral Large (latest)",
      api: "mistral-conversations",
      provider: "mistral",
      baseUrl: "https://api.mistral.ai",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 2,
        output: 6,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 128e3
    }
  },
  "openai": {
    "codex-mini-latest": {
      id: "codex-mini-latest",
      name: "Codex Mini",
      api: "openai-responses",
      provider: "openai",
      baseUrl: "https://api.openai.com/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 1.5,
        output: 6,
        cacheRead: 0.375,
        cacheWrite: 0
      },
      contextWindow: 2e5,
      maxTokens: 1e5
    },
    "gpt-4": {
      id: "gpt-4",
      name: "GPT-4",
      api: "openai-responses",
      provider: "openai",
      baseUrl: "https://api.openai.com/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 30,
        output: 60,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 8192,
      maxTokens: 8192
    },
    "gpt-4-turbo": {
      id: "gpt-4-turbo",
      name: "GPT-4 Turbo",
      api: "openai-responses",
      provider: "openai",
      baseUrl: "https://api.openai.com/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 10,
        output: 30,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 4096
    },
    "gpt-4.1": {
      id: "gpt-4.1",
      name: "GPT-4.1",
      api: "openai-responses",
      provider: "openai",
      baseUrl: "https://api.openai.com/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 2,
        output: 8,
        cacheRead: 0.5,
        cacheWrite: 0
      },
      contextWindow: 1047576,
      maxTokens: 32768
    },
    "gpt-4.1-mini": {
      id: "gpt-4.1-mini",
      name: "GPT-4.1 mini",
      api: "openai-responses",
      provider: "openai",
      baseUrl: "https://api.openai.com/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.4,
        output: 1.6,
        cacheRead: 0.1,
        cacheWrite: 0
      },
      contextWindow: 1047576,
      maxTokens: 32768
    },
    "gpt-4.1-nano": {
      id: "gpt-4.1-nano",
      name: "GPT-4.1 nano",
      api: "openai-responses",
      provider: "openai",
      baseUrl: "https://api.openai.com/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.1,
        output: 0.4,
        cacheRead: 0.03,
        cacheWrite: 0
      },
      contextWindow: 1047576,
      maxTokens: 32768
    },
    "gpt-4o": {
      id: "gpt-4o",
      name: "GPT-4o",
      api: "openai-responses",
      provider: "openai",
      baseUrl: "https://api.openai.com/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 2.5,
        output: 10,
        cacheRead: 1.25,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 16384
    },
    "gpt-4o-2024-05-13": {
      id: "gpt-4o-2024-05-13",
      name: "GPT-4o (2024-05-13)",
      api: "openai-responses",
      provider: "openai",
      baseUrl: "https://api.openai.com/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 5,
        output: 15,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 4096
    },
    "gpt-4o-2024-08-06": {
      id: "gpt-4o-2024-08-06",
      name: "GPT-4o (2024-08-06)",
      api: "openai-responses",
      provider: "openai",
      baseUrl: "https://api.openai.com/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 2.5,
        output: 10,
        cacheRead: 1.25,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 16384
    },
    "gpt-4o-2024-11-20": {
      id: "gpt-4o-2024-11-20",
      name: "GPT-4o (2024-11-20)",
      api: "openai-responses",
      provider: "openai",
      baseUrl: "https://api.openai.com/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 2.5,
        output: 10,
        cacheRead: 1.25,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 16384
    },
    "gpt-4o-mini": {
      id: "gpt-4o-mini",
      name: "GPT-4o mini",
      api: "openai-responses",
      provider: "openai",
      baseUrl: "https://api.openai.com/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.15,
        output: 0.6,
        cacheRead: 0.08,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 16384
    },
    "gpt-5": {
      id: "gpt-5",
      name: "GPT-5",
      api: "openai-responses",
      provider: "openai",
      baseUrl: "https://api.openai.com/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.25,
        output: 10,
        cacheRead: 0.125,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "gpt-5-chat-latest": {
      id: "gpt-5-chat-latest",
      name: "GPT-5 Chat Latest",
      api: "openai-responses",
      provider: "openai",
      baseUrl: "https://api.openai.com/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 1.25,
        output: 10,
        cacheRead: 0.125,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 16384
    },
    "gpt-5-codex": {
      id: "gpt-5-codex",
      name: "GPT-5-Codex",
      api: "openai-responses",
      provider: "openai",
      baseUrl: "https://api.openai.com/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.25,
        output: 10,
        cacheRead: 0.125,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "gpt-5-mini": {
      id: "gpt-5-mini",
      name: "GPT-5 Mini",
      api: "openai-responses",
      provider: "openai",
      baseUrl: "https://api.openai.com/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.25,
        output: 2,
        cacheRead: 0.025,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "gpt-5-nano": {
      id: "gpt-5-nano",
      name: "GPT-5 Nano",
      api: "openai-responses",
      provider: "openai",
      baseUrl: "https://api.openai.com/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.05,
        output: 0.4,
        cacheRead: 5e-3,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "gpt-5-pro": {
      id: "gpt-5-pro",
      name: "GPT-5 Pro",
      api: "openai-responses",
      provider: "openai",
      baseUrl: "https://api.openai.com/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 15,
        output: 120,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 272e3
    },
    "gpt-5.1": {
      id: "gpt-5.1",
      name: "GPT-5.1",
      api: "openai-responses",
      provider: "openai",
      baseUrl: "https://api.openai.com/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.25,
        output: 10,
        cacheRead: 0.13,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "gpt-5.1-chat-latest": {
      id: "gpt-5.1-chat-latest",
      name: "GPT-5.1 Chat",
      api: "openai-responses",
      provider: "openai",
      baseUrl: "https://api.openai.com/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.25,
        output: 10,
        cacheRead: 0.125,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 16384
    },
    "gpt-5.1-codex": {
      id: "gpt-5.1-codex",
      name: "GPT-5.1 Codex",
      api: "openai-responses",
      provider: "openai",
      baseUrl: "https://api.openai.com/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.25,
        output: 10,
        cacheRead: 0.125,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "gpt-5.1-codex-max": {
      id: "gpt-5.1-codex-max",
      name: "GPT-5.1 Codex Max",
      api: "openai-responses",
      provider: "openai",
      baseUrl: "https://api.openai.com/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.25,
        output: 10,
        cacheRead: 0.125,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "gpt-5.1-codex-mini": {
      id: "gpt-5.1-codex-mini",
      name: "GPT-5.1 Codex mini",
      api: "openai-responses",
      provider: "openai",
      baseUrl: "https://api.openai.com/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.25,
        output: 2,
        cacheRead: 0.025,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "gpt-5.2": {
      id: "gpt-5.2",
      name: "GPT-5.2",
      api: "openai-responses",
      provider: "openai",
      baseUrl: "https://api.openai.com/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.75,
        output: 14,
        cacheRead: 0.175,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "gpt-5.2-chat-latest": {
      id: "gpt-5.2-chat-latest",
      name: "GPT-5.2 Chat",
      api: "openai-responses",
      provider: "openai",
      baseUrl: "https://api.openai.com/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.75,
        output: 14,
        cacheRead: 0.175,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 16384
    },
    "gpt-5.2-codex": {
      id: "gpt-5.2-codex",
      name: "GPT-5.2 Codex",
      api: "openai-responses",
      provider: "openai",
      baseUrl: "https://api.openai.com/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.75,
        output: 14,
        cacheRead: 0.175,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "gpt-5.2-pro": {
      id: "gpt-5.2-pro",
      name: "GPT-5.2 Pro",
      api: "openai-responses",
      provider: "openai",
      baseUrl: "https://api.openai.com/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 21,
        output: 168,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "gpt-5.3-codex": {
      id: "gpt-5.3-codex",
      name: "GPT-5.3 Codex",
      api: "openai-responses",
      provider: "openai",
      baseUrl: "https://api.openai.com/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.75,
        output: 14,
        cacheRead: 0.175,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "gpt-5.3-codex-spark": {
      id: "gpt-5.3-codex-spark",
      name: "GPT-5.3 Codex Spark",
      api: "openai-responses",
      provider: "openai",
      baseUrl: "https://api.openai.com/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.75,
        output: 14,
        cacheRead: 0.175,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 32e3
    },
    "gpt-5.4": {
      id: "gpt-5.4",
      name: "GPT-5.4",
      api: "openai-responses",
      provider: "openai",
      baseUrl: "https://api.openai.com/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 2.5,
        output: 15,
        cacheRead: 0.25,
        cacheWrite: 0
      },
      contextWindow: 272e3,
      maxTokens: 128e3
    },
    "gpt-5.4-pro": {
      id: "gpt-5.4-pro",
      name: "GPT-5.4 Pro",
      api: "openai-responses",
      provider: "openai",
      baseUrl: "https://api.openai.com/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 30,
        output: 180,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 105e4,
      maxTokens: 128e3
    },
    "o1": {
      id: "o1",
      name: "o1",
      api: "openai-responses",
      provider: "openai",
      baseUrl: "https://api.openai.com/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 15,
        output: 60,
        cacheRead: 7.5,
        cacheWrite: 0
      },
      contextWindow: 2e5,
      maxTokens: 1e5
    },
    "o1-pro": {
      id: "o1-pro",
      name: "o1-pro",
      api: "openai-responses",
      provider: "openai",
      baseUrl: "https://api.openai.com/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 150,
        output: 600,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 2e5,
      maxTokens: 1e5
    },
    "o3": {
      id: "o3",
      name: "o3",
      api: "openai-responses",
      provider: "openai",
      baseUrl: "https://api.openai.com/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 2,
        output: 8,
        cacheRead: 0.5,
        cacheWrite: 0
      },
      contextWindow: 2e5,
      maxTokens: 1e5
    },
    "o3-deep-research": {
      id: "o3-deep-research",
      name: "o3-deep-research",
      api: "openai-responses",
      provider: "openai",
      baseUrl: "https://api.openai.com/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 10,
        output: 40,
        cacheRead: 2.5,
        cacheWrite: 0
      },
      contextWindow: 2e5,
      maxTokens: 1e5
    },
    "o3-mini": {
      id: "o3-mini",
      name: "o3-mini",
      api: "openai-responses",
      provider: "openai",
      baseUrl: "https://api.openai.com/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 1.1,
        output: 4.4,
        cacheRead: 0.55,
        cacheWrite: 0
      },
      contextWindow: 2e5,
      maxTokens: 1e5
    },
    "o3-pro": {
      id: "o3-pro",
      name: "o3-pro",
      api: "openai-responses",
      provider: "openai",
      baseUrl: "https://api.openai.com/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 20,
        output: 80,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 2e5,
      maxTokens: 1e5
    },
    "o4-mini": {
      id: "o4-mini",
      name: "o4-mini",
      api: "openai-responses",
      provider: "openai",
      baseUrl: "https://api.openai.com/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.1,
        output: 4.4,
        cacheRead: 0.28,
        cacheWrite: 0
      },
      contextWindow: 2e5,
      maxTokens: 1e5
    },
    "o4-mini-deep-research": {
      id: "o4-mini-deep-research",
      name: "o4-mini-deep-research",
      api: "openai-responses",
      provider: "openai",
      baseUrl: "https://api.openai.com/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 2,
        output: 8,
        cacheRead: 0.5,
        cacheWrite: 0
      },
      contextWindow: 2e5,
      maxTokens: 1e5
    }
  },
  "openai-codex": {
    "gpt-5.1": {
      id: "gpt-5.1",
      name: "GPT-5.1",
      api: "openai-codex-responses",
      provider: "openai-codex",
      baseUrl: "https://chatgpt.com/backend-api",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.25,
        output: 10,
        cacheRead: 0.125,
        cacheWrite: 0
      },
      contextWindow: 272e3,
      maxTokens: 128e3
    },
    "gpt-5.1-codex-max": {
      id: "gpt-5.1-codex-max",
      name: "GPT-5.1 Codex Max",
      api: "openai-codex-responses",
      provider: "openai-codex",
      baseUrl: "https://chatgpt.com/backend-api",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.25,
        output: 10,
        cacheRead: 0.125,
        cacheWrite: 0
      },
      contextWindow: 272e3,
      maxTokens: 128e3
    },
    "gpt-5.1-codex-mini": {
      id: "gpt-5.1-codex-mini",
      name: "GPT-5.1 Codex Mini",
      api: "openai-codex-responses",
      provider: "openai-codex",
      baseUrl: "https://chatgpt.com/backend-api",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.25,
        output: 2,
        cacheRead: 0.025,
        cacheWrite: 0
      },
      contextWindow: 272e3,
      maxTokens: 128e3
    },
    "gpt-5.2": {
      id: "gpt-5.2",
      name: "GPT-5.2",
      api: "openai-codex-responses",
      provider: "openai-codex",
      baseUrl: "https://chatgpt.com/backend-api",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.75,
        output: 14,
        cacheRead: 0.175,
        cacheWrite: 0
      },
      contextWindow: 272e3,
      maxTokens: 128e3
    },
    "gpt-5.2-codex": {
      id: "gpt-5.2-codex",
      name: "GPT-5.2 Codex",
      api: "openai-codex-responses",
      provider: "openai-codex",
      baseUrl: "https://chatgpt.com/backend-api",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.75,
        output: 14,
        cacheRead: 0.175,
        cacheWrite: 0
      },
      contextWindow: 272e3,
      maxTokens: 128e3
    },
    "gpt-5.3-codex": {
      id: "gpt-5.3-codex",
      name: "GPT-5.3 Codex",
      api: "openai-codex-responses",
      provider: "openai-codex",
      baseUrl: "https://chatgpt.com/backend-api",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.75,
        output: 14,
        cacheRead: 0.175,
        cacheWrite: 0
      },
      contextWindow: 272e3,
      maxTokens: 128e3
    },
    "gpt-5.3-codex-spark": {
      id: "gpt-5.3-codex-spark",
      name: "GPT-5.3 Codex Spark",
      api: "openai-codex-responses",
      provider: "openai-codex",
      baseUrl: "https://chatgpt.com/backend-api",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 128e3
    },
    "gpt-5.4": {
      id: "gpt-5.4",
      name: "GPT-5.4",
      api: "openai-codex-responses",
      provider: "openai-codex",
      baseUrl: "https://chatgpt.com/backend-api",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 2.5,
        output: 15,
        cacheRead: 0.25,
        cacheWrite: 0
      },
      contextWindow: 272e3,
      maxTokens: 128e3
    }
  },
  "opencode": {
    "big-pickle": {
      id: "big-pickle",
      name: "Big Pickle",
      api: "anthropic-messages",
      provider: "opencode",
      baseUrl: "https://opencode.ai/zen",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 2e5,
      maxTokens: 128e3
    },
    "claude-3-5-haiku": {
      id: "claude-3-5-haiku",
      name: "Claude Haiku 3.5",
      api: "anthropic-messages",
      provider: "opencode",
      baseUrl: "https://opencode.ai/zen",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.8,
        output: 4,
        cacheRead: 0.08,
        cacheWrite: 1
      },
      contextWindow: 2e5,
      maxTokens: 8192
    },
    "claude-haiku-4-5": {
      id: "claude-haiku-4-5",
      name: "Claude Haiku 4.5",
      api: "anthropic-messages",
      provider: "opencode",
      baseUrl: "https://opencode.ai/zen",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1,
        output: 5,
        cacheRead: 0.1,
        cacheWrite: 1.25
      },
      contextWindow: 2e5,
      maxTokens: 64e3
    },
    "claude-opus-4-1": {
      id: "claude-opus-4-1",
      name: "Claude Opus 4.1",
      api: "anthropic-messages",
      provider: "opencode",
      baseUrl: "https://opencode.ai/zen",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 15,
        output: 75,
        cacheRead: 1.5,
        cacheWrite: 18.75
      },
      contextWindow: 2e5,
      maxTokens: 32e3
    },
    "claude-opus-4-5": {
      id: "claude-opus-4-5",
      name: "Claude Opus 4.5",
      api: "anthropic-messages",
      provider: "opencode",
      baseUrl: "https://opencode.ai/zen",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 5,
        output: 25,
        cacheRead: 0.5,
        cacheWrite: 6.25
      },
      contextWindow: 2e5,
      maxTokens: 64e3
    },
    "claude-opus-4-6": {
      id: "claude-opus-4-6",
      name: "Claude Opus 4.6",
      api: "anthropic-messages",
      provider: "opencode",
      baseUrl: "https://opencode.ai/zen",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 5,
        output: 25,
        cacheRead: 0.5,
        cacheWrite: 6.25
      },
      contextWindow: 1e6,
      maxTokens: 128e3
    },
    "claude-sonnet-4": {
      id: "claude-sonnet-4",
      name: "Claude Sonnet 4",
      api: "anthropic-messages",
      provider: "opencode",
      baseUrl: "https://opencode.ai/zen",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.3,
        cacheWrite: 3.75
      },
      contextWindow: 2e5,
      maxTokens: 64e3
    },
    "claude-sonnet-4-5": {
      id: "claude-sonnet-4-5",
      name: "Claude Sonnet 4.5",
      api: "anthropic-messages",
      provider: "opencode",
      baseUrl: "https://opencode.ai/zen",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.3,
        cacheWrite: 3.75
      },
      contextWindow: 2e5,
      maxTokens: 64e3
    },
    "claude-sonnet-4-6": {
      id: "claude-sonnet-4-6",
      name: "Claude Sonnet 4.6",
      api: "anthropic-messages",
      provider: "opencode",
      baseUrl: "https://opencode.ai/zen",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.3,
        cacheWrite: 3.75
      },
      contextWindow: 1e6,
      maxTokens: 64e3
    },
    "gemini-3-flash": {
      id: "gemini-3-flash",
      name: "Gemini 3 Flash",
      api: "google-generative-ai",
      provider: "opencode",
      baseUrl: "https://opencode.ai/zen/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.5,
        output: 3,
        cacheRead: 0.05,
        cacheWrite: 0
      },
      contextWindow: 1048576,
      maxTokens: 65536
    },
    "gemini-3-pro": {
      id: "gemini-3-pro",
      name: "Gemini 3 Pro",
      api: "google-generative-ai",
      provider: "opencode",
      baseUrl: "https://opencode.ai/zen/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 2,
        output: 12,
        cacheRead: 0.2,
        cacheWrite: 0
      },
      contextWindow: 1048576,
      maxTokens: 65536
    },
    "gemini-3.1-pro": {
      id: "gemini-3.1-pro",
      name: "Gemini 3.1 Pro Preview",
      api: "google-generative-ai",
      provider: "opencode",
      baseUrl: "https://opencode.ai/zen/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 2,
        output: 12,
        cacheRead: 0.2,
        cacheWrite: 0
      },
      contextWindow: 1048576,
      maxTokens: 65536
    },
    "glm-4.6": {
      id: "glm-4.6",
      name: "GLM-4.6",
      api: "openai-completions",
      provider: "opencode",
      baseUrl: "https://opencode.ai/zen/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.6,
        output: 2.2,
        cacheRead: 0.1,
        cacheWrite: 0
      },
      contextWindow: 204800,
      maxTokens: 131072
    },
    "glm-4.7": {
      id: "glm-4.7",
      name: "GLM-4.7",
      api: "openai-completions",
      provider: "opencode",
      baseUrl: "https://opencode.ai/zen/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.6,
        output: 2.2,
        cacheRead: 0.1,
        cacheWrite: 0
      },
      contextWindow: 204800,
      maxTokens: 131072
    },
    "glm-5": {
      id: "glm-5",
      name: "GLM-5",
      api: "openai-completions",
      provider: "opencode",
      baseUrl: "https://opencode.ai/zen/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 1,
        output: 3.2,
        cacheRead: 0.2,
        cacheWrite: 0
      },
      contextWindow: 204800,
      maxTokens: 131072
    },
    "gpt-5": {
      id: "gpt-5",
      name: "GPT-5",
      api: "openai-responses",
      provider: "opencode",
      baseUrl: "https://opencode.ai/zen/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.07,
        output: 8.5,
        cacheRead: 0.107,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "gpt-5-codex": {
      id: "gpt-5-codex",
      name: "GPT-5 Codex",
      api: "openai-responses",
      provider: "opencode",
      baseUrl: "https://opencode.ai/zen/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.07,
        output: 8.5,
        cacheRead: 0.107,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "gpt-5-nano": {
      id: "gpt-5-nano",
      name: "GPT-5 Nano",
      api: "openai-responses",
      provider: "opencode",
      baseUrl: "https://opencode.ai/zen/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "gpt-5.1": {
      id: "gpt-5.1",
      name: "GPT-5.1",
      api: "openai-responses",
      provider: "opencode",
      baseUrl: "https://opencode.ai/zen/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.07,
        output: 8.5,
        cacheRead: 0.107,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "gpt-5.1-codex": {
      id: "gpt-5.1-codex",
      name: "GPT-5.1 Codex",
      api: "openai-responses",
      provider: "opencode",
      baseUrl: "https://opencode.ai/zen/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.07,
        output: 8.5,
        cacheRead: 0.107,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "gpt-5.1-codex-max": {
      id: "gpt-5.1-codex-max",
      name: "GPT-5.1 Codex Max",
      api: "openai-responses",
      provider: "opencode",
      baseUrl: "https://opencode.ai/zen/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.25,
        output: 10,
        cacheRead: 0.125,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "gpt-5.1-codex-mini": {
      id: "gpt-5.1-codex-mini",
      name: "GPT-5.1 Codex Mini",
      api: "openai-responses",
      provider: "opencode",
      baseUrl: "https://opencode.ai/zen/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.25,
        output: 2,
        cacheRead: 0.025,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "gpt-5.2": {
      id: "gpt-5.2",
      name: "GPT-5.2",
      api: "openai-responses",
      provider: "opencode",
      baseUrl: "https://opencode.ai/zen/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.75,
        output: 14,
        cacheRead: 0.175,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "gpt-5.2-codex": {
      id: "gpt-5.2-codex",
      name: "GPT-5.2 Codex",
      api: "openai-responses",
      provider: "opencode",
      baseUrl: "https://opencode.ai/zen/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.75,
        output: 14,
        cacheRead: 0.175,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "gpt-5.3-codex": {
      id: "gpt-5.3-codex",
      name: "GPT-5.3 Codex",
      api: "openai-responses",
      provider: "opencode",
      baseUrl: "https://opencode.ai/zen/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.75,
        output: 14,
        cacheRead: 0.175,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "gpt-5.4": {
      id: "gpt-5.4",
      name: "GPT-5.4",
      api: "openai-responses",
      provider: "opencode",
      baseUrl: "https://opencode.ai/zen/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 2.5,
        output: 15,
        cacheRead: 0.25,
        cacheWrite: 0
      },
      contextWindow: 272e3,
      maxTokens: 128e3
    },
    "gpt-5.4-pro": {
      id: "gpt-5.4-pro",
      name: "GPT-5.4 Pro",
      api: "openai-responses",
      provider: "opencode",
      baseUrl: "https://opencode.ai/zen/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 30,
        output: 180,
        cacheRead: 30,
        cacheWrite: 0
      },
      contextWindow: 105e4,
      maxTokens: 128e3
    },
    "kimi-k2.5": {
      id: "kimi-k2.5",
      name: "Kimi K2.5",
      api: "openai-completions",
      provider: "opencode",
      baseUrl: "https://opencode.ai/zen/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.6,
        output: 3,
        cacheRead: 0.08,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 65536
    },
    "mimo-v2-flash-free": {
      id: "mimo-v2-flash-free",
      name: "MiMo V2 Flash Free",
      api: "openai-completions",
      provider: "opencode",
      baseUrl: "https://opencode.ai/zen/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 65536
    },
    "minimax-m2.1": {
      id: "minimax-m2.1",
      name: "MiniMax M2.1",
      api: "openai-completions",
      provider: "opencode",
      baseUrl: "https://opencode.ai/zen/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.3,
        output: 1.2,
        cacheRead: 0.1,
        cacheWrite: 0
      },
      contextWindow: 204800,
      maxTokens: 131072
    },
    "minimax-m2.5": {
      id: "minimax-m2.5",
      name: "MiniMax M2.5",
      api: "openai-completions",
      provider: "opencode",
      baseUrl: "https://opencode.ai/zen/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.3,
        output: 1.2,
        cacheRead: 0.06,
        cacheWrite: 0
      },
      contextWindow: 204800,
      maxTokens: 131072
    },
    "minimax-m2.5-free": {
      id: "minimax-m2.5-free",
      name: "MiniMax M2.5 Free",
      api: "anthropic-messages",
      provider: "opencode",
      baseUrl: "https://opencode.ai/zen",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 204800,
      maxTokens: 131072
    },
    "nemotron-3-super-free": {
      id: "nemotron-3-super-free",
      name: "Nemotron 3 Super Free",
      api: "openai-completions",
      provider: "opencode",
      baseUrl: "https://opencode.ai/zen/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 1e6,
      maxTokens: 128e3
    }
  },
  "opencode-go": {
    "glm-5": {
      id: "glm-5",
      name: "GLM-5",
      api: "openai-completions",
      provider: "opencode-go",
      baseUrl: "https://opencode.ai/zen/go/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 1,
        output: 3.2,
        cacheRead: 0.2,
        cacheWrite: 0
      },
      contextWindow: 204800,
      maxTokens: 131072
    },
    "kimi-k2.5": {
      id: "kimi-k2.5",
      name: "Kimi K2.5",
      api: "openai-completions",
      provider: "opencode-go",
      baseUrl: "https://opencode.ai/zen/go/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.6,
        output: 3,
        cacheRead: 0.1,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 65536
    },
    "minimax-m2.5": {
      id: "minimax-m2.5",
      name: "MiniMax M2.5",
      api: "anthropic-messages",
      provider: "opencode-go",
      baseUrl: "https://opencode.ai/zen/go",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.3,
        output: 1.2,
        cacheRead: 0.03,
        cacheWrite: 0
      },
      contextWindow: 204800,
      maxTokens: 131072
    }
  },
  "openrouter": {
    "ai21/jamba-large-1.7": {
      id: "ai21/jamba-large-1.7",
      name: "AI21: Jamba Large 1.7",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 2,
        output: 8,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 256e3,
      maxTokens: 4096
    },
    "alibaba/tongyi-deepresearch-30b-a3b": {
      id: "alibaba/tongyi-deepresearch-30b-a3b",
      name: "Tongyi DeepResearch 30B A3B",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.09,
        output: 0.44999999999999996,
        cacheRead: 0.09,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 131072
    },
    "allenai/olmo-3.1-32b-instruct": {
      id: "allenai/olmo-3.1-32b-instruct",
      name: "AllenAI: Olmo 3.1 32B Instruct",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.19999999999999998,
        output: 0.6,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 65536,
      maxTokens: 4096
    },
    "amazon/nova-2-lite-v1": {
      id: "amazon/nova-2-lite-v1",
      name: "Amazon: Nova 2 Lite",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.3,
        output: 2.5,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 1e6,
      maxTokens: 65535
    },
    "amazon/nova-lite-v1": {
      id: "amazon/nova-lite-v1",
      name: "Amazon: Nova Lite 1.0",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.06,
        output: 0.24,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 3e5,
      maxTokens: 5120
    },
    "amazon/nova-micro-v1": {
      id: "amazon/nova-micro-v1",
      name: "Amazon: Nova Micro 1.0",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.035,
        output: 0.14,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 5120
    },
    "amazon/nova-premier-v1": {
      id: "amazon/nova-premier-v1",
      name: "Amazon: Nova Premier 1.0",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 2.5,
        output: 12.5,
        cacheRead: 0.625,
        cacheWrite: 0
      },
      contextWindow: 1e6,
      maxTokens: 32e3
    },
    "amazon/nova-pro-v1": {
      id: "amazon/nova-pro-v1",
      name: "Amazon: Nova Pro 1.0",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.7999999999999999,
        output: 3.1999999999999997,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 3e5,
      maxTokens: 5120
    },
    "anthropic/claude-3-haiku": {
      id: "anthropic/claude-3-haiku",
      name: "Anthropic: Claude 3 Haiku",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.25,
        output: 1.25,
        cacheRead: 0.03,
        cacheWrite: 0.3
      },
      contextWindow: 2e5,
      maxTokens: 4096
    },
    "anthropic/claude-3.5-haiku": {
      id: "anthropic/claude-3.5-haiku",
      name: "Anthropic: Claude 3.5 Haiku",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.7999999999999999,
        output: 4,
        cacheRead: 0.08,
        cacheWrite: 1
      },
      contextWindow: 2e5,
      maxTokens: 8192
    },
    "anthropic/claude-3.5-sonnet": {
      id: "anthropic/claude-3.5-sonnet",
      name: "Anthropic: Claude 3.5 Sonnet",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 6,
        output: 30,
        cacheRead: 0.6,
        cacheWrite: 7.5
      },
      contextWindow: 2e5,
      maxTokens: 8192
    },
    "anthropic/claude-3.7-sonnet": {
      id: "anthropic/claude-3.7-sonnet",
      name: "Anthropic: Claude 3.7 Sonnet",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.3,
        cacheWrite: 3.75
      },
      contextWindow: 2e5,
      maxTokens: 64e3
    },
    "anthropic/claude-3.7-sonnet:thinking": {
      id: "anthropic/claude-3.7-sonnet:thinking",
      name: "Anthropic: Claude 3.7 Sonnet (thinking)",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.3,
        cacheWrite: 3.75
      },
      contextWindow: 2e5,
      maxTokens: 64e3
    },
    "anthropic/claude-haiku-4.5": {
      id: "anthropic/claude-haiku-4.5",
      name: "Anthropic: Claude Haiku 4.5",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1,
        output: 5,
        cacheRead: 0.09999999999999999,
        cacheWrite: 1.25
      },
      contextWindow: 2e5,
      maxTokens: 64e3
    },
    "anthropic/claude-opus-4": {
      id: "anthropic/claude-opus-4",
      name: "Anthropic: Claude Opus 4",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 15,
        output: 75,
        cacheRead: 1.5,
        cacheWrite: 18.75
      },
      contextWindow: 2e5,
      maxTokens: 32e3
    },
    "anthropic/claude-opus-4.1": {
      id: "anthropic/claude-opus-4.1",
      name: "Anthropic: Claude Opus 4.1",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 15,
        output: 75,
        cacheRead: 1.5,
        cacheWrite: 18.75
      },
      contextWindow: 2e5,
      maxTokens: 32e3
    },
    "anthropic/claude-opus-4.5": {
      id: "anthropic/claude-opus-4.5",
      name: "Anthropic: Claude Opus 4.5",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 5,
        output: 25,
        cacheRead: 0.5,
        cacheWrite: 6.25
      },
      contextWindow: 2e5,
      maxTokens: 64e3
    },
    "anthropic/claude-opus-4.6": {
      id: "anthropic/claude-opus-4.6",
      name: "Anthropic: Claude Opus 4.6",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 5,
        output: 25,
        cacheRead: 0.5,
        cacheWrite: 6.25
      },
      contextWindow: 1e6,
      maxTokens: 128e3
    },
    "anthropic/claude-sonnet-4": {
      id: "anthropic/claude-sonnet-4",
      name: "Anthropic: Claude Sonnet 4",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.3,
        cacheWrite: 3.75
      },
      contextWindow: 2e5,
      maxTokens: 64e3
    },
    "anthropic/claude-sonnet-4.5": {
      id: "anthropic/claude-sonnet-4.5",
      name: "Anthropic: Claude Sonnet 4.5",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.3,
        cacheWrite: 3.75
      },
      contextWindow: 1e6,
      maxTokens: 64e3
    },
    "anthropic/claude-sonnet-4.6": {
      id: "anthropic/claude-sonnet-4.6",
      name: "Anthropic: Claude Sonnet 4.6",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.3,
        cacheWrite: 3.75
      },
      contextWindow: 1e6,
      maxTokens: 128e3
    },
    "arcee-ai/trinity-large-preview:free": {
      id: "arcee-ai/trinity-large-preview:free",
      name: "Arcee AI: Trinity Large Preview (free)",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131e3,
      maxTokens: 4096
    },
    "arcee-ai/trinity-mini": {
      id: "arcee-ai/trinity-mini",
      name: "Arcee AI: Trinity Mini",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.045,
        output: 0.15,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 131072
    },
    "arcee-ai/trinity-mini:free": {
      id: "arcee-ai/trinity-mini:free",
      name: "Arcee AI: Trinity Mini (free)",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 4096
    },
    "arcee-ai/virtuoso-large": {
      id: "arcee-ai/virtuoso-large",
      name: "Arcee AI: Virtuoso Large",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.75,
        output: 1.2,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 64e3
    },
    "auto": {
      id: "auto",
      name: "Auto",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 2e6,
      maxTokens: 3e4
    },
    "baidu/ernie-4.5-21b-a3b": {
      id: "baidu/ernie-4.5-21b-a3b",
      name: "Baidu: ERNIE 4.5 21B A3B",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.07,
        output: 0.28,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 12e4,
      maxTokens: 8e3
    },
    "baidu/ernie-4.5-vl-28b-a3b": {
      id: "baidu/ernie-4.5-vl-28b-a3b",
      name: "Baidu: ERNIE 4.5 VL 28B A3B",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.14,
        output: 0.56,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 3e4,
      maxTokens: 8e3
    },
    "bytedance-seed/seed-1.6": {
      id: "bytedance-seed/seed-1.6",
      name: "ByteDance Seed: Seed 1.6",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.25,
        output: 2,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 32768
    },
    "bytedance-seed/seed-1.6-flash": {
      id: "bytedance-seed/seed-1.6-flash",
      name: "ByteDance Seed: Seed 1.6 Flash",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.075,
        output: 0.3,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 32768
    },
    "bytedance-seed/seed-2.0-lite": {
      id: "bytedance-seed/seed-2.0-lite",
      name: "ByteDance Seed: Seed-2.0-Lite",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.25,
        output: 2,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 131072
    },
    "bytedance-seed/seed-2.0-mini": {
      id: "bytedance-seed/seed-2.0-mini",
      name: "ByteDance Seed: Seed-2.0-Mini",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.09999999999999999,
        output: 0.39999999999999997,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 131072
    },
    "cohere/command-r-08-2024": {
      id: "cohere/command-r-08-2024",
      name: "Cohere: Command R (08-2024)",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.15,
        output: 0.6,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 4e3
    },
    "cohere/command-r-plus-08-2024": {
      id: "cohere/command-r-plus-08-2024",
      name: "Cohere: Command R+ (08-2024)",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 2.5,
        output: 10,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 4e3
    },
    "deepseek/deepseek-chat": {
      id: "deepseek/deepseek-chat",
      name: "DeepSeek: DeepSeek V3",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.32,
        output: 0.8899999999999999,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 163840,
      maxTokens: 163840
    },
    "deepseek/deepseek-chat-v3-0324": {
      id: "deepseek/deepseek-chat-v3-0324",
      name: "DeepSeek: DeepSeek V3 0324",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.19999999999999998,
        output: 0.77,
        cacheRead: 0.135,
        cacheWrite: 0
      },
      contextWindow: 163840,
      maxTokens: 4096
    },
    "deepseek/deepseek-chat-v3.1": {
      id: "deepseek/deepseek-chat-v3.1",
      name: "DeepSeek: DeepSeek V3.1",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.15,
        output: 0.75,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 32768,
      maxTokens: 7168
    },
    "deepseek/deepseek-r1": {
      id: "deepseek/deepseek-r1",
      name: "DeepSeek: R1",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.7,
        output: 2.5,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 64e3,
      maxTokens: 16e3
    },
    "deepseek/deepseek-r1-0528": {
      id: "deepseek/deepseek-r1-0528",
      name: "DeepSeek: R1 0528",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.44999999999999996,
        output: 2.1500000000000004,
        cacheRead: 0.22499999999999998,
        cacheWrite: 0
      },
      contextWindow: 163840,
      maxTokens: 65536
    },
    "deepseek/deepseek-v3.1-terminus": {
      id: "deepseek/deepseek-v3.1-terminus",
      name: "DeepSeek: DeepSeek V3.1 Terminus",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.21,
        output: 0.7899999999999999,
        cacheRead: 0.1300000002,
        cacheWrite: 0
      },
      contextWindow: 163840,
      maxTokens: 4096
    },
    "deepseek/deepseek-v3.2": {
      id: "deepseek/deepseek-v3.2",
      name: "DeepSeek: DeepSeek V3.2",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.26,
        output: 0.38,
        cacheRead: 0.13,
        cacheWrite: 0
      },
      contextWindow: 163840,
      maxTokens: 4096
    },
    "deepseek/deepseek-v3.2-exp": {
      id: "deepseek/deepseek-v3.2-exp",
      name: "DeepSeek: DeepSeek V3.2 Exp",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.27,
        output: 0.41,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 163840,
      maxTokens: 65536
    },
    "essentialai/rnj-1-instruct": {
      id: "essentialai/rnj-1-instruct",
      name: "EssentialAI: Rnj 1 Instruct",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.15,
        output: 0.15,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 32768,
      maxTokens: 4096
    },
    "google/gemini-2.0-flash-001": {
      id: "google/gemini-2.0-flash-001",
      name: "Google: Gemini 2.0 Flash",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.09999999999999999,
        output: 0.39999999999999997,
        cacheRead: 0.024999999999999998,
        cacheWrite: 0.08333333333333334
      },
      contextWindow: 1048576,
      maxTokens: 8192
    },
    "google/gemini-2.0-flash-lite-001": {
      id: "google/gemini-2.0-flash-lite-001",
      name: "Google: Gemini 2.0 Flash Lite",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.075,
        output: 0.3,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 1048576,
      maxTokens: 8192
    },
    "google/gemini-2.5-flash": {
      id: "google/gemini-2.5-flash",
      name: "Google: Gemini 2.5 Flash",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.3,
        output: 2.5,
        cacheRead: 0.03,
        cacheWrite: 0.08333333333333334
      },
      contextWindow: 1048576,
      maxTokens: 65535
    },
    "google/gemini-2.5-flash-lite": {
      id: "google/gemini-2.5-flash-lite",
      name: "Google: Gemini 2.5 Flash Lite",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.09999999999999999,
        output: 0.39999999999999997,
        cacheRead: 0.01,
        cacheWrite: 0.08333333333333334
      },
      contextWindow: 1048576,
      maxTokens: 65535
    },
    "google/gemini-2.5-flash-lite-preview-09-2025": {
      id: "google/gemini-2.5-flash-lite-preview-09-2025",
      name: "Google: Gemini 2.5 Flash Lite Preview 09-2025",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.09999999999999999,
        output: 0.39999999999999997,
        cacheRead: 0.01,
        cacheWrite: 0.08333333333333334
      },
      contextWindow: 1048576,
      maxTokens: 65536
    },
    "google/gemini-2.5-pro": {
      id: "google/gemini-2.5-pro",
      name: "Google: Gemini 2.5 Pro",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.25,
        output: 10,
        cacheRead: 0.125,
        cacheWrite: 0.375
      },
      contextWindow: 1048576,
      maxTokens: 65536
    },
    "google/gemini-2.5-pro-preview": {
      id: "google/gemini-2.5-pro-preview",
      name: "Google: Gemini 2.5 Pro Preview 06-05",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.25,
        output: 10,
        cacheRead: 0.125,
        cacheWrite: 0.375
      },
      contextWindow: 1048576,
      maxTokens: 65536
    },
    "google/gemini-2.5-pro-preview-05-06": {
      id: "google/gemini-2.5-pro-preview-05-06",
      name: "Google: Gemini 2.5 Pro Preview 05-06",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.25,
        output: 10,
        cacheRead: 0.125,
        cacheWrite: 0.375
      },
      contextWindow: 1048576,
      maxTokens: 65535
    },
    "google/gemini-3-flash-preview": {
      id: "google/gemini-3-flash-preview",
      name: "Google: Gemini 3 Flash Preview",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.5,
        output: 3,
        cacheRead: 0.049999999999999996,
        cacheWrite: 0.08333333333333334
      },
      contextWindow: 1048576,
      maxTokens: 65536
    },
    "google/gemini-3-pro-preview": {
      id: "google/gemini-3-pro-preview",
      name: "Google: Gemini 3 Pro Preview",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 2,
        output: 12,
        cacheRead: 0.19999999999999998,
        cacheWrite: 0.375
      },
      contextWindow: 1048576,
      maxTokens: 65536
    },
    "google/gemini-3.1-flash-lite-preview": {
      id: "google/gemini-3.1-flash-lite-preview",
      name: "Google: Gemini 3.1 Flash Lite Preview",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.25,
        output: 1.5,
        cacheRead: 0.024999999999999998,
        cacheWrite: 0.08333333333333334
      },
      contextWindow: 1048576,
      maxTokens: 65536
    },
    "google/gemini-3.1-pro-preview": {
      id: "google/gemini-3.1-pro-preview",
      name: "Google: Gemini 3.1 Pro Preview",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 2,
        output: 12,
        cacheRead: 0.19999999999999998,
        cacheWrite: 0.375
      },
      contextWindow: 1048576,
      maxTokens: 65536
    },
    "google/gemini-3.1-pro-preview-customtools": {
      id: "google/gemini-3.1-pro-preview-customtools",
      name: "Google: Gemini 3.1 Pro Preview Custom Tools",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 2,
        output: 12,
        cacheRead: 0.19999999999999998,
        cacheWrite: 0.375
      },
      contextWindow: 1048576,
      maxTokens: 65536
    },
    "google/gemma-3-27b-it": {
      id: "google/gemma-3-27b-it",
      name: "Google: Gemma 3 27B",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.03,
        output: 0.11,
        cacheRead: 0.015,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 65536
    },
    "google/gemma-3-27b-it:free": {
      id: "google/gemma-3-27b-it:free",
      name: "Google: Gemma 3 27B (free)",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 8192
    },
    "inception/mercury": {
      id: "inception/mercury",
      name: "Inception: Mercury",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.25,
        output: 0.75,
        cacheRead: 0.024999999999999998,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 32e3
    },
    "inception/mercury-2": {
      id: "inception/mercury-2",
      name: "Inception: Mercury 2",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.25,
        output: 0.75,
        cacheRead: 0.024999999999999998,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 5e4
    },
    "inception/mercury-coder": {
      id: "inception/mercury-coder",
      name: "Inception: Mercury Coder",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.25,
        output: 0.75,
        cacheRead: 0.024999999999999998,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 32e3
    },
    "kwaipilot/kat-coder-pro": {
      id: "kwaipilot/kat-coder-pro",
      name: "Kwaipilot: KAT-Coder-Pro V1",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.207,
        output: 0.828,
        cacheRead: 0.0414,
        cacheWrite: 0
      },
      contextWindow: 256e3,
      maxTokens: 128e3
    },
    "meituan/longcat-flash-chat": {
      id: "meituan/longcat-flash-chat",
      name: "Meituan: LongCat Flash Chat",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.19999999999999998,
        output: 0.7999999999999999,
        cacheRead: 0.19999999999999998,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 131072
    },
    "meta-llama/llama-3-8b-instruct": {
      id: "meta-llama/llama-3-8b-instruct",
      name: "Meta: Llama 3 8B Instruct",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.03,
        output: 0.04,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 8192,
      maxTokens: 16384
    },
    "meta-llama/llama-3.1-70b-instruct": {
      id: "meta-llama/llama-3.1-70b-instruct",
      name: "Meta: Llama 3.1 70B Instruct",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.39999999999999997,
        output: 0.39999999999999997,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 4096
    },
    "meta-llama/llama-3.1-8b-instruct": {
      id: "meta-llama/llama-3.1-8b-instruct",
      name: "Meta: Llama 3.1 8B Instruct",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.02,
        output: 0.049999999999999996,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 16384,
      maxTokens: 16384
    },
    "meta-llama/llama-3.3-70b-instruct": {
      id: "meta-llama/llama-3.3-70b-instruct",
      name: "Meta: Llama 3.3 70B Instruct",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.09999999999999999,
        output: 0.32,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 16384
    },
    "meta-llama/llama-3.3-70b-instruct:free": {
      id: "meta-llama/llama-3.3-70b-instruct:free",
      name: "Meta: Llama 3.3 70B Instruct (free)",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 128e3
    },
    "meta-llama/llama-4-maverick": {
      id: "meta-llama/llama-4-maverick",
      name: "Meta: Llama 4 Maverick",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.15,
        output: 0.6,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 1048576,
      maxTokens: 16384
    },
    "meta-llama/llama-4-scout": {
      id: "meta-llama/llama-4-scout",
      name: "Meta: Llama 4 Scout",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.08,
        output: 0.3,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 327680,
      maxTokens: 16384
    },
    "minimax/minimax-m1": {
      id: "minimax/minimax-m1",
      name: "MiniMax: MiniMax M1",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.39999999999999997,
        output: 2.2,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 1e6,
      maxTokens: 4e4
    },
    "minimax/minimax-m2": {
      id: "minimax/minimax-m2",
      name: "MiniMax: MiniMax M2",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.255,
        output: 1,
        cacheRead: 0.03,
        cacheWrite: 0
      },
      contextWindow: 196608,
      maxTokens: 196608
    },
    "minimax/minimax-m2.1": {
      id: "minimax/minimax-m2.1",
      name: "MiniMax: MiniMax M2.1",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.27,
        output: 0.95,
        cacheRead: 0.0290000007,
        cacheWrite: 0
      },
      contextWindow: 196608,
      maxTokens: 4096
    },
    "minimax/minimax-m2.5": {
      id: "minimax/minimax-m2.5",
      name: "MiniMax: MiniMax M2.5",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.25,
        output: 1.2,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 196608,
      maxTokens: 196608
    },
    "minimax/minimax-m2.5:free": {
      id: "minimax/minimax-m2.5:free",
      name: "MiniMax: MiniMax M2.5 (free)",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 196608,
      maxTokens: 196608
    },
    "mistralai/codestral-2508": {
      id: "mistralai/codestral-2508",
      name: "Mistral: Codestral 2508",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.3,
        output: 0.8999999999999999,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 256e3,
      maxTokens: 4096
    },
    "mistralai/devstral-2512": {
      id: "mistralai/devstral-2512",
      name: "Mistral: Devstral 2 2512",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.39999999999999997,
        output: 2,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 4096
    },
    "mistralai/devstral-medium": {
      id: "mistralai/devstral-medium",
      name: "Mistral: Devstral Medium",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.39999999999999997,
        output: 2,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 4096
    },
    "mistralai/devstral-small": {
      id: "mistralai/devstral-small",
      name: "Mistral: Devstral Small 1.1",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.09999999999999999,
        output: 0.3,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 4096
    },
    "mistralai/ministral-14b-2512": {
      id: "mistralai/ministral-14b-2512",
      name: "Mistral: Ministral 3 14B 2512",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.19999999999999998,
        output: 0.19999999999999998,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 4096
    },
    "mistralai/ministral-3b-2512": {
      id: "mistralai/ministral-3b-2512",
      name: "Mistral: Ministral 3 3B 2512",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.09999999999999999,
        output: 0.09999999999999999,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 4096
    },
    "mistralai/ministral-8b-2512": {
      id: "mistralai/ministral-8b-2512",
      name: "Mistral: Ministral 3 8B 2512",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.15,
        output: 0.15,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 4096
    },
    "mistralai/mistral-large": {
      id: "mistralai/mistral-large",
      name: "Mistral Large",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 2,
        output: 6,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 4096
    },
    "mistralai/mistral-large-2407": {
      id: "mistralai/mistral-large-2407",
      name: "Mistral Large 2407",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 2,
        output: 6,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 4096
    },
    "mistralai/mistral-large-2411": {
      id: "mistralai/mistral-large-2411",
      name: "Mistral Large 2411",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 2,
        output: 6,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 4096
    },
    "mistralai/mistral-large-2512": {
      id: "mistralai/mistral-large-2512",
      name: "Mistral: Mistral Large 3 2512",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.5,
        output: 1.5,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 4096
    },
    "mistralai/mistral-medium-3": {
      id: "mistralai/mistral-medium-3",
      name: "Mistral: Mistral Medium 3",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.39999999999999997,
        output: 2,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 4096
    },
    "mistralai/mistral-medium-3.1": {
      id: "mistralai/mistral-medium-3.1",
      name: "Mistral: Mistral Medium 3.1",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.39999999999999997,
        output: 2,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 4096
    },
    "mistralai/mistral-nemo": {
      id: "mistralai/mistral-nemo",
      name: "Mistral: Mistral Nemo",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.02,
        output: 0.04,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 16384
    },
    "mistralai/mistral-saba": {
      id: "mistralai/mistral-saba",
      name: "Mistral: Saba",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.19999999999999998,
        output: 0.6,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 32768,
      maxTokens: 4096
    },
    "mistralai/mistral-small-24b-instruct-2501": {
      id: "mistralai/mistral-small-24b-instruct-2501",
      name: "Mistral: Mistral Small 3",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.049999999999999996,
        output: 0.08,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 32768,
      maxTokens: 16384
    },
    "mistralai/mistral-small-3.1-24b-instruct:free": {
      id: "mistralai/mistral-small-3.1-24b-instruct:free",
      name: "Mistral: Mistral Small 3.1 24B (free)",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 4096
    },
    "mistralai/mistral-small-3.2-24b-instruct": {
      id: "mistralai/mistral-small-3.2-24b-instruct",
      name: "Mistral: Mistral Small 3.2 24B",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.06,
        output: 0.18,
        cacheRead: 0.03,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 131072
    },
    "mistralai/mistral-small-creative": {
      id: "mistralai/mistral-small-creative",
      name: "Mistral: Mistral Small Creative",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.09999999999999999,
        output: 0.3,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 32768,
      maxTokens: 4096
    },
    "mistralai/mixtral-8x22b-instruct": {
      id: "mistralai/mixtral-8x22b-instruct",
      name: "Mistral: Mixtral 8x22B Instruct",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 2,
        output: 6,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 65536,
      maxTokens: 4096
    },
    "mistralai/mixtral-8x7b-instruct": {
      id: "mistralai/mixtral-8x7b-instruct",
      name: "Mistral: Mixtral 8x7B Instruct",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.54,
        output: 0.54,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 32768,
      maxTokens: 16384
    },
    "mistralai/pixtral-large-2411": {
      id: "mistralai/pixtral-large-2411",
      name: "Mistral: Pixtral Large 2411",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 2,
        output: 6,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 4096
    },
    "mistralai/voxtral-small-24b-2507": {
      id: "mistralai/voxtral-small-24b-2507",
      name: "Mistral: Voxtral Small 24B 2507",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.09999999999999999,
        output: 0.3,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 32e3,
      maxTokens: 4096
    },
    "moonshotai/kimi-k2": {
      id: "moonshotai/kimi-k2",
      name: "MoonshotAI: Kimi K2 0711",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.55,
        output: 2.2,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131e3,
      maxTokens: 4096
    },
    "moonshotai/kimi-k2-0905": {
      id: "moonshotai/kimi-k2-0905",
      name: "MoonshotAI: Kimi K2 0905",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.39999999999999997,
        output: 2,
        cacheRead: 0.15,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 4096
    },
    "moonshotai/kimi-k2-thinking": {
      id: "moonshotai/kimi-k2-thinking",
      name: "MoonshotAI: Kimi K2 Thinking",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.47,
        output: 2,
        cacheRead: 0.14100000000000001,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 4096
    },
    "moonshotai/kimi-k2.5": {
      id: "moonshotai/kimi-k2.5",
      name: "MoonshotAI: Kimi K2.5",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.41,
        output: 2.06,
        cacheRead: 0.07,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 4096
    },
    "nex-agi/deepseek-v3.1-nex-n1": {
      id: "nex-agi/deepseek-v3.1-nex-n1",
      name: "Nex AGI: DeepSeek V3.1 Nex N1",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.27,
        output: 1,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 163840
    },
    "nvidia/llama-3.1-nemotron-70b-instruct": {
      id: "nvidia/llama-3.1-nemotron-70b-instruct",
      name: "NVIDIA: Llama 3.1 Nemotron 70B Instruct",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 1.2,
        output: 1.2,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 16384
    },
    "nvidia/llama-3.3-nemotron-super-49b-v1.5": {
      id: "nvidia/llama-3.3-nemotron-super-49b-v1.5",
      name: "NVIDIA: Llama 3.3 Nemotron Super 49B V1.5",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.09999999999999999,
        output: 0.39999999999999997,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 4096
    },
    "nvidia/nemotron-3-nano-30b-a3b": {
      id: "nvidia/nemotron-3-nano-30b-a3b",
      name: "NVIDIA: Nemotron 3 Nano 30B A3B",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.049999999999999996,
        output: 0.19999999999999998,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 4096
    },
    "nvidia/nemotron-3-nano-30b-a3b:free": {
      id: "nvidia/nemotron-3-nano-30b-a3b:free",
      name: "NVIDIA: Nemotron 3 Nano 30B A3B (free)",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 256e3,
      maxTokens: 4096
    },
    "nvidia/nemotron-3-super-120b-a12b:free": {
      id: "nvidia/nemotron-3-super-120b-a12b:free",
      name: "NVIDIA: Nemotron 3 Super (free)",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 262144
    },
    "nvidia/nemotron-nano-12b-v2-vl:free": {
      id: "nvidia/nemotron-nano-12b-v2-vl:free",
      name: "NVIDIA: Nemotron Nano 12B 2 VL (free)",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 128e3
    },
    "nvidia/nemotron-nano-9b-v2": {
      id: "nvidia/nemotron-nano-9b-v2",
      name: "NVIDIA: Nemotron Nano 9B V2",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.04,
        output: 0.16,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 4096
    },
    "nvidia/nemotron-nano-9b-v2:free": {
      id: "nvidia/nemotron-nano-9b-v2:free",
      name: "NVIDIA: Nemotron Nano 9B V2 (free)",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 4096
    },
    "openai/gpt-3.5-turbo": {
      id: "openai/gpt-3.5-turbo",
      name: "OpenAI: GPT-3.5 Turbo",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.5,
        output: 1.5,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 16385,
      maxTokens: 4096
    },
    "openai/gpt-3.5-turbo-0613": {
      id: "openai/gpt-3.5-turbo-0613",
      name: "OpenAI: GPT-3.5 Turbo (older v0613)",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 1,
        output: 2,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 4095,
      maxTokens: 4096
    },
    "openai/gpt-3.5-turbo-16k": {
      id: "openai/gpt-3.5-turbo-16k",
      name: "OpenAI: GPT-3.5 Turbo 16k",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 3,
        output: 4,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 16385,
      maxTokens: 4096
    },
    "openai/gpt-4": {
      id: "openai/gpt-4",
      name: "OpenAI: GPT-4",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 30,
        output: 60,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 8191,
      maxTokens: 4096
    },
    "openai/gpt-4-0314": {
      id: "openai/gpt-4-0314",
      name: "OpenAI: GPT-4 (older v0314)",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 30,
        output: 60,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 8191,
      maxTokens: 4096
    },
    "openai/gpt-4-1106-preview": {
      id: "openai/gpt-4-1106-preview",
      name: "OpenAI: GPT-4 Turbo (older v1106)",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 10,
        output: 30,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 4096
    },
    "openai/gpt-4-turbo": {
      id: "openai/gpt-4-turbo",
      name: "OpenAI: GPT-4 Turbo",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 10,
        output: 30,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 4096
    },
    "openai/gpt-4-turbo-preview": {
      id: "openai/gpt-4-turbo-preview",
      name: "OpenAI: GPT-4 Turbo Preview",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 10,
        output: 30,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 4096
    },
    "openai/gpt-4.1": {
      id: "openai/gpt-4.1",
      name: "OpenAI: GPT-4.1",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 2,
        output: 8,
        cacheRead: 0.5,
        cacheWrite: 0
      },
      contextWindow: 1047576,
      maxTokens: 32768
    },
    "openai/gpt-4.1-mini": {
      id: "openai/gpt-4.1-mini",
      name: "OpenAI: GPT-4.1 Mini",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.39999999999999997,
        output: 1.5999999999999999,
        cacheRead: 0.09999999999999999,
        cacheWrite: 0
      },
      contextWindow: 1047576,
      maxTokens: 32768
    },
    "openai/gpt-4.1-nano": {
      id: "openai/gpt-4.1-nano",
      name: "OpenAI: GPT-4.1 Nano",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.09999999999999999,
        output: 0.39999999999999997,
        cacheRead: 0.024999999999999998,
        cacheWrite: 0
      },
      contextWindow: 1047576,
      maxTokens: 32768
    },
    "openai/gpt-4o": {
      id: "openai/gpt-4o",
      name: "OpenAI: GPT-4o",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 2.5,
        output: 10,
        cacheRead: 1.25,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 16384
    },
    "openai/gpt-4o-2024-05-13": {
      id: "openai/gpt-4o-2024-05-13",
      name: "OpenAI: GPT-4o (2024-05-13)",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 5,
        output: 15,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 4096
    },
    "openai/gpt-4o-2024-08-06": {
      id: "openai/gpt-4o-2024-08-06",
      name: "OpenAI: GPT-4o (2024-08-06)",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 2.5,
        output: 10,
        cacheRead: 1.25,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 16384
    },
    "openai/gpt-4o-2024-11-20": {
      id: "openai/gpt-4o-2024-11-20",
      name: "OpenAI: GPT-4o (2024-11-20)",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 2.5,
        output: 10,
        cacheRead: 1.25,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 16384
    },
    "openai/gpt-4o-audio-preview": {
      id: "openai/gpt-4o-audio-preview",
      name: "OpenAI: GPT-4o Audio",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 2.5,
        output: 10,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 16384
    },
    "openai/gpt-4o-mini": {
      id: "openai/gpt-4o-mini",
      name: "OpenAI: GPT-4o-mini",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.15,
        output: 0.6,
        cacheRead: 0.075,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 16384
    },
    "openai/gpt-4o-mini-2024-07-18": {
      id: "openai/gpt-4o-mini-2024-07-18",
      name: "OpenAI: GPT-4o-mini (2024-07-18)",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.15,
        output: 0.6,
        cacheRead: 0.075,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 16384
    },
    "openai/gpt-4o:extended": {
      id: "openai/gpt-4o:extended",
      name: "OpenAI: GPT-4o (extended)",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 6,
        output: 18,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 64e3
    },
    "openai/gpt-5": {
      id: "openai/gpt-5",
      name: "OpenAI: GPT-5",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.25,
        output: 10,
        cacheRead: 0.125,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "openai/gpt-5-codex": {
      id: "openai/gpt-5-codex",
      name: "OpenAI: GPT-5 Codex",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.25,
        output: 10,
        cacheRead: 0.125,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "openai/gpt-5-image": {
      id: "openai/gpt-5-image",
      name: "OpenAI: GPT-5 Image",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 10,
        output: 10,
        cacheRead: 1.25,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "openai/gpt-5-image-mini": {
      id: "openai/gpt-5-image-mini",
      name: "OpenAI: GPT-5 Image Mini",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 2.5,
        output: 2,
        cacheRead: 0.25,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "openai/gpt-5-mini": {
      id: "openai/gpt-5-mini",
      name: "OpenAI: GPT-5 Mini",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.25,
        output: 2,
        cacheRead: 0.024999999999999998,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "openai/gpt-5-nano": {
      id: "openai/gpt-5-nano",
      name: "OpenAI: GPT-5 Nano",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.049999999999999996,
        output: 0.39999999999999997,
        cacheRead: 5e-3,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "openai/gpt-5-pro": {
      id: "openai/gpt-5-pro",
      name: "OpenAI: GPT-5 Pro",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 15,
        output: 120,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "openai/gpt-5.1": {
      id: "openai/gpt-5.1",
      name: "OpenAI: GPT-5.1",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.25,
        output: 10,
        cacheRead: 0.125,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "openai/gpt-5.1-chat": {
      id: "openai/gpt-5.1-chat",
      name: "OpenAI: GPT-5.1 Chat",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 1.25,
        output: 10,
        cacheRead: 0.125,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 16384
    },
    "openai/gpt-5.1-codex": {
      id: "openai/gpt-5.1-codex",
      name: "OpenAI: GPT-5.1-Codex",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.25,
        output: 10,
        cacheRead: 0.125,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "openai/gpt-5.1-codex-max": {
      id: "openai/gpt-5.1-codex-max",
      name: "OpenAI: GPT-5.1-Codex-Max",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.25,
        output: 10,
        cacheRead: 0.125,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "openai/gpt-5.1-codex-mini": {
      id: "openai/gpt-5.1-codex-mini",
      name: "OpenAI: GPT-5.1-Codex-Mini",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.25,
        output: 2,
        cacheRead: 0.024999999999999998,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 1e5
    },
    "openai/gpt-5.2": {
      id: "openai/gpt-5.2",
      name: "OpenAI: GPT-5.2",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.75,
        output: 14,
        cacheRead: 0.175,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "openai/gpt-5.2-chat": {
      id: "openai/gpt-5.2-chat",
      name: "OpenAI: GPT-5.2 Chat",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 1.75,
        output: 14,
        cacheRead: 0.175,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 16384
    },
    "openai/gpt-5.2-codex": {
      id: "openai/gpt-5.2-codex",
      name: "OpenAI: GPT-5.2-Codex",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.75,
        output: 14,
        cacheRead: 0.175,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "openai/gpt-5.2-pro": {
      id: "openai/gpt-5.2-pro",
      name: "OpenAI: GPT-5.2 Pro",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 21,
        output: 168,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "openai/gpt-5.3-chat": {
      id: "openai/gpt-5.3-chat",
      name: "OpenAI: GPT-5.3 Chat",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 1.75,
        output: 14,
        cacheRead: 0.175,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 16384
    },
    "openai/gpt-5.3-codex": {
      id: "openai/gpt-5.3-codex",
      name: "OpenAI: GPT-5.3-Codex",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.75,
        output: 14,
        cacheRead: 0.175,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "openai/gpt-5.4": {
      id: "openai/gpt-5.4",
      name: "OpenAI: GPT-5.4",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 2.5,
        output: 15,
        cacheRead: 0.25,
        cacheWrite: 0
      },
      contextWindow: 105e4,
      maxTokens: 128e3
    },
    "openai/gpt-5.4-pro": {
      id: "openai/gpt-5.4-pro",
      name: "OpenAI: GPT-5.4 Pro",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 30,
        output: 180,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 105e4,
      maxTokens: 128e3
    },
    "openai/gpt-oss-120b": {
      id: "openai/gpt-oss-120b",
      name: "OpenAI: gpt-oss-120b",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.039,
        output: 0.19,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 4096
    },
    "openai/gpt-oss-120b:free": {
      id: "openai/gpt-oss-120b:free",
      name: "OpenAI: gpt-oss-120b (free)",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 131072
    },
    "openai/gpt-oss-20b": {
      id: "openai/gpt-oss-20b",
      name: "OpenAI: gpt-oss-20b",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.03,
        output: 0.14,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 4096
    },
    "openai/gpt-oss-20b:free": {
      id: "openai/gpt-oss-20b:free",
      name: "OpenAI: gpt-oss-20b (free)",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 131072
    },
    "openai/gpt-oss-safeguard-20b": {
      id: "openai/gpt-oss-safeguard-20b",
      name: "OpenAI: gpt-oss-safeguard-20b",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.075,
        output: 0.3,
        cacheRead: 0.037,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 65536
    },
    "openai/o1": {
      id: "openai/o1",
      name: "OpenAI: o1",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 15,
        output: 60,
        cacheRead: 7.5,
        cacheWrite: 0
      },
      contextWindow: 2e5,
      maxTokens: 1e5
    },
    "openai/o3": {
      id: "openai/o3",
      name: "OpenAI: o3",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 2,
        output: 8,
        cacheRead: 0.5,
        cacheWrite: 0
      },
      contextWindow: 2e5,
      maxTokens: 1e5
    },
    "openai/o3-deep-research": {
      id: "openai/o3-deep-research",
      name: "OpenAI: o3 Deep Research",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 10,
        output: 40,
        cacheRead: 2.5,
        cacheWrite: 0
      },
      contextWindow: 2e5,
      maxTokens: 1e5
    },
    "openai/o3-mini": {
      id: "openai/o3-mini",
      name: "OpenAI: o3 Mini",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 1.1,
        output: 4.4,
        cacheRead: 0.55,
        cacheWrite: 0
      },
      contextWindow: 2e5,
      maxTokens: 1e5
    },
    "openai/o3-mini-high": {
      id: "openai/o3-mini-high",
      name: "OpenAI: o3 Mini High",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 1.1,
        output: 4.4,
        cacheRead: 0.55,
        cacheWrite: 0
      },
      contextWindow: 2e5,
      maxTokens: 1e5
    },
    "openai/o3-pro": {
      id: "openai/o3-pro",
      name: "OpenAI: o3 Pro",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 20,
        output: 80,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 2e5,
      maxTokens: 1e5
    },
    "openai/o4-mini": {
      id: "openai/o4-mini",
      name: "OpenAI: o4 Mini",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.1,
        output: 4.4,
        cacheRead: 0.275,
        cacheWrite: 0
      },
      contextWindow: 2e5,
      maxTokens: 1e5
    },
    "openai/o4-mini-deep-research": {
      id: "openai/o4-mini-deep-research",
      name: "OpenAI: o4 Mini Deep Research",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 2,
        output: 8,
        cacheRead: 0.5,
        cacheWrite: 0
      },
      contextWindow: 2e5,
      maxTokens: 1e5
    },
    "openai/o4-mini-high": {
      id: "openai/o4-mini-high",
      name: "OpenAI: o4 Mini High",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.1,
        output: 4.4,
        cacheRead: 0.275,
        cacheWrite: 0
      },
      contextWindow: 2e5,
      maxTokens: 1e5
    },
    "openrouter/auto": {
      id: "openrouter/auto",
      name: "Auto Router",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: -1e6,
        output: -1e6,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 2e6,
      maxTokens: 4096
    },
    "openrouter/free": {
      id: "openrouter/free",
      name: "Free Models Router",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 2e5,
      maxTokens: 4096
    },
    "openrouter/healer-alpha": {
      id: "openrouter/healer-alpha",
      name: "Healer Alpha",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 32e3
    },
    "openrouter/hunter-alpha": {
      id: "openrouter/hunter-alpha",
      name: "Hunter Alpha",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 1048576,
      maxTokens: 32e3
    },
    "prime-intellect/intellect-3": {
      id: "prime-intellect/intellect-3",
      name: "Prime Intellect: INTELLECT-3",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.19999999999999998,
        output: 1.1,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 131072
    },
    "qwen/qwen-2.5-72b-instruct": {
      id: "qwen/qwen-2.5-72b-instruct",
      name: "Qwen2.5 72B Instruct",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.12,
        output: 0.39,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 32768,
      maxTokens: 16384
    },
    "qwen/qwen-2.5-7b-instruct": {
      id: "qwen/qwen-2.5-7b-instruct",
      name: "Qwen: Qwen2.5 7B Instruct",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.04,
        output: 0.09999999999999999,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 32768,
      maxTokens: 4096
    },
    "qwen/qwen-max": {
      id: "qwen/qwen-max",
      name: "Qwen: Qwen-Max ",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 1.04,
        output: 4.16,
        cacheRead: 0.20800000000000002,
        cacheWrite: 0
      },
      contextWindow: 32768,
      maxTokens: 8192
    },
    "qwen/qwen-plus": {
      id: "qwen/qwen-plus",
      name: "Qwen: Qwen-Plus",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.39999999999999997,
        output: 1.2,
        cacheRead: 0.08,
        cacheWrite: 0
      },
      contextWindow: 1e6,
      maxTokens: 32768
    },
    "qwen/qwen-plus-2025-07-28": {
      id: "qwen/qwen-plus-2025-07-28",
      name: "Qwen: Qwen Plus 0728",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.26,
        output: 0.78,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 1e6,
      maxTokens: 32768
    },
    "qwen/qwen-plus-2025-07-28:thinking": {
      id: "qwen/qwen-plus-2025-07-28:thinking",
      name: "Qwen: Qwen Plus 0728 (thinking)",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.26,
        output: 0.78,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 1e6,
      maxTokens: 32768
    },
    "qwen/qwen-turbo": {
      id: "qwen/qwen-turbo",
      name: "Qwen: Qwen-Turbo",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.0325,
        output: 0.13,
        cacheRead: 0.006500000000000001,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 8192
    },
    "qwen/qwen-vl-max": {
      id: "qwen/qwen-vl-max",
      name: "Qwen: Qwen VL Max",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.7999999999999999,
        output: 3.1999999999999997,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 32768
    },
    "qwen/qwen3-14b": {
      id: "qwen/qwen3-14b",
      name: "Qwen: Qwen3 14B",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.06,
        output: 0.24,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 40960,
      maxTokens: 40960
    },
    "qwen/qwen3-235b-a22b": {
      id: "qwen/qwen3-235b-a22b",
      name: "Qwen: Qwen3 235B A22B",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.45499999999999996,
        output: 1.8199999999999998,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 8192
    },
    "qwen/qwen3-235b-a22b-2507": {
      id: "qwen/qwen3-235b-a22b-2507",
      name: "Qwen: Qwen3 235B A22B Instruct 2507",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.071,
        output: 0.09999999999999999,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 4096
    },
    "qwen/qwen3-235b-a22b-thinking-2507": {
      id: "qwen/qwen3-235b-a22b-thinking-2507",
      name: "Qwen: Qwen3 235B A22B Thinking 2507",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.11,
        output: 0.6,
        cacheRead: 0.055,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 262144
    },
    "qwen/qwen3-30b-a3b": {
      id: "qwen/qwen3-30b-a3b",
      name: "Qwen: Qwen3 30B A3B",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.08,
        output: 0.28,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 40960,
      maxTokens: 40960
    },
    "qwen/qwen3-30b-a3b-instruct-2507": {
      id: "qwen/qwen3-30b-a3b-instruct-2507",
      name: "Qwen: Qwen3 30B A3B Instruct 2507",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.09,
        output: 0.3,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 262144
    },
    "qwen/qwen3-30b-a3b-thinking-2507": {
      id: "qwen/qwen3-30b-a3b-thinking-2507",
      name: "Qwen: Qwen3 30B A3B Thinking 2507",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.051,
        output: 0.33999999999999997,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 32768,
      maxTokens: 4096
    },
    "qwen/qwen3-32b": {
      id: "qwen/qwen3-32b",
      name: "Qwen: Qwen3 32B",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.08,
        output: 0.24,
        cacheRead: 0.04,
        cacheWrite: 0
      },
      contextWindow: 40960,
      maxTokens: 40960
    },
    "qwen/qwen3-4b:free": {
      id: "qwen/qwen3-4b:free",
      name: "Qwen: Qwen3 4B (free)",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 40960,
      maxTokens: 4096
    },
    "qwen/qwen3-8b": {
      id: "qwen/qwen3-8b",
      name: "Qwen: Qwen3 8B",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.049999999999999996,
        output: 0.39999999999999997,
        cacheRead: 0.049999999999999996,
        cacheWrite: 0
      },
      contextWindow: 40960,
      maxTokens: 8192
    },
    "qwen/qwen3-coder": {
      id: "qwen/qwen3-coder",
      name: "Qwen: Qwen3 Coder 480B A35B",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.22,
        output: 1,
        cacheRead: 0.022,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 4096
    },
    "qwen/qwen3-coder-30b-a3b-instruct": {
      id: "qwen/qwen3-coder-30b-a3b-instruct",
      name: "Qwen: Qwen3 Coder 30B A3B Instruct",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.07,
        output: 0.27,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 16e4,
      maxTokens: 32768
    },
    "qwen/qwen3-coder-flash": {
      id: "qwen/qwen3-coder-flash",
      name: "Qwen: Qwen3 Coder Flash",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.195,
        output: 0.975,
        cacheRead: 0.039,
        cacheWrite: 0
      },
      contextWindow: 1e6,
      maxTokens: 65536
    },
    "qwen/qwen3-coder-next": {
      id: "qwen/qwen3-coder-next",
      name: "Qwen: Qwen3 Coder Next",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.12,
        output: 0.75,
        cacheRead: 0.06,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 65536
    },
    "qwen/qwen3-coder-plus": {
      id: "qwen/qwen3-coder-plus",
      name: "Qwen: Qwen3 Coder Plus",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.65,
        output: 3.25,
        cacheRead: 0.13,
        cacheWrite: 0
      },
      contextWindow: 1e6,
      maxTokens: 65536
    },
    "qwen/qwen3-coder:free": {
      id: "qwen/qwen3-coder:free",
      name: "Qwen: Qwen3 Coder 480B A35B (free)",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 262e3,
      maxTokens: 262e3
    },
    "qwen/qwen3-max": {
      id: "qwen/qwen3-max",
      name: "Qwen: Qwen3 Max",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 1.2,
        output: 6,
        cacheRead: 0.24,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 32768
    },
    "qwen/qwen3-max-thinking": {
      id: "qwen/qwen3-max-thinking",
      name: "Qwen: Qwen3 Max Thinking",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.78,
        output: 3.9,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 32768
    },
    "qwen/qwen3-next-80b-a3b-instruct": {
      id: "qwen/qwen3-next-80b-a3b-instruct",
      name: "Qwen: Qwen3 Next 80B A3B Instruct",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.09,
        output: 1.1,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 4096
    },
    "qwen/qwen3-next-80b-a3b-instruct:free": {
      id: "qwen/qwen3-next-80b-a3b-instruct:free",
      name: "Qwen: Qwen3 Next 80B A3B Instruct (free)",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 4096
    },
    "qwen/qwen3-next-80b-a3b-thinking": {
      id: "qwen/qwen3-next-80b-a3b-thinking",
      name: "Qwen: Qwen3 Next 80B A3B Thinking",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.0975,
        output: 0.78,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 32768
    },
    "qwen/qwen3-vl-235b-a22b-instruct": {
      id: "qwen/qwen3-vl-235b-a22b-instruct",
      name: "Qwen: Qwen3 VL 235B A22B Instruct",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.19999999999999998,
        output: 0.88,
        cacheRead: 0.11,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 4096
    },
    "qwen/qwen3-vl-235b-a22b-thinking": {
      id: "qwen/qwen3-vl-235b-a22b-thinking",
      name: "Qwen: Qwen3 VL 235B A22B Thinking",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.26,
        output: 2.6,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 32768
    },
    "qwen/qwen3-vl-30b-a3b-instruct": {
      id: "qwen/qwen3-vl-30b-a3b-instruct",
      name: "Qwen: Qwen3 VL 30B A3B Instruct",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.13,
        output: 0.52,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 32768
    },
    "qwen/qwen3-vl-30b-a3b-thinking": {
      id: "qwen/qwen3-vl-30b-a3b-thinking",
      name: "Qwen: Qwen3 VL 30B A3B Thinking",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.13,
        output: 1.56,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 32768
    },
    "qwen/qwen3-vl-32b-instruct": {
      id: "qwen/qwen3-vl-32b-instruct",
      name: "Qwen: Qwen3 VL 32B Instruct",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.10400000000000001,
        output: 0.41600000000000004,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 32768
    },
    "qwen/qwen3-vl-8b-instruct": {
      id: "qwen/qwen3-vl-8b-instruct",
      name: "Qwen: Qwen3 VL 8B Instruct",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.08,
        output: 0.5,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 32768
    },
    "qwen/qwen3-vl-8b-thinking": {
      id: "qwen/qwen3-vl-8b-thinking",
      name: "Qwen: Qwen3 VL 8B Thinking",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.117,
        output: 1.365,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 32768
    },
    "qwen/qwen3.5-122b-a10b": {
      id: "qwen/qwen3.5-122b-a10b",
      name: "Qwen: Qwen3.5-122B-A10B",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.26,
        output: 2.08,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 65536
    },
    "qwen/qwen3.5-27b": {
      id: "qwen/qwen3.5-27b",
      name: "Qwen: Qwen3.5-27B",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.195,
        output: 1.56,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 65536
    },
    "qwen/qwen3.5-35b-a3b": {
      id: "qwen/qwen3.5-35b-a3b",
      name: "Qwen: Qwen3.5-35B-A3B",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.1625,
        output: 1.3,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 65536
    },
    "qwen/qwen3.5-397b-a17b": {
      id: "qwen/qwen3.5-397b-a17b",
      name: "Qwen: Qwen3.5 397B A17B",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.39,
        output: 2.34,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 65536
    },
    "qwen/qwen3.5-9b": {
      id: "qwen/qwen3.5-9b",
      name: "Qwen: Qwen3.5-9B",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.049999999999999996,
        output: 0.15,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 256e3,
      maxTokens: 4096
    },
    "qwen/qwen3.5-flash-02-23": {
      id: "qwen/qwen3.5-flash-02-23",
      name: "Qwen: Qwen3.5-Flash",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.09999999999999999,
        output: 0.39999999999999997,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 1e6,
      maxTokens: 65536
    },
    "qwen/qwen3.5-plus-02-15": {
      id: "qwen/qwen3.5-plus-02-15",
      name: "Qwen: Qwen3.5 Plus 2026-02-15",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.26,
        output: 1.56,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 1e6,
      maxTokens: 65536
    },
    "qwen/qwq-32b": {
      id: "qwen/qwq-32b",
      name: "Qwen: QwQ 32B",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.15,
        output: 0.39999999999999997,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 32768,
      maxTokens: 32768
    },
    "relace/relace-search": {
      id: "relace/relace-search",
      name: "Relace: Relace Search",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 1,
        output: 3,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 256e3,
      maxTokens: 128e3
    },
    "sao10k/l3-euryale-70b": {
      id: "sao10k/l3-euryale-70b",
      name: "Sao10k: Llama 3 Euryale 70B v2.1",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 1.48,
        output: 1.48,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 8192,
      maxTokens: 8192
    },
    "sao10k/l3.1-euryale-70b": {
      id: "sao10k/l3.1-euryale-70b",
      name: "Sao10K: Llama 3.1 Euryale 70B v2.2",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.85,
        output: 0.85,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 16384
    },
    "stepfun/step-3.5-flash": {
      id: "stepfun/step-3.5-flash",
      name: "StepFun: Step 3.5 Flash",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.09999999999999999,
        output: 0.3,
        cacheRead: 0.02,
        cacheWrite: 0
      },
      contextWindow: 256e3,
      maxTokens: 256e3
    },
    "stepfun/step-3.5-flash:free": {
      id: "stepfun/step-3.5-flash:free",
      name: "StepFun: Step 3.5 Flash (free)",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 256e3,
      maxTokens: 256e3
    },
    "thedrummer/rocinante-12b": {
      id: "thedrummer/rocinante-12b",
      name: "TheDrummer: Rocinante 12B",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.16999999999999998,
        output: 0.43,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 32768,
      maxTokens: 32768
    },
    "thedrummer/unslopnemo-12b": {
      id: "thedrummer/unslopnemo-12b",
      name: "TheDrummer: UnslopNemo 12B",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.39999999999999997,
        output: 0.39999999999999997,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 32768,
      maxTokens: 32768
    },
    "tngtech/deepseek-r1t2-chimera": {
      id: "tngtech/deepseek-r1t2-chimera",
      name: "TNG: DeepSeek R1T2 Chimera",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.25,
        output: 0.85,
        cacheRead: 0.125,
        cacheWrite: 0
      },
      contextWindow: 163840,
      maxTokens: 163840
    },
    "upstage/solar-pro-3": {
      id: "upstage/solar-pro-3",
      name: "Upstage: Solar Pro 3",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.15,
        output: 0.6,
        cacheRead: 0.015,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 4096
    },
    "x-ai/grok-3": {
      id: "x-ai/grok-3",
      name: "xAI: Grok 3",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.75,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 4096
    },
    "x-ai/grok-3-beta": {
      id: "x-ai/grok-3-beta",
      name: "xAI: Grok 3 Beta",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.75,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 4096
    },
    "x-ai/grok-3-mini": {
      id: "x-ai/grok-3-mini",
      name: "xAI: Grok 3 Mini",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.3,
        output: 0.5,
        cacheRead: 0.075,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 4096
    },
    "x-ai/grok-3-mini-beta": {
      id: "x-ai/grok-3-mini-beta",
      name: "xAI: Grok 3 Mini Beta",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.3,
        output: 0.5,
        cacheRead: 0.075,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 4096
    },
    "x-ai/grok-4": {
      id: "x-ai/grok-4",
      name: "xAI: Grok 4",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.75,
        cacheWrite: 0
      },
      contextWindow: 256e3,
      maxTokens: 4096
    },
    "x-ai/grok-4-fast": {
      id: "x-ai/grok-4-fast",
      name: "xAI: Grok 4 Fast",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.19999999999999998,
        output: 0.5,
        cacheRead: 0.049999999999999996,
        cacheWrite: 0
      },
      contextWindow: 2e6,
      maxTokens: 3e4
    },
    "x-ai/grok-4.1-fast": {
      id: "x-ai/grok-4.1-fast",
      name: "xAI: Grok 4.1 Fast",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.19999999999999998,
        output: 0.5,
        cacheRead: 0.049999999999999996,
        cacheWrite: 0
      },
      contextWindow: 2e6,
      maxTokens: 3e4
    },
    "x-ai/grok-4.20-beta": {
      id: "x-ai/grok-4.20-beta",
      name: "xAI: Grok 4.20 Beta",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 2,
        output: 6,
        cacheRead: 0.19999999999999998,
        cacheWrite: 0
      },
      contextWindow: 2e6,
      maxTokens: 4096
    },
    "x-ai/grok-code-fast-1": {
      id: "x-ai/grok-code-fast-1",
      name: "xAI: Grok Code Fast 1",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.19999999999999998,
        output: 1.5,
        cacheRead: 0.02,
        cacheWrite: 0
      },
      contextWindow: 256e3,
      maxTokens: 1e4
    },
    "xiaomi/mimo-v2-flash": {
      id: "xiaomi/mimo-v2-flash",
      name: "Xiaomi: MiMo-V2-Flash",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.09,
        output: 0.29,
        cacheRead: 0.045,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 65536
    },
    "z-ai/glm-4-32b": {
      id: "z-ai/glm-4-32b",
      name: "Z.ai: GLM 4 32B ",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.09999999999999999,
        output: 0.09999999999999999,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 4096
    },
    "z-ai/glm-4.5": {
      id: "z-ai/glm-4.5",
      name: "Z.ai: GLM 4.5",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.6,
        output: 2.2,
        cacheRead: 0.11,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 98304
    },
    "z-ai/glm-4.5-air": {
      id: "z-ai/glm-4.5-air",
      name: "Z.ai: GLM 4.5 Air",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.13,
        output: 0.85,
        cacheRead: 0.024999999999999998,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 98304
    },
    "z-ai/glm-4.5-air:free": {
      id: "z-ai/glm-4.5-air:free",
      name: "Z.ai: GLM 4.5 Air (free)",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 96e3
    },
    "z-ai/glm-4.5v": {
      id: "z-ai/glm-4.5v",
      name: "Z.ai: GLM 4.5V",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.6,
        output: 1.7999999999999998,
        cacheRead: 0.11,
        cacheWrite: 0
      },
      contextWindow: 65536,
      maxTokens: 16384
    },
    "z-ai/glm-4.6": {
      id: "z-ai/glm-4.6",
      name: "Z.ai: GLM 4.6",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.39,
        output: 1.9,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 204800,
      maxTokens: 204800
    },
    "z-ai/glm-4.6v": {
      id: "z-ai/glm-4.6v",
      name: "Z.ai: GLM 4.6V",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.3,
        output: 0.8999999999999999,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 131072
    },
    "z-ai/glm-4.7": {
      id: "z-ai/glm-4.7",
      name: "Z.ai: GLM 4.7",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.38,
        output: 1.9800000000000002,
        cacheRead: 0.19,
        cacheWrite: 0
      },
      contextWindow: 202752,
      maxTokens: 4096
    },
    "z-ai/glm-4.7-flash": {
      id: "z-ai/glm-4.7-flash",
      name: "Z.ai: GLM 4.7 Flash",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.06,
        output: 0.39999999999999997,
        cacheRead: 0.0100000002,
        cacheWrite: 0
      },
      contextWindow: 202752,
      maxTokens: 4096
    },
    "z-ai/glm-5": {
      id: "z-ai/glm-5",
      name: "Z.ai: GLM 5",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.6,
        output: 1.9,
        cacheRead: 0.119,
        cacheWrite: 0
      },
      contextWindow: 202752,
      maxTokens: 131072
    },
    "z-ai/glm-5-turbo": {
      id: "z-ai/glm-5-turbo",
      name: "Z.ai: GLM 5 Turbo",
      api: "openai-completions",
      provider: "openrouter",
      baseUrl: "https://openrouter.ai/api/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.96,
        output: 3.1999999999999997,
        cacheRead: 0.192,
        cacheWrite: 0
      },
      contextWindow: 202752,
      maxTokens: 131072
    }
  },
  "vercel-ai-gateway": {
    "alibaba/qwen-3-14b": {
      id: "alibaba/qwen-3-14b",
      name: "Qwen3-14B",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.06,
        output: 0.24,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 40960,
      maxTokens: 16384
    },
    "alibaba/qwen-3-235b": {
      id: "alibaba/qwen-3-235b",
      name: "Qwen3-235B-A22B",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.071,
        output: 0.463,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 40960,
      maxTokens: 16384
    },
    "alibaba/qwen-3-30b": {
      id: "alibaba/qwen-3-30b",
      name: "Qwen3-30B-A3B",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.08,
        output: 0.29,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 40960,
      maxTokens: 16384
    },
    "alibaba/qwen-3-32b": {
      id: "alibaba/qwen-3-32b",
      name: "Qwen 3 32B",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.29,
        output: 0.59,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 40960
    },
    "alibaba/qwen3-235b-a22b-thinking": {
      id: "alibaba/qwen3-235b-a22b-thinking",
      name: "Qwen3 235B A22B Thinking 2507",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.3,
        output: 2.9000000000000004,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 262114,
      maxTokens: 262114
    },
    "alibaba/qwen3-coder": {
      id: "alibaba/qwen3-coder",
      name: "Qwen3 Coder 480B A35B Instruct",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.39999999999999997,
        output: 1.5999999999999999,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 66536
    },
    "alibaba/qwen3-coder-30b-a3b": {
      id: "alibaba/qwen3-coder-30b-a3b",
      name: "Qwen 3 Coder 30B A3B Instruct",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.15,
        output: 0.6,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 8192
    },
    "alibaba/qwen3-coder-next": {
      id: "alibaba/qwen3-coder-next",
      name: "Qwen3 Coder Next",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.5,
        output: 1.2,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 256e3,
      maxTokens: 256e3
    },
    "alibaba/qwen3-coder-plus": {
      id: "alibaba/qwen3-coder-plus",
      name: "Qwen3 Coder Plus",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 1,
        output: 5,
        cacheRead: 0.19999999999999998,
        cacheWrite: 0
      },
      contextWindow: 1e6,
      maxTokens: 65536
    },
    "alibaba/qwen3-max": {
      id: "alibaba/qwen3-max",
      name: "Qwen3 Max",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 1.2,
        output: 6,
        cacheRead: 0.24,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 32768
    },
    "alibaba/qwen3-max-preview": {
      id: "alibaba/qwen3-max-preview",
      name: "Qwen3 Max Preview",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 1.2,
        output: 6,
        cacheRead: 0.24,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 32768
    },
    "alibaba/qwen3-max-thinking": {
      id: "alibaba/qwen3-max-thinking",
      name: "Qwen 3 Max Thinking",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 1.2,
        output: 6,
        cacheRead: 0.24,
        cacheWrite: 0
      },
      contextWindow: 256e3,
      maxTokens: 65536
    },
    "alibaba/qwen3-vl-thinking": {
      id: "alibaba/qwen3-vl-thinking",
      name: "Qwen3 VL 235B A22B Thinking",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.22,
        output: 0.88,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 256e3,
      maxTokens: 256e3
    },
    "alibaba/qwen3.5-flash": {
      id: "alibaba/qwen3.5-flash",
      name: "Qwen 3.5 Flash",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.09999999999999999,
        output: 0.39999999999999997,
        cacheRead: 1e-3,
        cacheWrite: 0.125
      },
      contextWindow: 1e6,
      maxTokens: 64e3
    },
    "alibaba/qwen3.5-plus": {
      id: "alibaba/qwen3.5-plus",
      name: "Qwen 3.5 Plus",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.39999999999999997,
        output: 2.4,
        cacheRead: 0.04,
        cacheWrite: 0.5
      },
      contextWindow: 1e6,
      maxTokens: 64e3
    },
    "anthropic/claude-3-haiku": {
      id: "anthropic/claude-3-haiku",
      name: "Claude 3 Haiku",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.25,
        output: 1.25,
        cacheRead: 0.03,
        cacheWrite: 0.3
      },
      contextWindow: 2e5,
      maxTokens: 4096
    },
    "anthropic/claude-3.5-haiku": {
      id: "anthropic/claude-3.5-haiku",
      name: "Claude 3.5 Haiku",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.7999999999999999,
        output: 4,
        cacheRead: 0.08,
        cacheWrite: 1
      },
      contextWindow: 2e5,
      maxTokens: 8192
    },
    "anthropic/claude-3.5-sonnet": {
      id: "anthropic/claude-3.5-sonnet",
      name: "Claude 3.5 Sonnet",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.3,
        cacheWrite: 3.75
      },
      contextWindow: 2e5,
      maxTokens: 8192
    },
    "anthropic/claude-3.5-sonnet-20240620": {
      id: "anthropic/claude-3.5-sonnet-20240620",
      name: "Claude 3.5 Sonnet (2024-06-20)",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.3,
        cacheWrite: 3.75
      },
      contextWindow: 2e5,
      maxTokens: 8192
    },
    "anthropic/claude-3.7-sonnet": {
      id: "anthropic/claude-3.7-sonnet",
      name: "Claude 3.7 Sonnet",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.3,
        cacheWrite: 3.75
      },
      contextWindow: 2e5,
      maxTokens: 8192
    },
    "anthropic/claude-haiku-4.5": {
      id: "anthropic/claude-haiku-4.5",
      name: "Claude Haiku 4.5",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1,
        output: 5,
        cacheRead: 0.09999999999999999,
        cacheWrite: 1.25
      },
      contextWindow: 2e5,
      maxTokens: 64e3
    },
    "anthropic/claude-opus-4": {
      id: "anthropic/claude-opus-4",
      name: "Claude Opus 4",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 15,
        output: 75,
        cacheRead: 1.5,
        cacheWrite: 18.75
      },
      contextWindow: 2e5,
      maxTokens: 32e3
    },
    "anthropic/claude-opus-4.1": {
      id: "anthropic/claude-opus-4.1",
      name: "Claude Opus 4.1",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 15,
        output: 75,
        cacheRead: 1.5,
        cacheWrite: 18.75
      },
      contextWindow: 2e5,
      maxTokens: 32e3
    },
    "anthropic/claude-opus-4.5": {
      id: "anthropic/claude-opus-4.5",
      name: "Claude Opus 4.5",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 5,
        output: 25,
        cacheRead: 0.5,
        cacheWrite: 6.25
      },
      contextWindow: 2e5,
      maxTokens: 64e3
    },
    "anthropic/claude-opus-4.6": {
      id: "anthropic/claude-opus-4.6",
      name: "Claude Opus 4.6",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 5,
        output: 25,
        cacheRead: 0.5,
        cacheWrite: 6.25
      },
      contextWindow: 1e6,
      maxTokens: 128e3
    },
    "anthropic/claude-sonnet-4": {
      id: "anthropic/claude-sonnet-4",
      name: "Claude Sonnet 4",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.3,
        cacheWrite: 3.75
      },
      contextWindow: 1e6,
      maxTokens: 64e3
    },
    "anthropic/claude-sonnet-4.5": {
      id: "anthropic/claude-sonnet-4.5",
      name: "Claude Sonnet 4.5",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.3,
        cacheWrite: 3.75
      },
      contextWindow: 1e6,
      maxTokens: 64e3
    },
    "anthropic/claude-sonnet-4.6": {
      id: "anthropic/claude-sonnet-4.6",
      name: "Claude Sonnet 4.6",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.3,
        cacheWrite: 3.75
      },
      contextWindow: 1e6,
      maxTokens: 128e3
    },
    "arcee-ai/trinity-large-preview": {
      id: "arcee-ai/trinity-large-preview",
      name: "Trinity Large Preview",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.25,
        output: 1,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131e3,
      maxTokens: 131e3
    },
    "bytedance/seed-1.6": {
      id: "bytedance/seed-1.6",
      name: "Seed 1.6",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.25,
        output: 2,
        cacheRead: 0.049999999999999996,
        cacheWrite: 0
      },
      contextWindow: 256e3,
      maxTokens: 32e3
    },
    "cohere/command-a": {
      id: "cohere/command-a",
      name: "Command A",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 2.5,
        output: 10,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 256e3,
      maxTokens: 8e3
    },
    "deepseek/deepseek-r1": {
      id: "deepseek/deepseek-r1",
      name: "DeepSeek-R1",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 1.35,
        output: 5.4,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 8192
    },
    "deepseek/deepseek-v3": {
      id: "deepseek/deepseek-v3",
      name: "DeepSeek V3 0324",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.77,
        output: 0.77,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 163840,
      maxTokens: 16384
    },
    "deepseek/deepseek-v3.1": {
      id: "deepseek/deepseek-v3.1",
      name: "DeepSeek-V3.1",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.5,
        output: 1.5,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 163840,
      maxTokens: 16384
    },
    "deepseek/deepseek-v3.1-terminus": {
      id: "deepseek/deepseek-v3.1-terminus",
      name: "DeepSeek V3.1 Terminus",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.27,
        output: 1,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 65536
    },
    "deepseek/deepseek-v3.2": {
      id: "deepseek/deepseek-v3.2",
      name: "DeepSeek V3.2",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.26,
        output: 0.38,
        cacheRead: 0.13,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 8e3
    },
    "deepseek/deepseek-v3.2-thinking": {
      id: "deepseek/deepseek-v3.2-thinking",
      name: "DeepSeek V3.2 Thinking",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.28,
        output: 0.42,
        cacheRead: 0.028,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 64e3
    },
    "google/gemini-2.0-flash": {
      id: "google/gemini-2.0-flash",
      name: "Gemini 2.0 Flash",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.15,
        output: 0.6,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 1048576,
      maxTokens: 8192
    },
    "google/gemini-2.0-flash-lite": {
      id: "google/gemini-2.0-flash-lite",
      name: "Gemini 2.0 Flash Lite",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.075,
        output: 0.3,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 1048576,
      maxTokens: 8192
    },
    "google/gemini-2.5-flash": {
      id: "google/gemini-2.5-flash",
      name: "Gemini 2.5 Flash",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.3,
        output: 2.5,
        cacheRead: 0.03,
        cacheWrite: 0
      },
      contextWindow: 1e6,
      maxTokens: 65536
    },
    "google/gemini-2.5-flash-lite": {
      id: "google/gemini-2.5-flash-lite",
      name: "Gemini 2.5 Flash Lite",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.09999999999999999,
        output: 0.39999999999999997,
        cacheRead: 0.01,
        cacheWrite: 0
      },
      contextWindow: 1048576,
      maxTokens: 65536
    },
    "google/gemini-2.5-flash-lite-preview-09-2025": {
      id: "google/gemini-2.5-flash-lite-preview-09-2025",
      name: "Gemini 2.5 Flash Lite Preview 09-2025",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.09999999999999999,
        output: 0.39999999999999997,
        cacheRead: 0.01,
        cacheWrite: 0
      },
      contextWindow: 1048576,
      maxTokens: 65536
    },
    "google/gemini-2.5-flash-preview-09-2025": {
      id: "google/gemini-2.5-flash-preview-09-2025",
      name: "Gemini 2.5 Flash Preview 09-2025",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.3,
        output: 2.5,
        cacheRead: 0.03,
        cacheWrite: 0
      },
      contextWindow: 1e6,
      maxTokens: 65536
    },
    "google/gemini-2.5-pro": {
      id: "google/gemini-2.5-pro",
      name: "Gemini 2.5 Pro",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.25,
        output: 10,
        cacheRead: 0.125,
        cacheWrite: 0
      },
      contextWindow: 1048576,
      maxTokens: 65536
    },
    "google/gemini-3-flash": {
      id: "google/gemini-3-flash",
      name: "Gemini 3 Flash",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.5,
        output: 3,
        cacheRead: 0.049999999999999996,
        cacheWrite: 0
      },
      contextWindow: 1e6,
      maxTokens: 65e3
    },
    "google/gemini-3-pro-preview": {
      id: "google/gemini-3-pro-preview",
      name: "Gemini 3 Pro Preview",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 2,
        output: 12,
        cacheRead: 0.19999999999999998,
        cacheWrite: 0
      },
      contextWindow: 1e6,
      maxTokens: 64e3
    },
    "google/gemini-3.1-flash-lite-preview": {
      id: "google/gemini-3.1-flash-lite-preview",
      name: "Gemini 3.1 Flash Lite Preview",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.25,
        output: 1.5,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 1e6,
      maxTokens: 65e3
    },
    "google/gemini-3.1-pro-preview": {
      id: "google/gemini-3.1-pro-preview",
      name: "Gemini 3.1 Pro Preview",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 2,
        output: 12,
        cacheRead: 0.19999999999999998,
        cacheWrite: 0
      },
      contextWindow: 1e6,
      maxTokens: 64e3
    },
    "inception/mercury-2": {
      id: "inception/mercury-2",
      name: "Mercury 2",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.25,
        output: 0.75,
        cacheRead: 0.024999999999999998,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 128e3
    },
    "inception/mercury-coder-small": {
      id: "inception/mercury-coder-small",
      name: "Mercury Coder Small Beta",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.25,
        output: 1,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 32e3,
      maxTokens: 16384
    },
    "meituan/longcat-flash-chat": {
      id: "meituan/longcat-flash-chat",
      name: "LongCat Flash Chat",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 1e5
    },
    "meituan/longcat-flash-thinking": {
      id: "meituan/longcat-flash-thinking",
      name: "LongCat Flash Thinking",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.15,
        output: 1.5,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 8192
    },
    "meta/llama-3.1-70b": {
      id: "meta/llama-3.1-70b",
      name: "Llama 3.1 70B Instruct",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.72,
        output: 0.72,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 8192
    },
    "meta/llama-3.1-8b": {
      id: "meta/llama-3.1-8b",
      name: "Llama 3.1 8B Instruct",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.09999999999999999,
        output: 0.09999999999999999,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 16384
    },
    "meta/llama-3.2-11b": {
      id: "meta/llama-3.2-11b",
      name: "Llama 3.2 11B Vision Instruct",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.16,
        output: 0.16,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 8192
    },
    "meta/llama-3.2-90b": {
      id: "meta/llama-3.2-90b",
      name: "Llama 3.2 90B Vision Instruct",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.72,
        output: 0.72,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 8192
    },
    "meta/llama-3.3-70b": {
      id: "meta/llama-3.3-70b",
      name: "Llama 3.3 70B Instruct",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.72,
        output: 0.72,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 8192
    },
    "meta/llama-4-maverick": {
      id: "meta/llama-4-maverick",
      name: "Llama 4 Maverick 17B Instruct",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.24,
        output: 0.9700000000000001,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 8192
    },
    "meta/llama-4-scout": {
      id: "meta/llama-4-scout",
      name: "Llama 4 Scout 17B Instruct",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.16999999999999998,
        output: 0.66,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 8192
    },
    "minimax/minimax-m2": {
      id: "minimax/minimax-m2",
      name: "MiniMax M2",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.3,
        output: 1.2,
        cacheRead: 0.03,
        cacheWrite: 0.375
      },
      contextWindow: 205e3,
      maxTokens: 205e3
    },
    "minimax/minimax-m2.1": {
      id: "minimax/minimax-m2.1",
      name: "MiniMax M2.1",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.3,
        output: 1.2,
        cacheRead: 0.03,
        cacheWrite: 0.375
      },
      contextWindow: 204800,
      maxTokens: 131072
    },
    "minimax/minimax-m2.1-lightning": {
      id: "minimax/minimax-m2.1-lightning",
      name: "MiniMax M2.1 Lightning",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.3,
        output: 2.4,
        cacheRead: 0.03,
        cacheWrite: 0.375
      },
      contextWindow: 204800,
      maxTokens: 131072
    },
    "minimax/minimax-m2.5": {
      id: "minimax/minimax-m2.5",
      name: "MiniMax M2.5",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.3,
        output: 1.2,
        cacheRead: 0.03,
        cacheWrite: 0.375
      },
      contextWindow: 204800,
      maxTokens: 131e3
    },
    "minimax/minimax-m2.5-highspeed": {
      id: "minimax/minimax-m2.5-highspeed",
      name: "MiniMax M2.5 High Speed",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.6,
        output: 2.4,
        cacheRead: 0.03,
        cacheWrite: 0.375
      },
      contextWindow: 4096,
      maxTokens: 4096
    },
    "mistral/codestral": {
      id: "mistral/codestral",
      name: "Mistral Codestral",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.3,
        output: 0.8999999999999999,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 4e3
    },
    "mistral/devstral-2": {
      id: "mistral/devstral-2",
      name: "Devstral 2",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 256e3,
      maxTokens: 256e3
    },
    "mistral/devstral-small": {
      id: "mistral/devstral-small",
      name: "Devstral Small 1.1",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.09999999999999999,
        output: 0.3,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 64e3
    },
    "mistral/devstral-small-2": {
      id: "mistral/devstral-small-2",
      name: "Devstral Small 2",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 256e3,
      maxTokens: 256e3
    },
    "mistral/ministral-3b": {
      id: "mistral/ministral-3b",
      name: "Ministral 3B",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.04,
        output: 0.04,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 4e3
    },
    "mistral/ministral-8b": {
      id: "mistral/ministral-8b",
      name: "Ministral 8B",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.09999999999999999,
        output: 0.09999999999999999,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 4e3
    },
    "mistral/mistral-medium": {
      id: "mistral/mistral-medium",
      name: "Mistral Medium 3.1",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.39999999999999997,
        output: 2,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 64e3
    },
    "mistral/mistral-small": {
      id: "mistral/mistral-small",
      name: "Mistral Small",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.09999999999999999,
        output: 0.3,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 32e3,
      maxTokens: 4e3
    },
    "mistral/pixtral-12b": {
      id: "mistral/pixtral-12b",
      name: "Pixtral 12B 2409",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.15,
        output: 0.15,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 4e3
    },
    "mistral/pixtral-large": {
      id: "mistral/pixtral-large",
      name: "Pixtral Large",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 2,
        output: 6,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 4e3
    },
    "moonshotai/kimi-k2": {
      id: "moonshotai/kimi-k2",
      name: "Kimi K2",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.6,
        output: 2.5,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 16384
    },
    "moonshotai/kimi-k2-0905": {
      id: "moonshotai/kimi-k2-0905",
      name: "Kimi K2 0905",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.6,
        output: 2.5,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 256e3,
      maxTokens: 16384
    },
    "moonshotai/kimi-k2-thinking": {
      id: "moonshotai/kimi-k2-thinking",
      name: "Kimi K2 Thinking",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.6,
        output: 2.5,
        cacheRead: 0.15,
        cacheWrite: 0
      },
      contextWindow: 262114,
      maxTokens: 262114
    },
    "moonshotai/kimi-k2-thinking-turbo": {
      id: "moonshotai/kimi-k2-thinking-turbo",
      name: "Kimi K2 Thinking Turbo",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 1.15,
        output: 8,
        cacheRead: 0.15,
        cacheWrite: 0
      },
      contextWindow: 262114,
      maxTokens: 262114
    },
    "moonshotai/kimi-k2-turbo": {
      id: "moonshotai/kimi-k2-turbo",
      name: "Kimi K2 Turbo",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 2.4,
        output: 10,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 256e3,
      maxTokens: 16384
    },
    "moonshotai/kimi-k2.5": {
      id: "moonshotai/kimi-k2.5",
      name: "Kimi K2.5",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.6,
        output: 3,
        cacheRead: 0.09999999999999999,
        cacheWrite: 0
      },
      contextWindow: 262114,
      maxTokens: 262114
    },
    "nvidia/nemotron-nano-12b-v2-vl": {
      id: "nvidia/nemotron-nano-12b-v2-vl",
      name: "Nvidia Nemotron Nano 12B V2 VL",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.19999999999999998,
        output: 0.6,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 131072
    },
    "nvidia/nemotron-nano-9b-v2": {
      id: "nvidia/nemotron-nano-9b-v2",
      name: "Nvidia Nemotron Nano 9B V2",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.06,
        output: 0.22999999999999998,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 131072
    },
    "openai/gpt-4-turbo": {
      id: "openai/gpt-4-turbo",
      name: "GPT-4 Turbo",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 10,
        output: 30,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 4096
    },
    "openai/gpt-4.1": {
      id: "openai/gpt-4.1",
      name: "GPT-4.1",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 2,
        output: 8,
        cacheRead: 0.5,
        cacheWrite: 0
      },
      contextWindow: 1047576,
      maxTokens: 32768
    },
    "openai/gpt-4.1-mini": {
      id: "openai/gpt-4.1-mini",
      name: "GPT-4.1 mini",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.39999999999999997,
        output: 1.5999999999999999,
        cacheRead: 0.09999999999999999,
        cacheWrite: 0
      },
      contextWindow: 1047576,
      maxTokens: 32768
    },
    "openai/gpt-4.1-nano": {
      id: "openai/gpt-4.1-nano",
      name: "GPT-4.1 nano",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.09999999999999999,
        output: 0.39999999999999997,
        cacheRead: 0.024999999999999998,
        cacheWrite: 0
      },
      contextWindow: 1047576,
      maxTokens: 32768
    },
    "openai/gpt-4o": {
      id: "openai/gpt-4o",
      name: "GPT-4o",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 2.5,
        output: 10,
        cacheRead: 1.25,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 16384
    },
    "openai/gpt-4o-mini": {
      id: "openai/gpt-4o-mini",
      name: "GPT-4o mini",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.15,
        output: 0.6,
        cacheRead: 0.075,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 16384
    },
    "openai/gpt-5": {
      id: "openai/gpt-5",
      name: "GPT-5",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.25,
        output: 10,
        cacheRead: 0.125,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "openai/gpt-5-chat": {
      id: "openai/gpt-5-chat",
      name: "GPT 5 Chat",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.25,
        output: 10,
        cacheRead: 0.125,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 16384
    },
    "openai/gpt-5-codex": {
      id: "openai/gpt-5-codex",
      name: "GPT-5-Codex",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 1.25,
        output: 10,
        cacheRead: 0.125,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "openai/gpt-5-mini": {
      id: "openai/gpt-5-mini",
      name: "GPT-5 mini",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.25,
        output: 2,
        cacheRead: 0.024999999999999998,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "openai/gpt-5-nano": {
      id: "openai/gpt-5-nano",
      name: "GPT-5 nano",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.049999999999999996,
        output: 0.39999999999999997,
        cacheRead: 5e-3,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "openai/gpt-5-pro": {
      id: "openai/gpt-5-pro",
      name: "GPT-5 pro",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 15,
        output: 120,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 272e3
    },
    "openai/gpt-5.1-codex": {
      id: "openai/gpt-5.1-codex",
      name: "GPT-5.1-Codex",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.25,
        output: 10,
        cacheRead: 0.125,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "openai/gpt-5.1-codex-max": {
      id: "openai/gpt-5.1-codex-max",
      name: "GPT 5.1 Codex Max",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.25,
        output: 10,
        cacheRead: 0.125,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "openai/gpt-5.1-codex-mini": {
      id: "openai/gpt-5.1-codex-mini",
      name: "GPT 5.1 Codex Mini",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.25,
        output: 2,
        cacheRead: 0.024999999999999998,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "openai/gpt-5.1-instant": {
      id: "openai/gpt-5.1-instant",
      name: "GPT-5.1 Instant",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.25,
        output: 10,
        cacheRead: 0.125,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 16384
    },
    "openai/gpt-5.1-thinking": {
      id: "openai/gpt-5.1-thinking",
      name: "GPT 5.1 Thinking",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.25,
        output: 10,
        cacheRead: 0.125,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "openai/gpt-5.2": {
      id: "openai/gpt-5.2",
      name: "GPT 5.2",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.75,
        output: 14,
        cacheRead: 0.175,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "openai/gpt-5.2-chat": {
      id: "openai/gpt-5.2-chat",
      name: "GPT 5.2 Chat",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.75,
        output: 14,
        cacheRead: 0.175,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 16384
    },
    "openai/gpt-5.2-codex": {
      id: "openai/gpt-5.2-codex",
      name: "GPT 5.2 Codex",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.75,
        output: 14,
        cacheRead: 0.175,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "openai/gpt-5.2-pro": {
      id: "openai/gpt-5.2-pro",
      name: "GPT 5.2 ",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 21,
        output: 168,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "openai/gpt-5.3-chat": {
      id: "openai/gpt-5.3-chat",
      name: "GPT-5.3 Chat",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.75,
        output: 14,
        cacheRead: 0.175,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 16384
    },
    "openai/gpt-5.3-codex": {
      id: "openai/gpt-5.3-codex",
      name: "GPT 5.3 Codex",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.75,
        output: 14,
        cacheRead: 0.175,
        cacheWrite: 0
      },
      contextWindow: 4e5,
      maxTokens: 128e3
    },
    "openai/gpt-5.4": {
      id: "openai/gpt-5.4",
      name: "GPT 5.4",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 2.5,
        output: 15,
        cacheRead: 0.25,
        cacheWrite: 0
      },
      contextWindow: 105e4,
      maxTokens: 128e3
    },
    "openai/gpt-5.4-pro": {
      id: "openai/gpt-5.4-pro",
      name: "GPT 5.4 Pro",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 30,
        output: 180,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 105e4,
      maxTokens: 128e3
    },
    "openai/gpt-oss-20b": {
      id: "openai/gpt-oss-20b",
      name: "gpt-oss-20b",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.07,
        output: 0.3,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 8192
    },
    "openai/gpt-oss-safeguard-20b": {
      id: "openai/gpt-oss-safeguard-20b",
      name: "gpt-oss-safeguard-20b",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.075,
        output: 0.3,
        cacheRead: 0.037,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 65536
    },
    "openai/o1": {
      id: "openai/o1",
      name: "o1",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 15,
        output: 60,
        cacheRead: 7.5,
        cacheWrite: 0
      },
      contextWindow: 2e5,
      maxTokens: 1e5
    },
    "openai/o3": {
      id: "openai/o3",
      name: "o3",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 2,
        output: 8,
        cacheRead: 0.5,
        cacheWrite: 0
      },
      contextWindow: 2e5,
      maxTokens: 1e5
    },
    "openai/o3-deep-research": {
      id: "openai/o3-deep-research",
      name: "o3-deep-research",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 10,
        output: 40,
        cacheRead: 2.5,
        cacheWrite: 0
      },
      contextWindow: 2e5,
      maxTokens: 1e5
    },
    "openai/o3-mini": {
      id: "openai/o3-mini",
      name: "o3-mini",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 1.1,
        output: 4.4,
        cacheRead: 0.55,
        cacheWrite: 0
      },
      contextWindow: 2e5,
      maxTokens: 1e5
    },
    "openai/o3-pro": {
      id: "openai/o3-pro",
      name: "o3 Pro",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 20,
        output: 80,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 2e5,
      maxTokens: 1e5
    },
    "openai/o4-mini": {
      id: "openai/o4-mini",
      name: "o4-mini",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 1.1,
        output: 4.4,
        cacheRead: 0.275,
        cacheWrite: 0
      },
      contextWindow: 2e5,
      maxTokens: 1e5
    },
    "perplexity/sonar": {
      id: "perplexity/sonar",
      name: "Sonar",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 1,
        output: 1,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 127e3,
      maxTokens: 8e3
    },
    "perplexity/sonar-pro": {
      id: "perplexity/sonar-pro",
      name: "Sonar Pro",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 2e5,
      maxTokens: 8e3
    },
    "prime-intellect/intellect-3": {
      id: "prime-intellect/intellect-3",
      name: "INTELLECT 3",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.19999999999999998,
        output: 1.1,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 131072
    },
    "vercel/v0-1.0-md": {
      id: "vercel/v0-1.0-md",
      name: "v0-1.0-md",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 32e3
    },
    "vercel/v0-1.5-md": {
      id: "vercel/v0-1.5-md",
      name: "v0-1.5-md",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 32768
    },
    "xai/grok-2-vision": {
      id: "xai/grok-2-vision",
      name: "Grok 2 Vision",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 2,
        output: 10,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 32768,
      maxTokens: 32768
    },
    "xai/grok-3": {
      id: "xai/grok-3",
      name: "Grok 3 Beta",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 131072
    },
    "xai/grok-3-fast": {
      id: "xai/grok-3-fast",
      name: "Grok 3 Fast Beta",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 5,
        output: 25,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 131072
    },
    "xai/grok-3-mini": {
      id: "xai/grok-3-mini",
      name: "Grok 3 Mini Beta",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.3,
        output: 0.5,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 131072
    },
    "xai/grok-3-mini-fast": {
      id: "xai/grok-3-mini-fast",
      name: "Grok 3 Mini Fast Beta",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.6,
        output: 4,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 131072
    },
    "xai/grok-4": {
      id: "xai/grok-4",
      name: "Grok 4",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.75,
        cacheWrite: 0
      },
      contextWindow: 256e3,
      maxTokens: 256e3
    },
    "xai/grok-4-fast-non-reasoning": {
      id: "xai/grok-4-fast-non-reasoning",
      name: "Grok 4 Fast Non-Reasoning",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.19999999999999998,
        output: 0.5,
        cacheRead: 0.049999999999999996,
        cacheWrite: 0
      },
      contextWindow: 2e6,
      maxTokens: 256e3
    },
    "xai/grok-4-fast-reasoning": {
      id: "xai/grok-4-fast-reasoning",
      name: "Grok 4 Fast Reasoning",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.19999999999999998,
        output: 0.5,
        cacheRead: 0.049999999999999996,
        cacheWrite: 0
      },
      contextWindow: 2e6,
      maxTokens: 256e3
    },
    "xai/grok-4.1-fast-non-reasoning": {
      id: "xai/grok-4.1-fast-non-reasoning",
      name: "Grok 4.1 Fast Non-Reasoning",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 0.19999999999999998,
        output: 0.5,
        cacheRead: 0.049999999999999996,
        cacheWrite: 0
      },
      contextWindow: 2e6,
      maxTokens: 3e4
    },
    "xai/grok-4.1-fast-reasoning": {
      id: "xai/grok-4.1-fast-reasoning",
      name: "Grok 4.1 Fast Reasoning",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.19999999999999998,
        output: 0.5,
        cacheRead: 0.049999999999999996,
        cacheWrite: 0
      },
      contextWindow: 2e6,
      maxTokens: 3e4
    },
    "xai/grok-4.20-multi-agent-beta": {
      id: "xai/grok-4.20-multi-agent-beta",
      name: "Grok 4.20 Multi Agent Beta",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 2,
        output: 6,
        cacheRead: 0.19999999999999998,
        cacheWrite: 0
      },
      contextWindow: 2e6,
      maxTokens: 2e6
    },
    "xai/grok-4.20-non-reasoning-beta": {
      id: "xai/grok-4.20-non-reasoning-beta",
      name: "Grok 4.20 Beta Non-Reasoning",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 2,
        output: 6,
        cacheRead: 0.19999999999999998,
        cacheWrite: 0
      },
      contextWindow: 2e6,
      maxTokens: 2e6
    },
    "xai/grok-4.20-reasoning-beta": {
      id: "xai/grok-4.20-reasoning-beta",
      name: "Grok 4.20 Beta Reasoning",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 2,
        output: 6,
        cacheRead: 0.19999999999999998,
        cacheWrite: 0
      },
      contextWindow: 2e6,
      maxTokens: 2e6
    },
    "xai/grok-code-fast-1": {
      id: "xai/grok-code-fast-1",
      name: "Grok Code Fast 1",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.19999999999999998,
        output: 1.5,
        cacheRead: 0.02,
        cacheWrite: 0
      },
      contextWindow: 256e3,
      maxTokens: 256e3
    },
    "xiaomi/mimo-v2-flash": {
      id: "xiaomi/mimo-v2-flash",
      name: "MiMo V2 Flash",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.09999999999999999,
        output: 0.3,
        cacheRead: 0.02,
        cacheWrite: 0
      },
      contextWindow: 262144,
      maxTokens: 32e3
    },
    "zai/glm-4.5": {
      id: "zai/glm-4.5",
      name: "GLM-4.5",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.6,
        output: 2.2,
        cacheRead: 0.11,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 96e3
    },
    "zai/glm-4.5-air": {
      id: "zai/glm-4.5-air",
      name: "GLM 4.5 Air",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.19999999999999998,
        output: 1.1,
        cacheRead: 0.03,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 96e3
    },
    "zai/glm-4.5v": {
      id: "zai/glm-4.5v",
      name: "GLM 4.5V",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.6,
        output: 1.7999999999999998,
        cacheRead: 0.11,
        cacheWrite: 0
      },
      contextWindow: 66e3,
      maxTokens: 16e3
    },
    "zai/glm-4.6": {
      id: "zai/glm-4.6",
      name: "GLM 4.6",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.44999999999999996,
        output: 1.7999999999999998,
        cacheRead: 0.11,
        cacheWrite: 0
      },
      contextWindow: 2e5,
      maxTokens: 96e3
    },
    "zai/glm-4.6v": {
      id: "zai/glm-4.6v",
      name: "GLM-4.6V",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.3,
        output: 0.8999999999999999,
        cacheRead: 0.049999999999999996,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 24e3
    },
    "zai/glm-4.6v-flash": {
      id: "zai/glm-4.6v-flash",
      name: "GLM-4.6V-Flash",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 24e3
    },
    "zai/glm-4.7": {
      id: "zai/glm-4.7",
      name: "GLM 4.7",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.6,
        output: 2.2,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 2e5,
      maxTokens: 12e4
    },
    "zai/glm-4.7-flash": {
      id: "zai/glm-4.7-flash",
      name: "GLM 4.7 Flash",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.07,
        output: 0.39999999999999997,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 2e5,
      maxTokens: 131e3
    },
    "zai/glm-4.7-flashx": {
      id: "zai/glm-4.7-flashx",
      name: "GLM 4.7 FlashX",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.06,
        output: 0.39999999999999997,
        cacheRead: 0.01,
        cacheWrite: 0
      },
      contextWindow: 2e5,
      maxTokens: 128e3
    },
    "zai/glm-5": {
      id: "zai/glm-5",
      name: "GLM 5",
      api: "anthropic-messages",
      provider: "vercel-ai-gateway",
      baseUrl: "https://ai-gateway.vercel.sh",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 1,
        output: 3.1999999999999997,
        cacheRead: 0.19999999999999998,
        cacheWrite: 0
      },
      contextWindow: 202800,
      maxTokens: 131100
    }
  },
  "xai": {
    "grok-2": {
      id: "grok-2",
      name: "Grok 2",
      api: "openai-completions",
      provider: "xai",
      baseUrl: "https://api.x.ai/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 2,
        output: 10,
        cacheRead: 2,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 8192
    },
    "grok-2-1212": {
      id: "grok-2-1212",
      name: "Grok 2 (1212)",
      api: "openai-completions",
      provider: "xai",
      baseUrl: "https://api.x.ai/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 2,
        output: 10,
        cacheRead: 2,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 8192
    },
    "grok-2-latest": {
      id: "grok-2-latest",
      name: "Grok 2 Latest",
      api: "openai-completions",
      provider: "xai",
      baseUrl: "https://api.x.ai/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 2,
        output: 10,
        cacheRead: 2,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 8192
    },
    "grok-2-vision": {
      id: "grok-2-vision",
      name: "Grok 2 Vision",
      api: "openai-completions",
      provider: "xai",
      baseUrl: "https://api.x.ai/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 2,
        output: 10,
        cacheRead: 2,
        cacheWrite: 0
      },
      contextWindow: 8192,
      maxTokens: 4096
    },
    "grok-2-vision-1212": {
      id: "grok-2-vision-1212",
      name: "Grok 2 Vision (1212)",
      api: "openai-completions",
      provider: "xai",
      baseUrl: "https://api.x.ai/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 2,
        output: 10,
        cacheRead: 2,
        cacheWrite: 0
      },
      contextWindow: 8192,
      maxTokens: 4096
    },
    "grok-2-vision-latest": {
      id: "grok-2-vision-latest",
      name: "Grok 2 Vision Latest",
      api: "openai-completions",
      provider: "xai",
      baseUrl: "https://api.x.ai/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 2,
        output: 10,
        cacheRead: 2,
        cacheWrite: 0
      },
      contextWindow: 8192,
      maxTokens: 4096
    },
    "grok-3": {
      id: "grok-3",
      name: "Grok 3",
      api: "openai-completions",
      provider: "xai",
      baseUrl: "https://api.x.ai/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.75,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 8192
    },
    "grok-3-fast": {
      id: "grok-3-fast",
      name: "Grok 3 Fast",
      api: "openai-completions",
      provider: "xai",
      baseUrl: "https://api.x.ai/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 5,
        output: 25,
        cacheRead: 1.25,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 8192
    },
    "grok-3-fast-latest": {
      id: "grok-3-fast-latest",
      name: "Grok 3 Fast Latest",
      api: "openai-completions",
      provider: "xai",
      baseUrl: "https://api.x.ai/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 5,
        output: 25,
        cacheRead: 1.25,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 8192
    },
    "grok-3-latest": {
      id: "grok-3-latest",
      name: "Grok 3 Latest",
      api: "openai-completions",
      provider: "xai",
      baseUrl: "https://api.x.ai/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.75,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 8192
    },
    "grok-3-mini": {
      id: "grok-3-mini",
      name: "Grok 3 Mini",
      api: "openai-completions",
      provider: "xai",
      baseUrl: "https://api.x.ai/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.3,
        output: 0.5,
        cacheRead: 0.075,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 8192
    },
    "grok-3-mini-fast": {
      id: "grok-3-mini-fast",
      name: "Grok 3 Mini Fast",
      api: "openai-completions",
      provider: "xai",
      baseUrl: "https://api.x.ai/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.6,
        output: 4,
        cacheRead: 0.15,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 8192
    },
    "grok-3-mini-fast-latest": {
      id: "grok-3-mini-fast-latest",
      name: "Grok 3 Mini Fast Latest",
      api: "openai-completions",
      provider: "xai",
      baseUrl: "https://api.x.ai/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.6,
        output: 4,
        cacheRead: 0.15,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 8192
    },
    "grok-3-mini-latest": {
      id: "grok-3-mini-latest",
      name: "Grok 3 Mini Latest",
      api: "openai-completions",
      provider: "xai",
      baseUrl: "https://api.x.ai/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.3,
        output: 0.5,
        cacheRead: 0.075,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 8192
    },
    "grok-4": {
      id: "grok-4",
      name: "Grok 4",
      api: "openai-completions",
      provider: "xai",
      baseUrl: "https://api.x.ai/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 3,
        output: 15,
        cacheRead: 0.75,
        cacheWrite: 0
      },
      contextWindow: 256e3,
      maxTokens: 64e3
    },
    "grok-4-1-fast": {
      id: "grok-4-1-fast",
      name: "Grok 4.1 Fast",
      api: "openai-completions",
      provider: "xai",
      baseUrl: "https://api.x.ai/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.2,
        output: 0.5,
        cacheRead: 0.05,
        cacheWrite: 0
      },
      contextWindow: 2e6,
      maxTokens: 3e4
    },
    "grok-4-1-fast-non-reasoning": {
      id: "grok-4-1-fast-non-reasoning",
      name: "Grok 4.1 Fast (Non-Reasoning)",
      api: "openai-completions",
      provider: "xai",
      baseUrl: "https://api.x.ai/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.2,
        output: 0.5,
        cacheRead: 0.05,
        cacheWrite: 0
      },
      contextWindow: 2e6,
      maxTokens: 3e4
    },
    "grok-4-fast": {
      id: "grok-4-fast",
      name: "Grok 4 Fast",
      api: "openai-completions",
      provider: "xai",
      baseUrl: "https://api.x.ai/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.2,
        output: 0.5,
        cacheRead: 0.05,
        cacheWrite: 0
      },
      contextWindow: 2e6,
      maxTokens: 3e4
    },
    "grok-4-fast-non-reasoning": {
      id: "grok-4-fast-non-reasoning",
      name: "Grok 4 Fast (Non-Reasoning)",
      api: "openai-completions",
      provider: "xai",
      baseUrl: "https://api.x.ai/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 0.2,
        output: 0.5,
        cacheRead: 0.05,
        cacheWrite: 0
      },
      contextWindow: 2e6,
      maxTokens: 3e4
    },
    "grok-4.20-beta-latest-non-reasoning": {
      id: "grok-4.20-beta-latest-non-reasoning",
      name: "Grok 4.20 Beta (Non-Reasoning)",
      api: "openai-completions",
      provider: "xai",
      baseUrl: "https://api.x.ai/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 2,
        output: 6,
        cacheRead: 0.2,
        cacheWrite: 0
      },
      contextWindow: 2e6,
      maxTokens: 3e4
    },
    "grok-4.20-beta-latest-reasoning": {
      id: "grok-4.20-beta-latest-reasoning",
      name: "Grok 4.20 Beta (Reasoning)",
      api: "openai-completions",
      provider: "xai",
      baseUrl: "https://api.x.ai/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 2,
        output: 6,
        cacheRead: 0.2,
        cacheWrite: 0
      },
      contextWindow: 2e6,
      maxTokens: 3e4
    },
    "grok-4.20-multi-agent-beta-latest": {
      id: "grok-4.20-multi-agent-beta-latest",
      name: "Grok 4.20 Multi-Agent Beta",
      api: "openai-completions",
      provider: "xai",
      baseUrl: "https://api.x.ai/v1",
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 2,
        output: 6,
        cacheRead: 0.2,
        cacheWrite: 0
      },
      contextWindow: 2e6,
      maxTokens: 3e4
    },
    "grok-beta": {
      id: "grok-beta",
      name: "Grok Beta",
      api: "openai-completions",
      provider: "xai",
      baseUrl: "https://api.x.ai/v1",
      reasoning: false,
      input: ["text"],
      cost: {
        input: 5,
        output: 15,
        cacheRead: 5,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 4096
    },
    "grok-code-fast-1": {
      id: "grok-code-fast-1",
      name: "Grok Code Fast 1",
      api: "openai-completions",
      provider: "xai",
      baseUrl: "https://api.x.ai/v1",
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.2,
        output: 1.5,
        cacheRead: 0.02,
        cacheWrite: 0
      },
      contextWindow: 256e3,
      maxTokens: 1e4
    },
    "grok-vision-beta": {
      id: "grok-vision-beta",
      name: "Grok Vision Beta",
      api: "openai-completions",
      provider: "xai",
      baseUrl: "https://api.x.ai/v1",
      reasoning: false,
      input: ["text", "image"],
      cost: {
        input: 5,
        output: 15,
        cacheRead: 5,
        cacheWrite: 0
      },
      contextWindow: 8192,
      maxTokens: 4096
    }
  },
  "zai": {
    "glm-4.5": {
      id: "glm-4.5",
      name: "GLM-4.5",
      api: "openai-completions",
      provider: "zai",
      baseUrl: "https://api.z.ai/api/coding/paas/v4",
      compat: { "supportsDeveloperRole": false, "thinkingFormat": "zai" },
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.6,
        output: 2.2,
        cacheRead: 0.11,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 98304
    },
    "glm-4.5-air": {
      id: "glm-4.5-air",
      name: "GLM-4.5-Air",
      api: "openai-completions",
      provider: "zai",
      baseUrl: "https://api.z.ai/api/coding/paas/v4",
      compat: { "supportsDeveloperRole": false, "thinkingFormat": "zai" },
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.2,
        output: 1.1,
        cacheRead: 0.03,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 98304
    },
    "glm-4.5-flash": {
      id: "glm-4.5-flash",
      name: "GLM-4.5-Flash",
      api: "openai-completions",
      provider: "zai",
      baseUrl: "https://api.z.ai/api/coding/paas/v4",
      compat: { "supportsDeveloperRole": false, "thinkingFormat": "zai" },
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 131072,
      maxTokens: 98304
    },
    "glm-4.5v": {
      id: "glm-4.5v",
      name: "GLM-4.5V",
      api: "openai-completions",
      provider: "zai",
      baseUrl: "https://api.z.ai/api/coding/paas/v4",
      compat: { "supportsDeveloperRole": false, "thinkingFormat": "zai" },
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.6,
        output: 1.8,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 64e3,
      maxTokens: 16384
    },
    "glm-4.6": {
      id: "glm-4.6",
      name: "GLM-4.6",
      api: "openai-completions",
      provider: "zai",
      baseUrl: "https://api.z.ai/api/coding/paas/v4",
      compat: { "supportsDeveloperRole": false, "thinkingFormat": "zai" },
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.6,
        output: 2.2,
        cacheRead: 0.11,
        cacheWrite: 0
      },
      contextWindow: 204800,
      maxTokens: 131072
    },
    "glm-4.6v": {
      id: "glm-4.6v",
      name: "GLM-4.6V",
      api: "openai-completions",
      provider: "zai",
      baseUrl: "https://api.z.ai/api/coding/paas/v4",
      compat: { "supportsDeveloperRole": false, "thinkingFormat": "zai" },
      reasoning: true,
      input: ["text", "image"],
      cost: {
        input: 0.3,
        output: 0.9,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 128e3,
      maxTokens: 32768
    },
    "glm-4.7": {
      id: "glm-4.7",
      name: "GLM-4.7",
      api: "openai-completions",
      provider: "zai",
      baseUrl: "https://api.z.ai/api/coding/paas/v4",
      compat: { "supportsDeveloperRole": false, "thinkingFormat": "zai" },
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0.6,
        output: 2.2,
        cacheRead: 0.11,
        cacheWrite: 0
      },
      contextWindow: 204800,
      maxTokens: 131072
    },
    "glm-4.7-flash": {
      id: "glm-4.7-flash",
      name: "GLM-4.7-Flash",
      api: "openai-completions",
      provider: "zai",
      baseUrl: "https://api.z.ai/api/coding/paas/v4",
      compat: { "supportsDeveloperRole": false, "thinkingFormat": "zai" },
      reasoning: true,
      input: ["text"],
      cost: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0
      },
      contextWindow: 2e5,
      maxTokens: 131072
    },
    "glm-5": {
      id: "glm-5",
      name: "GLM-5",
      api: "openai-completions",
      provider: "zai",
      baseUrl: "https://api.z.ai/api/coding/paas/v4",
      compat: { "supportsDeveloperRole": false, "thinkingFormat": "zai" },
      reasoning: true,
      input: ["text"],
      cost: {
        input: 1,
        output: 3.2,
        cacheRead: 0.2,
        cacheWrite: 0
      },
      contextWindow: 204800,
      maxTokens: 131072
    }
  }
};

// ../pi-mono/packages/ai/dist/models.js
var modelRegistry = /* @__PURE__ */ new Map();
for (const [provider, models2] of Object.entries(MODELS)) {
  const providerModels = /* @__PURE__ */ new Map();
  for (const [id, model] of Object.entries(models2)) {
    providerModels.set(id, model);
  }
  modelRegistry.set(provider, providerModels);
}
function getModel(provider, modelId) {
  const providerModels = modelRegistry.get(provider);
  return providerModels?.get(modelId);
}
function getProviders() {
  return Array.from(modelRegistry.keys());
}
function getModels(provider) {
  const models2 = modelRegistry.get(provider);
  return models2 ? Array.from(models2.values()) : [];
}
function calculateCost(model, usage) {
  usage.cost.input = model.cost.input / 1e6 * usage.input;
  usage.cost.output = model.cost.output / 1e6 * usage.output;
  usage.cost.cacheRead = model.cost.cacheRead / 1e6 * usage.cacheRead;
  usage.cost.cacheWrite = model.cost.cacheWrite / 1e6 * usage.cacheWrite;
  usage.cost.total = usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite;
  return usage.cost;
}
function supportsXhigh(model) {
  if (model.id.includes("gpt-5.2") || model.id.includes("gpt-5.3") || model.id.includes("gpt-5.4")) {
    return true;
  }
  if (model.id.includes("opus-4-6") || model.id.includes("opus-4.6")) {
    return true;
  }
  return false;
}
function modelsAreEqual(a3, b4) {
  if (!a3 || !b4)
    return false;
  return a3.id === b4.id && a3.provider === b4.provider;
}

// ../pi-mono/packages/ai/dist/providers/anthropic.js
init_process_shim();

// ../pi-mono/node_modules/@anthropic-ai/sdk/index.mjs
init_process_shim();

// ../pi-mono/node_modules/@anthropic-ai/sdk/client.mjs
init_process_shim();

// ../pi-mono/node_modules/@anthropic-ai/sdk/internal/tslib.mjs
init_process_shim();
function __classPrivateFieldSet(receiver, state, value, kind, f4) {
  if (kind === "m")
    throw new TypeError("Private method is not writable");
  if (kind === "a" && !f4)
    throw new TypeError("Private accessor was defined without a setter");
  if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver))
    throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return kind === "a" ? f4.call(receiver, value) : f4 ? f4.value = value : state.set(receiver, value), value;
}
function __classPrivateFieldGet(receiver, state, kind, f4) {
  if (kind === "a" && !f4)
    throw new TypeError("Private accessor was defined without a getter");
  if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver))
    throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return kind === "m" ? f4 : kind === "a" ? f4.call(receiver) : f4 ? f4.value : state.get(receiver);
}

// ../pi-mono/node_modules/@anthropic-ai/sdk/internal/utils/uuid.mjs
init_process_shim();
var uuid4 = function() {
  const { crypto: crypto2 } = globalThis;
  if (crypto2?.randomUUID) {
    uuid4 = crypto2.randomUUID.bind(crypto2);
    return crypto2.randomUUID();
  }
  const u8 = new Uint8Array(1);
  const randomByte = crypto2 ? () => crypto2.getRandomValues(u8)[0] : () => Math.random() * 255 & 255;
  return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c6) => (+c6 ^ randomByte() & 15 >> +c6 / 4).toString(16));
};

// ../pi-mono/node_modules/@anthropic-ai/sdk/internal/utils/values.mjs
init_process_shim();

// ../pi-mono/node_modules/@anthropic-ai/sdk/core/error.mjs
init_process_shim();

// ../pi-mono/node_modules/@anthropic-ai/sdk/internal/errors.mjs
init_process_shim();
function isAbortError(err) {
  return typeof err === "object" && err !== null && // Spec-compliant fetch implementations
  ("name" in err && err.name === "AbortError" || // Expo fetch
  "message" in err && String(err.message).includes("FetchRequestCanceledException"));
}
var castToError = (err) => {
  if (err instanceof Error)
    return err;
  if (typeof err === "object" && err !== null) {
    try {
      if (Object.prototype.toString.call(err) === "[object Error]") {
        const error = new Error(err.message, err.cause ? { cause: err.cause } : {});
        if (err.stack)
          error.stack = err.stack;
        if (err.cause && !error.cause)
          error.cause = err.cause;
        if (err.name)
          error.name = err.name;
        return error;
      }
    } catch {
    }
    try {
      return new Error(JSON.stringify(err));
    } catch {
    }
  }
  return new Error(err);
};

// ../pi-mono/node_modules/@anthropic-ai/sdk/core/error.mjs
var AnthropicError = class extends Error {
};
var APIError = class _APIError extends AnthropicError {
  constructor(status, error, message, headers) {
    super(`${_APIError.makeMessage(status, error, message)}`);
    this.status = status;
    this.headers = headers;
    this.requestID = headers?.get("request-id");
    this.error = error;
  }
  static makeMessage(status, error, message) {
    const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
    if (status && msg) {
      return `${status} ${msg}`;
    }
    if (status) {
      return `${status} status code (no body)`;
    }
    if (msg) {
      return msg;
    }
    return "(no status code or body)";
  }
  static generate(status, errorResponse, message, headers) {
    if (!status || !headers) {
      return new APIConnectionError({ message, cause: castToError(errorResponse) });
    }
    const error = errorResponse;
    if (status === 400) {
      return new BadRequestError(status, error, message, headers);
    }
    if (status === 401) {
      return new AuthenticationError(status, error, message, headers);
    }
    if (status === 403) {
      return new PermissionDeniedError(status, error, message, headers);
    }
    if (status === 404) {
      return new NotFoundError(status, error, message, headers);
    }
    if (status === 409) {
      return new ConflictError(status, error, message, headers);
    }
    if (status === 422) {
      return new UnprocessableEntityError(status, error, message, headers);
    }
    if (status === 429) {
      return new RateLimitError(status, error, message, headers);
    }
    if (status >= 500) {
      return new InternalServerError(status, error, message, headers);
    }
    return new _APIError(status, error, message, headers);
  }
};
var APIUserAbortError = class extends APIError {
  constructor({ message } = {}) {
    super(void 0, void 0, message || "Request was aborted.", void 0);
  }
};
var APIConnectionError = class extends APIError {
  constructor({ message, cause }) {
    super(void 0, void 0, message || "Connection error.", void 0);
    if (cause)
      this.cause = cause;
  }
};
var APIConnectionTimeoutError = class extends APIConnectionError {
  constructor({ message } = {}) {
    super({ message: message ?? "Request timed out." });
  }
};
var BadRequestError = class extends APIError {
};
var AuthenticationError = class extends APIError {
};
var PermissionDeniedError = class extends APIError {
};
var NotFoundError = class extends APIError {
};
var ConflictError = class extends APIError {
};
var UnprocessableEntityError = class extends APIError {
};
var RateLimitError = class extends APIError {
};
var InternalServerError = class extends APIError {
};

// ../pi-mono/node_modules/@anthropic-ai/sdk/internal/utils/values.mjs
var startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i;
var isAbsoluteURL = (url) => {
  return startsWithSchemeRegexp.test(url);
};
var isArray = (val2) => (isArray = Array.isArray, isArray(val2));
var isReadonlyArray = isArray;
function maybeObj(x2) {
  if (typeof x2 !== "object") {
    return {};
  }
  return x2 ?? {};
}
function isEmptyObj(obj) {
  if (!obj)
    return true;
  for (const _k in obj)
    return false;
  return true;
}
function hasOwn(obj, key) {
  return Object.prototype.hasOwnProperty.call(obj, key);
}
var validatePositiveInteger = (name, n7) => {
  if (typeof n7 !== "number" || !Number.isInteger(n7)) {
    throw new AnthropicError(`${name} must be an integer`);
  }
  if (n7 < 0) {
    throw new AnthropicError(`${name} must be a positive integer`);
  }
  return n7;
};
var safeJSON = (text3) => {
  try {
    return JSON.parse(text3);
  } catch (err) {
    return void 0;
  }
};

// ../pi-mono/node_modules/@anthropic-ai/sdk/internal/utils/sleep.mjs
init_process_shim();
var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

// ../pi-mono/node_modules/@anthropic-ai/sdk/internal/detect-platform.mjs
init_process_shim();

// ../pi-mono/node_modules/@anthropic-ai/sdk/version.mjs
init_process_shim();
var VERSION = "0.73.0";

// ../pi-mono/node_modules/@anthropic-ai/sdk/internal/detect-platform.mjs
var isRunningInBrowser = () => {
  return (
    // @ts-ignore
    typeof window !== "undefined" && // @ts-ignore
    typeof window.document !== "undefined" && // @ts-ignore
    typeof navigator !== "undefined"
  );
};
function getDetectedPlatform() {
  if (typeof Deno !== "undefined" && Deno.build != null) {
    return "deno";
  }
  if (typeof EdgeRuntime !== "undefined") {
    return "edge";
  }
  if (Object.prototype.toString.call(typeof globalThis.process !== "undefined" ? globalThis.process : 0) === "[object process]") {
    return "node";
  }
  return "unknown";
}
var getPlatformProperties = () => {
  const detectedPlatform = getDetectedPlatform();
  if (detectedPlatform === "deno") {
    return {
      "X-Stainless-Lang": "js",
      "X-Stainless-Package-Version": VERSION,
      "X-Stainless-OS": normalizePlatform(Deno.build.os),
      "X-Stainless-Arch": normalizeArch(Deno.build.arch),
      "X-Stainless-Runtime": "deno",
      "X-Stainless-Runtime-Version": typeof Deno.version === "string" ? Deno.version : Deno.version?.deno ?? "unknown"
    };
  }
  if (typeof EdgeRuntime !== "undefined") {
    return {
      "X-Stainless-Lang": "js",
      "X-Stainless-Package-Version": VERSION,
      "X-Stainless-OS": "Unknown",
      "X-Stainless-Arch": `other:${EdgeRuntime}`,
      "X-Stainless-Runtime": "edge",
      "X-Stainless-Runtime-Version": globalThis.process.version
    };
  }
  if (detectedPlatform === "node") {
    return {
      "X-Stainless-Lang": "js",
      "X-Stainless-Package-Version": VERSION,
      "X-Stainless-OS": normalizePlatform(globalThis.process.platform ?? "unknown"),
      "X-Stainless-Arch": normalizeArch(globalThis.process.arch ?? "unknown"),
      "X-Stainless-Runtime": "node",
      "X-Stainless-Runtime-Version": globalThis.process.version ?? "unknown"
    };
  }
  const browserInfo = getBrowserInfo();
  if (browserInfo) {
    return {
      "X-Stainless-Lang": "js",
      "X-Stainless-Package-Version": VERSION,
      "X-Stainless-OS": "Unknown",
      "X-Stainless-Arch": "unknown",
      "X-Stainless-Runtime": `browser:${browserInfo.browser}`,
      "X-Stainless-Runtime-Version": browserInfo.version
    };
  }
  return {
    "X-Stainless-Lang": "js",
    "X-Stainless-Package-Version": VERSION,
    "X-Stainless-OS": "Unknown",
    "X-Stainless-Arch": "unknown",
    "X-Stainless-Runtime": "unknown",
    "X-Stainless-Runtime-Version": "unknown"
  };
};
function getBrowserInfo() {
  if (typeof navigator === "undefined" || !navigator) {
    return null;
  }
  const browserPatterns = [
    { key: "edge", pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
    { key: "ie", pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
    { key: "ie", pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ },
    { key: "chrome", pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
    { key: "firefox", pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
    { key: "safari", pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ }
  ];
  for (const { key, pattern } of browserPatterns) {
    const match2 = pattern.exec(navigator.userAgent);
    if (match2) {
      const major = match2[1] || 0;
      const minor = match2[2] || 0;
      const patch = match2[3] || 0;
      return { browser: key, version: `${major}.${minor}.${patch}` };
    }
  }
  return null;
}
var normalizeArch = (arch) => {
  if (arch === "x32")
    return "x32";
  if (arch === "x86_64" || arch === "x64")
    return "x64";
  if (arch === "arm")
    return "arm";
  if (arch === "aarch64" || arch === "arm64")
    return "arm64";
  if (arch)
    return `other:${arch}`;
  return "unknown";
};
var normalizePlatform = (platform) => {
  platform = platform.toLowerCase();
  if (platform.includes("ios"))
    return "iOS";
  if (platform === "android")
    return "Android";
  if (platform === "darwin")
    return "MacOS";
  if (platform === "win32")
    return "Windows";
  if (platform === "freebsd")
    return "FreeBSD";
  if (platform === "openbsd")
    return "OpenBSD";
  if (platform === "linux")
    return "Linux";
  if (platform)
    return `Other:${platform}`;
  return "Unknown";
};
var _platformHeaders;
var getPlatformHeaders = () => {
  return _platformHeaders ?? (_platformHeaders = getPlatformProperties());
};

// ../pi-mono/node_modules/@anthropic-ai/sdk/internal/shims.mjs
init_process_shim();
function getDefaultFetch() {
  if (typeof fetch !== "undefined") {
    return fetch;
  }
  throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`");
}
function makeReadableStream(...args) {
  const ReadableStream2 = globalThis.ReadableStream;
  if (typeof ReadableStream2 === "undefined") {
    throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");
  }
  return new ReadableStream2(...args);
}
function ReadableStreamFrom(iterable) {
  let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator]();
  return makeReadableStream({
    start() {
    },
    async pull(controller) {
      const { done, value } = await iter.next();
      if (done) {
        controller.close();
      } else {
        controller.enqueue(value);
      }
    },
    async cancel() {
      await iter.return?.();
    }
  });
}
function ReadableStreamToAsyncIterable(stream2) {
  if (stream2[Symbol.asyncIterator])
    return stream2;
  const reader = stream2.getReader();
  return {
    async next() {
      try {
        const result = await reader.read();
        if (result?.done)
          reader.releaseLock();
        return result;
      } catch (e9) {
        reader.releaseLock();
        throw e9;
      }
    },
    async return() {
      const cancelPromise = reader.cancel();
      reader.releaseLock();
      await cancelPromise;
      return { done: true, value: void 0 };
    },
    [Symbol.asyncIterator]() {
      return this;
    }
  };
}
async function CancelReadableStream(stream2) {
  if (stream2 === null || typeof stream2 !== "object")
    return;
  if (stream2[Symbol.asyncIterator]) {
    await stream2[Symbol.asyncIterator]().return?.();
    return;
  }
  const reader = stream2.getReader();
  const cancelPromise = reader.cancel();
  reader.releaseLock();
  await cancelPromise;
}

// ../pi-mono/node_modules/@anthropic-ai/sdk/internal/request-options.mjs
init_process_shim();
var FallbackEncoder = ({ headers, body }) => {
  return {
    bodyHeaders: {
      "content-type": "application/json"
    },
    body: JSON.stringify(body)
  };
};

// ../pi-mono/node_modules/@anthropic-ai/sdk/core/pagination.mjs
init_process_shim();

// ../pi-mono/node_modules/@anthropic-ai/sdk/internal/parse.mjs
init_process_shim();

// ../pi-mono/node_modules/@anthropic-ai/sdk/core/streaming.mjs
init_process_shim();

// ../pi-mono/node_modules/@anthropic-ai/sdk/internal/decoders/line.mjs
init_process_shim();

// ../pi-mono/node_modules/@anthropic-ai/sdk/internal/utils/bytes.mjs
init_process_shim();
function concatBytes(buffers) {
  let length = 0;
  for (const buffer of buffers) {
    length += buffer.length;
  }
  const output = new Uint8Array(length);
  let index = 0;
  for (const buffer of buffers) {
    output.set(buffer, index);
    index += buffer.length;
  }
  return output;
}
var encodeUTF8_;
function encodeUTF8(str2) {
  let encoder;
  return (encodeUTF8_ ?? (encoder = new globalThis.TextEncoder(), encodeUTF8_ = encoder.encode.bind(encoder)))(str2);
}
var decodeUTF8_;
function decodeUTF8(bytes) {
  let decoder;
  return (decodeUTF8_ ?? (decoder = new globalThis.TextDecoder(), decodeUTF8_ = decoder.decode.bind(decoder)))(bytes);
}

// ../pi-mono/node_modules/@anthropic-ai/sdk/internal/decoders/line.mjs
var _LineDecoder_buffer;
var _LineDecoder_carriageReturnIndex;
var LineDecoder = class {
  constructor() {
    _LineDecoder_buffer.set(this, void 0);
    _LineDecoder_carriageReturnIndex.set(this, void 0);
    __classPrivateFieldSet(this, _LineDecoder_buffer, new Uint8Array(), "f");
    __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f");
  }
  decode(chunk) {
    if (chunk == null) {
      return [];
    }
    const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? encodeUTF8(chunk) : chunk;
    __classPrivateFieldSet(this, _LineDecoder_buffer, concatBytes([__classPrivateFieldGet(this, _LineDecoder_buffer, "f"), binaryChunk]), "f");
    const lines = [];
    let patternIndex;
    while ((patternIndex = findNewlineIndex(__classPrivateFieldGet(this, _LineDecoder_buffer, "f"), __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f"))) != null) {
      if (patternIndex.carriage && __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") == null) {
        __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, patternIndex.index, "f");
        continue;
      }
      if (__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") != null && (patternIndex.index !== __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") + 1 || patternIndex.carriage)) {
        lines.push(decodeUTF8(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(0, __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") - 1)));
        __classPrivateFieldSet(this, _LineDecoder_buffer, __classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f")), "f");
        __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f");
        continue;
      }
      const endIndex = __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") !== null ? patternIndex.preceding - 1 : patternIndex.preceding;
      const line = decodeUTF8(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(0, endIndex));
      lines.push(line);
      __classPrivateFieldSet(this, _LineDecoder_buffer, __classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(patternIndex.index), "f");
      __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f");
    }
    return lines;
  }
  flush() {
    if (!__classPrivateFieldGet(this, _LineDecoder_buffer, "f").length) {
      return [];
    }
    return this.decode("\n");
  }
};
_LineDecoder_buffer = /* @__PURE__ */ new WeakMap(), _LineDecoder_carriageReturnIndex = /* @__PURE__ */ new WeakMap();
LineDecoder.NEWLINE_CHARS = /* @__PURE__ */ new Set(["\n", "\r"]);
LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r]/g;
function findNewlineIndex(buffer, startIndex) {
  const newline = 10;
  const carriage = 13;
  for (let i7 = startIndex ?? 0; i7 < buffer.length; i7++) {
    if (buffer[i7] === newline) {
      return { preceding: i7, index: i7 + 1, carriage: false };
    }
    if (buffer[i7] === carriage) {
      return { preceding: i7, index: i7 + 1, carriage: true };
    }
  }
  return null;
}
function findDoubleNewlineIndex(buffer) {
  const newline = 10;
  const carriage = 13;
  for (let i7 = 0; i7 < buffer.length - 1; i7++) {
    if (buffer[i7] === newline && buffer[i7 + 1] === newline) {
      return i7 + 2;
    }
    if (buffer[i7] === carriage && buffer[i7 + 1] === carriage) {
      return i7 + 2;
    }
    if (buffer[i7] === carriage && buffer[i7 + 1] === newline && i7 + 3 < buffer.length && buffer[i7 + 2] === carriage && buffer[i7 + 3] === newline) {
      return i7 + 4;
    }
  }
  return -1;
}

// ../pi-mono/node_modules/@anthropic-ai/sdk/internal/utils/log.mjs
init_process_shim();
var levelNumbers = {
  off: 0,
  error: 200,
  warn: 300,
  info: 400,
  debug: 500
};
var parseLogLevel = (maybeLevel, sourceName, client) => {
  if (!maybeLevel) {
    return void 0;
  }
  if (hasOwn(levelNumbers, maybeLevel)) {
    return maybeLevel;
  }
  loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`);
  return void 0;
};
function noop() {
}
function makeLogFn(fnLevel, logger2, logLevel) {
  if (!logger2 || levelNumbers[fnLevel] > levelNumbers[logLevel]) {
    return noop;
  } else {
    return logger2[fnLevel].bind(logger2);
  }
}
var noopLogger = {
  error: noop,
  warn: noop,
  info: noop,
  debug: noop
};
var cachedLoggers = /* @__PURE__ */ new WeakMap();
function loggerFor(client) {
  const logger2 = client.logger;
  const logLevel = client.logLevel ?? "off";
  if (!logger2) {
    return noopLogger;
  }
  const cachedLogger = cachedLoggers.get(logger2);
  if (cachedLogger && cachedLogger[0] === logLevel) {
    return cachedLogger[1];
  }
  const levelLogger = {
    error: makeLogFn("error", logger2, logLevel),
    warn: makeLogFn("warn", logger2, logLevel),
    info: makeLogFn("info", logger2, logLevel),
    debug: makeLogFn("debug", logger2, logLevel)
  };
  cachedLoggers.set(logger2, [logLevel, levelLogger]);
  return levelLogger;
}
var formatRequestDetails = (details) => {
  if (details.options) {
    details.options = { ...details.options };
    delete details.options["headers"];
  }
  if (details.headers) {
    details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [
      name,
      name.toLowerCase() === "x-api-key" || name.toLowerCase() === "authorization" || name.toLowerCase() === "cookie" || name.toLowerCase() === "set-cookie" ? "***" : value
    ]));
  }
  if ("retryOfRequestLogID" in details) {
    if (details.retryOfRequestLogID) {
      details.retryOf = details.retryOfRequestLogID;
    }
    delete details.retryOfRequestLogID;
  }
  return details;
};

// ../pi-mono/node_modules/@anthropic-ai/sdk/core/streaming.mjs
var _Stream_client;
var Stream = class _Stream {
  constructor(iterator, controller, client) {
    this.iterator = iterator;
    _Stream_client.set(this, void 0);
    this.controller = controller;
    __classPrivateFieldSet(this, _Stream_client, client, "f");
  }
  static fromSSEResponse(response, controller, client) {
    let consumed2 = false;
    const logger2 = client ? loggerFor(client) : console;
    async function* iterator() {
      if (consumed2) {
        throw new AnthropicError("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
      }
      consumed2 = true;
      let done = false;
      try {
        for await (const sse of _iterSSEMessages(response, controller)) {
          if (sse.event === "completion") {
            try {
              yield JSON.parse(sse.data);
            } catch (e9) {
              logger2.error(`Could not parse message into JSON:`, sse.data);
              logger2.error(`From chunk:`, sse.raw);
              throw e9;
            }
          }
          if (sse.event === "message_start" || sse.event === "message_delta" || sse.event === "message_stop" || sse.event === "content_block_start" || sse.event === "content_block_delta" || sse.event === "content_block_stop") {
            try {
              yield JSON.parse(sse.data);
            } catch (e9) {
              logger2.error(`Could not parse message into JSON:`, sse.data);
              logger2.error(`From chunk:`, sse.raw);
              throw e9;
            }
          }
          if (sse.event === "ping") {
            continue;
          }
          if (sse.event === "error") {
            throw new APIError(void 0, safeJSON(sse.data) ?? sse.data, void 0, response.headers);
          }
        }
        done = true;
      } catch (e9) {
        if (isAbortError(e9))
          return;
        throw e9;
      } finally {
        if (!done)
          controller.abort();
      }
    }
    return new _Stream(iterator, controller, client);
  }
  /**
   * Generates a Stream from a newline-separated ReadableStream
   * where each item is a JSON value.
   */
  static fromReadableStream(readableStream, controller, client) {
    let consumed2 = false;
    async function* iterLines() {
      const lineDecoder = new LineDecoder();
      const iter = ReadableStreamToAsyncIterable(readableStream);
      for await (const chunk of iter) {
        for (const line of lineDecoder.decode(chunk)) {
          yield line;
        }
      }
      for (const line of lineDecoder.flush()) {
        yield line;
      }
    }
    async function* iterator() {
      if (consumed2) {
        throw new AnthropicError("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
      }
      consumed2 = true;
      let done = false;
      try {
        for await (const line of iterLines()) {
          if (done)
            continue;
          if (line)
            yield JSON.parse(line);
        }
        done = true;
      } catch (e9) {
        if (isAbortError(e9))
          return;
        throw e9;
      } finally {
        if (!done)
          controller.abort();
      }
    }
    return new _Stream(iterator, controller, client);
  }
  [(_Stream_client = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() {
    return this.iterator();
  }
  /**
   * Splits the stream into two streams which can be
   * independently read from at different speeds.
   */
  tee() {
    const left = [];
    const right = [];
    const iterator = this.iterator();
    const teeIterator = (queue) => {
      return {
        next: () => {
          if (queue.length === 0) {
            const result = iterator.next();
            left.push(result);
            right.push(result);
          }
          return queue.shift();
        }
      };
    };
    return [
      new _Stream(() => teeIterator(left), this.controller, __classPrivateFieldGet(this, _Stream_client, "f")),
      new _Stream(() => teeIterator(right), this.controller, __classPrivateFieldGet(this, _Stream_client, "f"))
    ];
  }
  /**
   * Converts this stream to a newline-separated ReadableStream of
   * JSON stringified values in the stream
   * which can be turned back into a Stream with `Stream.fromReadableStream()`.
   */
  toReadableStream() {
    const self2 = this;
    let iter;
    return makeReadableStream({
      async start() {
        iter = self2[Symbol.asyncIterator]();
      },
      async pull(ctrl) {
        try {
          const { value, done } = await iter.next();
          if (done)
            return ctrl.close();
          const bytes = encodeUTF8(JSON.stringify(value) + "\n");
          ctrl.enqueue(bytes);
        } catch (err) {
          ctrl.error(err);
        }
      },
      async cancel() {
        await iter.return?.();
      }
    });
  }
};
async function* _iterSSEMessages(response, controller) {
  if (!response.body) {
    controller.abort();
    if (typeof globalThis.navigator !== "undefined" && globalThis.navigator.product === "ReactNative") {
      throw new AnthropicError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`);
    }
    throw new AnthropicError(`Attempted to iterate over a response with no body`);
  }
  const sseDecoder = new SSEDecoder();
  const lineDecoder = new LineDecoder();
  const iter = ReadableStreamToAsyncIterable(response.body);
  for await (const sseChunk of iterSSEChunks(iter)) {
    for (const line of lineDecoder.decode(sseChunk)) {
      const sse = sseDecoder.decode(line);
      if (sse)
        yield sse;
    }
  }
  for (const line of lineDecoder.flush()) {
    const sse = sseDecoder.decode(line);
    if (sse)
      yield sse;
  }
}
async function* iterSSEChunks(iterator) {
  let data = new Uint8Array();
  for await (const chunk of iterator) {
    if (chunk == null) {
      continue;
    }
    const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? encodeUTF8(chunk) : chunk;
    let newData = new Uint8Array(data.length + binaryChunk.length);
    newData.set(data);
    newData.set(binaryChunk, data.length);
    data = newData;
    let patternIndex;
    while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) {
      yield data.slice(0, patternIndex);
      data = data.slice(patternIndex);
    }
  }
  if (data.length > 0) {
    yield data;
  }
}
var SSEDecoder = class {
  constructor() {
    this.event = null;
    this.data = [];
    this.chunks = [];
  }
  decode(line) {
    if (line.endsWith("\r")) {
      line = line.substring(0, line.length - 1);
    }
    if (!line) {
      if (!this.event && !this.data.length)
        return null;
      const sse = {
        event: this.event,
        data: this.data.join("\n"),
        raw: this.chunks
      };
      this.event = null;
      this.data = [];
      this.chunks = [];
      return sse;
    }
    this.chunks.push(line);
    if (line.startsWith(":")) {
      return null;
    }
    let [fieldname, _3, value] = partition(line, ":");
    if (value.startsWith(" ")) {
      value = value.substring(1);
    }
    if (fieldname === "event") {
      this.event = value;
    } else if (fieldname === "data") {
      this.data.push(value);
    }
    return null;
  }
};
function partition(str2, delimiter2) {
  const index = str2.indexOf(delimiter2);
  if (index !== -1) {
    return [str2.substring(0, index), delimiter2, str2.substring(index + delimiter2.length)];
  }
  return [str2, "", ""];
}

// ../pi-mono/node_modules/@anthropic-ai/sdk/internal/parse.mjs
async function defaultParseResponse(client, props) {
  const { response, requestLogID, retryOfRequestLogID, startTime } = props;
  const body = await (async () => {
    if (props.options.stream) {
      loggerFor(client).debug("response", response.status, response.url, response.headers, response.body);
      if (props.options.__streamClass) {
        return props.options.__streamClass.fromSSEResponse(response, props.controller);
      }
      return Stream.fromSSEResponse(response, props.controller);
    }
    if (response.status === 204) {
      return null;
    }
    if (props.options.__binaryResponse) {
      return response;
    }
    const contentType = response.headers.get("content-type");
    const mediaType = contentType?.split(";")[0]?.trim();
    const isJSON = mediaType?.includes("application/json") || mediaType?.endsWith("+json");
    if (isJSON) {
      const contentLength = response.headers.get("content-length");
      if (contentLength === "0") {
        return void 0;
      }
      const json2 = await response.json();
      return addRequestID(json2, response);
    }
    const text3 = await response.text();
    return text3;
  })();
  loggerFor(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails({
    retryOfRequestLogID,
    url: response.url,
    status: response.status,
    body,
    durationMs: Date.now() - startTime
  }));
  return body;
}
function addRequestID(value, response) {
  if (!value || typeof value !== "object" || Array.isArray(value)) {
    return value;
  }
  return Object.defineProperty(value, "_request_id", {
    value: response.headers.get("request-id"),
    enumerable: false
  });
}

// ../pi-mono/node_modules/@anthropic-ai/sdk/core/api-promise.mjs
init_process_shim();
var _APIPromise_client;
var APIPromise = class _APIPromise extends Promise {
  constructor(client, responsePromise, parseResponse2 = defaultParseResponse) {
    super((resolve) => {
      resolve(null);
    });
    this.responsePromise = responsePromise;
    this.parseResponse = parseResponse2;
    _APIPromise_client.set(this, void 0);
    __classPrivateFieldSet(this, _APIPromise_client, client, "f");
  }
  _thenUnwrap(transform) {
    return new _APIPromise(__classPrivateFieldGet(this, _APIPromise_client, "f"), this.responsePromise, async (client, props) => addRequestID(transform(await this.parseResponse(client, props), props), props.response));
  }
  /**
   * Gets the raw `Response` instance instead of parsing the response
   * data.
   *
   * If you want to parse the response body but still get the `Response`
   * instance, you can use {@link withResponse()}.
   *
   * 👋 Getting the wrong TypeScript type for `Response`?
   * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
   * to your `tsconfig.json`.
   */
  asResponse() {
    return this.responsePromise.then((p4) => p4.response);
  }
  /**
   * Gets the parsed response data, the raw `Response` instance and the ID of the request,
   * returned via the `request-id` header which is useful for debugging requests and resporting
   * issues to Anthropic.
   *
   * If you just want to get the raw `Response` instance without parsing it,
   * you can use {@link asResponse()}.
   *
   * 👋 Getting the wrong TypeScript type for `Response`?
   * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
   * to your `tsconfig.json`.
   */
  async withResponse() {
    const [data, response] = await Promise.all([this.parse(), this.asResponse()]);
    return { data, response, request_id: response.headers.get("request-id") };
  }
  parse() {
    if (!this.parsedPromise) {
      this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(__classPrivateFieldGet(this, _APIPromise_client, "f"), data));
    }
    return this.parsedPromise;
  }
  then(onfulfilled, onrejected) {
    return this.parse().then(onfulfilled, onrejected);
  }
  catch(onrejected) {
    return this.parse().catch(onrejected);
  }
  finally(onfinally) {
    return this.parse().finally(onfinally);
  }
};
_APIPromise_client = /* @__PURE__ */ new WeakMap();

// ../pi-mono/node_modules/@anthropic-ai/sdk/core/pagination.mjs
var _AbstractPage_client;
var AbstractPage = class {
  constructor(client, response, body, options) {
    _AbstractPage_client.set(this, void 0);
    __classPrivateFieldSet(this, _AbstractPage_client, client, "f");
    this.options = options;
    this.response = response;
    this.body = body;
  }
  hasNextPage() {
    const items = this.getPaginatedItems();
    if (!items.length)
      return false;
    return this.nextPageRequestOptions() != null;
  }
  async getNextPage() {
    const nextOptions = this.nextPageRequestOptions();
    if (!nextOptions) {
      throw new AnthropicError("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");
    }
    return await __classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions);
  }
  async *iterPages() {
    let page = this;
    yield page;
    while (page.hasNextPage()) {
      page = await page.getNextPage();
      yield page;
    }
  }
  async *[(_AbstractPage_client = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() {
    for await (const page of this.iterPages()) {
      for (const item of page.getPaginatedItems()) {
        yield item;
      }
    }
  }
};
var PagePromise = class extends APIPromise {
  constructor(client, request, Page3) {
    super(client, request, async (client2, props) => new Page3(client2, props.response, await defaultParseResponse(client2, props), props.options));
  }
  /**
   * Allow auto-paginating iteration on an unawaited list call, eg:
   *
   *    for await (const item of client.items.list()) {
   *      console.log(item)
   *    }
   */
  async *[Symbol.asyncIterator]() {
    const page = await this;
    for await (const item of page) {
      yield item;
    }
  }
};
var Page = class extends AbstractPage {
  constructor(client, response, body, options) {
    super(client, response, body, options);
    this.data = body.data || [];
    this.has_more = body.has_more || false;
    this.first_id = body.first_id || null;
    this.last_id = body.last_id || null;
  }
  getPaginatedItems() {
    return this.data ?? [];
  }
  hasNextPage() {
    if (this.has_more === false) {
      return false;
    }
    return super.hasNextPage();
  }
  nextPageRequestOptions() {
    if (this.options.query?.["before_id"]) {
      const first_id = this.first_id;
      if (!first_id) {
        return null;
      }
      return {
        ...this.options,
        query: {
          ...maybeObj(this.options.query),
          before_id: first_id
        }
      };
    }
    const cursor = this.last_id;
    if (!cursor) {
      return null;
    }
    return {
      ...this.options,
      query: {
        ...maybeObj(this.options.query),
        after_id: cursor
      }
    };
  }
};
var PageCursor = class extends AbstractPage {
  constructor(client, response, body, options) {
    super(client, response, body, options);
    this.data = body.data || [];
    this.has_more = body.has_more || false;
    this.next_page = body.next_page || null;
  }
  getPaginatedItems() {
    return this.data ?? [];
  }
  hasNextPage() {
    if (this.has_more === false) {
      return false;
    }
    return super.hasNextPage();
  }
  nextPageRequestOptions() {
    const cursor = this.next_page;
    if (!cursor) {
      return null;
    }
    return {
      ...this.options,
      query: {
        ...maybeObj(this.options.query),
        page: cursor
      }
    };
  }
};

// ../pi-mono/node_modules/@anthropic-ai/sdk/core/uploads.mjs
init_process_shim();

// ../pi-mono/node_modules/@anthropic-ai/sdk/internal/to-file.mjs
init_process_shim();

// ../pi-mono/node_modules/@anthropic-ai/sdk/internal/uploads.mjs
init_process_shim();
var checkFileSupport = () => {
  if (typeof File === "undefined") {
    const { process: process2 } = globalThis;
    const isOldNode = typeof process2?.versions?.node === "string" && parseInt(process2.versions.node.split(".")) < 20;
    throw new Error("`File` is not defined as a global, which is required for file uploads." + (isOldNode ? " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`." : ""));
  }
};
function makeFile(fileBits, fileName, options) {
  checkFileSupport();
  return new File(fileBits, fileName ?? "unknown_file", options);
}
function getName(value, stripPath) {
  const val2 = typeof value === "object" && value !== null && ("name" in value && value.name && String(value.name) || "url" in value && value.url && String(value.url) || "filename" in value && value.filename && String(value.filename) || "path" in value && value.path && String(value.path)) || "";
  return stripPath ? val2.split(/[\\/]/).pop() || void 0 : val2;
}
var isAsyncIterable = (value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function";
var multipartFormRequestOptions = async (opts, fetch3, stripFilenames = true) => {
  return { ...opts, body: await createForm(opts.body, fetch3, stripFilenames) };
};
var supportsFormDataMap = /* @__PURE__ */ new WeakMap();
function supportsFormData(fetchObject) {
  const fetch3 = typeof fetchObject === "function" ? fetchObject : fetchObject.fetch;
  const cached = supportsFormDataMap.get(fetch3);
  if (cached)
    return cached;
  const promise = (async () => {
    try {
      const FetchResponse = "Response" in fetch3 ? fetch3.Response : (await fetch3("data:,")).constructor;
      const data = new FormData();
      if (data.toString() === await new FetchResponse(data).text()) {
        return false;
      }
      return true;
    } catch {
      return true;
    }
  })();
  supportsFormDataMap.set(fetch3, promise);
  return promise;
}
var createForm = async (body, fetch3, stripFilenames = true) => {
  if (!await supportsFormData(fetch3)) {
    throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");
  }
  const form = new FormData();
  await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value, stripFilenames)));
  return form;
};
var isNamedBlob = (value) => value instanceof Blob && "name" in value;
var addFormValue = async (form, key, value, stripFilenames) => {
  if (value === void 0)
    return;
  if (value == null) {
    throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`);
  }
  if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
    form.append(key, String(value));
  } else if (value instanceof Response) {
    let options = {};
    const contentType = value.headers.get("Content-Type");
    if (contentType) {
      options = { type: contentType };
    }
    form.append(key, makeFile([await value.blob()], getName(value, stripFilenames), options));
  } else if (isAsyncIterable(value)) {
    form.append(key, makeFile([await new Response(ReadableStreamFrom(value)).blob()], getName(value, stripFilenames)));
  } else if (isNamedBlob(value)) {
    form.append(key, makeFile([value], getName(value, stripFilenames), { type: value.type }));
  } else if (Array.isArray(value)) {
    await Promise.all(value.map((entry) => addFormValue(form, key + "[]", entry, stripFilenames)));
  } else if (typeof value === "object") {
    await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop, stripFilenames)));
  } else {
    throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`);
  }
};

// ../pi-mono/node_modules/@anthropic-ai/sdk/internal/to-file.mjs
var isBlobLike = (value) => value != null && typeof value === "object" && typeof value.size === "number" && typeof value.type === "string" && typeof value.text === "function" && typeof value.slice === "function" && typeof value.arrayBuffer === "function";
var isFileLike = (value) => value != null && typeof value === "object" && typeof value.name === "string" && typeof value.lastModified === "number" && isBlobLike(value);
var isResponseLike = (value) => value != null && typeof value === "object" && typeof value.url === "string" && typeof value.blob === "function";
async function toFile(value, name, options) {
  checkFileSupport();
  value = await value;
  name || (name = getName(value, true));
  if (isFileLike(value)) {
    if (value instanceof File && name == null && options == null) {
      return value;
    }
    return makeFile([await value.arrayBuffer()], name ?? value.name, {
      type: value.type,
      lastModified: value.lastModified,
      ...options
    });
  }
  if (isResponseLike(value)) {
    const blob = await value.blob();
    name || (name = new URL(value.url).pathname.split(/[\\/]/).pop());
    return makeFile(await getBytes(blob), name, options);
  }
  const parts = await getBytes(value);
  if (!options?.type) {
    const type = parts.find((part) => typeof part === "object" && "type" in part && part.type);
    if (typeof type === "string") {
      options = { ...options, type };
    }
  }
  return makeFile(parts, name, options);
}
async function getBytes(value) {
  let parts = [];
  if (typeof value === "string" || ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc.
  value instanceof ArrayBuffer) {
    parts.push(value);
  } else if (isBlobLike(value)) {
    parts.push(value instanceof Blob ? value : await value.arrayBuffer());
  } else if (isAsyncIterable(value)) {
    for await (const chunk of value) {
      parts.push(...await getBytes(chunk));
    }
  } else {
    const constructor = value?.constructor?.name;
    throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ""}${propsForError(value)}`);
  }
  return parts;
}
function propsForError(value) {
  if (typeof value !== "object" || value === null)
    return "";
  const props = Object.getOwnPropertyNames(value);
  return `; props: [${props.map((p4) => `"${p4}"`).join(", ")}]`;
}

// ../pi-mono/node_modules/@anthropic-ai/sdk/resources/index.mjs
init_process_shim();

// ../pi-mono/node_modules/@anthropic-ai/sdk/resources/shared.mjs
init_process_shim();

// ../pi-mono/node_modules/@anthropic-ai/sdk/resources/beta/beta.mjs
init_process_shim();

// ../pi-mono/node_modules/@anthropic-ai/sdk/core/resource.mjs
init_process_shim();
var APIResource = class {
  constructor(client) {
    this._client = client;
  }
};

// ../pi-mono/node_modules/@anthropic-ai/sdk/resources/beta/files.mjs
init_process_shim();

// ../pi-mono/node_modules/@anthropic-ai/sdk/internal/headers.mjs
init_process_shim();
var brand_privateNullableHeaders = Symbol.for("brand.privateNullableHeaders");
function* iterateHeaders(headers) {
  if (!headers)
    return;
  if (brand_privateNullableHeaders in headers) {
    const { values: values2, nulls } = headers;
    yield* values2.entries();
    for (const name of nulls) {
      yield [name, null];
    }
    return;
  }
  let shouldClear = false;
  let iter;
  if (headers instanceof Headers) {
    iter = headers.entries();
  } else if (isReadonlyArray(headers)) {
    iter = headers;
  } else {
    shouldClear = true;
    iter = Object.entries(headers ?? {});
  }
  for (let row of iter) {
    const name = row[0];
    if (typeof name !== "string")
      throw new TypeError("expected header name to be a string");
    const values2 = isReadonlyArray(row[1]) ? row[1] : [row[1]];
    let didClear = false;
    for (const value of values2) {
      if (value === void 0)
        continue;
      if (shouldClear && !didClear) {
        didClear = true;
        yield [name, null];
      }
      yield [name, value];
    }
  }
}
var buildHeaders = (newHeaders) => {
  const targetHeaders = new Headers();
  const nullHeaders = /* @__PURE__ */ new Set();
  for (const headers of newHeaders) {
    const seenHeaders = /* @__PURE__ */ new Set();
    for (const [name, value] of iterateHeaders(headers)) {
      const lowerName = name.toLowerCase();
      if (!seenHeaders.has(lowerName)) {
        targetHeaders.delete(name);
        seenHeaders.add(lowerName);
      }
      if (value === null) {
        targetHeaders.delete(name);
        nullHeaders.add(lowerName);
      } else {
        targetHeaders.append(name, value);
        nullHeaders.delete(lowerName);
      }
    }
  }
  return { [brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders };
};

// ../pi-mono/node_modules/@anthropic-ai/sdk/lib/stainless-helper-header.mjs
init_process_shim();
var SDK_HELPER_SYMBOL = Symbol("anthropic.sdk.stainlessHelper");
function wasCreatedByStainlessHelper(value) {
  return typeof value === "object" && value !== null && SDK_HELPER_SYMBOL in value;
}
function collectStainlessHelpers(tools, messages) {
  const helpers2 = /* @__PURE__ */ new Set();
  if (tools) {
    for (const tool of tools) {
      if (wasCreatedByStainlessHelper(tool)) {
        helpers2.add(tool[SDK_HELPER_SYMBOL]);
      }
    }
  }
  if (messages) {
    for (const message of messages) {
      if (wasCreatedByStainlessHelper(message)) {
        helpers2.add(message[SDK_HELPER_SYMBOL]);
      }
      if (Array.isArray(message.content)) {
        for (const block of message.content) {
          if (wasCreatedByStainlessHelper(block)) {
            helpers2.add(block[SDK_HELPER_SYMBOL]);
          }
        }
      }
    }
  }
  return Array.from(helpers2);
}
function stainlessHelperHeader(tools, messages) {
  const helpers2 = collectStainlessHelpers(tools, messages);
  if (helpers2.length === 0)
    return {};
  return { "x-stainless-helper": helpers2.join(", ") };
}
function stainlessHelperHeaderFromFile(file) {
  if (wasCreatedByStainlessHelper(file)) {
    return { "x-stainless-helper": file[SDK_HELPER_SYMBOL] };
  }
  return {};
}

// ../pi-mono/node_modules/@anthropic-ai/sdk/internal/utils/path.mjs
init_process_shim();
function encodeURIPath(str2) {
  return str2.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent);
}
var EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null));
var createPathTagFunction = (pathEncoder = encodeURIPath) => function path6(statics, ...params) {
  if (statics.length === 1)
    return statics[0];
  let postPath = false;
  const invalidSegments = [];
  const path7 = statics.reduce((previousValue, currentValue, index) => {
    if (/[?#]/.test(currentValue)) {
      postPath = true;
    }
    const value = params[index];
    let encoded = (postPath ? encodeURIComponent : pathEncoder)("" + value);
    if (index !== params.length && (value == null || typeof value === "object" && // handle values from other realms
    value.toString === Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? EMPTY) ?? EMPTY)?.toString)) {
      encoded = value + "";
      invalidSegments.push({
        start: previousValue.length + currentValue.length,
        length: encoded.length,
        error: `Value of type ${Object.prototype.toString.call(value).slice(8, -1)} is not a valid path parameter`
      });
    }
    return previousValue + currentValue + (index === params.length ? "" : encoded);
  }, "");
  const pathOnly = path7.split(/[?#]/, 1)[0];
  const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;
  let match2;
  while ((match2 = invalidSegmentPattern.exec(pathOnly)) !== null) {
    invalidSegments.push({
      start: match2.index,
      length: match2[0].length,
      error: `Value "${match2[0]}" can't be safely passed as a path parameter`
    });
  }
  invalidSegments.sort((a3, b4) => a3.start - b4.start);
  if (invalidSegments.length > 0) {
    let lastEnd = 0;
    const underline = invalidSegments.reduce((acc, segment) => {
      const spaces = " ".repeat(segment.start - lastEnd);
      const arrows = "^".repeat(segment.length);
      lastEnd = segment.start + segment.length;
      return acc + spaces + arrows;
    }, "");
    throw new AnthropicError(`Path parameters result in path with invalid segments:
${invalidSegments.map((e9) => e9.error).join("\n")}
${path7}
${underline}`);
  }
  return path7;
};
var path = /* @__PURE__ */ createPathTagFunction(encodeURIPath);

// ../pi-mono/node_modules/@anthropic-ai/sdk/resources/beta/files.mjs
var Files = class extends APIResource {
  /**
   * List Files
   *
   * @example
   * ```ts
   * // Automatically fetches more pages as needed.
   * for await (const fileMetadata of client.beta.files.list()) {
   *   // ...
   * }
   * ```
   */
  list(params = {}, options) {
    const { betas, ...query } = params ?? {};
    return this._client.getAPIList("/v1/files", Page, {
      query,
      ...options,
      headers: buildHeaders([
        { "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString() },
        options?.headers
      ])
    });
  }
  /**
   * Delete File
   *
   * @example
   * ```ts
   * const deletedFile = await client.beta.files.delete(
   *   'file_id',
   * );
   * ```
   */
  delete(fileID, params = {}, options) {
    const { betas } = params ?? {};
    return this._client.delete(path`/v1/files/${fileID}`, {
      ...options,
      headers: buildHeaders([
        { "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString() },
        options?.headers
      ])
    });
  }
  /**
   * Download File
   *
   * @example
   * ```ts
   * const response = await client.beta.files.download(
   *   'file_id',
   * );
   *
   * const content = await response.blob();
   * console.log(content);
   * ```
   */
  download(fileID, params = {}, options) {
    const { betas } = params ?? {};
    return this._client.get(path`/v1/files/${fileID}/content`, {
      ...options,
      headers: buildHeaders([
        {
          "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString(),
          Accept: "application/binary"
        },
        options?.headers
      ]),
      __binaryResponse: true
    });
  }
  /**
   * Get File Metadata
   *
   * @example
   * ```ts
   * const fileMetadata =
   *   await client.beta.files.retrieveMetadata('file_id');
   * ```
   */
  retrieveMetadata(fileID, params = {}, options) {
    const { betas } = params ?? {};
    return this._client.get(path`/v1/files/${fileID}`, {
      ...options,
      headers: buildHeaders([
        { "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString() },
        options?.headers
      ])
    });
  }
  /**
   * Upload File
   *
   * @example
   * ```ts
   * const fileMetadata = await client.beta.files.upload({
   *   file: fs.createReadStream('path/to/file'),
   * });
   * ```
   */
  upload(params, options) {
    const { betas, ...body } = params;
    return this._client.post("/v1/files", multipartFormRequestOptions({
      body,
      ...options,
      headers: buildHeaders([
        { "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString() },
        stainlessHelperHeaderFromFile(body.file),
        options?.headers
      ])
    }, this._client));
  }
};

// ../pi-mono/node_modules/@anthropic-ai/sdk/resources/beta/models.mjs
init_process_shim();
var Models = class extends APIResource {
  /**
   * Get a specific model.
   *
   * The Models API response can be used to determine information about a specific
   * model or resolve a model alias to a model ID.
   *
   * @example
   * ```ts
   * const betaModelInfo = await client.beta.models.retrieve(
   *   'model_id',
   * );
   * ```
   */
  retrieve(modelID, params = {}, options) {
    const { betas } = params ?? {};
    return this._client.get(path`/v1/models/${modelID}?beta=true`, {
      ...options,
      headers: buildHeaders([
        { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 },
        options?.headers
      ])
    });
  }
  /**
   * List available models.
   *
   * The Models API response can be used to determine which models are available for
   * use in the API. More recently released models are listed first.
   *
   * @example
   * ```ts
   * // Automatically fetches more pages as needed.
   * for await (const betaModelInfo of client.beta.models.list()) {
   *   // ...
   * }
   * ```
   */
  list(params = {}, options) {
    const { betas, ...query } = params ?? {};
    return this._client.getAPIList("/v1/models?beta=true", Page, {
      query,
      ...options,
      headers: buildHeaders([
        { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 },
        options?.headers
      ])
    });
  }
};

// ../pi-mono/node_modules/@anthropic-ai/sdk/resources/beta/messages/messages.mjs
init_process_shim();

// ../pi-mono/node_modules/@anthropic-ai/sdk/error.mjs
init_process_shim();

// ../pi-mono/node_modules/@anthropic-ai/sdk/internal/constants.mjs
init_process_shim();
var MODEL_NONSTREAMING_TOKENS = {
  "claude-opus-4-20250514": 8192,
  "claude-opus-4-0": 8192,
  "claude-4-opus-20250514": 8192,
  "anthropic.claude-opus-4-20250514-v1:0": 8192,
  "claude-opus-4@20250514": 8192,
  "claude-opus-4-1-20250805": 8192,
  "anthropic.claude-opus-4-1-20250805-v1:0": 8192,
  "claude-opus-4-1@20250805": 8192
};

// ../pi-mono/node_modules/@anthropic-ai/sdk/lib/beta-parser.mjs
init_process_shim();
function getOutputFormat(params) {
  return params?.output_format ?? params?.output_config?.format;
}
function maybeParseBetaMessage(message, params, opts) {
  const outputFormat = getOutputFormat(params);
  if (!params || !("parse" in (outputFormat ?? {}))) {
    return {
      ...message,
      content: message.content.map((block) => {
        if (block.type === "text") {
          const parsedBlock = Object.defineProperty({ ...block }, "parsed_output", {
            value: null,
            enumerable: false
          });
          return Object.defineProperty(parsedBlock, "parsed", {
            get() {
              opts.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead.");
              return null;
            },
            enumerable: false
          });
        }
        return block;
      }),
      parsed_output: null
    };
  }
  return parseBetaMessage(message, params, opts);
}
function parseBetaMessage(message, params, opts) {
  let firstParsedOutput = null;
  const content = message.content.map((block) => {
    if (block.type === "text") {
      const parsedOutput = parseBetaOutputFormat(params, block.text);
      if (firstParsedOutput === null) {
        firstParsedOutput = parsedOutput;
      }
      const parsedBlock = Object.defineProperty({ ...block }, "parsed_output", {
        value: parsedOutput,
        enumerable: false
      });
      return Object.defineProperty(parsedBlock, "parsed", {
        get() {
          opts.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead.");
          return parsedOutput;
        },
        enumerable: false
      });
    }
    return block;
  });
  return {
    ...message,
    content,
    parsed_output: firstParsedOutput
  };
}
function parseBetaOutputFormat(params, content) {
  const outputFormat = getOutputFormat(params);
  if (outputFormat?.type !== "json_schema") {
    return null;
  }
  try {
    if ("parse" in outputFormat) {
      return outputFormat.parse(content);
    }
    return JSON.parse(content);
  } catch (error) {
    throw new AnthropicError(`Failed to parse structured output: ${error}`);
  }
}

// ../pi-mono/node_modules/@anthropic-ai/sdk/lib/BetaMessageStream.mjs
init_process_shim();

// ../pi-mono/node_modules/@anthropic-ai/sdk/_vendor/partial-json-parser/parser.mjs
init_process_shim();
var tokenize = (input) => {
  let current2 = 0;
  let tokens = [];
  while (current2 < input.length) {
    let char = input[current2];
    if (char === "\\") {
      current2++;
      continue;
    }
    if (char === "{") {
      tokens.push({
        type: "brace",
        value: "{"
      });
      current2++;
      continue;
    }
    if (char === "}") {
      tokens.push({
        type: "brace",
        value: "}"
      });
      current2++;
      continue;
    }
    if (char === "[") {
      tokens.push({
        type: "paren",
        value: "["
      });
      current2++;
      continue;
    }
    if (char === "]") {
      tokens.push({
        type: "paren",
        value: "]"
      });
      current2++;
      continue;
    }
    if (char === ":") {
      tokens.push({
        type: "separator",
        value: ":"
      });
      current2++;
      continue;
    }
    if (char === ",") {
      tokens.push({
        type: "delimiter",
        value: ","
      });
      current2++;
      continue;
    }
    if (char === '"') {
      let value = "";
      let danglingQuote = false;
      char = input[++current2];
      while (char !== '"') {
        if (current2 === input.length) {
          danglingQuote = true;
          break;
        }
        if (char === "\\") {
          current2++;
          if (current2 === input.length) {
            danglingQuote = true;
            break;
          }
          value += char + input[current2];
          char = input[++current2];
        } else {
          value += char;
          char = input[++current2];
        }
      }
      char = input[++current2];
      if (!danglingQuote) {
        tokens.push({
          type: "string",
          value
        });
      }
      continue;
    }
    let WHITESPACE = /\s/;
    if (char && WHITESPACE.test(char)) {
      current2++;
      continue;
    }
    let NUMBERS = /[0-9]/;
    if (char && NUMBERS.test(char) || char === "-" || char === ".") {
      let value = "";
      if (char === "-") {
        value += char;
        char = input[++current2];
      }
      while (char && NUMBERS.test(char) || char === ".") {
        value += char;
        char = input[++current2];
      }
      tokens.push({
        type: "number",
        value
      });
      continue;
    }
    let LETTERS = /[a-z]/i;
    if (char && LETTERS.test(char)) {
      let value = "";
      while (char && LETTERS.test(char)) {
        if (current2 === input.length) {
          break;
        }
        value += char;
        char = input[++current2];
      }
      if (value == "true" || value == "false" || value === "null") {
        tokens.push({
          type: "name",
          value
        });
      } else {
        current2++;
        continue;
      }
      continue;
    }
    current2++;
  }
  return tokens;
};
var strip = (tokens) => {
  if (tokens.length === 0) {
    return tokens;
  }
  let lastToken = tokens[tokens.length - 1];
  switch (lastToken.type) {
    case "separator":
      tokens = tokens.slice(0, tokens.length - 1);
      return strip(tokens);
      break;
    case "number":
      let lastCharacterOfLastToken = lastToken.value[lastToken.value.length - 1];
      if (lastCharacterOfLastToken === "." || lastCharacterOfLastToken === "-") {
        tokens = tokens.slice(0, tokens.length - 1);
        return strip(tokens);
      }
    case "string":
      let tokenBeforeTheLastToken = tokens[tokens.length - 2];
      if (tokenBeforeTheLastToken?.type === "delimiter") {
        tokens = tokens.slice(0, tokens.length - 1);
        return strip(tokens);
      } else if (tokenBeforeTheLastToken?.type === "brace" && tokenBeforeTheLastToken.value === "{") {
        tokens = tokens.slice(0, tokens.length - 1);
        return strip(tokens);
      }
      break;
    case "delimiter":
      tokens = tokens.slice(0, tokens.length - 1);
      return strip(tokens);
      break;
  }
  return tokens;
};
var unstrip = (tokens) => {
  let tail = [];
  tokens.map((token) => {
    if (token.type === "brace") {
      if (token.value === "{") {
        tail.push("}");
      } else {
        tail.splice(tail.lastIndexOf("}"), 1);
      }
    }
    if (token.type === "paren") {
      if (token.value === "[") {
        tail.push("]");
      } else {
        tail.splice(tail.lastIndexOf("]"), 1);
      }
    }
  });
  if (tail.length > 0) {
    tail.reverse().map((item) => {
      if (item === "}") {
        tokens.push({
          type: "brace",
          value: "}"
        });
      } else if (item === "]") {
        tokens.push({
          type: "paren",
          value: "]"
        });
      }
    });
  }
  return tokens;
};
var generate = (tokens) => {
  let output = "";
  tokens.map((token) => {
    switch (token.type) {
      case "string":
        output += '"' + token.value + '"';
        break;
      default:
        output += token.value;
        break;
    }
  });
  return output;
};
var partialParse = (input) => JSON.parse(generate(unstrip(strip(tokenize(input)))));

// ../pi-mono/node_modules/@anthropic-ai/sdk/streaming.mjs
init_process_shim();

// ../pi-mono/node_modules/@anthropic-ai/sdk/lib/BetaMessageStream.mjs
var _BetaMessageStream_instances;
var _BetaMessageStream_currentMessageSnapshot;
var _BetaMessageStream_params;
var _BetaMessageStream_connectedPromise;
var _BetaMessageStream_resolveConnectedPromise;
var _BetaMessageStream_rejectConnectedPromise;
var _BetaMessageStream_endPromise;
var _BetaMessageStream_resolveEndPromise;
var _BetaMessageStream_rejectEndPromise;
var _BetaMessageStream_listeners;
var _BetaMessageStream_ended;
var _BetaMessageStream_errored;
var _BetaMessageStream_aborted;
var _BetaMessageStream_catchingPromiseCreated;
var _BetaMessageStream_response;
var _BetaMessageStream_request_id;
var _BetaMessageStream_logger;
var _BetaMessageStream_getFinalMessage;
var _BetaMessageStream_getFinalText;
var _BetaMessageStream_handleError;
var _BetaMessageStream_beginRequest;
var _BetaMessageStream_addStreamEvent;
var _BetaMessageStream_endRequest;
var _BetaMessageStream_accumulateMessage;
var JSON_BUF_PROPERTY = "__json_buf";
function tracksToolInput(content) {
  return content.type === "tool_use" || content.type === "server_tool_use" || content.type === "mcp_tool_use";
}
var BetaMessageStream = class _BetaMessageStream {
  constructor(params, opts) {
    _BetaMessageStream_instances.add(this);
    this.messages = [];
    this.receivedMessages = [];
    _BetaMessageStream_currentMessageSnapshot.set(this, void 0);
    _BetaMessageStream_params.set(this, null);
    this.controller = new AbortController();
    _BetaMessageStream_connectedPromise.set(this, void 0);
    _BetaMessageStream_resolveConnectedPromise.set(this, () => {
    });
    _BetaMessageStream_rejectConnectedPromise.set(this, () => {
    });
    _BetaMessageStream_endPromise.set(this, void 0);
    _BetaMessageStream_resolveEndPromise.set(this, () => {
    });
    _BetaMessageStream_rejectEndPromise.set(this, () => {
    });
    _BetaMessageStream_listeners.set(this, {});
    _BetaMessageStream_ended.set(this, false);
    _BetaMessageStream_errored.set(this, false);
    _BetaMessageStream_aborted.set(this, false);
    _BetaMessageStream_catchingPromiseCreated.set(this, false);
    _BetaMessageStream_response.set(this, void 0);
    _BetaMessageStream_request_id.set(this, void 0);
    _BetaMessageStream_logger.set(this, void 0);
    _BetaMessageStream_handleError.set(this, (error) => {
      __classPrivateFieldSet(this, _BetaMessageStream_errored, true, "f");
      if (isAbortError(error)) {
        error = new APIUserAbortError();
      }
      if (error instanceof APIUserAbortError) {
        __classPrivateFieldSet(this, _BetaMessageStream_aborted, true, "f");
        return this._emit("abort", error);
      }
      if (error instanceof AnthropicError) {
        return this._emit("error", error);
      }
      if (error instanceof Error) {
        const anthropicError = new AnthropicError(error.message);
        anthropicError.cause = error;
        return this._emit("error", anthropicError);
      }
      return this._emit("error", new AnthropicError(String(error)));
    });
    __classPrivateFieldSet(this, _BetaMessageStream_connectedPromise, new Promise((resolve, reject) => {
      __classPrivateFieldSet(this, _BetaMessageStream_resolveConnectedPromise, resolve, "f");
      __classPrivateFieldSet(this, _BetaMessageStream_rejectConnectedPromise, reject, "f");
    }), "f");
    __classPrivateFieldSet(this, _BetaMessageStream_endPromise, new Promise((resolve, reject) => {
      __classPrivateFieldSet(this, _BetaMessageStream_resolveEndPromise, resolve, "f");
      __classPrivateFieldSet(this, _BetaMessageStream_rejectEndPromise, reject, "f");
    }), "f");
    __classPrivateFieldGet(this, _BetaMessageStream_connectedPromise, "f").catch(() => {
    });
    __classPrivateFieldGet(this, _BetaMessageStream_endPromise, "f").catch(() => {
    });
    __classPrivateFieldSet(this, _BetaMessageStream_params, params, "f");
    __classPrivateFieldSet(this, _BetaMessageStream_logger, opts?.logger ?? console, "f");
  }
  get response() {
    return __classPrivateFieldGet(this, _BetaMessageStream_response, "f");
  }
  get request_id() {
    return __classPrivateFieldGet(this, _BetaMessageStream_request_id, "f");
  }
  /**
   * Returns the `MessageStream` data, the raw `Response` instance and the ID of the request,
   * returned vie the `request-id` header which is useful for debugging requests and resporting
   * issues to Anthropic.
   *
   * This is the same as the `APIPromise.withResponse()` method.
   *
   * This method will raise an error if you created the stream using `MessageStream.fromReadableStream`
   * as no `Response` is available.
   */
  async withResponse() {
    __classPrivateFieldSet(this, _BetaMessageStream_catchingPromiseCreated, true, "f");
    const response = await __classPrivateFieldGet(this, _BetaMessageStream_connectedPromise, "f");
    if (!response) {
      throw new Error("Could not resolve a `Response` object");
    }
    return {
      data: this,
      response,
      request_id: response.headers.get("request-id")
    };
  }
  /**
   * Intended for use on the frontend, consuming a stream produced with
   * `.toReadableStream()` on the backend.
   *
   * Note that messages sent to the model do not appear in `.on('message')`
   * in this context.
   */
  static fromReadableStream(stream2) {
    const runner = new _BetaMessageStream(null);
    runner._run(() => runner._fromReadableStream(stream2));
    return runner;
  }
  static createMessage(messages, params, options, { logger: logger2 } = {}) {
    const runner = new _BetaMessageStream(params, { logger: logger2 });
    for (const message of params.messages) {
      runner._addMessageParam(message);
    }
    __classPrivateFieldSet(runner, _BetaMessageStream_params, { ...params, stream: true }, "f");
    runner._run(() => runner._createMessage(messages, { ...params, stream: true }, { ...options, headers: { ...options?.headers, "X-Stainless-Helper-Method": "stream" } }));
    return runner;
  }
  _run(executor) {
    executor().then(() => {
      this._emitFinal();
      this._emit("end");
    }, __classPrivateFieldGet(this, _BetaMessageStream_handleError, "f"));
  }
  _addMessageParam(message) {
    this.messages.push(message);
  }
  _addMessage(message, emit = true) {
    this.receivedMessages.push(message);
    if (emit) {
      this._emit("message", message);
    }
  }
  async _createMessage(messages, params, options) {
    const signal = options?.signal;
    let abortHandler;
    if (signal) {
      if (signal.aborted)
        this.controller.abort();
      abortHandler = this.controller.abort.bind(this.controller);
      signal.addEventListener("abort", abortHandler);
    }
    try {
      __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_beginRequest).call(this);
      const { response, data: stream2 } = await messages.create({ ...params, stream: true }, { ...options, signal: this.controller.signal }).withResponse();
      this._connected(response);
      for await (const event of stream2) {
        __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_addStreamEvent).call(this, event);
      }
      if (stream2.controller.signal?.aborted) {
        throw new APIUserAbortError();
      }
      __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_endRequest).call(this);
    } finally {
      if (signal && abortHandler) {
        signal.removeEventListener("abort", abortHandler);
      }
    }
  }
  _connected(response) {
    if (this.ended)
      return;
    __classPrivateFieldSet(this, _BetaMessageStream_response, response, "f");
    __classPrivateFieldSet(this, _BetaMessageStream_request_id, response?.headers.get("request-id"), "f");
    __classPrivateFieldGet(this, _BetaMessageStream_resolveConnectedPromise, "f").call(this, response);
    this._emit("connect");
  }
  get ended() {
    return __classPrivateFieldGet(this, _BetaMessageStream_ended, "f");
  }
  get errored() {
    return __classPrivateFieldGet(this, _BetaMessageStream_errored, "f");
  }
  get aborted() {
    return __classPrivateFieldGet(this, _BetaMessageStream_aborted, "f");
  }
  abort() {
    this.controller.abort();
  }
  /**
   * Adds the listener function to the end of the listeners array for the event.
   * No checks are made to see if the listener has already been added. Multiple calls passing
   * the same combination of event and listener will result in the listener being added, and
   * called, multiple times.
   * @returns this MessageStream, so that calls can be chained
   */
  on(event, listener) {
    const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] = []);
    listeners.push({ listener });
    return this;
  }
  /**
   * Removes the specified listener from the listener array for the event.
   * off() will remove, at most, one instance of a listener from the listener array. If any single
   * listener has been added multiple times to the listener array for the specified event, then
   * off() must be called multiple times to remove each instance.
   * @returns this MessageStream, so that calls can be chained
   */
  off(event, listener) {
    const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event];
    if (!listeners)
      return this;
    const index = listeners.findIndex((l5) => l5.listener === listener);
    if (index >= 0)
      listeners.splice(index, 1);
    return this;
  }
  /**
   * Adds a one-time listener function for the event. The next time the event is triggered,
   * this listener is removed and then invoked.
   * @returns this MessageStream, so that calls can be chained
   */
  once(event, listener) {
    const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] = []);
    listeners.push({ listener, once: true });
    return this;
  }
  /**
   * This is similar to `.once()`, but returns a Promise that resolves the next time
   * the event is triggered, instead of calling a listener callback.
   * @returns a Promise that resolves the next time given event is triggered,
   * or rejects if an error is emitted.  (If you request the 'error' event,
   * returns a promise that resolves with the error).
   *
   * Example:
   *
   *   const message = await stream.emitted('message') // rejects if the stream errors
   */
  emitted(event) {
    return new Promise((resolve, reject) => {
      __classPrivateFieldSet(this, _BetaMessageStream_catchingPromiseCreated, true, "f");
      if (event !== "error")
        this.once("error", reject);
      this.once(event, resolve);
    });
  }
  async done() {
    __classPrivateFieldSet(this, _BetaMessageStream_catchingPromiseCreated, true, "f");
    await __classPrivateFieldGet(this, _BetaMessageStream_endPromise, "f");
  }
  get currentMessage() {
    return __classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, "f");
  }
  /**
   * @returns a promise that resolves with the the final assistant Message response,
   * or rejects if an error occurred or the stream ended prematurely without producing a Message.
   * If structured outputs were used, this will be a ParsedMessage with a `parsed` field.
   */
  async finalMessage() {
    await this.done();
    return __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalMessage).call(this);
  }
  /**
   * @returns a promise that resolves with the the final assistant Message's text response, concatenated
   * together if there are more than one text blocks.
   * Rejects if an error occurred or the stream ended prematurely without producing a Message.
   */
  async finalText() {
    await this.done();
    return __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalText).call(this);
  }
  _emit(event, ...args) {
    if (__classPrivateFieldGet(this, _BetaMessageStream_ended, "f"))
      return;
    if (event === "end") {
      __classPrivateFieldSet(this, _BetaMessageStream_ended, true, "f");
      __classPrivateFieldGet(this, _BetaMessageStream_resolveEndPromise, "f").call(this);
    }
    const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event];
    if (listeners) {
      __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] = listeners.filter((l5) => !l5.once);
      listeners.forEach(({ listener }) => listener(...args));
    }
    if (event === "abort") {
      const error = args[0];
      if (!__classPrivateFieldGet(this, _BetaMessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
        Promise.reject(error);
      }
      __classPrivateFieldGet(this, _BetaMessageStream_rejectConnectedPromise, "f").call(this, error);
      __classPrivateFieldGet(this, _BetaMessageStream_rejectEndPromise, "f").call(this, error);
      this._emit("end");
      return;
    }
    if (event === "error") {
      const error = args[0];
      if (!__classPrivateFieldGet(this, _BetaMessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
        Promise.reject(error);
      }
      __classPrivateFieldGet(this, _BetaMessageStream_rejectConnectedPromise, "f").call(this, error);
      __classPrivateFieldGet(this, _BetaMessageStream_rejectEndPromise, "f").call(this, error);
      this._emit("end");
    }
  }
  _emitFinal() {
    const finalMessage = this.receivedMessages.at(-1);
    if (finalMessage) {
      this._emit("finalMessage", __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalMessage).call(this));
    }
  }
  async _fromReadableStream(readableStream, options) {
    const signal = options?.signal;
    let abortHandler;
    if (signal) {
      if (signal.aborted)
        this.controller.abort();
      abortHandler = this.controller.abort.bind(this.controller);
      signal.addEventListener("abort", abortHandler);
    }
    try {
      __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_beginRequest).call(this);
      this._connected(null);
      const stream2 = Stream.fromReadableStream(readableStream, this.controller);
      for await (const event of stream2) {
        __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_addStreamEvent).call(this, event);
      }
      if (stream2.controller.signal?.aborted) {
        throw new APIUserAbortError();
      }
      __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_endRequest).call(this);
    } finally {
      if (signal && abortHandler) {
        signal.removeEventListener("abort", abortHandler);
      }
    }
  }
  [(_BetaMessageStream_currentMessageSnapshot = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_params = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_connectedPromise = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_resolveConnectedPromise = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_rejectConnectedPromise = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_endPromise = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_resolveEndPromise = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_rejectEndPromise = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_listeners = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_ended = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_errored = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_aborted = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_catchingPromiseCreated = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_response = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_request_id = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_logger = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_handleError = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_instances = /* @__PURE__ */ new WeakSet(), _BetaMessageStream_getFinalMessage = function _BetaMessageStream_getFinalMessage2() {
    if (this.receivedMessages.length === 0) {
      throw new AnthropicError("stream ended without producing a Message with role=assistant");
    }
    return this.receivedMessages.at(-1);
  }, _BetaMessageStream_getFinalText = function _BetaMessageStream_getFinalText2() {
    if (this.receivedMessages.length === 0) {
      throw new AnthropicError("stream ended without producing a Message with role=assistant");
    }
    const textBlocks = this.receivedMessages.at(-1).content.filter((block) => block.type === "text").map((block) => block.text);
    if (textBlocks.length === 0) {
      throw new AnthropicError("stream ended without producing a content block with type=text");
    }
    return textBlocks.join(" ");
  }, _BetaMessageStream_beginRequest = function _BetaMessageStream_beginRequest2() {
    if (this.ended)
      return;
    __classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, void 0, "f");
  }, _BetaMessageStream_addStreamEvent = function _BetaMessageStream_addStreamEvent2(event) {
    if (this.ended)
      return;
    const messageSnapshot = __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_accumulateMessage).call(this, event);
    this._emit("streamEvent", event, messageSnapshot);
    switch (event.type) {
      case "content_block_delta": {
        const content = messageSnapshot.content.at(-1);
        switch (event.delta.type) {
          case "text_delta": {
            if (content.type === "text") {
              this._emit("text", event.delta.text, content.text || "");
            }
            break;
          }
          case "citations_delta": {
            if (content.type === "text") {
              this._emit("citation", event.delta.citation, content.citations ?? []);
            }
            break;
          }
          case "input_json_delta": {
            if (tracksToolInput(content) && content.input) {
              this._emit("inputJson", event.delta.partial_json, content.input);
            }
            break;
          }
          case "thinking_delta": {
            if (content.type === "thinking") {
              this._emit("thinking", event.delta.thinking, content.thinking);
            }
            break;
          }
          case "signature_delta": {
            if (content.type === "thinking") {
              this._emit("signature", content.signature);
            }
            break;
          }
          case "compaction_delta": {
            if (content.type === "compaction" && content.content) {
              this._emit("compaction", content.content);
            }
            break;
          }
          default:
            checkNever(event.delta);
        }
        break;
      }
      case "message_stop": {
        this._addMessageParam(messageSnapshot);
        this._addMessage(maybeParseBetaMessage(messageSnapshot, __classPrivateFieldGet(this, _BetaMessageStream_params, "f"), { logger: __classPrivateFieldGet(this, _BetaMessageStream_logger, "f") }), true);
        break;
      }
      case "content_block_stop": {
        this._emit("contentBlock", messageSnapshot.content.at(-1));
        break;
      }
      case "message_start": {
        __classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, messageSnapshot, "f");
        break;
      }
      case "content_block_start":
      case "message_delta":
        break;
    }
  }, _BetaMessageStream_endRequest = function _BetaMessageStream_endRequest2() {
    if (this.ended) {
      throw new AnthropicError(`stream has ended, this shouldn't happen`);
    }
    const snapshot = __classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, "f");
    if (!snapshot) {
      throw new AnthropicError(`request ended without sending any chunks`);
    }
    __classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, void 0, "f");
    return maybeParseBetaMessage(snapshot, __classPrivateFieldGet(this, _BetaMessageStream_params, "f"), { logger: __classPrivateFieldGet(this, _BetaMessageStream_logger, "f") });
  }, _BetaMessageStream_accumulateMessage = function _BetaMessageStream_accumulateMessage2(event) {
    let snapshot = __classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, "f");
    if (event.type === "message_start") {
      if (snapshot) {
        throw new AnthropicError(`Unexpected event order, got ${event.type} before receiving "message_stop"`);
      }
      return event.message;
    }
    if (!snapshot) {
      throw new AnthropicError(`Unexpected event order, got ${event.type} before "message_start"`);
    }
    switch (event.type) {
      case "message_stop":
        return snapshot;
      case "message_delta":
        snapshot.container = event.delta.container;
        snapshot.stop_reason = event.delta.stop_reason;
        snapshot.stop_sequence = event.delta.stop_sequence;
        snapshot.usage.output_tokens = event.usage.output_tokens;
        snapshot.context_management = event.context_management;
        if (event.usage.input_tokens != null) {
          snapshot.usage.input_tokens = event.usage.input_tokens;
        }
        if (event.usage.cache_creation_input_tokens != null) {
          snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens;
        }
        if (event.usage.cache_read_input_tokens != null) {
          snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens;
        }
        if (event.usage.server_tool_use != null) {
          snapshot.usage.server_tool_use = event.usage.server_tool_use;
        }
        if (event.usage.iterations != null) {
          snapshot.usage.iterations = event.usage.iterations;
        }
        return snapshot;
      case "content_block_start":
        snapshot.content.push(event.content_block);
        return snapshot;
      case "content_block_delta": {
        const snapshotContent = snapshot.content.at(event.index);
        switch (event.delta.type) {
          case "text_delta": {
            if (snapshotContent?.type === "text") {
              snapshot.content[event.index] = {
                ...snapshotContent,
                text: (snapshotContent.text || "") + event.delta.text
              };
            }
            break;
          }
          case "citations_delta": {
            if (snapshotContent?.type === "text") {
              snapshot.content[event.index] = {
                ...snapshotContent,
                citations: [...snapshotContent.citations ?? [], event.delta.citation]
              };
            }
            break;
          }
          case "input_json_delta": {
            if (snapshotContent && tracksToolInput(snapshotContent)) {
              let jsonBuf = snapshotContent[JSON_BUF_PROPERTY] || "";
              jsonBuf += event.delta.partial_json;
              const newContent = { ...snapshotContent };
              Object.defineProperty(newContent, JSON_BUF_PROPERTY, {
                value: jsonBuf,
                enumerable: false,
                writable: true
              });
              if (jsonBuf) {
                try {
                  newContent.input = partialParse(jsonBuf);
                } catch (err) {
                  const error = new AnthropicError(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${err}. JSON: ${jsonBuf}`);
                  __classPrivateFieldGet(this, _BetaMessageStream_handleError, "f").call(this, error);
                }
              }
              snapshot.content[event.index] = newContent;
            }
            break;
          }
          case "thinking_delta": {
            if (snapshotContent?.type === "thinking") {
              snapshot.content[event.index] = {
                ...snapshotContent,
                thinking: snapshotContent.thinking + event.delta.thinking
              };
            }
            break;
          }
          case "signature_delta": {
            if (snapshotContent?.type === "thinking") {
              snapshot.content[event.index] = {
                ...snapshotContent,
                signature: event.delta.signature
              };
            }
            break;
          }
          case "compaction_delta": {
            if (snapshotContent?.type === "compaction") {
              snapshot.content[event.index] = {
                ...snapshotContent,
                content: (snapshotContent.content || "") + event.delta.content
              };
            }
            break;
          }
          default:
            checkNever(event.delta);
        }
        return snapshot;
      }
      case "content_block_stop":
        return snapshot;
    }
  }, Symbol.asyncIterator)]() {
    const pushQueue = [];
    const readQueue = [];
    let done = false;
    this.on("streamEvent", (event) => {
      const reader = readQueue.shift();
      if (reader) {
        reader.resolve(event);
      } else {
        pushQueue.push(event);
      }
    });
    this.on("end", () => {
      done = true;
      for (const reader of readQueue) {
        reader.resolve(void 0);
      }
      readQueue.length = 0;
    });
    this.on("abort", (err) => {
      done = true;
      for (const reader of readQueue) {
        reader.reject(err);
      }
      readQueue.length = 0;
    });
    this.on("error", (err) => {
      done = true;
      for (const reader of readQueue) {
        reader.reject(err);
      }
      readQueue.length = 0;
    });
    return {
      next: async () => {
        if (!pushQueue.length) {
          if (done) {
            return { value: void 0, done: true };
          }
          return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: void 0, done: true });
        }
        const chunk = pushQueue.shift();
        return { value: chunk, done: false };
      },
      return: async () => {
        this.abort();
        return { value: void 0, done: true };
      }
    };
  }
  toReadableStream() {
    const stream2 = new Stream(this[Symbol.asyncIterator].bind(this), this.controller);
    return stream2.toReadableStream();
  }
};
function checkNever(x2) {
}

// ../pi-mono/node_modules/@anthropic-ai/sdk/lib/tools/BetaToolRunner.mjs
init_process_shim();

// ../pi-mono/node_modules/@anthropic-ai/sdk/lib/tools/ToolError.mjs
init_process_shim();
var ToolError = class extends Error {
  constructor(content) {
    const message = typeof content === "string" ? content : content.map((block) => {
      if (block.type === "text")
        return block.text;
      return `[${block.type}]`;
    }).join(" ");
    super(message);
    this.name = "ToolError";
    this.content = content;
  }
};

// ../pi-mono/node_modules/@anthropic-ai/sdk/lib/tools/CompactionControl.mjs
init_process_shim();
var DEFAULT_TOKEN_THRESHOLD = 1e5;
var DEFAULT_SUMMARY_PROMPT = `You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:
1. Task Overview
The user's core request and success criteria
Any clarifications or constraints they specified
2. Current State
What has been completed so far
Files created, modified, or analyzed (with paths if relevant)
Key outputs or artifacts produced
3. Important Discoveries
Technical constraints or requirements uncovered
Decisions made and their rationale
Errors encountered and how they were resolved
What approaches were tried that didn't work (and why)
4. Next Steps
Specific actions needed to complete the task
Any blockers or open questions to resolve
Priority order if multiple steps remain
5. Context to Preserve
User preferences or style requirements
Domain-specific details that aren't obvious
Any promises made to the user
Be concise but complete\u2014err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task.
Wrap your summary in <summary></summary> tags.`;

// ../pi-mono/node_modules/@anthropic-ai/sdk/lib/tools/BetaToolRunner.mjs
var _BetaToolRunner_instances;
var _BetaToolRunner_consumed;
var _BetaToolRunner_mutated;
var _BetaToolRunner_state;
var _BetaToolRunner_options;
var _BetaToolRunner_message;
var _BetaToolRunner_toolResponse;
var _BetaToolRunner_completion;
var _BetaToolRunner_iterationCount;
var _BetaToolRunner_checkAndCompact;
var _BetaToolRunner_generateToolResponse;
function promiseWithResolvers() {
  let resolve;
  let reject;
  const promise = new Promise((res, rej) => {
    resolve = res;
    reject = rej;
  });
  return { promise, resolve, reject };
}
var BetaToolRunner = class {
  constructor(client, params, options) {
    _BetaToolRunner_instances.add(this);
    this.client = client;
    _BetaToolRunner_consumed.set(this, false);
    _BetaToolRunner_mutated.set(this, false);
    _BetaToolRunner_state.set(this, void 0);
    _BetaToolRunner_options.set(this, void 0);
    _BetaToolRunner_message.set(this, void 0);
    _BetaToolRunner_toolResponse.set(this, void 0);
    _BetaToolRunner_completion.set(this, void 0);
    _BetaToolRunner_iterationCount.set(this, 0);
    __classPrivateFieldSet(this, _BetaToolRunner_state, {
      params: {
        // You can't clone the entire params since there are functions as handlers.
        // You also don't really need to clone params.messages, but it probably will prevent a foot gun
        // somewhere.
        ...params,
        messages: structuredClone(params.messages)
      }
    }, "f");
    const helpers2 = collectStainlessHelpers(params.tools, params.messages);
    const helperValue = ["BetaToolRunner", ...helpers2].join(", ");
    __classPrivateFieldSet(this, _BetaToolRunner_options, {
      ...options,
      headers: buildHeaders([{ "x-stainless-helper": helperValue }, options?.headers])
    }, "f");
    __classPrivateFieldSet(this, _BetaToolRunner_completion, promiseWithResolvers(), "f");
  }
  async *[(_BetaToolRunner_consumed = /* @__PURE__ */ new WeakMap(), _BetaToolRunner_mutated = /* @__PURE__ */ new WeakMap(), _BetaToolRunner_state = /* @__PURE__ */ new WeakMap(), _BetaToolRunner_options = /* @__PURE__ */ new WeakMap(), _BetaToolRunner_message = /* @__PURE__ */ new WeakMap(), _BetaToolRunner_toolResponse = /* @__PURE__ */ new WeakMap(), _BetaToolRunner_completion = /* @__PURE__ */ new WeakMap(), _BetaToolRunner_iterationCount = /* @__PURE__ */ new WeakMap(), _BetaToolRunner_instances = /* @__PURE__ */ new WeakSet(), _BetaToolRunner_checkAndCompact = async function _BetaToolRunner_checkAndCompact2() {
    const compactionControl = __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.compactionControl;
    if (!compactionControl || !compactionControl.enabled) {
      return false;
    }
    let tokensUsed = 0;
    if (__classPrivateFieldGet(this, _BetaToolRunner_message, "f") !== void 0) {
      try {
        const message = await __classPrivateFieldGet(this, _BetaToolRunner_message, "f");
        const totalInputTokens = message.usage.input_tokens + (message.usage.cache_creation_input_tokens ?? 0) + (message.usage.cache_read_input_tokens ?? 0);
        tokensUsed = totalInputTokens + message.usage.output_tokens;
      } catch {
        return false;
      }
    }
    const threshold = compactionControl.contextTokenThreshold ?? DEFAULT_TOKEN_THRESHOLD;
    if (tokensUsed < threshold) {
      return false;
    }
    const model = compactionControl.model ?? __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.model;
    const summaryPrompt = compactionControl.summaryPrompt ?? DEFAULT_SUMMARY_PROMPT;
    const messages = __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages;
    if (messages[messages.length - 1].role === "assistant") {
      const lastMessage = messages[messages.length - 1];
      if (Array.isArray(lastMessage.content)) {
        const nonToolBlocks = lastMessage.content.filter((block) => block.type !== "tool_use");
        if (nonToolBlocks.length === 0) {
          messages.pop();
        } else {
          lastMessage.content = nonToolBlocks;
        }
      }
    }
    const response = await this.client.beta.messages.create({
      model,
      messages: [
        ...messages,
        {
          role: "user",
          content: [
            {
              type: "text",
              text: summaryPrompt
            }
          ]
        }
      ],
      max_tokens: __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.max_tokens
    }, {
      headers: { "x-stainless-helper": "compaction" }
    });
    if (response.content[0]?.type !== "text") {
      throw new AnthropicError("Expected text response for compaction");
    }
    __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages = [
      {
        role: "user",
        content: response.content
      }
    ];
    return true;
  }, Symbol.asyncIterator)]() {
    var _a7;
    if (__classPrivateFieldGet(this, _BetaToolRunner_consumed, "f")) {
      throw new AnthropicError("Cannot iterate over a consumed stream");
    }
    __classPrivateFieldSet(this, _BetaToolRunner_consumed, true, "f");
    __classPrivateFieldSet(this, _BetaToolRunner_mutated, true, "f");
    __classPrivateFieldSet(this, _BetaToolRunner_toolResponse, void 0, "f");
    try {
      while (true) {
        let stream2;
        try {
          if (__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.max_iterations && __classPrivateFieldGet(this, _BetaToolRunner_iterationCount, "f") >= __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.max_iterations) {
            break;
          }
          __classPrivateFieldSet(this, _BetaToolRunner_mutated, false, "f");
          __classPrivateFieldSet(this, _BetaToolRunner_toolResponse, void 0, "f");
          __classPrivateFieldSet(this, _BetaToolRunner_iterationCount, (_a7 = __classPrivateFieldGet(this, _BetaToolRunner_iterationCount, "f"), _a7++, _a7), "f");
          __classPrivateFieldSet(this, _BetaToolRunner_message, void 0, "f");
          const { max_iterations, compactionControl, ...params } = __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params;
          if (params.stream) {
            stream2 = this.client.beta.messages.stream({ ...params }, __classPrivateFieldGet(this, _BetaToolRunner_options, "f"));
            __classPrivateFieldSet(this, _BetaToolRunner_message, stream2.finalMessage(), "f");
            __classPrivateFieldGet(this, _BetaToolRunner_message, "f").catch(() => {
            });
            yield stream2;
          } else {
            __classPrivateFieldSet(this, _BetaToolRunner_message, this.client.beta.messages.create({ ...params, stream: false }, __classPrivateFieldGet(this, _BetaToolRunner_options, "f")), "f");
            yield __classPrivateFieldGet(this, _BetaToolRunner_message, "f");
          }
          const isCompacted = await __classPrivateFieldGet(this, _BetaToolRunner_instances, "m", _BetaToolRunner_checkAndCompact).call(this);
          if (!isCompacted) {
            if (!__classPrivateFieldGet(this, _BetaToolRunner_mutated, "f")) {
              const { role, content } = await __classPrivateFieldGet(this, _BetaToolRunner_message, "f");
              __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages.push({ role, content });
            }
            const toolMessage = await __classPrivateFieldGet(this, _BetaToolRunner_instances, "m", _BetaToolRunner_generateToolResponse).call(this, __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages.at(-1));
            if (toolMessage) {
              __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages.push(toolMessage);
            } else if (!__classPrivateFieldGet(this, _BetaToolRunner_mutated, "f")) {
              break;
            }
          }
        } finally {
          if (stream2) {
            stream2.abort();
          }
        }
      }
      if (!__classPrivateFieldGet(this, _BetaToolRunner_message, "f")) {
        throw new AnthropicError("ToolRunner concluded without a message from the server");
      }
      __classPrivateFieldGet(this, _BetaToolRunner_completion, "f").resolve(await __classPrivateFieldGet(this, _BetaToolRunner_message, "f"));
    } catch (error) {
      __classPrivateFieldSet(this, _BetaToolRunner_consumed, false, "f");
      __classPrivateFieldGet(this, _BetaToolRunner_completion, "f").promise.catch(() => {
      });
      __classPrivateFieldGet(this, _BetaToolRunner_completion, "f").reject(error);
      __classPrivateFieldSet(this, _BetaToolRunner_completion, promiseWithResolvers(), "f");
      throw error;
    }
  }
  setMessagesParams(paramsOrMutator) {
    if (typeof paramsOrMutator === "function") {
      __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params = paramsOrMutator(__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params);
    } else {
      __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params = paramsOrMutator;
    }
    __classPrivateFieldSet(this, _BetaToolRunner_mutated, true, "f");
    __classPrivateFieldSet(this, _BetaToolRunner_toolResponse, void 0, "f");
  }
  /**
   * Get the tool response for the last message from the assistant.
   * Avoids redundant tool executions by caching results.
   *
   * @returns A promise that resolves to a BetaMessageParam containing tool results, or null if no tools need to be executed
   *
   * @example
   * const toolResponse = await runner.generateToolResponse();
   * if (toolResponse) {
   *   console.log('Tool results:', toolResponse.content);
   * }
   */
  async generateToolResponse() {
    const message = await __classPrivateFieldGet(this, _BetaToolRunner_message, "f") ?? this.params.messages.at(-1);
    if (!message) {
      return null;
    }
    return __classPrivateFieldGet(this, _BetaToolRunner_instances, "m", _BetaToolRunner_generateToolResponse).call(this, message);
  }
  /**
   * Wait for the async iterator to complete. This works even if the async iterator hasn't yet started, and
   * will wait for an instance to start and go to completion.
   *
   * @returns A promise that resolves to the final BetaMessage when the iterator completes
   *
   * @example
   * // Start consuming the iterator
   * for await (const message of runner) {
   *   console.log('Message:', message.content);
   * }
   *
   * // Meanwhile, wait for completion from another part of the code
   * const finalMessage = await runner.done();
   * console.log('Final response:', finalMessage.content);
   */
  done() {
    return __classPrivateFieldGet(this, _BetaToolRunner_completion, "f").promise;
  }
  /**
   * Returns a promise indicating that the stream is done. Unlike .done(), this will eagerly read the stream:
   * * If the iterator has not been consumed, consume the entire iterator and return the final message from the
   * assistant.
   * * If the iterator has been consumed, waits for it to complete and returns the final message.
   *
   * @returns A promise that resolves to the final BetaMessage from the conversation
   * @throws {AnthropicError} If no messages were processed during the conversation
   *
   * @example
   * const finalMessage = await runner.runUntilDone();
   * console.log('Final response:', finalMessage.content);
   */
  async runUntilDone() {
    if (!__classPrivateFieldGet(this, _BetaToolRunner_consumed, "f")) {
      for await (const _3 of this) {
      }
    }
    return this.done();
  }
  /**
   * Get the current parameters being used by the ToolRunner.
   *
   * @returns A readonly view of the current ToolRunnerParams
   *
   * @example
   * const currentParams = runner.params;
   * console.log('Current model:', currentParams.model);
   * console.log('Message count:', currentParams.messages.length);
   */
  get params() {
    return __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params;
  }
  /**
   * Add one or more messages to the conversation history.
   *
   * @param messages - One or more BetaMessageParam objects to add to the conversation
   *
   * @example
   * runner.pushMessages(
   *   { role: 'user', content: 'Also, what about the weather in NYC?' }
   * );
   *
   * @example
   * // Adding multiple messages
   * runner.pushMessages(
   *   { role: 'user', content: 'What about NYC?' },
   *   { role: 'user', content: 'And Boston?' }
   * );
   */
  pushMessages(...messages) {
    this.setMessagesParams((params) => ({
      ...params,
      messages: [...params.messages, ...messages]
    }));
  }
  /**
   * Makes the ToolRunner directly awaitable, equivalent to calling .runUntilDone()
   * This allows using `await runner` instead of `await runner.runUntilDone()`
   */
  then(onfulfilled, onrejected) {
    return this.runUntilDone().then(onfulfilled, onrejected);
  }
};
_BetaToolRunner_generateToolResponse = async function _BetaToolRunner_generateToolResponse2(lastMessage) {
  if (__classPrivateFieldGet(this, _BetaToolRunner_toolResponse, "f") !== void 0) {
    return __classPrivateFieldGet(this, _BetaToolRunner_toolResponse, "f");
  }
  __classPrivateFieldSet(this, _BetaToolRunner_toolResponse, generateToolResponse(__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params, lastMessage), "f");
  return __classPrivateFieldGet(this, _BetaToolRunner_toolResponse, "f");
};
async function generateToolResponse(params, lastMessage = params.messages.at(-1)) {
  if (!lastMessage || lastMessage.role !== "assistant" || !lastMessage.content || typeof lastMessage.content === "string") {
    return null;
  }
  const toolUseBlocks = lastMessage.content.filter((content) => content.type === "tool_use");
  if (toolUseBlocks.length === 0) {
    return null;
  }
  const toolResults = await Promise.all(toolUseBlocks.map(async (toolUse) => {
    const tool = params.tools.find((t6) => ("name" in t6 ? t6.name : t6.mcp_server_name) === toolUse.name);
    if (!tool || !("run" in tool)) {
      return {
        type: "tool_result",
        tool_use_id: toolUse.id,
        content: `Error: Tool '${toolUse.name}' not found`,
        is_error: true
      };
    }
    try {
      let input = toolUse.input;
      if ("parse" in tool && tool.parse) {
        input = tool.parse(input);
      }
      const result = await tool.run(input);
      return {
        type: "tool_result",
        tool_use_id: toolUse.id,
        content: result
      };
    } catch (error) {
      return {
        type: "tool_result",
        tool_use_id: toolUse.id,
        content: error instanceof ToolError ? error.content : `Error: ${error instanceof Error ? error.message : String(error)}`,
        is_error: true
      };
    }
  }));
  return {
    role: "user",
    content: toolResults
  };
}

// ../pi-mono/node_modules/@anthropic-ai/sdk/resources/beta/messages/batches.mjs
init_process_shim();

// ../pi-mono/node_modules/@anthropic-ai/sdk/internal/decoders/jsonl.mjs
init_process_shim();
var JSONLDecoder = class _JSONLDecoder {
  constructor(iterator, controller) {
    this.iterator = iterator;
    this.controller = controller;
  }
  async *decoder() {
    const lineDecoder = new LineDecoder();
    for await (const chunk of this.iterator) {
      for (const line of lineDecoder.decode(chunk)) {
        yield JSON.parse(line);
      }
    }
    for (const line of lineDecoder.flush()) {
      yield JSON.parse(line);
    }
  }
  [Symbol.asyncIterator]() {
    return this.decoder();
  }
  static fromResponse(response, controller) {
    if (!response.body) {
      controller.abort();
      if (typeof globalThis.navigator !== "undefined" && globalThis.navigator.product === "ReactNative") {
        throw new AnthropicError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`);
      }
      throw new AnthropicError(`Attempted to iterate over a response with no body`);
    }
    return new _JSONLDecoder(ReadableStreamToAsyncIterable(response.body), controller);
  }
};

// ../pi-mono/node_modules/@anthropic-ai/sdk/resources/beta/messages/batches.mjs
var Batches = class extends APIResource {
  /**
   * Send a batch of Message creation requests.
   *
   * The Message Batches API can be used to process multiple Messages API requests at
   * once. Once a Message Batch is created, it begins processing immediately. Batches
   * can take up to 24 hours to complete.
   *
   * Learn more about the Message Batches API in our
   * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
   *
   * @example
   * ```ts
   * const betaMessageBatch =
   *   await client.beta.messages.batches.create({
   *     requests: [
   *       {
   *         custom_id: 'my-custom-id-1',
   *         params: {
   *           max_tokens: 1024,
   *           messages: [
   *             { content: 'Hello, world', role: 'user' },
   *           ],
   *           model: 'claude-opus-4-6',
   *         },
   *       },
   *     ],
   *   });
   * ```
   */
  create(params, options) {
    const { betas, ...body } = params;
    return this._client.post("/v1/messages/batches?beta=true", {
      body,
      ...options,
      headers: buildHeaders([
        { "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() },
        options?.headers
      ])
    });
  }
  /**
   * This endpoint is idempotent and can be used to poll for Message Batch
   * completion. To access the results of a Message Batch, make a request to the
   * `results_url` field in the response.
   *
   * Learn more about the Message Batches API in our
   * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
   *
   * @example
   * ```ts
   * const betaMessageBatch =
   *   await client.beta.messages.batches.retrieve(
   *     'message_batch_id',
   *   );
   * ```
   */
  retrieve(messageBatchID, params = {}, options) {
    const { betas } = params ?? {};
    return this._client.get(path`/v1/messages/batches/${messageBatchID}?beta=true`, {
      ...options,
      headers: buildHeaders([
        { "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() },
        options?.headers
      ])
    });
  }
  /**
   * List all Message Batches within a Workspace. Most recently created batches are
   * returned first.
   *
   * Learn more about the Message Batches API in our
   * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
   *
   * @example
   * ```ts
   * // Automatically fetches more pages as needed.
   * for await (const betaMessageBatch of client.beta.messages.batches.list()) {
   *   // ...
   * }
   * ```
   */
  list(params = {}, options) {
    const { betas, ...query } = params ?? {};
    return this._client.getAPIList("/v1/messages/batches?beta=true", Page, {
      query,
      ...options,
      headers: buildHeaders([
        { "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() },
        options?.headers
      ])
    });
  }
  /**
   * Delete a Message Batch.
   *
   * Message Batches can only be deleted once they've finished processing. If you'd
   * like to delete an in-progress batch, you must first cancel it.
   *
   * Learn more about the Message Batches API in our
   * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
   *
   * @example
   * ```ts
   * const betaDeletedMessageBatch =
   *   await client.beta.messages.batches.delete(
   *     'message_batch_id',
   *   );
   * ```
   */
  delete(messageBatchID, params = {}, options) {
    const { betas } = params ?? {};
    return this._client.delete(path`/v1/messages/batches/${messageBatchID}?beta=true`, {
      ...options,
      headers: buildHeaders([
        { "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() },
        options?.headers
      ])
    });
  }
  /**
   * Batches may be canceled any time before processing ends. Once cancellation is
   * initiated, the batch enters a `canceling` state, at which time the system may
   * complete any in-progress, non-interruptible requests before finalizing
   * cancellation.
   *
   * The number of canceled requests is specified in `request_counts`. To determine
   * which requests were canceled, check the individual results within the batch.
   * Note that cancellation may not result in any canceled requests if they were
   * non-interruptible.
   *
   * Learn more about the Message Batches API in our
   * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
   *
   * @example
   * ```ts
   * const betaMessageBatch =
   *   await client.beta.messages.batches.cancel(
   *     'message_batch_id',
   *   );
   * ```
   */
  cancel(messageBatchID, params = {}, options) {
    const { betas } = params ?? {};
    return this._client.post(path`/v1/messages/batches/${messageBatchID}/cancel?beta=true`, {
      ...options,
      headers: buildHeaders([
        { "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() },
        options?.headers
      ])
    });
  }
  /**
   * Streams the results of a Message Batch as a `.jsonl` file.
   *
   * Each line in the file is a JSON object containing the result of a single request
   * in the Message Batch. Results are not guaranteed to be in the same order as
   * requests. Use the `custom_id` field to match results to requests.
   *
   * Learn more about the Message Batches API in our
   * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
   *
   * @example
   * ```ts
   * const betaMessageBatchIndividualResponse =
   *   await client.beta.messages.batches.results(
   *     'message_batch_id',
   *   );
   * ```
   */
  async results(messageBatchID, params = {}, options) {
    const batch = await this.retrieve(messageBatchID);
    if (!batch.results_url) {
      throw new AnthropicError(`No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`);
    }
    const { betas } = params ?? {};
    return this._client.get(batch.results_url, {
      ...options,
      headers: buildHeaders([
        {
          "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString(),
          Accept: "application/binary"
        },
        options?.headers
      ]),
      stream: true,
      __binaryResponse: true
    })._thenUnwrap((_3, props) => JSONLDecoder.fromResponse(props.response, props.controller));
  }
};

// ../pi-mono/node_modules/@anthropic-ai/sdk/resources/beta/messages/messages.mjs
var DEPRECATED_MODELS = {
  "claude-1.3": "November 6th, 2024",
  "claude-1.3-100k": "November 6th, 2024",
  "claude-instant-1.1": "November 6th, 2024",
  "claude-instant-1.1-100k": "November 6th, 2024",
  "claude-instant-1.2": "November 6th, 2024",
  "claude-3-sonnet-20240229": "July 21st, 2025",
  "claude-3-opus-20240229": "January 5th, 2026",
  "claude-2.1": "July 21st, 2025",
  "claude-2.0": "July 21st, 2025",
  "claude-3-7-sonnet-latest": "February 19th, 2026",
  "claude-3-7-sonnet-20250219": "February 19th, 2026"
};
var MODELS_TO_WARN_WITH_THINKING_ENABLED = ["claude-opus-4-6"];
var Messages = class extends APIResource {
  constructor() {
    super(...arguments);
    this.batches = new Batches(this._client);
  }
  create(params, options) {
    const modifiedParams = transformOutputFormat(params);
    const { betas, ...body } = modifiedParams;
    if (body.model in DEPRECATED_MODELS) {
      console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${DEPRECATED_MODELS[body.model]}
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);
    }
    if (body.model in MODELS_TO_WARN_WITH_THINKING_ENABLED && body.thinking && body.thinking.type === "enabled") {
      console.warn(`Using Claude with ${body.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);
    }
    let timeout = this._client._options.timeout;
    if (!body.stream && timeout == null) {
      const maxNonstreamingTokens = MODEL_NONSTREAMING_TOKENS[body.model] ?? void 0;
      timeout = this._client.calculateNonstreamingTimeout(body.max_tokens, maxNonstreamingTokens);
    }
    const helperHeader = stainlessHelperHeader(body.tools, body.messages);
    return this._client.post("/v1/messages?beta=true", {
      body,
      timeout: timeout ?? 6e5,
      ...options,
      headers: buildHeaders([
        { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 },
        helperHeader,
        options?.headers
      ]),
      stream: modifiedParams.stream ?? false
    });
  }
  /**
   * Send a structured list of input messages with text and/or image content, along with an expected `output_format` and
   * the response will be automatically parsed and available in the `parsed_output` property of the message.
   *
   * @example
   * ```ts
   * const message = await client.beta.messages.parse({
   *   model: 'claude-3-5-sonnet-20241022',
   *   max_tokens: 1024,
   *   messages: [{ role: 'user', content: 'What is 2+2?' }],
   *   output_format: zodOutputFormat(z.object({ answer: z.number() }), 'math'),
   * });
   *
   * console.log(message.parsed_output?.answer); // 4
   * ```
   */
  parse(params, options) {
    options = {
      ...options,
      headers: buildHeaders([
        { "anthropic-beta": [...params.betas ?? [], "structured-outputs-2025-12-15"].toString() },
        options?.headers
      ])
    };
    return this.create(params, options).then((message) => parseBetaMessage(message, params, { logger: this._client.logger ?? console }));
  }
  /**
   * Create a Message stream
   */
  stream(body, options) {
    return BetaMessageStream.createMessage(this, body, options);
  }
  /**
   * Count the number of tokens in a Message.
   *
   * The Token Count API can be used to count the number of tokens in a Message,
   * including tools, images, and documents, without creating it.
   *
   * Learn more about token counting in our
   * [user guide](https://docs.claude.com/en/docs/build-with-claude/token-counting)
   *
   * @example
   * ```ts
   * const betaMessageTokensCount =
   *   await client.beta.messages.countTokens({
   *     messages: [{ content: 'string', role: 'user' }],
   *     model: 'claude-opus-4-6',
   *   });
   * ```
   */
  countTokens(params, options) {
    const modifiedParams = transformOutputFormat(params);
    const { betas, ...body } = modifiedParams;
    return this._client.post("/v1/messages/count_tokens?beta=true", {
      body,
      ...options,
      headers: buildHeaders([
        { "anthropic-beta": [...betas ?? [], "token-counting-2024-11-01"].toString() },
        options?.headers
      ])
    });
  }
  toolRunner(body, options) {
    return new BetaToolRunner(this._client, body, options);
  }
};
function transformOutputFormat(params) {
  if (!params.output_format) {
    return params;
  }
  if (params.output_config?.format) {
    throw new AnthropicError("Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).");
  }
  const { output_format, ...rest } = params;
  return {
    ...rest,
    output_config: {
      ...params.output_config,
      format: output_format
    }
  };
}
Messages.Batches = Batches;
Messages.BetaToolRunner = BetaToolRunner;
Messages.ToolError = ToolError;

// ../pi-mono/node_modules/@anthropic-ai/sdk/resources/beta/skills/skills.mjs
init_process_shim();

// ../pi-mono/node_modules/@anthropic-ai/sdk/resources/beta/skills/versions.mjs
init_process_shim();
var Versions = class extends APIResource {
  /**
   * Create Skill Version
   *
   * @example
   * ```ts
   * const version = await client.beta.skills.versions.create(
   *   'skill_id',
   * );
   * ```
   */
  create(skillID, params = {}, options) {
    const { betas, ...body } = params ?? {};
    return this._client.post(path`/v1/skills/${skillID}/versions?beta=true`, multipartFormRequestOptions({
      body,
      ...options,
      headers: buildHeaders([
        { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() },
        options?.headers
      ])
    }, this._client));
  }
  /**
   * Get Skill Version
   *
   * @example
   * ```ts
   * const version = await client.beta.skills.versions.retrieve(
   *   'version',
   *   { skill_id: 'skill_id' },
   * );
   * ```
   */
  retrieve(version5, params, options) {
    const { skill_id, betas } = params;
    return this._client.get(path`/v1/skills/${skill_id}/versions/${version5}?beta=true`, {
      ...options,
      headers: buildHeaders([
        { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() },
        options?.headers
      ])
    });
  }
  /**
   * List Skill Versions
   *
   * @example
   * ```ts
   * // Automatically fetches more pages as needed.
   * for await (const versionListResponse of client.beta.skills.versions.list(
   *   'skill_id',
   * )) {
   *   // ...
   * }
   * ```
   */
  list(skillID, params = {}, options) {
    const { betas, ...query } = params ?? {};
    return this._client.getAPIList(path`/v1/skills/${skillID}/versions?beta=true`, PageCursor, {
      query,
      ...options,
      headers: buildHeaders([
        { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() },
        options?.headers
      ])
    });
  }
  /**
   * Delete Skill Version
   *
   * @example
   * ```ts
   * const version = await client.beta.skills.versions.delete(
   *   'version',
   *   { skill_id: 'skill_id' },
   * );
   * ```
   */
  delete(version5, params, options) {
    const { skill_id, betas } = params;
    return this._client.delete(path`/v1/skills/${skill_id}/versions/${version5}?beta=true`, {
      ...options,
      headers: buildHeaders([
        { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() },
        options?.headers
      ])
    });
  }
};

// ../pi-mono/node_modules/@anthropic-ai/sdk/resources/beta/skills/skills.mjs
var Skills = class extends APIResource {
  constructor() {
    super(...arguments);
    this.versions = new Versions(this._client);
  }
  /**
   * Create Skill
   *
   * @example
   * ```ts
   * const skill = await client.beta.skills.create();
   * ```
   */
  create(params = {}, options) {
    const { betas, ...body } = params ?? {};
    return this._client.post("/v1/skills?beta=true", multipartFormRequestOptions({
      body,
      ...options,
      headers: buildHeaders([
        { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() },
        options?.headers
      ])
    }, this._client, false));
  }
  /**
   * Get Skill
   *
   * @example
   * ```ts
   * const skill = await client.beta.skills.retrieve('skill_id');
   * ```
   */
  retrieve(skillID, params = {}, options) {
    const { betas } = params ?? {};
    return this._client.get(path`/v1/skills/${skillID}?beta=true`, {
      ...options,
      headers: buildHeaders([
        { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() },
        options?.headers
      ])
    });
  }
  /**
   * List Skills
   *
   * @example
   * ```ts
   * // Automatically fetches more pages as needed.
   * for await (const skillListResponse of client.beta.skills.list()) {
   *   // ...
   * }
   * ```
   */
  list(params = {}, options) {
    const { betas, ...query } = params ?? {};
    return this._client.getAPIList("/v1/skills?beta=true", PageCursor, {
      query,
      ...options,
      headers: buildHeaders([
        { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() },
        options?.headers
      ])
    });
  }
  /**
   * Delete Skill
   *
   * @example
   * ```ts
   * const skill = await client.beta.skills.delete('skill_id');
   * ```
   */
  delete(skillID, params = {}, options) {
    const { betas } = params ?? {};
    return this._client.delete(path`/v1/skills/${skillID}?beta=true`, {
      ...options,
      headers: buildHeaders([
        { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() },
        options?.headers
      ])
    });
  }
};
Skills.Versions = Versions;

// ../pi-mono/node_modules/@anthropic-ai/sdk/resources/beta/beta.mjs
var Beta = class extends APIResource {
  constructor() {
    super(...arguments);
    this.models = new Models(this._client);
    this.messages = new Messages(this._client);
    this.files = new Files(this._client);
    this.skills = new Skills(this._client);
  }
};
Beta.Models = Models;
Beta.Messages = Messages;
Beta.Files = Files;
Beta.Skills = Skills;

// ../pi-mono/node_modules/@anthropic-ai/sdk/resources/completions.mjs
init_process_shim();
var Completions = class extends APIResource {
  create(params, options) {
    const { betas, ...body } = params;
    return this._client.post("/v1/complete", {
      body,
      timeout: this._client._options.timeout ?? 6e5,
      ...options,
      headers: buildHeaders([
        { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 },
        options?.headers
      ]),
      stream: params.stream ?? false
    });
  }
};

// ../pi-mono/node_modules/@anthropic-ai/sdk/resources/messages/messages.mjs
init_process_shim();

// ../pi-mono/node_modules/@anthropic-ai/sdk/lib/MessageStream.mjs
init_process_shim();

// ../pi-mono/node_modules/@anthropic-ai/sdk/lib/parser.mjs
init_process_shim();
function getOutputFormat2(params) {
  return params?.output_config?.format;
}
function maybeParseMessage(message, params, opts) {
  const outputFormat = getOutputFormat2(params);
  if (!params || !("parse" in (outputFormat ?? {}))) {
    return {
      ...message,
      content: message.content.map((block) => {
        if (block.type === "text") {
          const parsedBlock = Object.defineProperty({ ...block }, "parsed_output", {
            value: null,
            enumerable: false
          });
          return parsedBlock;
        }
        return block;
      }),
      parsed_output: null
    };
  }
  return parseMessage(message, params, opts);
}
function parseMessage(message, params, opts) {
  let firstParsedOutput = null;
  const content = message.content.map((block) => {
    if (block.type === "text") {
      const parsedOutput = parseOutputFormat(params, block.text);
      if (firstParsedOutput === null) {
        firstParsedOutput = parsedOutput;
      }
      const parsedBlock = Object.defineProperty({ ...block }, "parsed_output", {
        value: parsedOutput,
        enumerable: false
      });
      return parsedBlock;
    }
    return block;
  });
  return {
    ...message,
    content,
    parsed_output: firstParsedOutput
  };
}
function parseOutputFormat(params, content) {
  const outputFormat = getOutputFormat2(params);
  if (outputFormat?.type !== "json_schema") {
    return null;
  }
  try {
    if ("parse" in outputFormat) {
      return outputFormat.parse(content);
    }
    return JSON.parse(content);
  } catch (error) {
    throw new AnthropicError(`Failed to parse structured output: ${error}`);
  }
}

// ../pi-mono/node_modules/@anthropic-ai/sdk/lib/MessageStream.mjs
var _MessageStream_instances;
var _MessageStream_currentMessageSnapshot;
var _MessageStream_params;
var _MessageStream_connectedPromise;
var _MessageStream_resolveConnectedPromise;
var _MessageStream_rejectConnectedPromise;
var _MessageStream_endPromise;
var _MessageStream_resolveEndPromise;
var _MessageStream_rejectEndPromise;
var _MessageStream_listeners;
var _MessageStream_ended;
var _MessageStream_errored;
var _MessageStream_aborted;
var _MessageStream_catchingPromiseCreated;
var _MessageStream_response;
var _MessageStream_request_id;
var _MessageStream_logger;
var _MessageStream_getFinalMessage;
var _MessageStream_getFinalText;
var _MessageStream_handleError;
var _MessageStream_beginRequest;
var _MessageStream_addStreamEvent;
var _MessageStream_endRequest;
var _MessageStream_accumulateMessage;
var JSON_BUF_PROPERTY2 = "__json_buf";
function tracksToolInput2(content) {
  return content.type === "tool_use" || content.type === "server_tool_use";
}
var MessageStream = class _MessageStream {
  constructor(params, opts) {
    _MessageStream_instances.add(this);
    this.messages = [];
    this.receivedMessages = [];
    _MessageStream_currentMessageSnapshot.set(this, void 0);
    _MessageStream_params.set(this, null);
    this.controller = new AbortController();
    _MessageStream_connectedPromise.set(this, void 0);
    _MessageStream_resolveConnectedPromise.set(this, () => {
    });
    _MessageStream_rejectConnectedPromise.set(this, () => {
    });
    _MessageStream_endPromise.set(this, void 0);
    _MessageStream_resolveEndPromise.set(this, () => {
    });
    _MessageStream_rejectEndPromise.set(this, () => {
    });
    _MessageStream_listeners.set(this, {});
    _MessageStream_ended.set(this, false);
    _MessageStream_errored.set(this, false);
    _MessageStream_aborted.set(this, false);
    _MessageStream_catchingPromiseCreated.set(this, false);
    _MessageStream_response.set(this, void 0);
    _MessageStream_request_id.set(this, void 0);
    _MessageStream_logger.set(this, void 0);
    _MessageStream_handleError.set(this, (error) => {
      __classPrivateFieldSet(this, _MessageStream_errored, true, "f");
      if (isAbortError(error)) {
        error = new APIUserAbortError();
      }
      if (error instanceof APIUserAbortError) {
        __classPrivateFieldSet(this, _MessageStream_aborted, true, "f");
        return this._emit("abort", error);
      }
      if (error instanceof AnthropicError) {
        return this._emit("error", error);
      }
      if (error instanceof Error) {
        const anthropicError = new AnthropicError(error.message);
        anthropicError.cause = error;
        return this._emit("error", anthropicError);
      }
      return this._emit("error", new AnthropicError(String(error)));
    });
    __classPrivateFieldSet(this, _MessageStream_connectedPromise, new Promise((resolve, reject) => {
      __classPrivateFieldSet(this, _MessageStream_resolveConnectedPromise, resolve, "f");
      __classPrivateFieldSet(this, _MessageStream_rejectConnectedPromise, reject, "f");
    }), "f");
    __classPrivateFieldSet(this, _MessageStream_endPromise, new Promise((resolve, reject) => {
      __classPrivateFieldSet(this, _MessageStream_resolveEndPromise, resolve, "f");
      __classPrivateFieldSet(this, _MessageStream_rejectEndPromise, reject, "f");
    }), "f");
    __classPrivateFieldGet(this, _MessageStream_connectedPromise, "f").catch(() => {
    });
    __classPrivateFieldGet(this, _MessageStream_endPromise, "f").catch(() => {
    });
    __classPrivateFieldSet(this, _MessageStream_params, params, "f");
    __classPrivateFieldSet(this, _MessageStream_logger, opts?.logger ?? console, "f");
  }
  get response() {
    return __classPrivateFieldGet(this, _MessageStream_response, "f");
  }
  get request_id() {
    return __classPrivateFieldGet(this, _MessageStream_request_id, "f");
  }
  /**
   * Returns the `MessageStream` data, the raw `Response` instance and the ID of the request,
   * returned vie the `request-id` header which is useful for debugging requests and resporting
   * issues to Anthropic.
   *
   * This is the same as the `APIPromise.withResponse()` method.
   *
   * This method will raise an error if you created the stream using `MessageStream.fromReadableStream`
   * as no `Response` is available.
   */
  async withResponse() {
    __classPrivateFieldSet(this, _MessageStream_catchingPromiseCreated, true, "f");
    const response = await __classPrivateFieldGet(this, _MessageStream_connectedPromise, "f");
    if (!response) {
      throw new Error("Could not resolve a `Response` object");
    }
    return {
      data: this,
      response,
      request_id: response.headers.get("request-id")
    };
  }
  /**
   * Intended for use on the frontend, consuming a stream produced with
   * `.toReadableStream()` on the backend.
   *
   * Note that messages sent to the model do not appear in `.on('message')`
   * in this context.
   */
  static fromReadableStream(stream2) {
    const runner = new _MessageStream(null);
    runner._run(() => runner._fromReadableStream(stream2));
    return runner;
  }
  static createMessage(messages, params, options, { logger: logger2 } = {}) {
    const runner = new _MessageStream(params, { logger: logger2 });
    for (const message of params.messages) {
      runner._addMessageParam(message);
    }
    __classPrivateFieldSet(runner, _MessageStream_params, { ...params, stream: true }, "f");
    runner._run(() => runner._createMessage(messages, { ...params, stream: true }, { ...options, headers: { ...options?.headers, "X-Stainless-Helper-Method": "stream" } }));
    return runner;
  }
  _run(executor) {
    executor().then(() => {
      this._emitFinal();
      this._emit("end");
    }, __classPrivateFieldGet(this, _MessageStream_handleError, "f"));
  }
  _addMessageParam(message) {
    this.messages.push(message);
  }
  _addMessage(message, emit = true) {
    this.receivedMessages.push(message);
    if (emit) {
      this._emit("message", message);
    }
  }
  async _createMessage(messages, params, options) {
    const signal = options?.signal;
    let abortHandler;
    if (signal) {
      if (signal.aborted)
        this.controller.abort();
      abortHandler = this.controller.abort.bind(this.controller);
      signal.addEventListener("abort", abortHandler);
    }
    try {
      __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this);
      const { response, data: stream2 } = await messages.create({ ...params, stream: true }, { ...options, signal: this.controller.signal }).withResponse();
      this._connected(response);
      for await (const event of stream2) {
        __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event);
      }
      if (stream2.controller.signal?.aborted) {
        throw new APIUserAbortError();
      }
      __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this);
    } finally {
      if (signal && abortHandler) {
        signal.removeEventListener("abort", abortHandler);
      }
    }
  }
  _connected(response) {
    if (this.ended)
      return;
    __classPrivateFieldSet(this, _MessageStream_response, response, "f");
    __classPrivateFieldSet(this, _MessageStream_request_id, response?.headers.get("request-id"), "f");
    __classPrivateFieldGet(this, _MessageStream_resolveConnectedPromise, "f").call(this, response);
    this._emit("connect");
  }
  get ended() {
    return __classPrivateFieldGet(this, _MessageStream_ended, "f");
  }
  get errored() {
    return __classPrivateFieldGet(this, _MessageStream_errored, "f");
  }
  get aborted() {
    return __classPrivateFieldGet(this, _MessageStream_aborted, "f");
  }
  abort() {
    this.controller.abort();
  }
  /**
   * Adds the listener function to the end of the listeners array for the event.
   * No checks are made to see if the listener has already been added. Multiple calls passing
   * the same combination of event and listener will result in the listener being added, and
   * called, multiple times.
   * @returns this MessageStream, so that calls can be chained
   */
  on(event, listener) {
    const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] = []);
    listeners.push({ listener });
    return this;
  }
  /**
   * Removes the specified listener from the listener array for the event.
   * off() will remove, at most, one instance of a listener from the listener array. If any single
   * listener has been added multiple times to the listener array for the specified event, then
   * off() must be called multiple times to remove each instance.
   * @returns this MessageStream, so that calls can be chained
   */
  off(event, listener) {
    const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event];
    if (!listeners)
      return this;
    const index = listeners.findIndex((l5) => l5.listener === listener);
    if (index >= 0)
      listeners.splice(index, 1);
    return this;
  }
  /**
   * Adds a one-time listener function for the event. The next time the event is triggered,
   * this listener is removed and then invoked.
   * @returns this MessageStream, so that calls can be chained
   */
  once(event, listener) {
    const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] = []);
    listeners.push({ listener, once: true });
    return this;
  }
  /**
   * This is similar to `.once()`, but returns a Promise that resolves the next time
   * the event is triggered, instead of calling a listener callback.
   * @returns a Promise that resolves the next time given event is triggered,
   * or rejects if an error is emitted.  (If you request the 'error' event,
   * returns a promise that resolves with the error).
   *
   * Example:
   *
   *   const message = await stream.emitted('message') // rejects if the stream errors
   */
  emitted(event) {
    return new Promise((resolve, reject) => {
      __classPrivateFieldSet(this, _MessageStream_catchingPromiseCreated, true, "f");
      if (event !== "error")
        this.once("error", reject);
      this.once(event, resolve);
    });
  }
  async done() {
    __classPrivateFieldSet(this, _MessageStream_catchingPromiseCreated, true, "f");
    await __classPrivateFieldGet(this, _MessageStream_endPromise, "f");
  }
  get currentMessage() {
    return __classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, "f");
  }
  /**
   * @returns a promise that resolves with the the final assistant Message response,
   * or rejects if an error occurred or the stream ended prematurely without producing a Message.
   * If structured outputs were used, this will be a ParsedMessage with a `parsed_output` field.
   */
  async finalMessage() {
    await this.done();
    return __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_getFinalMessage).call(this);
  }
  /**
   * @returns a promise that resolves with the the final assistant Message's text response, concatenated
   * together if there are more than one text blocks.
   * Rejects if an error occurred or the stream ended prematurely without producing a Message.
   */
  async finalText() {
    await this.done();
    return __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_getFinalText).call(this);
  }
  _emit(event, ...args) {
    if (__classPrivateFieldGet(this, _MessageStream_ended, "f"))
      return;
    if (event === "end") {
      __classPrivateFieldSet(this, _MessageStream_ended, true, "f");
      __classPrivateFieldGet(this, _MessageStream_resolveEndPromise, "f").call(this);
    }
    const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event];
    if (listeners) {
      __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] = listeners.filter((l5) => !l5.once);
      listeners.forEach(({ listener }) => listener(...args));
    }
    if (event === "abort") {
      const error = args[0];
      if (!__classPrivateFieldGet(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
        Promise.reject(error);
      }
      __classPrivateFieldGet(this, _MessageStream_rejectConnectedPromise, "f").call(this, error);
      __classPrivateFieldGet(this, _MessageStream_rejectEndPromise, "f").call(this, error);
      this._emit("end");
      return;
    }
    if (event === "error") {
      const error = args[0];
      if (!__classPrivateFieldGet(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
        Promise.reject(error);
      }
      __classPrivateFieldGet(this, _MessageStream_rejectConnectedPromise, "f").call(this, error);
      __classPrivateFieldGet(this, _MessageStream_rejectEndPromise, "f").call(this, error);
      this._emit("end");
    }
  }
  _emitFinal() {
    const finalMessage = this.receivedMessages.at(-1);
    if (finalMessage) {
      this._emit("finalMessage", __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_getFinalMessage).call(this));
    }
  }
  async _fromReadableStream(readableStream, options) {
    const signal = options?.signal;
    let abortHandler;
    if (signal) {
      if (signal.aborted)
        this.controller.abort();
      abortHandler = this.controller.abort.bind(this.controller);
      signal.addEventListener("abort", abortHandler);
    }
    try {
      __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this);
      this._connected(null);
      const stream2 = Stream.fromReadableStream(readableStream, this.controller);
      for await (const event of stream2) {
        __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event);
      }
      if (stream2.controller.signal?.aborted) {
        throw new APIUserAbortError();
      }
      __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this);
    } finally {
      if (signal && abortHandler) {
        signal.removeEventListener("abort", abortHandler);
      }
    }
  }
  [(_MessageStream_currentMessageSnapshot = /* @__PURE__ */ new WeakMap(), _MessageStream_params = /* @__PURE__ */ new WeakMap(), _MessageStream_connectedPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_resolveConnectedPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_rejectConnectedPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_endPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_resolveEndPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_rejectEndPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_listeners = /* @__PURE__ */ new WeakMap(), _MessageStream_ended = /* @__PURE__ */ new WeakMap(), _MessageStream_errored = /* @__PURE__ */ new WeakMap(), _MessageStream_aborted = /* @__PURE__ */ new WeakMap(), _MessageStream_catchingPromiseCreated = /* @__PURE__ */ new WeakMap(), _MessageStream_response = /* @__PURE__ */ new WeakMap(), _MessageStream_request_id = /* @__PURE__ */ new WeakMap(), _MessageStream_logger = /* @__PURE__ */ new WeakMap(), _MessageStream_handleError = /* @__PURE__ */ new WeakMap(), _MessageStream_instances = /* @__PURE__ */ new WeakSet(), _MessageStream_getFinalMessage = function _MessageStream_getFinalMessage2() {
    if (this.receivedMessages.length === 0) {
      throw new AnthropicError("stream ended without producing a Message with role=assistant");
    }
    return this.receivedMessages.at(-1);
  }, _MessageStream_getFinalText = function _MessageStream_getFinalText2() {
    if (this.receivedMessages.length === 0) {
      throw new AnthropicError("stream ended without producing a Message with role=assistant");
    }
    const textBlocks = this.receivedMessages.at(-1).content.filter((block) => block.type === "text").map((block) => block.text);
    if (textBlocks.length === 0) {
      throw new AnthropicError("stream ended without producing a content block with type=text");
    }
    return textBlocks.join(" ");
  }, _MessageStream_beginRequest = function _MessageStream_beginRequest2() {
    if (this.ended)
      return;
    __classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, void 0, "f");
  }, _MessageStream_addStreamEvent = function _MessageStream_addStreamEvent2(event) {
    if (this.ended)
      return;
    const messageSnapshot = __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_accumulateMessage).call(this, event);
    this._emit("streamEvent", event, messageSnapshot);
    switch (event.type) {
      case "content_block_delta": {
        const content = messageSnapshot.content.at(-1);
        switch (event.delta.type) {
          case "text_delta": {
            if (content.type === "text") {
              this._emit("text", event.delta.text, content.text || "");
            }
            break;
          }
          case "citations_delta": {
            if (content.type === "text") {
              this._emit("citation", event.delta.citation, content.citations ?? []);
            }
            break;
          }
          case "input_json_delta": {
            if (tracksToolInput2(content) && content.input) {
              this._emit("inputJson", event.delta.partial_json, content.input);
            }
            break;
          }
          case "thinking_delta": {
            if (content.type === "thinking") {
              this._emit("thinking", event.delta.thinking, content.thinking);
            }
            break;
          }
          case "signature_delta": {
            if (content.type === "thinking") {
              this._emit("signature", content.signature);
            }
            break;
          }
          default:
            checkNever2(event.delta);
        }
        break;
      }
      case "message_stop": {
        this._addMessageParam(messageSnapshot);
        this._addMessage(maybeParseMessage(messageSnapshot, __classPrivateFieldGet(this, _MessageStream_params, "f"), { logger: __classPrivateFieldGet(this, _MessageStream_logger, "f") }), true);
        break;
      }
      case "content_block_stop": {
        this._emit("contentBlock", messageSnapshot.content.at(-1));
        break;
      }
      case "message_start": {
        __classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, messageSnapshot, "f");
        break;
      }
      case "content_block_start":
      case "message_delta":
        break;
    }
  }, _MessageStream_endRequest = function _MessageStream_endRequest2() {
    if (this.ended) {
      throw new AnthropicError(`stream has ended, this shouldn't happen`);
    }
    const snapshot = __classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, "f");
    if (!snapshot) {
      throw new AnthropicError(`request ended without sending any chunks`);
    }
    __classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, void 0, "f");
    return maybeParseMessage(snapshot, __classPrivateFieldGet(this, _MessageStream_params, "f"), { logger: __classPrivateFieldGet(this, _MessageStream_logger, "f") });
  }, _MessageStream_accumulateMessage = function _MessageStream_accumulateMessage2(event) {
    let snapshot = __classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, "f");
    if (event.type === "message_start") {
      if (snapshot) {
        throw new AnthropicError(`Unexpected event order, got ${event.type} before receiving "message_stop"`);
      }
      return event.message;
    }
    if (!snapshot) {
      throw new AnthropicError(`Unexpected event order, got ${event.type} before "message_start"`);
    }
    switch (event.type) {
      case "message_stop":
        return snapshot;
      case "message_delta":
        snapshot.stop_reason = event.delta.stop_reason;
        snapshot.stop_sequence = event.delta.stop_sequence;
        snapshot.usage.output_tokens = event.usage.output_tokens;
        if (event.usage.input_tokens != null) {
          snapshot.usage.input_tokens = event.usage.input_tokens;
        }
        if (event.usage.cache_creation_input_tokens != null) {
          snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens;
        }
        if (event.usage.cache_read_input_tokens != null) {
          snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens;
        }
        if (event.usage.server_tool_use != null) {
          snapshot.usage.server_tool_use = event.usage.server_tool_use;
        }
        return snapshot;
      case "content_block_start":
        snapshot.content.push({ ...event.content_block });
        return snapshot;
      case "content_block_delta": {
        const snapshotContent = snapshot.content.at(event.index);
        switch (event.delta.type) {
          case "text_delta": {
            if (snapshotContent?.type === "text") {
              snapshot.content[event.index] = {
                ...snapshotContent,
                text: (snapshotContent.text || "") + event.delta.text
              };
            }
            break;
          }
          case "citations_delta": {
            if (snapshotContent?.type === "text") {
              snapshot.content[event.index] = {
                ...snapshotContent,
                citations: [...snapshotContent.citations ?? [], event.delta.citation]
              };
            }
            break;
          }
          case "input_json_delta": {
            if (snapshotContent && tracksToolInput2(snapshotContent)) {
              let jsonBuf = snapshotContent[JSON_BUF_PROPERTY2] || "";
              jsonBuf += event.delta.partial_json;
              const newContent = { ...snapshotContent };
              Object.defineProperty(newContent, JSON_BUF_PROPERTY2, {
                value: jsonBuf,
                enumerable: false,
                writable: true
              });
              if (jsonBuf) {
                newContent.input = partialParse(jsonBuf);
              }
              snapshot.content[event.index] = newContent;
            }
            break;
          }
          case "thinking_delta": {
            if (snapshotContent?.type === "thinking") {
              snapshot.content[event.index] = {
                ...snapshotContent,
                thinking: snapshotContent.thinking + event.delta.thinking
              };
            }
            break;
          }
          case "signature_delta": {
            if (snapshotContent?.type === "thinking") {
              snapshot.content[event.index] = {
                ...snapshotContent,
                signature: event.delta.signature
              };
            }
            break;
          }
          default:
            checkNever2(event.delta);
        }
        return snapshot;
      }
      case "content_block_stop":
        return snapshot;
    }
  }, Symbol.asyncIterator)]() {
    const pushQueue = [];
    const readQueue = [];
    let done = false;
    this.on("streamEvent", (event) => {
      const reader = readQueue.shift();
      if (reader) {
        reader.resolve(event);
      } else {
        pushQueue.push(event);
      }
    });
    this.on("end", () => {
      done = true;
      for (const reader of readQueue) {
        reader.resolve(void 0);
      }
      readQueue.length = 0;
    });
    this.on("abort", (err) => {
      done = true;
      for (const reader of readQueue) {
        reader.reject(err);
      }
      readQueue.length = 0;
    });
    this.on("error", (err) => {
      done = true;
      for (const reader of readQueue) {
        reader.reject(err);
      }
      readQueue.length = 0;
    });
    return {
      next: async () => {
        if (!pushQueue.length) {
          if (done) {
            return { value: void 0, done: true };
          }
          return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: void 0, done: true });
        }
        const chunk = pushQueue.shift();
        return { value: chunk, done: false };
      },
      return: async () => {
        this.abort();
        return { value: void 0, done: true };
      }
    };
  }
  toReadableStream() {
    const stream2 = new Stream(this[Symbol.asyncIterator].bind(this), this.controller);
    return stream2.toReadableStream();
  }
};
function checkNever2(x2) {
}

// ../pi-mono/node_modules/@anthropic-ai/sdk/resources/messages/batches.mjs
init_process_shim();
var Batches2 = class extends APIResource {
  /**
   * Send a batch of Message creation requests.
   *
   * The Message Batches API can be used to process multiple Messages API requests at
   * once. Once a Message Batch is created, it begins processing immediately. Batches
   * can take up to 24 hours to complete.
   *
   * Learn more about the Message Batches API in our
   * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
   *
   * @example
   * ```ts
   * const messageBatch = await client.messages.batches.create({
   *   requests: [
   *     {
   *       custom_id: 'my-custom-id-1',
   *       params: {
   *         max_tokens: 1024,
   *         messages: [
   *           { content: 'Hello, world', role: 'user' },
   *         ],
   *         model: 'claude-opus-4-6',
   *       },
   *     },
   *   ],
   * });
   * ```
   */
  create(body, options) {
    return this._client.post("/v1/messages/batches", { body, ...options });
  }
  /**
   * This endpoint is idempotent and can be used to poll for Message Batch
   * completion. To access the results of a Message Batch, make a request to the
   * `results_url` field in the response.
   *
   * Learn more about the Message Batches API in our
   * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
   *
   * @example
   * ```ts
   * const messageBatch = await client.messages.batches.retrieve(
   *   'message_batch_id',
   * );
   * ```
   */
  retrieve(messageBatchID, options) {
    return this._client.get(path`/v1/messages/batches/${messageBatchID}`, options);
  }
  /**
   * List all Message Batches within a Workspace. Most recently created batches are
   * returned first.
   *
   * Learn more about the Message Batches API in our
   * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
   *
   * @example
   * ```ts
   * // Automatically fetches more pages as needed.
   * for await (const messageBatch of client.messages.batches.list()) {
   *   // ...
   * }
   * ```
   */
  list(query = {}, options) {
    return this._client.getAPIList("/v1/messages/batches", Page, { query, ...options });
  }
  /**
   * Delete a Message Batch.
   *
   * Message Batches can only be deleted once they've finished processing. If you'd
   * like to delete an in-progress batch, you must first cancel it.
   *
   * Learn more about the Message Batches API in our
   * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
   *
   * @example
   * ```ts
   * const deletedMessageBatch =
   *   await client.messages.batches.delete('message_batch_id');
   * ```
   */
  delete(messageBatchID, options) {
    return this._client.delete(path`/v1/messages/batches/${messageBatchID}`, options);
  }
  /**
   * Batches may be canceled any time before processing ends. Once cancellation is
   * initiated, the batch enters a `canceling` state, at which time the system may
   * complete any in-progress, non-interruptible requests before finalizing
   * cancellation.
   *
   * The number of canceled requests is specified in `request_counts`. To determine
   * which requests were canceled, check the individual results within the batch.
   * Note that cancellation may not result in any canceled requests if they were
   * non-interruptible.
   *
   * Learn more about the Message Batches API in our
   * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
   *
   * @example
   * ```ts
   * const messageBatch = await client.messages.batches.cancel(
   *   'message_batch_id',
   * );
   * ```
   */
  cancel(messageBatchID, options) {
    return this._client.post(path`/v1/messages/batches/${messageBatchID}/cancel`, options);
  }
  /**
   * Streams the results of a Message Batch as a `.jsonl` file.
   *
   * Each line in the file is a JSON object containing the result of a single request
   * in the Message Batch. Results are not guaranteed to be in the same order as
   * requests. Use the `custom_id` field to match results to requests.
   *
   * Learn more about the Message Batches API in our
   * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
   *
   * @example
   * ```ts
   * const messageBatchIndividualResponse =
   *   await client.messages.batches.results('message_batch_id');
   * ```
   */
  async results(messageBatchID, options) {
    const batch = await this.retrieve(messageBatchID);
    if (!batch.results_url) {
      throw new AnthropicError(`No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`);
    }
    return this._client.get(batch.results_url, {
      ...options,
      headers: buildHeaders([{ Accept: "application/binary" }, options?.headers]),
      stream: true,
      __binaryResponse: true
    })._thenUnwrap((_3, props) => JSONLDecoder.fromResponse(props.response, props.controller));
  }
};

// ../pi-mono/node_modules/@anthropic-ai/sdk/resources/messages/messages.mjs
var Messages2 = class extends APIResource {
  constructor() {
    super(...arguments);
    this.batches = new Batches2(this._client);
  }
  create(body, options) {
    if (body.model in DEPRECATED_MODELS2) {
      console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${DEPRECATED_MODELS2[body.model]}
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);
    }
    if (body.model in MODELS_TO_WARN_WITH_THINKING_ENABLED2 && body.thinking && body.thinking.type === "enabled") {
      console.warn(`Using Claude with ${body.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);
    }
    let timeout = this._client._options.timeout;
    if (!body.stream && timeout == null) {
      const maxNonstreamingTokens = MODEL_NONSTREAMING_TOKENS[body.model] ?? void 0;
      timeout = this._client.calculateNonstreamingTimeout(body.max_tokens, maxNonstreamingTokens);
    }
    const helperHeader = stainlessHelperHeader(body.tools, body.messages);
    return this._client.post("/v1/messages", {
      body,
      timeout: timeout ?? 6e5,
      ...options,
      headers: buildHeaders([helperHeader, options?.headers]),
      stream: body.stream ?? false
    });
  }
  /**
   * Send a structured list of input messages with text and/or image content, along with an expected `output_config.format` and
   * the response will be automatically parsed and available in the `parsed_output` property of the message.
   *
   * @example
   * ```ts
   * const message = await client.messages.parse({
   *   model: 'claude-sonnet-4-5-20250929',
   *   max_tokens: 1024,
   *   messages: [{ role: 'user', content: 'What is 2+2?' }],
   *   output_config: {
   *     format: zodOutputFormat(z.object({ answer: z.number() })),
   *   },
   * });
   *
   * console.log(message.parsed_output?.answer); // 4
   * ```
   */
  parse(params, options) {
    return this.create(params, options).then((message) => parseMessage(message, params, { logger: this._client.logger ?? console }));
  }
  /**
   * Create a Message stream.
   *
   * If `output_config.format` is provided with a parseable format (like `zodOutputFormat()`),
   * the final message will include a `parsed_output` property with the parsed content.
   *
   * @example
   * ```ts
   * const stream = client.messages.stream({
   *   model: 'claude-sonnet-4-5-20250929',
   *   max_tokens: 1024,
   *   messages: [{ role: 'user', content: 'What is 2+2?' }],
   *   output_config: {
   *     format: zodOutputFormat(z.object({ answer: z.number() })),
   *   },
   * });
   *
   * const message = await stream.finalMessage();
   * console.log(message.parsed_output?.answer); // 4
   * ```
   */
  stream(body, options) {
    return MessageStream.createMessage(this, body, options, { logger: this._client.logger ?? console });
  }
  /**
   * Count the number of tokens in a Message.
   *
   * The Token Count API can be used to count the number of tokens in a Message,
   * including tools, images, and documents, without creating it.
   *
   * Learn more about token counting in our
   * [user guide](https://docs.claude.com/en/docs/build-with-claude/token-counting)
   *
   * @example
   * ```ts
   * const messageTokensCount =
   *   await client.messages.countTokens({
   *     messages: [{ content: 'string', role: 'user' }],
   *     model: 'claude-opus-4-6',
   *   });
   * ```
   */
  countTokens(body, options) {
    return this._client.post("/v1/messages/count_tokens", { body, ...options });
  }
};
var DEPRECATED_MODELS2 = {
  "claude-1.3": "November 6th, 2024",
  "claude-1.3-100k": "November 6th, 2024",
  "claude-instant-1.1": "November 6th, 2024",
  "claude-instant-1.1-100k": "November 6th, 2024",
  "claude-instant-1.2": "November 6th, 2024",
  "claude-3-sonnet-20240229": "July 21st, 2025",
  "claude-3-opus-20240229": "January 5th, 2026",
  "claude-2.1": "July 21st, 2025",
  "claude-2.0": "July 21st, 2025",
  "claude-3-7-sonnet-latest": "February 19th, 2026",
  "claude-3-7-sonnet-20250219": "February 19th, 2026",
  "claude-3-5-haiku-latest": "February 19th, 2026",
  "claude-3-5-haiku-20241022": "February 19th, 2026"
};
var MODELS_TO_WARN_WITH_THINKING_ENABLED2 = ["claude-opus-4-6"];
Messages2.Batches = Batches2;

// ../pi-mono/node_modules/@anthropic-ai/sdk/resources/models.mjs
init_process_shim();
var Models2 = class extends APIResource {
  /**
   * Get a specific model.
   *
   * The Models API response can be used to determine information about a specific
   * model or resolve a model alias to a model ID.
   */
  retrieve(modelID, params = {}, options) {
    const { betas } = params ?? {};
    return this._client.get(path`/v1/models/${modelID}`, {
      ...options,
      headers: buildHeaders([
        { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 },
        options?.headers
      ])
    });
  }
  /**
   * List available models.
   *
   * The Models API response can be used to determine which models are available for
   * use in the API. More recently released models are listed first.
   */
  list(params = {}, options) {
    const { betas, ...query } = params ?? {};
    return this._client.getAPIList("/v1/models", Page, {
      query,
      ...options,
      headers: buildHeaders([
        { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 },
        options?.headers
      ])
    });
  }
};

// ../pi-mono/node_modules/@anthropic-ai/sdk/internal/utils/env.mjs
init_process_shim();
var readEnv = (env) => {
  if (typeof globalThis.process !== "undefined") {
    return globalThis.process.env?.[env]?.trim() ?? void 0;
  }
  if (typeof globalThis.Deno !== "undefined") {
    return globalThis.Deno.env?.get?.(env)?.trim();
  }
  return void 0;
};

// ../pi-mono/node_modules/@anthropic-ai/sdk/client.mjs
var _BaseAnthropic_instances;
var _a;
var _BaseAnthropic_encoder;
var _BaseAnthropic_baseURLOverridden;
var HUMAN_PROMPT = "\\n\\nHuman:";
var AI_PROMPT = "\\n\\nAssistant:";
var BaseAnthropic = class {
  /**
   * API Client for interfacing with the Anthropic API.
   *
   * @param {string | null | undefined} [opts.apiKey=process.env['ANTHROPIC_API_KEY'] ?? null]
   * @param {string | null | undefined} [opts.authToken=process.env['ANTHROPIC_AUTH_TOKEN'] ?? null]
   * @param {string} [opts.baseURL=process.env['ANTHROPIC_BASE_URL'] ?? https://api.anthropic.com] - Override the default base URL for the API.
   * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
   * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.
   * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
   * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
   * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
   * @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.
   * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers.
   */
  constructor({ baseURL = readEnv("ANTHROPIC_BASE_URL"), apiKey = readEnv("ANTHROPIC_API_KEY") ?? null, authToken = readEnv("ANTHROPIC_AUTH_TOKEN") ?? null, ...opts } = {}) {
    _BaseAnthropic_instances.add(this);
    _BaseAnthropic_encoder.set(this, void 0);
    const options = {
      apiKey,
      authToken,
      ...opts,
      baseURL: baseURL || `https://api.anthropic.com`
    };
    if (!options.dangerouslyAllowBrowser && isRunningInBrowser()) {
      throw new AnthropicError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew Anthropic({ apiKey, dangerouslyAllowBrowser: true });\n");
    }
    this.baseURL = options.baseURL;
    this.timeout = options.timeout ?? _a.DEFAULT_TIMEOUT;
    this.logger = options.logger ?? console;
    const defaultLogLevel = "warn";
    this.logLevel = defaultLogLevel;
    this.logLevel = parseLogLevel(options.logLevel, "ClientOptions.logLevel", this) ?? parseLogLevel(readEnv("ANTHROPIC_LOG"), "process.env['ANTHROPIC_LOG']", this) ?? defaultLogLevel;
    this.fetchOptions = options.fetchOptions;
    this.maxRetries = options.maxRetries ?? 2;
    this.fetch = options.fetch ?? getDefaultFetch();
    __classPrivateFieldSet(this, _BaseAnthropic_encoder, FallbackEncoder, "f");
    this._options = options;
    this.apiKey = typeof apiKey === "string" ? apiKey : null;
    this.authToken = authToken;
  }
  /**
   * Create a new client instance re-using the same options given to the current client with optional overriding.
   */
  withOptions(options) {
    const client = new this.constructor({
      ...this._options,
      baseURL: this.baseURL,
      maxRetries: this.maxRetries,
      timeout: this.timeout,
      logger: this.logger,
      logLevel: this.logLevel,
      fetch: this.fetch,
      fetchOptions: this.fetchOptions,
      apiKey: this.apiKey,
      authToken: this.authToken,
      ...options
    });
    return client;
  }
  defaultQuery() {
    return this._options.defaultQuery;
  }
  validateHeaders({ values: values2, nulls }) {
    if (values2.get("x-api-key") || values2.get("authorization")) {
      return;
    }
    if (this.apiKey && values2.get("x-api-key")) {
      return;
    }
    if (nulls.has("x-api-key")) {
      return;
    }
    if (this.authToken && values2.get("authorization")) {
      return;
    }
    if (nulls.has("authorization")) {
      return;
    }
    throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted');
  }
  async authHeaders(opts) {
    return buildHeaders([await this.apiKeyAuth(opts), await this.bearerAuth(opts)]);
  }
  async apiKeyAuth(opts) {
    if (this.apiKey == null) {
      return void 0;
    }
    return buildHeaders([{ "X-Api-Key": this.apiKey }]);
  }
  async bearerAuth(opts) {
    if (this.authToken == null) {
      return void 0;
    }
    return buildHeaders([{ Authorization: `Bearer ${this.authToken}` }]);
  }
  /**
   * Basic re-implementation of `qs.stringify` for primitive types.
   */
  stringifyQuery(query) {
    return Object.entries(query).filter(([_3, value]) => typeof value !== "undefined").map(([key, value]) => {
      if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
        return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
      }
      if (value === null) {
        return `${encodeURIComponent(key)}=`;
      }
      throw new AnthropicError(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`);
    }).join("&");
  }
  getUserAgent() {
    return `${this.constructor.name}/JS ${VERSION}`;
  }
  defaultIdempotencyKey() {
    return `stainless-node-retry-${uuid4()}`;
  }
  makeStatusError(status, error, message, headers) {
    return APIError.generate(status, error, message, headers);
  }
  buildURL(path6, query, defaultBaseURL) {
    const baseURL = !__classPrivateFieldGet(this, _BaseAnthropic_instances, "m", _BaseAnthropic_baseURLOverridden).call(this) && defaultBaseURL || this.baseURL;
    const url = isAbsoluteURL(path6) ? new URL(path6) : new URL(baseURL + (baseURL.endsWith("/") && path6.startsWith("/") ? path6.slice(1) : path6));
    const defaultQuery = this.defaultQuery();
    if (!isEmptyObj(defaultQuery)) {
      query = { ...defaultQuery, ...query };
    }
    if (typeof query === "object" && query && !Array.isArray(query)) {
      url.search = this.stringifyQuery(query);
    }
    return url.toString();
  }
  _calculateNonstreamingTimeout(maxTokens) {
    const defaultTimeout = 10 * 60;
    const expectedTimeout = 60 * 60 * maxTokens / 128e3;
    if (expectedTimeout > defaultTimeout) {
      throw new AnthropicError("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");
    }
    return defaultTimeout * 1e3;
  }
  /**
   * Used as a callback for mutating the given `FinalRequestOptions` object.
   */
  async prepareOptions(options) {
  }
  /**
   * Used as a callback for mutating the given `RequestInit` object.
   *
   * This is useful for cases where you want to add certain headers based off of
   * the request properties, e.g. `method` or `url`.
   */
  async prepareRequest(request, { url, options }) {
  }
  get(path6, opts) {
    return this.methodRequest("get", path6, opts);
  }
  post(path6, opts) {
    return this.methodRequest("post", path6, opts);
  }
  patch(path6, opts) {
    return this.methodRequest("patch", path6, opts);
  }
  put(path6, opts) {
    return this.methodRequest("put", path6, opts);
  }
  delete(path6, opts) {
    return this.methodRequest("delete", path6, opts);
  }
  methodRequest(method, path6, opts) {
    return this.request(Promise.resolve(opts).then((opts2) => {
      return { method, path: path6, ...opts2 };
    }));
  }
  request(options, remainingRetries = null) {
    return new APIPromise(this, this.makeRequest(options, remainingRetries, void 0));
  }
  async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {
    const options = await optionsInput;
    const maxRetries = options.maxRetries ?? this.maxRetries;
    if (retriesRemaining == null) {
      retriesRemaining = maxRetries;
    }
    await this.prepareOptions(options);
    const { req, url, timeout } = await this.buildRequest(options, {
      retryCount: maxRetries - retriesRemaining
    });
    await this.prepareRequest(req, { url, options });
    const requestLogID = "log_" + (Math.random() * (1 << 24) | 0).toString(16).padStart(6, "0");
    const retryLogStr = retryOfRequestLogID === void 0 ? "" : `, retryOf: ${retryOfRequestLogID}`;
    const startTime = Date.now();
    loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({
      retryOfRequestLogID,
      method: options.method,
      url,
      options,
      headers: req.headers
    }));
    if (options.signal?.aborted) {
      throw new APIUserAbortError();
    }
    const controller = new AbortController();
    const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);
    const headersTime = Date.now();
    if (response instanceof globalThis.Error) {
      const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
      if (options.signal?.aborted) {
        throw new APIUserAbortError();
      }
      const isTimeout = isAbortError(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : ""));
      if (retriesRemaining) {
        loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`);
        loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails({
          retryOfRequestLogID,
          url,
          durationMs: headersTime - startTime,
          message: response.message
        }));
        return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID);
      }
      loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - error; no more retries left`);
      loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (error; no more retries left)`, formatRequestDetails({
        retryOfRequestLogID,
        url,
        durationMs: headersTime - startTime,
        message: response.message
      }));
      if (isTimeout) {
        throw new APIConnectionTimeoutError();
      }
      throw new APIConnectionError({ cause: response });
    }
    const specialHeaders = [...response.headers.entries()].filter(([name]) => name === "request-id").map(([name, value]) => ", " + name + ": " + JSON.stringify(value)).join("");
    const responseInfo = `[${requestLogID}${retryLogStr}${specialHeaders}] ${req.method} ${url} ${response.ok ? "succeeded" : "failed"} with status ${response.status} in ${headersTime - startTime}ms`;
    if (!response.ok) {
      const shouldRetry = await this.shouldRetry(response);
      if (retriesRemaining && shouldRetry) {
        const retryMessage2 = `retrying, ${retriesRemaining} attempts remaining`;
        await CancelReadableStream(response.body);
        loggerFor(this).info(`${responseInfo} - ${retryMessage2}`);
        loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage2})`, formatRequestDetails({
          retryOfRequestLogID,
          url: response.url,
          status: response.status,
          headers: response.headers,
          durationMs: headersTime - startTime
        }));
        return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers);
      }
      const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
      loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
      const errText = await response.text().catch((err2) => castToError(err2).message);
      const errJSON = safeJSON(errText);
      const errMessage = errJSON ? void 0 : errText;
      loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
        retryOfRequestLogID,
        url: response.url,
        status: response.status,
        headers: response.headers,
        message: errMessage,
        durationMs: Date.now() - startTime
      }));
      const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);
      throw err;
    }
    loggerFor(this).info(responseInfo);
    loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({
      retryOfRequestLogID,
      url: response.url,
      status: response.status,
      headers: response.headers,
      durationMs: headersTime - startTime
    }));
    return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };
  }
  getAPIList(path6, Page3, opts) {
    return this.requestAPIList(Page3, opts && "then" in opts ? opts.then((opts2) => ({ method: "get", path: path6, ...opts2 })) : { method: "get", path: path6, ...opts });
  }
  requestAPIList(Page3, options) {
    const request = this.makeRequest(options, null, void 0);
    return new PagePromise(this, request, Page3);
  }
  async fetchWithTimeout(url, init, ms, controller) {
    const { signal, method, ...options } = init || {};
    const abort = this._makeAbort(controller);
    if (signal)
      signal.addEventListener("abort", abort, { once: true });
    const timeout = setTimeout(abort, ms);
    const isReadableBody = globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream || typeof options.body === "object" && options.body !== null && Symbol.asyncIterator in options.body;
    const fetchOptions = {
      signal: controller.signal,
      ...isReadableBody ? { duplex: "half" } : {},
      method: "GET",
      ...options
    };
    if (method) {
      fetchOptions.method = method.toUpperCase();
    }
    try {
      return await this.fetch.call(void 0, url, fetchOptions);
    } finally {
      clearTimeout(timeout);
    }
  }
  async shouldRetry(response) {
    const shouldRetryHeader = response.headers.get("x-should-retry");
    if (shouldRetryHeader === "true")
      return true;
    if (shouldRetryHeader === "false")
      return false;
    if (response.status === 408)
      return true;
    if (response.status === 409)
      return true;
    if (response.status === 429)
      return true;
    if (response.status >= 500)
      return true;
    return false;
  }
  async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) {
    let timeoutMillis;
    const retryAfterMillisHeader = responseHeaders?.get("retry-after-ms");
    if (retryAfterMillisHeader) {
      const timeoutMs = parseFloat(retryAfterMillisHeader);
      if (!Number.isNaN(timeoutMs)) {
        timeoutMillis = timeoutMs;
      }
    }
    const retryAfterHeader = responseHeaders?.get("retry-after");
    if (retryAfterHeader && !timeoutMillis) {
      const timeoutSeconds = parseFloat(retryAfterHeader);
      if (!Number.isNaN(timeoutSeconds)) {
        timeoutMillis = timeoutSeconds * 1e3;
      } else {
        timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
      }
    }
    if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1e3)) {
      const maxRetries = options.maxRetries ?? this.maxRetries;
      timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
    }
    await sleep(timeoutMillis);
    return this.makeRequest(options, retriesRemaining - 1, requestLogID);
  }
  calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
    const initialRetryDelay = 0.5;
    const maxRetryDelay = 8;
    const numRetries = maxRetries - retriesRemaining;
    const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
    const jitter = 1 - Math.random() * 0.25;
    return sleepSeconds * jitter * 1e3;
  }
  calculateNonstreamingTimeout(maxTokens, maxNonstreamingTokens) {
    const maxTime = 60 * 60 * 1e3;
    const defaultTime = 60 * 10 * 1e3;
    const expectedTime = maxTime * maxTokens / 128e3;
    if (expectedTime > defaultTime || maxNonstreamingTokens != null && maxTokens > maxNonstreamingTokens) {
      throw new AnthropicError("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");
    }
    return defaultTime;
  }
  async buildRequest(inputOptions, { retryCount = 0 } = {}) {
    const options = { ...inputOptions };
    const { method, path: path6, query, defaultBaseURL } = options;
    const url = this.buildURL(path6, query, defaultBaseURL);
    if ("timeout" in options)
      validatePositiveInteger("timeout", options.timeout);
    options.timeout = options.timeout ?? this.timeout;
    const { bodyHeaders, body } = this.buildBody({ options });
    const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
    const req = {
      method,
      headers: reqHeaders,
      ...options.signal && { signal: options.signal },
      ...globalThis.ReadableStream && body instanceof globalThis.ReadableStream && { duplex: "half" },
      ...body && { body },
      ...this.fetchOptions ?? {},
      ...options.fetchOptions ?? {}
    };
    return { req, url, timeout: options.timeout };
  }
  async buildHeaders({ options, method, bodyHeaders, retryCount }) {
    let idempotencyHeaders = {};
    if (this.idempotencyHeader && method !== "get") {
      if (!options.idempotencyKey)
        options.idempotencyKey = this.defaultIdempotencyKey();
      idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey;
    }
    const headers = buildHeaders([
      idempotencyHeaders,
      {
        Accept: "application/json",
        "User-Agent": this.getUserAgent(),
        "X-Stainless-Retry-Count": String(retryCount),
        ...options.timeout ? { "X-Stainless-Timeout": String(Math.trunc(options.timeout / 1e3)) } : {},
        ...getPlatformHeaders(),
        ...this._options.dangerouslyAllowBrowser ? { "anthropic-dangerous-direct-browser-access": "true" } : void 0,
        "anthropic-version": "2023-06-01"
      },
      await this.authHeaders(options),
      this._options.defaultHeaders,
      bodyHeaders,
      options.headers
    ]);
    this.validateHeaders(headers);
    return headers.values;
  }
  _makeAbort(controller) {
    return () => controller.abort();
  }
  buildBody({ options: { body, headers: rawHeaders } }) {
    if (!body) {
      return { bodyHeaders: void 0, body: void 0 };
    }
    const headers = buildHeaders([rawHeaders]);
    if (
      // Pass raw type verbatim
      ArrayBuffer.isView(body) || body instanceof ArrayBuffer || body instanceof DataView || typeof body === "string" && // Preserve legacy string encoding behavior for now
      headers.values.has("content-type") || // `Blob` is superset of `File`
      globalThis.Blob && body instanceof globalThis.Blob || // `FormData` -> `multipart/form-data`
      body instanceof FormData || // `URLSearchParams` -> `application/x-www-form-urlencoded`
      body instanceof URLSearchParams || // Send chunked stream (each chunk has own `length`)
      globalThis.ReadableStream && body instanceof globalThis.ReadableStream
    ) {
      return { bodyHeaders: void 0, body };
    } else if (typeof body === "object" && (Symbol.asyncIterator in body || Symbol.iterator in body && "next" in body && typeof body.next === "function")) {
      return { bodyHeaders: void 0, body: ReadableStreamFrom(body) };
    } else {
      return __classPrivateFieldGet(this, _BaseAnthropic_encoder, "f").call(this, { body, headers });
    }
  }
};
_a = BaseAnthropic, _BaseAnthropic_encoder = /* @__PURE__ */ new WeakMap(), _BaseAnthropic_instances = /* @__PURE__ */ new WeakSet(), _BaseAnthropic_baseURLOverridden = function _BaseAnthropic_baseURLOverridden2() {
  return this.baseURL !== "https://api.anthropic.com";
};
BaseAnthropic.Anthropic = _a;
BaseAnthropic.HUMAN_PROMPT = HUMAN_PROMPT;
BaseAnthropic.AI_PROMPT = AI_PROMPT;
BaseAnthropic.DEFAULT_TIMEOUT = 6e5;
BaseAnthropic.AnthropicError = AnthropicError;
BaseAnthropic.APIError = APIError;
BaseAnthropic.APIConnectionError = APIConnectionError;
BaseAnthropic.APIConnectionTimeoutError = APIConnectionTimeoutError;
BaseAnthropic.APIUserAbortError = APIUserAbortError;
BaseAnthropic.NotFoundError = NotFoundError;
BaseAnthropic.ConflictError = ConflictError;
BaseAnthropic.RateLimitError = RateLimitError;
BaseAnthropic.BadRequestError = BadRequestError;
BaseAnthropic.AuthenticationError = AuthenticationError;
BaseAnthropic.InternalServerError = InternalServerError;
BaseAnthropic.PermissionDeniedError = PermissionDeniedError;
BaseAnthropic.UnprocessableEntityError = UnprocessableEntityError;
BaseAnthropic.toFile = toFile;
var Anthropic = class extends BaseAnthropic {
  constructor() {
    super(...arguments);
    this.completions = new Completions(this);
    this.messages = new Messages2(this);
    this.models = new Models2(this);
    this.beta = new Beta(this);
  }
};
Anthropic.Completions = Completions;
Anthropic.Messages = Messages2;
Anthropic.Models = Models2;
Anthropic.Beta = Beta;

// ../pi-mono/packages/ai/dist/utils/event-stream.js
init_process_shim();
var EventStream = class {
  isComplete;
  extractResult;
  queue = [];
  waiting = [];
  done = false;
  finalResultPromise;
  resolveFinalResult;
  constructor(isComplete, extractResult) {
    this.isComplete = isComplete;
    this.extractResult = extractResult;
    this.finalResultPromise = new Promise((resolve) => {
      this.resolveFinalResult = resolve;
    });
  }
  push(event) {
    if (this.done)
      return;
    if (this.isComplete(event)) {
      this.done = true;
      this.resolveFinalResult(this.extractResult(event));
    }
    const waiter = this.waiting.shift();
    if (waiter) {
      waiter({ value: event, done: false });
    } else {
      this.queue.push(event);
    }
  }
  end(result) {
    this.done = true;
    if (result !== void 0) {
      this.resolveFinalResult(result);
    }
    while (this.waiting.length > 0) {
      const waiter = this.waiting.shift();
      waiter({ value: void 0, done: true });
    }
  }
  async *[Symbol.asyncIterator]() {
    while (true) {
      if (this.queue.length > 0) {
        yield this.queue.shift();
      } else if (this.done) {
        return;
      } else {
        const result = await new Promise((resolve) => this.waiting.push(resolve));
        if (result.done)
          return;
        yield result.value;
      }
    }
  }
  result() {
    return this.finalResultPromise;
  }
};
var AssistantMessageEventStream = class extends EventStream {
  constructor() {
    super((event) => event.type === "done" || event.type === "error", (event) => {
      if (event.type === "done") {
        return event.message;
      } else if (event.type === "error") {
        return event.error;
      }
      throw new Error("Unexpected event type for final result");
    });
  }
};

// ../pi-mono/packages/ai/dist/utils/json-parse.js
init_process_shim();
var import_partial_json = __toESM(require_dist(), 1);
function parseStreamingJson(partialJson) {
  if (!partialJson || partialJson.trim() === "") {
    return {};
  }
  try {
    return JSON.parse(partialJson);
  } catch {
    try {
      const result = (0, import_partial_json.parse)(partialJson);
      return result ?? {};
    } catch {
      return {};
    }
  }
}

// ../pi-mono/packages/ai/dist/utils/sanitize-unicode.js
init_process_shim();
function sanitizeSurrogates(text3) {
  return text3.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "");
}

// ../pi-mono/packages/ai/dist/providers/github-copilot-headers.js
init_process_shim();
function inferCopilotInitiator(messages) {
  const last = messages[messages.length - 1];
  return last && last.role !== "user" ? "agent" : "user";
}
function hasCopilotVisionInput(messages) {
  return messages.some((msg) => {
    if (msg.role === "user" && Array.isArray(msg.content)) {
      return msg.content.some((c6) => c6.type === "image");
    }
    if (msg.role === "toolResult" && Array.isArray(msg.content)) {
      return msg.content.some((c6) => c6.type === "image");
    }
    return false;
  });
}
function buildCopilotDynamicHeaders(params) {
  const headers = {
    "X-Initiator": inferCopilotInitiator(params.messages),
    "Openai-Intent": "conversation-edits"
  };
  if (params.hasImages) {
    headers["Copilot-Vision-Request"] = "true";
  }
  return headers;
}

// ../pi-mono/packages/ai/dist/providers/simple-options.js
init_process_shim();
function buildBaseOptions(model, options, apiKey) {
  return {
    temperature: options?.temperature,
    maxTokens: options?.maxTokens || Math.min(model.maxTokens, 32e3),
    signal: options?.signal,
    apiKey: apiKey || options?.apiKey,
    cacheRetention: options?.cacheRetention,
    sessionId: options?.sessionId,
    headers: options?.headers,
    onPayload: options?.onPayload,
    maxRetryDelayMs: options?.maxRetryDelayMs,
    metadata: options?.metadata
  };
}
function clampReasoning(effort) {
  return effort === "xhigh" ? "high" : effort;
}
function adjustMaxTokensForThinking(baseMaxTokens, modelMaxTokens, reasoningLevel, customBudgets) {
  const defaultBudgets = {
    minimal: 1024,
    low: 2048,
    medium: 8192,
    high: 16384
  };
  const budgets = { ...defaultBudgets, ...customBudgets };
  const minOutputTokens = 1024;
  const level = clampReasoning(reasoningLevel);
  let thinkingBudget = budgets[level];
  const maxTokens = Math.min(baseMaxTokens + thinkingBudget, modelMaxTokens);
  if (maxTokens <= thinkingBudget) {
    thinkingBudget = Math.max(0, maxTokens - minOutputTokens);
  }
  return { maxTokens, thinkingBudget };
}

// ../pi-mono/packages/ai/dist/providers/transform-messages.js
init_process_shim();
function transformMessages(messages, model, normalizeToolCallId2) {
  const toolCallIdMap = /* @__PURE__ */ new Map();
  const transformed = messages.map((msg) => {
    if (msg.role === "user") {
      return msg;
    }
    if (msg.role === "toolResult") {
      const normalizedId = toolCallIdMap.get(msg.toolCallId);
      if (normalizedId && normalizedId !== msg.toolCallId) {
        return { ...msg, toolCallId: normalizedId };
      }
      return msg;
    }
    if (msg.role === "assistant") {
      const assistantMsg = msg;
      const isSameModel = assistantMsg.provider === model.provider && assistantMsg.api === model.api && assistantMsg.model === model.id;
      const transformedContent = assistantMsg.content.flatMap((block) => {
        if (block.type === "thinking") {
          if (block.redacted) {
            return isSameModel ? block : [];
          }
          if (isSameModel && block.thinkingSignature)
            return block;
          if (!block.thinking || block.thinking.trim() === "")
            return [];
          if (isSameModel)
            return block;
          return {
            type: "text",
            text: block.thinking
          };
        }
        if (block.type === "text") {
          if (isSameModel)
            return block;
          return {
            type: "text",
            text: block.text
          };
        }
        if (block.type === "toolCall") {
          const toolCall = block;
          let normalizedToolCall = toolCall;
          if (!isSameModel && toolCall.thoughtSignature) {
            normalizedToolCall = { ...toolCall };
            delete normalizedToolCall.thoughtSignature;
          }
          if (!isSameModel && normalizeToolCallId2) {
            const normalizedId = normalizeToolCallId2(toolCall.id, model, assistantMsg);
            if (normalizedId !== toolCall.id) {
              toolCallIdMap.set(toolCall.id, normalizedId);
              normalizedToolCall = { ...normalizedToolCall, id: normalizedId };
            }
          }
          return normalizedToolCall;
        }
        return block;
      });
      return {
        ...assistantMsg,
        content: transformedContent
      };
    }
    return msg;
  });
  const result = [];
  let pendingToolCalls = [];
  let existingToolResultIds = /* @__PURE__ */ new Set();
  for (let i7 = 0; i7 < transformed.length; i7++) {
    const msg = transformed[i7];
    if (msg.role === "assistant") {
      if (pendingToolCalls.length > 0) {
        for (const tc of pendingToolCalls) {
          if (!existingToolResultIds.has(tc.id)) {
            result.push({
              role: "toolResult",
              toolCallId: tc.id,
              toolName: tc.name,
              content: [{ type: "text", text: "No result provided" }],
              isError: true,
              timestamp: Date.now()
            });
          }
        }
        pendingToolCalls = [];
        existingToolResultIds = /* @__PURE__ */ new Set();
      }
      const assistantMsg = msg;
      if (assistantMsg.stopReason === "error" || assistantMsg.stopReason === "aborted") {
        continue;
      }
      const toolCalls = assistantMsg.content.filter((b4) => b4.type === "toolCall");
      if (toolCalls.length > 0) {
        pendingToolCalls = toolCalls;
        existingToolResultIds = /* @__PURE__ */ new Set();
      }
      result.push(msg);
    } else if (msg.role === "toolResult") {
      existingToolResultIds.add(msg.toolCallId);
      result.push(msg);
    } else if (msg.role === "user") {
      if (pendingToolCalls.length > 0) {
        for (const tc of pendingToolCalls) {
          if (!existingToolResultIds.has(tc.id)) {
            result.push({
              role: "toolResult",
              toolCallId: tc.id,
              toolName: tc.name,
              content: [{ type: "text", text: "No result provided" }],
              isError: true,
              timestamp: Date.now()
            });
          }
        }
        pendingToolCalls = [];
        existingToolResultIds = /* @__PURE__ */ new Set();
      }
      result.push(msg);
    } else {
      result.push(msg);
    }
  }
  return result;
}

// ../pi-mono/packages/ai/dist/providers/anthropic.js
function resolveCacheRetention(cacheRetention) {
  if (cacheRetention) {
    return cacheRetention;
  }
  if (typeof process !== "undefined" && process.env.PI_CACHE_RETENTION === "long") {
    return "long";
  }
  return "short";
}
function getCacheControl(baseUrl, cacheRetention) {
  const retention = resolveCacheRetention(cacheRetention);
  if (retention === "none") {
    return { retention };
  }
  const ttl = retention === "long" && baseUrl.includes("api.anthropic.com") ? "1h" : void 0;
  return {
    retention,
    cacheControl: { type: "ephemeral", ...ttl && { ttl } }
  };
}
var claudeCodeVersion = "2.1.75";
var claudeCodeTools = [
  "Read",
  "Write",
  "Edit",
  "Bash",
  "Grep",
  "Glob",
  "AskUserQuestion",
  "EnterPlanMode",
  "ExitPlanMode",
  "KillShell",
  "NotebookEdit",
  "Skill",
  "Task",
  "TaskOutput",
  "TodoWrite",
  "WebFetch",
  "WebSearch"
];
var ccToolLookup = new Map(claudeCodeTools.map((t6) => [t6.toLowerCase(), t6]));
var toClaudeCodeName = (name) => ccToolLookup.get(name.toLowerCase()) ?? name;
var fromClaudeCodeName = (name, tools) => {
  if (tools && tools.length > 0) {
    const lowerName = name.toLowerCase();
    const matchedTool = tools.find((tool) => tool.name.toLowerCase() === lowerName);
    if (matchedTool)
      return matchedTool.name;
  }
  return name;
};
function convertContentBlocks(content) {
  const hasImages = content.some((c6) => c6.type === "image");
  if (!hasImages) {
    return sanitizeSurrogates(content.map((c6) => c6.text).join("\n"));
  }
  const blocks = content.map((block) => {
    if (block.type === "text") {
      return {
        type: "text",
        text: sanitizeSurrogates(block.text)
      };
    }
    return {
      type: "image",
      source: {
        type: "base64",
        media_type: block.mimeType,
        data: block.data
      }
    };
  });
  const hasText = blocks.some((b4) => b4.type === "text");
  if (!hasText) {
    blocks.unshift({
      type: "text",
      text: "(see attached image)"
    });
  }
  return blocks;
}
function mergeHeaders(...headerSources) {
  const merged = {};
  for (const headers of headerSources) {
    if (headers) {
      Object.assign(merged, headers);
    }
  }
  return merged;
}
var streamAnthropic = (model, context, options) => {
  const stream2 = new AssistantMessageEventStream();
  (async () => {
    const output = {
      role: "assistant",
      content: [],
      api: model.api,
      provider: model.provider,
      model: model.id,
      usage: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0,
        totalTokens: 0,
        cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
      },
      stopReason: "stop",
      timestamp: Date.now()
    };
    try {
      const apiKey = options?.apiKey ?? getEnvApiKey(model.provider) ?? "";
      let copilotDynamicHeaders;
      if (model.provider === "github-copilot") {
        const hasImages = hasCopilotVisionInput(context.messages);
        copilotDynamicHeaders = buildCopilotDynamicHeaders({
          messages: context.messages,
          hasImages
        });
      }
      const { client, isOAuthToken: isOAuthToken2 } = createClient(model, apiKey, options?.interleavedThinking ?? true, options?.headers, copilotDynamicHeaders);
      let params = buildParams(model, context, isOAuthToken2, options);
      const nextParams = await options?.onPayload?.(params, model);
      if (nextParams !== void 0) {
        params = nextParams;
      }
      const anthropicStream = client.messages.stream({ ...params, stream: true }, { signal: options?.signal });
      stream2.push({ type: "start", partial: output });
      const blocks = output.content;
      for await (const event of anthropicStream) {
        if (event.type === "message_start") {
          output.usage.input = event.message.usage.input_tokens || 0;
          output.usage.output = event.message.usage.output_tokens || 0;
          output.usage.cacheRead = event.message.usage.cache_read_input_tokens || 0;
          output.usage.cacheWrite = event.message.usage.cache_creation_input_tokens || 0;
          output.usage.totalTokens = output.usage.input + output.usage.output + output.usage.cacheRead + output.usage.cacheWrite;
          calculateCost(model, output.usage);
        } else if (event.type === "content_block_start") {
          if (event.content_block.type === "text") {
            const block = {
              type: "text",
              text: "",
              index: event.index
            };
            output.content.push(block);
            stream2.push({ type: "text_start", contentIndex: output.content.length - 1, partial: output });
          } else if (event.content_block.type === "thinking") {
            const block = {
              type: "thinking",
              thinking: "",
              thinkingSignature: "",
              index: event.index
            };
            output.content.push(block);
            stream2.push({ type: "thinking_start", contentIndex: output.content.length - 1, partial: output });
          } else if (event.content_block.type === "redacted_thinking") {
            const block = {
              type: "thinking",
              thinking: "[Reasoning redacted]",
              thinkingSignature: event.content_block.data,
              redacted: true,
              index: event.index
            };
            output.content.push(block);
            stream2.push({ type: "thinking_start", contentIndex: output.content.length - 1, partial: output });
          } else if (event.content_block.type === "tool_use") {
            const block = {
              type: "toolCall",
              id: event.content_block.id,
              name: isOAuthToken2 ? fromClaudeCodeName(event.content_block.name, context.tools) : event.content_block.name,
              arguments: event.content_block.input ?? {},
              partialJson: "",
              index: event.index
            };
            output.content.push(block);
            stream2.push({ type: "toolcall_start", contentIndex: output.content.length - 1, partial: output });
          }
        } else if (event.type === "content_block_delta") {
          if (event.delta.type === "text_delta") {
            const index = blocks.findIndex((b4) => b4.index === event.index);
            const block = blocks[index];
            if (block && block.type === "text") {
              block.text += event.delta.text;
              stream2.push({
                type: "text_delta",
                contentIndex: index,
                delta: event.delta.text,
                partial: output
              });
            }
          } else if (event.delta.type === "thinking_delta") {
            const index = blocks.findIndex((b4) => b4.index === event.index);
            const block = blocks[index];
            if (block && block.type === "thinking") {
              block.thinking += event.delta.thinking;
              stream2.push({
                type: "thinking_delta",
                contentIndex: index,
                delta: event.delta.thinking,
                partial: output
              });
            }
          } else if (event.delta.type === "input_json_delta") {
            const index = blocks.findIndex((b4) => b4.index === event.index);
            const block = blocks[index];
            if (block && block.type === "toolCall") {
              block.partialJson += event.delta.partial_json;
              block.arguments = parseStreamingJson(block.partialJson);
              stream2.push({
                type: "toolcall_delta",
                contentIndex: index,
                delta: event.delta.partial_json,
                partial: output
              });
            }
          } else if (event.delta.type === "signature_delta") {
            const index = blocks.findIndex((b4) => b4.index === event.index);
            const block = blocks[index];
            if (block && block.type === "thinking") {
              block.thinkingSignature = block.thinkingSignature || "";
              block.thinkingSignature += event.delta.signature;
            }
          }
        } else if (event.type === "content_block_stop") {
          const index = blocks.findIndex((b4) => b4.index === event.index);
          const block = blocks[index];
          if (block) {
            delete block.index;
            if (block.type === "text") {
              stream2.push({
                type: "text_end",
                contentIndex: index,
                content: block.text,
                partial: output
              });
            } else if (block.type === "thinking") {
              stream2.push({
                type: "thinking_end",
                contentIndex: index,
                content: block.thinking,
                partial: output
              });
            } else if (block.type === "toolCall") {
              block.arguments = parseStreamingJson(block.partialJson);
              delete block.partialJson;
              stream2.push({
                type: "toolcall_end",
                contentIndex: index,
                toolCall: block,
                partial: output
              });
            }
          }
        } else if (event.type === "message_delta") {
          if (event.delta.stop_reason) {
            output.stopReason = mapStopReason(event.delta.stop_reason);
          }
          if (event.usage.input_tokens != null) {
            output.usage.input = event.usage.input_tokens;
          }
          if (event.usage.output_tokens != null) {
            output.usage.output = event.usage.output_tokens;
          }
          if (event.usage.cache_read_input_tokens != null) {
            output.usage.cacheRead = event.usage.cache_read_input_tokens;
          }
          if (event.usage.cache_creation_input_tokens != null) {
            output.usage.cacheWrite = event.usage.cache_creation_input_tokens;
          }
          output.usage.totalTokens = output.usage.input + output.usage.output + output.usage.cacheRead + output.usage.cacheWrite;
          calculateCost(model, output.usage);
        }
      }
      if (options?.signal?.aborted) {
        throw new Error("Request was aborted");
      }
      if (output.stopReason === "aborted" || output.stopReason === "error") {
        throw new Error("An unknown error occurred");
      }
      stream2.push({ type: "done", reason: output.stopReason, message: output });
      stream2.end();
    } catch (error) {
      for (const block of output.content)
        delete block.index;
      output.stopReason = options?.signal?.aborted ? "aborted" : "error";
      output.errorMessage = error instanceof Error ? error.message : JSON.stringify(error);
      stream2.push({ type: "error", reason: output.stopReason, error: output });
      stream2.end();
    }
  })();
  return stream2;
};
function supportsAdaptiveThinking(modelId) {
  return modelId.includes("opus-4-6") || modelId.includes("opus-4.6") || modelId.includes("sonnet-4-6") || modelId.includes("sonnet-4.6");
}
function mapThinkingLevelToEffort(level, modelId) {
  switch (level) {
    case "minimal":
      return "low";
    case "low":
      return "low";
    case "medium":
      return "medium";
    case "high":
      return "high";
    case "xhigh":
      return modelId.includes("opus-4-6") || modelId.includes("opus-4.6") ? "max" : "high";
    default:
      return "high";
  }
}
var streamSimpleAnthropic = (model, context, options) => {
  const apiKey = options?.apiKey || getEnvApiKey(model.provider);
  if (!apiKey) {
    throw new Error(`No API key for provider: ${model.provider}`);
  }
  const base = buildBaseOptions(model, options, apiKey);
  if (!options?.reasoning) {
    return streamAnthropic(model, context, { ...base, thinkingEnabled: false });
  }
  if (supportsAdaptiveThinking(model.id)) {
    const effort = mapThinkingLevelToEffort(options.reasoning, model.id);
    return streamAnthropic(model, context, {
      ...base,
      thinkingEnabled: true,
      effort
    });
  }
  const adjusted = adjustMaxTokensForThinking(base.maxTokens || 0, model.maxTokens, options.reasoning, options.thinkingBudgets);
  return streamAnthropic(model, context, {
    ...base,
    maxTokens: adjusted.maxTokens,
    thinkingEnabled: true,
    thinkingBudgetTokens: adjusted.thinkingBudget
  });
};
function isOAuthToken(apiKey) {
  return apiKey.includes("sk-ant-oat");
}
function createClient(model, apiKey, interleavedThinking, optionsHeaders, dynamicHeaders) {
  const needsInterleavedBeta = interleavedThinking && !supportsAdaptiveThinking(model.id);
  if (model.provider === "github-copilot") {
    const betaFeatures2 = [];
    if (needsInterleavedBeta) {
      betaFeatures2.push("interleaved-thinking-2025-05-14");
    }
    const client2 = new Anthropic({
      apiKey: null,
      authToken: apiKey,
      baseURL: model.baseUrl,
      dangerouslyAllowBrowser: true,
      defaultHeaders: mergeHeaders({
        accept: "application/json",
        "anthropic-dangerous-direct-browser-access": "true",
        ...betaFeatures2.length > 0 ? { "anthropic-beta": betaFeatures2.join(",") } : {}
      }, model.headers, dynamicHeaders, optionsHeaders)
    });
    return { client: client2, isOAuthToken: false };
  }
  const betaFeatures = ["fine-grained-tool-streaming-2025-05-14"];
  if (needsInterleavedBeta) {
    betaFeatures.push("interleaved-thinking-2025-05-14");
  }
  if (isOAuthToken(apiKey)) {
    const client2 = new Anthropic({
      apiKey: null,
      authToken: apiKey,
      baseURL: model.baseUrl,
      dangerouslyAllowBrowser: true,
      defaultHeaders: mergeHeaders({
        accept: "application/json",
        "anthropic-dangerous-direct-browser-access": "true",
        "anthropic-beta": `claude-code-20250219,oauth-2025-04-20,${betaFeatures.join(",")}`,
        "user-agent": `claude-cli/${claudeCodeVersion}`,
        "x-app": "cli"
      }, model.headers, optionsHeaders)
    });
    return { client: client2, isOAuthToken: true };
  }
  const client = new Anthropic({
    apiKey,
    baseURL: model.baseUrl,
    dangerouslyAllowBrowser: true,
    defaultHeaders: mergeHeaders({
      accept: "application/json",
      "anthropic-dangerous-direct-browser-access": "true",
      "anthropic-beta": betaFeatures.join(",")
    }, model.headers, optionsHeaders)
  });
  return { client, isOAuthToken: false };
}
function buildParams(model, context, isOAuthToken2, options) {
  const { cacheControl } = getCacheControl(model.baseUrl, options?.cacheRetention);
  const params = {
    model: model.id,
    messages: convertMessages(context.messages, model, isOAuthToken2, cacheControl),
    max_tokens: options?.maxTokens || model.maxTokens / 3 | 0,
    stream: true
  };
  if (isOAuthToken2) {
    params.system = [
      {
        type: "text",
        text: "You are Claude Code, Anthropic's official CLI for Claude.",
        ...cacheControl ? { cache_control: cacheControl } : {}
      }
    ];
    if (context.systemPrompt) {
      params.system.push({
        type: "text",
        text: sanitizeSurrogates(context.systemPrompt),
        ...cacheControl ? { cache_control: cacheControl } : {}
      });
    }
  } else if (context.systemPrompt) {
    params.system = [
      {
        type: "text",
        text: sanitizeSurrogates(context.systemPrompt),
        ...cacheControl ? { cache_control: cacheControl } : {}
      }
    ];
  }
  if (options?.temperature !== void 0 && !options?.thinkingEnabled) {
    params.temperature = options.temperature;
  }
  if (context.tools) {
    params.tools = convertTools(context.tools, isOAuthToken2);
  }
  if (options?.thinkingEnabled && model.reasoning) {
    if (supportsAdaptiveThinking(model.id)) {
      params.thinking = { type: "adaptive" };
      if (options.effort) {
        params.output_config = { effort: options.effort };
      }
    } else {
      params.thinking = {
        type: "enabled",
        budget_tokens: options.thinkingBudgetTokens || 1024
      };
    }
  }
  if (options?.metadata) {
    const userId = options.metadata.user_id;
    if (typeof userId === "string") {
      params.metadata = { user_id: userId };
    }
  }
  if (options?.toolChoice) {
    if (typeof options.toolChoice === "string") {
      params.tool_choice = { type: options.toolChoice };
    } else {
      params.tool_choice = options.toolChoice;
    }
  }
  return params;
}
function normalizeToolCallId(id) {
  return id.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 64);
}
function convertMessages(messages, model, isOAuthToken2, cacheControl) {
  const params = [];
  const transformedMessages = transformMessages(messages, model, normalizeToolCallId);
  for (let i7 = 0; i7 < transformedMessages.length; i7++) {
    const msg = transformedMessages[i7];
    if (msg.role === "user") {
      if (typeof msg.content === "string") {
        if (msg.content.trim().length > 0) {
          params.push({
            role: "user",
            content: sanitizeSurrogates(msg.content)
          });
        }
      } else {
        const blocks = msg.content.map((item) => {
          if (item.type === "text") {
            return {
              type: "text",
              text: sanitizeSurrogates(item.text)
            };
          } else {
            return {
              type: "image",
              source: {
                type: "base64",
                media_type: item.mimeType,
                data: item.data
              }
            };
          }
        });
        let filteredBlocks = !model?.input.includes("image") ? blocks.filter((b4) => b4.type !== "image") : blocks;
        filteredBlocks = filteredBlocks.filter((b4) => {
          if (b4.type === "text") {
            return b4.text.trim().length > 0;
          }
          return true;
        });
        if (filteredBlocks.length === 0)
          continue;
        params.push({
          role: "user",
          content: filteredBlocks
        });
      }
    } else if (msg.role === "assistant") {
      const blocks = [];
      for (const block of msg.content) {
        if (block.type === "text") {
          if (block.text.trim().length === 0)
            continue;
          blocks.push({
            type: "text",
            text: sanitizeSurrogates(block.text)
          });
        } else if (block.type === "thinking") {
          if (block.redacted) {
            blocks.push({
              type: "redacted_thinking",
              data: block.thinkingSignature
            });
            continue;
          }
          if (block.thinking.trim().length === 0)
            continue;
          if (!block.thinkingSignature || block.thinkingSignature.trim().length === 0) {
            blocks.push({
              type: "text",
              text: sanitizeSurrogates(block.thinking)
            });
          } else {
            blocks.push({
              type: "thinking",
              thinking: sanitizeSurrogates(block.thinking),
              signature: block.thinkingSignature
            });
          }
        } else if (block.type === "toolCall") {
          blocks.push({
            type: "tool_use",
            id: block.id,
            name: isOAuthToken2 ? toClaudeCodeName(block.name) : block.name,
            input: block.arguments ?? {}
          });
        }
      }
      if (blocks.length === 0)
        continue;
      params.push({
        role: "assistant",
        content: blocks
      });
    } else if (msg.role === "toolResult") {
      const toolResults = [];
      toolResults.push({
        type: "tool_result",
        tool_use_id: msg.toolCallId,
        content: convertContentBlocks(msg.content),
        is_error: msg.isError
      });
      let j3 = i7 + 1;
      while (j3 < transformedMessages.length && transformedMessages[j3].role === "toolResult") {
        const nextMsg = transformedMessages[j3];
        toolResults.push({
          type: "tool_result",
          tool_use_id: nextMsg.toolCallId,
          content: convertContentBlocks(nextMsg.content),
          is_error: nextMsg.isError
        });
        j3++;
      }
      i7 = j3 - 1;
      params.push({
        role: "user",
        content: toolResults
      });
    }
  }
  if (cacheControl && params.length > 0) {
    const lastMessage = params[params.length - 1];
    if (lastMessage.role === "user") {
      if (Array.isArray(lastMessage.content)) {
        const lastBlock = lastMessage.content[lastMessage.content.length - 1];
        if (lastBlock && (lastBlock.type === "text" || lastBlock.type === "image" || lastBlock.type === "tool_result")) {
          lastBlock.cache_control = cacheControl;
        }
      } else if (typeof lastMessage.content === "string") {
        lastMessage.content = [
          {
            type: "text",
            text: lastMessage.content,
            cache_control: cacheControl
          }
        ];
      }
    }
  }
  return params;
}
function convertTools(tools, isOAuthToken2) {
  if (!tools)
    return [];
  return tools.map((tool) => {
    const jsonSchema = tool.parameters;
    return {
      name: isOAuthToken2 ? toClaudeCodeName(tool.name) : tool.name,
      description: tool.description,
      input_schema: {
        type: "object",
        properties: jsonSchema.properties || {},
        required: jsonSchema.required || []
      }
    };
  });
}
function mapStopReason(reason) {
  switch (reason) {
    case "end_turn":
      return "stop";
    case "max_tokens":
      return "length";
    case "tool_use":
      return "toolUse";
    case "refusal":
      return "error";
    case "pause_turn":
      return "stop";
    case "stop_sequence":
      return "stop";
    // We don't supply stop sequences, so this should never happen
    case "sensitive":
      return "error";
    default:
      throw new Error(`Unhandled stop reason: ${reason}`);
  }
}

// ../pi-mono/packages/ai/dist/providers/azure-openai-responses.js
init_process_shim();

// ../pi-mono/node_modules/openai/index.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/client.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/internal/tslib.mjs
init_process_shim();
function __classPrivateFieldSet2(receiver, state, value, kind, f4) {
  if (kind === "m")
    throw new TypeError("Private method is not writable");
  if (kind === "a" && !f4)
    throw new TypeError("Private accessor was defined without a setter");
  if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver))
    throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return kind === "a" ? f4.call(receiver, value) : f4 ? f4.value = value : state.set(receiver, value), value;
}
function __classPrivateFieldGet2(receiver, state, kind, f4) {
  if (kind === "a" && !f4)
    throw new TypeError("Private accessor was defined without a getter");
  if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver))
    throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return kind === "m" ? f4 : kind === "a" ? f4.call(receiver) : f4 ? f4.value : state.get(receiver);
}

// ../pi-mono/node_modules/openai/internal/utils/uuid.mjs
init_process_shim();
var uuid42 = function() {
  const { crypto: crypto2 } = globalThis;
  if (crypto2?.randomUUID) {
    uuid42 = crypto2.randomUUID.bind(crypto2);
    return crypto2.randomUUID();
  }
  const u8 = new Uint8Array(1);
  const randomByte = crypto2 ? () => crypto2.getRandomValues(u8)[0] : () => Math.random() * 255 & 255;
  return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c6) => (+c6 ^ randomByte() & 15 >> +c6 / 4).toString(16));
};

// ../pi-mono/node_modules/openai/internal/utils/values.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/core/error.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/internal/errors.mjs
init_process_shim();
function isAbortError2(err) {
  return typeof err === "object" && err !== null && // Spec-compliant fetch implementations
  ("name" in err && err.name === "AbortError" || // Expo fetch
  "message" in err && String(err.message).includes("FetchRequestCanceledException"));
}
var castToError2 = (err) => {
  if (err instanceof Error)
    return err;
  if (typeof err === "object" && err !== null) {
    try {
      if (Object.prototype.toString.call(err) === "[object Error]") {
        const error = new Error(err.message, err.cause ? { cause: err.cause } : {});
        if (err.stack)
          error.stack = err.stack;
        if (err.cause && !error.cause)
          error.cause = err.cause;
        if (err.name)
          error.name = err.name;
        return error;
      }
    } catch {
    }
    try {
      return new Error(JSON.stringify(err));
    } catch {
    }
  }
  return new Error(err);
};

// ../pi-mono/node_modules/openai/core/error.mjs
var OpenAIError = class extends Error {
};
var APIError2 = class _APIError extends OpenAIError {
  constructor(status, error, message, headers) {
    super(`${_APIError.makeMessage(status, error, message)}`);
    this.status = status;
    this.headers = headers;
    this.requestID = headers?.get("x-request-id");
    this.error = error;
    const data = error;
    this.code = data?.["code"];
    this.param = data?.["param"];
    this.type = data?.["type"];
  }
  static makeMessage(status, error, message) {
    const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
    if (status && msg) {
      return `${status} ${msg}`;
    }
    if (status) {
      return `${status} status code (no body)`;
    }
    if (msg) {
      return msg;
    }
    return "(no status code or body)";
  }
  static generate(status, errorResponse, message, headers) {
    if (!status || !headers) {
      return new APIConnectionError2({ message, cause: castToError2(errorResponse) });
    }
    const error = errorResponse?.["error"];
    if (status === 400) {
      return new BadRequestError2(status, error, message, headers);
    }
    if (status === 401) {
      return new AuthenticationError2(status, error, message, headers);
    }
    if (status === 403) {
      return new PermissionDeniedError2(status, error, message, headers);
    }
    if (status === 404) {
      return new NotFoundError2(status, error, message, headers);
    }
    if (status === 409) {
      return new ConflictError2(status, error, message, headers);
    }
    if (status === 422) {
      return new UnprocessableEntityError2(status, error, message, headers);
    }
    if (status === 429) {
      return new RateLimitError2(status, error, message, headers);
    }
    if (status >= 500) {
      return new InternalServerError2(status, error, message, headers);
    }
    return new _APIError(status, error, message, headers);
  }
};
var APIUserAbortError2 = class extends APIError2 {
  constructor({ message } = {}) {
    super(void 0, void 0, message || "Request was aborted.", void 0);
  }
};
var APIConnectionError2 = class extends APIError2 {
  constructor({ message, cause }) {
    super(void 0, void 0, message || "Connection error.", void 0);
    if (cause)
      this.cause = cause;
  }
};
var APIConnectionTimeoutError2 = class extends APIConnectionError2 {
  constructor({ message } = {}) {
    super({ message: message ?? "Request timed out." });
  }
};
var BadRequestError2 = class extends APIError2 {
};
var AuthenticationError2 = class extends APIError2 {
};
var PermissionDeniedError2 = class extends APIError2 {
};
var NotFoundError2 = class extends APIError2 {
};
var ConflictError2 = class extends APIError2 {
};
var UnprocessableEntityError2 = class extends APIError2 {
};
var RateLimitError2 = class extends APIError2 {
};
var InternalServerError2 = class extends APIError2 {
};
var LengthFinishReasonError = class extends OpenAIError {
  constructor() {
    super(`Could not parse response content as the length limit was reached`);
  }
};
var ContentFilterFinishReasonError = class extends OpenAIError {
  constructor() {
    super(`Could not parse response content as the request was rejected by the content filter`);
  }
};
var InvalidWebhookSignatureError = class extends Error {
  constructor(message) {
    super(message);
  }
};

// ../pi-mono/node_modules/openai/internal/utils/values.mjs
var startsWithSchemeRegexp2 = /^[a-z][a-z0-9+.-]*:/i;
var isAbsoluteURL2 = (url) => {
  return startsWithSchemeRegexp2.test(url);
};
var isArray2 = (val2) => (isArray2 = Array.isArray, isArray2(val2));
var isReadonlyArray2 = isArray2;
function maybeObj2(x2) {
  if (typeof x2 !== "object") {
    return {};
  }
  return x2 ?? {};
}
function isEmptyObj2(obj) {
  if (!obj)
    return true;
  for (const _k in obj)
    return false;
  return true;
}
function hasOwn2(obj, key) {
  return Object.prototype.hasOwnProperty.call(obj, key);
}
function isObj(obj) {
  return obj != null && typeof obj === "object" && !Array.isArray(obj);
}
var validatePositiveInteger2 = (name, n7) => {
  if (typeof n7 !== "number" || !Number.isInteger(n7)) {
    throw new OpenAIError(`${name} must be an integer`);
  }
  if (n7 < 0) {
    throw new OpenAIError(`${name} must be a positive integer`);
  }
  return n7;
};
var safeJSON2 = (text3) => {
  try {
    return JSON.parse(text3);
  } catch (err) {
    return void 0;
  }
};

// ../pi-mono/node_modules/openai/internal/utils/sleep.mjs
init_process_shim();
var sleep2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

// ../pi-mono/node_modules/openai/internal/detect-platform.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/version.mjs
init_process_shim();
var VERSION2 = "6.26.0";

// ../pi-mono/node_modules/openai/internal/detect-platform.mjs
var isRunningInBrowser2 = () => {
  return (
    // @ts-ignore
    typeof window !== "undefined" && // @ts-ignore
    typeof window.document !== "undefined" && // @ts-ignore
    typeof navigator !== "undefined"
  );
};
function getDetectedPlatform2() {
  if (typeof Deno !== "undefined" && Deno.build != null) {
    return "deno";
  }
  if (typeof EdgeRuntime !== "undefined") {
    return "edge";
  }
  if (Object.prototype.toString.call(typeof globalThis.process !== "undefined" ? globalThis.process : 0) === "[object process]") {
    return "node";
  }
  return "unknown";
}
var getPlatformProperties2 = () => {
  const detectedPlatform = getDetectedPlatform2();
  if (detectedPlatform === "deno") {
    return {
      "X-Stainless-Lang": "js",
      "X-Stainless-Package-Version": VERSION2,
      "X-Stainless-OS": normalizePlatform2(Deno.build.os),
      "X-Stainless-Arch": normalizeArch2(Deno.build.arch),
      "X-Stainless-Runtime": "deno",
      "X-Stainless-Runtime-Version": typeof Deno.version === "string" ? Deno.version : Deno.version?.deno ?? "unknown"
    };
  }
  if (typeof EdgeRuntime !== "undefined") {
    return {
      "X-Stainless-Lang": "js",
      "X-Stainless-Package-Version": VERSION2,
      "X-Stainless-OS": "Unknown",
      "X-Stainless-Arch": `other:${EdgeRuntime}`,
      "X-Stainless-Runtime": "edge",
      "X-Stainless-Runtime-Version": globalThis.process.version
    };
  }
  if (detectedPlatform === "node") {
    return {
      "X-Stainless-Lang": "js",
      "X-Stainless-Package-Version": VERSION2,
      "X-Stainless-OS": normalizePlatform2(globalThis.process.platform ?? "unknown"),
      "X-Stainless-Arch": normalizeArch2(globalThis.process.arch ?? "unknown"),
      "X-Stainless-Runtime": "node",
      "X-Stainless-Runtime-Version": globalThis.process.version ?? "unknown"
    };
  }
  const browserInfo = getBrowserInfo2();
  if (browserInfo) {
    return {
      "X-Stainless-Lang": "js",
      "X-Stainless-Package-Version": VERSION2,
      "X-Stainless-OS": "Unknown",
      "X-Stainless-Arch": "unknown",
      "X-Stainless-Runtime": `browser:${browserInfo.browser}`,
      "X-Stainless-Runtime-Version": browserInfo.version
    };
  }
  return {
    "X-Stainless-Lang": "js",
    "X-Stainless-Package-Version": VERSION2,
    "X-Stainless-OS": "Unknown",
    "X-Stainless-Arch": "unknown",
    "X-Stainless-Runtime": "unknown",
    "X-Stainless-Runtime-Version": "unknown"
  };
};
function getBrowserInfo2() {
  if (typeof navigator === "undefined" || !navigator) {
    return null;
  }
  const browserPatterns = [
    { key: "edge", pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
    { key: "ie", pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
    { key: "ie", pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ },
    { key: "chrome", pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
    { key: "firefox", pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
    { key: "safari", pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ }
  ];
  for (const { key, pattern } of browserPatterns) {
    const match2 = pattern.exec(navigator.userAgent);
    if (match2) {
      const major = match2[1] || 0;
      const minor = match2[2] || 0;
      const patch = match2[3] || 0;
      return { browser: key, version: `${major}.${minor}.${patch}` };
    }
  }
  return null;
}
var normalizeArch2 = (arch) => {
  if (arch === "x32")
    return "x32";
  if (arch === "x86_64" || arch === "x64")
    return "x64";
  if (arch === "arm")
    return "arm";
  if (arch === "aarch64" || arch === "arm64")
    return "arm64";
  if (arch)
    return `other:${arch}`;
  return "unknown";
};
var normalizePlatform2 = (platform) => {
  platform = platform.toLowerCase();
  if (platform.includes("ios"))
    return "iOS";
  if (platform === "android")
    return "Android";
  if (platform === "darwin")
    return "MacOS";
  if (platform === "win32")
    return "Windows";
  if (platform === "freebsd")
    return "FreeBSD";
  if (platform === "openbsd")
    return "OpenBSD";
  if (platform === "linux")
    return "Linux";
  if (platform)
    return `Other:${platform}`;
  return "Unknown";
};
var _platformHeaders2;
var getPlatformHeaders2 = () => {
  return _platformHeaders2 ?? (_platformHeaders2 = getPlatformProperties2());
};

// ../pi-mono/node_modules/openai/internal/shims.mjs
init_process_shim();
function getDefaultFetch2() {
  if (typeof fetch !== "undefined") {
    return fetch;
  }
  throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`");
}
function makeReadableStream2(...args) {
  const ReadableStream2 = globalThis.ReadableStream;
  if (typeof ReadableStream2 === "undefined") {
    throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");
  }
  return new ReadableStream2(...args);
}
function ReadableStreamFrom2(iterable) {
  let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator]();
  return makeReadableStream2({
    start() {
    },
    async pull(controller) {
      const { done, value } = await iter.next();
      if (done) {
        controller.close();
      } else {
        controller.enqueue(value);
      }
    },
    async cancel() {
      await iter.return?.();
    }
  });
}
function ReadableStreamToAsyncIterable2(stream2) {
  if (stream2[Symbol.asyncIterator])
    return stream2;
  const reader = stream2.getReader();
  return {
    async next() {
      try {
        const result = await reader.read();
        if (result?.done)
          reader.releaseLock();
        return result;
      } catch (e9) {
        reader.releaseLock();
        throw e9;
      }
    },
    async return() {
      const cancelPromise = reader.cancel();
      reader.releaseLock();
      await cancelPromise;
      return { done: true, value: void 0 };
    },
    [Symbol.asyncIterator]() {
      return this;
    }
  };
}
async function CancelReadableStream2(stream2) {
  if (stream2 === null || typeof stream2 !== "object")
    return;
  if (stream2[Symbol.asyncIterator]) {
    await stream2[Symbol.asyncIterator]().return?.();
    return;
  }
  const reader = stream2.getReader();
  const cancelPromise = reader.cancel();
  reader.releaseLock();
  await cancelPromise;
}

// ../pi-mono/node_modules/openai/internal/request-options.mjs
init_process_shim();
var FallbackEncoder2 = ({ headers, body }) => {
  return {
    bodyHeaders: {
      "content-type": "application/json"
    },
    body: JSON.stringify(body)
  };
};

// ../pi-mono/node_modules/openai/internal/utils/query.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/internal/qs/stringify.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/internal/qs/utils.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/internal/qs/formats.mjs
init_process_shim();
var default_format = "RFC3986";
var default_formatter = (v4) => String(v4);
var formatters = {
  RFC1738: (v4) => String(v4).replace(/%20/g, "+"),
  RFC3986: default_formatter
};
var RFC1738 = "RFC1738";

// ../pi-mono/node_modules/openai/internal/qs/utils.mjs
var has = (obj, key) => (has = Object.hasOwn ?? Function.prototype.call.bind(Object.prototype.hasOwnProperty), has(obj, key));
var hex_table = /* @__PURE__ */ (() => {
  const array = [];
  for (let i7 = 0; i7 < 256; ++i7) {
    array.push("%" + ((i7 < 16 ? "0" : "") + i7.toString(16)).toUpperCase());
  }
  return array;
})();
var limit = 1024;
var encode = (str2, _defaultEncoder, charset, _kind, format) => {
  if (str2.length === 0) {
    return str2;
  }
  let string = str2;
  if (typeof str2 === "symbol") {
    string = Symbol.prototype.toString.call(str2);
  } else if (typeof str2 !== "string") {
    string = String(str2);
  }
  if (charset === "iso-8859-1") {
    return escape(string).replace(/%u[0-9a-f]{4}/gi, function($0) {
      return "%26%23" + parseInt($0.slice(2), 16) + "%3B";
    });
  }
  let out = "";
  for (let j3 = 0; j3 < string.length; j3 += limit) {
    const segment = string.length >= limit ? string.slice(j3, j3 + limit) : string;
    const arr = [];
    for (let i7 = 0; i7 < segment.length; ++i7) {
      let c6 = segment.charCodeAt(i7);
      if (c6 === 45 || // -
      c6 === 46 || // .
      c6 === 95 || // _
      c6 === 126 || // ~
      c6 >= 48 && c6 <= 57 || // 0-9
      c6 >= 65 && c6 <= 90 || // a-z
      c6 >= 97 && c6 <= 122 || // A-Z
      format === RFC1738 && (c6 === 40 || c6 === 41)) {
        arr[arr.length] = segment.charAt(i7);
        continue;
      }
      if (c6 < 128) {
        arr[arr.length] = hex_table[c6];
        continue;
      }
      if (c6 < 2048) {
        arr[arr.length] = hex_table[192 | c6 >> 6] + hex_table[128 | c6 & 63];
        continue;
      }
      if (c6 < 55296 || c6 >= 57344) {
        arr[arr.length] = hex_table[224 | c6 >> 12] + hex_table[128 | c6 >> 6 & 63] + hex_table[128 | c6 & 63];
        continue;
      }
      i7 += 1;
      c6 = 65536 + ((c6 & 1023) << 10 | segment.charCodeAt(i7) & 1023);
      arr[arr.length] = hex_table[240 | c6 >> 18] + hex_table[128 | c6 >> 12 & 63] + hex_table[128 | c6 >> 6 & 63] + hex_table[128 | c6 & 63];
    }
    out += arr.join("");
  }
  return out;
};
function is_buffer(obj) {
  if (!obj || typeof obj !== "object") {
    return false;
  }
  return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));
}
function maybe_map(val2, fn) {
  if (isArray2(val2)) {
    const mapped = [];
    for (let i7 = 0; i7 < val2.length; i7 += 1) {
      mapped.push(fn(val2[i7]));
    }
    return mapped;
  }
  return fn(val2);
}

// ../pi-mono/node_modules/openai/internal/qs/stringify.mjs
var array_prefix_generators = {
  brackets(prefix) {
    return String(prefix) + "[]";
  },
  comma: "comma",
  indices(prefix, key) {
    return String(prefix) + "[" + key + "]";
  },
  repeat(prefix) {
    return String(prefix);
  }
};
var push_to_array = function(arr, value_or_array) {
  Array.prototype.push.apply(arr, isArray2(value_or_array) ? value_or_array : [value_or_array]);
};
var toISOString;
var defaults = {
  addQueryPrefix: false,
  allowDots: false,
  allowEmptyArrays: false,
  arrayFormat: "indices",
  charset: "utf-8",
  charsetSentinel: false,
  delimiter: "&",
  encode: true,
  encodeDotInKeys: false,
  encoder: encode,
  encodeValuesOnly: false,
  format: default_format,
  formatter: default_formatter,
  /** @deprecated */
  indices: false,
  serializeDate(date) {
    return (toISOString ?? (toISOString = Function.prototype.call.bind(Date.prototype.toISOString)))(date);
  },
  skipNulls: false,
  strictNullHandling: false
};
function is_non_nullish_primitive(v4) {
  return typeof v4 === "string" || typeof v4 === "number" || typeof v4 === "boolean" || typeof v4 === "symbol" || typeof v4 === "bigint";
}
var sentinel = {};
function inner_stringify(object, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder, filter2, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) {
  let obj = object;
  let tmp_sc = sideChannel;
  let step = 0;
  let find_flag = false;
  while ((tmp_sc = tmp_sc.get(sentinel)) !== void 0 && !find_flag) {
    const pos = tmp_sc.get(object);
    step += 1;
    if (typeof pos !== "undefined") {
      if (pos === step) {
        throw new RangeError("Cyclic object value");
      } else {
        find_flag = true;
      }
    }
    if (typeof tmp_sc.get(sentinel) === "undefined") {
      step = 0;
    }
  }
  if (typeof filter2 === "function") {
    obj = filter2(prefix, obj);
  } else if (obj instanceof Date) {
    obj = serializeDate?.(obj);
  } else if (generateArrayPrefix === "comma" && isArray2(obj)) {
    obj = maybe_map(obj, function(value) {
      if (value instanceof Date) {
        return serializeDate?.(value);
      }
      return value;
    });
  }
  if (obj === null) {
    if (strictNullHandling) {
      return encoder && !encodeValuesOnly ? (
        // @ts-expect-error
        encoder(prefix, defaults.encoder, charset, "key", format)
      ) : prefix;
    }
    obj = "";
  }
  if (is_non_nullish_primitive(obj) || is_buffer(obj)) {
    if (encoder) {
      const key_value = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, "key", format);
      return [
        formatter?.(key_value) + "=" + // @ts-expect-error
        formatter?.(encoder(obj, defaults.encoder, charset, "value", format))
      ];
    }
    return [formatter?.(prefix) + "=" + formatter?.(String(obj))];
  }
  const values2 = [];
  if (typeof obj === "undefined") {
    return values2;
  }
  let obj_keys;
  if (generateArrayPrefix === "comma" && isArray2(obj)) {
    if (encodeValuesOnly && encoder) {
      obj = maybe_map(obj, encoder);
    }
    obj_keys = [{ value: obj.length > 0 ? obj.join(",") || null : void 0 }];
  } else if (isArray2(filter2)) {
    obj_keys = filter2;
  } else {
    const keys2 = Object.keys(obj);
    obj_keys = sort ? keys2.sort(sort) : keys2;
  }
  const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\./g, "%2E") : String(prefix);
  const adjusted_prefix = commaRoundTrip && isArray2(obj) && obj.length === 1 ? encoded_prefix + "[]" : encoded_prefix;
  if (allowEmptyArrays && isArray2(obj) && obj.length === 0) {
    return adjusted_prefix + "[]";
  }
  for (let j3 = 0; j3 < obj_keys.length; ++j3) {
    const key = obj_keys[j3];
    const value = (
      // @ts-ignore
      typeof key === "object" && typeof key.value !== "undefined" ? key.value : obj[key]
    );
    if (skipNulls && value === null) {
      continue;
    }
    const encoded_key = allowDots && encodeDotInKeys ? key.replace(/\./g, "%2E") : key;
    const key_prefix = isArray2(obj) ? typeof generateArrayPrefix === "function" ? generateArrayPrefix(adjusted_prefix, encoded_key) : adjusted_prefix : adjusted_prefix + (allowDots ? "." + encoded_key : "[" + encoded_key + "]");
    sideChannel.set(object, step);
    const valueSideChannel = /* @__PURE__ */ new WeakMap();
    valueSideChannel.set(sentinel, sideChannel);
    push_to_array(values2, inner_stringify(
      value,
      key_prefix,
      generateArrayPrefix,
      commaRoundTrip,
      allowEmptyArrays,
      strictNullHandling,
      skipNulls,
      encodeDotInKeys,
      // @ts-ignore
      generateArrayPrefix === "comma" && encodeValuesOnly && isArray2(obj) ? null : encoder,
      filter2,
      sort,
      allowDots,
      serializeDate,
      format,
      formatter,
      encodeValuesOnly,
      charset,
      valueSideChannel
    ));
  }
  return values2;
}
function normalize_stringify_options(opts = defaults) {
  if (typeof opts.allowEmptyArrays !== "undefined" && typeof opts.allowEmptyArrays !== "boolean") {
    throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");
  }
  if (typeof opts.encodeDotInKeys !== "undefined" && typeof opts.encodeDotInKeys !== "boolean") {
    throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");
  }
  if (opts.encoder !== null && typeof opts.encoder !== "undefined" && typeof opts.encoder !== "function") {
    throw new TypeError("Encoder has to be a function.");
  }
  const charset = opts.charset || defaults.charset;
  if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") {
    throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");
  }
  let format = default_format;
  if (typeof opts.format !== "undefined") {
    if (!has(formatters, opts.format)) {
      throw new TypeError("Unknown format option provided.");
    }
    format = opts.format;
  }
  const formatter = formatters[format];
  let filter2 = defaults.filter;
  if (typeof opts.filter === "function" || isArray2(opts.filter)) {
    filter2 = opts.filter;
  }
  let arrayFormat;
  if (opts.arrayFormat && opts.arrayFormat in array_prefix_generators) {
    arrayFormat = opts.arrayFormat;
  } else if ("indices" in opts) {
    arrayFormat = opts.indices ? "indices" : "repeat";
  } else {
    arrayFormat = defaults.arrayFormat;
  }
  if ("commaRoundTrip" in opts && typeof opts.commaRoundTrip !== "boolean") {
    throw new TypeError("`commaRoundTrip` must be a boolean, or absent");
  }
  const allowDots = typeof opts.allowDots === "undefined" ? !!opts.encodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots;
  return {
    addQueryPrefix: typeof opts.addQueryPrefix === "boolean" ? opts.addQueryPrefix : defaults.addQueryPrefix,
    // @ts-ignore
    allowDots,
    allowEmptyArrays: typeof opts.allowEmptyArrays === "boolean" ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays,
    arrayFormat,
    charset,
    charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults.charsetSentinel,
    commaRoundTrip: !!opts.commaRoundTrip,
    delimiter: typeof opts.delimiter === "undefined" ? defaults.delimiter : opts.delimiter,
    encode: typeof opts.encode === "boolean" ? opts.encode : defaults.encode,
    encodeDotInKeys: typeof opts.encodeDotInKeys === "boolean" ? opts.encodeDotInKeys : defaults.encodeDotInKeys,
    encoder: typeof opts.encoder === "function" ? opts.encoder : defaults.encoder,
    encodeValuesOnly: typeof opts.encodeValuesOnly === "boolean" ? opts.encodeValuesOnly : defaults.encodeValuesOnly,
    filter: filter2,
    format,
    formatter,
    serializeDate: typeof opts.serializeDate === "function" ? opts.serializeDate : defaults.serializeDate,
    skipNulls: typeof opts.skipNulls === "boolean" ? opts.skipNulls : defaults.skipNulls,
    // @ts-ignore
    sort: typeof opts.sort === "function" ? opts.sort : null,
    strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults.strictNullHandling
  };
}
function stringify(object, opts = {}) {
  let obj = object;
  const options = normalize_stringify_options(opts);
  let obj_keys;
  let filter2;
  if (typeof options.filter === "function") {
    filter2 = options.filter;
    obj = filter2("", obj);
  } else if (isArray2(options.filter)) {
    filter2 = options.filter;
    obj_keys = filter2;
  }
  const keys2 = [];
  if (typeof obj !== "object" || obj === null) {
    return "";
  }
  const generateArrayPrefix = array_prefix_generators[options.arrayFormat];
  const commaRoundTrip = generateArrayPrefix === "comma" && options.commaRoundTrip;
  if (!obj_keys) {
    obj_keys = Object.keys(obj);
  }
  if (options.sort) {
    obj_keys.sort(options.sort);
  }
  const sideChannel = /* @__PURE__ */ new WeakMap();
  for (let i7 = 0; i7 < obj_keys.length; ++i7) {
    const key = obj_keys[i7];
    if (options.skipNulls && obj[key] === null) {
      continue;
    }
    push_to_array(keys2, inner_stringify(
      obj[key],
      key,
      // @ts-expect-error
      generateArrayPrefix,
      commaRoundTrip,
      options.allowEmptyArrays,
      options.strictNullHandling,
      options.skipNulls,
      options.encodeDotInKeys,
      options.encode ? options.encoder : null,
      options.filter,
      options.sort,
      options.allowDots,
      options.serializeDate,
      options.format,
      options.formatter,
      options.encodeValuesOnly,
      options.charset,
      sideChannel
    ));
  }
  const joined = keys2.join(options.delimiter);
  let prefix = options.addQueryPrefix === true ? "?" : "";
  if (options.charsetSentinel) {
    if (options.charset === "iso-8859-1") {
      prefix += "utf8=%26%2310003%3B&";
    } else {
      prefix += "utf8=%E2%9C%93&";
    }
  }
  return joined.length > 0 ? prefix + joined : "";
}

// ../pi-mono/node_modules/openai/internal/utils/query.mjs
function stringifyQuery(query) {
  return stringify(query, { arrayFormat: "brackets" });
}

// ../pi-mono/node_modules/openai/core/pagination.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/internal/parse.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/core/streaming.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/internal/decoders/line.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/internal/utils/bytes.mjs
init_process_shim();
function concatBytes2(buffers) {
  let length = 0;
  for (const buffer of buffers) {
    length += buffer.length;
  }
  const output = new Uint8Array(length);
  let index = 0;
  for (const buffer of buffers) {
    output.set(buffer, index);
    index += buffer.length;
  }
  return output;
}
var encodeUTF8_2;
function encodeUTF82(str2) {
  let encoder;
  return (encodeUTF8_2 ?? (encoder = new globalThis.TextEncoder(), encodeUTF8_2 = encoder.encode.bind(encoder)))(str2);
}
var decodeUTF8_2;
function decodeUTF82(bytes) {
  let decoder;
  return (decodeUTF8_2 ?? (decoder = new globalThis.TextDecoder(), decodeUTF8_2 = decoder.decode.bind(decoder)))(bytes);
}

// ../pi-mono/node_modules/openai/internal/decoders/line.mjs
var _LineDecoder_buffer2;
var _LineDecoder_carriageReturnIndex2;
var LineDecoder2 = class {
  constructor() {
    _LineDecoder_buffer2.set(this, void 0);
    _LineDecoder_carriageReturnIndex2.set(this, void 0);
    __classPrivateFieldSet2(this, _LineDecoder_buffer2, new Uint8Array(), "f");
    __classPrivateFieldSet2(this, _LineDecoder_carriageReturnIndex2, null, "f");
  }
  decode(chunk) {
    if (chunk == null) {
      return [];
    }
    const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? encodeUTF82(chunk) : chunk;
    __classPrivateFieldSet2(this, _LineDecoder_buffer2, concatBytes2([__classPrivateFieldGet2(this, _LineDecoder_buffer2, "f"), binaryChunk]), "f");
    const lines = [];
    let patternIndex;
    while ((patternIndex = findNewlineIndex2(__classPrivateFieldGet2(this, _LineDecoder_buffer2, "f"), __classPrivateFieldGet2(this, _LineDecoder_carriageReturnIndex2, "f"))) != null) {
      if (patternIndex.carriage && __classPrivateFieldGet2(this, _LineDecoder_carriageReturnIndex2, "f") == null) {
        __classPrivateFieldSet2(this, _LineDecoder_carriageReturnIndex2, patternIndex.index, "f");
        continue;
      }
      if (__classPrivateFieldGet2(this, _LineDecoder_carriageReturnIndex2, "f") != null && (patternIndex.index !== __classPrivateFieldGet2(this, _LineDecoder_carriageReturnIndex2, "f") + 1 || patternIndex.carriage)) {
        lines.push(decodeUTF82(__classPrivateFieldGet2(this, _LineDecoder_buffer2, "f").subarray(0, __classPrivateFieldGet2(this, _LineDecoder_carriageReturnIndex2, "f") - 1)));
        __classPrivateFieldSet2(this, _LineDecoder_buffer2, __classPrivateFieldGet2(this, _LineDecoder_buffer2, "f").subarray(__classPrivateFieldGet2(this, _LineDecoder_carriageReturnIndex2, "f")), "f");
        __classPrivateFieldSet2(this, _LineDecoder_carriageReturnIndex2, null, "f");
        continue;
      }
      const endIndex = __classPrivateFieldGet2(this, _LineDecoder_carriageReturnIndex2, "f") !== null ? patternIndex.preceding - 1 : patternIndex.preceding;
      const line = decodeUTF82(__classPrivateFieldGet2(this, _LineDecoder_buffer2, "f").subarray(0, endIndex));
      lines.push(line);
      __classPrivateFieldSet2(this, _LineDecoder_buffer2, __classPrivateFieldGet2(this, _LineDecoder_buffer2, "f").subarray(patternIndex.index), "f");
      __classPrivateFieldSet2(this, _LineDecoder_carriageReturnIndex2, null, "f");
    }
    return lines;
  }
  flush() {
    if (!__classPrivateFieldGet2(this, _LineDecoder_buffer2, "f").length) {
      return [];
    }
    return this.decode("\n");
  }
};
_LineDecoder_buffer2 = /* @__PURE__ */ new WeakMap(), _LineDecoder_carriageReturnIndex2 = /* @__PURE__ */ new WeakMap();
LineDecoder2.NEWLINE_CHARS = /* @__PURE__ */ new Set(["\n", "\r"]);
LineDecoder2.NEWLINE_REGEXP = /\r\n|[\n\r]/g;
function findNewlineIndex2(buffer, startIndex) {
  const newline = 10;
  const carriage = 13;
  for (let i7 = startIndex ?? 0; i7 < buffer.length; i7++) {
    if (buffer[i7] === newline) {
      return { preceding: i7, index: i7 + 1, carriage: false };
    }
    if (buffer[i7] === carriage) {
      return { preceding: i7, index: i7 + 1, carriage: true };
    }
  }
  return null;
}
function findDoubleNewlineIndex2(buffer) {
  const newline = 10;
  const carriage = 13;
  for (let i7 = 0; i7 < buffer.length - 1; i7++) {
    if (buffer[i7] === newline && buffer[i7 + 1] === newline) {
      return i7 + 2;
    }
    if (buffer[i7] === carriage && buffer[i7 + 1] === carriage) {
      return i7 + 2;
    }
    if (buffer[i7] === carriage && buffer[i7 + 1] === newline && i7 + 3 < buffer.length && buffer[i7 + 2] === carriage && buffer[i7 + 3] === newline) {
      return i7 + 4;
    }
  }
  return -1;
}

// ../pi-mono/node_modules/openai/internal/utils/log.mjs
init_process_shim();
var levelNumbers2 = {
  off: 0,
  error: 200,
  warn: 300,
  info: 400,
  debug: 500
};
var parseLogLevel2 = (maybeLevel, sourceName, client) => {
  if (!maybeLevel) {
    return void 0;
  }
  if (hasOwn2(levelNumbers2, maybeLevel)) {
    return maybeLevel;
  }
  loggerFor2(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers2))}`);
  return void 0;
};
function noop2() {
}
function makeLogFn2(fnLevel, logger2, logLevel) {
  if (!logger2 || levelNumbers2[fnLevel] > levelNumbers2[logLevel]) {
    return noop2;
  } else {
    return logger2[fnLevel].bind(logger2);
  }
}
var noopLogger2 = {
  error: noop2,
  warn: noop2,
  info: noop2,
  debug: noop2
};
var cachedLoggers2 = /* @__PURE__ */ new WeakMap();
function loggerFor2(client) {
  const logger2 = client.logger;
  const logLevel = client.logLevel ?? "off";
  if (!logger2) {
    return noopLogger2;
  }
  const cachedLogger = cachedLoggers2.get(logger2);
  if (cachedLogger && cachedLogger[0] === logLevel) {
    return cachedLogger[1];
  }
  const levelLogger = {
    error: makeLogFn2("error", logger2, logLevel),
    warn: makeLogFn2("warn", logger2, logLevel),
    info: makeLogFn2("info", logger2, logLevel),
    debug: makeLogFn2("debug", logger2, logLevel)
  };
  cachedLoggers2.set(logger2, [logLevel, levelLogger]);
  return levelLogger;
}
var formatRequestDetails2 = (details) => {
  if (details.options) {
    details.options = { ...details.options };
    delete details.options["headers"];
  }
  if (details.headers) {
    details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [
      name,
      name.toLowerCase() === "authorization" || name.toLowerCase() === "cookie" || name.toLowerCase() === "set-cookie" ? "***" : value
    ]));
  }
  if ("retryOfRequestLogID" in details) {
    if (details.retryOfRequestLogID) {
      details.retryOf = details.retryOfRequestLogID;
    }
    delete details.retryOfRequestLogID;
  }
  return details;
};

// ../pi-mono/node_modules/openai/core/streaming.mjs
var _Stream_client2;
var Stream2 = class _Stream {
  constructor(iterator, controller, client) {
    this.iterator = iterator;
    _Stream_client2.set(this, void 0);
    this.controller = controller;
    __classPrivateFieldSet2(this, _Stream_client2, client, "f");
  }
  static fromSSEResponse(response, controller, client, synthesizeEventData) {
    let consumed2 = false;
    const logger2 = client ? loggerFor2(client) : console;
    async function* iterator() {
      if (consumed2) {
        throw new OpenAIError("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
      }
      consumed2 = true;
      let done = false;
      try {
        for await (const sse of _iterSSEMessages2(response, controller)) {
          if (done)
            continue;
          if (sse.data.startsWith("[DONE]")) {
            done = true;
            continue;
          }
          if (sse.event === null || !sse.event.startsWith("thread.")) {
            let data;
            try {
              data = JSON.parse(sse.data);
            } catch (e9) {
              logger2.error(`Could not parse message into JSON:`, sse.data);
              logger2.error(`From chunk:`, sse.raw);
              throw e9;
            }
            if (data && data.error) {
              throw new APIError2(void 0, data.error, void 0, response.headers);
            }
            yield synthesizeEventData ? { event: sse.event, data } : data;
          } else {
            let data;
            try {
              data = JSON.parse(sse.data);
            } catch (e9) {
              console.error(`Could not parse message into JSON:`, sse.data);
              console.error(`From chunk:`, sse.raw);
              throw e9;
            }
            if (sse.event == "error") {
              throw new APIError2(void 0, data.error, data.message, void 0);
            }
            yield { event: sse.event, data };
          }
        }
        done = true;
      } catch (e9) {
        if (isAbortError2(e9))
          return;
        throw e9;
      } finally {
        if (!done)
          controller.abort();
      }
    }
    return new _Stream(iterator, controller, client);
  }
  /**
   * Generates a Stream from a newline-separated ReadableStream
   * where each item is a JSON value.
   */
  static fromReadableStream(readableStream, controller, client) {
    let consumed2 = false;
    async function* iterLines() {
      const lineDecoder = new LineDecoder2();
      const iter = ReadableStreamToAsyncIterable2(readableStream);
      for await (const chunk of iter) {
        for (const line of lineDecoder.decode(chunk)) {
          yield line;
        }
      }
      for (const line of lineDecoder.flush()) {
        yield line;
      }
    }
    async function* iterator() {
      if (consumed2) {
        throw new OpenAIError("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
      }
      consumed2 = true;
      let done = false;
      try {
        for await (const line of iterLines()) {
          if (done)
            continue;
          if (line)
            yield JSON.parse(line);
        }
        done = true;
      } catch (e9) {
        if (isAbortError2(e9))
          return;
        throw e9;
      } finally {
        if (!done)
          controller.abort();
      }
    }
    return new _Stream(iterator, controller, client);
  }
  [(_Stream_client2 = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() {
    return this.iterator();
  }
  /**
   * Splits the stream into two streams which can be
   * independently read from at different speeds.
   */
  tee() {
    const left = [];
    const right = [];
    const iterator = this.iterator();
    const teeIterator = (queue) => {
      return {
        next: () => {
          if (queue.length === 0) {
            const result = iterator.next();
            left.push(result);
            right.push(result);
          }
          return queue.shift();
        }
      };
    };
    return [
      new _Stream(() => teeIterator(left), this.controller, __classPrivateFieldGet2(this, _Stream_client2, "f")),
      new _Stream(() => teeIterator(right), this.controller, __classPrivateFieldGet2(this, _Stream_client2, "f"))
    ];
  }
  /**
   * Converts this stream to a newline-separated ReadableStream of
   * JSON stringified values in the stream
   * which can be turned back into a Stream with `Stream.fromReadableStream()`.
   */
  toReadableStream() {
    const self2 = this;
    let iter;
    return makeReadableStream2({
      async start() {
        iter = self2[Symbol.asyncIterator]();
      },
      async pull(ctrl) {
        try {
          const { value, done } = await iter.next();
          if (done)
            return ctrl.close();
          const bytes = encodeUTF82(JSON.stringify(value) + "\n");
          ctrl.enqueue(bytes);
        } catch (err) {
          ctrl.error(err);
        }
      },
      async cancel() {
        await iter.return?.();
      }
    });
  }
};
async function* _iterSSEMessages2(response, controller) {
  if (!response.body) {
    controller.abort();
    if (typeof globalThis.navigator !== "undefined" && globalThis.navigator.product === "ReactNative") {
      throw new OpenAIError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`);
    }
    throw new OpenAIError(`Attempted to iterate over a response with no body`);
  }
  const sseDecoder = new SSEDecoder2();
  const lineDecoder = new LineDecoder2();
  const iter = ReadableStreamToAsyncIterable2(response.body);
  for await (const sseChunk of iterSSEChunks2(iter)) {
    for (const line of lineDecoder.decode(sseChunk)) {
      const sse = sseDecoder.decode(line);
      if (sse)
        yield sse;
    }
  }
  for (const line of lineDecoder.flush()) {
    const sse = sseDecoder.decode(line);
    if (sse)
      yield sse;
  }
}
async function* iterSSEChunks2(iterator) {
  let data = new Uint8Array();
  for await (const chunk of iterator) {
    if (chunk == null) {
      continue;
    }
    const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? encodeUTF82(chunk) : chunk;
    let newData = new Uint8Array(data.length + binaryChunk.length);
    newData.set(data);
    newData.set(binaryChunk, data.length);
    data = newData;
    let patternIndex;
    while ((patternIndex = findDoubleNewlineIndex2(data)) !== -1) {
      yield data.slice(0, patternIndex);
      data = data.slice(patternIndex);
    }
  }
  if (data.length > 0) {
    yield data;
  }
}
var SSEDecoder2 = class {
  constructor() {
    this.event = null;
    this.data = [];
    this.chunks = [];
  }
  decode(line) {
    if (line.endsWith("\r")) {
      line = line.substring(0, line.length - 1);
    }
    if (!line) {
      if (!this.event && !this.data.length)
        return null;
      const sse = {
        event: this.event,
        data: this.data.join("\n"),
        raw: this.chunks
      };
      this.event = null;
      this.data = [];
      this.chunks = [];
      return sse;
    }
    this.chunks.push(line);
    if (line.startsWith(":")) {
      return null;
    }
    let [fieldname, _3, value] = partition2(line, ":");
    if (value.startsWith(" ")) {
      value = value.substring(1);
    }
    if (fieldname === "event") {
      this.event = value;
    } else if (fieldname === "data") {
      this.data.push(value);
    }
    return null;
  }
};
function partition2(str2, delimiter2) {
  const index = str2.indexOf(delimiter2);
  if (index !== -1) {
    return [str2.substring(0, index), delimiter2, str2.substring(index + delimiter2.length)];
  }
  return [str2, "", ""];
}

// ../pi-mono/node_modules/openai/internal/parse.mjs
async function defaultParseResponse2(client, props) {
  const { response, requestLogID, retryOfRequestLogID, startTime } = props;
  const body = await (async () => {
    if (props.options.stream) {
      loggerFor2(client).debug("response", response.status, response.url, response.headers, response.body);
      if (props.options.__streamClass) {
        return props.options.__streamClass.fromSSEResponse(response, props.controller, client, props.options.__synthesizeEventData);
      }
      return Stream2.fromSSEResponse(response, props.controller, client, props.options.__synthesizeEventData);
    }
    if (response.status === 204) {
      return null;
    }
    if (props.options.__binaryResponse) {
      return response;
    }
    const contentType = response.headers.get("content-type");
    const mediaType = contentType?.split(";")[0]?.trim();
    const isJSON = mediaType?.includes("application/json") || mediaType?.endsWith("+json");
    if (isJSON) {
      const contentLength = response.headers.get("content-length");
      if (contentLength === "0") {
        return void 0;
      }
      const json2 = await response.json();
      return addRequestID2(json2, response);
    }
    const text3 = await response.text();
    return text3;
  })();
  loggerFor2(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails2({
    retryOfRequestLogID,
    url: response.url,
    status: response.status,
    body,
    durationMs: Date.now() - startTime
  }));
  return body;
}
function addRequestID2(value, response) {
  if (!value || typeof value !== "object" || Array.isArray(value)) {
    return value;
  }
  return Object.defineProperty(value, "_request_id", {
    value: response.headers.get("x-request-id"),
    enumerable: false
  });
}

// ../pi-mono/node_modules/openai/core/api-promise.mjs
init_process_shim();
var _APIPromise_client2;
var APIPromise2 = class _APIPromise extends Promise {
  constructor(client, responsePromise, parseResponse2 = defaultParseResponse2) {
    super((resolve) => {
      resolve(null);
    });
    this.responsePromise = responsePromise;
    this.parseResponse = parseResponse2;
    _APIPromise_client2.set(this, void 0);
    __classPrivateFieldSet2(this, _APIPromise_client2, client, "f");
  }
  _thenUnwrap(transform) {
    return new _APIPromise(__classPrivateFieldGet2(this, _APIPromise_client2, "f"), this.responsePromise, async (client, props) => addRequestID2(transform(await this.parseResponse(client, props), props), props.response));
  }
  /**
   * Gets the raw `Response` instance instead of parsing the response
   * data.
   *
   * If you want to parse the response body but still get the `Response`
   * instance, you can use {@link withResponse()}.
   *
   * 👋 Getting the wrong TypeScript type for `Response`?
   * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
   * to your `tsconfig.json`.
   */
  asResponse() {
    return this.responsePromise.then((p4) => p4.response);
  }
  /**
   * Gets the parsed response data, the raw `Response` instance and the ID of the request,
   * returned via the X-Request-ID header which is useful for debugging requests and reporting
   * issues to OpenAI.
   *
   * If you just want to get the raw `Response` instance without parsing it,
   * you can use {@link asResponse()}.
   *
   * 👋 Getting the wrong TypeScript type for `Response`?
   * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
   * to your `tsconfig.json`.
   */
  async withResponse() {
    const [data, response] = await Promise.all([this.parse(), this.asResponse()]);
    return { data, response, request_id: response.headers.get("x-request-id") };
  }
  parse() {
    if (!this.parsedPromise) {
      this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(__classPrivateFieldGet2(this, _APIPromise_client2, "f"), data));
    }
    return this.parsedPromise;
  }
  then(onfulfilled, onrejected) {
    return this.parse().then(onfulfilled, onrejected);
  }
  catch(onrejected) {
    return this.parse().catch(onrejected);
  }
  finally(onfinally) {
    return this.parse().finally(onfinally);
  }
};
_APIPromise_client2 = /* @__PURE__ */ new WeakMap();

// ../pi-mono/node_modules/openai/core/pagination.mjs
var _AbstractPage_client2;
var AbstractPage2 = class {
  constructor(client, response, body, options) {
    _AbstractPage_client2.set(this, void 0);
    __classPrivateFieldSet2(this, _AbstractPage_client2, client, "f");
    this.options = options;
    this.response = response;
    this.body = body;
  }
  hasNextPage() {
    const items = this.getPaginatedItems();
    if (!items.length)
      return false;
    return this.nextPageRequestOptions() != null;
  }
  async getNextPage() {
    const nextOptions = this.nextPageRequestOptions();
    if (!nextOptions) {
      throw new OpenAIError("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");
    }
    return await __classPrivateFieldGet2(this, _AbstractPage_client2, "f").requestAPIList(this.constructor, nextOptions);
  }
  async *iterPages() {
    let page = this;
    yield page;
    while (page.hasNextPage()) {
      page = await page.getNextPage();
      yield page;
    }
  }
  async *[(_AbstractPage_client2 = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() {
    for await (const page of this.iterPages()) {
      for (const item of page.getPaginatedItems()) {
        yield item;
      }
    }
  }
};
var PagePromise2 = class extends APIPromise2 {
  constructor(client, request, Page3) {
    super(client, request, async (client2, props) => new Page3(client2, props.response, await defaultParseResponse2(client2, props), props.options));
  }
  /**
   * Allow auto-paginating iteration on an unawaited list call, eg:
   *
   *    for await (const item of client.items.list()) {
   *      console.log(item)
   *    }
   */
  async *[Symbol.asyncIterator]() {
    const page = await this;
    for await (const item of page) {
      yield item;
    }
  }
};
var Page2 = class extends AbstractPage2 {
  constructor(client, response, body, options) {
    super(client, response, body, options);
    this.data = body.data || [];
    this.object = body.object;
  }
  getPaginatedItems() {
    return this.data ?? [];
  }
  nextPageRequestOptions() {
    return null;
  }
};
var CursorPage = class extends AbstractPage2 {
  constructor(client, response, body, options) {
    super(client, response, body, options);
    this.data = body.data || [];
    this.has_more = body.has_more || false;
  }
  getPaginatedItems() {
    return this.data ?? [];
  }
  hasNextPage() {
    if (this.has_more === false) {
      return false;
    }
    return super.hasNextPage();
  }
  nextPageRequestOptions() {
    const data = this.getPaginatedItems();
    const id = data[data.length - 1]?.id;
    if (!id) {
      return null;
    }
    return {
      ...this.options,
      query: {
        ...maybeObj2(this.options.query),
        after: id
      }
    };
  }
};
var ConversationCursorPage = class extends AbstractPage2 {
  constructor(client, response, body, options) {
    super(client, response, body, options);
    this.data = body.data || [];
    this.has_more = body.has_more || false;
    this.last_id = body.last_id || "";
  }
  getPaginatedItems() {
    return this.data ?? [];
  }
  hasNextPage() {
    if (this.has_more === false) {
      return false;
    }
    return super.hasNextPage();
  }
  nextPageRequestOptions() {
    const cursor = this.last_id;
    if (!cursor) {
      return null;
    }
    return {
      ...this.options,
      query: {
        ...maybeObj2(this.options.query),
        after: cursor
      }
    };
  }
};

// ../pi-mono/node_modules/openai/core/uploads.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/internal/to-file.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/internal/uploads.mjs
init_process_shim();
var checkFileSupport2 = () => {
  if (typeof File === "undefined") {
    const { process: process2 } = globalThis;
    const isOldNode = typeof process2?.versions?.node === "string" && parseInt(process2.versions.node.split(".")) < 20;
    throw new Error("`File` is not defined as a global, which is required for file uploads." + (isOldNode ? " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`." : ""));
  }
};
function makeFile2(fileBits, fileName, options) {
  checkFileSupport2();
  return new File(fileBits, fileName ?? "unknown_file", options);
}
function getName2(value) {
  return (typeof value === "object" && value !== null && ("name" in value && value.name && String(value.name) || "url" in value && value.url && String(value.url) || "filename" in value && value.filename && String(value.filename) || "path" in value && value.path && String(value.path)) || "").split(/[\\/]/).pop() || void 0;
}
var isAsyncIterable2 = (value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function";
var maybeMultipartFormRequestOptions = async (opts, fetch3) => {
  if (!hasUploadableValue(opts.body))
    return opts;
  return { ...opts, body: await createForm2(opts.body, fetch3) };
};
var multipartFormRequestOptions2 = async (opts, fetch3) => {
  return { ...opts, body: await createForm2(opts.body, fetch3) };
};
var supportsFormDataMap2 = /* @__PURE__ */ new WeakMap();
function supportsFormData2(fetchObject) {
  const fetch3 = typeof fetchObject === "function" ? fetchObject : fetchObject.fetch;
  const cached = supportsFormDataMap2.get(fetch3);
  if (cached)
    return cached;
  const promise = (async () => {
    try {
      const FetchResponse = "Response" in fetch3 ? fetch3.Response : (await fetch3("data:,")).constructor;
      const data = new FormData();
      if (data.toString() === await new FetchResponse(data).text()) {
        return false;
      }
      return true;
    } catch {
      return true;
    }
  })();
  supportsFormDataMap2.set(fetch3, promise);
  return promise;
}
var createForm2 = async (body, fetch3) => {
  if (!await supportsFormData2(fetch3)) {
    throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");
  }
  const form = new FormData();
  await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue2(form, key, value)));
  return form;
};
var isNamedBlob2 = (value) => value instanceof Blob && "name" in value;
var isUploadable = (value) => typeof value === "object" && value !== null && (value instanceof Response || isAsyncIterable2(value) || isNamedBlob2(value));
var hasUploadableValue = (value) => {
  if (isUploadable(value))
    return true;
  if (Array.isArray(value))
    return value.some(hasUploadableValue);
  if (value && typeof value === "object") {
    for (const k2 in value) {
      if (hasUploadableValue(value[k2]))
        return true;
    }
  }
  return false;
};
var addFormValue2 = async (form, key, value) => {
  if (value === void 0)
    return;
  if (value == null) {
    throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`);
  }
  if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
    form.append(key, String(value));
  } else if (value instanceof Response) {
    form.append(key, makeFile2([await value.blob()], getName2(value)));
  } else if (isAsyncIterable2(value)) {
    form.append(key, makeFile2([await new Response(ReadableStreamFrom2(value)).blob()], getName2(value)));
  } else if (isNamedBlob2(value)) {
    form.append(key, value, getName2(value));
  } else if (Array.isArray(value)) {
    await Promise.all(value.map((entry) => addFormValue2(form, key + "[]", entry)));
  } else if (typeof value === "object") {
    await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue2(form, `${key}[${name}]`, prop)));
  } else {
    throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`);
  }
};

// ../pi-mono/node_modules/openai/internal/to-file.mjs
var isBlobLike2 = (value) => value != null && typeof value === "object" && typeof value.size === "number" && typeof value.type === "string" && typeof value.text === "function" && typeof value.slice === "function" && typeof value.arrayBuffer === "function";
var isFileLike2 = (value) => value != null && typeof value === "object" && typeof value.name === "string" && typeof value.lastModified === "number" && isBlobLike2(value);
var isResponseLike2 = (value) => value != null && typeof value === "object" && typeof value.url === "string" && typeof value.blob === "function";
async function toFile2(value, name, options) {
  checkFileSupport2();
  value = await value;
  if (isFileLike2(value)) {
    if (value instanceof File) {
      return value;
    }
    return makeFile2([await value.arrayBuffer()], value.name);
  }
  if (isResponseLike2(value)) {
    const blob = await value.blob();
    name || (name = new URL(value.url).pathname.split(/[\\/]/).pop());
    return makeFile2(await getBytes2(blob), name, options);
  }
  const parts = await getBytes2(value);
  name || (name = getName2(value));
  if (!options?.type) {
    const type = parts.find((part) => typeof part === "object" && "type" in part && part.type);
    if (typeof type === "string") {
      options = { ...options, type };
    }
  }
  return makeFile2(parts, name, options);
}
async function getBytes2(value) {
  let parts = [];
  if (typeof value === "string" || ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc.
  value instanceof ArrayBuffer) {
    parts.push(value);
  } else if (isBlobLike2(value)) {
    parts.push(value instanceof Blob ? value : await value.arrayBuffer());
  } else if (isAsyncIterable2(value)) {
    for await (const chunk of value) {
      parts.push(...await getBytes2(chunk));
    }
  } else {
    const constructor = value?.constructor?.name;
    throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ""}${propsForError2(value)}`);
  }
  return parts;
}
function propsForError2(value) {
  if (typeof value !== "object" || value === null)
    return "";
  const props = Object.getOwnPropertyNames(value);
  return `; props: [${props.map((p4) => `"${p4}"`).join(", ")}]`;
}

// ../pi-mono/node_modules/openai/resources/index.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/resources/chat/index.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/resources/chat/chat.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/core/resource.mjs
init_process_shim();
var APIResource2 = class {
  constructor(client) {
    this._client = client;
  }
};

// ../pi-mono/node_modules/openai/resources/chat/completions/completions.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/resources/chat/completions/messages.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/internal/utils/path.mjs
init_process_shim();
function encodeURIPath2(str2) {
  return str2.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent);
}
var EMPTY2 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null));
var createPathTagFunction2 = (pathEncoder = encodeURIPath2) => function path6(statics, ...params) {
  if (statics.length === 1)
    return statics[0];
  let postPath = false;
  const invalidSegments = [];
  const path7 = statics.reduce((previousValue, currentValue, index) => {
    if (/[?#]/.test(currentValue)) {
      postPath = true;
    }
    const value = params[index];
    let encoded = (postPath ? encodeURIComponent : pathEncoder)("" + value);
    if (index !== params.length && (value == null || typeof value === "object" && // handle values from other realms
    value.toString === Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? EMPTY2) ?? EMPTY2)?.toString)) {
      encoded = value + "";
      invalidSegments.push({
        start: previousValue.length + currentValue.length,
        length: encoded.length,
        error: `Value of type ${Object.prototype.toString.call(value).slice(8, -1)} is not a valid path parameter`
      });
    }
    return previousValue + currentValue + (index === params.length ? "" : encoded);
  }, "");
  const pathOnly = path7.split(/[?#]/, 1)[0];
  const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;
  let match2;
  while ((match2 = invalidSegmentPattern.exec(pathOnly)) !== null) {
    invalidSegments.push({
      start: match2.index,
      length: match2[0].length,
      error: `Value "${match2[0]}" can't be safely passed as a path parameter`
    });
  }
  invalidSegments.sort((a3, b4) => a3.start - b4.start);
  if (invalidSegments.length > 0) {
    let lastEnd = 0;
    const underline = invalidSegments.reduce((acc, segment) => {
      const spaces = " ".repeat(segment.start - lastEnd);
      const arrows = "^".repeat(segment.length);
      lastEnd = segment.start + segment.length;
      return acc + spaces + arrows;
    }, "");
    throw new OpenAIError(`Path parameters result in path with invalid segments:
${invalidSegments.map((e9) => e9.error).join("\n")}
${path7}
${underline}`);
  }
  return path7;
};
var path2 = /* @__PURE__ */ createPathTagFunction2(encodeURIPath2);

// ../pi-mono/node_modules/openai/resources/chat/completions/messages.mjs
var Messages3 = class extends APIResource2 {
  /**
   * Get the messages in a stored chat completion. Only Chat Completions that have
   * been created with the `store` parameter set to `true` will be returned.
   *
   * @example
   * ```ts
   * // Automatically fetches more pages as needed.
   * for await (const chatCompletionStoreMessage of client.chat.completions.messages.list(
   *   'completion_id',
   * )) {
   *   // ...
   * }
   * ```
   */
  list(completionID, query = {}, options) {
    return this._client.getAPIList(path2`/chat/completions/${completionID}/messages`, CursorPage, { query, ...options });
  }
};

// ../pi-mono/node_modules/openai/lib/ChatCompletionRunner.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/lib/AbstractChatCompletionRunner.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/error.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/lib/parser.mjs
init_process_shim();
function isChatCompletionFunctionTool(tool) {
  return tool !== void 0 && "function" in tool && tool.function !== void 0;
}
function isAutoParsableResponseFormat(response_format) {
  return response_format?.["$brand"] === "auto-parseable-response-format";
}
function isAutoParsableTool(tool) {
  return tool?.["$brand"] === "auto-parseable-tool";
}
function maybeParseChatCompletion(completion, params) {
  if (!params || !hasAutoParseableInput(params)) {
    return {
      ...completion,
      choices: completion.choices.map((choice) => {
        assertToolCallsAreChatCompletionFunctionToolCalls(choice.message.tool_calls);
        return {
          ...choice,
          message: {
            ...choice.message,
            parsed: null,
            ...choice.message.tool_calls ? {
              tool_calls: choice.message.tool_calls
            } : void 0
          }
        };
      })
    };
  }
  return parseChatCompletion(completion, params);
}
function parseChatCompletion(completion, params) {
  const choices = completion.choices.map((choice) => {
    if (choice.finish_reason === "length") {
      throw new LengthFinishReasonError();
    }
    if (choice.finish_reason === "content_filter") {
      throw new ContentFilterFinishReasonError();
    }
    assertToolCallsAreChatCompletionFunctionToolCalls(choice.message.tool_calls);
    return {
      ...choice,
      message: {
        ...choice.message,
        ...choice.message.tool_calls ? {
          tool_calls: choice.message.tool_calls?.map((toolCall) => parseToolCall(params, toolCall)) ?? void 0
        } : void 0,
        parsed: choice.message.content && !choice.message.refusal ? parseResponseFormat(params, choice.message.content) : null
      }
    };
  });
  return { ...completion, choices };
}
function parseResponseFormat(params, content) {
  if (params.response_format?.type !== "json_schema") {
    return null;
  }
  if (params.response_format?.type === "json_schema") {
    if ("$parseRaw" in params.response_format) {
      const response_format = params.response_format;
      return response_format.$parseRaw(content);
    }
    return JSON.parse(content);
  }
  return null;
}
function parseToolCall(params, toolCall) {
  const inputTool = params.tools?.find((inputTool2) => isChatCompletionFunctionTool(inputTool2) && inputTool2.function?.name === toolCall.function.name);
  return {
    ...toolCall,
    function: {
      ...toolCall.function,
      parsed_arguments: isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCall.function.arguments) : inputTool?.function.strict ? JSON.parse(toolCall.function.arguments) : null
    }
  };
}
function shouldParseToolCall(params, toolCall) {
  if (!params || !("tools" in params) || !params.tools) {
    return false;
  }
  const inputTool = params.tools?.find((inputTool2) => isChatCompletionFunctionTool(inputTool2) && inputTool2.function?.name === toolCall.function.name);
  return isChatCompletionFunctionTool(inputTool) && (isAutoParsableTool(inputTool) || inputTool?.function.strict || false);
}
function hasAutoParseableInput(params) {
  if (isAutoParsableResponseFormat(params.response_format)) {
    return true;
  }
  return params.tools?.some((t6) => isAutoParsableTool(t6) || t6.type === "function" && t6.function.strict === true) ?? false;
}
function assertToolCallsAreChatCompletionFunctionToolCalls(toolCalls) {
  for (const toolCall of toolCalls || []) {
    if (toolCall.type !== "function") {
      throw new OpenAIError(`Currently only \`function\` tool calls are supported; Received \`${toolCall.type}\``);
    }
  }
}
function validateInputTools(tools) {
  for (const tool of tools ?? []) {
    if (tool.type !== "function") {
      throw new OpenAIError(`Currently only \`function\` tool types support auto-parsing; Received \`${tool.type}\``);
    }
    if (tool.function.strict !== true) {
      throw new OpenAIError(`The \`${tool.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`);
    }
  }
}

// ../pi-mono/node_modules/openai/lib/chatCompletionUtils.mjs
init_process_shim();
var isAssistantMessage = (message) => {
  return message?.role === "assistant";
};
var isToolMessage = (message) => {
  return message?.role === "tool";
};

// ../pi-mono/node_modules/openai/lib/EventStream.mjs
init_process_shim();
var _EventStream_instances;
var _EventStream_connectedPromise;
var _EventStream_resolveConnectedPromise;
var _EventStream_rejectConnectedPromise;
var _EventStream_endPromise;
var _EventStream_resolveEndPromise;
var _EventStream_rejectEndPromise;
var _EventStream_listeners;
var _EventStream_ended;
var _EventStream_errored;
var _EventStream_aborted;
var _EventStream_catchingPromiseCreated;
var _EventStream_handleError;
var EventStream2 = class {
  constructor() {
    _EventStream_instances.add(this);
    this.controller = new AbortController();
    _EventStream_connectedPromise.set(this, void 0);
    _EventStream_resolveConnectedPromise.set(this, () => {
    });
    _EventStream_rejectConnectedPromise.set(this, () => {
    });
    _EventStream_endPromise.set(this, void 0);
    _EventStream_resolveEndPromise.set(this, () => {
    });
    _EventStream_rejectEndPromise.set(this, () => {
    });
    _EventStream_listeners.set(this, {});
    _EventStream_ended.set(this, false);
    _EventStream_errored.set(this, false);
    _EventStream_aborted.set(this, false);
    _EventStream_catchingPromiseCreated.set(this, false);
    __classPrivateFieldSet2(this, _EventStream_connectedPromise, new Promise((resolve, reject) => {
      __classPrivateFieldSet2(this, _EventStream_resolveConnectedPromise, resolve, "f");
      __classPrivateFieldSet2(this, _EventStream_rejectConnectedPromise, reject, "f");
    }), "f");
    __classPrivateFieldSet2(this, _EventStream_endPromise, new Promise((resolve, reject) => {
      __classPrivateFieldSet2(this, _EventStream_resolveEndPromise, resolve, "f");
      __classPrivateFieldSet2(this, _EventStream_rejectEndPromise, reject, "f");
    }), "f");
    __classPrivateFieldGet2(this, _EventStream_connectedPromise, "f").catch(() => {
    });
    __classPrivateFieldGet2(this, _EventStream_endPromise, "f").catch(() => {
    });
  }
  _run(executor) {
    setTimeout(() => {
      executor().then(() => {
        this._emitFinal();
        this._emit("end");
      }, __classPrivateFieldGet2(this, _EventStream_instances, "m", _EventStream_handleError).bind(this));
    }, 0);
  }
  _connected() {
    if (this.ended)
      return;
    __classPrivateFieldGet2(this, _EventStream_resolveConnectedPromise, "f").call(this);
    this._emit("connect");
  }
  get ended() {
    return __classPrivateFieldGet2(this, _EventStream_ended, "f");
  }
  get errored() {
    return __classPrivateFieldGet2(this, _EventStream_errored, "f");
  }
  get aborted() {
    return __classPrivateFieldGet2(this, _EventStream_aborted, "f");
  }
  abort() {
    this.controller.abort();
  }
  /**
   * Adds the listener function to the end of the listeners array for the event.
   * No checks are made to see if the listener has already been added. Multiple calls passing
   * the same combination of event and listener will result in the listener being added, and
   * called, multiple times.
   * @returns this ChatCompletionStream, so that calls can be chained
   */
  on(event, listener) {
    const listeners = __classPrivateFieldGet2(this, _EventStream_listeners, "f")[event] || (__classPrivateFieldGet2(this, _EventStream_listeners, "f")[event] = []);
    listeners.push({ listener });
    return this;
  }
  /**
   * Removes the specified listener from the listener array for the event.
   * off() will remove, at most, one instance of a listener from the listener array. If any single
   * listener has been added multiple times to the listener array for the specified event, then
   * off() must be called multiple times to remove each instance.
   * @returns this ChatCompletionStream, so that calls can be chained
   */
  off(event, listener) {
    const listeners = __classPrivateFieldGet2(this, _EventStream_listeners, "f")[event];
    if (!listeners)
      return this;
    const index = listeners.findIndex((l5) => l5.listener === listener);
    if (index >= 0)
      listeners.splice(index, 1);
    return this;
  }
  /**
   * Adds a one-time listener function for the event. The next time the event is triggered,
   * this listener is removed and then invoked.
   * @returns this ChatCompletionStream, so that calls can be chained
   */
  once(event, listener) {
    const listeners = __classPrivateFieldGet2(this, _EventStream_listeners, "f")[event] || (__classPrivateFieldGet2(this, _EventStream_listeners, "f")[event] = []);
    listeners.push({ listener, once: true });
    return this;
  }
  /**
   * This is similar to `.once()`, but returns a Promise that resolves the next time
   * the event is triggered, instead of calling a listener callback.
   * @returns a Promise that resolves the next time given event is triggered,
   * or rejects if an error is emitted.  (If you request the 'error' event,
   * returns a promise that resolves with the error).
   *
   * Example:
   *
   *   const message = await stream.emitted('message') // rejects if the stream errors
   */
  emitted(event) {
    return new Promise((resolve, reject) => {
      __classPrivateFieldSet2(this, _EventStream_catchingPromiseCreated, true, "f");
      if (event !== "error")
        this.once("error", reject);
      this.once(event, resolve);
    });
  }
  async done() {
    __classPrivateFieldSet2(this, _EventStream_catchingPromiseCreated, true, "f");
    await __classPrivateFieldGet2(this, _EventStream_endPromise, "f");
  }
  _emit(event, ...args) {
    if (__classPrivateFieldGet2(this, _EventStream_ended, "f")) {
      return;
    }
    if (event === "end") {
      __classPrivateFieldSet2(this, _EventStream_ended, true, "f");
      __classPrivateFieldGet2(this, _EventStream_resolveEndPromise, "f").call(this);
    }
    const listeners = __classPrivateFieldGet2(this, _EventStream_listeners, "f")[event];
    if (listeners) {
      __classPrivateFieldGet2(this, _EventStream_listeners, "f")[event] = listeners.filter((l5) => !l5.once);
      listeners.forEach(({ listener }) => listener(...args));
    }
    if (event === "abort") {
      const error = args[0];
      if (!__classPrivateFieldGet2(this, _EventStream_catchingPromiseCreated, "f") && !listeners?.length) {
        Promise.reject(error);
      }
      __classPrivateFieldGet2(this, _EventStream_rejectConnectedPromise, "f").call(this, error);
      __classPrivateFieldGet2(this, _EventStream_rejectEndPromise, "f").call(this, error);
      this._emit("end");
      return;
    }
    if (event === "error") {
      const error = args[0];
      if (!__classPrivateFieldGet2(this, _EventStream_catchingPromiseCreated, "f") && !listeners?.length) {
        Promise.reject(error);
      }
      __classPrivateFieldGet2(this, _EventStream_rejectConnectedPromise, "f").call(this, error);
      __classPrivateFieldGet2(this, _EventStream_rejectEndPromise, "f").call(this, error);
      this._emit("end");
    }
  }
  _emitFinal() {
  }
};
_EventStream_connectedPromise = /* @__PURE__ */ new WeakMap(), _EventStream_resolveConnectedPromise = /* @__PURE__ */ new WeakMap(), _EventStream_rejectConnectedPromise = /* @__PURE__ */ new WeakMap(), _EventStream_endPromise = /* @__PURE__ */ new WeakMap(), _EventStream_resolveEndPromise = /* @__PURE__ */ new WeakMap(), _EventStream_rejectEndPromise = /* @__PURE__ */ new WeakMap(), _EventStream_listeners = /* @__PURE__ */ new WeakMap(), _EventStream_ended = /* @__PURE__ */ new WeakMap(), _EventStream_errored = /* @__PURE__ */ new WeakMap(), _EventStream_aborted = /* @__PURE__ */ new WeakMap(), _EventStream_catchingPromiseCreated = /* @__PURE__ */ new WeakMap(), _EventStream_instances = /* @__PURE__ */ new WeakSet(), _EventStream_handleError = function _EventStream_handleError2(error) {
  __classPrivateFieldSet2(this, _EventStream_errored, true, "f");
  if (error instanceof Error && error.name === "AbortError") {
    error = new APIUserAbortError2();
  }
  if (error instanceof APIUserAbortError2) {
    __classPrivateFieldSet2(this, _EventStream_aborted, true, "f");
    return this._emit("abort", error);
  }
  if (error instanceof OpenAIError) {
    return this._emit("error", error);
  }
  if (error instanceof Error) {
    const openAIError = new OpenAIError(error.message);
    openAIError.cause = error;
    return this._emit("error", openAIError);
  }
  return this._emit("error", new OpenAIError(String(error)));
};

// ../pi-mono/node_modules/openai/lib/RunnableFunction.mjs
init_process_shim();
function isRunnableFunctionWithParse(fn) {
  return typeof fn.parse === "function";
}

// ../pi-mono/node_modules/openai/lib/AbstractChatCompletionRunner.mjs
var _AbstractChatCompletionRunner_instances;
var _AbstractChatCompletionRunner_getFinalContent;
var _AbstractChatCompletionRunner_getFinalMessage;
var _AbstractChatCompletionRunner_getFinalFunctionToolCall;
var _AbstractChatCompletionRunner_getFinalFunctionToolCallResult;
var _AbstractChatCompletionRunner_calculateTotalUsage;
var _AbstractChatCompletionRunner_validateParams;
var _AbstractChatCompletionRunner_stringifyFunctionCallResult;
var DEFAULT_MAX_CHAT_COMPLETIONS = 10;
var AbstractChatCompletionRunner = class extends EventStream2 {
  constructor() {
    super(...arguments);
    _AbstractChatCompletionRunner_instances.add(this);
    this._chatCompletions = [];
    this.messages = [];
  }
  _addChatCompletion(chatCompletion) {
    this._chatCompletions.push(chatCompletion);
    this._emit("chatCompletion", chatCompletion);
    const message = chatCompletion.choices[0]?.message;
    if (message)
      this._addMessage(message);
    return chatCompletion;
  }
  _addMessage(message, emit = true) {
    if (!("content" in message))
      message.content = null;
    this.messages.push(message);
    if (emit) {
      this._emit("message", message);
      if (isToolMessage(message) && message.content) {
        this._emit("functionToolCallResult", message.content);
      } else if (isAssistantMessage(message) && message.tool_calls) {
        for (const tool_call of message.tool_calls) {
          if (tool_call.type === "function") {
            this._emit("functionToolCall", tool_call.function);
          }
        }
      }
    }
  }
  /**
   * @returns a promise that resolves with the final ChatCompletion, or rejects
   * if an error occurred or the stream ended prematurely without producing a ChatCompletion.
   */
  async finalChatCompletion() {
    await this.done();
    const completion = this._chatCompletions[this._chatCompletions.length - 1];
    if (!completion)
      throw new OpenAIError("stream ended without producing a ChatCompletion");
    return completion;
  }
  /**
   * @returns a promise that resolves with the content of the final ChatCompletionMessage, or rejects
   * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage.
   */
  async finalContent() {
    await this.done();
    return __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this);
  }
  /**
   * @returns a promise that resolves with the the final assistant ChatCompletionMessage response,
   * or rejects if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage.
   */
  async finalMessage() {
    await this.done();
    return __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this);
  }
  /**
   * @returns a promise that resolves with the content of the final FunctionCall, or rejects
   * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage.
   */
  async finalFunctionToolCall() {
    await this.done();
    return __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCall).call(this);
  }
  async finalFunctionToolCallResult() {
    await this.done();
    return __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCallResult).call(this);
  }
  async totalUsage() {
    await this.done();
    return __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this);
  }
  allChatCompletions() {
    return [...this._chatCompletions];
  }
  _emitFinal() {
    const completion = this._chatCompletions[this._chatCompletions.length - 1];
    if (completion)
      this._emit("finalChatCompletion", completion);
    const finalMessage = __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this);
    if (finalMessage)
      this._emit("finalMessage", finalMessage);
    const finalContent = __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this);
    if (finalContent)
      this._emit("finalContent", finalContent);
    const finalFunctionCall = __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCall).call(this);
    if (finalFunctionCall)
      this._emit("finalFunctionToolCall", finalFunctionCall);
    const finalFunctionCallResult = __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCallResult).call(this);
    if (finalFunctionCallResult != null)
      this._emit("finalFunctionToolCallResult", finalFunctionCallResult);
    if (this._chatCompletions.some((c6) => c6.usage)) {
      this._emit("totalUsage", __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this));
    }
  }
  async _createChatCompletion(client, params, options) {
    const signal = options?.signal;
    if (signal) {
      if (signal.aborted)
        this.controller.abort();
      signal.addEventListener("abort", () => this.controller.abort());
    }
    __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_validateParams).call(this, params);
    const chatCompletion = await client.chat.completions.create({ ...params, stream: false }, { ...options, signal: this.controller.signal });
    this._connected();
    return this._addChatCompletion(parseChatCompletion(chatCompletion, params));
  }
  async _runChatCompletion(client, params, options) {
    for (const message of params.messages) {
      this._addMessage(message, false);
    }
    return await this._createChatCompletion(client, params, options);
  }
  async _runTools(client, params, options) {
    const role = "tool";
    const { tool_choice = "auto", stream: stream2, ...restParams } = params;
    const singleFunctionToCall = typeof tool_choice !== "string" && tool_choice.type === "function" && tool_choice?.function?.name;
    const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS } = options || {};
    const inputTools = params.tools.map((tool) => {
      if (isAutoParsableTool(tool)) {
        if (!tool.$callback) {
          throw new OpenAIError("Tool given to `.runTools()` that does not have an associated function");
        }
        return {
          type: "function",
          function: {
            function: tool.$callback,
            name: tool.function.name,
            description: tool.function.description || "",
            parameters: tool.function.parameters,
            parse: tool.$parseRaw,
            strict: true
          }
        };
      }
      return tool;
    });
    const functionsByName = {};
    for (const f4 of inputTools) {
      if (f4.type === "function") {
        functionsByName[f4.function.name || f4.function.function.name] = f4.function;
      }
    }
    const tools = "tools" in params ? inputTools.map((t6) => t6.type === "function" ? {
      type: "function",
      function: {
        name: t6.function.name || t6.function.function.name,
        parameters: t6.function.parameters,
        description: t6.function.description,
        strict: t6.function.strict
      }
    } : t6) : void 0;
    for (const message of params.messages) {
      this._addMessage(message, false);
    }
    for (let i7 = 0; i7 < maxChatCompletions; ++i7) {
      const chatCompletion = await this._createChatCompletion(client, {
        ...restParams,
        tool_choice,
        tools,
        messages: [...this.messages]
      }, options);
      const message = chatCompletion.choices[0]?.message;
      if (!message) {
        throw new OpenAIError(`missing message in ChatCompletion response`);
      }
      if (!message.tool_calls?.length) {
        return;
      }
      for (const tool_call of message.tool_calls) {
        if (tool_call.type !== "function")
          continue;
        const tool_call_id = tool_call.id;
        const { name, arguments: args } = tool_call.function;
        const fn = functionsByName[name];
        if (!fn) {
          const content2 = `Invalid tool_call: ${JSON.stringify(name)}. Available options are: ${Object.keys(functionsByName).map((name2) => JSON.stringify(name2)).join(", ")}. Please try again`;
          this._addMessage({ role, tool_call_id, content: content2 });
          continue;
        } else if (singleFunctionToCall && singleFunctionToCall !== name) {
          const content2 = `Invalid tool_call: ${JSON.stringify(name)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`;
          this._addMessage({ role, tool_call_id, content: content2 });
          continue;
        }
        let parsed;
        try {
          parsed = isRunnableFunctionWithParse(fn) ? await fn.parse(args) : args;
        } catch (error) {
          const content2 = error instanceof Error ? error.message : String(error);
          this._addMessage({ role, tool_call_id, content: content2 });
          continue;
        }
        const rawContent = await fn.function(parsed, this);
        const content = __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent);
        this._addMessage({ role, tool_call_id, content });
        if (singleFunctionToCall) {
          return;
        }
      }
    }
    return;
  }
};
_AbstractChatCompletionRunner_instances = /* @__PURE__ */ new WeakSet(), _AbstractChatCompletionRunner_getFinalContent = function _AbstractChatCompletionRunner_getFinalContent2() {
  return __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this).content ?? null;
}, _AbstractChatCompletionRunner_getFinalMessage = function _AbstractChatCompletionRunner_getFinalMessage2() {
  let i7 = this.messages.length;
  while (i7-- > 0) {
    const message = this.messages[i7];
    if (isAssistantMessage(message)) {
      const ret = {
        ...message,
        content: message.content ?? null,
        refusal: message.refusal ?? null
      };
      return ret;
    }
  }
  throw new OpenAIError("stream ended without producing a ChatCompletionMessage with role=assistant");
}, _AbstractChatCompletionRunner_getFinalFunctionToolCall = function _AbstractChatCompletionRunner_getFinalFunctionToolCall2() {
  for (let i7 = this.messages.length - 1; i7 >= 0; i7--) {
    const message = this.messages[i7];
    if (isAssistantMessage(message) && message?.tool_calls?.length) {
      return message.tool_calls.filter((x2) => x2.type === "function").at(-1)?.function;
    }
  }
  return;
}, _AbstractChatCompletionRunner_getFinalFunctionToolCallResult = function _AbstractChatCompletionRunner_getFinalFunctionToolCallResult2() {
  for (let i7 = this.messages.length - 1; i7 >= 0; i7--) {
    const message = this.messages[i7];
    if (isToolMessage(message) && message.content != null && typeof message.content === "string" && this.messages.some((x2) => x2.role === "assistant" && x2.tool_calls?.some((y4) => y4.type === "function" && y4.id === message.tool_call_id))) {
      return message.content;
    }
  }
  return;
}, _AbstractChatCompletionRunner_calculateTotalUsage = function _AbstractChatCompletionRunner_calculateTotalUsage2() {
  const total = {
    completion_tokens: 0,
    prompt_tokens: 0,
    total_tokens: 0
  };
  for (const { usage } of this._chatCompletions) {
    if (usage) {
      total.completion_tokens += usage.completion_tokens;
      total.prompt_tokens += usage.prompt_tokens;
      total.total_tokens += usage.total_tokens;
    }
  }
  return total;
}, _AbstractChatCompletionRunner_validateParams = function _AbstractChatCompletionRunner_validateParams2(params) {
  if (params.n != null && params.n > 1) {
    throw new OpenAIError("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.");
  }
}, _AbstractChatCompletionRunner_stringifyFunctionCallResult = function _AbstractChatCompletionRunner_stringifyFunctionCallResult2(rawContent) {
  return typeof rawContent === "string" ? rawContent : rawContent === void 0 ? "undefined" : JSON.stringify(rawContent);
};

// ../pi-mono/node_modules/openai/lib/ChatCompletionRunner.mjs
var ChatCompletionRunner = class _ChatCompletionRunner extends AbstractChatCompletionRunner {
  static runTools(client, params, options) {
    const runner = new _ChatCompletionRunner();
    const opts = {
      ...options,
      headers: { ...options?.headers, "X-Stainless-Helper-Method": "runTools" }
    };
    runner._run(() => runner._runTools(client, params, opts));
    return runner;
  }
  _addMessage(message, emit = true) {
    super._addMessage(message, emit);
    if (isAssistantMessage(message) && message.content) {
      this._emit("content", message.content);
    }
  }
};

// ../pi-mono/node_modules/openai/lib/ChatCompletionStreamingRunner.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/lib/ChatCompletionStream.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/_vendor/partial-json-parser/parser.mjs
init_process_shim();
var STR = 1;
var NUM = 2;
var ARR = 4;
var OBJ = 8;
var NULL = 16;
var BOOL = 32;
var NAN = 64;
var INFINITY = 128;
var MINUS_INFINITY = 256;
var INF = INFINITY | MINUS_INFINITY;
var SPECIAL = NULL | BOOL | INF | NAN;
var ATOM = STR | NUM | SPECIAL;
var COLLECTION = ARR | OBJ;
var ALL = ATOM | COLLECTION;
var Allow = {
  STR,
  NUM,
  ARR,
  OBJ,
  NULL,
  BOOL,
  NAN,
  INFINITY,
  MINUS_INFINITY,
  INF,
  SPECIAL,
  ATOM,
  COLLECTION,
  ALL
};
var PartialJSON = class extends Error {
};
var MalformedJSON = class extends Error {
};
function parseJSON(jsonString, allowPartial = Allow.ALL) {
  if (typeof jsonString !== "string") {
    throw new TypeError(`expecting str, got ${typeof jsonString}`);
  }
  if (!jsonString.trim()) {
    throw new Error(`${jsonString} is empty`);
  }
  return _parseJSON(jsonString.trim(), allowPartial);
}
var _parseJSON = (jsonString, allow) => {
  const length = jsonString.length;
  let index = 0;
  const markPartialJSON = (msg) => {
    throw new PartialJSON(`${msg} at position ${index}`);
  };
  const throwMalformedError = (msg) => {
    throw new MalformedJSON(`${msg} at position ${index}`);
  };
  const parseAny = () => {
    skipBlank();
    if (index >= length)
      markPartialJSON("Unexpected end of input");
    if (jsonString[index] === '"')
      return parseStr();
    if (jsonString[index] === "{")
      return parseObj();
    if (jsonString[index] === "[")
      return parseArr();
    if (jsonString.substring(index, index + 4) === "null" || Allow.NULL & allow && length - index < 4 && "null".startsWith(jsonString.substring(index))) {
      index += 4;
      return null;
    }
    if (jsonString.substring(index, index + 4) === "true" || Allow.BOOL & allow && length - index < 4 && "true".startsWith(jsonString.substring(index))) {
      index += 4;
      return true;
    }
    if (jsonString.substring(index, index + 5) === "false" || Allow.BOOL & allow && length - index < 5 && "false".startsWith(jsonString.substring(index))) {
      index += 5;
      return false;
    }
    if (jsonString.substring(index, index + 8) === "Infinity" || Allow.INFINITY & allow && length - index < 8 && "Infinity".startsWith(jsonString.substring(index))) {
      index += 8;
      return Infinity;
    }
    if (jsonString.substring(index, index + 9) === "-Infinity" || Allow.MINUS_INFINITY & allow && 1 < length - index && length - index < 9 && "-Infinity".startsWith(jsonString.substring(index))) {
      index += 9;
      return -Infinity;
    }
    if (jsonString.substring(index, index + 3) === "NaN" || Allow.NAN & allow && length - index < 3 && "NaN".startsWith(jsonString.substring(index))) {
      index += 3;
      return NaN;
    }
    return parseNum();
  };
  const parseStr = () => {
    const start = index;
    let escape4 = false;
    index++;
    while (index < length && (jsonString[index] !== '"' || escape4 && jsonString[index - 1] === "\\")) {
      escape4 = jsonString[index] === "\\" ? !escape4 : false;
      index++;
    }
    if (jsonString.charAt(index) == '"') {
      try {
        return JSON.parse(jsonString.substring(start, ++index - Number(escape4)));
      } catch (e9) {
        throwMalformedError(String(e9));
      }
    } else if (Allow.STR & allow) {
      try {
        return JSON.parse(jsonString.substring(start, index - Number(escape4)) + '"');
      } catch (e9) {
        return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf("\\")) + '"');
      }
    }
    markPartialJSON("Unterminated string literal");
  };
  const parseObj = () => {
    index++;
    skipBlank();
    const obj = {};
    try {
      while (jsonString[index] !== "}") {
        skipBlank();
        if (index >= length && Allow.OBJ & allow)
          return obj;
        const key = parseStr();
        skipBlank();
        index++;
        try {
          const value = parseAny();
          Object.defineProperty(obj, key, { value, writable: true, enumerable: true, configurable: true });
        } catch (e9) {
          if (Allow.OBJ & allow)
            return obj;
          else
            throw e9;
        }
        skipBlank();
        if (jsonString[index] === ",")
          index++;
      }
    } catch (e9) {
      if (Allow.OBJ & allow)
        return obj;
      else
        markPartialJSON("Expected '}' at end of object");
    }
    index++;
    return obj;
  };
  const parseArr = () => {
    index++;
    const arr = [];
    try {
      while (jsonString[index] !== "]") {
        arr.push(parseAny());
        skipBlank();
        if (jsonString[index] === ",") {
          index++;
        }
      }
    } catch (e9) {
      if (Allow.ARR & allow) {
        return arr;
      }
      markPartialJSON("Expected ']' at end of array");
    }
    index++;
    return arr;
  };
  const parseNum = () => {
    if (index === 0) {
      if (jsonString === "-" && Allow.NUM & allow)
        markPartialJSON("Not sure what '-' is");
      try {
        return JSON.parse(jsonString);
      } catch (e9) {
        if (Allow.NUM & allow) {
          try {
            if ("." === jsonString[jsonString.length - 1])
              return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf(".")));
            return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf("e")));
          } catch (e10) {
          }
        }
        throwMalformedError(String(e9));
      }
    }
    const start = index;
    if (jsonString[index] === "-")
      index++;
    while (jsonString[index] && !",]}".includes(jsonString[index]))
      index++;
    if (index == length && !(Allow.NUM & allow))
      markPartialJSON("Unterminated number literal");
    try {
      return JSON.parse(jsonString.substring(start, index));
    } catch (e9) {
      if (jsonString.substring(start, index) === "-" && Allow.NUM & allow)
        markPartialJSON("Not sure what '-' is");
      try {
        return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf("e")));
      } catch (e10) {
        throwMalformedError(String(e10));
      }
    }
  };
  const skipBlank = () => {
    while (index < length && " \n\r	".includes(jsonString[index])) {
      index++;
    }
  };
  return parseAny();
};
var partialParse3 = (input) => parseJSON(input, Allow.ALL ^ Allow.NUM);

// ../pi-mono/node_modules/openai/streaming.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/lib/ChatCompletionStream.mjs
var _ChatCompletionStream_instances;
var _ChatCompletionStream_params;
var _ChatCompletionStream_choiceEventStates;
var _ChatCompletionStream_currentChatCompletionSnapshot;
var _ChatCompletionStream_beginRequest;
var _ChatCompletionStream_getChoiceEventState;
var _ChatCompletionStream_addChunk;
var _ChatCompletionStream_emitToolCallDoneEvent;
var _ChatCompletionStream_emitContentDoneEvents;
var _ChatCompletionStream_endRequest;
var _ChatCompletionStream_getAutoParseableResponseFormat;
var _ChatCompletionStream_accumulateChatCompletion;
var ChatCompletionStream = class _ChatCompletionStream extends AbstractChatCompletionRunner {
  constructor(params) {
    super();
    _ChatCompletionStream_instances.add(this);
    _ChatCompletionStream_params.set(this, void 0);
    _ChatCompletionStream_choiceEventStates.set(this, void 0);
    _ChatCompletionStream_currentChatCompletionSnapshot.set(this, void 0);
    __classPrivateFieldSet2(this, _ChatCompletionStream_params, params, "f");
    __classPrivateFieldSet2(this, _ChatCompletionStream_choiceEventStates, [], "f");
  }
  get currentChatCompletionSnapshot() {
    return __classPrivateFieldGet2(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f");
  }
  /**
   * Intended for use on the frontend, consuming a stream produced with
   * `.toReadableStream()` on the backend.
   *
   * Note that messages sent to the model do not appear in `.on('message')`
   * in this context.
   */
  static fromReadableStream(stream2) {
    const runner = new _ChatCompletionStream(null);
    runner._run(() => runner._fromReadableStream(stream2));
    return runner;
  }
  static createChatCompletion(client, params, options) {
    const runner = new _ChatCompletionStream(params);
    runner._run(() => runner._runChatCompletion(client, { ...params, stream: true }, { ...options, headers: { ...options?.headers, "X-Stainless-Helper-Method": "stream" } }));
    return runner;
  }
  async _createChatCompletion(client, params, options) {
    super._createChatCompletion;
    const signal = options?.signal;
    if (signal) {
      if (signal.aborted)
        this.controller.abort();
      signal.addEventListener("abort", () => this.controller.abort());
    }
    __classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this);
    const stream2 = await client.chat.completions.create({ ...params, stream: true }, { ...options, signal: this.controller.signal });
    this._connected();
    for await (const chunk of stream2) {
      __classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk);
    }
    if (stream2.controller.signal?.aborted) {
      throw new APIUserAbortError2();
    }
    return this._addChatCompletion(__classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
  }
  async _fromReadableStream(readableStream, options) {
    const signal = options?.signal;
    if (signal) {
      if (signal.aborted)
        this.controller.abort();
      signal.addEventListener("abort", () => this.controller.abort());
    }
    __classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this);
    this._connected();
    const stream2 = Stream2.fromReadableStream(readableStream, this.controller);
    let chatId;
    for await (const chunk of stream2) {
      if (chatId && chatId !== chunk.id) {
        this._addChatCompletion(__classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
      }
      __classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk);
      chatId = chunk.id;
    }
    if (stream2.controller.signal?.aborted) {
      throw new APIUserAbortError2();
    }
    return this._addChatCompletion(__classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
  }
  [(_ChatCompletionStream_params = /* @__PURE__ */ new WeakMap(), _ChatCompletionStream_choiceEventStates = /* @__PURE__ */ new WeakMap(), _ChatCompletionStream_currentChatCompletionSnapshot = /* @__PURE__ */ new WeakMap(), _ChatCompletionStream_instances = /* @__PURE__ */ new WeakSet(), _ChatCompletionStream_beginRequest = function _ChatCompletionStream_beginRequest2() {
    if (this.ended)
      return;
    __classPrivateFieldSet2(this, _ChatCompletionStream_currentChatCompletionSnapshot, void 0, "f");
  }, _ChatCompletionStream_getChoiceEventState = function _ChatCompletionStream_getChoiceEventState2(choice) {
    let state = __classPrivateFieldGet2(this, _ChatCompletionStream_choiceEventStates, "f")[choice.index];
    if (state) {
      return state;
    }
    state = {
      content_done: false,
      refusal_done: false,
      logprobs_content_done: false,
      logprobs_refusal_done: false,
      done_tool_calls: /* @__PURE__ */ new Set(),
      current_tool_call_index: null
    };
    __classPrivateFieldGet2(this, _ChatCompletionStream_choiceEventStates, "f")[choice.index] = state;
    return state;
  }, _ChatCompletionStream_addChunk = function _ChatCompletionStream_addChunk2(chunk) {
    if (this.ended)
      return;
    const completion = __classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_accumulateChatCompletion).call(this, chunk);
    this._emit("chunk", chunk, completion);
    for (const choice of chunk.choices) {
      const choiceSnapshot = completion.choices[choice.index];
      if (choice.delta.content != null && choiceSnapshot.message?.role === "assistant" && choiceSnapshot.message?.content) {
        this._emit("content", choice.delta.content, choiceSnapshot.message.content);
        this._emit("content.delta", {
          delta: choice.delta.content,
          snapshot: choiceSnapshot.message.content,
          parsed: choiceSnapshot.message.parsed
        });
      }
      if (choice.delta.refusal != null && choiceSnapshot.message?.role === "assistant" && choiceSnapshot.message?.refusal) {
        this._emit("refusal.delta", {
          delta: choice.delta.refusal,
          snapshot: choiceSnapshot.message.refusal
        });
      }
      if (choice.logprobs?.content != null && choiceSnapshot.message?.role === "assistant") {
        this._emit("logprobs.content.delta", {
          content: choice.logprobs?.content,
          snapshot: choiceSnapshot.logprobs?.content ?? []
        });
      }
      if (choice.logprobs?.refusal != null && choiceSnapshot.message?.role === "assistant") {
        this._emit("logprobs.refusal.delta", {
          refusal: choice.logprobs?.refusal,
          snapshot: choiceSnapshot.logprobs?.refusal ?? []
        });
      }
      const state = __classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot);
      if (choiceSnapshot.finish_reason) {
        __classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot);
        if (state.current_tool_call_index != null) {
          __classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state.current_tool_call_index);
        }
      }
      for (const toolCall of choice.delta.tool_calls ?? []) {
        if (state.current_tool_call_index !== toolCall.index) {
          __classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot);
          if (state.current_tool_call_index != null) {
            __classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state.current_tool_call_index);
          }
        }
        state.current_tool_call_index = toolCall.index;
      }
      for (const toolCallDelta of choice.delta.tool_calls ?? []) {
        const toolCallSnapshot = choiceSnapshot.message.tool_calls?.[toolCallDelta.index];
        if (!toolCallSnapshot?.type) {
          continue;
        }
        if (toolCallSnapshot?.type === "function") {
          this._emit("tool_calls.function.arguments.delta", {
            name: toolCallSnapshot.function?.name,
            index: toolCallDelta.index,
            arguments: toolCallSnapshot.function.arguments,
            parsed_arguments: toolCallSnapshot.function.parsed_arguments,
            arguments_delta: toolCallDelta.function?.arguments ?? ""
          });
        } else {
          assertNever(toolCallSnapshot?.type);
        }
      }
    }
  }, _ChatCompletionStream_emitToolCallDoneEvent = function _ChatCompletionStream_emitToolCallDoneEvent2(choiceSnapshot, toolCallIndex) {
    const state = __classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot);
    if (state.done_tool_calls.has(toolCallIndex)) {
      return;
    }
    const toolCallSnapshot = choiceSnapshot.message.tool_calls?.[toolCallIndex];
    if (!toolCallSnapshot) {
      throw new Error("no tool call snapshot");
    }
    if (!toolCallSnapshot.type) {
      throw new Error("tool call snapshot missing `type`");
    }
    if (toolCallSnapshot.type === "function") {
      const inputTool = __classPrivateFieldGet2(this, _ChatCompletionStream_params, "f")?.tools?.find((tool) => isChatCompletionFunctionTool(tool) && tool.function.name === toolCallSnapshot.function.name);
      this._emit("tool_calls.function.arguments.done", {
        name: toolCallSnapshot.function.name,
        index: toolCallIndex,
        arguments: toolCallSnapshot.function.arguments,
        parsed_arguments: isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCallSnapshot.function.arguments) : inputTool?.function.strict ? JSON.parse(toolCallSnapshot.function.arguments) : null
      });
    } else {
      assertNever(toolCallSnapshot.type);
    }
  }, _ChatCompletionStream_emitContentDoneEvents = function _ChatCompletionStream_emitContentDoneEvents2(choiceSnapshot) {
    const state = __classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot);
    if (choiceSnapshot.message.content && !state.content_done) {
      state.content_done = true;
      const responseFormat = __classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getAutoParseableResponseFormat).call(this);
      this._emit("content.done", {
        content: choiceSnapshot.message.content,
        parsed: responseFormat ? responseFormat.$parseRaw(choiceSnapshot.message.content) : null
      });
    }
    if (choiceSnapshot.message.refusal && !state.refusal_done) {
      state.refusal_done = true;
      this._emit("refusal.done", { refusal: choiceSnapshot.message.refusal });
    }
    if (choiceSnapshot.logprobs?.content && !state.logprobs_content_done) {
      state.logprobs_content_done = true;
      this._emit("logprobs.content.done", { content: choiceSnapshot.logprobs.content });
    }
    if (choiceSnapshot.logprobs?.refusal && !state.logprobs_refusal_done) {
      state.logprobs_refusal_done = true;
      this._emit("logprobs.refusal.done", { refusal: choiceSnapshot.logprobs.refusal });
    }
  }, _ChatCompletionStream_endRequest = function _ChatCompletionStream_endRequest2() {
    if (this.ended) {
      throw new OpenAIError(`stream has ended, this shouldn't happen`);
    }
    const snapshot = __classPrivateFieldGet2(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f");
    if (!snapshot) {
      throw new OpenAIError(`request ended without sending any chunks`);
    }
    __classPrivateFieldSet2(this, _ChatCompletionStream_currentChatCompletionSnapshot, void 0, "f");
    __classPrivateFieldSet2(this, _ChatCompletionStream_choiceEventStates, [], "f");
    return finalizeChatCompletion(snapshot, __classPrivateFieldGet2(this, _ChatCompletionStream_params, "f"));
  }, _ChatCompletionStream_getAutoParseableResponseFormat = function _ChatCompletionStream_getAutoParseableResponseFormat2() {
    const responseFormat = __classPrivateFieldGet2(this, _ChatCompletionStream_params, "f")?.response_format;
    if (isAutoParsableResponseFormat(responseFormat)) {
      return responseFormat;
    }
    return null;
  }, _ChatCompletionStream_accumulateChatCompletion = function _ChatCompletionStream_accumulateChatCompletion2(chunk) {
    var _a7, _b, _c, _d;
    let snapshot = __classPrivateFieldGet2(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f");
    const { choices, ...rest } = chunk;
    if (!snapshot) {
      snapshot = __classPrivateFieldSet2(this, _ChatCompletionStream_currentChatCompletionSnapshot, {
        ...rest,
        choices: []
      }, "f");
    } else {
      Object.assign(snapshot, rest);
    }
    for (const { delta, finish_reason, index, logprobs = null, ...other } of chunk.choices) {
      let choice = snapshot.choices[index];
      if (!choice) {
        choice = snapshot.choices[index] = { finish_reason, index, message: {}, logprobs, ...other };
      }
      if (logprobs) {
        if (!choice.logprobs) {
          choice.logprobs = Object.assign({}, logprobs);
        } else {
          const { content: content2, refusal: refusal2, ...rest3 } = logprobs;
          assertIsEmpty(rest3);
          Object.assign(choice.logprobs, rest3);
          if (content2) {
            (_a7 = choice.logprobs).content ?? (_a7.content = []);
            choice.logprobs.content.push(...content2);
          }
          if (refusal2) {
            (_b = choice.logprobs).refusal ?? (_b.refusal = []);
            choice.logprobs.refusal.push(...refusal2);
          }
        }
      }
      if (finish_reason) {
        choice.finish_reason = finish_reason;
        if (__classPrivateFieldGet2(this, _ChatCompletionStream_params, "f") && hasAutoParseableInput(__classPrivateFieldGet2(this, _ChatCompletionStream_params, "f"))) {
          if (finish_reason === "length") {
            throw new LengthFinishReasonError();
          }
          if (finish_reason === "content_filter") {
            throw new ContentFilterFinishReasonError();
          }
        }
      }
      Object.assign(choice, other);
      if (!delta)
        continue;
      const { content, refusal, function_call, role, tool_calls, ...rest2 } = delta;
      assertIsEmpty(rest2);
      Object.assign(choice.message, rest2);
      if (refusal) {
        choice.message.refusal = (choice.message.refusal || "") + refusal;
      }
      if (role)
        choice.message.role = role;
      if (function_call) {
        if (!choice.message.function_call) {
          choice.message.function_call = function_call;
        } else {
          if (function_call.name)
            choice.message.function_call.name = function_call.name;
          if (function_call.arguments) {
            (_c = choice.message.function_call).arguments ?? (_c.arguments = "");
            choice.message.function_call.arguments += function_call.arguments;
          }
        }
      }
      if (content) {
        choice.message.content = (choice.message.content || "") + content;
        if (!choice.message.refusal && __classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getAutoParseableResponseFormat).call(this)) {
          choice.message.parsed = partialParse3(choice.message.content);
        }
      }
      if (tool_calls) {
        if (!choice.message.tool_calls)
          choice.message.tool_calls = [];
        for (const { index: index2, id, type, function: fn, ...rest3 } of tool_calls) {
          const tool_call = (_d = choice.message.tool_calls)[index2] ?? (_d[index2] = {});
          Object.assign(tool_call, rest3);
          if (id)
            tool_call.id = id;
          if (type)
            tool_call.type = type;
          if (fn)
            tool_call.function ?? (tool_call.function = { name: fn.name ?? "", arguments: "" });
          if (fn?.name)
            tool_call.function.name = fn.name;
          if (fn?.arguments) {
            tool_call.function.arguments += fn.arguments;
            if (shouldParseToolCall(__classPrivateFieldGet2(this, _ChatCompletionStream_params, "f"), tool_call)) {
              tool_call.function.parsed_arguments = partialParse3(tool_call.function.arguments);
            }
          }
        }
      }
    }
    return snapshot;
  }, Symbol.asyncIterator)]() {
    const pushQueue = [];
    const readQueue = [];
    let done = false;
    this.on("chunk", (chunk) => {
      const reader = readQueue.shift();
      if (reader) {
        reader.resolve(chunk);
      } else {
        pushQueue.push(chunk);
      }
    });
    this.on("end", () => {
      done = true;
      for (const reader of readQueue) {
        reader.resolve(void 0);
      }
      readQueue.length = 0;
    });
    this.on("abort", (err) => {
      done = true;
      for (const reader of readQueue) {
        reader.reject(err);
      }
      readQueue.length = 0;
    });
    this.on("error", (err) => {
      done = true;
      for (const reader of readQueue) {
        reader.reject(err);
      }
      readQueue.length = 0;
    });
    return {
      next: async () => {
        if (!pushQueue.length) {
          if (done) {
            return { value: void 0, done: true };
          }
          return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: void 0, done: true });
        }
        const chunk = pushQueue.shift();
        return { value: chunk, done: false };
      },
      return: async () => {
        this.abort();
        return { value: void 0, done: true };
      }
    };
  }
  toReadableStream() {
    const stream2 = new Stream2(this[Symbol.asyncIterator].bind(this), this.controller);
    return stream2.toReadableStream();
  }
};
function finalizeChatCompletion(snapshot, params) {
  const { id, choices, created, model, system_fingerprint, ...rest } = snapshot;
  const completion = {
    ...rest,
    id,
    choices: choices.map(({ message, finish_reason, index, logprobs, ...choiceRest }) => {
      if (!finish_reason) {
        throw new OpenAIError(`missing finish_reason for choice ${index}`);
      }
      const { content = null, function_call, tool_calls, ...messageRest } = message;
      const role = message.role;
      if (!role) {
        throw new OpenAIError(`missing role for choice ${index}`);
      }
      if (function_call) {
        const { arguments: args, name } = function_call;
        if (args == null) {
          throw new OpenAIError(`missing function_call.arguments for choice ${index}`);
        }
        if (!name) {
          throw new OpenAIError(`missing function_call.name for choice ${index}`);
        }
        return {
          ...choiceRest,
          message: {
            content,
            function_call: { arguments: args, name },
            role,
            refusal: message.refusal ?? null
          },
          finish_reason,
          index,
          logprobs
        };
      }
      if (tool_calls) {
        return {
          ...choiceRest,
          index,
          finish_reason,
          logprobs,
          message: {
            ...messageRest,
            role,
            content,
            refusal: message.refusal ?? null,
            tool_calls: tool_calls.map((tool_call, i7) => {
              const { function: fn, type, id: id2, ...toolRest } = tool_call;
              const { arguments: args, name, ...fnRest } = fn || {};
              if (id2 == null) {
                throw new OpenAIError(`missing choices[${index}].tool_calls[${i7}].id
${str(snapshot)}`);
              }
              if (type == null) {
                throw new OpenAIError(`missing choices[${index}].tool_calls[${i7}].type
${str(snapshot)}`);
              }
              if (name == null) {
                throw new OpenAIError(`missing choices[${index}].tool_calls[${i7}].function.name
${str(snapshot)}`);
              }
              if (args == null) {
                throw new OpenAIError(`missing choices[${index}].tool_calls[${i7}].function.arguments
${str(snapshot)}`);
              }
              return { ...toolRest, id: id2, type, function: { ...fnRest, name, arguments: args } };
            })
          }
        };
      }
      return {
        ...choiceRest,
        message: { ...messageRest, content, role, refusal: message.refusal ?? null },
        finish_reason,
        index,
        logprobs
      };
    }),
    created,
    model,
    object: "chat.completion",
    ...system_fingerprint ? { system_fingerprint } : {}
  };
  return maybeParseChatCompletion(completion, params);
}
function str(x2) {
  return JSON.stringify(x2);
}
function assertIsEmpty(obj) {
  return;
}
function assertNever(_x) {
}

// ../pi-mono/node_modules/openai/lib/ChatCompletionStreamingRunner.mjs
var ChatCompletionStreamingRunner = class _ChatCompletionStreamingRunner extends ChatCompletionStream {
  static fromReadableStream(stream2) {
    const runner = new _ChatCompletionStreamingRunner(null);
    runner._run(() => runner._fromReadableStream(stream2));
    return runner;
  }
  static runTools(client, params, options) {
    const runner = new _ChatCompletionStreamingRunner(
      // @ts-expect-error TODO these types are incompatible
      params
    );
    const opts = {
      ...options,
      headers: { ...options?.headers, "X-Stainless-Helper-Method": "runTools" }
    };
    runner._run(() => runner._runTools(client, params, opts));
    return runner;
  }
};

// ../pi-mono/node_modules/openai/resources/chat/completions/completions.mjs
var Completions2 = class extends APIResource2 {
  constructor() {
    super(...arguments);
    this.messages = new Messages3(this._client);
  }
  create(body, options) {
    return this._client.post("/chat/completions", { body, ...options, stream: body.stream ?? false });
  }
  /**
   * Get a stored chat completion. Only Chat Completions that have been created with
   * the `store` parameter set to `true` will be returned.
   *
   * @example
   * ```ts
   * const chatCompletion =
   *   await client.chat.completions.retrieve('completion_id');
   * ```
   */
  retrieve(completionID, options) {
    return this._client.get(path2`/chat/completions/${completionID}`, options);
  }
  /**
   * Modify a stored chat completion. Only Chat Completions that have been created
   * with the `store` parameter set to `true` can be modified. Currently, the only
   * supported modification is to update the `metadata` field.
   *
   * @example
   * ```ts
   * const chatCompletion = await client.chat.completions.update(
   *   'completion_id',
   *   { metadata: { foo: 'string' } },
   * );
   * ```
   */
  update(completionID, body, options) {
    return this._client.post(path2`/chat/completions/${completionID}`, { body, ...options });
  }
  /**
   * List stored Chat Completions. Only Chat Completions that have been stored with
   * the `store` parameter set to `true` will be returned.
   *
   * @example
   * ```ts
   * // Automatically fetches more pages as needed.
   * for await (const chatCompletion of client.chat.completions.list()) {
   *   // ...
   * }
   * ```
   */
  list(query = {}, options) {
    return this._client.getAPIList("/chat/completions", CursorPage, { query, ...options });
  }
  /**
   * Delete a stored chat completion. Only Chat Completions that have been created
   * with the `store` parameter set to `true` can be deleted.
   *
   * @example
   * ```ts
   * const chatCompletionDeleted =
   *   await client.chat.completions.delete('completion_id');
   * ```
   */
  delete(completionID, options) {
    return this._client.delete(path2`/chat/completions/${completionID}`, options);
  }
  parse(body, options) {
    validateInputTools(body.tools);
    return this._client.chat.completions.create(body, {
      ...options,
      headers: {
        ...options?.headers,
        "X-Stainless-Helper-Method": "chat.completions.parse"
      }
    })._thenUnwrap((completion) => parseChatCompletion(completion, body));
  }
  runTools(body, options) {
    if (body.stream) {
      return ChatCompletionStreamingRunner.runTools(this._client, body, options);
    }
    return ChatCompletionRunner.runTools(this._client, body, options);
  }
  /**
   * Creates a chat completion stream
   */
  stream(body, options) {
    return ChatCompletionStream.createChatCompletion(this._client, body, options);
  }
};
Completions2.Messages = Messages3;

// ../pi-mono/node_modules/openai/resources/chat/chat.mjs
var Chat = class extends APIResource2 {
  constructor() {
    super(...arguments);
    this.completions = new Completions2(this._client);
  }
};
Chat.Completions = Completions2;

// ../pi-mono/node_modules/openai/resources/chat/completions/index.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/resources/shared.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/resources/audio/audio.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/resources/audio/speech.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/internal/headers.mjs
init_process_shim();
var brand_privateNullableHeaders2 = /* @__PURE__ */ Symbol("brand.privateNullableHeaders");
function* iterateHeaders2(headers) {
  if (!headers)
    return;
  if (brand_privateNullableHeaders2 in headers) {
    const { values: values2, nulls } = headers;
    yield* values2.entries();
    for (const name of nulls) {
      yield [name, null];
    }
    return;
  }
  let shouldClear = false;
  let iter;
  if (headers instanceof Headers) {
    iter = headers.entries();
  } else if (isReadonlyArray2(headers)) {
    iter = headers;
  } else {
    shouldClear = true;
    iter = Object.entries(headers ?? {});
  }
  for (let row of iter) {
    const name = row[0];
    if (typeof name !== "string")
      throw new TypeError("expected header name to be a string");
    const values2 = isReadonlyArray2(row[1]) ? row[1] : [row[1]];
    let didClear = false;
    for (const value of values2) {
      if (value === void 0)
        continue;
      if (shouldClear && !didClear) {
        didClear = true;
        yield [name, null];
      }
      yield [name, value];
    }
  }
}
var buildHeaders2 = (newHeaders) => {
  const targetHeaders = new Headers();
  const nullHeaders = /* @__PURE__ */ new Set();
  for (const headers of newHeaders) {
    const seenHeaders = /* @__PURE__ */ new Set();
    for (const [name, value] of iterateHeaders2(headers)) {
      const lowerName = name.toLowerCase();
      if (!seenHeaders.has(lowerName)) {
        targetHeaders.delete(name);
        seenHeaders.add(lowerName);
      }
      if (value === null) {
        targetHeaders.delete(name);
        nullHeaders.add(lowerName);
      } else {
        targetHeaders.append(name, value);
        nullHeaders.delete(lowerName);
      }
    }
  }
  return { [brand_privateNullableHeaders2]: true, values: targetHeaders, nulls: nullHeaders };
};

// ../pi-mono/node_modules/openai/resources/audio/speech.mjs
var Speech = class extends APIResource2 {
  /**
   * Generates audio from the input text.
   *
   * Returns the audio file content, or a stream of audio events.
   *
   * @example
   * ```ts
   * const speech = await client.audio.speech.create({
   *   input: 'input',
   *   model: 'string',
   *   voice: 'ash',
   * });
   *
   * const content = await speech.blob();
   * console.log(content);
   * ```
   */
  create(body, options) {
    return this._client.post("/audio/speech", {
      body,
      ...options,
      headers: buildHeaders2([{ Accept: "application/octet-stream" }, options?.headers]),
      __binaryResponse: true
    });
  }
};

// ../pi-mono/node_modules/openai/resources/audio/transcriptions.mjs
init_process_shim();
var Transcriptions = class extends APIResource2 {
  create(body, options) {
    return this._client.post("/audio/transcriptions", multipartFormRequestOptions2({
      body,
      ...options,
      stream: body.stream ?? false,
      __metadata: { model: body.model }
    }, this._client));
  }
};

// ../pi-mono/node_modules/openai/resources/audio/translations.mjs
init_process_shim();
var Translations = class extends APIResource2 {
  create(body, options) {
    return this._client.post("/audio/translations", multipartFormRequestOptions2({ body, ...options, __metadata: { model: body.model } }, this._client));
  }
};

// ../pi-mono/node_modules/openai/resources/audio/audio.mjs
var Audio = class extends APIResource2 {
  constructor() {
    super(...arguments);
    this.transcriptions = new Transcriptions(this._client);
    this.translations = new Translations(this._client);
    this.speech = new Speech(this._client);
  }
};
Audio.Transcriptions = Transcriptions;
Audio.Translations = Translations;
Audio.Speech = Speech;

// ../pi-mono/node_modules/openai/resources/batches.mjs
init_process_shim();
var Batches3 = class extends APIResource2 {
  /**
   * Creates and executes a batch from an uploaded file of requests
   */
  create(body, options) {
    return this._client.post("/batches", { body, ...options });
  }
  /**
   * Retrieves a batch.
   */
  retrieve(batchID, options) {
    return this._client.get(path2`/batches/${batchID}`, options);
  }
  /**
   * List your organization's batches.
   */
  list(query = {}, options) {
    return this._client.getAPIList("/batches", CursorPage, { query, ...options });
  }
  /**
   * Cancels an in-progress batch. The batch will be in status `cancelling` for up to
   * 10 minutes, before changing to `cancelled`, where it will have partial results
   * (if any) available in the output file.
   */
  cancel(batchID, options) {
    return this._client.post(path2`/batches/${batchID}/cancel`, options);
  }
};

// ../pi-mono/node_modules/openai/resources/beta/beta.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/resources/beta/assistants.mjs
init_process_shim();
var Assistants = class extends APIResource2 {
  /**
   * Create an assistant with a model and instructions.
   *
   * @deprecated
   */
  create(body, options) {
    return this._client.post("/assistants", {
      body,
      ...options,
      headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers])
    });
  }
  /**
   * Retrieves an assistant.
   *
   * @deprecated
   */
  retrieve(assistantID, options) {
    return this._client.get(path2`/assistants/${assistantID}`, {
      ...options,
      headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers])
    });
  }
  /**
   * Modifies an assistant.
   *
   * @deprecated
   */
  update(assistantID, body, options) {
    return this._client.post(path2`/assistants/${assistantID}`, {
      body,
      ...options,
      headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers])
    });
  }
  /**
   * Returns a list of assistants.
   *
   * @deprecated
   */
  list(query = {}, options) {
    return this._client.getAPIList("/assistants", CursorPage, {
      query,
      ...options,
      headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers])
    });
  }
  /**
   * Delete an assistant.
   *
   * @deprecated
   */
  delete(assistantID, options) {
    return this._client.delete(path2`/assistants/${assistantID}`, {
      ...options,
      headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers])
    });
  }
};

// ../pi-mono/node_modules/openai/resources/beta/realtime/realtime.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/resources/beta/realtime/sessions.mjs
init_process_shim();
var Sessions = class extends APIResource2 {
  /**
   * Create an ephemeral API token for use in client-side applications with the
   * Realtime API. Can be configured with the same session parameters as the
   * `session.update` client event.
   *
   * It responds with a session object, plus a `client_secret` key which contains a
   * usable ephemeral API token that can be used to authenticate browser clients for
   * the Realtime API.
   *
   * @example
   * ```ts
   * const session =
   *   await client.beta.realtime.sessions.create();
   * ```
   */
  create(body, options) {
    return this._client.post("/realtime/sessions", {
      body,
      ...options,
      headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers])
    });
  }
};

// ../pi-mono/node_modules/openai/resources/beta/realtime/transcription-sessions.mjs
init_process_shim();
var TranscriptionSessions = class extends APIResource2 {
  /**
   * Create an ephemeral API token for use in client-side applications with the
   * Realtime API specifically for realtime transcriptions. Can be configured with
   * the same session parameters as the `transcription_session.update` client event.
   *
   * It responds with a session object, plus a `client_secret` key which contains a
   * usable ephemeral API token that can be used to authenticate browser clients for
   * the Realtime API.
   *
   * @example
   * ```ts
   * const transcriptionSession =
   *   await client.beta.realtime.transcriptionSessions.create();
   * ```
   */
  create(body, options) {
    return this._client.post("/realtime/transcription_sessions", {
      body,
      ...options,
      headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers])
    });
  }
};

// ../pi-mono/node_modules/openai/resources/beta/realtime/realtime.mjs
var Realtime = class extends APIResource2 {
  constructor() {
    super(...arguments);
    this.sessions = new Sessions(this._client);
    this.transcriptionSessions = new TranscriptionSessions(this._client);
  }
};
Realtime.Sessions = Sessions;
Realtime.TranscriptionSessions = TranscriptionSessions;

// ../pi-mono/node_modules/openai/resources/beta/chatkit/chatkit.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/resources/beta/chatkit/sessions.mjs
init_process_shim();
var Sessions2 = class extends APIResource2 {
  /**
   * Create a ChatKit session.
   *
   * @example
   * ```ts
   * const chatSession =
   *   await client.beta.chatkit.sessions.create({
   *     user: 'x',
   *     workflow: { id: 'id' },
   *   });
   * ```
   */
  create(body, options) {
    return this._client.post("/chatkit/sessions", {
      body,
      ...options,
      headers: buildHeaders2([{ "OpenAI-Beta": "chatkit_beta=v1" }, options?.headers])
    });
  }
  /**
   * Cancel an active ChatKit session and return its most recent metadata.
   *
   * Cancelling prevents new requests from using the issued client secret.
   *
   * @example
   * ```ts
   * const chatSession =
   *   await client.beta.chatkit.sessions.cancel('cksess_123');
   * ```
   */
  cancel(sessionID, options) {
    return this._client.post(path2`/chatkit/sessions/${sessionID}/cancel`, {
      ...options,
      headers: buildHeaders2([{ "OpenAI-Beta": "chatkit_beta=v1" }, options?.headers])
    });
  }
};

// ../pi-mono/node_modules/openai/resources/beta/chatkit/threads.mjs
init_process_shim();
var Threads = class extends APIResource2 {
  /**
   * Retrieve a ChatKit thread by its identifier.
   *
   * @example
   * ```ts
   * const chatkitThread =
   *   await client.beta.chatkit.threads.retrieve('cthr_123');
   * ```
   */
  retrieve(threadID, options) {
    return this._client.get(path2`/chatkit/threads/${threadID}`, {
      ...options,
      headers: buildHeaders2([{ "OpenAI-Beta": "chatkit_beta=v1" }, options?.headers])
    });
  }
  /**
   * List ChatKit threads with optional pagination and user filters.
   *
   * @example
   * ```ts
   * // Automatically fetches more pages as needed.
   * for await (const chatkitThread of client.beta.chatkit.threads.list()) {
   *   // ...
   * }
   * ```
   */
  list(query = {}, options) {
    return this._client.getAPIList("/chatkit/threads", ConversationCursorPage, {
      query,
      ...options,
      headers: buildHeaders2([{ "OpenAI-Beta": "chatkit_beta=v1" }, options?.headers])
    });
  }
  /**
   * Delete a ChatKit thread along with its items and stored attachments.
   *
   * @example
   * ```ts
   * const thread = await client.beta.chatkit.threads.delete(
   *   'cthr_123',
   * );
   * ```
   */
  delete(threadID, options) {
    return this._client.delete(path2`/chatkit/threads/${threadID}`, {
      ...options,
      headers: buildHeaders2([{ "OpenAI-Beta": "chatkit_beta=v1" }, options?.headers])
    });
  }
  /**
   * List items that belong to a ChatKit thread.
   *
   * @example
   * ```ts
   * // Automatically fetches more pages as needed.
   * for await (const thread of client.beta.chatkit.threads.listItems(
   *   'cthr_123',
   * )) {
   *   // ...
   * }
   * ```
   */
  listItems(threadID, query = {}, options) {
    return this._client.getAPIList(path2`/chatkit/threads/${threadID}/items`, ConversationCursorPage, { query, ...options, headers: buildHeaders2([{ "OpenAI-Beta": "chatkit_beta=v1" }, options?.headers]) });
  }
};

// ../pi-mono/node_modules/openai/resources/beta/chatkit/chatkit.mjs
var ChatKit = class extends APIResource2 {
  constructor() {
    super(...arguments);
    this.sessions = new Sessions2(this._client);
    this.threads = new Threads(this._client);
  }
};
ChatKit.Sessions = Sessions2;
ChatKit.Threads = Threads;

// ../pi-mono/node_modules/openai/resources/beta/threads/threads.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/resources/beta/threads/messages.mjs
init_process_shim();
var Messages4 = class extends APIResource2 {
  /**
   * Create a message.
   *
   * @deprecated The Assistants API is deprecated in favor of the Responses API
   */
  create(threadID, body, options) {
    return this._client.post(path2`/threads/${threadID}/messages`, {
      body,
      ...options,
      headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers])
    });
  }
  /**
   * Retrieve a message.
   *
   * @deprecated The Assistants API is deprecated in favor of the Responses API
   */
  retrieve(messageID, params, options) {
    const { thread_id } = params;
    return this._client.get(path2`/threads/${thread_id}/messages/${messageID}`, {
      ...options,
      headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers])
    });
  }
  /**
   * Modifies a message.
   *
   * @deprecated The Assistants API is deprecated in favor of the Responses API
   */
  update(messageID, params, options) {
    const { thread_id, ...body } = params;
    return this._client.post(path2`/threads/${thread_id}/messages/${messageID}`, {
      body,
      ...options,
      headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers])
    });
  }
  /**
   * Returns a list of messages for a given thread.
   *
   * @deprecated The Assistants API is deprecated in favor of the Responses API
   */
  list(threadID, query = {}, options) {
    return this._client.getAPIList(path2`/threads/${threadID}/messages`, CursorPage, {
      query,
      ...options,
      headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers])
    });
  }
  /**
   * Deletes a message.
   *
   * @deprecated The Assistants API is deprecated in favor of the Responses API
   */
  delete(messageID, params, options) {
    const { thread_id } = params;
    return this._client.delete(path2`/threads/${thread_id}/messages/${messageID}`, {
      ...options,
      headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers])
    });
  }
};

// ../pi-mono/node_modules/openai/resources/beta/threads/runs/runs.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/resources/beta/threads/runs/steps.mjs
init_process_shim();
var Steps = class extends APIResource2 {
  /**
   * Retrieves a run step.
   *
   * @deprecated The Assistants API is deprecated in favor of the Responses API
   */
  retrieve(stepID, params, options) {
    const { thread_id, run_id, ...query } = params;
    return this._client.get(path2`/threads/${thread_id}/runs/${run_id}/steps/${stepID}`, {
      query,
      ...options,
      headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers])
    });
  }
  /**
   * Returns a list of run steps belonging to a run.
   *
   * @deprecated The Assistants API is deprecated in favor of the Responses API
   */
  list(runID, params, options) {
    const { thread_id, ...query } = params;
    return this._client.getAPIList(path2`/threads/${thread_id}/runs/${runID}/steps`, CursorPage, {
      query,
      ...options,
      headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers])
    });
  }
};

// ../pi-mono/node_modules/openai/lib/AssistantStream.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/internal/utils.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/internal/utils/base64.mjs
init_process_shim();
var toFloat32Array = (base64Str) => {
  if (typeof Buffer !== "undefined") {
    const buf = Buffer.from(base64Str, "base64");
    return Array.from(new Float32Array(buf.buffer, buf.byteOffset, buf.length / Float32Array.BYTES_PER_ELEMENT));
  } else {
    const binaryStr = atob(base64Str);
    const len = binaryStr.length;
    const bytes = new Uint8Array(len);
    for (let i7 = 0; i7 < len; i7++) {
      bytes[i7] = binaryStr.charCodeAt(i7);
    }
    return Array.from(new Float32Array(bytes.buffer));
  }
};

// ../pi-mono/node_modules/openai/internal/utils/env.mjs
init_process_shim();
var readEnv2 = (env) => {
  if (typeof globalThis.process !== "undefined") {
    return globalThis.process.env?.[env]?.trim() ?? void 0;
  }
  if (typeof globalThis.Deno !== "undefined") {
    return globalThis.Deno.env?.get?.(env)?.trim();
  }
  return void 0;
};

// ../pi-mono/node_modules/openai/lib/AssistantStream.mjs
var _AssistantStream_instances;
var _a2;
var _AssistantStream_events;
var _AssistantStream_runStepSnapshots;
var _AssistantStream_messageSnapshots;
var _AssistantStream_messageSnapshot;
var _AssistantStream_finalRun;
var _AssistantStream_currentContentIndex;
var _AssistantStream_currentContent;
var _AssistantStream_currentToolCallIndex;
var _AssistantStream_currentToolCall;
var _AssistantStream_currentEvent;
var _AssistantStream_currentRunSnapshot;
var _AssistantStream_currentRunStepSnapshot;
var _AssistantStream_addEvent;
var _AssistantStream_endRequest;
var _AssistantStream_handleMessage;
var _AssistantStream_handleRunStep;
var _AssistantStream_handleEvent;
var _AssistantStream_accumulateRunStep;
var _AssistantStream_accumulateMessage;
var _AssistantStream_accumulateContent;
var _AssistantStream_handleRun;
var AssistantStream = class extends EventStream2 {
  constructor() {
    super(...arguments);
    _AssistantStream_instances.add(this);
    _AssistantStream_events.set(this, []);
    _AssistantStream_runStepSnapshots.set(this, {});
    _AssistantStream_messageSnapshots.set(this, {});
    _AssistantStream_messageSnapshot.set(this, void 0);
    _AssistantStream_finalRun.set(this, void 0);
    _AssistantStream_currentContentIndex.set(this, void 0);
    _AssistantStream_currentContent.set(this, void 0);
    _AssistantStream_currentToolCallIndex.set(this, void 0);
    _AssistantStream_currentToolCall.set(this, void 0);
    _AssistantStream_currentEvent.set(this, void 0);
    _AssistantStream_currentRunSnapshot.set(this, void 0);
    _AssistantStream_currentRunStepSnapshot.set(this, void 0);
  }
  [(_AssistantStream_events = /* @__PURE__ */ new WeakMap(), _AssistantStream_runStepSnapshots = /* @__PURE__ */ new WeakMap(), _AssistantStream_messageSnapshots = /* @__PURE__ */ new WeakMap(), _AssistantStream_messageSnapshot = /* @__PURE__ */ new WeakMap(), _AssistantStream_finalRun = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentContentIndex = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentContent = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentToolCallIndex = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentToolCall = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentEvent = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentRunSnapshot = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentRunStepSnapshot = /* @__PURE__ */ new WeakMap(), _AssistantStream_instances = /* @__PURE__ */ new WeakSet(), Symbol.asyncIterator)]() {
    const pushQueue = [];
    const readQueue = [];
    let done = false;
    this.on("event", (event) => {
      const reader = readQueue.shift();
      if (reader) {
        reader.resolve(event);
      } else {
        pushQueue.push(event);
      }
    });
    this.on("end", () => {
      done = true;
      for (const reader of readQueue) {
        reader.resolve(void 0);
      }
      readQueue.length = 0;
    });
    this.on("abort", (err) => {
      done = true;
      for (const reader of readQueue) {
        reader.reject(err);
      }
      readQueue.length = 0;
    });
    this.on("error", (err) => {
      done = true;
      for (const reader of readQueue) {
        reader.reject(err);
      }
      readQueue.length = 0;
    });
    return {
      next: async () => {
        if (!pushQueue.length) {
          if (done) {
            return { value: void 0, done: true };
          }
          return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: void 0, done: true });
        }
        const chunk = pushQueue.shift();
        return { value: chunk, done: false };
      },
      return: async () => {
        this.abort();
        return { value: void 0, done: true };
      }
    };
  }
  static fromReadableStream(stream2) {
    const runner = new _a2();
    runner._run(() => runner._fromReadableStream(stream2));
    return runner;
  }
  async _fromReadableStream(readableStream, options) {
    const signal = options?.signal;
    if (signal) {
      if (signal.aborted)
        this.controller.abort();
      signal.addEventListener("abort", () => this.controller.abort());
    }
    this._connected();
    const stream2 = Stream2.fromReadableStream(readableStream, this.controller);
    for await (const event of stream2) {
      __classPrivateFieldGet2(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
    }
    if (stream2.controller.signal?.aborted) {
      throw new APIUserAbortError2();
    }
    return this._addRun(__classPrivateFieldGet2(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
  }
  toReadableStream() {
    const stream2 = new Stream2(this[Symbol.asyncIterator].bind(this), this.controller);
    return stream2.toReadableStream();
  }
  static createToolAssistantStream(runId, runs, params, options) {
    const runner = new _a2();
    runner._run(() => runner._runToolAssistantStream(runId, runs, params, {
      ...options,
      headers: { ...options?.headers, "X-Stainless-Helper-Method": "stream" }
    }));
    return runner;
  }
  async _createToolAssistantStream(run, runId, params, options) {
    const signal = options?.signal;
    if (signal) {
      if (signal.aborted)
        this.controller.abort();
      signal.addEventListener("abort", () => this.controller.abort());
    }
    const body = { ...params, stream: true };
    const stream2 = await run.submitToolOutputs(runId, body, {
      ...options,
      signal: this.controller.signal
    });
    this._connected();
    for await (const event of stream2) {
      __classPrivateFieldGet2(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
    }
    if (stream2.controller.signal?.aborted) {
      throw new APIUserAbortError2();
    }
    return this._addRun(__classPrivateFieldGet2(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
  }
  static createThreadAssistantStream(params, thread, options) {
    const runner = new _a2();
    runner._run(() => runner._threadAssistantStream(params, thread, {
      ...options,
      headers: { ...options?.headers, "X-Stainless-Helper-Method": "stream" }
    }));
    return runner;
  }
  static createAssistantStream(threadId, runs, params, options) {
    const runner = new _a2();
    runner._run(() => runner._runAssistantStream(threadId, runs, params, {
      ...options,
      headers: { ...options?.headers, "X-Stainless-Helper-Method": "stream" }
    }));
    return runner;
  }
  currentEvent() {
    return __classPrivateFieldGet2(this, _AssistantStream_currentEvent, "f");
  }
  currentRun() {
    return __classPrivateFieldGet2(this, _AssistantStream_currentRunSnapshot, "f");
  }
  currentMessageSnapshot() {
    return __classPrivateFieldGet2(this, _AssistantStream_messageSnapshot, "f");
  }
  currentRunStepSnapshot() {
    return __classPrivateFieldGet2(this, _AssistantStream_currentRunStepSnapshot, "f");
  }
  async finalRunSteps() {
    await this.done();
    return Object.values(__classPrivateFieldGet2(this, _AssistantStream_runStepSnapshots, "f"));
  }
  async finalMessages() {
    await this.done();
    return Object.values(__classPrivateFieldGet2(this, _AssistantStream_messageSnapshots, "f"));
  }
  async finalRun() {
    await this.done();
    if (!__classPrivateFieldGet2(this, _AssistantStream_finalRun, "f"))
      throw Error("Final run was not received.");
    return __classPrivateFieldGet2(this, _AssistantStream_finalRun, "f");
  }
  async _createThreadAssistantStream(thread, params, options) {
    const signal = options?.signal;
    if (signal) {
      if (signal.aborted)
        this.controller.abort();
      signal.addEventListener("abort", () => this.controller.abort());
    }
    const body = { ...params, stream: true };
    const stream2 = await thread.createAndRun(body, { ...options, signal: this.controller.signal });
    this._connected();
    for await (const event of stream2) {
      __classPrivateFieldGet2(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
    }
    if (stream2.controller.signal?.aborted) {
      throw new APIUserAbortError2();
    }
    return this._addRun(__classPrivateFieldGet2(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
  }
  async _createAssistantStream(run, threadId, params, options) {
    const signal = options?.signal;
    if (signal) {
      if (signal.aborted)
        this.controller.abort();
      signal.addEventListener("abort", () => this.controller.abort());
    }
    const body = { ...params, stream: true };
    const stream2 = await run.create(threadId, body, { ...options, signal: this.controller.signal });
    this._connected();
    for await (const event of stream2) {
      __classPrivateFieldGet2(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
    }
    if (stream2.controller.signal?.aborted) {
      throw new APIUserAbortError2();
    }
    return this._addRun(__classPrivateFieldGet2(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
  }
  static accumulateDelta(acc, delta) {
    for (const [key, deltaValue] of Object.entries(delta)) {
      if (!acc.hasOwnProperty(key)) {
        acc[key] = deltaValue;
        continue;
      }
      let accValue = acc[key];
      if (accValue === null || accValue === void 0) {
        acc[key] = deltaValue;
        continue;
      }
      if (key === "index" || key === "type") {
        acc[key] = deltaValue;
        continue;
      }
      if (typeof accValue === "string" && typeof deltaValue === "string") {
        accValue += deltaValue;
      } else if (typeof accValue === "number" && typeof deltaValue === "number") {
        accValue += deltaValue;
      } else if (isObj(accValue) && isObj(deltaValue)) {
        accValue = this.accumulateDelta(accValue, deltaValue);
      } else if (Array.isArray(accValue) && Array.isArray(deltaValue)) {
        if (accValue.every((x2) => typeof x2 === "string" || typeof x2 === "number")) {
          accValue.push(...deltaValue);
          continue;
        }
        for (const deltaEntry of deltaValue) {
          if (!isObj(deltaEntry)) {
            throw new Error(`Expected array delta entry to be an object but got: ${deltaEntry}`);
          }
          const index = deltaEntry["index"];
          if (index == null) {
            console.error(deltaEntry);
            throw new Error("Expected array delta entry to have an `index` property");
          }
          if (typeof index !== "number") {
            throw new Error(`Expected array delta entry \`index\` property to be a number but got ${index}`);
          }
          const accEntry = accValue[index];
          if (accEntry == null) {
            accValue.push(deltaEntry);
          } else {
            accValue[index] = this.accumulateDelta(accEntry, deltaEntry);
          }
        }
        continue;
      } else {
        throw Error(`Unhandled record type: ${key}, deltaValue: ${deltaValue}, accValue: ${accValue}`);
      }
      acc[key] = accValue;
    }
    return acc;
  }
  _addRun(run) {
    return run;
  }
  async _threadAssistantStream(params, thread, options) {
    return await this._createThreadAssistantStream(thread, params, options);
  }
  async _runAssistantStream(threadId, runs, params, options) {
    return await this._createAssistantStream(runs, threadId, params, options);
  }
  async _runToolAssistantStream(runId, runs, params, options) {
    return await this._createToolAssistantStream(runs, runId, params, options);
  }
};
_a2 = AssistantStream, _AssistantStream_addEvent = function _AssistantStream_addEvent2(event) {
  if (this.ended)
    return;
  __classPrivateFieldSet2(this, _AssistantStream_currentEvent, event, "f");
  __classPrivateFieldGet2(this, _AssistantStream_instances, "m", _AssistantStream_handleEvent).call(this, event);
  switch (event.event) {
    case "thread.created":
      break;
    case "thread.run.created":
    case "thread.run.queued":
    case "thread.run.in_progress":
    case "thread.run.requires_action":
    case "thread.run.completed":
    case "thread.run.incomplete":
    case "thread.run.failed":
    case "thread.run.cancelling":
    case "thread.run.cancelled":
    case "thread.run.expired":
      __classPrivateFieldGet2(this, _AssistantStream_instances, "m", _AssistantStream_handleRun).call(this, event);
      break;
    case "thread.run.step.created":
    case "thread.run.step.in_progress":
    case "thread.run.step.delta":
    case "thread.run.step.completed":
    case "thread.run.step.failed":
    case "thread.run.step.cancelled":
    case "thread.run.step.expired":
      __classPrivateFieldGet2(this, _AssistantStream_instances, "m", _AssistantStream_handleRunStep).call(this, event);
      break;
    case "thread.message.created":
    case "thread.message.in_progress":
    case "thread.message.delta":
    case "thread.message.completed":
    case "thread.message.incomplete":
      __classPrivateFieldGet2(this, _AssistantStream_instances, "m", _AssistantStream_handleMessage).call(this, event);
      break;
    case "error":
      throw new Error("Encountered an error event in event processing - errors should be processed earlier");
    default:
      assertNever2(event);
  }
}, _AssistantStream_endRequest = function _AssistantStream_endRequest2() {
  if (this.ended) {
    throw new OpenAIError(`stream has ended, this shouldn't happen`);
  }
  if (!__classPrivateFieldGet2(this, _AssistantStream_finalRun, "f"))
    throw Error("Final run has not been received");
  return __classPrivateFieldGet2(this, _AssistantStream_finalRun, "f");
}, _AssistantStream_handleMessage = function _AssistantStream_handleMessage2(event) {
  const [accumulatedMessage, newContent] = __classPrivateFieldGet2(this, _AssistantStream_instances, "m", _AssistantStream_accumulateMessage).call(this, event, __classPrivateFieldGet2(this, _AssistantStream_messageSnapshot, "f"));
  __classPrivateFieldSet2(this, _AssistantStream_messageSnapshot, accumulatedMessage, "f");
  __classPrivateFieldGet2(this, _AssistantStream_messageSnapshots, "f")[accumulatedMessage.id] = accumulatedMessage;
  for (const content of newContent) {
    const snapshotContent = accumulatedMessage.content[content.index];
    if (snapshotContent?.type == "text") {
      this._emit("textCreated", snapshotContent.text);
    }
  }
  switch (event.event) {
    case "thread.message.created":
      this._emit("messageCreated", event.data);
      break;
    case "thread.message.in_progress":
      break;
    case "thread.message.delta":
      this._emit("messageDelta", event.data.delta, accumulatedMessage);
      if (event.data.delta.content) {
        for (const content of event.data.delta.content) {
          if (content.type == "text" && content.text) {
            let textDelta = content.text;
            let snapshot = accumulatedMessage.content[content.index];
            if (snapshot && snapshot.type == "text") {
              this._emit("textDelta", textDelta, snapshot.text);
            } else {
              throw Error("The snapshot associated with this text delta is not text or missing");
            }
          }
          if (content.index != __classPrivateFieldGet2(this, _AssistantStream_currentContentIndex, "f")) {
            if (__classPrivateFieldGet2(this, _AssistantStream_currentContent, "f")) {
              switch (__classPrivateFieldGet2(this, _AssistantStream_currentContent, "f").type) {
                case "text":
                  this._emit("textDone", __classPrivateFieldGet2(this, _AssistantStream_currentContent, "f").text, __classPrivateFieldGet2(this, _AssistantStream_messageSnapshot, "f"));
                  break;
                case "image_file":
                  this._emit("imageFileDone", __classPrivateFieldGet2(this, _AssistantStream_currentContent, "f").image_file, __classPrivateFieldGet2(this, _AssistantStream_messageSnapshot, "f"));
                  break;
              }
            }
            __classPrivateFieldSet2(this, _AssistantStream_currentContentIndex, content.index, "f");
          }
          __classPrivateFieldSet2(this, _AssistantStream_currentContent, accumulatedMessage.content[content.index], "f");
        }
      }
      break;
    case "thread.message.completed":
    case "thread.message.incomplete":
      if (__classPrivateFieldGet2(this, _AssistantStream_currentContentIndex, "f") !== void 0) {
        const currentContent = event.data.content[__classPrivateFieldGet2(this, _AssistantStream_currentContentIndex, "f")];
        if (currentContent) {
          switch (currentContent.type) {
            case "image_file":
              this._emit("imageFileDone", currentContent.image_file, __classPrivateFieldGet2(this, _AssistantStream_messageSnapshot, "f"));
              break;
            case "text":
              this._emit("textDone", currentContent.text, __classPrivateFieldGet2(this, _AssistantStream_messageSnapshot, "f"));
              break;
          }
        }
      }
      if (__classPrivateFieldGet2(this, _AssistantStream_messageSnapshot, "f")) {
        this._emit("messageDone", event.data);
      }
      __classPrivateFieldSet2(this, _AssistantStream_messageSnapshot, void 0, "f");
  }
}, _AssistantStream_handleRunStep = function _AssistantStream_handleRunStep2(event) {
  const accumulatedRunStep = __classPrivateFieldGet2(this, _AssistantStream_instances, "m", _AssistantStream_accumulateRunStep).call(this, event);
  __classPrivateFieldSet2(this, _AssistantStream_currentRunStepSnapshot, accumulatedRunStep, "f");
  switch (event.event) {
    case "thread.run.step.created":
      this._emit("runStepCreated", event.data);
      break;
    case "thread.run.step.delta":
      const delta = event.data.delta;
      if (delta.step_details && delta.step_details.type == "tool_calls" && delta.step_details.tool_calls && accumulatedRunStep.step_details.type == "tool_calls") {
        for (const toolCall of delta.step_details.tool_calls) {
          if (toolCall.index == __classPrivateFieldGet2(this, _AssistantStream_currentToolCallIndex, "f")) {
            this._emit("toolCallDelta", toolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index]);
          } else {
            if (__classPrivateFieldGet2(this, _AssistantStream_currentToolCall, "f")) {
              this._emit("toolCallDone", __classPrivateFieldGet2(this, _AssistantStream_currentToolCall, "f"));
            }
            __classPrivateFieldSet2(this, _AssistantStream_currentToolCallIndex, toolCall.index, "f");
            __classPrivateFieldSet2(this, _AssistantStream_currentToolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index], "f");
            if (__classPrivateFieldGet2(this, _AssistantStream_currentToolCall, "f"))
              this._emit("toolCallCreated", __classPrivateFieldGet2(this, _AssistantStream_currentToolCall, "f"));
          }
        }
      }
      this._emit("runStepDelta", event.data.delta, accumulatedRunStep);
      break;
    case "thread.run.step.completed":
    case "thread.run.step.failed":
    case "thread.run.step.cancelled":
    case "thread.run.step.expired":
      __classPrivateFieldSet2(this, _AssistantStream_currentRunStepSnapshot, void 0, "f");
      const details = event.data.step_details;
      if (details.type == "tool_calls") {
        if (__classPrivateFieldGet2(this, _AssistantStream_currentToolCall, "f")) {
          this._emit("toolCallDone", __classPrivateFieldGet2(this, _AssistantStream_currentToolCall, "f"));
          __classPrivateFieldSet2(this, _AssistantStream_currentToolCall, void 0, "f");
        }
      }
      this._emit("runStepDone", event.data, accumulatedRunStep);
      break;
    case "thread.run.step.in_progress":
      break;
  }
}, _AssistantStream_handleEvent = function _AssistantStream_handleEvent2(event) {
  __classPrivateFieldGet2(this, _AssistantStream_events, "f").push(event);
  this._emit("event", event);
}, _AssistantStream_accumulateRunStep = function _AssistantStream_accumulateRunStep2(event) {
  switch (event.event) {
    case "thread.run.step.created":
      __classPrivateFieldGet2(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = event.data;
      return event.data;
    case "thread.run.step.delta":
      let snapshot = __classPrivateFieldGet2(this, _AssistantStream_runStepSnapshots, "f")[event.data.id];
      if (!snapshot) {
        throw Error("Received a RunStepDelta before creation of a snapshot");
      }
      let data = event.data;
      if (data.delta) {
        const accumulated = _a2.accumulateDelta(snapshot, data.delta);
        __classPrivateFieldGet2(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = accumulated;
      }
      return __classPrivateFieldGet2(this, _AssistantStream_runStepSnapshots, "f")[event.data.id];
    case "thread.run.step.completed":
    case "thread.run.step.failed":
    case "thread.run.step.cancelled":
    case "thread.run.step.expired":
    case "thread.run.step.in_progress":
      __classPrivateFieldGet2(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = event.data;
      break;
  }
  if (__classPrivateFieldGet2(this, _AssistantStream_runStepSnapshots, "f")[event.data.id])
    return __classPrivateFieldGet2(this, _AssistantStream_runStepSnapshots, "f")[event.data.id];
  throw new Error("No snapshot available");
}, _AssistantStream_accumulateMessage = function _AssistantStream_accumulateMessage2(event, snapshot) {
  let newContent = [];
  switch (event.event) {
    case "thread.message.created":
      return [event.data, newContent];
    case "thread.message.delta":
      if (!snapshot) {
        throw Error("Received a delta with no existing snapshot (there should be one from message creation)");
      }
      let data = event.data;
      if (data.delta.content) {
        for (const contentElement of data.delta.content) {
          if (contentElement.index in snapshot.content) {
            let currentContent = snapshot.content[contentElement.index];
            snapshot.content[contentElement.index] = __classPrivateFieldGet2(this, _AssistantStream_instances, "m", _AssistantStream_accumulateContent).call(this, contentElement, currentContent);
          } else {
            snapshot.content[contentElement.index] = contentElement;
            newContent.push(contentElement);
          }
        }
      }
      return [snapshot, newContent];
    case "thread.message.in_progress":
    case "thread.message.completed":
    case "thread.message.incomplete":
      if (snapshot) {
        return [snapshot, newContent];
      } else {
        throw Error("Received thread message event with no existing snapshot");
      }
  }
  throw Error("Tried to accumulate a non-message event");
}, _AssistantStream_accumulateContent = function _AssistantStream_accumulateContent2(contentElement, currentContent) {
  return _a2.accumulateDelta(currentContent, contentElement);
}, _AssistantStream_handleRun = function _AssistantStream_handleRun2(event) {
  __classPrivateFieldSet2(this, _AssistantStream_currentRunSnapshot, event.data, "f");
  switch (event.event) {
    case "thread.run.created":
      break;
    case "thread.run.queued":
      break;
    case "thread.run.in_progress":
      break;
    case "thread.run.requires_action":
    case "thread.run.cancelled":
    case "thread.run.failed":
    case "thread.run.completed":
    case "thread.run.expired":
    case "thread.run.incomplete":
      __classPrivateFieldSet2(this, _AssistantStream_finalRun, event.data, "f");
      if (__classPrivateFieldGet2(this, _AssistantStream_currentToolCall, "f")) {
        this._emit("toolCallDone", __classPrivateFieldGet2(this, _AssistantStream_currentToolCall, "f"));
        __classPrivateFieldSet2(this, _AssistantStream_currentToolCall, void 0, "f");
      }
      break;
    case "thread.run.cancelling":
      break;
  }
};
function assertNever2(_x) {
}

// ../pi-mono/node_modules/openai/resources/beta/threads/runs/runs.mjs
var Runs = class extends APIResource2 {
  constructor() {
    super(...arguments);
    this.steps = new Steps(this._client);
  }
  create(threadID, params, options) {
    const { include, ...body } = params;
    return this._client.post(path2`/threads/${threadID}/runs`, {
      query: { include },
      body,
      ...options,
      headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
      stream: params.stream ?? false,
      __synthesizeEventData: true
    });
  }
  /**
   * Retrieves a run.
   *
   * @deprecated The Assistants API is deprecated in favor of the Responses API
   */
  retrieve(runID, params, options) {
    const { thread_id } = params;
    return this._client.get(path2`/threads/${thread_id}/runs/${runID}`, {
      ...options,
      headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers])
    });
  }
  /**
   * Modifies a run.
   *
   * @deprecated The Assistants API is deprecated in favor of the Responses API
   */
  update(runID, params, options) {
    const { thread_id, ...body } = params;
    return this._client.post(path2`/threads/${thread_id}/runs/${runID}`, {
      body,
      ...options,
      headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers])
    });
  }
  /**
   * Returns a list of runs belonging to a thread.
   *
   * @deprecated The Assistants API is deprecated in favor of the Responses API
   */
  list(threadID, query = {}, options) {
    return this._client.getAPIList(path2`/threads/${threadID}/runs`, CursorPage, {
      query,
      ...options,
      headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers])
    });
  }
  /**
   * Cancels a run that is `in_progress`.
   *
   * @deprecated The Assistants API is deprecated in favor of the Responses API
   */
  cancel(runID, params, options) {
    const { thread_id } = params;
    return this._client.post(path2`/threads/${thread_id}/runs/${runID}/cancel`, {
      ...options,
      headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers])
    });
  }
  /**
   * A helper to create a run an poll for a terminal state. More information on Run
   * lifecycles can be found here:
   * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps
   */
  async createAndPoll(threadId, body, options) {
    const run = await this.create(threadId, body, options);
    return await this.poll(run.id, { thread_id: threadId }, options);
  }
  /**
   * Create a Run stream
   *
   * @deprecated use `stream` instead
   */
  createAndStream(threadId, body, options) {
    return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options);
  }
  /**
   * A helper to poll a run status until it reaches a terminal state. More
   * information on Run lifecycles can be found here:
   * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps
   */
  async poll(runId, params, options) {
    const headers = buildHeaders2([
      options?.headers,
      {
        "X-Stainless-Poll-Helper": "true",
        "X-Stainless-Custom-Poll-Interval": options?.pollIntervalMs?.toString() ?? void 0
      }
    ]);
    while (true) {
      const { data: run, response } = await this.retrieve(runId, params, {
        ...options,
        headers: { ...options?.headers, ...headers }
      }).withResponse();
      switch (run.status) {
        //If we are in any sort of intermediate state we poll
        case "queued":
        case "in_progress":
        case "cancelling":
          let sleepInterval = 5e3;
          if (options?.pollIntervalMs) {
            sleepInterval = options.pollIntervalMs;
          } else {
            const headerInterval = response.headers.get("openai-poll-after-ms");
            if (headerInterval) {
              const headerIntervalMs = parseInt(headerInterval);
              if (!isNaN(headerIntervalMs)) {
                sleepInterval = headerIntervalMs;
              }
            }
          }
          await sleep2(sleepInterval);
          break;
        //We return the run in any terminal state.
        case "requires_action":
        case "incomplete":
        case "cancelled":
        case "completed":
        case "failed":
        case "expired":
          return run;
      }
    }
  }
  /**
   * Create a Run stream
   */
  stream(threadId, body, options) {
    return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options);
  }
  submitToolOutputs(runID, params, options) {
    const { thread_id, ...body } = params;
    return this._client.post(path2`/threads/${thread_id}/runs/${runID}/submit_tool_outputs`, {
      body,
      ...options,
      headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
      stream: params.stream ?? false,
      __synthesizeEventData: true
    });
  }
  /**
   * A helper to submit a tool output to a run and poll for a terminal run state.
   * More information on Run lifecycles can be found here:
   * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps
   */
  async submitToolOutputsAndPoll(runId, params, options) {
    const run = await this.submitToolOutputs(runId, params, options);
    return await this.poll(run.id, params, options);
  }
  /**
   * Submit the tool outputs from a previous run and stream the run to a terminal
   * state. More information on Run lifecycles can be found here:
   * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps
   */
  submitToolOutputsStream(runId, params, options) {
    return AssistantStream.createToolAssistantStream(runId, this._client.beta.threads.runs, params, options);
  }
};
Runs.Steps = Steps;

// ../pi-mono/node_modules/openai/resources/beta/threads/threads.mjs
var Threads2 = class extends APIResource2 {
  constructor() {
    super(...arguments);
    this.runs = new Runs(this._client);
    this.messages = new Messages4(this._client);
  }
  /**
   * Create a thread.
   *
   * @deprecated The Assistants API is deprecated in favor of the Responses API
   */
  create(body = {}, options) {
    return this._client.post("/threads", {
      body,
      ...options,
      headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers])
    });
  }
  /**
   * Retrieves a thread.
   *
   * @deprecated The Assistants API is deprecated in favor of the Responses API
   */
  retrieve(threadID, options) {
    return this._client.get(path2`/threads/${threadID}`, {
      ...options,
      headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers])
    });
  }
  /**
   * Modifies a thread.
   *
   * @deprecated The Assistants API is deprecated in favor of the Responses API
   */
  update(threadID, body, options) {
    return this._client.post(path2`/threads/${threadID}`, {
      body,
      ...options,
      headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers])
    });
  }
  /**
   * Delete a thread.
   *
   * @deprecated The Assistants API is deprecated in favor of the Responses API
   */
  delete(threadID, options) {
    return this._client.delete(path2`/threads/${threadID}`, {
      ...options,
      headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers])
    });
  }
  createAndRun(body, options) {
    return this._client.post("/threads/runs", {
      body,
      ...options,
      headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
      stream: body.stream ?? false,
      __synthesizeEventData: true
    });
  }
  /**
   * A helper to create a thread, start a run and then poll for a terminal state.
   * More information on Run lifecycles can be found here:
   * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps
   */
  async createAndRunPoll(body, options) {
    const run = await this.createAndRun(body, options);
    return await this.runs.poll(run.id, { thread_id: run.thread_id }, options);
  }
  /**
   * Create a thread and stream the run back
   */
  createAndRunStream(body, options) {
    return AssistantStream.createThreadAssistantStream(body, this._client.beta.threads, options);
  }
};
Threads2.Runs = Runs;
Threads2.Messages = Messages4;

// ../pi-mono/node_modules/openai/resources/beta/beta.mjs
var Beta2 = class extends APIResource2 {
  constructor() {
    super(...arguments);
    this.realtime = new Realtime(this._client);
    this.chatkit = new ChatKit(this._client);
    this.assistants = new Assistants(this._client);
    this.threads = new Threads2(this._client);
  }
};
Beta2.Realtime = Realtime;
Beta2.ChatKit = ChatKit;
Beta2.Assistants = Assistants;
Beta2.Threads = Threads2;

// ../pi-mono/node_modules/openai/resources/completions.mjs
init_process_shim();
var Completions3 = class extends APIResource2 {
  create(body, options) {
    return this._client.post("/completions", { body, ...options, stream: body.stream ?? false });
  }
};

// ../pi-mono/node_modules/openai/resources/containers/containers.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/resources/containers/files/files.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/resources/containers/files/content.mjs
init_process_shim();
var Content = class extends APIResource2 {
  /**
   * Retrieve Container File Content
   */
  retrieve(fileID, params, options) {
    const { container_id } = params;
    return this._client.get(path2`/containers/${container_id}/files/${fileID}/content`, {
      ...options,
      headers: buildHeaders2([{ Accept: "application/binary" }, options?.headers]),
      __binaryResponse: true
    });
  }
};

// ../pi-mono/node_modules/openai/resources/containers/files/files.mjs
var Files2 = class extends APIResource2 {
  constructor() {
    super(...arguments);
    this.content = new Content(this._client);
  }
  /**
   * Create a Container File
   *
   * You can send either a multipart/form-data request with the raw file content, or
   * a JSON request with a file ID.
   */
  create(containerID, body, options) {
    return this._client.post(path2`/containers/${containerID}/files`, maybeMultipartFormRequestOptions({ body, ...options }, this._client));
  }
  /**
   * Retrieve Container File
   */
  retrieve(fileID, params, options) {
    const { container_id } = params;
    return this._client.get(path2`/containers/${container_id}/files/${fileID}`, options);
  }
  /**
   * List Container files
   */
  list(containerID, query = {}, options) {
    return this._client.getAPIList(path2`/containers/${containerID}/files`, CursorPage, {
      query,
      ...options
    });
  }
  /**
   * Delete Container File
   */
  delete(fileID, params, options) {
    const { container_id } = params;
    return this._client.delete(path2`/containers/${container_id}/files/${fileID}`, {
      ...options,
      headers: buildHeaders2([{ Accept: "*/*" }, options?.headers])
    });
  }
};
Files2.Content = Content;

// ../pi-mono/node_modules/openai/resources/containers/containers.mjs
var Containers = class extends APIResource2 {
  constructor() {
    super(...arguments);
    this.files = new Files2(this._client);
  }
  /**
   * Create Container
   */
  create(body, options) {
    return this._client.post("/containers", { body, ...options });
  }
  /**
   * Retrieve Container
   */
  retrieve(containerID, options) {
    return this._client.get(path2`/containers/${containerID}`, options);
  }
  /**
   * List Containers
   */
  list(query = {}, options) {
    return this._client.getAPIList("/containers", CursorPage, { query, ...options });
  }
  /**
   * Delete Container
   */
  delete(containerID, options) {
    return this._client.delete(path2`/containers/${containerID}`, {
      ...options,
      headers: buildHeaders2([{ Accept: "*/*" }, options?.headers])
    });
  }
};
Containers.Files = Files2;

// ../pi-mono/node_modules/openai/resources/conversations/conversations.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/resources/conversations/items.mjs
init_process_shim();
var Items = class extends APIResource2 {
  /**
   * Create items in a conversation with the given ID.
   */
  create(conversationID, params, options) {
    const { include, ...body } = params;
    return this._client.post(path2`/conversations/${conversationID}/items`, {
      query: { include },
      body,
      ...options
    });
  }
  /**
   * Get a single item from a conversation with the given IDs.
   */
  retrieve(itemID, params, options) {
    const { conversation_id, ...query } = params;
    return this._client.get(path2`/conversations/${conversation_id}/items/${itemID}`, { query, ...options });
  }
  /**
   * List all items for a conversation with the given ID.
   */
  list(conversationID, query = {}, options) {
    return this._client.getAPIList(path2`/conversations/${conversationID}/items`, ConversationCursorPage, { query, ...options });
  }
  /**
   * Delete an item from a conversation with the given IDs.
   */
  delete(itemID, params, options) {
    const { conversation_id } = params;
    return this._client.delete(path2`/conversations/${conversation_id}/items/${itemID}`, options);
  }
};

// ../pi-mono/node_modules/openai/resources/conversations/conversations.mjs
var Conversations = class extends APIResource2 {
  constructor() {
    super(...arguments);
    this.items = new Items(this._client);
  }
  /**
   * Create a conversation.
   */
  create(body = {}, options) {
    return this._client.post("/conversations", { body, ...options });
  }
  /**
   * Get a conversation
   */
  retrieve(conversationID, options) {
    return this._client.get(path2`/conversations/${conversationID}`, options);
  }
  /**
   * Update a conversation
   */
  update(conversationID, body, options) {
    return this._client.post(path2`/conversations/${conversationID}`, { body, ...options });
  }
  /**
   * Delete a conversation. Items in the conversation will not be deleted.
   */
  delete(conversationID, options) {
    return this._client.delete(path2`/conversations/${conversationID}`, options);
  }
};
Conversations.Items = Items;

// ../pi-mono/node_modules/openai/resources/embeddings.mjs
init_process_shim();
var Embeddings = class extends APIResource2 {
  /**
   * Creates an embedding vector representing the input text.
   *
   * @example
   * ```ts
   * const createEmbeddingResponse =
   *   await client.embeddings.create({
   *     input: 'The quick brown fox jumped over the lazy dog',
   *     model: 'text-embedding-3-small',
   *   });
   * ```
   */
  create(body, options) {
    const hasUserProvidedEncodingFormat = !!body.encoding_format;
    let encoding_format = hasUserProvidedEncodingFormat ? body.encoding_format : "base64";
    if (hasUserProvidedEncodingFormat) {
      loggerFor2(this._client).debug("embeddings/user defined encoding_format:", body.encoding_format);
    }
    const response = this._client.post("/embeddings", {
      body: {
        ...body,
        encoding_format
      },
      ...options
    });
    if (hasUserProvidedEncodingFormat) {
      return response;
    }
    loggerFor2(this._client).debug("embeddings/decoding base64 embeddings from base64");
    return response._thenUnwrap((response2) => {
      if (response2 && response2.data) {
        response2.data.forEach((embeddingBase64Obj) => {
          const embeddingBase64Str = embeddingBase64Obj.embedding;
          embeddingBase64Obj.embedding = toFloat32Array(embeddingBase64Str);
        });
      }
      return response2;
    });
  }
};

// ../pi-mono/node_modules/openai/resources/evals/evals.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/resources/evals/runs/runs.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/resources/evals/runs/output-items.mjs
init_process_shim();
var OutputItems = class extends APIResource2 {
  /**
   * Get an evaluation run output item by ID.
   */
  retrieve(outputItemID, params, options) {
    const { eval_id, run_id } = params;
    return this._client.get(path2`/evals/${eval_id}/runs/${run_id}/output_items/${outputItemID}`, options);
  }
  /**
   * Get a list of output items for an evaluation run.
   */
  list(runID, params, options) {
    const { eval_id, ...query } = params;
    return this._client.getAPIList(path2`/evals/${eval_id}/runs/${runID}/output_items`, CursorPage, { query, ...options });
  }
};

// ../pi-mono/node_modules/openai/resources/evals/runs/runs.mjs
var Runs2 = class extends APIResource2 {
  constructor() {
    super(...arguments);
    this.outputItems = new OutputItems(this._client);
  }
  /**
   * Kicks off a new run for a given evaluation, specifying the data source, and what
   * model configuration to use to test. The datasource will be validated against the
   * schema specified in the config of the evaluation.
   */
  create(evalID, body, options) {
    return this._client.post(path2`/evals/${evalID}/runs`, { body, ...options });
  }
  /**
   * Get an evaluation run by ID.
   */
  retrieve(runID, params, options) {
    const { eval_id } = params;
    return this._client.get(path2`/evals/${eval_id}/runs/${runID}`, options);
  }
  /**
   * Get a list of runs for an evaluation.
   */
  list(evalID, query = {}, options) {
    return this._client.getAPIList(path2`/evals/${evalID}/runs`, CursorPage, {
      query,
      ...options
    });
  }
  /**
   * Delete an eval run.
   */
  delete(runID, params, options) {
    const { eval_id } = params;
    return this._client.delete(path2`/evals/${eval_id}/runs/${runID}`, options);
  }
  /**
   * Cancel an ongoing evaluation run.
   */
  cancel(runID, params, options) {
    const { eval_id } = params;
    return this._client.post(path2`/evals/${eval_id}/runs/${runID}`, options);
  }
};
Runs2.OutputItems = OutputItems;

// ../pi-mono/node_modules/openai/resources/evals/evals.mjs
var Evals = class extends APIResource2 {
  constructor() {
    super(...arguments);
    this.runs = new Runs2(this._client);
  }
  /**
   * Create the structure of an evaluation that can be used to test a model's
   * performance. An evaluation is a set of testing criteria and the config for a
   * data source, which dictates the schema of the data used in the evaluation. After
   * creating an evaluation, you can run it on different models and model parameters.
   * We support several types of graders and datasources. For more information, see
   * the [Evals guide](https://platform.openai.com/docs/guides/evals).
   */
  create(body, options) {
    return this._client.post("/evals", { body, ...options });
  }
  /**
   * Get an evaluation by ID.
   */
  retrieve(evalID, options) {
    return this._client.get(path2`/evals/${evalID}`, options);
  }
  /**
   * Update certain properties of an evaluation.
   */
  update(evalID, body, options) {
    return this._client.post(path2`/evals/${evalID}`, { body, ...options });
  }
  /**
   * List evaluations for a project.
   */
  list(query = {}, options) {
    return this._client.getAPIList("/evals", CursorPage, { query, ...options });
  }
  /**
   * Delete an evaluation.
   */
  delete(evalID, options) {
    return this._client.delete(path2`/evals/${evalID}`, options);
  }
};
Evals.Runs = Runs2;

// ../pi-mono/node_modules/openai/resources/files.mjs
init_process_shim();
var Files3 = class extends APIResource2 {
  /**
   * Upload a file that can be used across various endpoints. Individual files can be
   * up to 512 MB, and each project can store up to 2.5 TB of files in total. There
   * is no organization-wide storage limit.
   *
   * - The Assistants API supports files up to 2 million tokens and of specific file
   *   types. See the
   *   [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools)
   *   for details.
   * - The Fine-tuning API only supports `.jsonl` files. The input also has certain
   *   required formats for fine-tuning
   *   [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input)
   *   or
   *   [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input)
   *   models.
   * - The Batch API only supports `.jsonl` files up to 200 MB in size. The input
   *   also has a specific required
   *   [format](https://platform.openai.com/docs/api-reference/batch/request-input).
   *
   * Please [contact us](https://help.openai.com/) if you need to increase these
   * storage limits.
   */
  create(body, options) {
    return this._client.post("/files", multipartFormRequestOptions2({ body, ...options }, this._client));
  }
  /**
   * Returns information about a specific file.
   */
  retrieve(fileID, options) {
    return this._client.get(path2`/files/${fileID}`, options);
  }
  /**
   * Returns a list of files.
   */
  list(query = {}, options) {
    return this._client.getAPIList("/files", CursorPage, { query, ...options });
  }
  /**
   * Delete a file and remove it from all vector stores.
   */
  delete(fileID, options) {
    return this._client.delete(path2`/files/${fileID}`, options);
  }
  /**
   * Returns the contents of the specified file.
   */
  content(fileID, options) {
    return this._client.get(path2`/files/${fileID}/content`, {
      ...options,
      headers: buildHeaders2([{ Accept: "application/binary" }, options?.headers]),
      __binaryResponse: true
    });
  }
  /**
   * Waits for the given file to be processed, default timeout is 30 mins.
   */
  async waitForProcessing(id, { pollInterval = 5e3, maxWait = 30 * 60 * 1e3 } = {}) {
    const TERMINAL_STATES = /* @__PURE__ */ new Set(["processed", "error", "deleted"]);
    const start = Date.now();
    let file = await this.retrieve(id);
    while (!file.status || !TERMINAL_STATES.has(file.status)) {
      await sleep2(pollInterval);
      file = await this.retrieve(id);
      if (Date.now() - start > maxWait) {
        throw new APIConnectionTimeoutError2({
          message: `Giving up on waiting for file ${id} to finish processing after ${maxWait} milliseconds.`
        });
      }
    }
    return file;
  }
};

// ../pi-mono/node_modules/openai/resources/fine-tuning/fine-tuning.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/resources/fine-tuning/methods.mjs
init_process_shim();
var Methods = class extends APIResource2 {
};

// ../pi-mono/node_modules/openai/resources/fine-tuning/alpha/alpha.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/resources/fine-tuning/alpha/graders.mjs
init_process_shim();
var Graders = class extends APIResource2 {
  /**
   * Run a grader.
   *
   * @example
   * ```ts
   * const response = await client.fineTuning.alpha.graders.run({
   *   grader: {
   *     input: 'input',
   *     name: 'name',
   *     operation: 'eq',
   *     reference: 'reference',
   *     type: 'string_check',
   *   },
   *   model_sample: 'model_sample',
   * });
   * ```
   */
  run(body, options) {
    return this._client.post("/fine_tuning/alpha/graders/run", { body, ...options });
  }
  /**
   * Validate a grader.
   *
   * @example
   * ```ts
   * const response =
   *   await client.fineTuning.alpha.graders.validate({
   *     grader: {
   *       input: 'input',
   *       name: 'name',
   *       operation: 'eq',
   *       reference: 'reference',
   *       type: 'string_check',
   *     },
   *   });
   * ```
   */
  validate(body, options) {
    return this._client.post("/fine_tuning/alpha/graders/validate", { body, ...options });
  }
};

// ../pi-mono/node_modules/openai/resources/fine-tuning/alpha/alpha.mjs
var Alpha = class extends APIResource2 {
  constructor() {
    super(...arguments);
    this.graders = new Graders(this._client);
  }
};
Alpha.Graders = Graders;

// ../pi-mono/node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/resources/fine-tuning/checkpoints/permissions.mjs
init_process_shim();
var Permissions = class extends APIResource2 {
  /**
   * **NOTE:** Calling this endpoint requires an [admin API key](../admin-api-keys).
   *
   * This enables organization owners to share fine-tuned models with other projects
   * in their organization.
   *
   * @example
   * ```ts
   * // Automatically fetches more pages as needed.
   * for await (const permissionCreateResponse of client.fineTuning.checkpoints.permissions.create(
   *   'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd',
   *   { project_ids: ['string'] },
   * )) {
   *   // ...
   * }
   * ```
   */
  create(fineTunedModelCheckpoint, body, options) {
    return this._client.getAPIList(path2`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`, Page2, { body, method: "post", ...options });
  }
  /**
   * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys).
   *
   * Organization owners can use this endpoint to view all permissions for a
   * fine-tuned model checkpoint.
   *
   * @deprecated Retrieve is deprecated. Please swap to the paginated list method instead.
   */
  retrieve(fineTunedModelCheckpoint, query = {}, options) {
    return this._client.get(path2`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`, {
      query,
      ...options
    });
  }
  /**
   * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys).
   *
   * Organization owners can use this endpoint to view all permissions for a
   * fine-tuned model checkpoint.
   *
   * @example
   * ```ts
   * // Automatically fetches more pages as needed.
   * for await (const permissionListResponse of client.fineTuning.checkpoints.permissions.list(
   *   'ft-AF1WoRqd3aJAHsqc9NY7iL8F',
   * )) {
   *   // ...
   * }
   * ```
   */
  list(fineTunedModelCheckpoint, query = {}, options) {
    return this._client.getAPIList(path2`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`, ConversationCursorPage, { query, ...options });
  }
  /**
   * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys).
   *
   * Organization owners can use this endpoint to delete a permission for a
   * fine-tuned model checkpoint.
   *
   * @example
   * ```ts
   * const permission =
   *   await client.fineTuning.checkpoints.permissions.delete(
   *     'cp_zc4Q7MP6XxulcVzj4MZdwsAB',
   *     {
   *       fine_tuned_model_checkpoint:
   *         'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd',
   *     },
   *   );
   * ```
   */
  delete(permissionID, params, options) {
    const { fine_tuned_model_checkpoint } = params;
    return this._client.delete(path2`/fine_tuning/checkpoints/${fine_tuned_model_checkpoint}/permissions/${permissionID}`, options);
  }
};

// ../pi-mono/node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.mjs
var Checkpoints = class extends APIResource2 {
  constructor() {
    super(...arguments);
    this.permissions = new Permissions(this._client);
  }
};
Checkpoints.Permissions = Permissions;

// ../pi-mono/node_modules/openai/resources/fine-tuning/jobs/jobs.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/resources/fine-tuning/jobs/checkpoints.mjs
init_process_shim();
var Checkpoints2 = class extends APIResource2 {
  /**
   * List checkpoints for a fine-tuning job.
   *
   * @example
   * ```ts
   * // Automatically fetches more pages as needed.
   * for await (const fineTuningJobCheckpoint of client.fineTuning.jobs.checkpoints.list(
   *   'ft-AF1WoRqd3aJAHsqc9NY7iL8F',
   * )) {
   *   // ...
   * }
   * ```
   */
  list(fineTuningJobID, query = {}, options) {
    return this._client.getAPIList(path2`/fine_tuning/jobs/${fineTuningJobID}/checkpoints`, CursorPage, { query, ...options });
  }
};

// ../pi-mono/node_modules/openai/resources/fine-tuning/jobs/jobs.mjs
var Jobs = class extends APIResource2 {
  constructor() {
    super(...arguments);
    this.checkpoints = new Checkpoints2(this._client);
  }
  /**
   * Creates a fine-tuning job which begins the process of creating a new model from
   * a given dataset.
   *
   * Response includes details of the enqueued job including job status and the name
   * of the fine-tuned models once complete.
   *
   * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/model-optimization)
   *
   * @example
   * ```ts
   * const fineTuningJob = await client.fineTuning.jobs.create({
   *   model: 'gpt-4o-mini',
   *   training_file: 'file-abc123',
   * });
   * ```
   */
  create(body, options) {
    return this._client.post("/fine_tuning/jobs", { body, ...options });
  }
  /**
   * Get info about a fine-tuning job.
   *
   * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/model-optimization)
   *
   * @example
   * ```ts
   * const fineTuningJob = await client.fineTuning.jobs.retrieve(
   *   'ft-AF1WoRqd3aJAHsqc9NY7iL8F',
   * );
   * ```
   */
  retrieve(fineTuningJobID, options) {
    return this._client.get(path2`/fine_tuning/jobs/${fineTuningJobID}`, options);
  }
  /**
   * List your organization's fine-tuning jobs
   *
   * @example
   * ```ts
   * // Automatically fetches more pages as needed.
   * for await (const fineTuningJob of client.fineTuning.jobs.list()) {
   *   // ...
   * }
   * ```
   */
  list(query = {}, options) {
    return this._client.getAPIList("/fine_tuning/jobs", CursorPage, { query, ...options });
  }
  /**
   * Immediately cancel a fine-tune job.
   *
   * @example
   * ```ts
   * const fineTuningJob = await client.fineTuning.jobs.cancel(
   *   'ft-AF1WoRqd3aJAHsqc9NY7iL8F',
   * );
   * ```
   */
  cancel(fineTuningJobID, options) {
    return this._client.post(path2`/fine_tuning/jobs/${fineTuningJobID}/cancel`, options);
  }
  /**
   * Get status updates for a fine-tuning job.
   *
   * @example
   * ```ts
   * // Automatically fetches more pages as needed.
   * for await (const fineTuningJobEvent of client.fineTuning.jobs.listEvents(
   *   'ft-AF1WoRqd3aJAHsqc9NY7iL8F',
   * )) {
   *   // ...
   * }
   * ```
   */
  listEvents(fineTuningJobID, query = {}, options) {
    return this._client.getAPIList(path2`/fine_tuning/jobs/${fineTuningJobID}/events`, CursorPage, { query, ...options });
  }
  /**
   * Pause a fine-tune job.
   *
   * @example
   * ```ts
   * const fineTuningJob = await client.fineTuning.jobs.pause(
   *   'ft-AF1WoRqd3aJAHsqc9NY7iL8F',
   * );
   * ```
   */
  pause(fineTuningJobID, options) {
    return this._client.post(path2`/fine_tuning/jobs/${fineTuningJobID}/pause`, options);
  }
  /**
   * Resume a fine-tune job.
   *
   * @example
   * ```ts
   * const fineTuningJob = await client.fineTuning.jobs.resume(
   *   'ft-AF1WoRqd3aJAHsqc9NY7iL8F',
   * );
   * ```
   */
  resume(fineTuningJobID, options) {
    return this._client.post(path2`/fine_tuning/jobs/${fineTuningJobID}/resume`, options);
  }
};
Jobs.Checkpoints = Checkpoints2;

// ../pi-mono/node_modules/openai/resources/fine-tuning/fine-tuning.mjs
var FineTuning = class extends APIResource2 {
  constructor() {
    super(...arguments);
    this.methods = new Methods(this._client);
    this.jobs = new Jobs(this._client);
    this.checkpoints = new Checkpoints(this._client);
    this.alpha = new Alpha(this._client);
  }
};
FineTuning.Methods = Methods;
FineTuning.Jobs = Jobs;
FineTuning.Checkpoints = Checkpoints;
FineTuning.Alpha = Alpha;

// ../pi-mono/node_modules/openai/resources/graders/graders.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/resources/graders/grader-models.mjs
init_process_shim();
var GraderModels = class extends APIResource2 {
};

// ../pi-mono/node_modules/openai/resources/graders/graders.mjs
var Graders2 = class extends APIResource2 {
  constructor() {
    super(...arguments);
    this.graderModels = new GraderModels(this._client);
  }
};
Graders2.GraderModels = GraderModels;

// ../pi-mono/node_modules/openai/resources/images.mjs
init_process_shim();
var Images = class extends APIResource2 {
  /**
   * Creates a variation of a given image. This endpoint only supports `dall-e-2`.
   *
   * @example
   * ```ts
   * const imagesResponse = await client.images.createVariation({
   *   image: fs.createReadStream('otter.png'),
   * });
   * ```
   */
  createVariation(body, options) {
    return this._client.post("/images/variations", multipartFormRequestOptions2({ body, ...options }, this._client));
  }
  edit(body, options) {
    return this._client.post("/images/edits", multipartFormRequestOptions2({ body, ...options, stream: body.stream ?? false }, this._client));
  }
  generate(body, options) {
    return this._client.post("/images/generations", { body, ...options, stream: body.stream ?? false });
  }
};

// ../pi-mono/node_modules/openai/resources/models.mjs
init_process_shim();
var Models3 = class extends APIResource2 {
  /**
   * Retrieves a model instance, providing basic information about the model such as
   * the owner and permissioning.
   */
  retrieve(model, options) {
    return this._client.get(path2`/models/${model}`, options);
  }
  /**
   * Lists the currently available models, and provides basic information about each
   * one such as the owner and availability.
   */
  list(options) {
    return this._client.getAPIList("/models", Page2, options);
  }
  /**
   * Delete a fine-tuned model. You must have the Owner role in your organization to
   * delete a model.
   */
  delete(model, options) {
    return this._client.delete(path2`/models/${model}`, options);
  }
};

// ../pi-mono/node_modules/openai/resources/moderations.mjs
init_process_shim();
var Moderations = class extends APIResource2 {
  /**
   * Classifies if text and/or image inputs are potentially harmful. Learn more in
   * the [moderation guide](https://platform.openai.com/docs/guides/moderation).
   */
  create(body, options) {
    return this._client.post("/moderations", { body, ...options });
  }
};

// ../pi-mono/node_modules/openai/resources/realtime/realtime.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/resources/realtime/calls.mjs
init_process_shim();
var Calls = class extends APIResource2 {
  /**
   * Accept an incoming SIP call and configure the realtime session that will handle
   * it.
   *
   * @example
   * ```ts
   * await client.realtime.calls.accept('call_id', {
   *   type: 'realtime',
   * });
   * ```
   */
  accept(callID, body, options) {
    return this._client.post(path2`/realtime/calls/${callID}/accept`, {
      body,
      ...options,
      headers: buildHeaders2([{ Accept: "*/*" }, options?.headers])
    });
  }
  /**
   * End an active Realtime API call, whether it was initiated over SIP or WebRTC.
   *
   * @example
   * ```ts
   * await client.realtime.calls.hangup('call_id');
   * ```
   */
  hangup(callID, options) {
    return this._client.post(path2`/realtime/calls/${callID}/hangup`, {
      ...options,
      headers: buildHeaders2([{ Accept: "*/*" }, options?.headers])
    });
  }
  /**
   * Transfer an active SIP call to a new destination using the SIP REFER verb.
   *
   * @example
   * ```ts
   * await client.realtime.calls.refer('call_id', {
   *   target_uri: 'tel:+14155550123',
   * });
   * ```
   */
  refer(callID, body, options) {
    return this._client.post(path2`/realtime/calls/${callID}/refer`, {
      body,
      ...options,
      headers: buildHeaders2([{ Accept: "*/*" }, options?.headers])
    });
  }
  /**
   * Decline an incoming SIP call by returning a SIP status code to the caller.
   *
   * @example
   * ```ts
   * await client.realtime.calls.reject('call_id');
   * ```
   */
  reject(callID, body = {}, options) {
    return this._client.post(path2`/realtime/calls/${callID}/reject`, {
      body,
      ...options,
      headers: buildHeaders2([{ Accept: "*/*" }, options?.headers])
    });
  }
};

// ../pi-mono/node_modules/openai/resources/realtime/client-secrets.mjs
init_process_shim();
var ClientSecrets = class extends APIResource2 {
  /**
   * Create a Realtime client secret with an associated session configuration.
   *
   * Client secrets are short-lived tokens that can be passed to a client app, such
   * as a web frontend or mobile client, which grants access to the Realtime API
   * without leaking your main API key. You can configure a custom TTL for each
   * client secret.
   *
   * You can also attach session configuration options to the client secret, which
   * will be applied to any sessions created using that client secret, but these can
   * also be overridden by the client connection.
   *
   * [Learn more about authentication with client secrets over WebRTC](https://platform.openai.com/docs/guides/realtime-webrtc).
   *
   * Returns the created client secret and the effective session object. The client
   * secret is a string that looks like `ek_1234`.
   *
   * @example
   * ```ts
   * const clientSecret =
   *   await client.realtime.clientSecrets.create();
   * ```
   */
  create(body, options) {
    return this._client.post("/realtime/client_secrets", { body, ...options });
  }
};

// ../pi-mono/node_modules/openai/resources/realtime/realtime.mjs
var Realtime2 = class extends APIResource2 {
  constructor() {
    super(...arguments);
    this.clientSecrets = new ClientSecrets(this._client);
    this.calls = new Calls(this._client);
  }
};
Realtime2.ClientSecrets = ClientSecrets;
Realtime2.Calls = Calls;

// ../pi-mono/node_modules/openai/resources/responses/responses.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/lib/ResponsesParser.mjs
init_process_shim();
function maybeParseResponse(response, params) {
  if (!params || !hasAutoParseableInput2(params)) {
    return {
      ...response,
      output_parsed: null,
      output: response.output.map((item) => {
        if (item.type === "function_call") {
          return {
            ...item,
            parsed_arguments: null
          };
        }
        if (item.type === "message") {
          return {
            ...item,
            content: item.content.map((content) => ({
              ...content,
              parsed: null
            }))
          };
        } else {
          return item;
        }
      })
    };
  }
  return parseResponse(response, params);
}
function parseResponse(response, params) {
  const output = response.output.map((item) => {
    if (item.type === "function_call") {
      return {
        ...item,
        parsed_arguments: parseToolCall2(params, item)
      };
    }
    if (item.type === "message") {
      const content = item.content.map((content2) => {
        if (content2.type === "output_text") {
          return {
            ...content2,
            parsed: parseTextFormat(params, content2.text)
          };
        }
        return content2;
      });
      return {
        ...item,
        content
      };
    }
    return item;
  });
  const parsed = Object.assign({}, response, { output });
  if (!Object.getOwnPropertyDescriptor(response, "output_text")) {
    addOutputText(parsed);
  }
  Object.defineProperty(parsed, "output_parsed", {
    enumerable: true,
    get() {
      for (const output2 of parsed.output) {
        if (output2.type !== "message") {
          continue;
        }
        for (const content of output2.content) {
          if (content.type === "output_text" && content.parsed !== null) {
            return content.parsed;
          }
        }
      }
      return null;
    }
  });
  return parsed;
}
function parseTextFormat(params, content) {
  if (params.text?.format?.type !== "json_schema") {
    return null;
  }
  if ("$parseRaw" in params.text?.format) {
    const text_format = params.text?.format;
    return text_format.$parseRaw(content);
  }
  return JSON.parse(content);
}
function hasAutoParseableInput2(params) {
  if (isAutoParsableResponseFormat(params.text?.format)) {
    return true;
  }
  return false;
}
function isAutoParsableTool2(tool) {
  return tool?.["$brand"] === "auto-parseable-tool";
}
function getInputToolByName(input_tools, name) {
  return input_tools.find((tool) => tool.type === "function" && tool.name === name);
}
function parseToolCall2(params, toolCall) {
  const inputTool = getInputToolByName(params.tools ?? [], toolCall.name);
  return {
    ...toolCall,
    ...toolCall,
    parsed_arguments: isAutoParsableTool2(inputTool) ? inputTool.$parseRaw(toolCall.arguments) : inputTool?.strict ? JSON.parse(toolCall.arguments) : null
  };
}
function addOutputText(rsp) {
  const texts = [];
  for (const output of rsp.output) {
    if (output.type !== "message") {
      continue;
    }
    for (const content of output.content) {
      if (content.type === "output_text") {
        texts.push(content.text);
      }
    }
  }
  rsp.output_text = texts.join("");
}

// ../pi-mono/node_modules/openai/lib/responses/ResponseStream.mjs
init_process_shim();
var _ResponseStream_instances;
var _ResponseStream_params;
var _ResponseStream_currentResponseSnapshot;
var _ResponseStream_finalResponse;
var _ResponseStream_beginRequest;
var _ResponseStream_addEvent;
var _ResponseStream_endRequest;
var _ResponseStream_accumulateResponse;
var ResponseStream = class _ResponseStream extends EventStream2 {
  constructor(params) {
    super();
    _ResponseStream_instances.add(this);
    _ResponseStream_params.set(this, void 0);
    _ResponseStream_currentResponseSnapshot.set(this, void 0);
    _ResponseStream_finalResponse.set(this, void 0);
    __classPrivateFieldSet2(this, _ResponseStream_params, params, "f");
  }
  static createResponse(client, params, options) {
    const runner = new _ResponseStream(params);
    runner._run(() => runner._createOrRetrieveResponse(client, params, {
      ...options,
      headers: { ...options?.headers, "X-Stainless-Helper-Method": "stream" }
    }));
    return runner;
  }
  async _createOrRetrieveResponse(client, params, options) {
    const signal = options?.signal;
    if (signal) {
      if (signal.aborted)
        this.controller.abort();
      signal.addEventListener("abort", () => this.controller.abort());
    }
    __classPrivateFieldGet2(this, _ResponseStream_instances, "m", _ResponseStream_beginRequest).call(this);
    let stream2;
    let starting_after = null;
    if ("response_id" in params) {
      stream2 = await client.responses.retrieve(params.response_id, { stream: true }, { ...options, signal: this.controller.signal, stream: true });
      starting_after = params.starting_after ?? null;
    } else {
      stream2 = await client.responses.create({ ...params, stream: true }, { ...options, signal: this.controller.signal });
    }
    this._connected();
    for await (const event of stream2) {
      __classPrivateFieldGet2(this, _ResponseStream_instances, "m", _ResponseStream_addEvent).call(this, event, starting_after);
    }
    if (stream2.controller.signal?.aborted) {
      throw new APIUserAbortError2();
    }
    return __classPrivateFieldGet2(this, _ResponseStream_instances, "m", _ResponseStream_endRequest).call(this);
  }
  [(_ResponseStream_params = /* @__PURE__ */ new WeakMap(), _ResponseStream_currentResponseSnapshot = /* @__PURE__ */ new WeakMap(), _ResponseStream_finalResponse = /* @__PURE__ */ new WeakMap(), _ResponseStream_instances = /* @__PURE__ */ new WeakSet(), _ResponseStream_beginRequest = function _ResponseStream_beginRequest2() {
    if (this.ended)
      return;
    __classPrivateFieldSet2(this, _ResponseStream_currentResponseSnapshot, void 0, "f");
  }, _ResponseStream_addEvent = function _ResponseStream_addEvent2(event, starting_after) {
    if (this.ended)
      return;
    const maybeEmit = (name, event2) => {
      if (starting_after == null || event2.sequence_number > starting_after) {
        this._emit(name, event2);
      }
    };
    const response = __classPrivateFieldGet2(this, _ResponseStream_instances, "m", _ResponseStream_accumulateResponse).call(this, event);
    maybeEmit("event", event);
    switch (event.type) {
      case "response.output_text.delta": {
        const output = response.output[event.output_index];
        if (!output) {
          throw new OpenAIError(`missing output at index ${event.output_index}`);
        }
        if (output.type === "message") {
          const content = output.content[event.content_index];
          if (!content) {
            throw new OpenAIError(`missing content at index ${event.content_index}`);
          }
          if (content.type !== "output_text") {
            throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`);
          }
          maybeEmit("response.output_text.delta", {
            ...event,
            snapshot: content.text
          });
        }
        break;
      }
      case "response.function_call_arguments.delta": {
        const output = response.output[event.output_index];
        if (!output) {
          throw new OpenAIError(`missing output at index ${event.output_index}`);
        }
        if (output.type === "function_call") {
          maybeEmit("response.function_call_arguments.delta", {
            ...event,
            snapshot: output.arguments
          });
        }
        break;
      }
      default:
        maybeEmit(event.type, event);
        break;
    }
  }, _ResponseStream_endRequest = function _ResponseStream_endRequest2() {
    if (this.ended) {
      throw new OpenAIError(`stream has ended, this shouldn't happen`);
    }
    const snapshot = __classPrivateFieldGet2(this, _ResponseStream_currentResponseSnapshot, "f");
    if (!snapshot) {
      throw new OpenAIError(`request ended without sending any events`);
    }
    __classPrivateFieldSet2(this, _ResponseStream_currentResponseSnapshot, void 0, "f");
    const parsedResponse = finalizeResponse(snapshot, __classPrivateFieldGet2(this, _ResponseStream_params, "f"));
    __classPrivateFieldSet2(this, _ResponseStream_finalResponse, parsedResponse, "f");
    return parsedResponse;
  }, _ResponseStream_accumulateResponse = function _ResponseStream_accumulateResponse2(event) {
    let snapshot = __classPrivateFieldGet2(this, _ResponseStream_currentResponseSnapshot, "f");
    if (!snapshot) {
      if (event.type !== "response.created") {
        throw new OpenAIError(`When snapshot hasn't been set yet, expected 'response.created' event, got ${event.type}`);
      }
      snapshot = __classPrivateFieldSet2(this, _ResponseStream_currentResponseSnapshot, event.response, "f");
      return snapshot;
    }
    switch (event.type) {
      case "response.output_item.added": {
        snapshot.output.push(event.item);
        break;
      }
      case "response.content_part.added": {
        const output = snapshot.output[event.output_index];
        if (!output) {
          throw new OpenAIError(`missing output at index ${event.output_index}`);
        }
        const type = output.type;
        const part = event.part;
        if (type === "message" && part.type !== "reasoning_text") {
          output.content.push(part);
        } else if (type === "reasoning" && part.type === "reasoning_text") {
          if (!output.content) {
            output.content = [];
          }
          output.content.push(part);
        }
        break;
      }
      case "response.output_text.delta": {
        const output = snapshot.output[event.output_index];
        if (!output) {
          throw new OpenAIError(`missing output at index ${event.output_index}`);
        }
        if (output.type === "message") {
          const content = output.content[event.content_index];
          if (!content) {
            throw new OpenAIError(`missing content at index ${event.content_index}`);
          }
          if (content.type !== "output_text") {
            throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`);
          }
          content.text += event.delta;
        }
        break;
      }
      case "response.function_call_arguments.delta": {
        const output = snapshot.output[event.output_index];
        if (!output) {
          throw new OpenAIError(`missing output at index ${event.output_index}`);
        }
        if (output.type === "function_call") {
          output.arguments += event.delta;
        }
        break;
      }
      case "response.reasoning_text.delta": {
        const output = snapshot.output[event.output_index];
        if (!output) {
          throw new OpenAIError(`missing output at index ${event.output_index}`);
        }
        if (output.type === "reasoning") {
          const content = output.content?.[event.content_index];
          if (!content) {
            throw new OpenAIError(`missing content at index ${event.content_index}`);
          }
          if (content.type !== "reasoning_text") {
            throw new OpenAIError(`expected content to be 'reasoning_text', got ${content.type}`);
          }
          content.text += event.delta;
        }
        break;
      }
      case "response.completed": {
        __classPrivateFieldSet2(this, _ResponseStream_currentResponseSnapshot, event.response, "f");
        break;
      }
    }
    return snapshot;
  }, Symbol.asyncIterator)]() {
    const pushQueue = [];
    const readQueue = [];
    let done = false;
    this.on("event", (event) => {
      const reader = readQueue.shift();
      if (reader) {
        reader.resolve(event);
      } else {
        pushQueue.push(event);
      }
    });
    this.on("end", () => {
      done = true;
      for (const reader of readQueue) {
        reader.resolve(void 0);
      }
      readQueue.length = 0;
    });
    this.on("abort", (err) => {
      done = true;
      for (const reader of readQueue) {
        reader.reject(err);
      }
      readQueue.length = 0;
    });
    this.on("error", (err) => {
      done = true;
      for (const reader of readQueue) {
        reader.reject(err);
      }
      readQueue.length = 0;
    });
    return {
      next: async () => {
        if (!pushQueue.length) {
          if (done) {
            return { value: void 0, done: true };
          }
          return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((event2) => event2 ? { value: event2, done: false } : { value: void 0, done: true });
        }
        const event = pushQueue.shift();
        return { value: event, done: false };
      },
      return: async () => {
        this.abort();
        return { value: void 0, done: true };
      }
    };
  }
  /**
   * @returns a promise that resolves with the final Response, or rejects
   * if an error occurred or the stream ended prematurely without producing a REsponse.
   */
  async finalResponse() {
    await this.done();
    const response = __classPrivateFieldGet2(this, _ResponseStream_finalResponse, "f");
    if (!response)
      throw new OpenAIError("stream ended without producing a ChatCompletion");
    return response;
  }
};
function finalizeResponse(snapshot, params) {
  return maybeParseResponse(snapshot, params);
}

// ../pi-mono/node_modules/openai/resources/responses/input-items.mjs
init_process_shim();
var InputItems = class extends APIResource2 {
  /**
   * Returns a list of input items for a given response.
   *
   * @example
   * ```ts
   * // Automatically fetches more pages as needed.
   * for await (const responseItem of client.responses.inputItems.list(
   *   'response_id',
   * )) {
   *   // ...
   * }
   * ```
   */
  list(responseID, query = {}, options) {
    return this._client.getAPIList(path2`/responses/${responseID}/input_items`, CursorPage, { query, ...options });
  }
};

// ../pi-mono/node_modules/openai/resources/responses/input-tokens.mjs
init_process_shim();
var InputTokens = class extends APIResource2 {
  /**
   * Returns input token counts of the request.
   *
   * Returns an object with `object` set to `response.input_tokens` and an
   * `input_tokens` count.
   *
   * @example
   * ```ts
   * const response = await client.responses.inputTokens.count();
   * ```
   */
  count(body = {}, options) {
    return this._client.post("/responses/input_tokens", { body, ...options });
  }
};

// ../pi-mono/node_modules/openai/resources/responses/responses.mjs
var Responses = class extends APIResource2 {
  constructor() {
    super(...arguments);
    this.inputItems = new InputItems(this._client);
    this.inputTokens = new InputTokens(this._client);
  }
  create(body, options) {
    return this._client.post("/responses", { body, ...options, stream: body.stream ?? false })._thenUnwrap((rsp) => {
      if ("object" in rsp && rsp.object === "response") {
        addOutputText(rsp);
      }
      return rsp;
    });
  }
  retrieve(responseID, query = {}, options) {
    return this._client.get(path2`/responses/${responseID}`, {
      query,
      ...options,
      stream: query?.stream ?? false
    })._thenUnwrap((rsp) => {
      if ("object" in rsp && rsp.object === "response") {
        addOutputText(rsp);
      }
      return rsp;
    });
  }
  /**
   * Deletes a model response with the given ID.
   *
   * @example
   * ```ts
   * await client.responses.delete(
   *   'resp_677efb5139a88190b512bc3fef8e535d',
   * );
   * ```
   */
  delete(responseID, options) {
    return this._client.delete(path2`/responses/${responseID}`, {
      ...options,
      headers: buildHeaders2([{ Accept: "*/*" }, options?.headers])
    });
  }
  parse(body, options) {
    return this._client.responses.create(body, options)._thenUnwrap((response) => parseResponse(response, body));
  }
  /**
   * Creates a model response stream
   */
  stream(body, options) {
    return ResponseStream.createResponse(this._client, body, options);
  }
  /**
   * Cancels a model response with the given ID. Only responses created with the
   * `background` parameter set to `true` can be cancelled.
   * [Learn more](https://platform.openai.com/docs/guides/background).
   *
   * @example
   * ```ts
   * const response = await client.responses.cancel(
   *   'resp_677efb5139a88190b512bc3fef8e535d',
   * );
   * ```
   */
  cancel(responseID, options) {
    return this._client.post(path2`/responses/${responseID}/cancel`, options);
  }
  /**
   * Compact a conversation. Returns a compacted response object.
   *
   * Learn when and how to compact long-running conversations in the
   * [conversation state guide](https://platform.openai.com/docs/guides/conversation-state#managing-the-context-window).
   * For ZDR-compatible compaction details, see
   * [Compaction (advanced)](https://platform.openai.com/docs/guides/conversation-state#compaction-advanced).
   *
   * @example
   * ```ts
   * const compactedResponse = await client.responses.compact({
   *   model: 'gpt-5.4',
   * });
   * ```
   */
  compact(body, options) {
    return this._client.post("/responses/compact", { body, ...options });
  }
};
Responses.InputItems = InputItems;
Responses.InputTokens = InputTokens;

// ../pi-mono/node_modules/openai/resources/skills/skills.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/resources/skills/content.mjs
init_process_shim();
var Content2 = class extends APIResource2 {
  /**
   * Download a skill zip bundle by its ID.
   */
  retrieve(skillID, options) {
    return this._client.get(path2`/skills/${skillID}/content`, {
      ...options,
      headers: buildHeaders2([{ Accept: "application/binary" }, options?.headers]),
      __binaryResponse: true
    });
  }
};

// ../pi-mono/node_modules/openai/resources/skills/versions/versions.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/resources/skills/versions/content.mjs
init_process_shim();
var Content3 = class extends APIResource2 {
  /**
   * Download a skill version zip bundle.
   */
  retrieve(version5, params, options) {
    const { skill_id } = params;
    return this._client.get(path2`/skills/${skill_id}/versions/${version5}/content`, {
      ...options,
      headers: buildHeaders2([{ Accept: "application/binary" }, options?.headers]),
      __binaryResponse: true
    });
  }
};

// ../pi-mono/node_modules/openai/resources/skills/versions/versions.mjs
var Versions2 = class extends APIResource2 {
  constructor() {
    super(...arguments);
    this.content = new Content3(this._client);
  }
  /**
   * Create a new immutable skill version.
   */
  create(skillID, body = {}, options) {
    return this._client.post(path2`/skills/${skillID}/versions`, maybeMultipartFormRequestOptions({ body, ...options }, this._client));
  }
  /**
   * Get a specific skill version.
   */
  retrieve(version5, params, options) {
    const { skill_id } = params;
    return this._client.get(path2`/skills/${skill_id}/versions/${version5}`, options);
  }
  /**
   * List skill versions for a skill.
   */
  list(skillID, query = {}, options) {
    return this._client.getAPIList(path2`/skills/${skillID}/versions`, CursorPage, {
      query,
      ...options
    });
  }
  /**
   * Delete a skill version.
   */
  delete(version5, params, options) {
    const { skill_id } = params;
    return this._client.delete(path2`/skills/${skill_id}/versions/${version5}`, options);
  }
};
Versions2.Content = Content3;

// ../pi-mono/node_modules/openai/resources/skills/skills.mjs
var Skills2 = class extends APIResource2 {
  constructor() {
    super(...arguments);
    this.content = new Content2(this._client);
    this.versions = new Versions2(this._client);
  }
  /**
   * Create a new skill.
   */
  create(body = {}, options) {
    return this._client.post("/skills", maybeMultipartFormRequestOptions({ body, ...options }, this._client));
  }
  /**
   * Get a skill by its ID.
   */
  retrieve(skillID, options) {
    return this._client.get(path2`/skills/${skillID}`, options);
  }
  /**
   * Update the default version pointer for a skill.
   */
  update(skillID, body, options) {
    return this._client.post(path2`/skills/${skillID}`, { body, ...options });
  }
  /**
   * List all skills for the current project.
   */
  list(query = {}, options) {
    return this._client.getAPIList("/skills", CursorPage, { query, ...options });
  }
  /**
   * Delete a skill by its ID.
   */
  delete(skillID, options) {
    return this._client.delete(path2`/skills/${skillID}`, options);
  }
};
Skills2.Content = Content2;
Skills2.Versions = Versions2;

// ../pi-mono/node_modules/openai/resources/uploads/uploads.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/resources/uploads/parts.mjs
init_process_shim();
var Parts = class extends APIResource2 {
  /**
   * Adds a
   * [Part](https://platform.openai.com/docs/api-reference/uploads/part-object) to an
   * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object.
   * A Part represents a chunk of bytes from the file you are trying to upload.
   *
   * Each Part can be at most 64 MB, and you can add Parts until you hit the Upload
   * maximum of 8 GB.
   *
   * It is possible to add multiple Parts in parallel. You can decide the intended
   * order of the Parts when you
   * [complete the Upload](https://platform.openai.com/docs/api-reference/uploads/complete).
   */
  create(uploadID, body, options) {
    return this._client.post(path2`/uploads/${uploadID}/parts`, multipartFormRequestOptions2({ body, ...options }, this._client));
  }
};

// ../pi-mono/node_modules/openai/resources/uploads/uploads.mjs
var Uploads = class extends APIResource2 {
  constructor() {
    super(...arguments);
    this.parts = new Parts(this._client);
  }
  /**
   * Creates an intermediate
   * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object
   * that you can add
   * [Parts](https://platform.openai.com/docs/api-reference/uploads/part-object) to.
   * Currently, an Upload can accept at most 8 GB in total and expires after an hour
   * after you create it.
   *
   * Once you complete the Upload, we will create a
   * [File](https://platform.openai.com/docs/api-reference/files/object) object that
   * contains all the parts you uploaded. This File is usable in the rest of our
   * platform as a regular File object.
   *
   * For certain `purpose` values, the correct `mime_type` must be specified. Please
   * refer to documentation for the
   * [supported MIME types for your use case](https://platform.openai.com/docs/assistants/tools/file-search#supported-files).
   *
   * For guidance on the proper filename extensions for each purpose, please follow
   * the documentation on
   * [creating a File](https://platform.openai.com/docs/api-reference/files/create).
   *
   * Returns the Upload object with status `pending`.
   */
  create(body, options) {
    return this._client.post("/uploads", { body, ...options });
  }
  /**
   * Cancels the Upload. No Parts may be added after an Upload is cancelled.
   *
   * Returns the Upload object with status `cancelled`.
   */
  cancel(uploadID, options) {
    return this._client.post(path2`/uploads/${uploadID}/cancel`, options);
  }
  /**
   * Completes the
   * [Upload](https://platform.openai.com/docs/api-reference/uploads/object).
   *
   * Within the returned Upload object, there is a nested
   * [File](https://platform.openai.com/docs/api-reference/files/object) object that
   * is ready to use in the rest of the platform.
   *
   * You can specify the order of the Parts by passing in an ordered list of the Part
   * IDs.
   *
   * The number of bytes uploaded upon completion must match the number of bytes
   * initially specified when creating the Upload object. No Parts may be added after
   * an Upload is completed. Returns the Upload object with status `completed`,
   * including an additional `file` property containing the created usable File
   * object.
   */
  complete(uploadID, body, options) {
    return this._client.post(path2`/uploads/${uploadID}/complete`, { body, ...options });
  }
};
Uploads.Parts = Parts;

// ../pi-mono/node_modules/openai/resources/vector-stores/vector-stores.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/resources/vector-stores/file-batches.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/lib/Util.mjs
init_process_shim();
var allSettledWithThrow = async (promises) => {
  const results = await Promise.allSettled(promises);
  const rejected = results.filter((result) => result.status === "rejected");
  if (rejected.length) {
    for (const result of rejected) {
      console.error(result.reason);
    }
    throw new Error(`${rejected.length} promise(s) failed - see the above errors`);
  }
  const values2 = [];
  for (const result of results) {
    if (result.status === "fulfilled") {
      values2.push(result.value);
    }
  }
  return values2;
};

// ../pi-mono/node_modules/openai/resources/vector-stores/file-batches.mjs
var FileBatches = class extends APIResource2 {
  /**
   * Create a vector store file batch.
   */
  create(vectorStoreID, body, options) {
    return this._client.post(path2`/vector_stores/${vectorStoreID}/file_batches`, {
      body,
      ...options,
      headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers])
    });
  }
  /**
   * Retrieves a vector store file batch.
   */
  retrieve(batchID, params, options) {
    const { vector_store_id } = params;
    return this._client.get(path2`/vector_stores/${vector_store_id}/file_batches/${batchID}`, {
      ...options,
      headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers])
    });
  }
  /**
   * Cancel a vector store file batch. This attempts to cancel the processing of
   * files in this batch as soon as possible.
   */
  cancel(batchID, params, options) {
    const { vector_store_id } = params;
    return this._client.post(path2`/vector_stores/${vector_store_id}/file_batches/${batchID}/cancel`, {
      ...options,
      headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers])
    });
  }
  /**
   * Create a vector store batch and poll until all files have been processed.
   */
  async createAndPoll(vectorStoreId, body, options) {
    const batch = await this.create(vectorStoreId, body);
    return await this.poll(vectorStoreId, batch.id, options);
  }
  /**
   * Returns a list of vector store files in a batch.
   */
  listFiles(batchID, params, options) {
    const { vector_store_id, ...query } = params;
    return this._client.getAPIList(path2`/vector_stores/${vector_store_id}/file_batches/${batchID}/files`, CursorPage, { query, ...options, headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]) });
  }
  /**
   * Wait for the given file batch to be processed.
   *
   * Note: this will return even if one of the files failed to process, you need to
   * check batch.file_counts.failed_count to handle this case.
   */
  async poll(vectorStoreID, batchID, options) {
    const headers = buildHeaders2([
      options?.headers,
      {
        "X-Stainless-Poll-Helper": "true",
        "X-Stainless-Custom-Poll-Interval": options?.pollIntervalMs?.toString() ?? void 0
      }
    ]);
    while (true) {
      const { data: batch, response } = await this.retrieve(batchID, { vector_store_id: vectorStoreID }, {
        ...options,
        headers
      }).withResponse();
      switch (batch.status) {
        case "in_progress":
          let sleepInterval = 5e3;
          if (options?.pollIntervalMs) {
            sleepInterval = options.pollIntervalMs;
          } else {
            const headerInterval = response.headers.get("openai-poll-after-ms");
            if (headerInterval) {
              const headerIntervalMs = parseInt(headerInterval);
              if (!isNaN(headerIntervalMs)) {
                sleepInterval = headerIntervalMs;
              }
            }
          }
          await sleep2(sleepInterval);
          break;
        case "failed":
        case "cancelled":
        case "completed":
          return batch;
      }
    }
  }
  /**
   * Uploads the given files concurrently and then creates a vector store file batch.
   *
   * The concurrency limit is configurable using the `maxConcurrency` parameter.
   */
  async uploadAndPoll(vectorStoreId, { files, fileIds = [] }, options) {
    if (files == null || files.length == 0) {
      throw new Error(`No \`files\` provided to process. If you've already uploaded files you should use \`.createAndPoll()\` instead`);
    }
    const configuredConcurrency = options?.maxConcurrency ?? 5;
    const concurrencyLimit = Math.min(configuredConcurrency, files.length);
    const client = this._client;
    const fileIterator = files.values();
    const allFileIds = [...fileIds];
    async function processFiles(iterator) {
      for (let item of iterator) {
        const fileObj = await client.files.create({ file: item, purpose: "assistants" }, options);
        allFileIds.push(fileObj.id);
      }
    }
    const workers = Array(concurrencyLimit).fill(fileIterator).map(processFiles);
    await allSettledWithThrow(workers);
    return await this.createAndPoll(vectorStoreId, {
      file_ids: allFileIds
    });
  }
};

// ../pi-mono/node_modules/openai/resources/vector-stores/files.mjs
init_process_shim();
var Files4 = class extends APIResource2 {
  /**
   * Create a vector store file by attaching a
   * [File](https://platform.openai.com/docs/api-reference/files) to a
   * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object).
   */
  create(vectorStoreID, body, options) {
    return this._client.post(path2`/vector_stores/${vectorStoreID}/files`, {
      body,
      ...options,
      headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers])
    });
  }
  /**
   * Retrieves a vector store file.
   */
  retrieve(fileID, params, options) {
    const { vector_store_id } = params;
    return this._client.get(path2`/vector_stores/${vector_store_id}/files/${fileID}`, {
      ...options,
      headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers])
    });
  }
  /**
   * Update attributes on a vector store file.
   */
  update(fileID, params, options) {
    const { vector_store_id, ...body } = params;
    return this._client.post(path2`/vector_stores/${vector_store_id}/files/${fileID}`, {
      body,
      ...options,
      headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers])
    });
  }
  /**
   * Returns a list of vector store files.
   */
  list(vectorStoreID, query = {}, options) {
    return this._client.getAPIList(path2`/vector_stores/${vectorStoreID}/files`, CursorPage, {
      query,
      ...options,
      headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers])
    });
  }
  /**
   * Delete a vector store file. This will remove the file from the vector store but
   * the file itself will not be deleted. To delete the file, use the
   * [delete file](https://platform.openai.com/docs/api-reference/files/delete)
   * endpoint.
   */
  delete(fileID, params, options) {
    const { vector_store_id } = params;
    return this._client.delete(path2`/vector_stores/${vector_store_id}/files/${fileID}`, {
      ...options,
      headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers])
    });
  }
  /**
   * Attach a file to the given vector store and wait for it to be processed.
   */
  async createAndPoll(vectorStoreId, body, options) {
    const file = await this.create(vectorStoreId, body, options);
    return await this.poll(vectorStoreId, file.id, options);
  }
  /**
   * Wait for the vector store file to finish processing.
   *
   * Note: this will return even if the file failed to process, you need to check
   * file.last_error and file.status to handle these cases
   */
  async poll(vectorStoreID, fileID, options) {
    const headers = buildHeaders2([
      options?.headers,
      {
        "X-Stainless-Poll-Helper": "true",
        "X-Stainless-Custom-Poll-Interval": options?.pollIntervalMs?.toString() ?? void 0
      }
    ]);
    while (true) {
      const fileResponse = await this.retrieve(fileID, {
        vector_store_id: vectorStoreID
      }, { ...options, headers }).withResponse();
      const file = fileResponse.data;
      switch (file.status) {
        case "in_progress":
          let sleepInterval = 5e3;
          if (options?.pollIntervalMs) {
            sleepInterval = options.pollIntervalMs;
          } else {
            const headerInterval = fileResponse.response.headers.get("openai-poll-after-ms");
            if (headerInterval) {
              const headerIntervalMs = parseInt(headerInterval);
              if (!isNaN(headerIntervalMs)) {
                sleepInterval = headerIntervalMs;
              }
            }
          }
          await sleep2(sleepInterval);
          break;
        case "failed":
        case "completed":
          return file;
      }
    }
  }
  /**
   * Upload a file to the `files` API and then attach it to the given vector store.
   *
   * Note the file will be asynchronously processed (you can use the alternative
   * polling helper method to wait for processing to complete).
   */
  async upload(vectorStoreId, file, options) {
    const fileInfo = await this._client.files.create({ file, purpose: "assistants" }, options);
    return this.create(vectorStoreId, { file_id: fileInfo.id }, options);
  }
  /**
   * Add a file to a vector store and poll until processing is complete.
   */
  async uploadAndPoll(vectorStoreId, file, options) {
    const fileInfo = await this.upload(vectorStoreId, file, options);
    return await this.poll(vectorStoreId, fileInfo.id, options);
  }
  /**
   * Retrieve the parsed contents of a vector store file.
   */
  content(fileID, params, options) {
    const { vector_store_id } = params;
    return this._client.getAPIList(path2`/vector_stores/${vector_store_id}/files/${fileID}/content`, Page2, { ...options, headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]) });
  }
};

// ../pi-mono/node_modules/openai/resources/vector-stores/vector-stores.mjs
var VectorStores = class extends APIResource2 {
  constructor() {
    super(...arguments);
    this.files = new Files4(this._client);
    this.fileBatches = new FileBatches(this._client);
  }
  /**
   * Create a vector store.
   */
  create(body, options) {
    return this._client.post("/vector_stores", {
      body,
      ...options,
      headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers])
    });
  }
  /**
   * Retrieves a vector store.
   */
  retrieve(vectorStoreID, options) {
    return this._client.get(path2`/vector_stores/${vectorStoreID}`, {
      ...options,
      headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers])
    });
  }
  /**
   * Modifies a vector store.
   */
  update(vectorStoreID, body, options) {
    return this._client.post(path2`/vector_stores/${vectorStoreID}`, {
      body,
      ...options,
      headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers])
    });
  }
  /**
   * Returns a list of vector stores.
   */
  list(query = {}, options) {
    return this._client.getAPIList("/vector_stores", CursorPage, {
      query,
      ...options,
      headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers])
    });
  }
  /**
   * Delete a vector store.
   */
  delete(vectorStoreID, options) {
    return this._client.delete(path2`/vector_stores/${vectorStoreID}`, {
      ...options,
      headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers])
    });
  }
  /**
   * Search a vector store for relevant chunks based on a query and file attributes
   * filter.
   */
  search(vectorStoreID, body, options) {
    return this._client.getAPIList(path2`/vector_stores/${vectorStoreID}/search`, Page2, {
      body,
      method: "post",
      ...options,
      headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers])
    });
  }
};
VectorStores.Files = Files4;
VectorStores.FileBatches = FileBatches;

// ../pi-mono/node_modules/openai/resources/videos.mjs
init_process_shim();
var Videos = class extends APIResource2 {
  /**
   * Create a new video generation job from a prompt and optional reference assets.
   */
  create(body, options) {
    return this._client.post("/videos", maybeMultipartFormRequestOptions({ body, ...options }, this._client));
  }
  /**
   * Fetch the latest metadata for a generated video.
   */
  retrieve(videoID, options) {
    return this._client.get(path2`/videos/${videoID}`, options);
  }
  /**
   * List recently generated videos for the current project.
   */
  list(query = {}, options) {
    return this._client.getAPIList("/videos", ConversationCursorPage, { query, ...options });
  }
  /**
   * Permanently delete a completed or failed video and its stored assets.
   */
  delete(videoID, options) {
    return this._client.delete(path2`/videos/${videoID}`, options);
  }
  /**
   * Download the generated video bytes or a derived preview asset.
   *
   * Streams the rendered video content for the specified video job.
   */
  downloadContent(videoID, query = {}, options) {
    return this._client.get(path2`/videos/${videoID}/content`, {
      query,
      ...options,
      headers: buildHeaders2([{ Accept: "application/binary" }, options?.headers]),
      __binaryResponse: true
    });
  }
  /**
   * Create a remix of a completed video using a refreshed prompt.
   */
  remix(videoID, body, options) {
    return this._client.post(path2`/videos/${videoID}/remix`, maybeMultipartFormRequestOptions({ body, ...options }, this._client));
  }
};

// ../pi-mono/node_modules/openai/resources/webhooks.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/resources/webhooks/index.mjs
init_process_shim();

// ../pi-mono/node_modules/openai/resources/webhooks/webhooks.mjs
init_process_shim();
var _Webhooks_instances;
var _Webhooks_validateSecret;
var _Webhooks_getRequiredHeader;
var Webhooks = class extends APIResource2 {
  constructor() {
    super(...arguments);
    _Webhooks_instances.add(this);
  }
  /**
   * Validates that the given payload was sent by OpenAI and parses the payload.
   */
  async unwrap(payload, headers, secret = this._client.webhookSecret, tolerance = 300) {
    await this.verifySignature(payload, headers, secret, tolerance);
    return JSON.parse(payload);
  }
  /**
   * Validates whether or not the webhook payload was sent by OpenAI.
   *
   * An error will be raised if the webhook payload was not sent by OpenAI.
   *
   * @param payload - The webhook payload
   * @param headers - The webhook headers
   * @param secret - The webhook secret (optional, will use client secret if not provided)
   * @param tolerance - Maximum age of the webhook in seconds (default: 300 = 5 minutes)
   */
  async verifySignature(payload, headers, secret = this._client.webhookSecret, tolerance = 300) {
    if (typeof crypto === "undefined" || typeof crypto.subtle.importKey !== "function" || typeof crypto.subtle.verify !== "function") {
      throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");
    }
    __classPrivateFieldGet2(this, _Webhooks_instances, "m", _Webhooks_validateSecret).call(this, secret);
    const headersObj = buildHeaders2([headers]).values;
    const signatureHeader = __classPrivateFieldGet2(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, "webhook-signature");
    const timestamp = __classPrivateFieldGet2(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, "webhook-timestamp");
    const webhookId = __classPrivateFieldGet2(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, "webhook-id");
    const timestampSeconds = parseInt(timestamp, 10);
    if (isNaN(timestampSeconds)) {
      throw new InvalidWebhookSignatureError("Invalid webhook timestamp format");
    }
    const nowSeconds = Math.floor(Date.now() / 1e3);
    if (nowSeconds - timestampSeconds > tolerance) {
      throw new InvalidWebhookSignatureError("Webhook timestamp is too old");
    }
    if (timestampSeconds > nowSeconds + tolerance) {
      throw new InvalidWebhookSignatureError("Webhook timestamp is too new");
    }
    const signatures = signatureHeader.split(" ").map((part) => part.startsWith("v1,") ? part.substring(3) : part);
    const decodedSecret = secret.startsWith("whsec_") ? Buffer.from(secret.replace("whsec_", ""), "base64") : Buffer.from(secret, "utf-8");
    const signedPayload = webhookId ? `${webhookId}.${timestamp}.${payload}` : `${timestamp}.${payload}`;
    const key = await crypto.subtle.importKey("raw", decodedSecret, { name: "HMAC", hash: "SHA-256" }, false, ["verify"]);
    for (const signature of signatures) {
      try {
        const signatureBytes = Buffer.from(signature, "base64");
        const isValid3 = await crypto.subtle.verify("HMAC", key, signatureBytes, new TextEncoder().encode(signedPayload));
        if (isValid3) {
          return;
        }
      } catch {
        continue;
      }
    }
    throw new InvalidWebhookSignatureError("The given webhook signature does not match the expected signature");
  }
};
_Webhooks_instances = /* @__PURE__ */ new WeakSet(), _Webhooks_validateSecret = function _Webhooks_validateSecret2(secret) {
  if (typeof secret !== "string" || secret.length === 0) {
    throw new Error(`The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function`);
  }
}, _Webhooks_getRequiredHeader = function _Webhooks_getRequiredHeader2(headers, name) {
  if (!headers) {
    throw new Error(`Headers are required`);
  }
  const value = headers.get(name);
  if (value === null || value === void 0) {
    throw new Error(`Missing required header: ${name}`);
  }
  return value;
};

// ../pi-mono/node_modules/openai/client.mjs
var _OpenAI_instances;
var _a3;
var _OpenAI_encoder;
var _OpenAI_baseURLOverridden;
var OpenAI = class {
  /**
   * API Client for interfacing with the OpenAI API.
   *
   * @param {string | undefined} [opts.apiKey=process.env['OPENAI_API_KEY'] ?? undefined]
   * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null]
   * @param {string | null | undefined} [opts.project=process.env['OPENAI_PROJECT_ID'] ?? null]
   * @param {string | null | undefined} [opts.webhookSecret=process.env['OPENAI_WEBHOOK_SECRET'] ?? null]
   * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL'] ?? https://api.openai.com/v1] - Override the default base URL for the API.
   * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
   * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.
   * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
   * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
   * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
   * @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.
   * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers.
   */
  constructor({ baseURL = readEnv2("OPENAI_BASE_URL"), apiKey = readEnv2("OPENAI_API_KEY"), organization = readEnv2("OPENAI_ORG_ID") ?? null, project = readEnv2("OPENAI_PROJECT_ID") ?? null, webhookSecret = readEnv2("OPENAI_WEBHOOK_SECRET") ?? null, ...opts } = {}) {
    _OpenAI_instances.add(this);
    _OpenAI_encoder.set(this, void 0);
    this.completions = new Completions3(this);
    this.chat = new Chat(this);
    this.embeddings = new Embeddings(this);
    this.files = new Files3(this);
    this.images = new Images(this);
    this.audio = new Audio(this);
    this.moderations = new Moderations(this);
    this.models = new Models3(this);
    this.fineTuning = new FineTuning(this);
    this.graders = new Graders2(this);
    this.vectorStores = new VectorStores(this);
    this.webhooks = new Webhooks(this);
    this.beta = new Beta2(this);
    this.batches = new Batches3(this);
    this.uploads = new Uploads(this);
    this.responses = new Responses(this);
    this.realtime = new Realtime2(this);
    this.conversations = new Conversations(this);
    this.evals = new Evals(this);
    this.containers = new Containers(this);
    this.skills = new Skills2(this);
    this.videos = new Videos(this);
    if (apiKey === void 0) {
      throw new OpenAIError("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");
    }
    const options = {
      apiKey,
      organization,
      project,
      webhookSecret,
      ...opts,
      baseURL: baseURL || `https://api.openai.com/v1`
    };
    if (!options.dangerouslyAllowBrowser && isRunningInBrowser2()) {
      throw new OpenAIError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n");
    }
    this.baseURL = options.baseURL;
    this.timeout = options.timeout ?? _a3.DEFAULT_TIMEOUT;
    this.logger = options.logger ?? console;
    const defaultLogLevel = "warn";
    this.logLevel = defaultLogLevel;
    this.logLevel = parseLogLevel2(options.logLevel, "ClientOptions.logLevel", this) ?? parseLogLevel2(readEnv2("OPENAI_LOG"), "process.env['OPENAI_LOG']", this) ?? defaultLogLevel;
    this.fetchOptions = options.fetchOptions;
    this.maxRetries = options.maxRetries ?? 2;
    this.fetch = options.fetch ?? getDefaultFetch2();
    __classPrivateFieldSet2(this, _OpenAI_encoder, FallbackEncoder2, "f");
    this._options = options;
    this.apiKey = typeof apiKey === "string" ? apiKey : "Missing Key";
    this.organization = organization;
    this.project = project;
    this.webhookSecret = webhookSecret;
  }
  /**
   * Create a new client instance re-using the same options given to the current client with optional overriding.
   */
  withOptions(options) {
    const client = new this.constructor({
      ...this._options,
      baseURL: this.baseURL,
      maxRetries: this.maxRetries,
      timeout: this.timeout,
      logger: this.logger,
      logLevel: this.logLevel,
      fetch: this.fetch,
      fetchOptions: this.fetchOptions,
      apiKey: this.apiKey,
      organization: this.organization,
      project: this.project,
      webhookSecret: this.webhookSecret,
      ...options
    });
    return client;
  }
  defaultQuery() {
    return this._options.defaultQuery;
  }
  validateHeaders({ values: values2, nulls }) {
    return;
  }
  async authHeaders(opts) {
    return buildHeaders2([{ Authorization: `Bearer ${this.apiKey}` }]);
  }
  stringifyQuery(query) {
    return stringifyQuery(query);
  }
  getUserAgent() {
    return `${this.constructor.name}/JS ${VERSION2}`;
  }
  defaultIdempotencyKey() {
    return `stainless-node-retry-${uuid42()}`;
  }
  makeStatusError(status, error, message, headers) {
    return APIError2.generate(status, error, message, headers);
  }
  async _callApiKey() {
    const apiKey = this._options.apiKey;
    if (typeof apiKey !== "function")
      return false;
    let token;
    try {
      token = await apiKey();
    } catch (err) {
      if (err instanceof OpenAIError)
        throw err;
      throw new OpenAIError(
        `Failed to get token from 'apiKey' function: ${err.message}`,
        // @ts-ignore
        { cause: err }
      );
    }
    if (typeof token !== "string" || !token) {
      throw new OpenAIError(`Expected 'apiKey' function argument to return a string but it returned ${token}`);
    }
    this.apiKey = token;
    return true;
  }
  buildURL(path6, query, defaultBaseURL) {
    const baseURL = !__classPrivateFieldGet2(this, _OpenAI_instances, "m", _OpenAI_baseURLOverridden).call(this) && defaultBaseURL || this.baseURL;
    const url = isAbsoluteURL2(path6) ? new URL(path6) : new URL(baseURL + (baseURL.endsWith("/") && path6.startsWith("/") ? path6.slice(1) : path6));
    const defaultQuery = this.defaultQuery();
    if (!isEmptyObj2(defaultQuery)) {
      query = { ...defaultQuery, ...query };
    }
    if (typeof query === "object" && query && !Array.isArray(query)) {
      url.search = this.stringifyQuery(query);
    }
    return url.toString();
  }
  /**
   * Used as a callback for mutating the given `FinalRequestOptions` object.
   */
  async prepareOptions(options) {
    await this._callApiKey();
  }
  /**
   * Used as a callback for mutating the given `RequestInit` object.
   *
   * This is useful for cases where you want to add certain headers based off of
   * the request properties, e.g. `method` or `url`.
   */
  async prepareRequest(request, { url, options }) {
  }
  get(path6, opts) {
    return this.methodRequest("get", path6, opts);
  }
  post(path6, opts) {
    return this.methodRequest("post", path6, opts);
  }
  patch(path6, opts) {
    return this.methodRequest("patch", path6, opts);
  }
  put(path6, opts) {
    return this.methodRequest("put", path6, opts);
  }
  delete(path6, opts) {
    return this.methodRequest("delete", path6, opts);
  }
  methodRequest(method, path6, opts) {
    return this.request(Promise.resolve(opts).then((opts2) => {
      return { method, path: path6, ...opts2 };
    }));
  }
  request(options, remainingRetries = null) {
    return new APIPromise2(this, this.makeRequest(options, remainingRetries, void 0));
  }
  async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {
    const options = await optionsInput;
    const maxRetries = options.maxRetries ?? this.maxRetries;
    if (retriesRemaining == null) {
      retriesRemaining = maxRetries;
    }
    await this.prepareOptions(options);
    const { req, url, timeout } = await this.buildRequest(options, {
      retryCount: maxRetries - retriesRemaining
    });
    await this.prepareRequest(req, { url, options });
    const requestLogID = "log_" + (Math.random() * (1 << 24) | 0).toString(16).padStart(6, "0");
    const retryLogStr = retryOfRequestLogID === void 0 ? "" : `, retryOf: ${retryOfRequestLogID}`;
    const startTime = Date.now();
    loggerFor2(this).debug(`[${requestLogID}] sending request`, formatRequestDetails2({
      retryOfRequestLogID,
      method: options.method,
      url,
      options,
      headers: req.headers
    }));
    if (options.signal?.aborted) {
      throw new APIUserAbortError2();
    }
    const controller = new AbortController();
    const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError2);
    const headersTime = Date.now();
    if (response instanceof globalThis.Error) {
      const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
      if (options.signal?.aborted) {
        throw new APIUserAbortError2();
      }
      const isTimeout = isAbortError2(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : ""));
      if (retriesRemaining) {
        loggerFor2(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`);
        loggerFor2(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails2({
          retryOfRequestLogID,
          url,
          durationMs: headersTime - startTime,
          message: response.message
        }));
        return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID);
      }
      loggerFor2(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - error; no more retries left`);
      loggerFor2(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (error; no more retries left)`, formatRequestDetails2({
        retryOfRequestLogID,
        url,
        durationMs: headersTime - startTime,
        message: response.message
      }));
      if (isTimeout) {
        throw new APIConnectionTimeoutError2();
      }
      throw new APIConnectionError2({ cause: response });
    }
    const specialHeaders = [...response.headers.entries()].filter(([name]) => name === "x-request-id").map(([name, value]) => ", " + name + ": " + JSON.stringify(value)).join("");
    const responseInfo = `[${requestLogID}${retryLogStr}${specialHeaders}] ${req.method} ${url} ${response.ok ? "succeeded" : "failed"} with status ${response.status} in ${headersTime - startTime}ms`;
    if (!response.ok) {
      const shouldRetry = await this.shouldRetry(response);
      if (retriesRemaining && shouldRetry) {
        const retryMessage2 = `retrying, ${retriesRemaining} attempts remaining`;
        await CancelReadableStream2(response.body);
        loggerFor2(this).info(`${responseInfo} - ${retryMessage2}`);
        loggerFor2(this).debug(`[${requestLogID}] response error (${retryMessage2})`, formatRequestDetails2({
          retryOfRequestLogID,
          url: response.url,
          status: response.status,
          headers: response.headers,
          durationMs: headersTime - startTime
        }));
        return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers);
      }
      const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
      loggerFor2(this).info(`${responseInfo} - ${retryMessage}`);
      const errText = await response.text().catch((err2) => castToError2(err2).message);
      const errJSON = safeJSON2(errText);
      const errMessage = errJSON ? void 0 : errText;
      loggerFor2(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails2({
        retryOfRequestLogID,
        url: response.url,
        status: response.status,
        headers: response.headers,
        message: errMessage,
        durationMs: Date.now() - startTime
      }));
      const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);
      throw err;
    }
    loggerFor2(this).info(responseInfo);
    loggerFor2(this).debug(`[${requestLogID}] response start`, formatRequestDetails2({
      retryOfRequestLogID,
      url: response.url,
      status: response.status,
      headers: response.headers,
      durationMs: headersTime - startTime
    }));
    return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };
  }
  getAPIList(path6, Page3, opts) {
    return this.requestAPIList(Page3, opts && "then" in opts ? opts.then((opts2) => ({ method: "get", path: path6, ...opts2 })) : { method: "get", path: path6, ...opts });
  }
  requestAPIList(Page3, options) {
    const request = this.makeRequest(options, null, void 0);
    return new PagePromise2(this, request, Page3);
  }
  async fetchWithTimeout(url, init, ms, controller) {
    const { signal, method, ...options } = init || {};
    const abort = this._makeAbort(controller);
    if (signal)
      signal.addEventListener("abort", abort, { once: true });
    const timeout = setTimeout(abort, ms);
    const isReadableBody = globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream || typeof options.body === "object" && options.body !== null && Symbol.asyncIterator in options.body;
    const fetchOptions = {
      signal: controller.signal,
      ...isReadableBody ? { duplex: "half" } : {},
      method: "GET",
      ...options
    };
    if (method) {
      fetchOptions.method = method.toUpperCase();
    }
    try {
      return await this.fetch.call(void 0, url, fetchOptions);
    } finally {
      clearTimeout(timeout);
    }
  }
  async shouldRetry(response) {
    const shouldRetryHeader = response.headers.get("x-should-retry");
    if (shouldRetryHeader === "true")
      return true;
    if (shouldRetryHeader === "false")
      return false;
    if (response.status === 408)
      return true;
    if (response.status === 409)
      return true;
    if (response.status === 429)
      return true;
    if (response.status >= 500)
      return true;
    return false;
  }
  async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) {
    let timeoutMillis;
    const retryAfterMillisHeader = responseHeaders?.get("retry-after-ms");
    if (retryAfterMillisHeader) {
      const timeoutMs = parseFloat(retryAfterMillisHeader);
      if (!Number.isNaN(timeoutMs)) {
        timeoutMillis = timeoutMs;
      }
    }
    const retryAfterHeader = responseHeaders?.get("retry-after");
    if (retryAfterHeader && !timeoutMillis) {
      const timeoutSeconds = parseFloat(retryAfterHeader);
      if (!Number.isNaN(timeoutSeconds)) {
        timeoutMillis = timeoutSeconds * 1e3;
      } else {
        timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
      }
    }
    if (timeoutMillis === void 0) {
      const maxRetries = options.maxRetries ?? this.maxRetries;
      timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
    }
    await sleep2(timeoutMillis);
    return this.makeRequest(options, retriesRemaining - 1, requestLogID);
  }
  calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
    const initialRetryDelay = 0.5;
    const maxRetryDelay = 8;
    const numRetries = maxRetries - retriesRemaining;
    const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
    const jitter = 1 - Math.random() * 0.25;
    return sleepSeconds * jitter * 1e3;
  }
  async buildRequest(inputOptions, { retryCount = 0 } = {}) {
    const options = { ...inputOptions };
    const { method, path: path6, query, defaultBaseURL } = options;
    const url = this.buildURL(path6, query, defaultBaseURL);
    if ("timeout" in options)
      validatePositiveInteger2("timeout", options.timeout);
    options.timeout = options.timeout ?? this.timeout;
    const { bodyHeaders, body } = this.buildBody({ options });
    const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
    const req = {
      method,
      headers: reqHeaders,
      ...options.signal && { signal: options.signal },
      ...globalThis.ReadableStream && body instanceof globalThis.ReadableStream && { duplex: "half" },
      ...body && { body },
      ...this.fetchOptions ?? {},
      ...options.fetchOptions ?? {}
    };
    return { req, url, timeout: options.timeout };
  }
  async buildHeaders({ options, method, bodyHeaders, retryCount }) {
    let idempotencyHeaders = {};
    if (this.idempotencyHeader && method !== "get") {
      if (!options.idempotencyKey)
        options.idempotencyKey = this.defaultIdempotencyKey();
      idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey;
    }
    const headers = buildHeaders2([
      idempotencyHeaders,
      {
        Accept: "application/json",
        "User-Agent": this.getUserAgent(),
        "X-Stainless-Retry-Count": String(retryCount),
        ...options.timeout ? { "X-Stainless-Timeout": String(Math.trunc(options.timeout / 1e3)) } : {},
        ...getPlatformHeaders2(),
        "OpenAI-Organization": this.organization,
        "OpenAI-Project": this.project
      },
      await this.authHeaders(options),
      this._options.defaultHeaders,
      bodyHeaders,
      options.headers
    ]);
    this.validateHeaders(headers);
    return headers.values;
  }
  _makeAbort(controller) {
    return () => controller.abort();
  }
  buildBody({ options: { body, headers: rawHeaders } }) {
    if (!body) {
      return { bodyHeaders: void 0, body: void 0 };
    }
    const headers = buildHeaders2([rawHeaders]);
    if (
      // Pass raw type verbatim
      ArrayBuffer.isView(body) || body instanceof ArrayBuffer || body instanceof DataView || typeof body === "string" && // Preserve legacy string encoding behavior for now
      headers.values.has("content-type") || // `Blob` is superset of `File`
      globalThis.Blob && body instanceof globalThis.Blob || // `FormData` -> `multipart/form-data`
      body instanceof FormData || // `URLSearchParams` -> `application/x-www-form-urlencoded`
      body instanceof URLSearchParams || // Send chunked stream (each chunk has own `length`)
      globalThis.ReadableStream && body instanceof globalThis.ReadableStream
    ) {
      return { bodyHeaders: void 0, body };
    } else if (typeof body === "object" && (Symbol.asyncIterator in body || Symbol.iterator in body && "next" in body && typeof body.next === "function")) {
      return { bodyHeaders: void 0, body: ReadableStreamFrom2(body) };
    } else if (typeof body === "object" && headers.values.get("content-type") === "application/x-www-form-urlencoded") {
      return {
        bodyHeaders: { "content-type": "application/x-www-form-urlencoded" },
        body: this.stringifyQuery(body)
      };
    } else {
      return __classPrivateFieldGet2(this, _OpenAI_encoder, "f").call(this, { body, headers });
    }
  }
};
_a3 = OpenAI, _OpenAI_encoder = /* @__PURE__ */ new WeakMap(), _OpenAI_instances = /* @__PURE__ */ new WeakSet(), _OpenAI_baseURLOverridden = function _OpenAI_baseURLOverridden2() {
  return this.baseURL !== "https://api.openai.com/v1";
};
OpenAI.OpenAI = _a3;
OpenAI.DEFAULT_TIMEOUT = 6e5;
OpenAI.OpenAIError = OpenAIError;
OpenAI.APIError = APIError2;
OpenAI.APIConnectionError = APIConnectionError2;
OpenAI.APIConnectionTimeoutError = APIConnectionTimeoutError2;
OpenAI.APIUserAbortError = APIUserAbortError2;
OpenAI.NotFoundError = NotFoundError2;
OpenAI.ConflictError = ConflictError2;
OpenAI.RateLimitError = RateLimitError2;
OpenAI.BadRequestError = BadRequestError2;
OpenAI.AuthenticationError = AuthenticationError2;
OpenAI.InternalServerError = InternalServerError2;
OpenAI.PermissionDeniedError = PermissionDeniedError2;
OpenAI.UnprocessableEntityError = UnprocessableEntityError2;
OpenAI.InvalidWebhookSignatureError = InvalidWebhookSignatureError;
OpenAI.toFile = toFile2;
OpenAI.Completions = Completions3;
OpenAI.Chat = Chat;
OpenAI.Embeddings = Embeddings;
OpenAI.Files = Files3;
OpenAI.Images = Images;
OpenAI.Audio = Audio;
OpenAI.Moderations = Moderations;
OpenAI.Models = Models3;
OpenAI.FineTuning = FineTuning;
OpenAI.Graders = Graders2;
OpenAI.VectorStores = VectorStores;
OpenAI.Webhooks = Webhooks;
OpenAI.Beta = Beta2;
OpenAI.Batches = Batches3;
OpenAI.Uploads = Uploads;
OpenAI.Responses = Responses;
OpenAI.Realtime = Realtime2;
OpenAI.Conversations = Conversations;
OpenAI.Evals = Evals;
OpenAI.Containers = Containers;
OpenAI.Skills = Skills2;
OpenAI.Videos = Videos;

// ../pi-mono/node_modules/openai/azure.mjs
init_process_shim();
var AzureOpenAI = class extends OpenAI {
  /**
   * API Client for interfacing with the Azure OpenAI API.
   *
   * @param {string | undefined} [opts.apiVersion=process.env['OPENAI_API_VERSION'] ?? undefined]
   * @param {string | undefined} [opts.endpoint=process.env['AZURE_OPENAI_ENDPOINT'] ?? undefined] - Your Azure endpoint, including the resource, e.g. `https://example-resource.azure.openai.com/`
   * @param {string | undefined} [opts.apiKey=process.env['AZURE_OPENAI_API_KEY'] ?? undefined]
   * @param {string | undefined} opts.deployment - A model deployment, if given, sets the base client URL to include `/deployments/{deployment}`.
   * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null]
   * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL']] - Sets the base URL for the API, e.g. `https://example-resource.azure.openai.com/openai/`.
   * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
   * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections.
   * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
   * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
   * @param {Headers} opts.defaultHeaders - Default headers to include with every request to the API.
   * @param {DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API.
   * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers.
   */
  constructor({ baseURL = readEnv2("OPENAI_BASE_URL"), apiKey = readEnv2("AZURE_OPENAI_API_KEY"), apiVersion = readEnv2("OPENAI_API_VERSION"), endpoint, deployment, azureADTokenProvider, dangerouslyAllowBrowser, ...opts } = {}) {
    if (!apiVersion) {
      throw new OpenAIError("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).");
    }
    if (typeof azureADTokenProvider === "function") {
      dangerouslyAllowBrowser = true;
    }
    if (!azureADTokenProvider && !apiKey) {
      throw new OpenAIError("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");
    }
    if (azureADTokenProvider && apiKey) {
      throw new OpenAIError("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");
    }
    opts.defaultQuery = { ...opts.defaultQuery, "api-version": apiVersion };
    if (!baseURL) {
      if (!endpoint) {
        endpoint = process.env["AZURE_OPENAI_ENDPOINT"];
      }
      if (!endpoint) {
        throw new OpenAIError("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");
      }
      baseURL = `${endpoint}/openai`;
    } else {
      if (endpoint) {
        throw new OpenAIError("baseURL and endpoint are mutually exclusive");
      }
    }
    super({
      apiKey: azureADTokenProvider ?? apiKey,
      baseURL,
      ...opts,
      ...dangerouslyAllowBrowser !== void 0 ? { dangerouslyAllowBrowser } : {}
    });
    this.apiVersion = "";
    this.apiVersion = apiVersion;
    this.deploymentName = deployment;
  }
  async buildRequest(options, props = {}) {
    if (_deployments_endpoints.has(options.path) && options.method === "post" && options.body !== void 0) {
      if (!isObj(options.body)) {
        throw new Error("Expected request body to be an object");
      }
      const model = this.deploymentName || options.body["model"] || options.__metadata?.["model"];
      if (model !== void 0 && !this.baseURL.includes("/deployments")) {
        options.path = `/deployments/${model}${options.path}`;
      }
    }
    return super.buildRequest(options, props);
  }
  async authHeaders(opts) {
    if (typeof this._options.apiKey === "string") {
      return buildHeaders2([{ "api-key": this.apiKey }]);
    }
    return super.authHeaders(opts);
  }
};
var _deployments_endpoints = /* @__PURE__ */ new Set([
  "/completions",
  "/chat/completions",
  "/embeddings",
  "/audio/transcriptions",
  "/audio/translations",
  "/audio/speech",
  "/images/generations",
  "/batches",
  "/images/edits"
]);

// ../pi-mono/packages/ai/dist/providers/openai-responses-shared.js
init_process_shim();

// ../pi-mono/packages/ai/dist/utils/hash.js
init_process_shim();
function shortHash(str2) {
  let h1 = 3735928559;
  let h22 = 1103547991;
  for (let i7 = 0; i7 < str2.length; i7++) {
    const ch = str2.charCodeAt(i7);
    h1 = Math.imul(h1 ^ ch, 2654435761);
    h22 = Math.imul(h22 ^ ch, 1597334677);
  }
  h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507) ^ Math.imul(h22 ^ h22 >>> 13, 3266489909);
  h22 = Math.imul(h22 ^ h22 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
  return (h22 >>> 0).toString(36) + (h1 >>> 0).toString(36);
}

// ../pi-mono/packages/ai/dist/providers/openai-responses-shared.js
function encodeTextSignatureV1(id, phase) {
  const payload = { v: 1, id };
  if (phase)
    payload.phase = phase;
  return JSON.stringify(payload);
}
function parseTextSignature(signature) {
  if (!signature)
    return void 0;
  if (signature.startsWith("{")) {
    try {
      const parsed = JSON.parse(signature);
      if (parsed.v === 1 && typeof parsed.id === "string") {
        if (parsed.phase === "commentary" || parsed.phase === "final_answer") {
          return { id: parsed.id, phase: parsed.phase };
        }
        return { id: parsed.id };
      }
    } catch {
    }
  }
  return { id: signature };
}
function convertResponsesMessages(model, context, allowedToolCallProviders, options) {
  const messages = [];
  const normalizeToolCallId2 = (id) => {
    if (!allowedToolCallProviders.has(model.provider))
      return id;
    if (!id.includes("|"))
      return id;
    const [callId, itemId] = id.split("|");
    const sanitizedCallId = callId.replace(/[^a-zA-Z0-9_-]/g, "_");
    let sanitizedItemId = itemId.replace(/[^a-zA-Z0-9_-]/g, "_");
    if (!sanitizedItemId.startsWith("fc")) {
      sanitizedItemId = `fc_${sanitizedItemId}`;
    }
    let normalizedCallId = sanitizedCallId.length > 64 ? sanitizedCallId.slice(0, 64) : sanitizedCallId;
    let normalizedItemId = sanitizedItemId.length > 64 ? sanitizedItemId.slice(0, 64) : sanitizedItemId;
    normalizedCallId = normalizedCallId.replace(/_+$/, "");
    normalizedItemId = normalizedItemId.replace(/_+$/, "");
    return `${normalizedCallId}|${normalizedItemId}`;
  };
  const transformedMessages = transformMessages(context.messages, model, normalizeToolCallId2);
  const includeSystemPrompt = options?.includeSystemPrompt ?? true;
  if (includeSystemPrompt && context.systemPrompt) {
    const role = model.reasoning ? "developer" : "system";
    messages.push({
      role,
      content: sanitizeSurrogates(context.systemPrompt)
    });
  }
  let msgIndex = 0;
  for (const msg of transformedMessages) {
    if (msg.role === "user") {
      if (typeof msg.content === "string") {
        messages.push({
          role: "user",
          content: [{ type: "input_text", text: sanitizeSurrogates(msg.content) }]
        });
      } else {
        const content = msg.content.map((item) => {
          if (item.type === "text") {
            return {
              type: "input_text",
              text: sanitizeSurrogates(item.text)
            };
          }
          return {
            type: "input_image",
            detail: "auto",
            image_url: `data:${item.mimeType};base64,${item.data}`
          };
        });
        const filteredContent = !model.input.includes("image") ? content.filter((c6) => c6.type !== "input_image") : content;
        if (filteredContent.length === 0)
          continue;
        messages.push({
          role: "user",
          content: filteredContent
        });
      }
    } else if (msg.role === "assistant") {
      const output = [];
      const assistantMsg = msg;
      const isDifferentModel = assistantMsg.model !== model.id && assistantMsg.provider === model.provider && assistantMsg.api === model.api;
      for (const block of msg.content) {
        if (block.type === "thinking") {
          if (block.thinkingSignature) {
            const reasoningItem = JSON.parse(block.thinkingSignature);
            output.push(reasoningItem);
          }
        } else if (block.type === "text") {
          const textBlock = block;
          const parsedSignature = parseTextSignature(textBlock.textSignature);
          let msgId = parsedSignature?.id;
          if (!msgId) {
            msgId = `msg_${msgIndex}`;
          } else if (msgId.length > 64) {
            msgId = `msg_${shortHash(msgId)}`;
          }
          output.push({
            type: "message",
            role: "assistant",
            content: [{ type: "output_text", text: sanitizeSurrogates(textBlock.text), annotations: [] }],
            status: "completed",
            id: msgId,
            phase: parsedSignature?.phase
          });
        } else if (block.type === "toolCall") {
          const toolCall = block;
          const [callId, itemIdRaw] = toolCall.id.split("|");
          let itemId = itemIdRaw;
          if (isDifferentModel && itemId?.startsWith("fc_")) {
            itemId = void 0;
          }
          output.push({
            type: "function_call",
            id: itemId,
            call_id: callId,
            name: toolCall.name,
            arguments: JSON.stringify(toolCall.arguments)
          });
        }
      }
      if (output.length === 0)
        continue;
      messages.push(...output);
    } else if (msg.role === "toolResult") {
      const textResult = msg.content.filter((c6) => c6.type === "text").map((c6) => c6.text).join("\n");
      const hasImages = msg.content.some((c6) => c6.type === "image");
      const hasText = textResult.length > 0;
      const [callId] = msg.toolCallId.split("|");
      let output;
      if (hasImages && model.input.includes("image")) {
        const contentParts = [];
        if (hasText) {
          contentParts.push({
            type: "input_text",
            text: sanitizeSurrogates(textResult)
          });
        }
        for (const block of msg.content) {
          if (block.type === "image") {
            contentParts.push({
              type: "input_image",
              detail: "auto",
              image_url: `data:${block.mimeType};base64,${block.data}`
            });
          }
        }
        output = contentParts;
      } else {
        output = sanitizeSurrogates(hasText ? textResult : "(see attached image)");
      }
      messages.push({
        type: "function_call_output",
        call_id: callId,
        output
      });
    }
    msgIndex++;
  }
  return messages;
}
function convertResponsesTools(tools, options) {
  const strict = options?.strict === void 0 ? false : options.strict;
  return tools.map((tool) => ({
    type: "function",
    name: tool.name,
    description: tool.description,
    parameters: tool.parameters,
    // TypeBox already generates JSON Schema
    strict
  }));
}
async function processResponsesStream(openaiStream, output, stream2, model, options) {
  let currentItem = null;
  let currentBlock = null;
  const blocks = output.content;
  const blockIndex = () => blocks.length - 1;
  for await (const event of openaiStream) {
    if (event.type === "response.output_item.added") {
      const item = event.item;
      if (item.type === "reasoning") {
        currentItem = item;
        currentBlock = { type: "thinking", thinking: "" };
        output.content.push(currentBlock);
        stream2.push({ type: "thinking_start", contentIndex: blockIndex(), partial: output });
      } else if (item.type === "message") {
        currentItem = item;
        currentBlock = { type: "text", text: "" };
        output.content.push(currentBlock);
        stream2.push({ type: "text_start", contentIndex: blockIndex(), partial: output });
      } else if (item.type === "function_call") {
        currentItem = item;
        currentBlock = {
          type: "toolCall",
          id: `${item.call_id}|${item.id}`,
          name: item.name,
          arguments: {},
          partialJson: item.arguments || ""
        };
        output.content.push(currentBlock);
        stream2.push({ type: "toolcall_start", contentIndex: blockIndex(), partial: output });
      }
    } else if (event.type === "response.reasoning_summary_part.added") {
      if (currentItem && currentItem.type === "reasoning") {
        currentItem.summary = currentItem.summary || [];
        currentItem.summary.push(event.part);
      }
    } else if (event.type === "response.reasoning_summary_text.delta") {
      if (currentItem?.type === "reasoning" && currentBlock?.type === "thinking") {
        currentItem.summary = currentItem.summary || [];
        const lastPart = currentItem.summary[currentItem.summary.length - 1];
        if (lastPart) {
          currentBlock.thinking += event.delta;
          lastPart.text += event.delta;
          stream2.push({
            type: "thinking_delta",
            contentIndex: blockIndex(),
            delta: event.delta,
            partial: output
          });
        }
      }
    } else if (event.type === "response.reasoning_summary_part.done") {
      if (currentItem?.type === "reasoning" && currentBlock?.type === "thinking") {
        currentItem.summary = currentItem.summary || [];
        const lastPart = currentItem.summary[currentItem.summary.length - 1];
        if (lastPart) {
          currentBlock.thinking += "\n\n";
          lastPart.text += "\n\n";
          stream2.push({
            type: "thinking_delta",
            contentIndex: blockIndex(),
            delta: "\n\n",
            partial: output
          });
        }
      }
    } else if (event.type === "response.content_part.added") {
      if (currentItem?.type === "message") {
        currentItem.content = currentItem.content || [];
        if (event.part.type === "output_text" || event.part.type === "refusal") {
          currentItem.content.push(event.part);
        }
      }
    } else if (event.type === "response.output_text.delta") {
      if (currentItem?.type === "message" && currentBlock?.type === "text") {
        if (!currentItem.content || currentItem.content.length === 0) {
          continue;
        }
        const lastPart = currentItem.content[currentItem.content.length - 1];
        if (lastPart?.type === "output_text") {
          currentBlock.text += event.delta;
          lastPart.text += event.delta;
          stream2.push({
            type: "text_delta",
            contentIndex: blockIndex(),
            delta: event.delta,
            partial: output
          });
        }
      }
    } else if (event.type === "response.refusal.delta") {
      if (currentItem?.type === "message" && currentBlock?.type === "text") {
        if (!currentItem.content || currentItem.content.length === 0) {
          continue;
        }
        const lastPart = currentItem.content[currentItem.content.length - 1];
        if (lastPart?.type === "refusal") {
          currentBlock.text += event.delta;
          lastPart.refusal += event.delta;
          stream2.push({
            type: "text_delta",
            contentIndex: blockIndex(),
            delta: event.delta,
            partial: output
          });
        }
      }
    } else if (event.type === "response.function_call_arguments.delta") {
      if (currentItem?.type === "function_call" && currentBlock?.type === "toolCall") {
        currentBlock.partialJson += event.delta;
        currentBlock.arguments = parseStreamingJson(currentBlock.partialJson);
        stream2.push({
          type: "toolcall_delta",
          contentIndex: blockIndex(),
          delta: event.delta,
          partial: output
        });
      }
    } else if (event.type === "response.function_call_arguments.done") {
      if (currentItem?.type === "function_call" && currentBlock?.type === "toolCall") {
        currentBlock.partialJson = event.arguments;
        currentBlock.arguments = parseStreamingJson(currentBlock.partialJson);
      }
    } else if (event.type === "response.output_item.done") {
      const item = event.item;
      if (item.type === "reasoning" && currentBlock?.type === "thinking") {
        currentBlock.thinking = item.summary?.map((s6) => s6.text).join("\n\n") || "";
        currentBlock.thinkingSignature = JSON.stringify(item);
        stream2.push({
          type: "thinking_end",
          contentIndex: blockIndex(),
          content: currentBlock.thinking,
          partial: output
        });
        currentBlock = null;
      } else if (item.type === "message" && currentBlock?.type === "text") {
        currentBlock.text = item.content.map((c6) => c6.type === "output_text" ? c6.text : c6.refusal).join("");
        currentBlock.textSignature = encodeTextSignatureV1(item.id, item.phase ?? void 0);
        stream2.push({
          type: "text_end",
          contentIndex: blockIndex(),
          content: currentBlock.text,
          partial: output
        });
        currentBlock = null;
      } else if (item.type === "function_call") {
        const args = currentBlock?.type === "toolCall" && currentBlock.partialJson ? parseStreamingJson(currentBlock.partialJson) : parseStreamingJson(item.arguments || "{}");
        const toolCall = {
          type: "toolCall",
          id: `${item.call_id}|${item.id}`,
          name: item.name,
          arguments: args
        };
        currentBlock = null;
        stream2.push({ type: "toolcall_end", contentIndex: blockIndex(), toolCall, partial: output });
      }
    } else if (event.type === "response.completed") {
      const response = event.response;
      if (response?.usage) {
        const cachedTokens = response.usage.input_tokens_details?.cached_tokens || 0;
        output.usage = {
          // OpenAI includes cached tokens in input_tokens, so subtract to get non-cached input
          input: (response.usage.input_tokens || 0) - cachedTokens,
          output: response.usage.output_tokens || 0,
          cacheRead: cachedTokens,
          cacheWrite: 0,
          totalTokens: response.usage.total_tokens || 0,
          cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
        };
      }
      calculateCost(model, output.usage);
      if (options?.applyServiceTierPricing) {
        const serviceTier = response?.service_tier ?? options.serviceTier;
        options.applyServiceTierPricing(output.usage, serviceTier);
      }
      output.stopReason = mapStopReason2(response?.status);
      if (output.content.some((b4) => b4.type === "toolCall") && output.stopReason === "stop") {
        output.stopReason = "toolUse";
      }
    } else if (event.type === "error") {
      throw new Error(`Error Code ${event.code}: ${event.message}` || "Unknown error");
    } else if (event.type === "response.failed") {
      const error = event.response?.error;
      const details = event.response?.incomplete_details;
      const msg = error ? `${error.code || "unknown"}: ${error.message || "no message"}` : details?.reason ? `incomplete: ${details.reason}` : "Unknown error (no error details in response)";
      throw new Error(msg);
    }
  }
}
function mapStopReason2(status) {
  if (!status)
    return "stop";
  switch (status) {
    case "completed":
      return "stop";
    case "incomplete":
      return "length";
    case "failed":
    case "cancelled":
      return "error";
    // These two are wonky ...
    case "in_progress":
    case "queued":
      return "stop";
    default: {
      const _exhaustive = status;
      throw new Error(`Unhandled stop reason: ${_exhaustive}`);
    }
  }
}

// ../pi-mono/packages/ai/dist/providers/azure-openai-responses.js
var DEFAULT_AZURE_API_VERSION = "v1";
var AZURE_TOOL_CALL_PROVIDERS = /* @__PURE__ */ new Set(["openai", "openai-codex", "opencode", "azure-openai-responses"]);
function parseDeploymentNameMap(value) {
  const map = /* @__PURE__ */ new Map();
  if (!value)
    return map;
  for (const entry of value.split(",")) {
    const trimmed = entry.trim();
    if (!trimmed)
      continue;
    const [modelId, deploymentName] = trimmed.split("=", 2);
    if (!modelId || !deploymentName)
      continue;
    map.set(modelId.trim(), deploymentName.trim());
  }
  return map;
}
function resolveDeploymentName(model, options) {
  if (options?.azureDeploymentName) {
    return options.azureDeploymentName;
  }
  const mappedDeployment = parseDeploymentNameMap(process.env.AZURE_OPENAI_DEPLOYMENT_NAME_MAP).get(model.id);
  return mappedDeployment || model.id;
}
var streamAzureOpenAIResponses = (model, context, options) => {
  const stream2 = new AssistantMessageEventStream();
  (async () => {
    const deploymentName = resolveDeploymentName(model, options);
    const output = {
      role: "assistant",
      content: [],
      api: "azure-openai-responses",
      provider: model.provider,
      model: model.id,
      usage: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0,
        totalTokens: 0,
        cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
      },
      stopReason: "stop",
      timestamp: Date.now()
    };
    try {
      const apiKey = options?.apiKey || getEnvApiKey(model.provider) || "";
      const client = createClient2(model, apiKey, options);
      let params = buildParams2(model, context, options, deploymentName);
      const nextParams = await options?.onPayload?.(params, model);
      if (nextParams !== void 0) {
        params = nextParams;
      }
      const openaiStream = await client.responses.create(params, options?.signal ? { signal: options.signal } : void 0);
      stream2.push({ type: "start", partial: output });
      await processResponsesStream(openaiStream, output, stream2, model);
      if (options?.signal?.aborted) {
        throw new Error("Request was aborted");
      }
      if (output.stopReason === "aborted" || output.stopReason === "error") {
        throw new Error("An unknown error occurred");
      }
      stream2.push({ type: "done", reason: output.stopReason, message: output });
      stream2.end();
    } catch (error) {
      for (const block of output.content)
        delete block.index;
      output.stopReason = options?.signal?.aborted ? "aborted" : "error";
      output.errorMessage = error instanceof Error ? error.message : JSON.stringify(error);
      stream2.push({ type: "error", reason: output.stopReason, error: output });
      stream2.end();
    }
  })();
  return stream2;
};
var streamSimpleAzureOpenAIResponses = (model, context, options) => {
  const apiKey = options?.apiKey || getEnvApiKey(model.provider);
  if (!apiKey) {
    throw new Error(`No API key for provider: ${model.provider}`);
  }
  const base = buildBaseOptions(model, options, apiKey);
  const reasoningEffort = supportsXhigh(model) ? options?.reasoning : clampReasoning(options?.reasoning);
  return streamAzureOpenAIResponses(model, context, {
    ...base,
    reasoningEffort
  });
};
function normalizeAzureBaseUrl(baseUrl) {
  return baseUrl.replace(/\/+$/, "");
}
function buildDefaultBaseUrl(resourceName2) {
  return `https://${resourceName2}.openai.azure.com/openai/v1`;
}
function resolveAzureConfig(model, options) {
  const apiVersion = options?.azureApiVersion || process.env.AZURE_OPENAI_API_VERSION || DEFAULT_AZURE_API_VERSION;
  const baseUrl = options?.azureBaseUrl?.trim() || process.env.AZURE_OPENAI_BASE_URL?.trim() || void 0;
  const resourceName2 = options?.azureResourceName || process.env.AZURE_OPENAI_RESOURCE_NAME;
  let resolvedBaseUrl = baseUrl;
  if (!resolvedBaseUrl && resourceName2) {
    resolvedBaseUrl = buildDefaultBaseUrl(resourceName2);
  }
  if (!resolvedBaseUrl && model.baseUrl) {
    resolvedBaseUrl = model.baseUrl;
  }
  if (!resolvedBaseUrl) {
    throw new Error("Azure OpenAI base URL is required. Set AZURE_OPENAI_BASE_URL or AZURE_OPENAI_RESOURCE_NAME, or pass azureBaseUrl, azureResourceName, or model.baseUrl.");
  }
  return {
    baseUrl: normalizeAzureBaseUrl(resolvedBaseUrl),
    apiVersion
  };
}
function createClient2(model, apiKey, options) {
  if (!apiKey) {
    if (!process.env.AZURE_OPENAI_API_KEY) {
      throw new Error("Azure OpenAI API key is required. Set AZURE_OPENAI_API_KEY environment variable or pass it as an argument.");
    }
    apiKey = process.env.AZURE_OPENAI_API_KEY;
  }
  const headers = { ...model.headers };
  if (options?.headers) {
    Object.assign(headers, options.headers);
  }
  const { baseUrl, apiVersion } = resolveAzureConfig(model, options);
  return new AzureOpenAI({
    apiKey,
    apiVersion,
    dangerouslyAllowBrowser: true,
    defaultHeaders: headers,
    baseURL: baseUrl
  });
}
function buildParams2(model, context, options, deploymentName) {
  const messages = convertResponsesMessages(model, context, AZURE_TOOL_CALL_PROVIDERS);
  const params = {
    model: deploymentName,
    input: messages,
    stream: true,
    prompt_cache_key: options?.sessionId
  };
  if (options?.maxTokens) {
    params.max_output_tokens = options?.maxTokens;
  }
  if (options?.temperature !== void 0) {
    params.temperature = options?.temperature;
  }
  if (context.tools) {
    params.tools = convertResponsesTools(context.tools);
  }
  if (model.reasoning) {
    if (options?.reasoningEffort || options?.reasoningSummary) {
      params.reasoning = {
        effort: options?.reasoningEffort || "medium",
        summary: options?.reasoningSummary || "auto"
      };
      params.include = ["reasoning.encrypted_content"];
    } else {
      if (model.name.toLowerCase().startsWith("gpt-5")) {
        messages.push({
          role: "developer",
          content: [
            {
              type: "input_text",
              text: "# Juice: 0 !important"
            }
          ]
        });
      }
    }
  }
  return params;
}

// ../pi-mono/packages/ai/dist/providers/google.js
init_process_shim();

// ../pi-mono/node_modules/@google/genai/dist/web/index.mjs
init_process_shim();
var import_p_retry = __toESM(require_p_retry(), 1);
var _defaultBaseGeminiUrl = void 0;
var _defaultBaseVertexUrl = void 0;
function getDefaultBaseUrls() {
  return {
    geminiUrl: _defaultBaseGeminiUrl,
    vertexUrl: _defaultBaseVertexUrl
  };
}
function getBaseUrl(httpOptions, vertexai, vertexBaseUrlFromEnv, geminiBaseUrlFromEnv) {
  var _a7, _b;
  if (!(httpOptions === null || httpOptions === void 0 ? void 0 : httpOptions.baseUrl)) {
    const defaultBaseUrls = getDefaultBaseUrls();
    if (vertexai) {
      return (_a7 = defaultBaseUrls.vertexUrl) !== null && _a7 !== void 0 ? _a7 : vertexBaseUrlFromEnv;
    } else {
      return (_b = defaultBaseUrls.geminiUrl) !== null && _b !== void 0 ? _b : geminiBaseUrlFromEnv;
    }
  }
  return httpOptions.baseUrl;
}
var BaseModule = class {
};
function formatMap(templateString, valueMap) {
  const regex = /\{([^}]+)\}/g;
  return templateString.replace(regex, (match2, key) => {
    if (Object.prototype.hasOwnProperty.call(valueMap, key)) {
      const value = valueMap[key];
      return value !== void 0 && value !== null ? String(value) : "";
    } else {
      throw new Error(`Key '${key}' not found in valueMap.`);
    }
  });
}
function setValueByPath(data, keys2, value) {
  for (let i7 = 0; i7 < keys2.length - 1; i7++) {
    const key = keys2[i7];
    if (key.endsWith("[]")) {
      const keyName = key.slice(0, -2);
      if (!(keyName in data)) {
        if (Array.isArray(value)) {
          data[keyName] = Array.from({ length: value.length }, () => ({}));
        } else {
          throw new Error(`Value must be a list given an array path ${key}`);
        }
      }
      if (Array.isArray(data[keyName])) {
        const arrayData = data[keyName];
        if (Array.isArray(value)) {
          for (let j3 = 0; j3 < arrayData.length; j3++) {
            const entry = arrayData[j3];
            setValueByPath(entry, keys2.slice(i7 + 1), value[j3]);
          }
        } else {
          for (const d4 of arrayData) {
            setValueByPath(d4, keys2.slice(i7 + 1), value);
          }
        }
      }
      return;
    } else if (key.endsWith("[0]")) {
      const keyName = key.slice(0, -3);
      if (!(keyName in data)) {
        data[keyName] = [{}];
      }
      const arrayData = data[keyName];
      setValueByPath(arrayData[0], keys2.slice(i7 + 1), value);
      return;
    }
    if (!data[key] || typeof data[key] !== "object") {
      data[key] = {};
    }
    data = data[key];
  }
  const keyToSet = keys2[keys2.length - 1];
  const existingData = data[keyToSet];
  if (existingData !== void 0) {
    if (!value || typeof value === "object" && Object.keys(value).length === 0) {
      return;
    }
    if (value === existingData) {
      return;
    }
    if (typeof existingData === "object" && typeof value === "object" && existingData !== null && value !== null) {
      Object.assign(existingData, value);
    } else {
      throw new Error(`Cannot set value for an existing key. Key: ${keyToSet}`);
    }
  } else {
    if (keyToSet === "_self" && typeof value === "object" && value !== null && !Array.isArray(value)) {
      const valueAsRecord = value;
      Object.assign(data, valueAsRecord);
    } else {
      data[keyToSet] = value;
    }
  }
}
function getValueByPath(data, keys2, defaultValue = void 0) {
  try {
    if (keys2.length === 1 && keys2[0] === "_self") {
      return data;
    }
    for (let i7 = 0; i7 < keys2.length; i7++) {
      if (typeof data !== "object" || data === null) {
        return defaultValue;
      }
      const key = keys2[i7];
      if (key.endsWith("[]")) {
        const keyName = key.slice(0, -2);
        if (keyName in data) {
          const arrayData = data[keyName];
          if (!Array.isArray(arrayData)) {
            return defaultValue;
          }
          return arrayData.map((d4) => getValueByPath(d4, keys2.slice(i7 + 1), defaultValue));
        } else {
          return defaultValue;
        }
      } else {
        data = data[key];
      }
    }
    return data;
  } catch (error) {
    if (error instanceof TypeError) {
      return defaultValue;
    }
    throw error;
  }
}
function moveValueByPath(data, paths) {
  for (const [sourcePath, destPath] of Object.entries(paths)) {
    const sourceKeys = sourcePath.split(".");
    const destKeys = destPath.split(".");
    const excludeKeys = /* @__PURE__ */ new Set();
    let wildcardIdx = -1;
    for (let i7 = 0; i7 < sourceKeys.length; i7++) {
      if (sourceKeys[i7] === "*") {
        wildcardIdx = i7;
        break;
      }
    }
    if (wildcardIdx !== -1 && destKeys.length > wildcardIdx) {
      for (let i7 = wildcardIdx; i7 < destKeys.length; i7++) {
        const key = destKeys[i7];
        if (key !== "*" && !key.endsWith("[]") && !key.endsWith("[0]")) {
          excludeKeys.add(key);
        }
      }
    }
    _moveValueRecursive(data, sourceKeys, destKeys, 0, excludeKeys);
  }
}
function _moveValueRecursive(data, sourceKeys, destKeys, keyIdx, excludeKeys) {
  if (keyIdx >= sourceKeys.length) {
    return;
  }
  if (typeof data !== "object" || data === null) {
    return;
  }
  const key = sourceKeys[keyIdx];
  if (key.endsWith("[]")) {
    const keyName = key.slice(0, -2);
    const dataRecord = data;
    if (keyName in dataRecord && Array.isArray(dataRecord[keyName])) {
      for (const item of dataRecord[keyName]) {
        _moveValueRecursive(item, sourceKeys, destKeys, keyIdx + 1, excludeKeys);
      }
    }
  } else if (key === "*") {
    if (typeof data === "object" && data !== null && !Array.isArray(data)) {
      const dataRecord = data;
      const keysToMove = Object.keys(dataRecord).filter((k2) => !k2.startsWith("_") && !excludeKeys.has(k2));
      const valuesToMove = {};
      for (const k2 of keysToMove) {
        valuesToMove[k2] = dataRecord[k2];
      }
      for (const [k2, v4] of Object.entries(valuesToMove)) {
        const newDestKeys = [];
        for (const dk of destKeys.slice(keyIdx)) {
          if (dk === "*") {
            newDestKeys.push(k2);
          } else {
            newDestKeys.push(dk);
          }
        }
        setValueByPath(dataRecord, newDestKeys, v4);
      }
      for (const k2 of keysToMove) {
        delete dataRecord[k2];
      }
    }
  } else {
    const dataRecord = data;
    if (key in dataRecord) {
      _moveValueRecursive(dataRecord[key], sourceKeys, destKeys, keyIdx + 1, excludeKeys);
    }
  }
}
function tBytes$1(fromBytes) {
  if (typeof fromBytes !== "string") {
    throw new Error("fromImageBytes must be a string");
  }
  return fromBytes;
}
function fetchPredictOperationParametersToVertex(fromObject) {
  const toObject = {};
  const fromOperationName = getValueByPath(fromObject, [
    "operationName"
  ]);
  if (fromOperationName != null) {
    setValueByPath(toObject, ["operationName"], fromOperationName);
  }
  const fromResourceName = getValueByPath(fromObject, ["resourceName"]);
  if (fromResourceName != null) {
    setValueByPath(toObject, ["_url", "resourceName"], fromResourceName);
  }
  return toObject;
}
function generateVideosOperationFromMldev$1(fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromMetadata = getValueByPath(fromObject, ["metadata"]);
  if (fromMetadata != null) {
    setValueByPath(toObject, ["metadata"], fromMetadata);
  }
  const fromDone = getValueByPath(fromObject, ["done"]);
  if (fromDone != null) {
    setValueByPath(toObject, ["done"], fromDone);
  }
  const fromError = getValueByPath(fromObject, ["error"]);
  if (fromError != null) {
    setValueByPath(toObject, ["error"], fromError);
  }
  const fromResponse = getValueByPath(fromObject, [
    "response",
    "generateVideoResponse"
  ]);
  if (fromResponse != null) {
    setValueByPath(toObject, ["response"], generateVideosResponseFromMldev$1(fromResponse));
  }
  return toObject;
}
function generateVideosOperationFromVertex$1(fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromMetadata = getValueByPath(fromObject, ["metadata"]);
  if (fromMetadata != null) {
    setValueByPath(toObject, ["metadata"], fromMetadata);
  }
  const fromDone = getValueByPath(fromObject, ["done"]);
  if (fromDone != null) {
    setValueByPath(toObject, ["done"], fromDone);
  }
  const fromError = getValueByPath(fromObject, ["error"]);
  if (fromError != null) {
    setValueByPath(toObject, ["error"], fromError);
  }
  const fromResponse = getValueByPath(fromObject, ["response"]);
  if (fromResponse != null) {
    setValueByPath(toObject, ["response"], generateVideosResponseFromVertex$1(fromResponse));
  }
  return toObject;
}
function generateVideosResponseFromMldev$1(fromObject) {
  const toObject = {};
  const fromGeneratedVideos = getValueByPath(fromObject, [
    "generatedSamples"
  ]);
  if (fromGeneratedVideos != null) {
    let transformedList = fromGeneratedVideos;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return generatedVideoFromMldev$1(item);
      });
    }
    setValueByPath(toObject, ["generatedVideos"], transformedList);
  }
  const fromRaiMediaFilteredCount = getValueByPath(fromObject, [
    "raiMediaFilteredCount"
  ]);
  if (fromRaiMediaFilteredCount != null) {
    setValueByPath(toObject, ["raiMediaFilteredCount"], fromRaiMediaFilteredCount);
  }
  const fromRaiMediaFilteredReasons = getValueByPath(fromObject, [
    "raiMediaFilteredReasons"
  ]);
  if (fromRaiMediaFilteredReasons != null) {
    setValueByPath(toObject, ["raiMediaFilteredReasons"], fromRaiMediaFilteredReasons);
  }
  return toObject;
}
function generateVideosResponseFromVertex$1(fromObject) {
  const toObject = {};
  const fromGeneratedVideos = getValueByPath(fromObject, ["videos"]);
  if (fromGeneratedVideos != null) {
    let transformedList = fromGeneratedVideos;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return generatedVideoFromVertex$1(item);
      });
    }
    setValueByPath(toObject, ["generatedVideos"], transformedList);
  }
  const fromRaiMediaFilteredCount = getValueByPath(fromObject, [
    "raiMediaFilteredCount"
  ]);
  if (fromRaiMediaFilteredCount != null) {
    setValueByPath(toObject, ["raiMediaFilteredCount"], fromRaiMediaFilteredCount);
  }
  const fromRaiMediaFilteredReasons = getValueByPath(fromObject, [
    "raiMediaFilteredReasons"
  ]);
  if (fromRaiMediaFilteredReasons != null) {
    setValueByPath(toObject, ["raiMediaFilteredReasons"], fromRaiMediaFilteredReasons);
  }
  return toObject;
}
function generatedVideoFromMldev$1(fromObject) {
  const toObject = {};
  const fromVideo = getValueByPath(fromObject, ["video"]);
  if (fromVideo != null) {
    setValueByPath(toObject, ["video"], videoFromMldev$1(fromVideo));
  }
  return toObject;
}
function generatedVideoFromVertex$1(fromObject) {
  const toObject = {};
  const fromVideo = getValueByPath(fromObject, ["_self"]);
  if (fromVideo != null) {
    setValueByPath(toObject, ["video"], videoFromVertex$1(fromVideo));
  }
  return toObject;
}
function getOperationParametersToMldev(fromObject) {
  const toObject = {};
  const fromOperationName = getValueByPath(fromObject, [
    "operationName"
  ]);
  if (fromOperationName != null) {
    setValueByPath(toObject, ["_url", "operationName"], fromOperationName);
  }
  return toObject;
}
function getOperationParametersToVertex(fromObject) {
  const toObject = {};
  const fromOperationName = getValueByPath(fromObject, [
    "operationName"
  ]);
  if (fromOperationName != null) {
    setValueByPath(toObject, ["_url", "operationName"], fromOperationName);
  }
  return toObject;
}
function importFileOperationFromMldev$1(fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromMetadata = getValueByPath(fromObject, ["metadata"]);
  if (fromMetadata != null) {
    setValueByPath(toObject, ["metadata"], fromMetadata);
  }
  const fromDone = getValueByPath(fromObject, ["done"]);
  if (fromDone != null) {
    setValueByPath(toObject, ["done"], fromDone);
  }
  const fromError = getValueByPath(fromObject, ["error"]);
  if (fromError != null) {
    setValueByPath(toObject, ["error"], fromError);
  }
  const fromResponse = getValueByPath(fromObject, ["response"]);
  if (fromResponse != null) {
    setValueByPath(toObject, ["response"], importFileResponseFromMldev$1(fromResponse));
  }
  return toObject;
}
function importFileResponseFromMldev$1(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromParent = getValueByPath(fromObject, ["parent"]);
  if (fromParent != null) {
    setValueByPath(toObject, ["parent"], fromParent);
  }
  const fromDocumentName = getValueByPath(fromObject, ["documentName"]);
  if (fromDocumentName != null) {
    setValueByPath(toObject, ["documentName"], fromDocumentName);
  }
  return toObject;
}
function uploadToFileSearchStoreOperationFromMldev(fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromMetadata = getValueByPath(fromObject, ["metadata"]);
  if (fromMetadata != null) {
    setValueByPath(toObject, ["metadata"], fromMetadata);
  }
  const fromDone = getValueByPath(fromObject, ["done"]);
  if (fromDone != null) {
    setValueByPath(toObject, ["done"], fromDone);
  }
  const fromError = getValueByPath(fromObject, ["error"]);
  if (fromError != null) {
    setValueByPath(toObject, ["error"], fromError);
  }
  const fromResponse = getValueByPath(fromObject, ["response"]);
  if (fromResponse != null) {
    setValueByPath(toObject, ["response"], uploadToFileSearchStoreResponseFromMldev(fromResponse));
  }
  return toObject;
}
function uploadToFileSearchStoreResponseFromMldev(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromParent = getValueByPath(fromObject, ["parent"]);
  if (fromParent != null) {
    setValueByPath(toObject, ["parent"], fromParent);
  }
  const fromDocumentName = getValueByPath(fromObject, ["documentName"]);
  if (fromDocumentName != null) {
    setValueByPath(toObject, ["documentName"], fromDocumentName);
  }
  return toObject;
}
function videoFromMldev$1(fromObject) {
  const toObject = {};
  const fromUri = getValueByPath(fromObject, ["uri"]);
  if (fromUri != null) {
    setValueByPath(toObject, ["uri"], fromUri);
  }
  const fromVideoBytes = getValueByPath(fromObject, ["encodedVideo"]);
  if (fromVideoBytes != null) {
    setValueByPath(toObject, ["videoBytes"], tBytes$1(fromVideoBytes));
  }
  const fromMimeType = getValueByPath(fromObject, ["encoding"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function videoFromVertex$1(fromObject) {
  const toObject = {};
  const fromUri = getValueByPath(fromObject, ["gcsUri"]);
  if (fromUri != null) {
    setValueByPath(toObject, ["uri"], fromUri);
  }
  const fromVideoBytes = getValueByPath(fromObject, [
    "bytesBase64Encoded"
  ]);
  if (fromVideoBytes != null) {
    setValueByPath(toObject, ["videoBytes"], tBytes$1(fromVideoBytes));
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
var Outcome;
(function(Outcome2) {
  Outcome2["OUTCOME_UNSPECIFIED"] = "OUTCOME_UNSPECIFIED";
  Outcome2["OUTCOME_OK"] = "OUTCOME_OK";
  Outcome2["OUTCOME_FAILED"] = "OUTCOME_FAILED";
  Outcome2["OUTCOME_DEADLINE_EXCEEDED"] = "OUTCOME_DEADLINE_EXCEEDED";
})(Outcome || (Outcome = {}));
var Language;
(function(Language2) {
  Language2["LANGUAGE_UNSPECIFIED"] = "LANGUAGE_UNSPECIFIED";
  Language2["PYTHON"] = "PYTHON";
})(Language || (Language = {}));
var FunctionResponseScheduling;
(function(FunctionResponseScheduling2) {
  FunctionResponseScheduling2["SCHEDULING_UNSPECIFIED"] = "SCHEDULING_UNSPECIFIED";
  FunctionResponseScheduling2["SILENT"] = "SILENT";
  FunctionResponseScheduling2["WHEN_IDLE"] = "WHEN_IDLE";
  FunctionResponseScheduling2["INTERRUPT"] = "INTERRUPT";
})(FunctionResponseScheduling || (FunctionResponseScheduling = {}));
var Type2;
(function(Type4) {
  Type4["TYPE_UNSPECIFIED"] = "TYPE_UNSPECIFIED";
  Type4["STRING"] = "STRING";
  Type4["NUMBER"] = "NUMBER";
  Type4["INTEGER"] = "INTEGER";
  Type4["BOOLEAN"] = "BOOLEAN";
  Type4["ARRAY"] = "ARRAY";
  Type4["OBJECT"] = "OBJECT";
  Type4["NULL"] = "NULL";
})(Type2 || (Type2 = {}));
var PhishBlockThreshold;
(function(PhishBlockThreshold2) {
  PhishBlockThreshold2["PHISH_BLOCK_THRESHOLD_UNSPECIFIED"] = "PHISH_BLOCK_THRESHOLD_UNSPECIFIED";
  PhishBlockThreshold2["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE";
  PhishBlockThreshold2["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE";
  PhishBlockThreshold2["BLOCK_HIGH_AND_ABOVE"] = "BLOCK_HIGH_AND_ABOVE";
  PhishBlockThreshold2["BLOCK_HIGHER_AND_ABOVE"] = "BLOCK_HIGHER_AND_ABOVE";
  PhishBlockThreshold2["BLOCK_VERY_HIGH_AND_ABOVE"] = "BLOCK_VERY_HIGH_AND_ABOVE";
  PhishBlockThreshold2["BLOCK_ONLY_EXTREMELY_HIGH"] = "BLOCK_ONLY_EXTREMELY_HIGH";
})(PhishBlockThreshold || (PhishBlockThreshold = {}));
var AuthType;
(function(AuthType2) {
  AuthType2["AUTH_TYPE_UNSPECIFIED"] = "AUTH_TYPE_UNSPECIFIED";
  AuthType2["NO_AUTH"] = "NO_AUTH";
  AuthType2["API_KEY_AUTH"] = "API_KEY_AUTH";
  AuthType2["HTTP_BASIC_AUTH"] = "HTTP_BASIC_AUTH";
  AuthType2["GOOGLE_SERVICE_ACCOUNT_AUTH"] = "GOOGLE_SERVICE_ACCOUNT_AUTH";
  AuthType2["OAUTH"] = "OAUTH";
  AuthType2["OIDC_AUTH"] = "OIDC_AUTH";
})(AuthType || (AuthType = {}));
var HttpElementLocation;
(function(HttpElementLocation2) {
  HttpElementLocation2["HTTP_IN_UNSPECIFIED"] = "HTTP_IN_UNSPECIFIED";
  HttpElementLocation2["HTTP_IN_QUERY"] = "HTTP_IN_QUERY";
  HttpElementLocation2["HTTP_IN_HEADER"] = "HTTP_IN_HEADER";
  HttpElementLocation2["HTTP_IN_PATH"] = "HTTP_IN_PATH";
  HttpElementLocation2["HTTP_IN_BODY"] = "HTTP_IN_BODY";
  HttpElementLocation2["HTTP_IN_COOKIE"] = "HTTP_IN_COOKIE";
})(HttpElementLocation || (HttpElementLocation = {}));
var ApiSpec;
(function(ApiSpec2) {
  ApiSpec2["API_SPEC_UNSPECIFIED"] = "API_SPEC_UNSPECIFIED";
  ApiSpec2["SIMPLE_SEARCH"] = "SIMPLE_SEARCH";
  ApiSpec2["ELASTIC_SEARCH"] = "ELASTIC_SEARCH";
})(ApiSpec || (ApiSpec = {}));
var Behavior;
(function(Behavior2) {
  Behavior2["UNSPECIFIED"] = "UNSPECIFIED";
  Behavior2["BLOCKING"] = "BLOCKING";
  Behavior2["NON_BLOCKING"] = "NON_BLOCKING";
})(Behavior || (Behavior = {}));
var DynamicRetrievalConfigMode;
(function(DynamicRetrievalConfigMode2) {
  DynamicRetrievalConfigMode2["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED";
  DynamicRetrievalConfigMode2["MODE_DYNAMIC"] = "MODE_DYNAMIC";
})(DynamicRetrievalConfigMode || (DynamicRetrievalConfigMode = {}));
var FunctionCallingConfigMode;
(function(FunctionCallingConfigMode2) {
  FunctionCallingConfigMode2["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED";
  FunctionCallingConfigMode2["AUTO"] = "AUTO";
  FunctionCallingConfigMode2["ANY"] = "ANY";
  FunctionCallingConfigMode2["NONE"] = "NONE";
  FunctionCallingConfigMode2["VALIDATED"] = "VALIDATED";
})(FunctionCallingConfigMode || (FunctionCallingConfigMode = {}));
var ThinkingLevel;
(function(ThinkingLevel2) {
  ThinkingLevel2["THINKING_LEVEL_UNSPECIFIED"] = "THINKING_LEVEL_UNSPECIFIED";
  ThinkingLevel2["LOW"] = "LOW";
  ThinkingLevel2["MEDIUM"] = "MEDIUM";
  ThinkingLevel2["HIGH"] = "HIGH";
  ThinkingLevel2["MINIMAL"] = "MINIMAL";
})(ThinkingLevel || (ThinkingLevel = {}));
var PersonGeneration;
(function(PersonGeneration2) {
  PersonGeneration2["DONT_ALLOW"] = "DONT_ALLOW";
  PersonGeneration2["ALLOW_ADULT"] = "ALLOW_ADULT";
  PersonGeneration2["ALLOW_ALL"] = "ALLOW_ALL";
})(PersonGeneration || (PersonGeneration = {}));
var HarmCategory;
(function(HarmCategory2) {
  HarmCategory2["HARM_CATEGORY_UNSPECIFIED"] = "HARM_CATEGORY_UNSPECIFIED";
  HarmCategory2["HARM_CATEGORY_HARASSMENT"] = "HARM_CATEGORY_HARASSMENT";
  HarmCategory2["HARM_CATEGORY_HATE_SPEECH"] = "HARM_CATEGORY_HATE_SPEECH";
  HarmCategory2["HARM_CATEGORY_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_SEXUALLY_EXPLICIT";
  HarmCategory2["HARM_CATEGORY_DANGEROUS_CONTENT"] = "HARM_CATEGORY_DANGEROUS_CONTENT";
  HarmCategory2["HARM_CATEGORY_CIVIC_INTEGRITY"] = "HARM_CATEGORY_CIVIC_INTEGRITY";
  HarmCategory2["HARM_CATEGORY_IMAGE_HATE"] = "HARM_CATEGORY_IMAGE_HATE";
  HarmCategory2["HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT"] = "HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT";
  HarmCategory2["HARM_CATEGORY_IMAGE_HARASSMENT"] = "HARM_CATEGORY_IMAGE_HARASSMENT";
  HarmCategory2["HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT";
  HarmCategory2["HARM_CATEGORY_JAILBREAK"] = "HARM_CATEGORY_JAILBREAK";
})(HarmCategory || (HarmCategory = {}));
var HarmBlockMethod;
(function(HarmBlockMethod2) {
  HarmBlockMethod2["HARM_BLOCK_METHOD_UNSPECIFIED"] = "HARM_BLOCK_METHOD_UNSPECIFIED";
  HarmBlockMethod2["SEVERITY"] = "SEVERITY";
  HarmBlockMethod2["PROBABILITY"] = "PROBABILITY";
})(HarmBlockMethod || (HarmBlockMethod = {}));
var HarmBlockThreshold;
(function(HarmBlockThreshold2) {
  HarmBlockThreshold2["HARM_BLOCK_THRESHOLD_UNSPECIFIED"] = "HARM_BLOCK_THRESHOLD_UNSPECIFIED";
  HarmBlockThreshold2["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE";
  HarmBlockThreshold2["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE";
  HarmBlockThreshold2["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH";
  HarmBlockThreshold2["BLOCK_NONE"] = "BLOCK_NONE";
  HarmBlockThreshold2["OFF"] = "OFF";
})(HarmBlockThreshold || (HarmBlockThreshold = {}));
var FinishReason;
(function(FinishReason2) {
  FinishReason2["FINISH_REASON_UNSPECIFIED"] = "FINISH_REASON_UNSPECIFIED";
  FinishReason2["STOP"] = "STOP";
  FinishReason2["MAX_TOKENS"] = "MAX_TOKENS";
  FinishReason2["SAFETY"] = "SAFETY";
  FinishReason2["RECITATION"] = "RECITATION";
  FinishReason2["LANGUAGE"] = "LANGUAGE";
  FinishReason2["OTHER"] = "OTHER";
  FinishReason2["BLOCKLIST"] = "BLOCKLIST";
  FinishReason2["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT";
  FinishReason2["SPII"] = "SPII";
  FinishReason2["MALFORMED_FUNCTION_CALL"] = "MALFORMED_FUNCTION_CALL";
  FinishReason2["IMAGE_SAFETY"] = "IMAGE_SAFETY";
  FinishReason2["UNEXPECTED_TOOL_CALL"] = "UNEXPECTED_TOOL_CALL";
  FinishReason2["IMAGE_PROHIBITED_CONTENT"] = "IMAGE_PROHIBITED_CONTENT";
  FinishReason2["NO_IMAGE"] = "NO_IMAGE";
  FinishReason2["IMAGE_RECITATION"] = "IMAGE_RECITATION";
  FinishReason2["IMAGE_OTHER"] = "IMAGE_OTHER";
})(FinishReason || (FinishReason = {}));
var HarmProbability;
(function(HarmProbability2) {
  HarmProbability2["HARM_PROBABILITY_UNSPECIFIED"] = "HARM_PROBABILITY_UNSPECIFIED";
  HarmProbability2["NEGLIGIBLE"] = "NEGLIGIBLE";
  HarmProbability2["LOW"] = "LOW";
  HarmProbability2["MEDIUM"] = "MEDIUM";
  HarmProbability2["HIGH"] = "HIGH";
})(HarmProbability || (HarmProbability = {}));
var HarmSeverity;
(function(HarmSeverity2) {
  HarmSeverity2["HARM_SEVERITY_UNSPECIFIED"] = "HARM_SEVERITY_UNSPECIFIED";
  HarmSeverity2["HARM_SEVERITY_NEGLIGIBLE"] = "HARM_SEVERITY_NEGLIGIBLE";
  HarmSeverity2["HARM_SEVERITY_LOW"] = "HARM_SEVERITY_LOW";
  HarmSeverity2["HARM_SEVERITY_MEDIUM"] = "HARM_SEVERITY_MEDIUM";
  HarmSeverity2["HARM_SEVERITY_HIGH"] = "HARM_SEVERITY_HIGH";
})(HarmSeverity || (HarmSeverity = {}));
var UrlRetrievalStatus;
(function(UrlRetrievalStatus2) {
  UrlRetrievalStatus2["URL_RETRIEVAL_STATUS_UNSPECIFIED"] = "URL_RETRIEVAL_STATUS_UNSPECIFIED";
  UrlRetrievalStatus2["URL_RETRIEVAL_STATUS_SUCCESS"] = "URL_RETRIEVAL_STATUS_SUCCESS";
  UrlRetrievalStatus2["URL_RETRIEVAL_STATUS_ERROR"] = "URL_RETRIEVAL_STATUS_ERROR";
  UrlRetrievalStatus2["URL_RETRIEVAL_STATUS_PAYWALL"] = "URL_RETRIEVAL_STATUS_PAYWALL";
  UrlRetrievalStatus2["URL_RETRIEVAL_STATUS_UNSAFE"] = "URL_RETRIEVAL_STATUS_UNSAFE";
})(UrlRetrievalStatus || (UrlRetrievalStatus = {}));
var BlockedReason;
(function(BlockedReason2) {
  BlockedReason2["BLOCKED_REASON_UNSPECIFIED"] = "BLOCKED_REASON_UNSPECIFIED";
  BlockedReason2["SAFETY"] = "SAFETY";
  BlockedReason2["OTHER"] = "OTHER";
  BlockedReason2["BLOCKLIST"] = "BLOCKLIST";
  BlockedReason2["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT";
  BlockedReason2["IMAGE_SAFETY"] = "IMAGE_SAFETY";
  BlockedReason2["MODEL_ARMOR"] = "MODEL_ARMOR";
  BlockedReason2["JAILBREAK"] = "JAILBREAK";
})(BlockedReason || (BlockedReason = {}));
var TrafficType;
(function(TrafficType2) {
  TrafficType2["TRAFFIC_TYPE_UNSPECIFIED"] = "TRAFFIC_TYPE_UNSPECIFIED";
  TrafficType2["ON_DEMAND"] = "ON_DEMAND";
  TrafficType2["ON_DEMAND_PRIORITY"] = "ON_DEMAND_PRIORITY";
  TrafficType2["ON_DEMAND_FLEX"] = "ON_DEMAND_FLEX";
  TrafficType2["PROVISIONED_THROUGHPUT"] = "PROVISIONED_THROUGHPUT";
})(TrafficType || (TrafficType = {}));
var Modality;
(function(Modality2) {
  Modality2["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED";
  Modality2["TEXT"] = "TEXT";
  Modality2["IMAGE"] = "IMAGE";
  Modality2["AUDIO"] = "AUDIO";
})(Modality || (Modality = {}));
var MediaResolution;
(function(MediaResolution2) {
  MediaResolution2["MEDIA_RESOLUTION_UNSPECIFIED"] = "MEDIA_RESOLUTION_UNSPECIFIED";
  MediaResolution2["MEDIA_RESOLUTION_LOW"] = "MEDIA_RESOLUTION_LOW";
  MediaResolution2["MEDIA_RESOLUTION_MEDIUM"] = "MEDIA_RESOLUTION_MEDIUM";
  MediaResolution2["MEDIA_RESOLUTION_HIGH"] = "MEDIA_RESOLUTION_HIGH";
})(MediaResolution || (MediaResolution = {}));
var TuningMode;
(function(TuningMode2) {
  TuningMode2["TUNING_MODE_UNSPECIFIED"] = "TUNING_MODE_UNSPECIFIED";
  TuningMode2["TUNING_MODE_FULL"] = "TUNING_MODE_FULL";
  TuningMode2["TUNING_MODE_PEFT_ADAPTER"] = "TUNING_MODE_PEFT_ADAPTER";
})(TuningMode || (TuningMode = {}));
var AdapterSize;
(function(AdapterSize2) {
  AdapterSize2["ADAPTER_SIZE_UNSPECIFIED"] = "ADAPTER_SIZE_UNSPECIFIED";
  AdapterSize2["ADAPTER_SIZE_ONE"] = "ADAPTER_SIZE_ONE";
  AdapterSize2["ADAPTER_SIZE_TWO"] = "ADAPTER_SIZE_TWO";
  AdapterSize2["ADAPTER_SIZE_FOUR"] = "ADAPTER_SIZE_FOUR";
  AdapterSize2["ADAPTER_SIZE_EIGHT"] = "ADAPTER_SIZE_EIGHT";
  AdapterSize2["ADAPTER_SIZE_SIXTEEN"] = "ADAPTER_SIZE_SIXTEEN";
  AdapterSize2["ADAPTER_SIZE_THIRTY_TWO"] = "ADAPTER_SIZE_THIRTY_TWO";
})(AdapterSize || (AdapterSize = {}));
var JobState;
(function(JobState2) {
  JobState2["JOB_STATE_UNSPECIFIED"] = "JOB_STATE_UNSPECIFIED";
  JobState2["JOB_STATE_QUEUED"] = "JOB_STATE_QUEUED";
  JobState2["JOB_STATE_PENDING"] = "JOB_STATE_PENDING";
  JobState2["JOB_STATE_RUNNING"] = "JOB_STATE_RUNNING";
  JobState2["JOB_STATE_SUCCEEDED"] = "JOB_STATE_SUCCEEDED";
  JobState2["JOB_STATE_FAILED"] = "JOB_STATE_FAILED";
  JobState2["JOB_STATE_CANCELLING"] = "JOB_STATE_CANCELLING";
  JobState2["JOB_STATE_CANCELLED"] = "JOB_STATE_CANCELLED";
  JobState2["JOB_STATE_PAUSED"] = "JOB_STATE_PAUSED";
  JobState2["JOB_STATE_EXPIRED"] = "JOB_STATE_EXPIRED";
  JobState2["JOB_STATE_UPDATING"] = "JOB_STATE_UPDATING";
  JobState2["JOB_STATE_PARTIALLY_SUCCEEDED"] = "JOB_STATE_PARTIALLY_SUCCEEDED";
})(JobState || (JobState = {}));
var TuningJobState;
(function(TuningJobState2) {
  TuningJobState2["TUNING_JOB_STATE_UNSPECIFIED"] = "TUNING_JOB_STATE_UNSPECIFIED";
  TuningJobState2["TUNING_JOB_STATE_WAITING_FOR_QUOTA"] = "TUNING_JOB_STATE_WAITING_FOR_QUOTA";
  TuningJobState2["TUNING_JOB_STATE_PROCESSING_DATASET"] = "TUNING_JOB_STATE_PROCESSING_DATASET";
  TuningJobState2["TUNING_JOB_STATE_WAITING_FOR_CAPACITY"] = "TUNING_JOB_STATE_WAITING_FOR_CAPACITY";
  TuningJobState2["TUNING_JOB_STATE_TUNING"] = "TUNING_JOB_STATE_TUNING";
  TuningJobState2["TUNING_JOB_STATE_POST_PROCESSING"] = "TUNING_JOB_STATE_POST_PROCESSING";
})(TuningJobState || (TuningJobState = {}));
var AggregationMetric;
(function(AggregationMetric2) {
  AggregationMetric2["AGGREGATION_METRIC_UNSPECIFIED"] = "AGGREGATION_METRIC_UNSPECIFIED";
  AggregationMetric2["AVERAGE"] = "AVERAGE";
  AggregationMetric2["MODE"] = "MODE";
  AggregationMetric2["STANDARD_DEVIATION"] = "STANDARD_DEVIATION";
  AggregationMetric2["VARIANCE"] = "VARIANCE";
  AggregationMetric2["MINIMUM"] = "MINIMUM";
  AggregationMetric2["MAXIMUM"] = "MAXIMUM";
  AggregationMetric2["MEDIAN"] = "MEDIAN";
  AggregationMetric2["PERCENTILE_P90"] = "PERCENTILE_P90";
  AggregationMetric2["PERCENTILE_P95"] = "PERCENTILE_P95";
  AggregationMetric2["PERCENTILE_P99"] = "PERCENTILE_P99";
})(AggregationMetric || (AggregationMetric = {}));
var PairwiseChoice;
(function(PairwiseChoice2) {
  PairwiseChoice2["PAIRWISE_CHOICE_UNSPECIFIED"] = "PAIRWISE_CHOICE_UNSPECIFIED";
  PairwiseChoice2["BASELINE"] = "BASELINE";
  PairwiseChoice2["CANDIDATE"] = "CANDIDATE";
  PairwiseChoice2["TIE"] = "TIE";
})(PairwiseChoice || (PairwiseChoice = {}));
var TuningTask;
(function(TuningTask2) {
  TuningTask2["TUNING_TASK_UNSPECIFIED"] = "TUNING_TASK_UNSPECIFIED";
  TuningTask2["TUNING_TASK_I2V"] = "TUNING_TASK_I2V";
  TuningTask2["TUNING_TASK_T2V"] = "TUNING_TASK_T2V";
  TuningTask2["TUNING_TASK_R2V"] = "TUNING_TASK_R2V";
})(TuningTask || (TuningTask = {}));
var PartMediaResolutionLevel;
(function(PartMediaResolutionLevel2) {
  PartMediaResolutionLevel2["MEDIA_RESOLUTION_UNSPECIFIED"] = "MEDIA_RESOLUTION_UNSPECIFIED";
  PartMediaResolutionLevel2["MEDIA_RESOLUTION_LOW"] = "MEDIA_RESOLUTION_LOW";
  PartMediaResolutionLevel2["MEDIA_RESOLUTION_MEDIUM"] = "MEDIA_RESOLUTION_MEDIUM";
  PartMediaResolutionLevel2["MEDIA_RESOLUTION_HIGH"] = "MEDIA_RESOLUTION_HIGH";
  PartMediaResolutionLevel2["MEDIA_RESOLUTION_ULTRA_HIGH"] = "MEDIA_RESOLUTION_ULTRA_HIGH";
})(PartMediaResolutionLevel || (PartMediaResolutionLevel = {}));
var ResourceScope;
(function(ResourceScope2) {
  ResourceScope2["COLLECTION"] = "COLLECTION";
})(ResourceScope || (ResourceScope = {}));
var FeatureSelectionPreference;
(function(FeatureSelectionPreference2) {
  FeatureSelectionPreference2["FEATURE_SELECTION_PREFERENCE_UNSPECIFIED"] = "FEATURE_SELECTION_PREFERENCE_UNSPECIFIED";
  FeatureSelectionPreference2["PRIORITIZE_QUALITY"] = "PRIORITIZE_QUALITY";
  FeatureSelectionPreference2["BALANCED"] = "BALANCED";
  FeatureSelectionPreference2["PRIORITIZE_COST"] = "PRIORITIZE_COST";
})(FeatureSelectionPreference || (FeatureSelectionPreference = {}));
var Environment;
(function(Environment2) {
  Environment2["ENVIRONMENT_UNSPECIFIED"] = "ENVIRONMENT_UNSPECIFIED";
  Environment2["ENVIRONMENT_BROWSER"] = "ENVIRONMENT_BROWSER";
})(Environment || (Environment = {}));
var ProminentPeople;
(function(ProminentPeople2) {
  ProminentPeople2["PROMINENT_PEOPLE_UNSPECIFIED"] = "PROMINENT_PEOPLE_UNSPECIFIED";
  ProminentPeople2["ALLOW_PROMINENT_PEOPLE"] = "ALLOW_PROMINENT_PEOPLE";
  ProminentPeople2["BLOCK_PROMINENT_PEOPLE"] = "BLOCK_PROMINENT_PEOPLE";
})(ProminentPeople || (ProminentPeople = {}));
var EmbeddingApiType;
(function(EmbeddingApiType2) {
  EmbeddingApiType2["PREDICT"] = "PREDICT";
  EmbeddingApiType2["EMBED_CONTENT"] = "EMBED_CONTENT";
})(EmbeddingApiType || (EmbeddingApiType = {}));
var SafetyFilterLevel;
(function(SafetyFilterLevel2) {
  SafetyFilterLevel2["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE";
  SafetyFilterLevel2["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE";
  SafetyFilterLevel2["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH";
  SafetyFilterLevel2["BLOCK_NONE"] = "BLOCK_NONE";
})(SafetyFilterLevel || (SafetyFilterLevel = {}));
var ImagePromptLanguage;
(function(ImagePromptLanguage2) {
  ImagePromptLanguage2["auto"] = "auto";
  ImagePromptLanguage2["en"] = "en";
  ImagePromptLanguage2["ja"] = "ja";
  ImagePromptLanguage2["ko"] = "ko";
  ImagePromptLanguage2["hi"] = "hi";
  ImagePromptLanguage2["zh"] = "zh";
  ImagePromptLanguage2["pt"] = "pt";
  ImagePromptLanguage2["es"] = "es";
})(ImagePromptLanguage || (ImagePromptLanguage = {}));
var MaskReferenceMode;
(function(MaskReferenceMode2) {
  MaskReferenceMode2["MASK_MODE_DEFAULT"] = "MASK_MODE_DEFAULT";
  MaskReferenceMode2["MASK_MODE_USER_PROVIDED"] = "MASK_MODE_USER_PROVIDED";
  MaskReferenceMode2["MASK_MODE_BACKGROUND"] = "MASK_MODE_BACKGROUND";
  MaskReferenceMode2["MASK_MODE_FOREGROUND"] = "MASK_MODE_FOREGROUND";
  MaskReferenceMode2["MASK_MODE_SEMANTIC"] = "MASK_MODE_SEMANTIC";
})(MaskReferenceMode || (MaskReferenceMode = {}));
var ControlReferenceType;
(function(ControlReferenceType2) {
  ControlReferenceType2["CONTROL_TYPE_DEFAULT"] = "CONTROL_TYPE_DEFAULT";
  ControlReferenceType2["CONTROL_TYPE_CANNY"] = "CONTROL_TYPE_CANNY";
  ControlReferenceType2["CONTROL_TYPE_SCRIBBLE"] = "CONTROL_TYPE_SCRIBBLE";
  ControlReferenceType2["CONTROL_TYPE_FACE_MESH"] = "CONTROL_TYPE_FACE_MESH";
})(ControlReferenceType || (ControlReferenceType = {}));
var SubjectReferenceType;
(function(SubjectReferenceType2) {
  SubjectReferenceType2["SUBJECT_TYPE_DEFAULT"] = "SUBJECT_TYPE_DEFAULT";
  SubjectReferenceType2["SUBJECT_TYPE_PERSON"] = "SUBJECT_TYPE_PERSON";
  SubjectReferenceType2["SUBJECT_TYPE_ANIMAL"] = "SUBJECT_TYPE_ANIMAL";
  SubjectReferenceType2["SUBJECT_TYPE_PRODUCT"] = "SUBJECT_TYPE_PRODUCT";
})(SubjectReferenceType || (SubjectReferenceType = {}));
var EditMode;
(function(EditMode2) {
  EditMode2["EDIT_MODE_DEFAULT"] = "EDIT_MODE_DEFAULT";
  EditMode2["EDIT_MODE_INPAINT_REMOVAL"] = "EDIT_MODE_INPAINT_REMOVAL";
  EditMode2["EDIT_MODE_INPAINT_INSERTION"] = "EDIT_MODE_INPAINT_INSERTION";
  EditMode2["EDIT_MODE_OUTPAINT"] = "EDIT_MODE_OUTPAINT";
  EditMode2["EDIT_MODE_CONTROLLED_EDITING"] = "EDIT_MODE_CONTROLLED_EDITING";
  EditMode2["EDIT_MODE_STYLE"] = "EDIT_MODE_STYLE";
  EditMode2["EDIT_MODE_BGSWAP"] = "EDIT_MODE_BGSWAP";
  EditMode2["EDIT_MODE_PRODUCT_IMAGE"] = "EDIT_MODE_PRODUCT_IMAGE";
})(EditMode || (EditMode = {}));
var SegmentMode;
(function(SegmentMode2) {
  SegmentMode2["FOREGROUND"] = "FOREGROUND";
  SegmentMode2["BACKGROUND"] = "BACKGROUND";
  SegmentMode2["PROMPT"] = "PROMPT";
  SegmentMode2["SEMANTIC"] = "SEMANTIC";
  SegmentMode2["INTERACTIVE"] = "INTERACTIVE";
})(SegmentMode || (SegmentMode = {}));
var VideoGenerationReferenceType;
(function(VideoGenerationReferenceType2) {
  VideoGenerationReferenceType2["ASSET"] = "ASSET";
  VideoGenerationReferenceType2["STYLE"] = "STYLE";
})(VideoGenerationReferenceType || (VideoGenerationReferenceType = {}));
var VideoGenerationMaskMode;
(function(VideoGenerationMaskMode2) {
  VideoGenerationMaskMode2["INSERT"] = "INSERT";
  VideoGenerationMaskMode2["REMOVE"] = "REMOVE";
  VideoGenerationMaskMode2["REMOVE_STATIC"] = "REMOVE_STATIC";
  VideoGenerationMaskMode2["OUTPAINT"] = "OUTPAINT";
})(VideoGenerationMaskMode || (VideoGenerationMaskMode = {}));
var VideoCompressionQuality;
(function(VideoCompressionQuality2) {
  VideoCompressionQuality2["OPTIMIZED"] = "OPTIMIZED";
  VideoCompressionQuality2["LOSSLESS"] = "LOSSLESS";
})(VideoCompressionQuality || (VideoCompressionQuality = {}));
var TuningMethod;
(function(TuningMethod2) {
  TuningMethod2["SUPERVISED_FINE_TUNING"] = "SUPERVISED_FINE_TUNING";
  TuningMethod2["PREFERENCE_TUNING"] = "PREFERENCE_TUNING";
  TuningMethod2["DISTILLATION"] = "DISTILLATION";
})(TuningMethod || (TuningMethod = {}));
var DocumentState;
(function(DocumentState2) {
  DocumentState2["STATE_UNSPECIFIED"] = "STATE_UNSPECIFIED";
  DocumentState2["STATE_PENDING"] = "STATE_PENDING";
  DocumentState2["STATE_ACTIVE"] = "STATE_ACTIVE";
  DocumentState2["STATE_FAILED"] = "STATE_FAILED";
})(DocumentState || (DocumentState = {}));
var FileState;
(function(FileState2) {
  FileState2["STATE_UNSPECIFIED"] = "STATE_UNSPECIFIED";
  FileState2["PROCESSING"] = "PROCESSING";
  FileState2["ACTIVE"] = "ACTIVE";
  FileState2["FAILED"] = "FAILED";
})(FileState || (FileState = {}));
var FileSource;
(function(FileSource2) {
  FileSource2["SOURCE_UNSPECIFIED"] = "SOURCE_UNSPECIFIED";
  FileSource2["UPLOADED"] = "UPLOADED";
  FileSource2["GENERATED"] = "GENERATED";
  FileSource2["REGISTERED"] = "REGISTERED";
})(FileSource || (FileSource = {}));
var TurnCompleteReason;
(function(TurnCompleteReason2) {
  TurnCompleteReason2["TURN_COMPLETE_REASON_UNSPECIFIED"] = "TURN_COMPLETE_REASON_UNSPECIFIED";
  TurnCompleteReason2["MALFORMED_FUNCTION_CALL"] = "MALFORMED_FUNCTION_CALL";
  TurnCompleteReason2["RESPONSE_REJECTED"] = "RESPONSE_REJECTED";
  TurnCompleteReason2["NEED_MORE_INPUT"] = "NEED_MORE_INPUT";
})(TurnCompleteReason || (TurnCompleteReason = {}));
var MediaModality;
(function(MediaModality2) {
  MediaModality2["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED";
  MediaModality2["TEXT"] = "TEXT";
  MediaModality2["IMAGE"] = "IMAGE";
  MediaModality2["VIDEO"] = "VIDEO";
  MediaModality2["AUDIO"] = "AUDIO";
  MediaModality2["DOCUMENT"] = "DOCUMENT";
})(MediaModality || (MediaModality = {}));
var VadSignalType;
(function(VadSignalType2) {
  VadSignalType2["VAD_SIGNAL_TYPE_UNSPECIFIED"] = "VAD_SIGNAL_TYPE_UNSPECIFIED";
  VadSignalType2["VAD_SIGNAL_TYPE_SOS"] = "VAD_SIGNAL_TYPE_SOS";
  VadSignalType2["VAD_SIGNAL_TYPE_EOS"] = "VAD_SIGNAL_TYPE_EOS";
})(VadSignalType || (VadSignalType = {}));
var VoiceActivityType;
(function(VoiceActivityType2) {
  VoiceActivityType2["TYPE_UNSPECIFIED"] = "TYPE_UNSPECIFIED";
  VoiceActivityType2["ACTIVITY_START"] = "ACTIVITY_START";
  VoiceActivityType2["ACTIVITY_END"] = "ACTIVITY_END";
})(VoiceActivityType || (VoiceActivityType = {}));
var StartSensitivity;
(function(StartSensitivity2) {
  StartSensitivity2["START_SENSITIVITY_UNSPECIFIED"] = "START_SENSITIVITY_UNSPECIFIED";
  StartSensitivity2["START_SENSITIVITY_HIGH"] = "START_SENSITIVITY_HIGH";
  StartSensitivity2["START_SENSITIVITY_LOW"] = "START_SENSITIVITY_LOW";
})(StartSensitivity || (StartSensitivity = {}));
var EndSensitivity;
(function(EndSensitivity2) {
  EndSensitivity2["END_SENSITIVITY_UNSPECIFIED"] = "END_SENSITIVITY_UNSPECIFIED";
  EndSensitivity2["END_SENSITIVITY_HIGH"] = "END_SENSITIVITY_HIGH";
  EndSensitivity2["END_SENSITIVITY_LOW"] = "END_SENSITIVITY_LOW";
})(EndSensitivity || (EndSensitivity = {}));
var ActivityHandling;
(function(ActivityHandling2) {
  ActivityHandling2["ACTIVITY_HANDLING_UNSPECIFIED"] = "ACTIVITY_HANDLING_UNSPECIFIED";
  ActivityHandling2["START_OF_ACTIVITY_INTERRUPTS"] = "START_OF_ACTIVITY_INTERRUPTS";
  ActivityHandling2["NO_INTERRUPTION"] = "NO_INTERRUPTION";
})(ActivityHandling || (ActivityHandling = {}));
var TurnCoverage;
(function(TurnCoverage2) {
  TurnCoverage2["TURN_COVERAGE_UNSPECIFIED"] = "TURN_COVERAGE_UNSPECIFIED";
  TurnCoverage2["TURN_INCLUDES_ONLY_ACTIVITY"] = "TURN_INCLUDES_ONLY_ACTIVITY";
  TurnCoverage2["TURN_INCLUDES_ALL_INPUT"] = "TURN_INCLUDES_ALL_INPUT";
})(TurnCoverage || (TurnCoverage = {}));
var Scale;
(function(Scale2) {
  Scale2["SCALE_UNSPECIFIED"] = "SCALE_UNSPECIFIED";
  Scale2["C_MAJOR_A_MINOR"] = "C_MAJOR_A_MINOR";
  Scale2["D_FLAT_MAJOR_B_FLAT_MINOR"] = "D_FLAT_MAJOR_B_FLAT_MINOR";
  Scale2["D_MAJOR_B_MINOR"] = "D_MAJOR_B_MINOR";
  Scale2["E_FLAT_MAJOR_C_MINOR"] = "E_FLAT_MAJOR_C_MINOR";
  Scale2["E_MAJOR_D_FLAT_MINOR"] = "E_MAJOR_D_FLAT_MINOR";
  Scale2["F_MAJOR_D_MINOR"] = "F_MAJOR_D_MINOR";
  Scale2["G_FLAT_MAJOR_E_FLAT_MINOR"] = "G_FLAT_MAJOR_E_FLAT_MINOR";
  Scale2["G_MAJOR_E_MINOR"] = "G_MAJOR_E_MINOR";
  Scale2["A_FLAT_MAJOR_F_MINOR"] = "A_FLAT_MAJOR_F_MINOR";
  Scale2["A_MAJOR_G_FLAT_MINOR"] = "A_MAJOR_G_FLAT_MINOR";
  Scale2["B_FLAT_MAJOR_G_MINOR"] = "B_FLAT_MAJOR_G_MINOR";
  Scale2["B_MAJOR_A_FLAT_MINOR"] = "B_MAJOR_A_FLAT_MINOR";
})(Scale || (Scale = {}));
var MusicGenerationMode;
(function(MusicGenerationMode2) {
  MusicGenerationMode2["MUSIC_GENERATION_MODE_UNSPECIFIED"] = "MUSIC_GENERATION_MODE_UNSPECIFIED";
  MusicGenerationMode2["QUALITY"] = "QUALITY";
  MusicGenerationMode2["DIVERSITY"] = "DIVERSITY";
  MusicGenerationMode2["VOCALIZATION"] = "VOCALIZATION";
})(MusicGenerationMode || (MusicGenerationMode = {}));
var LiveMusicPlaybackControl;
(function(LiveMusicPlaybackControl2) {
  LiveMusicPlaybackControl2["PLAYBACK_CONTROL_UNSPECIFIED"] = "PLAYBACK_CONTROL_UNSPECIFIED";
  LiveMusicPlaybackControl2["PLAY"] = "PLAY";
  LiveMusicPlaybackControl2["PAUSE"] = "PAUSE";
  LiveMusicPlaybackControl2["STOP"] = "STOP";
  LiveMusicPlaybackControl2["RESET_CONTEXT"] = "RESET_CONTEXT";
})(LiveMusicPlaybackControl || (LiveMusicPlaybackControl = {}));
var HttpResponse = class {
  constructor(response) {
    const headers = {};
    for (const pair of response.headers.entries()) {
      headers[pair[0]] = pair[1];
    }
    this.headers = headers;
    this.responseInternal = response;
  }
  json() {
    return this.responseInternal.json();
  }
};
var GenerateContentResponse = class {
  /**
   * Returns the concatenation of all text parts from the first candidate in the response.
   *
   * @remarks
   * If there are multiple candidates in the response, the text from the first
   * one will be returned.
   * If there are non-text parts in the response, the concatenation of all text
   * parts will be returned, and a warning will be logged.
   * If there are thought parts in the response, the concatenation of all text
   * parts excluding the thought parts will be returned.
   *
   * @example
   * ```ts
   * const response = await ai.models.generateContent({
   *   model: 'gemini-2.0-flash',
   *   contents:
   *     'Why is the sky blue?',
   * });
   *
   * console.debug(response.text);
   * ```
   */
  get text() {
    var _a7, _b, _c, _d, _e2, _f, _g, _h;
    if (((_d = (_c = (_b = (_a7 = this.candidates) === null || _a7 === void 0 ? void 0 : _a7[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) {
      return void 0;
    }
    if (this.candidates && this.candidates.length > 1) {
      console.warn("there are multiple candidates in the response, returning text from the first one.");
    }
    let text3 = "";
    let anyTextPartText = false;
    const nonTextParts = [];
    for (const part of (_h = (_g = (_f = (_e2 = this.candidates) === null || _e2 === void 0 ? void 0 : _e2[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) !== null && _h !== void 0 ? _h : []) {
      for (const [fieldName, fieldValue] of Object.entries(part)) {
        if (fieldName !== "text" && fieldName !== "thought" && fieldName !== "thoughtSignature" && (fieldValue !== null || fieldValue !== void 0)) {
          nonTextParts.push(fieldName);
        }
      }
      if (typeof part.text === "string") {
        if (typeof part.thought === "boolean" && part.thought) {
          continue;
        }
        anyTextPartText = true;
        text3 += part.text;
      }
    }
    if (nonTextParts.length > 0) {
      console.warn(`there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`);
    }
    return anyTextPartText ? text3 : void 0;
  }
  /**
   * Returns the concatenation of all inline data parts from the first candidate
   * in the response.
   *
   * @remarks
   * If there are multiple candidates in the response, the inline data from the
   * first one will be returned. If there are non-inline data parts in the
   * response, the concatenation of all inline data parts will be returned, and
   * a warning will be logged.
   */
  get data() {
    var _a7, _b, _c, _d, _e2, _f, _g, _h;
    if (((_d = (_c = (_b = (_a7 = this.candidates) === null || _a7 === void 0 ? void 0 : _a7[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) {
      return void 0;
    }
    if (this.candidates && this.candidates.length > 1) {
      console.warn("there are multiple candidates in the response, returning data from the first one.");
    }
    let data = "";
    const nonDataParts = [];
    for (const part of (_h = (_g = (_f = (_e2 = this.candidates) === null || _e2 === void 0 ? void 0 : _e2[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) !== null && _h !== void 0 ? _h : []) {
      for (const [fieldName, fieldValue] of Object.entries(part)) {
        if (fieldName !== "inlineData" && (fieldValue !== null || fieldValue !== void 0)) {
          nonDataParts.push(fieldName);
        }
      }
      if (part.inlineData && typeof part.inlineData.data === "string") {
        data += atob(part.inlineData.data);
      }
    }
    if (nonDataParts.length > 0) {
      console.warn(`there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`);
    }
    return data.length > 0 ? btoa(data) : void 0;
  }
  /**
   * Returns the function calls from the first candidate in the response.
   *
   * @remarks
   * If there are multiple candidates in the response, the function calls from
   * the first one will be returned.
   * If there are no function calls in the response, undefined will be returned.
   *
   * @example
   * ```ts
   * const controlLightFunctionDeclaration: FunctionDeclaration = {
   *   name: 'controlLight',
   *   parameters: {
   *   type: Type.OBJECT,
   *   description: 'Set the brightness and color temperature of a room light.',
   *   properties: {
   *     brightness: {
   *       type: Type.NUMBER,
   *       description:
   *         'Light level from 0 to 100. Zero is off and 100 is full brightness.',
   *     },
   *     colorTemperature: {
   *       type: Type.STRING,
   *       description:
   *         'Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.',
   *     },
   *   },
   *   required: ['brightness', 'colorTemperature'],
   *  };
   *  const response = await ai.models.generateContent({
   *     model: 'gemini-2.0-flash',
   *     contents: 'Dim the lights so the room feels cozy and warm.',
   *     config: {
   *       tools: [{functionDeclarations: [controlLightFunctionDeclaration]}],
   *       toolConfig: {
   *         functionCallingConfig: {
   *           mode: FunctionCallingConfigMode.ANY,
   *           allowedFunctionNames: ['controlLight'],
   *         },
   *       },
   *     },
   *   });
   *  console.debug(JSON.stringify(response.functionCalls));
   * ```
   */
  get functionCalls() {
    var _a7, _b, _c, _d, _e2, _f, _g, _h;
    if (((_d = (_c = (_b = (_a7 = this.candidates) === null || _a7 === void 0 ? void 0 : _a7[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) {
      return void 0;
    }
    if (this.candidates && this.candidates.length > 1) {
      console.warn("there are multiple candidates in the response, returning function calls from the first one.");
    }
    const functionCalls = (_h = (_g = (_f = (_e2 = this.candidates) === null || _e2 === void 0 ? void 0 : _e2[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) === null || _h === void 0 ? void 0 : _h.filter((part) => part.functionCall).map((part) => part.functionCall).filter((functionCall) => functionCall !== void 0);
    if ((functionCalls === null || functionCalls === void 0 ? void 0 : functionCalls.length) === 0) {
      return void 0;
    }
    return functionCalls;
  }
  /**
   * Returns the first executable code from the first candidate in the response.
   *
   * @remarks
   * If there are multiple candidates in the response, the executable code from
   * the first one will be returned.
   * If there are no executable code in the response, undefined will be
   * returned.
   *
   * @example
   * ```ts
   * const response = await ai.models.generateContent({
   *   model: 'gemini-2.0-flash',
   *   contents:
   *     'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.'
   *   config: {
   *     tools: [{codeExecution: {}}],
   *   },
   * });
   *
   * console.debug(response.executableCode);
   * ```
   */
  get executableCode() {
    var _a7, _b, _c, _d, _e2, _f, _g, _h, _j;
    if (((_d = (_c = (_b = (_a7 = this.candidates) === null || _a7 === void 0 ? void 0 : _a7[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) {
      return void 0;
    }
    if (this.candidates && this.candidates.length > 1) {
      console.warn("there are multiple candidates in the response, returning executable code from the first one.");
    }
    const executableCode = (_h = (_g = (_f = (_e2 = this.candidates) === null || _e2 === void 0 ? void 0 : _e2[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) === null || _h === void 0 ? void 0 : _h.filter((part) => part.executableCode).map((part) => part.executableCode).filter((executableCode2) => executableCode2 !== void 0);
    if ((executableCode === null || executableCode === void 0 ? void 0 : executableCode.length) === 0) {
      return void 0;
    }
    return (_j = executableCode === null || executableCode === void 0 ? void 0 : executableCode[0]) === null || _j === void 0 ? void 0 : _j.code;
  }
  /**
   * Returns the first code execution result from the first candidate in the response.
   *
   * @remarks
   * If there are multiple candidates in the response, the code execution result from
   * the first one will be returned.
   * If there are no code execution result in the response, undefined will be returned.
   *
   * @example
   * ```ts
   * const response = await ai.models.generateContent({
   *   model: 'gemini-2.0-flash',
   *   contents:
   *     'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.'
   *   config: {
   *     tools: [{codeExecution: {}}],
   *   },
   * });
   *
   * console.debug(response.codeExecutionResult);
   * ```
   */
  get codeExecutionResult() {
    var _a7, _b, _c, _d, _e2, _f, _g, _h, _j;
    if (((_d = (_c = (_b = (_a7 = this.candidates) === null || _a7 === void 0 ? void 0 : _a7[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) {
      return void 0;
    }
    if (this.candidates && this.candidates.length > 1) {
      console.warn("there are multiple candidates in the response, returning code execution result from the first one.");
    }
    const codeExecutionResult = (_h = (_g = (_f = (_e2 = this.candidates) === null || _e2 === void 0 ? void 0 : _e2[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) === null || _h === void 0 ? void 0 : _h.filter((part) => part.codeExecutionResult).map((part) => part.codeExecutionResult).filter((codeExecutionResult2) => codeExecutionResult2 !== void 0);
    if ((codeExecutionResult === null || codeExecutionResult === void 0 ? void 0 : codeExecutionResult.length) === 0) {
      return void 0;
    }
    return (_j = codeExecutionResult === null || codeExecutionResult === void 0 ? void 0 : codeExecutionResult[0]) === null || _j === void 0 ? void 0 : _j.output;
  }
};
var EmbedContentResponse = class {
};
var GenerateImagesResponse = class {
};
var EditImageResponse = class {
};
var UpscaleImageResponse = class {
};
var RecontextImageResponse = class {
};
var SegmentImageResponse = class {
};
var ListModelsResponse = class {
};
var DeleteModelResponse = class {
};
var CountTokensResponse = class {
};
var ComputeTokensResponse = class {
};
var GenerateVideosOperation = class _GenerateVideosOperation {
  /**
   * Instantiates an Operation of the same type as the one being called with the fields set from the API response.
   * @internal
   */
  _fromAPIResponse({ apiResponse, _isVertexAI }) {
    const operation = new _GenerateVideosOperation();
    let response;
    const op2 = apiResponse;
    if (_isVertexAI) {
      response = generateVideosOperationFromVertex$1(op2);
    } else {
      response = generateVideosOperationFromMldev$1(op2);
    }
    Object.assign(operation, response);
    return operation;
  }
};
var ListTuningJobsResponse = class {
};
var CancelTuningJobResponse = class {
};
var DeleteCachedContentResponse = class {
};
var ListCachedContentsResponse = class {
};
var ListDocumentsResponse = class {
};
var ListFileSearchStoresResponse = class {
};
var UploadToFileSearchStoreResumableResponse = class {
};
var ImportFileOperation = class _ImportFileOperation {
  /**
   * Instantiates an Operation of the same type as the one being called with the fields set from the API response.
   * @internal
   */
  _fromAPIResponse({ apiResponse, _isVertexAI }) {
    const operation = new _ImportFileOperation();
    const op2 = apiResponse;
    const response = importFileOperationFromMldev$1(op2);
    Object.assign(operation, response);
    return operation;
  }
};
var ListFilesResponse = class {
};
var CreateFileResponse = class {
};
var DeleteFileResponse = class {
};
var RegisterFilesResponse = class {
};
var ListBatchJobsResponse = class {
};
var LiveServerMessage = class {
  /**
   * Returns the concatenation of all text parts from the server content if present.
   *
   * @remarks
   * If there are non-text parts in the response, the concatenation of all text
   * parts will be returned, and a warning will be logged.
   */
  get text() {
    var _a7, _b, _c;
    let text3 = "";
    let anyTextPartFound = false;
    const nonTextParts = [];
    for (const part of (_c = (_b = (_a7 = this.serverContent) === null || _a7 === void 0 ? void 0 : _a7.modelTurn) === null || _b === void 0 ? void 0 : _b.parts) !== null && _c !== void 0 ? _c : []) {
      for (const [fieldName, fieldValue] of Object.entries(part)) {
        if (fieldName !== "text" && fieldName !== "thought" && fieldValue !== null) {
          nonTextParts.push(fieldName);
        }
      }
      if (typeof part.text === "string") {
        if (typeof part.thought === "boolean" && part.thought) {
          continue;
        }
        anyTextPartFound = true;
        text3 += part.text;
      }
    }
    if (nonTextParts.length > 0) {
      console.warn(`there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`);
    }
    return anyTextPartFound ? text3 : void 0;
  }
  /**
   * Returns the concatenation of all inline data parts from the server content if present.
   *
   * @remarks
   * If there are non-inline data parts in the
   * response, the concatenation of all inline data parts will be returned, and
   * a warning will be logged.
   */
  get data() {
    var _a7, _b, _c;
    let data = "";
    const nonDataParts = [];
    for (const part of (_c = (_b = (_a7 = this.serverContent) === null || _a7 === void 0 ? void 0 : _a7.modelTurn) === null || _b === void 0 ? void 0 : _b.parts) !== null && _c !== void 0 ? _c : []) {
      for (const [fieldName, fieldValue] of Object.entries(part)) {
        if (fieldName !== "inlineData" && fieldValue !== null) {
          nonDataParts.push(fieldName);
        }
      }
      if (part.inlineData && typeof part.inlineData.data === "string") {
        data += atob(part.inlineData.data);
      }
    }
    if (nonDataParts.length > 0) {
      console.warn(`there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`);
    }
    return data.length > 0 ? btoa(data) : void 0;
  }
};
var LiveMusicServerMessage = class {
  /**
   * Returns the first audio chunk from the server content, if present.
   *
   * @remarks
   * If there are no audio chunks in the response, undefined will be returned.
   */
  get audioChunk() {
    if (this.serverContent && this.serverContent.audioChunks && this.serverContent.audioChunks.length > 0) {
      return this.serverContent.audioChunks[0];
    }
    return void 0;
  }
};
var UploadToFileSearchStoreOperation = class _UploadToFileSearchStoreOperation {
  /**
   * Instantiates an Operation of the same type as the one being called with the fields set from the API response.
   * @internal
   */
  _fromAPIResponse({ apiResponse, _isVertexAI }) {
    const operation = new _UploadToFileSearchStoreOperation();
    const op2 = apiResponse;
    const response = uploadToFileSearchStoreOperationFromMldev(op2);
    Object.assign(operation, response);
    return operation;
  }
};
function tModel(apiClient, model) {
  if (!model || typeof model !== "string") {
    throw new Error("model is required and must be a string");
  }
  if (model.includes("..") || model.includes("?") || model.includes("&")) {
    throw new Error("invalid model parameter");
  }
  if (apiClient.isVertexAI()) {
    if (model.startsWith("publishers/") || model.startsWith("projects/") || model.startsWith("models/")) {
      return model;
    } else if (model.indexOf("/") >= 0) {
      const parts = model.split("/", 2);
      return `publishers/${parts[0]}/models/${parts[1]}`;
    } else {
      return `publishers/google/models/${model}`;
    }
  } else {
    if (model.startsWith("models/") || model.startsWith("tunedModels/")) {
      return model;
    } else {
      return `models/${model}`;
    }
  }
}
function tCachesModel(apiClient, model) {
  const transformedModel = tModel(apiClient, model);
  if (!transformedModel) {
    return "";
  }
  if (transformedModel.startsWith("publishers/") && apiClient.isVertexAI()) {
    return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/${transformedModel}`;
  } else if (transformedModel.startsWith("models/") && apiClient.isVertexAI()) {
    return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/publishers/google/${transformedModel}`;
  } else {
    return transformedModel;
  }
}
function tBlobs(blobs) {
  if (Array.isArray(blobs)) {
    return blobs.map((blob) => tBlob(blob));
  } else {
    return [tBlob(blobs)];
  }
}
function tBlob(blob) {
  if (typeof blob === "object" && blob !== null) {
    return blob;
  }
  throw new Error(`Could not parse input as Blob. Unsupported blob type: ${typeof blob}`);
}
function tImageBlob(blob) {
  const transformedBlob = tBlob(blob);
  if (transformedBlob.mimeType && transformedBlob.mimeType.startsWith("image/")) {
    return transformedBlob;
  }
  throw new Error(`Unsupported mime type: ${transformedBlob.mimeType}`);
}
function tAudioBlob(blob) {
  const transformedBlob = tBlob(blob);
  if (transformedBlob.mimeType && transformedBlob.mimeType.startsWith("audio/")) {
    return transformedBlob;
  }
  throw new Error(`Unsupported mime type: ${transformedBlob.mimeType}`);
}
function tPart(origin) {
  if (origin === null || origin === void 0) {
    throw new Error("PartUnion is required");
  }
  if (typeof origin === "object") {
    return origin;
  }
  if (typeof origin === "string") {
    return { text: origin };
  }
  throw new Error(`Unsupported part type: ${typeof origin}`);
}
function tParts(origin) {
  if (origin === null || origin === void 0 || Array.isArray(origin) && origin.length === 0) {
    throw new Error("PartListUnion is required");
  }
  if (Array.isArray(origin)) {
    return origin.map((item) => tPart(item));
  }
  return [tPart(origin)];
}
function _isContent(origin) {
  return origin !== null && origin !== void 0 && typeof origin === "object" && "parts" in origin && Array.isArray(origin.parts);
}
function _isFunctionCallPart(origin) {
  return origin !== null && origin !== void 0 && typeof origin === "object" && "functionCall" in origin;
}
function _isFunctionResponsePart(origin) {
  return origin !== null && origin !== void 0 && typeof origin === "object" && "functionResponse" in origin;
}
function tContent(origin) {
  if (origin === null || origin === void 0) {
    throw new Error("ContentUnion is required");
  }
  if (_isContent(origin)) {
    return origin;
  }
  return {
    role: "user",
    parts: tParts(origin)
  };
}
function tContentsForEmbed(apiClient, origin) {
  if (!origin) {
    return [];
  }
  if (apiClient.isVertexAI() && Array.isArray(origin)) {
    return origin.flatMap((item) => {
      const content = tContent(item);
      if (content.parts && content.parts.length > 0 && content.parts[0].text !== void 0) {
        return [content.parts[0].text];
      }
      return [];
    });
  } else if (apiClient.isVertexAI()) {
    const content = tContent(origin);
    if (content.parts && content.parts.length > 0 && content.parts[0].text !== void 0) {
      return [content.parts[0].text];
    }
    return [];
  }
  if (Array.isArray(origin)) {
    return origin.map((item) => tContent(item));
  }
  return [tContent(origin)];
}
function tContents(origin) {
  if (origin === null || origin === void 0 || Array.isArray(origin) && origin.length === 0) {
    throw new Error("contents are required");
  }
  if (!Array.isArray(origin)) {
    if (_isFunctionCallPart(origin) || _isFunctionResponsePart(origin)) {
      throw new Error("To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them");
    }
    return [tContent(origin)];
  }
  const result = [];
  const accumulatedParts = [];
  const isContentArray = _isContent(origin[0]);
  for (const item of origin) {
    const isContent = _isContent(item);
    if (isContent != isContentArray) {
      throw new Error("Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them");
    }
    if (isContent) {
      result.push(item);
    } else if (_isFunctionCallPart(item) || _isFunctionResponsePart(item)) {
      throw new Error("To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them");
    } else {
      accumulatedParts.push(item);
    }
  }
  if (!isContentArray) {
    result.push({ role: "user", parts: tParts(accumulatedParts) });
  }
  return result;
}
function flattenTypeArrayToAnyOf(typeList, resultingSchema) {
  if (typeList.includes("null")) {
    resultingSchema["nullable"] = true;
  }
  const listWithoutNull = typeList.filter((type) => type !== "null");
  if (listWithoutNull.length === 1) {
    resultingSchema["type"] = Object.values(Type2).includes(listWithoutNull[0].toUpperCase()) ? listWithoutNull[0].toUpperCase() : Type2.TYPE_UNSPECIFIED;
  } else {
    resultingSchema["anyOf"] = [];
    for (const i7 of listWithoutNull) {
      resultingSchema["anyOf"].push({
        "type": Object.values(Type2).includes(i7.toUpperCase()) ? i7.toUpperCase() : Type2.TYPE_UNSPECIFIED
      });
    }
  }
}
function processJsonSchema(_jsonSchema) {
  const genAISchema = {};
  const schemaFieldNames = ["items"];
  const listSchemaFieldNames = ["anyOf"];
  const dictSchemaFieldNames = ["properties"];
  if (_jsonSchema["type"] && _jsonSchema["anyOf"]) {
    throw new Error("type and anyOf cannot be both populated.");
  }
  const incomingAnyOf = _jsonSchema["anyOf"];
  if (incomingAnyOf != null && incomingAnyOf.length == 2) {
    if (incomingAnyOf[0]["type"] === "null") {
      genAISchema["nullable"] = true;
      _jsonSchema = incomingAnyOf[1];
    } else if (incomingAnyOf[1]["type"] === "null") {
      genAISchema["nullable"] = true;
      _jsonSchema = incomingAnyOf[0];
    }
  }
  if (_jsonSchema["type"] instanceof Array) {
    flattenTypeArrayToAnyOf(_jsonSchema["type"], genAISchema);
  }
  for (const [fieldName, fieldValue] of Object.entries(_jsonSchema)) {
    if (fieldValue == null) {
      continue;
    }
    if (fieldName == "type") {
      if (fieldValue === "null") {
        throw new Error("type: null can not be the only possible type for the field.");
      }
      if (fieldValue instanceof Array) {
        continue;
      }
      genAISchema["type"] = Object.values(Type2).includes(fieldValue.toUpperCase()) ? fieldValue.toUpperCase() : Type2.TYPE_UNSPECIFIED;
    } else if (schemaFieldNames.includes(fieldName)) {
      genAISchema[fieldName] = processJsonSchema(fieldValue);
    } else if (listSchemaFieldNames.includes(fieldName)) {
      const listSchemaFieldValue = [];
      for (const item of fieldValue) {
        if (item["type"] == "null") {
          genAISchema["nullable"] = true;
          continue;
        }
        listSchemaFieldValue.push(processJsonSchema(item));
      }
      genAISchema[fieldName] = listSchemaFieldValue;
    } else if (dictSchemaFieldNames.includes(fieldName)) {
      const dictSchemaFieldValue = {};
      for (const [key, value] of Object.entries(fieldValue)) {
        dictSchemaFieldValue[key] = processJsonSchema(value);
      }
      genAISchema[fieldName] = dictSchemaFieldValue;
    } else {
      if (fieldName === "additionalProperties") {
        continue;
      }
      genAISchema[fieldName] = fieldValue;
    }
  }
  return genAISchema;
}
function tSchema(schema) {
  return processJsonSchema(schema);
}
function tSpeechConfig(speechConfig) {
  if (typeof speechConfig === "object") {
    return speechConfig;
  } else if (typeof speechConfig === "string") {
    return {
      voiceConfig: {
        prebuiltVoiceConfig: {
          voiceName: speechConfig
        }
      }
    };
  } else {
    throw new Error(`Unsupported speechConfig type: ${typeof speechConfig}`);
  }
}
function tLiveSpeechConfig(speechConfig) {
  if ("multiSpeakerVoiceConfig" in speechConfig) {
    throw new Error("multiSpeakerVoiceConfig is not supported in the live API.");
  }
  return speechConfig;
}
function tTool(tool) {
  if (tool.functionDeclarations) {
    for (const functionDeclaration of tool.functionDeclarations) {
      if (functionDeclaration.parameters) {
        if (!Object.keys(functionDeclaration.parameters).includes("$schema")) {
          functionDeclaration.parameters = processJsonSchema(functionDeclaration.parameters);
        } else {
          if (!functionDeclaration.parametersJsonSchema) {
            functionDeclaration.parametersJsonSchema = functionDeclaration.parameters;
            delete functionDeclaration.parameters;
          }
        }
      }
      if (functionDeclaration.response) {
        if (!Object.keys(functionDeclaration.response).includes("$schema")) {
          functionDeclaration.response = processJsonSchema(functionDeclaration.response);
        } else {
          if (!functionDeclaration.responseJsonSchema) {
            functionDeclaration.responseJsonSchema = functionDeclaration.response;
            delete functionDeclaration.response;
          }
        }
      }
    }
  }
  return tool;
}
function tTools(tools) {
  if (tools === void 0 || tools === null) {
    throw new Error("tools is required");
  }
  if (!Array.isArray(tools)) {
    throw new Error("tools is required and must be an array of Tools");
  }
  const result = [];
  for (const tool of tools) {
    result.push(tool);
  }
  return result;
}
function resourceName(client, resourceName2, resourcePrefix, splitsAfterPrefix = 1) {
  const shouldAppendPrefix = !resourceName2.startsWith(`${resourcePrefix}/`) && resourceName2.split("/").length === splitsAfterPrefix;
  if (client.isVertexAI()) {
    if (resourceName2.startsWith("projects/")) {
      return resourceName2;
    } else if (resourceName2.startsWith("locations/")) {
      return `projects/${client.getProject()}/${resourceName2}`;
    } else if (resourceName2.startsWith(`${resourcePrefix}/`)) {
      return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourceName2}`;
    } else if (shouldAppendPrefix) {
      return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourcePrefix}/${resourceName2}`;
    } else {
      return resourceName2;
    }
  }
  if (shouldAppendPrefix) {
    return `${resourcePrefix}/${resourceName2}`;
  }
  return resourceName2;
}
function tCachedContentName(apiClient, name) {
  if (typeof name !== "string") {
    throw new Error("name must be a string");
  }
  return resourceName(apiClient, name, "cachedContents");
}
function tTuningJobStatus(status) {
  switch (status) {
    case "STATE_UNSPECIFIED":
      return "JOB_STATE_UNSPECIFIED";
    case "CREATING":
      return "JOB_STATE_RUNNING";
    case "ACTIVE":
      return "JOB_STATE_SUCCEEDED";
    case "FAILED":
      return "JOB_STATE_FAILED";
    default:
      return status;
  }
}
function tBytes(fromImageBytes) {
  return tBytes$1(fromImageBytes);
}
function _isFile(origin) {
  return origin !== null && origin !== void 0 && typeof origin === "object" && "name" in origin;
}
function isGeneratedVideo(origin) {
  return origin !== null && origin !== void 0 && typeof origin === "object" && "video" in origin;
}
function isVideo(origin) {
  return origin !== null && origin !== void 0 && typeof origin === "object" && "uri" in origin;
}
function tFileName(fromName) {
  var _a7;
  let name;
  if (_isFile(fromName)) {
    name = fromName.name;
  }
  if (isVideo(fromName)) {
    name = fromName.uri;
    if (name === void 0) {
      return void 0;
    }
  }
  if (isGeneratedVideo(fromName)) {
    name = (_a7 = fromName.video) === null || _a7 === void 0 ? void 0 : _a7.uri;
    if (name === void 0) {
      return void 0;
    }
  }
  if (typeof fromName === "string") {
    name = fromName;
  }
  if (name === void 0) {
    throw new Error("Could not extract file name from the provided input.");
  }
  if (name.startsWith("https://")) {
    const suffix = name.split("files/")[1];
    const match2 = suffix.match(/[a-z0-9]+/);
    if (match2 === null) {
      throw new Error(`Could not extract file name from URI ${name}`);
    }
    name = match2[0];
  } else if (name.startsWith("files/")) {
    name = name.split("files/")[1];
  }
  return name;
}
function tModelsUrl(apiClient, baseModels) {
  let res;
  if (apiClient.isVertexAI()) {
    res = baseModels ? "publishers/google/models" : "models";
  } else {
    res = baseModels ? "models" : "tunedModels";
  }
  return res;
}
function tExtractModels(response) {
  for (const key of ["models", "tunedModels", "publisherModels"]) {
    if (hasField(response, key)) {
      return response[key];
    }
  }
  return [];
}
function hasField(data, fieldName) {
  return data !== null && typeof data === "object" && fieldName in data;
}
function mcpToGeminiTool(mcpTool, config = {}) {
  const mcpToolSchema = mcpTool;
  const functionDeclaration = {
    name: mcpToolSchema["name"],
    description: mcpToolSchema["description"],
    parametersJsonSchema: mcpToolSchema["inputSchema"]
  };
  if (mcpToolSchema["outputSchema"]) {
    functionDeclaration["responseJsonSchema"] = mcpToolSchema["outputSchema"];
  }
  if (config.behavior) {
    functionDeclaration["behavior"] = config.behavior;
  }
  const geminiTool = {
    functionDeclarations: [
      functionDeclaration
    ]
  };
  return geminiTool;
}
function mcpToolsToGeminiTool(mcpTools, config = {}) {
  const functionDeclarations = [];
  const toolNames = /* @__PURE__ */ new Set();
  for (const mcpTool of mcpTools) {
    const mcpToolName = mcpTool.name;
    if (toolNames.has(mcpToolName)) {
      throw new Error(`Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`);
    }
    toolNames.add(mcpToolName);
    const geminiTool = mcpToGeminiTool(mcpTool, config);
    if (geminiTool.functionDeclarations) {
      functionDeclarations.push(...geminiTool.functionDeclarations);
    }
  }
  return { functionDeclarations };
}
function tBatchJobSource(client, src) {
  let sourceObj;
  if (typeof src === "string") {
    if (client.isVertexAI()) {
      if (src.startsWith("gs://")) {
        sourceObj = { format: "jsonl", gcsUri: [src] };
      } else if (src.startsWith("bq://")) {
        sourceObj = { format: "bigquery", bigqueryUri: src };
      } else {
        throw new Error(`Unsupported string source for Vertex AI: ${src}`);
      }
    } else {
      if (src.startsWith("files/")) {
        sourceObj = { fileName: src };
      } else {
        throw new Error(`Unsupported string source for Gemini API: ${src}`);
      }
    }
  } else if (Array.isArray(src)) {
    if (client.isVertexAI()) {
      throw new Error("InlinedRequest[] is not supported in Vertex AI.");
    }
    sourceObj = { inlinedRequests: src };
  } else {
    sourceObj = src;
  }
  const vertexSourcesCount = [sourceObj.gcsUri, sourceObj.bigqueryUri].filter(Boolean).length;
  const mldevSourcesCount = [
    sourceObj.inlinedRequests,
    sourceObj.fileName
  ].filter(Boolean).length;
  if (client.isVertexAI()) {
    if (mldevSourcesCount > 0 || vertexSourcesCount !== 1) {
      throw new Error("Exactly one of `gcsUri` or `bigqueryUri` must be set for Vertex AI.");
    }
  } else {
    if (vertexSourcesCount > 0 || mldevSourcesCount !== 1) {
      throw new Error("Exactly one of `inlinedRequests`, `fileName`, must be set for Gemini API.");
    }
  }
  return sourceObj;
}
function tBatchJobDestination(dest) {
  if (typeof dest !== "string") {
    return dest;
  }
  const destString = dest;
  if (destString.startsWith("gs://")) {
    return {
      format: "jsonl",
      gcsUri: destString
    };
  } else if (destString.startsWith("bq://")) {
    return {
      format: "bigquery",
      bigqueryUri: destString
    };
  } else {
    throw new Error(`Unsupported destination: ${destString}`);
  }
}
function tRecvBatchJobDestination(dest) {
  if (typeof dest !== "object" || dest === null) {
    return {};
  }
  const obj = dest;
  const inlineResponsesVal = obj["inlinedResponses"];
  if (typeof inlineResponsesVal !== "object" || inlineResponsesVal === null) {
    return dest;
  }
  const inlineResponsesObj = inlineResponsesVal;
  const responsesArray = inlineResponsesObj["inlinedResponses"];
  if (!Array.isArray(responsesArray) || responsesArray.length === 0) {
    return dest;
  }
  let hasEmbedding = false;
  for (const responseItem of responsesArray) {
    if (typeof responseItem !== "object" || responseItem === null) {
      continue;
    }
    const responseItemObj = responseItem;
    const responseVal = responseItemObj["response"];
    if (typeof responseVal !== "object" || responseVal === null) {
      continue;
    }
    const responseObj = responseVal;
    if (responseObj["embedding"] !== void 0) {
      hasEmbedding = true;
      break;
    }
  }
  if (hasEmbedding) {
    obj["inlinedEmbedContentResponses"] = obj["inlinedResponses"];
    delete obj["inlinedResponses"];
  }
  return dest;
}
function tBatchJobName(apiClient, name) {
  const nameString = name;
  if (!apiClient.isVertexAI()) {
    const mldevPattern = /batches\/[^/]+$/;
    if (mldevPattern.test(nameString)) {
      return nameString.split("/").pop();
    } else {
      throw new Error(`Invalid batch job name: ${nameString}.`);
    }
  }
  const vertexPattern = /^projects\/[^/]+\/locations\/[^/]+\/batchPredictionJobs\/[^/]+$/;
  if (vertexPattern.test(nameString)) {
    return nameString.split("/").pop();
  } else if (/^\d+$/.test(nameString)) {
    return nameString;
  } else {
    throw new Error(`Invalid batch job name: ${nameString}.`);
  }
}
function tJobState(state) {
  const stateString = state;
  if (stateString === "BATCH_STATE_UNSPECIFIED") {
    return "JOB_STATE_UNSPECIFIED";
  } else if (stateString === "BATCH_STATE_PENDING") {
    return "JOB_STATE_PENDING";
  } else if (stateString === "BATCH_STATE_RUNNING") {
    return "JOB_STATE_RUNNING";
  } else if (stateString === "BATCH_STATE_SUCCEEDED") {
    return "JOB_STATE_SUCCEEDED";
  } else if (stateString === "BATCH_STATE_FAILED") {
    return "JOB_STATE_FAILED";
  } else if (stateString === "BATCH_STATE_CANCELLED") {
    return "JOB_STATE_CANCELLED";
  } else if (stateString === "BATCH_STATE_EXPIRED") {
    return "JOB_STATE_EXPIRED";
  } else {
    return stateString;
  }
}
function tIsVertexEmbedContentModel(model) {
  return model.includes("gemini") && model !== "gemini-embedding-001" || model.includes("maas");
}
function authConfigToMldev$4(fromObject) {
  const toObject = {};
  const fromApiKey = getValueByPath(fromObject, ["apiKey"]);
  if (fromApiKey != null) {
    setValueByPath(toObject, ["apiKey"], fromApiKey);
  }
  if (getValueByPath(fromObject, ["apiKeyConfig"]) !== void 0) {
    throw new Error("apiKeyConfig parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["authType"]) !== void 0) {
    throw new Error("authType parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["googleServiceAccountConfig"]) !== void 0) {
    throw new Error("googleServiceAccountConfig parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["httpBasicAuthConfig"]) !== void 0) {
    throw new Error("httpBasicAuthConfig parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["oauthConfig"]) !== void 0) {
    throw new Error("oauthConfig parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["oidcConfig"]) !== void 0) {
    throw new Error("oidcConfig parameter is not supported in Gemini API.");
  }
  return toObject;
}
function batchJobDestinationFromMldev(fromObject) {
  const toObject = {};
  const fromFileName = getValueByPath(fromObject, ["responsesFile"]);
  if (fromFileName != null) {
    setValueByPath(toObject, ["fileName"], fromFileName);
  }
  const fromInlinedResponses = getValueByPath(fromObject, [
    "inlinedResponses",
    "inlinedResponses"
  ]);
  if (fromInlinedResponses != null) {
    let transformedList = fromInlinedResponses;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return inlinedResponseFromMldev(item);
      });
    }
    setValueByPath(toObject, ["inlinedResponses"], transformedList);
  }
  const fromInlinedEmbedContentResponses = getValueByPath(fromObject, [
    "inlinedEmbedContentResponses",
    "inlinedResponses"
  ]);
  if (fromInlinedEmbedContentResponses != null) {
    let transformedList = fromInlinedEmbedContentResponses;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["inlinedEmbedContentResponses"], transformedList);
  }
  return toObject;
}
function batchJobDestinationFromVertex(fromObject) {
  const toObject = {};
  const fromFormat = getValueByPath(fromObject, ["predictionsFormat"]);
  if (fromFormat != null) {
    setValueByPath(toObject, ["format"], fromFormat);
  }
  const fromGcsUri = getValueByPath(fromObject, [
    "gcsDestination",
    "outputUriPrefix"
  ]);
  if (fromGcsUri != null) {
    setValueByPath(toObject, ["gcsUri"], fromGcsUri);
  }
  const fromBigqueryUri = getValueByPath(fromObject, [
    "bigqueryDestination",
    "outputUri"
  ]);
  if (fromBigqueryUri != null) {
    setValueByPath(toObject, ["bigqueryUri"], fromBigqueryUri);
  }
  return toObject;
}
function batchJobDestinationToVertex(fromObject) {
  const toObject = {};
  const fromFormat = getValueByPath(fromObject, ["format"]);
  if (fromFormat != null) {
    setValueByPath(toObject, ["predictionsFormat"], fromFormat);
  }
  const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]);
  if (fromGcsUri != null) {
    setValueByPath(toObject, ["gcsDestination", "outputUriPrefix"], fromGcsUri);
  }
  const fromBigqueryUri = getValueByPath(fromObject, ["bigqueryUri"]);
  if (fromBigqueryUri != null) {
    setValueByPath(toObject, ["bigqueryDestination", "outputUri"], fromBigqueryUri);
  }
  if (getValueByPath(fromObject, ["fileName"]) !== void 0) {
    throw new Error("fileName parameter is not supported in Vertex AI.");
  }
  if (getValueByPath(fromObject, ["inlinedResponses"]) !== void 0) {
    throw new Error("inlinedResponses parameter is not supported in Vertex AI.");
  }
  if (getValueByPath(fromObject, ["inlinedEmbedContentResponses"]) !== void 0) {
    throw new Error("inlinedEmbedContentResponses parameter is not supported in Vertex AI.");
  }
  return toObject;
}
function batchJobFromMldev(fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromDisplayName = getValueByPath(fromObject, [
    "metadata",
    "displayName"
  ]);
  if (fromDisplayName != null) {
    setValueByPath(toObject, ["displayName"], fromDisplayName);
  }
  const fromState = getValueByPath(fromObject, ["metadata", "state"]);
  if (fromState != null) {
    setValueByPath(toObject, ["state"], tJobState(fromState));
  }
  const fromCreateTime = getValueByPath(fromObject, [
    "metadata",
    "createTime"
  ]);
  if (fromCreateTime != null) {
    setValueByPath(toObject, ["createTime"], fromCreateTime);
  }
  const fromEndTime = getValueByPath(fromObject, [
    "metadata",
    "endTime"
  ]);
  if (fromEndTime != null) {
    setValueByPath(toObject, ["endTime"], fromEndTime);
  }
  const fromUpdateTime = getValueByPath(fromObject, [
    "metadata",
    "updateTime"
  ]);
  if (fromUpdateTime != null) {
    setValueByPath(toObject, ["updateTime"], fromUpdateTime);
  }
  const fromModel = getValueByPath(fromObject, ["metadata", "model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["model"], fromModel);
  }
  const fromDest = getValueByPath(fromObject, ["metadata", "output"]);
  if (fromDest != null) {
    setValueByPath(toObject, ["dest"], batchJobDestinationFromMldev(tRecvBatchJobDestination(fromDest)));
  }
  return toObject;
}
function batchJobFromVertex(fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromDisplayName = getValueByPath(fromObject, ["displayName"]);
  if (fromDisplayName != null) {
    setValueByPath(toObject, ["displayName"], fromDisplayName);
  }
  const fromState = getValueByPath(fromObject, ["state"]);
  if (fromState != null) {
    setValueByPath(toObject, ["state"], tJobState(fromState));
  }
  const fromError = getValueByPath(fromObject, ["error"]);
  if (fromError != null) {
    setValueByPath(toObject, ["error"], fromError);
  }
  const fromCreateTime = getValueByPath(fromObject, ["createTime"]);
  if (fromCreateTime != null) {
    setValueByPath(toObject, ["createTime"], fromCreateTime);
  }
  const fromStartTime = getValueByPath(fromObject, ["startTime"]);
  if (fromStartTime != null) {
    setValueByPath(toObject, ["startTime"], fromStartTime);
  }
  const fromEndTime = getValueByPath(fromObject, ["endTime"]);
  if (fromEndTime != null) {
    setValueByPath(toObject, ["endTime"], fromEndTime);
  }
  const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]);
  if (fromUpdateTime != null) {
    setValueByPath(toObject, ["updateTime"], fromUpdateTime);
  }
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["model"], fromModel);
  }
  const fromSrc = getValueByPath(fromObject, ["inputConfig"]);
  if (fromSrc != null) {
    setValueByPath(toObject, ["src"], batchJobSourceFromVertex(fromSrc));
  }
  const fromDest = getValueByPath(fromObject, ["outputConfig"]);
  if (fromDest != null) {
    setValueByPath(toObject, ["dest"], batchJobDestinationFromVertex(tRecvBatchJobDestination(fromDest)));
  }
  const fromCompletionStats = getValueByPath(fromObject, [
    "completionStats"
  ]);
  if (fromCompletionStats != null) {
    setValueByPath(toObject, ["completionStats"], fromCompletionStats);
  }
  return toObject;
}
function batchJobSourceFromVertex(fromObject) {
  const toObject = {};
  const fromFormat = getValueByPath(fromObject, ["instancesFormat"]);
  if (fromFormat != null) {
    setValueByPath(toObject, ["format"], fromFormat);
  }
  const fromGcsUri = getValueByPath(fromObject, ["gcsSource", "uris"]);
  if (fromGcsUri != null) {
    setValueByPath(toObject, ["gcsUri"], fromGcsUri);
  }
  const fromBigqueryUri = getValueByPath(fromObject, [
    "bigquerySource",
    "inputUri"
  ]);
  if (fromBigqueryUri != null) {
    setValueByPath(toObject, ["bigqueryUri"], fromBigqueryUri);
  }
  return toObject;
}
function batchJobSourceToMldev(apiClient, fromObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["format"]) !== void 0) {
    throw new Error("format parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["gcsUri"]) !== void 0) {
    throw new Error("gcsUri parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["bigqueryUri"]) !== void 0) {
    throw new Error("bigqueryUri parameter is not supported in Gemini API.");
  }
  const fromFileName = getValueByPath(fromObject, ["fileName"]);
  if (fromFileName != null) {
    setValueByPath(toObject, ["fileName"], fromFileName);
  }
  const fromInlinedRequests = getValueByPath(fromObject, [
    "inlinedRequests"
  ]);
  if (fromInlinedRequests != null) {
    let transformedList = fromInlinedRequests;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return inlinedRequestToMldev(apiClient, item);
      });
    }
    setValueByPath(toObject, ["requests", "requests"], transformedList);
  }
  return toObject;
}
function batchJobSourceToVertex(fromObject) {
  const toObject = {};
  const fromFormat = getValueByPath(fromObject, ["format"]);
  if (fromFormat != null) {
    setValueByPath(toObject, ["instancesFormat"], fromFormat);
  }
  const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]);
  if (fromGcsUri != null) {
    setValueByPath(toObject, ["gcsSource", "uris"], fromGcsUri);
  }
  const fromBigqueryUri = getValueByPath(fromObject, ["bigqueryUri"]);
  if (fromBigqueryUri != null) {
    setValueByPath(toObject, ["bigquerySource", "inputUri"], fromBigqueryUri);
  }
  if (getValueByPath(fromObject, ["fileName"]) !== void 0) {
    throw new Error("fileName parameter is not supported in Vertex AI.");
  }
  if (getValueByPath(fromObject, ["inlinedRequests"]) !== void 0) {
    throw new Error("inlinedRequests parameter is not supported in Vertex AI.");
  }
  return toObject;
}
function blobToMldev$4(fromObject) {
  const toObject = {};
  const fromData = getValueByPath(fromObject, ["data"]);
  if (fromData != null) {
    setValueByPath(toObject, ["data"], fromData);
  }
  if (getValueByPath(fromObject, ["displayName"]) !== void 0) {
    throw new Error("displayName parameter is not supported in Gemini API.");
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function cancelBatchJobParametersToMldev(apiClient, fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], tBatchJobName(apiClient, fromName));
  }
  return toObject;
}
function cancelBatchJobParametersToVertex(apiClient, fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], tBatchJobName(apiClient, fromName));
  }
  return toObject;
}
function candidateFromMldev$1(fromObject) {
  const toObject = {};
  const fromContent = getValueByPath(fromObject, ["content"]);
  if (fromContent != null) {
    setValueByPath(toObject, ["content"], fromContent);
  }
  const fromCitationMetadata = getValueByPath(fromObject, [
    "citationMetadata"
  ]);
  if (fromCitationMetadata != null) {
    setValueByPath(toObject, ["citationMetadata"], citationMetadataFromMldev$1(fromCitationMetadata));
  }
  const fromTokenCount = getValueByPath(fromObject, ["tokenCount"]);
  if (fromTokenCount != null) {
    setValueByPath(toObject, ["tokenCount"], fromTokenCount);
  }
  const fromFinishReason = getValueByPath(fromObject, ["finishReason"]);
  if (fromFinishReason != null) {
    setValueByPath(toObject, ["finishReason"], fromFinishReason);
  }
  const fromGroundingMetadata = getValueByPath(fromObject, [
    "groundingMetadata"
  ]);
  if (fromGroundingMetadata != null) {
    setValueByPath(toObject, ["groundingMetadata"], fromGroundingMetadata);
  }
  const fromAvgLogprobs = getValueByPath(fromObject, ["avgLogprobs"]);
  if (fromAvgLogprobs != null) {
    setValueByPath(toObject, ["avgLogprobs"], fromAvgLogprobs);
  }
  const fromIndex = getValueByPath(fromObject, ["index"]);
  if (fromIndex != null) {
    setValueByPath(toObject, ["index"], fromIndex);
  }
  const fromLogprobsResult = getValueByPath(fromObject, [
    "logprobsResult"
  ]);
  if (fromLogprobsResult != null) {
    setValueByPath(toObject, ["logprobsResult"], fromLogprobsResult);
  }
  const fromSafetyRatings = getValueByPath(fromObject, [
    "safetyRatings"
  ]);
  if (fromSafetyRatings != null) {
    let transformedList = fromSafetyRatings;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["safetyRatings"], transformedList);
  }
  const fromUrlContextMetadata = getValueByPath(fromObject, [
    "urlContextMetadata"
  ]);
  if (fromUrlContextMetadata != null) {
    setValueByPath(toObject, ["urlContextMetadata"], fromUrlContextMetadata);
  }
  return toObject;
}
function citationMetadataFromMldev$1(fromObject) {
  const toObject = {};
  const fromCitations = getValueByPath(fromObject, ["citationSources"]);
  if (fromCitations != null) {
    let transformedList = fromCitations;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["citations"], transformedList);
  }
  return toObject;
}
function contentToMldev$4(fromObject) {
  const toObject = {};
  const fromParts = getValueByPath(fromObject, ["parts"]);
  if (fromParts != null) {
    let transformedList = fromParts;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return partToMldev$4(item);
      });
    }
    setValueByPath(toObject, ["parts"], transformedList);
  }
  const fromRole = getValueByPath(fromObject, ["role"]);
  if (fromRole != null) {
    setValueByPath(toObject, ["role"], fromRole);
  }
  return toObject;
}
function createBatchJobConfigToMldev(fromObject, parentObject) {
  const toObject = {};
  const fromDisplayName = getValueByPath(fromObject, ["displayName"]);
  if (parentObject !== void 0 && fromDisplayName != null) {
    setValueByPath(parentObject, ["batch", "displayName"], fromDisplayName);
  }
  if (getValueByPath(fromObject, ["dest"]) !== void 0) {
    throw new Error("dest parameter is not supported in Gemini API.");
  }
  return toObject;
}
function createBatchJobConfigToVertex(fromObject, parentObject) {
  const toObject = {};
  const fromDisplayName = getValueByPath(fromObject, ["displayName"]);
  if (parentObject !== void 0 && fromDisplayName != null) {
    setValueByPath(parentObject, ["displayName"], fromDisplayName);
  }
  const fromDest = getValueByPath(fromObject, ["dest"]);
  if (parentObject !== void 0 && fromDest != null) {
    setValueByPath(parentObject, ["outputConfig"], batchJobDestinationToVertex(tBatchJobDestination(fromDest)));
  }
  return toObject;
}
function createBatchJobParametersToMldev(apiClient, fromObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromSrc = getValueByPath(fromObject, ["src"]);
  if (fromSrc != null) {
    setValueByPath(toObject, ["batch", "inputConfig"], batchJobSourceToMldev(apiClient, tBatchJobSource(apiClient, fromSrc)));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    createBatchJobConfigToMldev(fromConfig, toObject);
  }
  return toObject;
}
function createBatchJobParametersToVertex(apiClient, fromObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["model"], tModel(apiClient, fromModel));
  }
  const fromSrc = getValueByPath(fromObject, ["src"]);
  if (fromSrc != null) {
    setValueByPath(toObject, ["inputConfig"], batchJobSourceToVertex(tBatchJobSource(apiClient, fromSrc)));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    createBatchJobConfigToVertex(fromConfig, toObject);
  }
  return toObject;
}
function createEmbeddingsBatchJobConfigToMldev(fromObject, parentObject) {
  const toObject = {};
  const fromDisplayName = getValueByPath(fromObject, ["displayName"]);
  if (parentObject !== void 0 && fromDisplayName != null) {
    setValueByPath(parentObject, ["batch", "displayName"], fromDisplayName);
  }
  return toObject;
}
function createEmbeddingsBatchJobParametersToMldev(apiClient, fromObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromSrc = getValueByPath(fromObject, ["src"]);
  if (fromSrc != null) {
    setValueByPath(toObject, ["batch", "inputConfig"], embeddingsBatchJobSourceToMldev(apiClient, fromSrc));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    createEmbeddingsBatchJobConfigToMldev(fromConfig, toObject);
  }
  return toObject;
}
function deleteBatchJobParametersToMldev(apiClient, fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], tBatchJobName(apiClient, fromName));
  }
  return toObject;
}
function deleteBatchJobParametersToVertex(apiClient, fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], tBatchJobName(apiClient, fromName));
  }
  return toObject;
}
function deleteResourceJobFromMldev(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromDone = getValueByPath(fromObject, ["done"]);
  if (fromDone != null) {
    setValueByPath(toObject, ["done"], fromDone);
  }
  const fromError = getValueByPath(fromObject, ["error"]);
  if (fromError != null) {
    setValueByPath(toObject, ["error"], fromError);
  }
  return toObject;
}
function deleteResourceJobFromVertex(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromDone = getValueByPath(fromObject, ["done"]);
  if (fromDone != null) {
    setValueByPath(toObject, ["done"], fromDone);
  }
  const fromError = getValueByPath(fromObject, ["error"]);
  if (fromError != null) {
    setValueByPath(toObject, ["error"], fromError);
  }
  return toObject;
}
function embedContentBatchToMldev(apiClient, fromObject) {
  const toObject = {};
  const fromContents = getValueByPath(fromObject, ["contents"]);
  if (fromContents != null) {
    let transformedList = tContentsForEmbed(apiClient, fromContents);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["requests[]", "request", "content"], transformedList);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["_self"], embedContentConfigToMldev$1(fromConfig, toObject));
    moveValueByPath(toObject, { "requests[].*": "requests[].request.*" });
  }
  return toObject;
}
function embedContentConfigToMldev$1(fromObject, parentObject) {
  const toObject = {};
  const fromTaskType = getValueByPath(fromObject, ["taskType"]);
  if (parentObject !== void 0 && fromTaskType != null) {
    setValueByPath(parentObject, ["requests[]", "taskType"], fromTaskType);
  }
  const fromTitle = getValueByPath(fromObject, ["title"]);
  if (parentObject !== void 0 && fromTitle != null) {
    setValueByPath(parentObject, ["requests[]", "title"], fromTitle);
  }
  const fromOutputDimensionality = getValueByPath(fromObject, [
    "outputDimensionality"
  ]);
  if (parentObject !== void 0 && fromOutputDimensionality != null) {
    setValueByPath(parentObject, ["requests[]", "outputDimensionality"], fromOutputDimensionality);
  }
  if (getValueByPath(fromObject, ["mimeType"]) !== void 0) {
    throw new Error("mimeType parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["autoTruncate"]) !== void 0) {
    throw new Error("autoTruncate parameter is not supported in Gemini API.");
  }
  return toObject;
}
function embeddingsBatchJobSourceToMldev(apiClient, fromObject) {
  const toObject = {};
  const fromFileName = getValueByPath(fromObject, ["fileName"]);
  if (fromFileName != null) {
    setValueByPath(toObject, ["file_name"], fromFileName);
  }
  const fromInlinedRequests = getValueByPath(fromObject, [
    "inlinedRequests"
  ]);
  if (fromInlinedRequests != null) {
    setValueByPath(toObject, ["requests"], embedContentBatchToMldev(apiClient, fromInlinedRequests));
  }
  return toObject;
}
function fileDataToMldev$4(fromObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["displayName"]) !== void 0) {
    throw new Error("displayName parameter is not supported in Gemini API.");
  }
  const fromFileUri = getValueByPath(fromObject, ["fileUri"]);
  if (fromFileUri != null) {
    setValueByPath(toObject, ["fileUri"], fromFileUri);
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function functionCallToMldev$4(fromObject) {
  const toObject = {};
  const fromId = getValueByPath(fromObject, ["id"]);
  if (fromId != null) {
    setValueByPath(toObject, ["id"], fromId);
  }
  const fromArgs = getValueByPath(fromObject, ["args"]);
  if (fromArgs != null) {
    setValueByPath(toObject, ["args"], fromArgs);
  }
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  if (getValueByPath(fromObject, ["partialArgs"]) !== void 0) {
    throw new Error("partialArgs parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["willContinue"]) !== void 0) {
    throw new Error("willContinue parameter is not supported in Gemini API.");
  }
  return toObject;
}
function functionCallingConfigToMldev$2(fromObject) {
  const toObject = {};
  const fromAllowedFunctionNames = getValueByPath(fromObject, [
    "allowedFunctionNames"
  ]);
  if (fromAllowedFunctionNames != null) {
    setValueByPath(toObject, ["allowedFunctionNames"], fromAllowedFunctionNames);
  }
  const fromMode = getValueByPath(fromObject, ["mode"]);
  if (fromMode != null) {
    setValueByPath(toObject, ["mode"], fromMode);
  }
  if (getValueByPath(fromObject, ["streamFunctionCallArguments"]) !== void 0) {
    throw new Error("streamFunctionCallArguments parameter is not supported in Gemini API.");
  }
  return toObject;
}
function generateContentConfigToMldev$1(apiClient, fromObject, parentObject) {
  const toObject = {};
  const fromSystemInstruction = getValueByPath(fromObject, [
    "systemInstruction"
  ]);
  if (parentObject !== void 0 && fromSystemInstruction != null) {
    setValueByPath(parentObject, ["systemInstruction"], contentToMldev$4(tContent(fromSystemInstruction)));
  }
  const fromTemperature = getValueByPath(fromObject, ["temperature"]);
  if (fromTemperature != null) {
    setValueByPath(toObject, ["temperature"], fromTemperature);
  }
  const fromTopP = getValueByPath(fromObject, ["topP"]);
  if (fromTopP != null) {
    setValueByPath(toObject, ["topP"], fromTopP);
  }
  const fromTopK = getValueByPath(fromObject, ["topK"]);
  if (fromTopK != null) {
    setValueByPath(toObject, ["topK"], fromTopK);
  }
  const fromCandidateCount = getValueByPath(fromObject, [
    "candidateCount"
  ]);
  if (fromCandidateCount != null) {
    setValueByPath(toObject, ["candidateCount"], fromCandidateCount);
  }
  const fromMaxOutputTokens = getValueByPath(fromObject, [
    "maxOutputTokens"
  ]);
  if (fromMaxOutputTokens != null) {
    setValueByPath(toObject, ["maxOutputTokens"], fromMaxOutputTokens);
  }
  const fromStopSequences = getValueByPath(fromObject, [
    "stopSequences"
  ]);
  if (fromStopSequences != null) {
    setValueByPath(toObject, ["stopSequences"], fromStopSequences);
  }
  const fromResponseLogprobs = getValueByPath(fromObject, [
    "responseLogprobs"
  ]);
  if (fromResponseLogprobs != null) {
    setValueByPath(toObject, ["responseLogprobs"], fromResponseLogprobs);
  }
  const fromLogprobs = getValueByPath(fromObject, ["logprobs"]);
  if (fromLogprobs != null) {
    setValueByPath(toObject, ["logprobs"], fromLogprobs);
  }
  const fromPresencePenalty = getValueByPath(fromObject, [
    "presencePenalty"
  ]);
  if (fromPresencePenalty != null) {
    setValueByPath(toObject, ["presencePenalty"], fromPresencePenalty);
  }
  const fromFrequencyPenalty = getValueByPath(fromObject, [
    "frequencyPenalty"
  ]);
  if (fromFrequencyPenalty != null) {
    setValueByPath(toObject, ["frequencyPenalty"], fromFrequencyPenalty);
  }
  const fromSeed = getValueByPath(fromObject, ["seed"]);
  if (fromSeed != null) {
    setValueByPath(toObject, ["seed"], fromSeed);
  }
  const fromResponseMimeType = getValueByPath(fromObject, [
    "responseMimeType"
  ]);
  if (fromResponseMimeType != null) {
    setValueByPath(toObject, ["responseMimeType"], fromResponseMimeType);
  }
  const fromResponseSchema = getValueByPath(fromObject, [
    "responseSchema"
  ]);
  if (fromResponseSchema != null) {
    setValueByPath(toObject, ["responseSchema"], tSchema(fromResponseSchema));
  }
  const fromResponseJsonSchema = getValueByPath(fromObject, [
    "responseJsonSchema"
  ]);
  if (fromResponseJsonSchema != null) {
    setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema);
  }
  if (getValueByPath(fromObject, ["routingConfig"]) !== void 0) {
    throw new Error("routingConfig parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["modelSelectionConfig"]) !== void 0) {
    throw new Error("modelSelectionConfig parameter is not supported in Gemini API.");
  }
  const fromSafetySettings = getValueByPath(fromObject, [
    "safetySettings"
  ]);
  if (parentObject !== void 0 && fromSafetySettings != null) {
    let transformedList = fromSafetySettings;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return safetySettingToMldev$1(item);
      });
    }
    setValueByPath(parentObject, ["safetySettings"], transformedList);
  }
  const fromTools = getValueByPath(fromObject, ["tools"]);
  if (parentObject !== void 0 && fromTools != null) {
    let transformedList = tTools(fromTools);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return toolToMldev$4(tTool(item));
      });
    }
    setValueByPath(parentObject, ["tools"], transformedList);
  }
  const fromToolConfig = getValueByPath(fromObject, ["toolConfig"]);
  if (parentObject !== void 0 && fromToolConfig != null) {
    setValueByPath(parentObject, ["toolConfig"], toolConfigToMldev$2(fromToolConfig));
  }
  if (getValueByPath(fromObject, ["labels"]) !== void 0) {
    throw new Error("labels parameter is not supported in Gemini API.");
  }
  const fromCachedContent = getValueByPath(fromObject, [
    "cachedContent"
  ]);
  if (parentObject !== void 0 && fromCachedContent != null) {
    setValueByPath(parentObject, ["cachedContent"], tCachedContentName(apiClient, fromCachedContent));
  }
  const fromResponseModalities = getValueByPath(fromObject, [
    "responseModalities"
  ]);
  if (fromResponseModalities != null) {
    setValueByPath(toObject, ["responseModalities"], fromResponseModalities);
  }
  const fromMediaResolution = getValueByPath(fromObject, [
    "mediaResolution"
  ]);
  if (fromMediaResolution != null) {
    setValueByPath(toObject, ["mediaResolution"], fromMediaResolution);
  }
  const fromSpeechConfig = getValueByPath(fromObject, ["speechConfig"]);
  if (fromSpeechConfig != null) {
    setValueByPath(toObject, ["speechConfig"], tSpeechConfig(fromSpeechConfig));
  }
  if (getValueByPath(fromObject, ["audioTimestamp"]) !== void 0) {
    throw new Error("audioTimestamp parameter is not supported in Gemini API.");
  }
  const fromThinkingConfig = getValueByPath(fromObject, [
    "thinkingConfig"
  ]);
  if (fromThinkingConfig != null) {
    setValueByPath(toObject, ["thinkingConfig"], fromThinkingConfig);
  }
  const fromImageConfig = getValueByPath(fromObject, ["imageConfig"]);
  if (fromImageConfig != null) {
    setValueByPath(toObject, ["imageConfig"], imageConfigToMldev$1(fromImageConfig));
  }
  const fromEnableEnhancedCivicAnswers = getValueByPath(fromObject, [
    "enableEnhancedCivicAnswers"
  ]);
  if (fromEnableEnhancedCivicAnswers != null) {
    setValueByPath(toObject, ["enableEnhancedCivicAnswers"], fromEnableEnhancedCivicAnswers);
  }
  if (getValueByPath(fromObject, ["modelArmorConfig"]) !== void 0) {
    throw new Error("modelArmorConfig parameter is not supported in Gemini API.");
  }
  return toObject;
}
function generateContentResponseFromMldev$1(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromCandidates = getValueByPath(fromObject, ["candidates"]);
  if (fromCandidates != null) {
    let transformedList = fromCandidates;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return candidateFromMldev$1(item);
      });
    }
    setValueByPath(toObject, ["candidates"], transformedList);
  }
  const fromModelVersion = getValueByPath(fromObject, ["modelVersion"]);
  if (fromModelVersion != null) {
    setValueByPath(toObject, ["modelVersion"], fromModelVersion);
  }
  const fromPromptFeedback = getValueByPath(fromObject, [
    "promptFeedback"
  ]);
  if (fromPromptFeedback != null) {
    setValueByPath(toObject, ["promptFeedback"], fromPromptFeedback);
  }
  const fromResponseId = getValueByPath(fromObject, ["responseId"]);
  if (fromResponseId != null) {
    setValueByPath(toObject, ["responseId"], fromResponseId);
  }
  const fromUsageMetadata = getValueByPath(fromObject, [
    "usageMetadata"
  ]);
  if (fromUsageMetadata != null) {
    setValueByPath(toObject, ["usageMetadata"], fromUsageMetadata);
  }
  return toObject;
}
function getBatchJobParametersToMldev(apiClient, fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], tBatchJobName(apiClient, fromName));
  }
  return toObject;
}
function getBatchJobParametersToVertex(apiClient, fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], tBatchJobName(apiClient, fromName));
  }
  return toObject;
}
function googleMapsToMldev$4(fromObject) {
  const toObject = {};
  const fromAuthConfig = getValueByPath(fromObject, ["authConfig"]);
  if (fromAuthConfig != null) {
    setValueByPath(toObject, ["authConfig"], authConfigToMldev$4(fromAuthConfig));
  }
  const fromEnableWidget = getValueByPath(fromObject, ["enableWidget"]);
  if (fromEnableWidget != null) {
    setValueByPath(toObject, ["enableWidget"], fromEnableWidget);
  }
  return toObject;
}
function googleSearchToMldev$4(fromObject) {
  const toObject = {};
  const fromSearchTypes = getValueByPath(fromObject, ["searchTypes"]);
  if (fromSearchTypes != null) {
    setValueByPath(toObject, ["searchTypes"], fromSearchTypes);
  }
  if (getValueByPath(fromObject, ["blockingConfidence"]) !== void 0) {
    throw new Error("blockingConfidence parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["excludeDomains"]) !== void 0) {
    throw new Error("excludeDomains parameter is not supported in Gemini API.");
  }
  const fromTimeRangeFilter = getValueByPath(fromObject, [
    "timeRangeFilter"
  ]);
  if (fromTimeRangeFilter != null) {
    setValueByPath(toObject, ["timeRangeFilter"], fromTimeRangeFilter);
  }
  return toObject;
}
function imageConfigToMldev$1(fromObject) {
  const toObject = {};
  const fromAspectRatio = getValueByPath(fromObject, ["aspectRatio"]);
  if (fromAspectRatio != null) {
    setValueByPath(toObject, ["aspectRatio"], fromAspectRatio);
  }
  const fromImageSize = getValueByPath(fromObject, ["imageSize"]);
  if (fromImageSize != null) {
    setValueByPath(toObject, ["imageSize"], fromImageSize);
  }
  if (getValueByPath(fromObject, ["personGeneration"]) !== void 0) {
    throw new Error("personGeneration parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["prominentPeople"]) !== void 0) {
    throw new Error("prominentPeople parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["outputMimeType"]) !== void 0) {
    throw new Error("outputMimeType parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["outputCompressionQuality"]) !== void 0) {
    throw new Error("outputCompressionQuality parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["imageOutputOptions"]) !== void 0) {
    throw new Error("imageOutputOptions parameter is not supported in Gemini API.");
  }
  return toObject;
}
function inlinedRequestToMldev(apiClient, fromObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["request", "model"], tModel(apiClient, fromModel));
  }
  const fromContents = getValueByPath(fromObject, ["contents"]);
  if (fromContents != null) {
    let transformedList = tContents(fromContents);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return contentToMldev$4(item);
      });
    }
    setValueByPath(toObject, ["request", "contents"], transformedList);
  }
  const fromMetadata = getValueByPath(fromObject, ["metadata"]);
  if (fromMetadata != null) {
    setValueByPath(toObject, ["metadata"], fromMetadata);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["request", "generationConfig"], generateContentConfigToMldev$1(apiClient, fromConfig, getValueByPath(toObject, ["request"], {})));
  }
  return toObject;
}
function inlinedResponseFromMldev(fromObject) {
  const toObject = {};
  const fromResponse = getValueByPath(fromObject, ["response"]);
  if (fromResponse != null) {
    setValueByPath(toObject, ["response"], generateContentResponseFromMldev$1(fromResponse));
  }
  const fromMetadata = getValueByPath(fromObject, ["metadata"]);
  if (fromMetadata != null) {
    setValueByPath(toObject, ["metadata"], fromMetadata);
  }
  const fromError = getValueByPath(fromObject, ["error"]);
  if (fromError != null) {
    setValueByPath(toObject, ["error"], fromError);
  }
  return toObject;
}
function listBatchJobsConfigToMldev(fromObject, parentObject) {
  const toObject = {};
  const fromPageSize = getValueByPath(fromObject, ["pageSize"]);
  if (parentObject !== void 0 && fromPageSize != null) {
    setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize);
  }
  const fromPageToken = getValueByPath(fromObject, ["pageToken"]);
  if (parentObject !== void 0 && fromPageToken != null) {
    setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken);
  }
  if (getValueByPath(fromObject, ["filter"]) !== void 0) {
    throw new Error("filter parameter is not supported in Gemini API.");
  }
  return toObject;
}
function listBatchJobsConfigToVertex(fromObject, parentObject) {
  const toObject = {};
  const fromPageSize = getValueByPath(fromObject, ["pageSize"]);
  if (parentObject !== void 0 && fromPageSize != null) {
    setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize);
  }
  const fromPageToken = getValueByPath(fromObject, ["pageToken"]);
  if (parentObject !== void 0 && fromPageToken != null) {
    setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken);
  }
  const fromFilter = getValueByPath(fromObject, ["filter"]);
  if (parentObject !== void 0 && fromFilter != null) {
    setValueByPath(parentObject, ["_query", "filter"], fromFilter);
  }
  return toObject;
}
function listBatchJobsParametersToMldev(fromObject) {
  const toObject = {};
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    listBatchJobsConfigToMldev(fromConfig, toObject);
  }
  return toObject;
}
function listBatchJobsParametersToVertex(fromObject) {
  const toObject = {};
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    listBatchJobsConfigToVertex(fromConfig, toObject);
  }
  return toObject;
}
function listBatchJobsResponseFromMldev(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromNextPageToken = getValueByPath(fromObject, [
    "nextPageToken"
  ]);
  if (fromNextPageToken != null) {
    setValueByPath(toObject, ["nextPageToken"], fromNextPageToken);
  }
  const fromBatchJobs = getValueByPath(fromObject, ["operations"]);
  if (fromBatchJobs != null) {
    let transformedList = fromBatchJobs;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return batchJobFromMldev(item);
      });
    }
    setValueByPath(toObject, ["batchJobs"], transformedList);
  }
  return toObject;
}
function listBatchJobsResponseFromVertex(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromNextPageToken = getValueByPath(fromObject, [
    "nextPageToken"
  ]);
  if (fromNextPageToken != null) {
    setValueByPath(toObject, ["nextPageToken"], fromNextPageToken);
  }
  const fromBatchJobs = getValueByPath(fromObject, [
    "batchPredictionJobs"
  ]);
  if (fromBatchJobs != null) {
    let transformedList = fromBatchJobs;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return batchJobFromVertex(item);
      });
    }
    setValueByPath(toObject, ["batchJobs"], transformedList);
  }
  return toObject;
}
function partToMldev$4(fromObject) {
  const toObject = {};
  const fromMediaResolution = getValueByPath(fromObject, [
    "mediaResolution"
  ]);
  if (fromMediaResolution != null) {
    setValueByPath(toObject, ["mediaResolution"], fromMediaResolution);
  }
  const fromCodeExecutionResult = getValueByPath(fromObject, [
    "codeExecutionResult"
  ]);
  if (fromCodeExecutionResult != null) {
    setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult);
  }
  const fromExecutableCode = getValueByPath(fromObject, [
    "executableCode"
  ]);
  if (fromExecutableCode != null) {
    setValueByPath(toObject, ["executableCode"], fromExecutableCode);
  }
  const fromFileData = getValueByPath(fromObject, ["fileData"]);
  if (fromFileData != null) {
    setValueByPath(toObject, ["fileData"], fileDataToMldev$4(fromFileData));
  }
  const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]);
  if (fromFunctionCall != null) {
    setValueByPath(toObject, ["functionCall"], functionCallToMldev$4(fromFunctionCall));
  }
  const fromFunctionResponse = getValueByPath(fromObject, [
    "functionResponse"
  ]);
  if (fromFunctionResponse != null) {
    setValueByPath(toObject, ["functionResponse"], fromFunctionResponse);
  }
  const fromInlineData = getValueByPath(fromObject, ["inlineData"]);
  if (fromInlineData != null) {
    setValueByPath(toObject, ["inlineData"], blobToMldev$4(fromInlineData));
  }
  const fromText = getValueByPath(fromObject, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  const fromThought = getValueByPath(fromObject, ["thought"]);
  if (fromThought != null) {
    setValueByPath(toObject, ["thought"], fromThought);
  }
  const fromThoughtSignature = getValueByPath(fromObject, [
    "thoughtSignature"
  ]);
  if (fromThoughtSignature != null) {
    setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature);
  }
  const fromVideoMetadata = getValueByPath(fromObject, [
    "videoMetadata"
  ]);
  if (fromVideoMetadata != null) {
    setValueByPath(toObject, ["videoMetadata"], fromVideoMetadata);
  }
  return toObject;
}
function safetySettingToMldev$1(fromObject) {
  const toObject = {};
  const fromCategory = getValueByPath(fromObject, ["category"]);
  if (fromCategory != null) {
    setValueByPath(toObject, ["category"], fromCategory);
  }
  if (getValueByPath(fromObject, ["method"]) !== void 0) {
    throw new Error("method parameter is not supported in Gemini API.");
  }
  const fromThreshold = getValueByPath(fromObject, ["threshold"]);
  if (fromThreshold != null) {
    setValueByPath(toObject, ["threshold"], fromThreshold);
  }
  return toObject;
}
function toolConfigToMldev$2(fromObject) {
  const toObject = {};
  const fromRetrievalConfig = getValueByPath(fromObject, [
    "retrievalConfig"
  ]);
  if (fromRetrievalConfig != null) {
    setValueByPath(toObject, ["retrievalConfig"], fromRetrievalConfig);
  }
  const fromFunctionCallingConfig = getValueByPath(fromObject, [
    "functionCallingConfig"
  ]);
  if (fromFunctionCallingConfig != null) {
    setValueByPath(toObject, ["functionCallingConfig"], functionCallingConfigToMldev$2(fromFunctionCallingConfig));
  }
  return toObject;
}
function toolToMldev$4(fromObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["retrieval"]) !== void 0) {
    throw new Error("retrieval parameter is not supported in Gemini API.");
  }
  const fromComputerUse = getValueByPath(fromObject, ["computerUse"]);
  if (fromComputerUse != null) {
    setValueByPath(toObject, ["computerUse"], fromComputerUse);
  }
  const fromFileSearch = getValueByPath(fromObject, ["fileSearch"]);
  if (fromFileSearch != null) {
    setValueByPath(toObject, ["fileSearch"], fromFileSearch);
  }
  const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]);
  if (fromGoogleSearch != null) {
    setValueByPath(toObject, ["googleSearch"], googleSearchToMldev$4(fromGoogleSearch));
  }
  const fromGoogleMaps = getValueByPath(fromObject, ["googleMaps"]);
  if (fromGoogleMaps != null) {
    setValueByPath(toObject, ["googleMaps"], googleMapsToMldev$4(fromGoogleMaps));
  }
  const fromCodeExecution = getValueByPath(fromObject, [
    "codeExecution"
  ]);
  if (fromCodeExecution != null) {
    setValueByPath(toObject, ["codeExecution"], fromCodeExecution);
  }
  if (getValueByPath(fromObject, ["enterpriseWebSearch"]) !== void 0) {
    throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");
  }
  const fromFunctionDeclarations = getValueByPath(fromObject, [
    "functionDeclarations"
  ]);
  if (fromFunctionDeclarations != null) {
    let transformedList = fromFunctionDeclarations;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["functionDeclarations"], transformedList);
  }
  const fromGoogleSearchRetrieval = getValueByPath(fromObject, [
    "googleSearchRetrieval"
  ]);
  if (fromGoogleSearchRetrieval != null) {
    setValueByPath(toObject, ["googleSearchRetrieval"], fromGoogleSearchRetrieval);
  }
  if (getValueByPath(fromObject, ["parallelAiSearch"]) !== void 0) {
    throw new Error("parallelAiSearch parameter is not supported in Gemini API.");
  }
  const fromUrlContext = getValueByPath(fromObject, ["urlContext"]);
  if (fromUrlContext != null) {
    setValueByPath(toObject, ["urlContext"], fromUrlContext);
  }
  const fromMcpServers = getValueByPath(fromObject, ["mcpServers"]);
  if (fromMcpServers != null) {
    let transformedList = fromMcpServers;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["mcpServers"], transformedList);
  }
  return toObject;
}
var PagedItem;
(function(PagedItem2) {
  PagedItem2["PAGED_ITEM_BATCH_JOBS"] = "batchJobs";
  PagedItem2["PAGED_ITEM_MODELS"] = "models";
  PagedItem2["PAGED_ITEM_TUNING_JOBS"] = "tuningJobs";
  PagedItem2["PAGED_ITEM_FILES"] = "files";
  PagedItem2["PAGED_ITEM_CACHED_CONTENTS"] = "cachedContents";
  PagedItem2["PAGED_ITEM_FILE_SEARCH_STORES"] = "fileSearchStores";
  PagedItem2["PAGED_ITEM_DOCUMENTS"] = "documents";
})(PagedItem || (PagedItem = {}));
var Pager = class {
  constructor(name, request, response, params) {
    this.pageInternal = [];
    this.paramsInternal = {};
    this.requestInternal = request;
    this.init(name, response, params);
  }
  init(name, response, params) {
    var _a7, _b;
    this.nameInternal = name;
    this.pageInternal = response[this.nameInternal] || [];
    this.sdkHttpResponseInternal = response === null || response === void 0 ? void 0 : response.sdkHttpResponse;
    this.idxInternal = 0;
    let requestParams = { config: {} };
    if (!params || Object.keys(params).length === 0) {
      requestParams = { config: {} };
    } else if (typeof params === "object") {
      requestParams = Object.assign({}, params);
    } else {
      requestParams = params;
    }
    if (requestParams["config"]) {
      requestParams["config"]["pageToken"] = response["nextPageToken"];
    }
    this.paramsInternal = requestParams;
    this.pageInternalSize = (_b = (_a7 = requestParams["config"]) === null || _a7 === void 0 ? void 0 : _a7["pageSize"]) !== null && _b !== void 0 ? _b : this.pageInternal.length;
  }
  initNextPage(response) {
    this.init(this.nameInternal, response, this.paramsInternal);
  }
  /**
   * Returns the current page, which is a list of items.
   *
   * @remarks
   * The first page is retrieved when the pager is created. The returned list of
   * items could be a subset of the entire list.
   */
  get page() {
    return this.pageInternal;
  }
  /**
   * Returns the type of paged item (for example, ``batch_jobs``).
   */
  get name() {
    return this.nameInternal;
  }
  /**
   * Returns the length of the page fetched each time by this pager.
   *
   * @remarks
   * The number of items in the page is less than or equal to the page length.
   */
  get pageSize() {
    return this.pageInternalSize;
  }
  /**
   * Returns the headers of the API response.
   */
  get sdkHttpResponse() {
    return this.sdkHttpResponseInternal;
  }
  /**
   * Returns the parameters when making the API request for the next page.
   *
   * @remarks
   * Parameters contain a set of optional configs that can be
   * used to customize the API request. For example, the `pageToken` parameter
   * contains the token to request the next page.
   */
  get params() {
    return this.paramsInternal;
  }
  /**
   * Returns the total number of items in the current page.
   */
  get pageLength() {
    return this.pageInternal.length;
  }
  /**
   * Returns the item at the given index.
   */
  getItem(index) {
    return this.pageInternal[index];
  }
  /**
   * Returns an async iterator that support iterating through all items
   * retrieved from the API.
   *
   * @remarks
   * The iterator will automatically fetch the next page if there are more items
   * to fetch from the API.
   *
   * @example
   *
   * ```ts
   * const pager = await ai.files.list({config: {pageSize: 10}});
   * for await (const file of pager) {
   *   console.log(file.name);
   * }
   * ```
   */
  [Symbol.asyncIterator]() {
    return {
      next: async () => {
        if (this.idxInternal >= this.pageLength) {
          if (this.hasNextPage()) {
            await this.nextPage();
          } else {
            return { value: void 0, done: true };
          }
        }
        const item = this.getItem(this.idxInternal);
        this.idxInternal += 1;
        return { value: item, done: false };
      },
      return: async () => {
        return { value: void 0, done: true };
      }
    };
  }
  /**
   * Fetches the next page of items. This makes a new API request.
   *
   * @throws {Error} If there are no more pages to fetch.
   *
   * @example
   *
   * ```ts
   * const pager = await ai.files.list({config: {pageSize: 10}});
   * let page = pager.page;
   * while (true) {
   *   for (const file of page) {
   *     console.log(file.name);
   *   }
   *   if (!pager.hasNextPage()) {
   *     break;
   *   }
   *   page = await pager.nextPage();
   * }
   * ```
   */
  async nextPage() {
    if (!this.hasNextPage()) {
      throw new Error("No more pages to fetch.");
    }
    const response = await this.requestInternal(this.params);
    this.initNextPage(response);
    return this.page;
  }
  /**
   * Returns true if there are more pages to fetch from the API.
   */
  hasNextPage() {
    var _a7;
    if (((_a7 = this.params["config"]) === null || _a7 === void 0 ? void 0 : _a7["pageToken"]) !== void 0) {
      return true;
    }
    return false;
  }
};
var Batches4 = class extends BaseModule {
  constructor(apiClient) {
    super();
    this.apiClient = apiClient;
    this.list = async (params = {}) => {
      return new Pager(PagedItem.PAGED_ITEM_BATCH_JOBS, (x2) => this.listInternal(x2), await this.listInternal(params), params);
    };
    this.create = async (params) => {
      if (this.apiClient.isVertexAI()) {
        params.config = this.formatDestination(params.src, params.config);
      }
      return this.createInternal(params);
    };
    this.createEmbeddings = async (params) => {
      console.warn("batches.createEmbeddings() is experimental and may change without notice.");
      if (this.apiClient.isVertexAI()) {
        throw new Error("Vertex AI does not support batches.createEmbeddings.");
      }
      return this.createEmbeddingsInternal(params);
    };
  }
  // Helper function to handle inlined generate content requests
  createInlinedGenerateContentRequest(params) {
    const body = createBatchJobParametersToMldev(
      this.apiClient,
      // Use instance apiClient
      params
    );
    const urlParams = body["_url"];
    const path6 = formatMap("{model}:batchGenerateContent", urlParams);
    const batch = body["batch"];
    const inputConfig = batch["inputConfig"];
    const requestsWrapper = inputConfig["requests"];
    const requests = requestsWrapper["requests"];
    const newRequests = [];
    for (const request of requests) {
      const requestDict = Object.assign({}, request);
      if (requestDict["systemInstruction"]) {
        const systemInstructionValue = requestDict["systemInstruction"];
        delete requestDict["systemInstruction"];
        const requestContent = requestDict["request"];
        requestContent["systemInstruction"] = systemInstructionValue;
        requestDict["request"] = requestContent;
      }
      newRequests.push(requestDict);
    }
    requestsWrapper["requests"] = newRequests;
    delete body["config"];
    delete body["_url"];
    delete body["_query"];
    return { path: path6, body };
  }
  // Helper function to get the first GCS URI
  getGcsUri(src) {
    if (typeof src === "string") {
      return src.startsWith("gs://") ? src : void 0;
    }
    if (!Array.isArray(src) && src.gcsUri && src.gcsUri.length > 0) {
      return src.gcsUri[0];
    }
    return void 0;
  }
  // Helper function to get the BigQuery URI
  getBigqueryUri(src) {
    if (typeof src === "string") {
      return src.startsWith("bq://") ? src : void 0;
    }
    if (!Array.isArray(src)) {
      return src.bigqueryUri;
    }
    return void 0;
  }
  // Function to format the destination configuration for Vertex AI
  formatDestination(src, config) {
    const newConfig = config ? Object.assign({}, config) : {};
    const timestampStr = Date.now().toString();
    if (!newConfig.displayName) {
      newConfig.displayName = `genaiBatchJob_${timestampStr}`;
    }
    if (newConfig.dest === void 0) {
      const gcsUri = this.getGcsUri(src);
      const bigqueryUri = this.getBigqueryUri(src);
      if (gcsUri) {
        if (gcsUri.endsWith(".jsonl")) {
          newConfig.dest = `${gcsUri.slice(0, -6)}/dest`;
        } else {
          newConfig.dest = `${gcsUri}_dest_${timestampStr}`;
        }
      } else if (bigqueryUri) {
        newConfig.dest = `${bigqueryUri}_dest_${timestampStr}`;
      } else {
        throw new Error("Unsupported source for Vertex AI: No GCS or BigQuery URI found.");
      }
    }
    return newConfig;
  }
  /**
   * Internal method to create batch job.
   *
   * @param params - The parameters for create batch job request.
   * @return The created batch job.
   *
   */
  async createInternal(params) {
    var _a7, _b, _c, _d;
    let response;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = createBatchJobParametersToVertex(this.apiClient, params);
      path6 = formatMap("batchPredictionJobs", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((apiResponse) => {
        const resp = batchJobFromVertex(apiResponse);
        return resp;
      });
    } else {
      const body = createBatchJobParametersToMldev(this.apiClient, params);
      path6 = formatMap("{model}:batchGenerateContent", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,
        abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((apiResponse) => {
        const resp = batchJobFromMldev(apiResponse);
        return resp;
      });
    }
  }
  /**
   * Internal method to create batch job.
   *
   * @param params - The parameters for create batch job request.
   * @return The created batch job.
   *
   */
  async createEmbeddingsInternal(params) {
    var _a7, _b;
    let response;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      throw new Error("This method is only supported by the Gemini Developer API.");
    } else {
      const body = createEmbeddingsBatchJobParametersToMldev(this.apiClient, params);
      path6 = formatMap("{model}:asyncBatchEmbedContent", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((apiResponse) => {
        const resp = batchJobFromMldev(apiResponse);
        return resp;
      });
    }
  }
  /**
   * Gets batch job configurations.
   *
   * @param params - The parameters for the get request.
   * @return The batch job.
   *
   * @example
   * ```ts
   * await ai.batches.get({name: '...'}); // The server-generated resource name.
   * ```
   */
  async get(params) {
    var _a7, _b, _c, _d;
    let response;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = getBatchJobParametersToVertex(this.apiClient, params);
      path6 = formatMap("batchPredictionJobs/{name}", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "GET",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((apiResponse) => {
        const resp = batchJobFromVertex(apiResponse);
        return resp;
      });
    } else {
      const body = getBatchJobParametersToMldev(this.apiClient, params);
      path6 = formatMap("batches/{name}", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "GET",
        httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,
        abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((apiResponse) => {
        const resp = batchJobFromMldev(apiResponse);
        return resp;
      });
    }
  }
  /**
   * Cancels a batch job.
   *
   * @param params - The parameters for the cancel request.
   * @return The empty response returned by the API.
   *
   * @example
   * ```ts
   * await ai.batches.cancel({name: '...'}); // The server-generated resource name.
   * ```
   */
  async cancel(params) {
    var _a7, _b, _c, _d;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = cancelBatchJobParametersToVertex(this.apiClient, params);
      path6 = formatMap("batchPredictionJobs/{name}:cancel", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      await this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      });
    } else {
      const body = cancelBatchJobParametersToMldev(this.apiClient, params);
      path6 = formatMap("batches/{name}:cancel", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      await this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,
        abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
      });
    }
  }
  async listInternal(params) {
    var _a7, _b, _c, _d;
    let response;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = listBatchJobsParametersToVertex(params);
      path6 = formatMap("batchPredictionJobs", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "GET",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = listBatchJobsResponseFromVertex(apiResponse);
        const typedResp = new ListBatchJobsResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    } else {
      const body = listBatchJobsParametersToMldev(params);
      path6 = formatMap("batches", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "GET",
        httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,
        abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = listBatchJobsResponseFromMldev(apiResponse);
        const typedResp = new ListBatchJobsResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    }
  }
  /**
   * Deletes a batch job.
   *
   * @param params - The parameters for the delete request.
   * @return The empty response returned by the API.
   *
   * @example
   * ```ts
   * await ai.batches.delete({name: '...'}); // The server-generated resource name.
   * ```
   */
  async delete(params) {
    var _a7, _b, _c, _d;
    let response;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = deleteBatchJobParametersToVertex(this.apiClient, params);
      path6 = formatMap("batchPredictionJobs/{name}", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "DELETE",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = deleteResourceJobFromVertex(apiResponse);
        return resp;
      });
    } else {
      const body = deleteBatchJobParametersToMldev(this.apiClient, params);
      path6 = formatMap("batches/{name}", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "DELETE",
        httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,
        abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = deleteResourceJobFromMldev(apiResponse);
        return resp;
      });
    }
  }
};
function authConfigToMldev$3(fromObject) {
  const toObject = {};
  const fromApiKey = getValueByPath(fromObject, ["apiKey"]);
  if (fromApiKey != null) {
    setValueByPath(toObject, ["apiKey"], fromApiKey);
  }
  if (getValueByPath(fromObject, ["apiKeyConfig"]) !== void 0) {
    throw new Error("apiKeyConfig parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["authType"]) !== void 0) {
    throw new Error("authType parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["googleServiceAccountConfig"]) !== void 0) {
    throw new Error("googleServiceAccountConfig parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["httpBasicAuthConfig"]) !== void 0) {
    throw new Error("httpBasicAuthConfig parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["oauthConfig"]) !== void 0) {
    throw new Error("oauthConfig parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["oidcConfig"]) !== void 0) {
    throw new Error("oidcConfig parameter is not supported in Gemini API.");
  }
  return toObject;
}
function blobToMldev$3(fromObject) {
  const toObject = {};
  const fromData = getValueByPath(fromObject, ["data"]);
  if (fromData != null) {
    setValueByPath(toObject, ["data"], fromData);
  }
  if (getValueByPath(fromObject, ["displayName"]) !== void 0) {
    throw new Error("displayName parameter is not supported in Gemini API.");
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function contentToMldev$3(fromObject) {
  const toObject = {};
  const fromParts = getValueByPath(fromObject, ["parts"]);
  if (fromParts != null) {
    let transformedList = fromParts;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return partToMldev$3(item);
      });
    }
    setValueByPath(toObject, ["parts"], transformedList);
  }
  const fromRole = getValueByPath(fromObject, ["role"]);
  if (fromRole != null) {
    setValueByPath(toObject, ["role"], fromRole);
  }
  return toObject;
}
function createCachedContentConfigToMldev(fromObject, parentObject) {
  const toObject = {};
  const fromTtl = getValueByPath(fromObject, ["ttl"]);
  if (parentObject !== void 0 && fromTtl != null) {
    setValueByPath(parentObject, ["ttl"], fromTtl);
  }
  const fromExpireTime = getValueByPath(fromObject, ["expireTime"]);
  if (parentObject !== void 0 && fromExpireTime != null) {
    setValueByPath(parentObject, ["expireTime"], fromExpireTime);
  }
  const fromDisplayName = getValueByPath(fromObject, ["displayName"]);
  if (parentObject !== void 0 && fromDisplayName != null) {
    setValueByPath(parentObject, ["displayName"], fromDisplayName);
  }
  const fromContents = getValueByPath(fromObject, ["contents"]);
  if (parentObject !== void 0 && fromContents != null) {
    let transformedList = tContents(fromContents);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return contentToMldev$3(item);
      });
    }
    setValueByPath(parentObject, ["contents"], transformedList);
  }
  const fromSystemInstruction = getValueByPath(fromObject, [
    "systemInstruction"
  ]);
  if (parentObject !== void 0 && fromSystemInstruction != null) {
    setValueByPath(parentObject, ["systemInstruction"], contentToMldev$3(tContent(fromSystemInstruction)));
  }
  const fromTools = getValueByPath(fromObject, ["tools"]);
  if (parentObject !== void 0 && fromTools != null) {
    let transformedList = fromTools;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return toolToMldev$3(item);
      });
    }
    setValueByPath(parentObject, ["tools"], transformedList);
  }
  const fromToolConfig = getValueByPath(fromObject, ["toolConfig"]);
  if (parentObject !== void 0 && fromToolConfig != null) {
    setValueByPath(parentObject, ["toolConfig"], toolConfigToMldev$1(fromToolConfig));
  }
  if (getValueByPath(fromObject, ["kmsKeyName"]) !== void 0) {
    throw new Error("kmsKeyName parameter is not supported in Gemini API.");
  }
  return toObject;
}
function createCachedContentConfigToVertex(fromObject, parentObject) {
  const toObject = {};
  const fromTtl = getValueByPath(fromObject, ["ttl"]);
  if (parentObject !== void 0 && fromTtl != null) {
    setValueByPath(parentObject, ["ttl"], fromTtl);
  }
  const fromExpireTime = getValueByPath(fromObject, ["expireTime"]);
  if (parentObject !== void 0 && fromExpireTime != null) {
    setValueByPath(parentObject, ["expireTime"], fromExpireTime);
  }
  const fromDisplayName = getValueByPath(fromObject, ["displayName"]);
  if (parentObject !== void 0 && fromDisplayName != null) {
    setValueByPath(parentObject, ["displayName"], fromDisplayName);
  }
  const fromContents = getValueByPath(fromObject, ["contents"]);
  if (parentObject !== void 0 && fromContents != null) {
    let transformedList = tContents(fromContents);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(parentObject, ["contents"], transformedList);
  }
  const fromSystemInstruction = getValueByPath(fromObject, [
    "systemInstruction"
  ]);
  if (parentObject !== void 0 && fromSystemInstruction != null) {
    setValueByPath(parentObject, ["systemInstruction"], tContent(fromSystemInstruction));
  }
  const fromTools = getValueByPath(fromObject, ["tools"]);
  if (parentObject !== void 0 && fromTools != null) {
    let transformedList = fromTools;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return toolToVertex$2(item);
      });
    }
    setValueByPath(parentObject, ["tools"], transformedList);
  }
  const fromToolConfig = getValueByPath(fromObject, ["toolConfig"]);
  if (parentObject !== void 0 && fromToolConfig != null) {
    setValueByPath(parentObject, ["toolConfig"], fromToolConfig);
  }
  const fromKmsKeyName = getValueByPath(fromObject, ["kmsKeyName"]);
  if (parentObject !== void 0 && fromKmsKeyName != null) {
    setValueByPath(parentObject, ["encryption_spec", "kmsKeyName"], fromKmsKeyName);
  }
  return toObject;
}
function createCachedContentParametersToMldev(apiClient, fromObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["model"], tCachesModel(apiClient, fromModel));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    createCachedContentConfigToMldev(fromConfig, toObject);
  }
  return toObject;
}
function createCachedContentParametersToVertex(apiClient, fromObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["model"], tCachesModel(apiClient, fromModel));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    createCachedContentConfigToVertex(fromConfig, toObject);
  }
  return toObject;
}
function deleteCachedContentParametersToMldev(apiClient, fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], tCachedContentName(apiClient, fromName));
  }
  return toObject;
}
function deleteCachedContentParametersToVertex(apiClient, fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], tCachedContentName(apiClient, fromName));
  }
  return toObject;
}
function deleteCachedContentResponseFromMldev(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  return toObject;
}
function deleteCachedContentResponseFromVertex(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  return toObject;
}
function fileDataToMldev$3(fromObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["displayName"]) !== void 0) {
    throw new Error("displayName parameter is not supported in Gemini API.");
  }
  const fromFileUri = getValueByPath(fromObject, ["fileUri"]);
  if (fromFileUri != null) {
    setValueByPath(toObject, ["fileUri"], fromFileUri);
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function functionCallToMldev$3(fromObject) {
  const toObject = {};
  const fromId = getValueByPath(fromObject, ["id"]);
  if (fromId != null) {
    setValueByPath(toObject, ["id"], fromId);
  }
  const fromArgs = getValueByPath(fromObject, ["args"]);
  if (fromArgs != null) {
    setValueByPath(toObject, ["args"], fromArgs);
  }
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  if (getValueByPath(fromObject, ["partialArgs"]) !== void 0) {
    throw new Error("partialArgs parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["willContinue"]) !== void 0) {
    throw new Error("willContinue parameter is not supported in Gemini API.");
  }
  return toObject;
}
function functionCallingConfigToMldev$1(fromObject) {
  const toObject = {};
  const fromAllowedFunctionNames = getValueByPath(fromObject, [
    "allowedFunctionNames"
  ]);
  if (fromAllowedFunctionNames != null) {
    setValueByPath(toObject, ["allowedFunctionNames"], fromAllowedFunctionNames);
  }
  const fromMode = getValueByPath(fromObject, ["mode"]);
  if (fromMode != null) {
    setValueByPath(toObject, ["mode"], fromMode);
  }
  if (getValueByPath(fromObject, ["streamFunctionCallArguments"]) !== void 0) {
    throw new Error("streamFunctionCallArguments parameter is not supported in Gemini API.");
  }
  return toObject;
}
function functionDeclarationToVertex$2(fromObject) {
  const toObject = {};
  const fromDescription = getValueByPath(fromObject, ["description"]);
  if (fromDescription != null) {
    setValueByPath(toObject, ["description"], fromDescription);
  }
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromParameters = getValueByPath(fromObject, ["parameters"]);
  if (fromParameters != null) {
    setValueByPath(toObject, ["parameters"], fromParameters);
  }
  const fromParametersJsonSchema = getValueByPath(fromObject, [
    "parametersJsonSchema"
  ]);
  if (fromParametersJsonSchema != null) {
    setValueByPath(toObject, ["parametersJsonSchema"], fromParametersJsonSchema);
  }
  const fromResponse = getValueByPath(fromObject, ["response"]);
  if (fromResponse != null) {
    setValueByPath(toObject, ["response"], fromResponse);
  }
  const fromResponseJsonSchema = getValueByPath(fromObject, [
    "responseJsonSchema"
  ]);
  if (fromResponseJsonSchema != null) {
    setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema);
  }
  if (getValueByPath(fromObject, ["behavior"]) !== void 0) {
    throw new Error("behavior parameter is not supported in Vertex AI.");
  }
  return toObject;
}
function getCachedContentParametersToMldev(apiClient, fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], tCachedContentName(apiClient, fromName));
  }
  return toObject;
}
function getCachedContentParametersToVertex(apiClient, fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], tCachedContentName(apiClient, fromName));
  }
  return toObject;
}
function googleMapsToMldev$3(fromObject) {
  const toObject = {};
  const fromAuthConfig = getValueByPath(fromObject, ["authConfig"]);
  if (fromAuthConfig != null) {
    setValueByPath(toObject, ["authConfig"], authConfigToMldev$3(fromAuthConfig));
  }
  const fromEnableWidget = getValueByPath(fromObject, ["enableWidget"]);
  if (fromEnableWidget != null) {
    setValueByPath(toObject, ["enableWidget"], fromEnableWidget);
  }
  return toObject;
}
function googleSearchToMldev$3(fromObject) {
  const toObject = {};
  const fromSearchTypes = getValueByPath(fromObject, ["searchTypes"]);
  if (fromSearchTypes != null) {
    setValueByPath(toObject, ["searchTypes"], fromSearchTypes);
  }
  if (getValueByPath(fromObject, ["blockingConfidence"]) !== void 0) {
    throw new Error("blockingConfidence parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["excludeDomains"]) !== void 0) {
    throw new Error("excludeDomains parameter is not supported in Gemini API.");
  }
  const fromTimeRangeFilter = getValueByPath(fromObject, [
    "timeRangeFilter"
  ]);
  if (fromTimeRangeFilter != null) {
    setValueByPath(toObject, ["timeRangeFilter"], fromTimeRangeFilter);
  }
  return toObject;
}
function listCachedContentsConfigToMldev(fromObject, parentObject) {
  const toObject = {};
  const fromPageSize = getValueByPath(fromObject, ["pageSize"]);
  if (parentObject !== void 0 && fromPageSize != null) {
    setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize);
  }
  const fromPageToken = getValueByPath(fromObject, ["pageToken"]);
  if (parentObject !== void 0 && fromPageToken != null) {
    setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken);
  }
  return toObject;
}
function listCachedContentsConfigToVertex(fromObject, parentObject) {
  const toObject = {};
  const fromPageSize = getValueByPath(fromObject, ["pageSize"]);
  if (parentObject !== void 0 && fromPageSize != null) {
    setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize);
  }
  const fromPageToken = getValueByPath(fromObject, ["pageToken"]);
  if (parentObject !== void 0 && fromPageToken != null) {
    setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken);
  }
  return toObject;
}
function listCachedContentsParametersToMldev(fromObject) {
  const toObject = {};
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    listCachedContentsConfigToMldev(fromConfig, toObject);
  }
  return toObject;
}
function listCachedContentsParametersToVertex(fromObject) {
  const toObject = {};
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    listCachedContentsConfigToVertex(fromConfig, toObject);
  }
  return toObject;
}
function listCachedContentsResponseFromMldev(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromNextPageToken = getValueByPath(fromObject, [
    "nextPageToken"
  ]);
  if (fromNextPageToken != null) {
    setValueByPath(toObject, ["nextPageToken"], fromNextPageToken);
  }
  const fromCachedContents = getValueByPath(fromObject, [
    "cachedContents"
  ]);
  if (fromCachedContents != null) {
    let transformedList = fromCachedContents;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["cachedContents"], transformedList);
  }
  return toObject;
}
function listCachedContentsResponseFromVertex(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromNextPageToken = getValueByPath(fromObject, [
    "nextPageToken"
  ]);
  if (fromNextPageToken != null) {
    setValueByPath(toObject, ["nextPageToken"], fromNextPageToken);
  }
  const fromCachedContents = getValueByPath(fromObject, [
    "cachedContents"
  ]);
  if (fromCachedContents != null) {
    let transformedList = fromCachedContents;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["cachedContents"], transformedList);
  }
  return toObject;
}
function partToMldev$3(fromObject) {
  const toObject = {};
  const fromMediaResolution = getValueByPath(fromObject, [
    "mediaResolution"
  ]);
  if (fromMediaResolution != null) {
    setValueByPath(toObject, ["mediaResolution"], fromMediaResolution);
  }
  const fromCodeExecutionResult = getValueByPath(fromObject, [
    "codeExecutionResult"
  ]);
  if (fromCodeExecutionResult != null) {
    setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult);
  }
  const fromExecutableCode = getValueByPath(fromObject, [
    "executableCode"
  ]);
  if (fromExecutableCode != null) {
    setValueByPath(toObject, ["executableCode"], fromExecutableCode);
  }
  const fromFileData = getValueByPath(fromObject, ["fileData"]);
  if (fromFileData != null) {
    setValueByPath(toObject, ["fileData"], fileDataToMldev$3(fromFileData));
  }
  const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]);
  if (fromFunctionCall != null) {
    setValueByPath(toObject, ["functionCall"], functionCallToMldev$3(fromFunctionCall));
  }
  const fromFunctionResponse = getValueByPath(fromObject, [
    "functionResponse"
  ]);
  if (fromFunctionResponse != null) {
    setValueByPath(toObject, ["functionResponse"], fromFunctionResponse);
  }
  const fromInlineData = getValueByPath(fromObject, ["inlineData"]);
  if (fromInlineData != null) {
    setValueByPath(toObject, ["inlineData"], blobToMldev$3(fromInlineData));
  }
  const fromText = getValueByPath(fromObject, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  const fromThought = getValueByPath(fromObject, ["thought"]);
  if (fromThought != null) {
    setValueByPath(toObject, ["thought"], fromThought);
  }
  const fromThoughtSignature = getValueByPath(fromObject, [
    "thoughtSignature"
  ]);
  if (fromThoughtSignature != null) {
    setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature);
  }
  const fromVideoMetadata = getValueByPath(fromObject, [
    "videoMetadata"
  ]);
  if (fromVideoMetadata != null) {
    setValueByPath(toObject, ["videoMetadata"], fromVideoMetadata);
  }
  return toObject;
}
function toolConfigToMldev$1(fromObject) {
  const toObject = {};
  const fromRetrievalConfig = getValueByPath(fromObject, [
    "retrievalConfig"
  ]);
  if (fromRetrievalConfig != null) {
    setValueByPath(toObject, ["retrievalConfig"], fromRetrievalConfig);
  }
  const fromFunctionCallingConfig = getValueByPath(fromObject, [
    "functionCallingConfig"
  ]);
  if (fromFunctionCallingConfig != null) {
    setValueByPath(toObject, ["functionCallingConfig"], functionCallingConfigToMldev$1(fromFunctionCallingConfig));
  }
  return toObject;
}
function toolToMldev$3(fromObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["retrieval"]) !== void 0) {
    throw new Error("retrieval parameter is not supported in Gemini API.");
  }
  const fromComputerUse = getValueByPath(fromObject, ["computerUse"]);
  if (fromComputerUse != null) {
    setValueByPath(toObject, ["computerUse"], fromComputerUse);
  }
  const fromFileSearch = getValueByPath(fromObject, ["fileSearch"]);
  if (fromFileSearch != null) {
    setValueByPath(toObject, ["fileSearch"], fromFileSearch);
  }
  const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]);
  if (fromGoogleSearch != null) {
    setValueByPath(toObject, ["googleSearch"], googleSearchToMldev$3(fromGoogleSearch));
  }
  const fromGoogleMaps = getValueByPath(fromObject, ["googleMaps"]);
  if (fromGoogleMaps != null) {
    setValueByPath(toObject, ["googleMaps"], googleMapsToMldev$3(fromGoogleMaps));
  }
  const fromCodeExecution = getValueByPath(fromObject, [
    "codeExecution"
  ]);
  if (fromCodeExecution != null) {
    setValueByPath(toObject, ["codeExecution"], fromCodeExecution);
  }
  if (getValueByPath(fromObject, ["enterpriseWebSearch"]) !== void 0) {
    throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");
  }
  const fromFunctionDeclarations = getValueByPath(fromObject, [
    "functionDeclarations"
  ]);
  if (fromFunctionDeclarations != null) {
    let transformedList = fromFunctionDeclarations;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["functionDeclarations"], transformedList);
  }
  const fromGoogleSearchRetrieval = getValueByPath(fromObject, [
    "googleSearchRetrieval"
  ]);
  if (fromGoogleSearchRetrieval != null) {
    setValueByPath(toObject, ["googleSearchRetrieval"], fromGoogleSearchRetrieval);
  }
  if (getValueByPath(fromObject, ["parallelAiSearch"]) !== void 0) {
    throw new Error("parallelAiSearch parameter is not supported in Gemini API.");
  }
  const fromUrlContext = getValueByPath(fromObject, ["urlContext"]);
  if (fromUrlContext != null) {
    setValueByPath(toObject, ["urlContext"], fromUrlContext);
  }
  const fromMcpServers = getValueByPath(fromObject, ["mcpServers"]);
  if (fromMcpServers != null) {
    let transformedList = fromMcpServers;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["mcpServers"], transformedList);
  }
  return toObject;
}
function toolToVertex$2(fromObject) {
  const toObject = {};
  const fromRetrieval = getValueByPath(fromObject, ["retrieval"]);
  if (fromRetrieval != null) {
    setValueByPath(toObject, ["retrieval"], fromRetrieval);
  }
  const fromComputerUse = getValueByPath(fromObject, ["computerUse"]);
  if (fromComputerUse != null) {
    setValueByPath(toObject, ["computerUse"], fromComputerUse);
  }
  if (getValueByPath(fromObject, ["fileSearch"]) !== void 0) {
    throw new Error("fileSearch parameter is not supported in Vertex AI.");
  }
  const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]);
  if (fromGoogleSearch != null) {
    setValueByPath(toObject, ["googleSearch"], fromGoogleSearch);
  }
  const fromGoogleMaps = getValueByPath(fromObject, ["googleMaps"]);
  if (fromGoogleMaps != null) {
    setValueByPath(toObject, ["googleMaps"], fromGoogleMaps);
  }
  const fromCodeExecution = getValueByPath(fromObject, [
    "codeExecution"
  ]);
  if (fromCodeExecution != null) {
    setValueByPath(toObject, ["codeExecution"], fromCodeExecution);
  }
  const fromEnterpriseWebSearch = getValueByPath(fromObject, [
    "enterpriseWebSearch"
  ]);
  if (fromEnterpriseWebSearch != null) {
    setValueByPath(toObject, ["enterpriseWebSearch"], fromEnterpriseWebSearch);
  }
  const fromFunctionDeclarations = getValueByPath(fromObject, [
    "functionDeclarations"
  ]);
  if (fromFunctionDeclarations != null) {
    let transformedList = fromFunctionDeclarations;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return functionDeclarationToVertex$2(item);
      });
    }
    setValueByPath(toObject, ["functionDeclarations"], transformedList);
  }
  const fromGoogleSearchRetrieval = getValueByPath(fromObject, [
    "googleSearchRetrieval"
  ]);
  if (fromGoogleSearchRetrieval != null) {
    setValueByPath(toObject, ["googleSearchRetrieval"], fromGoogleSearchRetrieval);
  }
  const fromParallelAiSearch = getValueByPath(fromObject, [
    "parallelAiSearch"
  ]);
  if (fromParallelAiSearch != null) {
    setValueByPath(toObject, ["parallelAiSearch"], fromParallelAiSearch);
  }
  const fromUrlContext = getValueByPath(fromObject, ["urlContext"]);
  if (fromUrlContext != null) {
    setValueByPath(toObject, ["urlContext"], fromUrlContext);
  }
  if (getValueByPath(fromObject, ["mcpServers"]) !== void 0) {
    throw new Error("mcpServers parameter is not supported in Vertex AI.");
  }
  return toObject;
}
function updateCachedContentConfigToMldev(fromObject, parentObject) {
  const toObject = {};
  const fromTtl = getValueByPath(fromObject, ["ttl"]);
  if (parentObject !== void 0 && fromTtl != null) {
    setValueByPath(parentObject, ["ttl"], fromTtl);
  }
  const fromExpireTime = getValueByPath(fromObject, ["expireTime"]);
  if (parentObject !== void 0 && fromExpireTime != null) {
    setValueByPath(parentObject, ["expireTime"], fromExpireTime);
  }
  return toObject;
}
function updateCachedContentConfigToVertex(fromObject, parentObject) {
  const toObject = {};
  const fromTtl = getValueByPath(fromObject, ["ttl"]);
  if (parentObject !== void 0 && fromTtl != null) {
    setValueByPath(parentObject, ["ttl"], fromTtl);
  }
  const fromExpireTime = getValueByPath(fromObject, ["expireTime"]);
  if (parentObject !== void 0 && fromExpireTime != null) {
    setValueByPath(parentObject, ["expireTime"], fromExpireTime);
  }
  return toObject;
}
function updateCachedContentParametersToMldev(apiClient, fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], tCachedContentName(apiClient, fromName));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    updateCachedContentConfigToMldev(fromConfig, toObject);
  }
  return toObject;
}
function updateCachedContentParametersToVertex(apiClient, fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], tCachedContentName(apiClient, fromName));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    updateCachedContentConfigToVertex(fromConfig, toObject);
  }
  return toObject;
}
var Caches = class extends BaseModule {
  constructor(apiClient) {
    super();
    this.apiClient = apiClient;
    this.list = async (params = {}) => {
      return new Pager(PagedItem.PAGED_ITEM_CACHED_CONTENTS, (x2) => this.listInternal(x2), await this.listInternal(params), params);
    };
  }
  /**
   * Creates a cached contents resource.
   *
   * @remarks
   * Context caching is only supported for specific models. See [Gemini
   * Developer API reference](https://ai.google.dev/gemini-api/docs/caching?lang=node/context-cac)
   * and [Vertex AI reference](https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview#supported_models)
   * for more information.
   *
   * @param params - The parameters for the create request.
   * @return The created cached content.
   *
   * @example
   * ```ts
   * const contents = ...; // Initialize the content to cache.
   * const response = await ai.caches.create({
   *   model: 'gemini-2.0-flash-001',
   *   config: {
   *    'contents': contents,
   *    'displayName': 'test cache',
   *    'systemInstruction': 'What is the sum of the two pdfs?',
   *    'ttl': '86400s',
   *  }
   * });
   * ```
   */
  async create(params) {
    var _a7, _b, _c, _d;
    let response;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = createCachedContentParametersToVertex(this.apiClient, params);
      path6 = formatMap("cachedContents", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((resp) => {
        return resp;
      });
    } else {
      const body = createCachedContentParametersToMldev(this.apiClient, params);
      path6 = formatMap("cachedContents", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,
        abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((resp) => {
        return resp;
      });
    }
  }
  /**
   * Gets cached content configurations.
   *
   * @param params - The parameters for the get request.
   * @return The cached content.
   *
   * @example
   * ```ts
   * await ai.caches.get({name: '...'}); // The server-generated resource name.
   * ```
   */
  async get(params) {
    var _a7, _b, _c, _d;
    let response;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = getCachedContentParametersToVertex(this.apiClient, params);
      path6 = formatMap("{name}", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "GET",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((resp) => {
        return resp;
      });
    } else {
      const body = getCachedContentParametersToMldev(this.apiClient, params);
      path6 = formatMap("{name}", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "GET",
        httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,
        abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((resp) => {
        return resp;
      });
    }
  }
  /**
   * Deletes cached content.
   *
   * @param params - The parameters for the delete request.
   * @return The empty response returned by the API.
   *
   * @example
   * ```ts
   * await ai.caches.delete({name: '...'}); // The server-generated resource name.
   * ```
   */
  async delete(params) {
    var _a7, _b, _c, _d;
    let response;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = deleteCachedContentParametersToVertex(this.apiClient, params);
      path6 = formatMap("{name}", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "DELETE",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = deleteCachedContentResponseFromVertex(apiResponse);
        const typedResp = new DeleteCachedContentResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    } else {
      const body = deleteCachedContentParametersToMldev(this.apiClient, params);
      path6 = formatMap("{name}", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "DELETE",
        httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,
        abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = deleteCachedContentResponseFromMldev(apiResponse);
        const typedResp = new DeleteCachedContentResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    }
  }
  /**
   * Updates cached content configurations.
   *
   * @param params - The parameters for the update request.
   * @return The updated cached content.
   *
   * @example
   * ```ts
   * const response = await ai.caches.update({
   *   name: '...',  // The server-generated resource name.
   *   config: {'ttl': '7600s'}
   * });
   * ```
   */
  async update(params) {
    var _a7, _b, _c, _d;
    let response;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = updateCachedContentParametersToVertex(this.apiClient, params);
      path6 = formatMap("{name}", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "PATCH",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((resp) => {
        return resp;
      });
    } else {
      const body = updateCachedContentParametersToMldev(this.apiClient, params);
      path6 = formatMap("{name}", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "PATCH",
        httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,
        abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((resp) => {
        return resp;
      });
    }
  }
  async listInternal(params) {
    var _a7, _b, _c, _d;
    let response;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = listCachedContentsParametersToVertex(params);
      path6 = formatMap("cachedContents", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "GET",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = listCachedContentsResponseFromVertex(apiResponse);
        const typedResp = new ListCachedContentsResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    } else {
      const body = listCachedContentsParametersToMldev(params);
      path6 = formatMap("cachedContents", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "GET",
        httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,
        abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = listCachedContentsResponseFromMldev(apiResponse);
        const typedResp = new ListCachedContentsResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    }
  }
};
function __rest(s6, e9) {
  var t6 = {};
  for (var p4 in s6) if (Object.prototype.hasOwnProperty.call(s6, p4) && e9.indexOf(p4) < 0)
    t6[p4] = s6[p4];
  if (s6 != null && typeof Object.getOwnPropertySymbols === "function")
    for (var i7 = 0, p4 = Object.getOwnPropertySymbols(s6); i7 < p4.length; i7++) {
      if (e9.indexOf(p4[i7]) < 0 && Object.prototype.propertyIsEnumerable.call(s6, p4[i7]))
        t6[p4[i7]] = s6[p4[i7]];
    }
  return t6;
}
function __values(o9) {
  var s6 = typeof Symbol === "function" && Symbol.iterator, m4 = s6 && o9[s6], i7 = 0;
  if (m4) return m4.call(o9);
  if (o9 && typeof o9.length === "number") return {
    next: function() {
      if (o9 && i7 >= o9.length) o9 = void 0;
      return { value: o9 && o9[i7++], done: !o9 };
    }
  };
  throw new TypeError(s6 ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __await(v4) {
  return this instanceof __await ? (this.v = v4, this) : new __await(v4);
}
function __asyncGenerator(thisArg, _arguments, generator) {
  if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  var g3 = generator.apply(thisArg, _arguments || []), i7, q2 = [];
  return i7 = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i7[Symbol.asyncIterator] = function() {
    return this;
  }, i7;
  function awaitReturn(f4) {
    return function(v4) {
      return Promise.resolve(v4).then(f4, reject);
    };
  }
  function verb(n7, f4) {
    if (g3[n7]) {
      i7[n7] = function(v4) {
        return new Promise(function(a3, b4) {
          q2.push([n7, v4, a3, b4]) > 1 || resume(n7, v4);
        });
      };
      if (f4) i7[n7] = f4(i7[n7]);
    }
  }
  function resume(n7, v4) {
    try {
      step(g3[n7](v4));
    } catch (e9) {
      settle(q2[0][3], e9);
    }
  }
  function step(r8) {
    r8.value instanceof __await ? Promise.resolve(r8.value.v).then(fulfill, reject) : settle(q2[0][2], r8);
  }
  function fulfill(value) {
    resume("next", value);
  }
  function reject(value) {
    resume("throw", value);
  }
  function settle(f4, v4) {
    if (f4(v4), q2.shift(), q2.length) resume(q2[0][0], q2[0][1]);
  }
}
function __asyncValues(o9) {
  if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  var m4 = o9[Symbol.asyncIterator], i7;
  return m4 ? m4.call(o9) : (o9 = typeof __values === "function" ? __values(o9) : o9[Symbol.iterator](), i7 = {}, verb("next"), verb("throw"), verb("return"), i7[Symbol.asyncIterator] = function() {
    return this;
  }, i7);
  function verb(n7) {
    i7[n7] = o9[n7] && function(v4) {
      return new Promise(function(resolve, reject) {
        v4 = o9[n7](v4), settle(resolve, reject, v4.done, v4.value);
      });
    };
  }
  function settle(resolve, reject, d4, v4) {
    Promise.resolve(v4).then(function(v5) {
      resolve({ value: v5, done: d4 });
    }, reject);
  }
}
function isValidResponse(response) {
  var _a7;
  if (response.candidates == void 0 || response.candidates.length === 0) {
    return false;
  }
  const content = (_a7 = response.candidates[0]) === null || _a7 === void 0 ? void 0 : _a7.content;
  if (content === void 0) {
    return false;
  }
  return isValidContent(content);
}
function isValidContent(content) {
  if (content.parts === void 0 || content.parts.length === 0) {
    return false;
  }
  for (const part of content.parts) {
    if (part === void 0 || Object.keys(part).length === 0) {
      return false;
    }
  }
  return true;
}
function validateHistory(history) {
  if (history.length === 0) {
    return;
  }
  for (const content of history) {
    if (content.role !== "user" && content.role !== "model") {
      throw new Error(`Role must be user or model, but got ${content.role}.`);
    }
  }
}
function extractCuratedHistory(comprehensiveHistory) {
  if (comprehensiveHistory === void 0 || comprehensiveHistory.length === 0) {
    return [];
  }
  const curatedHistory = [];
  const length = comprehensiveHistory.length;
  let i7 = 0;
  while (i7 < length) {
    if (comprehensiveHistory[i7].role === "user") {
      curatedHistory.push(comprehensiveHistory[i7]);
      i7++;
    } else {
      const modelOutput = [];
      let isValid3 = true;
      while (i7 < length && comprehensiveHistory[i7].role === "model") {
        modelOutput.push(comprehensiveHistory[i7]);
        if (isValid3 && !isValidContent(comprehensiveHistory[i7])) {
          isValid3 = false;
        }
        i7++;
      }
      if (isValid3) {
        curatedHistory.push(...modelOutput);
      } else {
        curatedHistory.pop();
      }
    }
  }
  return curatedHistory;
}
var Chats = class {
  constructor(modelsModule, apiClient) {
    this.modelsModule = modelsModule;
    this.apiClient = apiClient;
  }
  /**
   * Creates a new chat session.
   *
   * @remarks
   * The config in the params will be used for all requests within the chat
   * session unless overridden by a per-request `config` in
   * @see {@link types.SendMessageParameters#config}.
   *
   * @param params - Parameters for creating a chat session.
   * @returns A new chat session.
   *
   * @example
   * ```ts
   * const chat = ai.chats.create({
   *   model: 'gemini-2.0-flash'
   *   config: {
   *     temperature: 0.5,
   *     maxOutputTokens: 1024,
   *   }
   * });
   * ```
   */
  create(params) {
    return new Chat2(
      this.apiClient,
      this.modelsModule,
      params.model,
      params.config,
      // Deep copy the history to avoid mutating the history outside of the
      // chat session.
      structuredClone(params.history)
    );
  }
};
var Chat2 = class {
  constructor(apiClient, modelsModule, model, config = {}, history = []) {
    this.apiClient = apiClient;
    this.modelsModule = modelsModule;
    this.model = model;
    this.config = config;
    this.history = history;
    this.sendPromise = Promise.resolve();
    validateHistory(history);
  }
  /**
   * Sends a message to the model and returns the response.
   *
   * @remarks
   * This method will wait for the previous message to be processed before
   * sending the next message.
   *
   * @see {@link Chat#sendMessageStream} for streaming method.
   * @param params - parameters for sending messages within a chat session.
   * @returns The model's response.
   *
   * @example
   * ```ts
   * const chat = ai.chats.create({model: 'gemini-2.0-flash'});
   * const response = await chat.sendMessage({
   *   message: 'Why is the sky blue?'
   * });
   * console.log(response.text);
   * ```
   */
  async sendMessage(params) {
    var _a7;
    await this.sendPromise;
    const inputContent = tContent(params.message);
    const responsePromise = this.modelsModule.generateContent({
      model: this.model,
      contents: this.getHistory(true).concat(inputContent),
      config: (_a7 = params.config) !== null && _a7 !== void 0 ? _a7 : this.config
    });
    this.sendPromise = (async () => {
      var _a8, _b, _c;
      const response = await responsePromise;
      const outputContent = (_b = (_a8 = response.candidates) === null || _a8 === void 0 ? void 0 : _a8[0]) === null || _b === void 0 ? void 0 : _b.content;
      const fullAutomaticFunctionCallingHistory = response.automaticFunctionCallingHistory;
      const index = this.getHistory(true).length;
      let automaticFunctionCallingHistory = [];
      if (fullAutomaticFunctionCallingHistory != null) {
        automaticFunctionCallingHistory = (_c = fullAutomaticFunctionCallingHistory.slice(index)) !== null && _c !== void 0 ? _c : [];
      }
      const modelOutput = outputContent ? [outputContent] : [];
      this.recordHistory(inputContent, modelOutput, automaticFunctionCallingHistory);
      return;
    })();
    await this.sendPromise.catch(() => {
      this.sendPromise = Promise.resolve();
    });
    return responsePromise;
  }
  /**
   * Sends a message to the model and returns the response in chunks.
   *
   * @remarks
   * This method will wait for the previous message to be processed before
   * sending the next message.
   *
   * @see {@link Chat#sendMessage} for non-streaming method.
   * @param params - parameters for sending the message.
   * @return The model's response.
   *
   * @example
   * ```ts
   * const chat = ai.chats.create({model: 'gemini-2.0-flash'});
   * const response = await chat.sendMessageStream({
   *   message: 'Why is the sky blue?'
   * });
   * for await (const chunk of response) {
   *   console.log(chunk.text);
   * }
   * ```
   */
  async sendMessageStream(params) {
    var _a7;
    await this.sendPromise;
    const inputContent = tContent(params.message);
    const streamResponse = this.modelsModule.generateContentStream({
      model: this.model,
      contents: this.getHistory(true).concat(inputContent),
      config: (_a7 = params.config) !== null && _a7 !== void 0 ? _a7 : this.config
    });
    this.sendPromise = streamResponse.then(() => void 0).catch(() => void 0);
    const response = await streamResponse;
    const result = this.processStreamResponse(response, inputContent);
    return result;
  }
  /**
   * Returns the chat history.
   *
   * @remarks
   * The history is a list of contents alternating between user and model.
   *
   * There are two types of history:
   * - The `curated history` contains only the valid turns between user and
   * model, which will be included in the subsequent requests sent to the model.
   * - The `comprehensive history` contains all turns, including invalid or
   *   empty model outputs, providing a complete record of the history.
   *
   * The history is updated after receiving the response from the model,
   * for streaming response, it means receiving the last chunk of the response.
   *
   * The `comprehensive history` is returned by default. To get the `curated
   * history`, set the `curated` parameter to `true`.
   *
   * @param curated - whether to return the curated history or the comprehensive
   *     history.
   * @return History contents alternating between user and model for the entire
   *     chat session.
   */
  getHistory(curated = false) {
    const history = curated ? extractCuratedHistory(this.history) : this.history;
    return structuredClone(history);
  }
  processStreamResponse(streamResponse, inputContent) {
    return __asyncGenerator(this, arguments, function* processStreamResponse_1() {
      var _a7, e_1, _b, _c;
      var _d, _e2;
      const outputContent = [];
      try {
        for (var _f = true, streamResponse_1 = __asyncValues(streamResponse), streamResponse_1_1; streamResponse_1_1 = yield __await(streamResponse_1.next()), _a7 = streamResponse_1_1.done, !_a7; _f = true) {
          _c = streamResponse_1_1.value;
          _f = false;
          const chunk = _c;
          if (isValidResponse(chunk)) {
            const content = (_e2 = (_d = chunk.candidates) === null || _d === void 0 ? void 0 : _d[0]) === null || _e2 === void 0 ? void 0 : _e2.content;
            if (content !== void 0) {
              outputContent.push(content);
            }
          }
          yield yield __await(chunk);
        }
      } catch (e_1_1) {
        e_1 = { error: e_1_1 };
      } finally {
        try {
          if (!_f && !_a7 && (_b = streamResponse_1.return)) yield __await(_b.call(streamResponse_1));
        } finally {
          if (e_1) throw e_1.error;
        }
      }
      this.recordHistory(inputContent, outputContent);
    });
  }
  recordHistory(userInput, modelOutput, automaticFunctionCallingHistory) {
    let outputContents = [];
    if (modelOutput.length > 0 && modelOutput.every((content) => content.role !== void 0)) {
      outputContents = modelOutput;
    } else {
      outputContents.push({
        role: "model",
        parts: []
      });
    }
    if (automaticFunctionCallingHistory && automaticFunctionCallingHistory.length > 0) {
      this.history.push(...extractCuratedHistory(automaticFunctionCallingHistory));
    } else {
      this.history.push(userInput);
    }
    this.history.push(...outputContents);
  }
};
var ApiError = class _ApiError extends Error {
  constructor(options) {
    super(options.message);
    this.name = "ApiError";
    this.status = options.status;
    Object.setPrototypeOf(this, _ApiError.prototype);
  }
};
function createFileParametersToMldev(fromObject) {
  const toObject = {};
  const fromFile = getValueByPath(fromObject, ["file"]);
  if (fromFile != null) {
    setValueByPath(toObject, ["file"], fromFile);
  }
  return toObject;
}
function createFileResponseFromMldev(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  return toObject;
}
function deleteFileParametersToMldev(fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "file"], tFileName(fromName));
  }
  return toObject;
}
function deleteFileResponseFromMldev(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  return toObject;
}
function getFileParametersToMldev(fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "file"], tFileName(fromName));
  }
  return toObject;
}
function internalRegisterFilesParametersToMldev(fromObject) {
  const toObject = {};
  const fromUris = getValueByPath(fromObject, ["uris"]);
  if (fromUris != null) {
    setValueByPath(toObject, ["uris"], fromUris);
  }
  return toObject;
}
function listFilesConfigToMldev(fromObject, parentObject) {
  const toObject = {};
  const fromPageSize = getValueByPath(fromObject, ["pageSize"]);
  if (parentObject !== void 0 && fromPageSize != null) {
    setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize);
  }
  const fromPageToken = getValueByPath(fromObject, ["pageToken"]);
  if (parentObject !== void 0 && fromPageToken != null) {
    setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken);
  }
  return toObject;
}
function listFilesParametersToMldev(fromObject) {
  const toObject = {};
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    listFilesConfigToMldev(fromConfig, toObject);
  }
  return toObject;
}
function listFilesResponseFromMldev(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromNextPageToken = getValueByPath(fromObject, [
    "nextPageToken"
  ]);
  if (fromNextPageToken != null) {
    setValueByPath(toObject, ["nextPageToken"], fromNextPageToken);
  }
  const fromFiles = getValueByPath(fromObject, ["files"]);
  if (fromFiles != null) {
    let transformedList = fromFiles;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["files"], transformedList);
  }
  return toObject;
}
function registerFilesResponseFromMldev(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromFiles = getValueByPath(fromObject, ["files"]);
  if (fromFiles != null) {
    let transformedList = fromFiles;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["files"], transformedList);
  }
  return toObject;
}
var Files5 = class extends BaseModule {
  constructor(apiClient) {
    super();
    this.apiClient = apiClient;
    this.list = async (params = {}) => {
      return new Pager(PagedItem.PAGED_ITEM_FILES, (x2) => this.listInternal(x2), await this.listInternal(params), params);
    };
  }
  /**
   * Uploads a file asynchronously to the Gemini API.
   * This method is not available in Vertex AI.
   * Supported upload sources:
   * - Node.js: File path (string) or Blob object.
   * - Browser: Blob object (e.g., File).
   *
   * @remarks
   * The `mimeType` can be specified in the `config` parameter. If omitted:
   *  - For file path (string) inputs, the `mimeType` will be inferred from the
   *     file extension.
   *  - For Blob object inputs, the `mimeType` will be set to the Blob's `type`
   *     property.
   * Somex eamples for file extension to mimeType mapping:
   * .txt -> text/plain
   * .json -> application/json
   * .jpg  -> image/jpeg
   * .png -> image/png
   * .mp3 -> audio/mpeg
   * .mp4 -> video/mp4
   *
   * This section can contain multiple paragraphs and code examples.
   *
   * @param params - Optional parameters specified in the
   *        `types.UploadFileParameters` interface.
   *         @see {@link types.UploadFileParameters#config} for the optional
   *         config in the parameters.
   * @return A promise that resolves to a `types.File` object.
   * @throws An error if called on a Vertex AI client.
   * @throws An error if the `mimeType` is not provided and can not be inferred,
   * the `mimeType` can be provided in the `params.config` parameter.
   * @throws An error occurs if a suitable upload location cannot be established.
   *
   * @example
   * The following code uploads a file to Gemini API.
   *
   * ```ts
   * const file = await ai.files.upload({file: 'file.txt', config: {
   *   mimeType: 'text/plain',
   * }});
   * console.log(file.name);
   * ```
   */
  async upload(params) {
    if (this.apiClient.isVertexAI()) {
      throw new Error("Vertex AI does not support uploading files. You can share files through a GCS bucket.");
    }
    return this.apiClient.uploadFile(params.file, params.config).then((resp) => {
      return resp;
    });
  }
  /**
   * Downloads a remotely stored file asynchronously to a location specified in
   * the `params` object. This method only works on Node environment, to
   * download files in the browser, use a browser compliant method like an <a>
   * tag.
   *
   * @param params - The parameters for the download request.
   *
   * @example
   * The following code downloads an example file named "files/mehozpxf877d" as
   * "file.txt".
   *
   * ```ts
   * await ai.files.download({file: file.name, downloadPath: 'file.txt'});
   * ```
   */
  async download(params) {
    await this.apiClient.downloadFile(params);
  }
  /**
   * Registers Google Cloud Storage files for use with the API.
   * This method is only available in Node.js environments.
   */
  async registerFiles(params) {
    throw new Error("registerFiles is only supported in Node.js environments.");
  }
  async _registerFiles(params) {
    return this.registerFilesInternal(params);
  }
  async listInternal(params) {
    var _a7, _b;
    let response;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      throw new Error("This method is only supported by the Gemini Developer API.");
    } else {
      const body = listFilesParametersToMldev(params);
      path6 = formatMap("files", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "GET",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = listFilesResponseFromMldev(apiResponse);
        const typedResp = new ListFilesResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    }
  }
  async createInternal(params) {
    var _a7, _b;
    let response;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      throw new Error("This method is only supported by the Gemini Developer API.");
    } else {
      const body = createFileParametersToMldev(params);
      path6 = formatMap("upload/v1beta/files", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((apiResponse) => {
        const resp = createFileResponseFromMldev(apiResponse);
        const typedResp = new CreateFileResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    }
  }
  /**
   * Retrieves the file information from the service.
   *
   * @param params - The parameters for the get request
   * @return The Promise that resolves to the types.File object requested.
   *
   * @example
   * ```ts
   * const config: GetFileParameters = {
   *   name: fileName,
   * };
   * file = await ai.files.get(config);
   * console.log(file.name);
   * ```
   */
  async get(params) {
    var _a7, _b;
    let response;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      throw new Error("This method is only supported by the Gemini Developer API.");
    } else {
      const body = getFileParametersToMldev(params);
      path6 = formatMap("files/{file}", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "GET",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((resp) => {
        return resp;
      });
    }
  }
  /**
   * Deletes a remotely stored file.
   *
   * @param params - The parameters for the delete request.
   * @return The DeleteFileResponse, the response for the delete method.
   *
   * @example
   * The following code deletes an example file named "files/mehozpxf877d".
   *
   * ```ts
   * await ai.files.delete({name: file.name});
   * ```
   */
  async delete(params) {
    var _a7, _b;
    let response;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      throw new Error("This method is only supported by the Gemini Developer API.");
    } else {
      const body = deleteFileParametersToMldev(params);
      path6 = formatMap("files/{file}", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "DELETE",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = deleteFileResponseFromMldev(apiResponse);
        const typedResp = new DeleteFileResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    }
  }
  async registerFilesInternal(params) {
    var _a7, _b;
    let response;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      throw new Error("This method is only supported by the Gemini Developer API.");
    } else {
      const body = internalRegisterFilesParametersToMldev(params);
      path6 = formatMap("files:register", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((apiResponse) => {
        const resp = registerFilesResponseFromMldev(apiResponse);
        const typedResp = new RegisterFilesResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    }
  }
};
function audioTranscriptionConfigToMldev$1(fromObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["languageCodes"]) !== void 0) {
    throw new Error("languageCodes parameter is not supported in Gemini API.");
  }
  return toObject;
}
function authConfigToMldev$2(fromObject) {
  const toObject = {};
  const fromApiKey = getValueByPath(fromObject, ["apiKey"]);
  if (fromApiKey != null) {
    setValueByPath(toObject, ["apiKey"], fromApiKey);
  }
  if (getValueByPath(fromObject, ["apiKeyConfig"]) !== void 0) {
    throw new Error("apiKeyConfig parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["authType"]) !== void 0) {
    throw new Error("authType parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["googleServiceAccountConfig"]) !== void 0) {
    throw new Error("googleServiceAccountConfig parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["httpBasicAuthConfig"]) !== void 0) {
    throw new Error("httpBasicAuthConfig parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["oauthConfig"]) !== void 0) {
    throw new Error("oauthConfig parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["oidcConfig"]) !== void 0) {
    throw new Error("oidcConfig parameter is not supported in Gemini API.");
  }
  return toObject;
}
function blobToMldev$2(fromObject) {
  const toObject = {};
  const fromData = getValueByPath(fromObject, ["data"]);
  if (fromData != null) {
    setValueByPath(toObject, ["data"], fromData);
  }
  if (getValueByPath(fromObject, ["displayName"]) !== void 0) {
    throw new Error("displayName parameter is not supported in Gemini API.");
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function contentToMldev$2(fromObject) {
  const toObject = {};
  const fromParts = getValueByPath(fromObject, ["parts"]);
  if (fromParts != null) {
    let transformedList = fromParts;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return partToMldev$2(item);
      });
    }
    setValueByPath(toObject, ["parts"], transformedList);
  }
  const fromRole = getValueByPath(fromObject, ["role"]);
  if (fromRole != null) {
    setValueByPath(toObject, ["role"], fromRole);
  }
  return toObject;
}
function fileDataToMldev$2(fromObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["displayName"]) !== void 0) {
    throw new Error("displayName parameter is not supported in Gemini API.");
  }
  const fromFileUri = getValueByPath(fromObject, ["fileUri"]);
  if (fromFileUri != null) {
    setValueByPath(toObject, ["fileUri"], fromFileUri);
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function functionCallToMldev$2(fromObject) {
  const toObject = {};
  const fromId = getValueByPath(fromObject, ["id"]);
  if (fromId != null) {
    setValueByPath(toObject, ["id"], fromId);
  }
  const fromArgs = getValueByPath(fromObject, ["args"]);
  if (fromArgs != null) {
    setValueByPath(toObject, ["args"], fromArgs);
  }
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  if (getValueByPath(fromObject, ["partialArgs"]) !== void 0) {
    throw new Error("partialArgs parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["willContinue"]) !== void 0) {
    throw new Error("willContinue parameter is not supported in Gemini API.");
  }
  return toObject;
}
function functionDeclarationToVertex$1(fromObject) {
  const toObject = {};
  const fromDescription = getValueByPath(fromObject, ["description"]);
  if (fromDescription != null) {
    setValueByPath(toObject, ["description"], fromDescription);
  }
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromParameters = getValueByPath(fromObject, ["parameters"]);
  if (fromParameters != null) {
    setValueByPath(toObject, ["parameters"], fromParameters);
  }
  const fromParametersJsonSchema = getValueByPath(fromObject, [
    "parametersJsonSchema"
  ]);
  if (fromParametersJsonSchema != null) {
    setValueByPath(toObject, ["parametersJsonSchema"], fromParametersJsonSchema);
  }
  const fromResponse = getValueByPath(fromObject, ["response"]);
  if (fromResponse != null) {
    setValueByPath(toObject, ["response"], fromResponse);
  }
  const fromResponseJsonSchema = getValueByPath(fromObject, [
    "responseJsonSchema"
  ]);
  if (fromResponseJsonSchema != null) {
    setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema);
  }
  if (getValueByPath(fromObject, ["behavior"]) !== void 0) {
    throw new Error("behavior parameter is not supported in Vertex AI.");
  }
  return toObject;
}
function generationConfigToVertex$1(fromObject) {
  const toObject = {};
  const fromModelSelectionConfig = getValueByPath(fromObject, [
    "modelSelectionConfig"
  ]);
  if (fromModelSelectionConfig != null) {
    setValueByPath(toObject, ["modelConfig"], fromModelSelectionConfig);
  }
  const fromResponseJsonSchema = getValueByPath(fromObject, [
    "responseJsonSchema"
  ]);
  if (fromResponseJsonSchema != null) {
    setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema);
  }
  const fromAudioTimestamp = getValueByPath(fromObject, [
    "audioTimestamp"
  ]);
  if (fromAudioTimestamp != null) {
    setValueByPath(toObject, ["audioTimestamp"], fromAudioTimestamp);
  }
  const fromCandidateCount = getValueByPath(fromObject, [
    "candidateCount"
  ]);
  if (fromCandidateCount != null) {
    setValueByPath(toObject, ["candidateCount"], fromCandidateCount);
  }
  const fromEnableAffectiveDialog = getValueByPath(fromObject, [
    "enableAffectiveDialog"
  ]);
  if (fromEnableAffectiveDialog != null) {
    setValueByPath(toObject, ["enableAffectiveDialog"], fromEnableAffectiveDialog);
  }
  const fromFrequencyPenalty = getValueByPath(fromObject, [
    "frequencyPenalty"
  ]);
  if (fromFrequencyPenalty != null) {
    setValueByPath(toObject, ["frequencyPenalty"], fromFrequencyPenalty);
  }
  const fromLogprobs = getValueByPath(fromObject, ["logprobs"]);
  if (fromLogprobs != null) {
    setValueByPath(toObject, ["logprobs"], fromLogprobs);
  }
  const fromMaxOutputTokens = getValueByPath(fromObject, [
    "maxOutputTokens"
  ]);
  if (fromMaxOutputTokens != null) {
    setValueByPath(toObject, ["maxOutputTokens"], fromMaxOutputTokens);
  }
  const fromMediaResolution = getValueByPath(fromObject, [
    "mediaResolution"
  ]);
  if (fromMediaResolution != null) {
    setValueByPath(toObject, ["mediaResolution"], fromMediaResolution);
  }
  const fromPresencePenalty = getValueByPath(fromObject, [
    "presencePenalty"
  ]);
  if (fromPresencePenalty != null) {
    setValueByPath(toObject, ["presencePenalty"], fromPresencePenalty);
  }
  const fromResponseLogprobs = getValueByPath(fromObject, [
    "responseLogprobs"
  ]);
  if (fromResponseLogprobs != null) {
    setValueByPath(toObject, ["responseLogprobs"], fromResponseLogprobs);
  }
  const fromResponseMimeType = getValueByPath(fromObject, [
    "responseMimeType"
  ]);
  if (fromResponseMimeType != null) {
    setValueByPath(toObject, ["responseMimeType"], fromResponseMimeType);
  }
  const fromResponseModalities = getValueByPath(fromObject, [
    "responseModalities"
  ]);
  if (fromResponseModalities != null) {
    setValueByPath(toObject, ["responseModalities"], fromResponseModalities);
  }
  const fromResponseSchema = getValueByPath(fromObject, [
    "responseSchema"
  ]);
  if (fromResponseSchema != null) {
    setValueByPath(toObject, ["responseSchema"], fromResponseSchema);
  }
  const fromRoutingConfig = getValueByPath(fromObject, [
    "routingConfig"
  ]);
  if (fromRoutingConfig != null) {
    setValueByPath(toObject, ["routingConfig"], fromRoutingConfig);
  }
  const fromSeed = getValueByPath(fromObject, ["seed"]);
  if (fromSeed != null) {
    setValueByPath(toObject, ["seed"], fromSeed);
  }
  const fromSpeechConfig = getValueByPath(fromObject, ["speechConfig"]);
  if (fromSpeechConfig != null) {
    setValueByPath(toObject, ["speechConfig"], fromSpeechConfig);
  }
  const fromStopSequences = getValueByPath(fromObject, [
    "stopSequences"
  ]);
  if (fromStopSequences != null) {
    setValueByPath(toObject, ["stopSequences"], fromStopSequences);
  }
  const fromTemperature = getValueByPath(fromObject, ["temperature"]);
  if (fromTemperature != null) {
    setValueByPath(toObject, ["temperature"], fromTemperature);
  }
  const fromThinkingConfig = getValueByPath(fromObject, [
    "thinkingConfig"
  ]);
  if (fromThinkingConfig != null) {
    setValueByPath(toObject, ["thinkingConfig"], fromThinkingConfig);
  }
  const fromTopK = getValueByPath(fromObject, ["topK"]);
  if (fromTopK != null) {
    setValueByPath(toObject, ["topK"], fromTopK);
  }
  const fromTopP = getValueByPath(fromObject, ["topP"]);
  if (fromTopP != null) {
    setValueByPath(toObject, ["topP"], fromTopP);
  }
  if (getValueByPath(fromObject, ["enableEnhancedCivicAnswers"]) !== void 0) {
    throw new Error("enableEnhancedCivicAnswers parameter is not supported in Vertex AI.");
  }
  return toObject;
}
function googleMapsToMldev$2(fromObject) {
  const toObject = {};
  const fromAuthConfig = getValueByPath(fromObject, ["authConfig"]);
  if (fromAuthConfig != null) {
    setValueByPath(toObject, ["authConfig"], authConfigToMldev$2(fromAuthConfig));
  }
  const fromEnableWidget = getValueByPath(fromObject, ["enableWidget"]);
  if (fromEnableWidget != null) {
    setValueByPath(toObject, ["enableWidget"], fromEnableWidget);
  }
  return toObject;
}
function googleSearchToMldev$2(fromObject) {
  const toObject = {};
  const fromSearchTypes = getValueByPath(fromObject, ["searchTypes"]);
  if (fromSearchTypes != null) {
    setValueByPath(toObject, ["searchTypes"], fromSearchTypes);
  }
  if (getValueByPath(fromObject, ["blockingConfidence"]) !== void 0) {
    throw new Error("blockingConfidence parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["excludeDomains"]) !== void 0) {
    throw new Error("excludeDomains parameter is not supported in Gemini API.");
  }
  const fromTimeRangeFilter = getValueByPath(fromObject, [
    "timeRangeFilter"
  ]);
  if (fromTimeRangeFilter != null) {
    setValueByPath(toObject, ["timeRangeFilter"], fromTimeRangeFilter);
  }
  return toObject;
}
function liveConnectConfigToMldev$1(fromObject, parentObject) {
  const toObject = {};
  const fromGenerationConfig = getValueByPath(fromObject, [
    "generationConfig"
  ]);
  if (parentObject !== void 0 && fromGenerationConfig != null) {
    setValueByPath(parentObject, ["setup", "generationConfig"], fromGenerationConfig);
  }
  const fromResponseModalities = getValueByPath(fromObject, [
    "responseModalities"
  ]);
  if (parentObject !== void 0 && fromResponseModalities != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "responseModalities"], fromResponseModalities);
  }
  const fromTemperature = getValueByPath(fromObject, ["temperature"]);
  if (parentObject !== void 0 && fromTemperature != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "temperature"], fromTemperature);
  }
  const fromTopP = getValueByPath(fromObject, ["topP"]);
  if (parentObject !== void 0 && fromTopP != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "topP"], fromTopP);
  }
  const fromTopK = getValueByPath(fromObject, ["topK"]);
  if (parentObject !== void 0 && fromTopK != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "topK"], fromTopK);
  }
  const fromMaxOutputTokens = getValueByPath(fromObject, [
    "maxOutputTokens"
  ]);
  if (parentObject !== void 0 && fromMaxOutputTokens != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "maxOutputTokens"], fromMaxOutputTokens);
  }
  const fromMediaResolution = getValueByPath(fromObject, [
    "mediaResolution"
  ]);
  if (parentObject !== void 0 && fromMediaResolution != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "mediaResolution"], fromMediaResolution);
  }
  const fromSeed = getValueByPath(fromObject, ["seed"]);
  if (parentObject !== void 0 && fromSeed != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "seed"], fromSeed);
  }
  const fromSpeechConfig = getValueByPath(fromObject, ["speechConfig"]);
  if (parentObject !== void 0 && fromSpeechConfig != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "speechConfig"], tLiveSpeechConfig(fromSpeechConfig));
  }
  const fromThinkingConfig = getValueByPath(fromObject, [
    "thinkingConfig"
  ]);
  if (parentObject !== void 0 && fromThinkingConfig != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "thinkingConfig"], fromThinkingConfig);
  }
  const fromEnableAffectiveDialog = getValueByPath(fromObject, [
    "enableAffectiveDialog"
  ]);
  if (parentObject !== void 0 && fromEnableAffectiveDialog != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "enableAffectiveDialog"], fromEnableAffectiveDialog);
  }
  const fromSystemInstruction = getValueByPath(fromObject, [
    "systemInstruction"
  ]);
  if (parentObject !== void 0 && fromSystemInstruction != null) {
    setValueByPath(parentObject, ["setup", "systemInstruction"], contentToMldev$2(tContent(fromSystemInstruction)));
  }
  const fromTools = getValueByPath(fromObject, ["tools"]);
  if (parentObject !== void 0 && fromTools != null) {
    let transformedList = tTools(fromTools);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return toolToMldev$2(tTool(item));
      });
    }
    setValueByPath(parentObject, ["setup", "tools"], transformedList);
  }
  const fromSessionResumption = getValueByPath(fromObject, [
    "sessionResumption"
  ]);
  if (parentObject !== void 0 && fromSessionResumption != null) {
    setValueByPath(parentObject, ["setup", "sessionResumption"], sessionResumptionConfigToMldev$1(fromSessionResumption));
  }
  const fromInputAudioTranscription = getValueByPath(fromObject, [
    "inputAudioTranscription"
  ]);
  if (parentObject !== void 0 && fromInputAudioTranscription != null) {
    setValueByPath(parentObject, ["setup", "inputAudioTranscription"], audioTranscriptionConfigToMldev$1(fromInputAudioTranscription));
  }
  const fromOutputAudioTranscription = getValueByPath(fromObject, [
    "outputAudioTranscription"
  ]);
  if (parentObject !== void 0 && fromOutputAudioTranscription != null) {
    setValueByPath(parentObject, ["setup", "outputAudioTranscription"], audioTranscriptionConfigToMldev$1(fromOutputAudioTranscription));
  }
  const fromRealtimeInputConfig = getValueByPath(fromObject, [
    "realtimeInputConfig"
  ]);
  if (parentObject !== void 0 && fromRealtimeInputConfig != null) {
    setValueByPath(parentObject, ["setup", "realtimeInputConfig"], fromRealtimeInputConfig);
  }
  const fromContextWindowCompression = getValueByPath(fromObject, [
    "contextWindowCompression"
  ]);
  if (parentObject !== void 0 && fromContextWindowCompression != null) {
    setValueByPath(parentObject, ["setup", "contextWindowCompression"], fromContextWindowCompression);
  }
  const fromProactivity = getValueByPath(fromObject, ["proactivity"]);
  if (parentObject !== void 0 && fromProactivity != null) {
    setValueByPath(parentObject, ["setup", "proactivity"], fromProactivity);
  }
  if (getValueByPath(fromObject, ["explicitVadSignal"]) !== void 0) {
    throw new Error("explicitVadSignal parameter is not supported in Gemini API.");
  }
  return toObject;
}
function liveConnectConfigToVertex(fromObject, parentObject) {
  const toObject = {};
  const fromGenerationConfig = getValueByPath(fromObject, [
    "generationConfig"
  ]);
  if (parentObject !== void 0 && fromGenerationConfig != null) {
    setValueByPath(parentObject, ["setup", "generationConfig"], generationConfigToVertex$1(fromGenerationConfig));
  }
  const fromResponseModalities = getValueByPath(fromObject, [
    "responseModalities"
  ]);
  if (parentObject !== void 0 && fromResponseModalities != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "responseModalities"], fromResponseModalities);
  }
  const fromTemperature = getValueByPath(fromObject, ["temperature"]);
  if (parentObject !== void 0 && fromTemperature != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "temperature"], fromTemperature);
  }
  const fromTopP = getValueByPath(fromObject, ["topP"]);
  if (parentObject !== void 0 && fromTopP != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "topP"], fromTopP);
  }
  const fromTopK = getValueByPath(fromObject, ["topK"]);
  if (parentObject !== void 0 && fromTopK != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "topK"], fromTopK);
  }
  const fromMaxOutputTokens = getValueByPath(fromObject, [
    "maxOutputTokens"
  ]);
  if (parentObject !== void 0 && fromMaxOutputTokens != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "maxOutputTokens"], fromMaxOutputTokens);
  }
  const fromMediaResolution = getValueByPath(fromObject, [
    "mediaResolution"
  ]);
  if (parentObject !== void 0 && fromMediaResolution != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "mediaResolution"], fromMediaResolution);
  }
  const fromSeed = getValueByPath(fromObject, ["seed"]);
  if (parentObject !== void 0 && fromSeed != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "seed"], fromSeed);
  }
  const fromSpeechConfig = getValueByPath(fromObject, ["speechConfig"]);
  if (parentObject !== void 0 && fromSpeechConfig != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "speechConfig"], tLiveSpeechConfig(fromSpeechConfig));
  }
  const fromThinkingConfig = getValueByPath(fromObject, [
    "thinkingConfig"
  ]);
  if (parentObject !== void 0 && fromThinkingConfig != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "thinkingConfig"], fromThinkingConfig);
  }
  const fromEnableAffectiveDialog = getValueByPath(fromObject, [
    "enableAffectiveDialog"
  ]);
  if (parentObject !== void 0 && fromEnableAffectiveDialog != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "enableAffectiveDialog"], fromEnableAffectiveDialog);
  }
  const fromSystemInstruction = getValueByPath(fromObject, [
    "systemInstruction"
  ]);
  if (parentObject !== void 0 && fromSystemInstruction != null) {
    setValueByPath(parentObject, ["setup", "systemInstruction"], tContent(fromSystemInstruction));
  }
  const fromTools = getValueByPath(fromObject, ["tools"]);
  if (parentObject !== void 0 && fromTools != null) {
    let transformedList = tTools(fromTools);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return toolToVertex$1(tTool(item));
      });
    }
    setValueByPath(parentObject, ["setup", "tools"], transformedList);
  }
  const fromSessionResumption = getValueByPath(fromObject, [
    "sessionResumption"
  ]);
  if (parentObject !== void 0 && fromSessionResumption != null) {
    setValueByPath(parentObject, ["setup", "sessionResumption"], fromSessionResumption);
  }
  const fromInputAudioTranscription = getValueByPath(fromObject, [
    "inputAudioTranscription"
  ]);
  if (parentObject !== void 0 && fromInputAudioTranscription != null) {
    setValueByPath(parentObject, ["setup", "inputAudioTranscription"], fromInputAudioTranscription);
  }
  const fromOutputAudioTranscription = getValueByPath(fromObject, [
    "outputAudioTranscription"
  ]);
  if (parentObject !== void 0 && fromOutputAudioTranscription != null) {
    setValueByPath(parentObject, ["setup", "outputAudioTranscription"], fromOutputAudioTranscription);
  }
  const fromRealtimeInputConfig = getValueByPath(fromObject, [
    "realtimeInputConfig"
  ]);
  if (parentObject !== void 0 && fromRealtimeInputConfig != null) {
    setValueByPath(parentObject, ["setup", "realtimeInputConfig"], fromRealtimeInputConfig);
  }
  const fromContextWindowCompression = getValueByPath(fromObject, [
    "contextWindowCompression"
  ]);
  if (parentObject !== void 0 && fromContextWindowCompression != null) {
    setValueByPath(parentObject, ["setup", "contextWindowCompression"], fromContextWindowCompression);
  }
  const fromProactivity = getValueByPath(fromObject, ["proactivity"]);
  if (parentObject !== void 0 && fromProactivity != null) {
    setValueByPath(parentObject, ["setup", "proactivity"], fromProactivity);
  }
  const fromExplicitVadSignal = getValueByPath(fromObject, [
    "explicitVadSignal"
  ]);
  if (parentObject !== void 0 && fromExplicitVadSignal != null) {
    setValueByPath(parentObject, ["setup", "explicitVadSignal"], fromExplicitVadSignal);
  }
  return toObject;
}
function liveConnectParametersToMldev(apiClient, fromObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["setup", "model"], tModel(apiClient, fromModel));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], liveConnectConfigToMldev$1(fromConfig, toObject));
  }
  return toObject;
}
function liveConnectParametersToVertex(apiClient, fromObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["setup", "model"], tModel(apiClient, fromModel));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], liveConnectConfigToVertex(fromConfig, toObject));
  }
  return toObject;
}
function liveMusicSetConfigParametersToMldev(fromObject) {
  const toObject = {};
  const fromMusicGenerationConfig = getValueByPath(fromObject, [
    "musicGenerationConfig"
  ]);
  if (fromMusicGenerationConfig != null) {
    setValueByPath(toObject, ["musicGenerationConfig"], fromMusicGenerationConfig);
  }
  return toObject;
}
function liveMusicSetWeightedPromptsParametersToMldev(fromObject) {
  const toObject = {};
  const fromWeightedPrompts = getValueByPath(fromObject, [
    "weightedPrompts"
  ]);
  if (fromWeightedPrompts != null) {
    let transformedList = fromWeightedPrompts;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["weightedPrompts"], transformedList);
  }
  return toObject;
}
function liveSendRealtimeInputParametersToMldev(fromObject) {
  const toObject = {};
  const fromMedia = getValueByPath(fromObject, ["media"]);
  if (fromMedia != null) {
    let transformedList = tBlobs(fromMedia);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return blobToMldev$2(item);
      });
    }
    setValueByPath(toObject, ["mediaChunks"], transformedList);
  }
  const fromAudio = getValueByPath(fromObject, ["audio"]);
  if (fromAudio != null) {
    setValueByPath(toObject, ["audio"], blobToMldev$2(tAudioBlob(fromAudio)));
  }
  const fromAudioStreamEnd = getValueByPath(fromObject, [
    "audioStreamEnd"
  ]);
  if (fromAudioStreamEnd != null) {
    setValueByPath(toObject, ["audioStreamEnd"], fromAudioStreamEnd);
  }
  const fromVideo = getValueByPath(fromObject, ["video"]);
  if (fromVideo != null) {
    setValueByPath(toObject, ["video"], blobToMldev$2(tImageBlob(fromVideo)));
  }
  const fromText = getValueByPath(fromObject, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  const fromActivityStart = getValueByPath(fromObject, [
    "activityStart"
  ]);
  if (fromActivityStart != null) {
    setValueByPath(toObject, ["activityStart"], fromActivityStart);
  }
  const fromActivityEnd = getValueByPath(fromObject, ["activityEnd"]);
  if (fromActivityEnd != null) {
    setValueByPath(toObject, ["activityEnd"], fromActivityEnd);
  }
  return toObject;
}
function liveSendRealtimeInputParametersToVertex(fromObject) {
  const toObject = {};
  const fromMedia = getValueByPath(fromObject, ["media"]);
  if (fromMedia != null) {
    let transformedList = tBlobs(fromMedia);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["mediaChunks"], transformedList);
  }
  const fromAudio = getValueByPath(fromObject, ["audio"]);
  if (fromAudio != null) {
    setValueByPath(toObject, ["audio"], tAudioBlob(fromAudio));
  }
  const fromAudioStreamEnd = getValueByPath(fromObject, [
    "audioStreamEnd"
  ]);
  if (fromAudioStreamEnd != null) {
    setValueByPath(toObject, ["audioStreamEnd"], fromAudioStreamEnd);
  }
  const fromVideo = getValueByPath(fromObject, ["video"]);
  if (fromVideo != null) {
    setValueByPath(toObject, ["video"], tImageBlob(fromVideo));
  }
  const fromText = getValueByPath(fromObject, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  const fromActivityStart = getValueByPath(fromObject, [
    "activityStart"
  ]);
  if (fromActivityStart != null) {
    setValueByPath(toObject, ["activityStart"], fromActivityStart);
  }
  const fromActivityEnd = getValueByPath(fromObject, ["activityEnd"]);
  if (fromActivityEnd != null) {
    setValueByPath(toObject, ["activityEnd"], fromActivityEnd);
  }
  return toObject;
}
function liveServerMessageFromVertex(fromObject) {
  const toObject = {};
  const fromSetupComplete = getValueByPath(fromObject, [
    "setupComplete"
  ]);
  if (fromSetupComplete != null) {
    setValueByPath(toObject, ["setupComplete"], fromSetupComplete);
  }
  const fromServerContent = getValueByPath(fromObject, [
    "serverContent"
  ]);
  if (fromServerContent != null) {
    setValueByPath(toObject, ["serverContent"], fromServerContent);
  }
  const fromToolCall = getValueByPath(fromObject, ["toolCall"]);
  if (fromToolCall != null) {
    setValueByPath(toObject, ["toolCall"], fromToolCall);
  }
  const fromToolCallCancellation = getValueByPath(fromObject, [
    "toolCallCancellation"
  ]);
  if (fromToolCallCancellation != null) {
    setValueByPath(toObject, ["toolCallCancellation"], fromToolCallCancellation);
  }
  const fromUsageMetadata = getValueByPath(fromObject, [
    "usageMetadata"
  ]);
  if (fromUsageMetadata != null) {
    setValueByPath(toObject, ["usageMetadata"], usageMetadataFromVertex(fromUsageMetadata));
  }
  const fromGoAway = getValueByPath(fromObject, ["goAway"]);
  if (fromGoAway != null) {
    setValueByPath(toObject, ["goAway"], fromGoAway);
  }
  const fromSessionResumptionUpdate = getValueByPath(fromObject, [
    "sessionResumptionUpdate"
  ]);
  if (fromSessionResumptionUpdate != null) {
    setValueByPath(toObject, ["sessionResumptionUpdate"], fromSessionResumptionUpdate);
  }
  const fromVoiceActivityDetectionSignal = getValueByPath(fromObject, [
    "voiceActivityDetectionSignal"
  ]);
  if (fromVoiceActivityDetectionSignal != null) {
    setValueByPath(toObject, ["voiceActivityDetectionSignal"], fromVoiceActivityDetectionSignal);
  }
  const fromVoiceActivity = getValueByPath(fromObject, [
    "voiceActivity"
  ]);
  if (fromVoiceActivity != null) {
    setValueByPath(toObject, ["voiceActivity"], voiceActivityFromVertex(fromVoiceActivity));
  }
  return toObject;
}
function partToMldev$2(fromObject) {
  const toObject = {};
  const fromMediaResolution = getValueByPath(fromObject, [
    "mediaResolution"
  ]);
  if (fromMediaResolution != null) {
    setValueByPath(toObject, ["mediaResolution"], fromMediaResolution);
  }
  const fromCodeExecutionResult = getValueByPath(fromObject, [
    "codeExecutionResult"
  ]);
  if (fromCodeExecutionResult != null) {
    setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult);
  }
  const fromExecutableCode = getValueByPath(fromObject, [
    "executableCode"
  ]);
  if (fromExecutableCode != null) {
    setValueByPath(toObject, ["executableCode"], fromExecutableCode);
  }
  const fromFileData = getValueByPath(fromObject, ["fileData"]);
  if (fromFileData != null) {
    setValueByPath(toObject, ["fileData"], fileDataToMldev$2(fromFileData));
  }
  const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]);
  if (fromFunctionCall != null) {
    setValueByPath(toObject, ["functionCall"], functionCallToMldev$2(fromFunctionCall));
  }
  const fromFunctionResponse = getValueByPath(fromObject, [
    "functionResponse"
  ]);
  if (fromFunctionResponse != null) {
    setValueByPath(toObject, ["functionResponse"], fromFunctionResponse);
  }
  const fromInlineData = getValueByPath(fromObject, ["inlineData"]);
  if (fromInlineData != null) {
    setValueByPath(toObject, ["inlineData"], blobToMldev$2(fromInlineData));
  }
  const fromText = getValueByPath(fromObject, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  const fromThought = getValueByPath(fromObject, ["thought"]);
  if (fromThought != null) {
    setValueByPath(toObject, ["thought"], fromThought);
  }
  const fromThoughtSignature = getValueByPath(fromObject, [
    "thoughtSignature"
  ]);
  if (fromThoughtSignature != null) {
    setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature);
  }
  const fromVideoMetadata = getValueByPath(fromObject, [
    "videoMetadata"
  ]);
  if (fromVideoMetadata != null) {
    setValueByPath(toObject, ["videoMetadata"], fromVideoMetadata);
  }
  return toObject;
}
function sessionResumptionConfigToMldev$1(fromObject) {
  const toObject = {};
  const fromHandle = getValueByPath(fromObject, ["handle"]);
  if (fromHandle != null) {
    setValueByPath(toObject, ["handle"], fromHandle);
  }
  if (getValueByPath(fromObject, ["transparent"]) !== void 0) {
    throw new Error("transparent parameter is not supported in Gemini API.");
  }
  return toObject;
}
function toolToMldev$2(fromObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["retrieval"]) !== void 0) {
    throw new Error("retrieval parameter is not supported in Gemini API.");
  }
  const fromComputerUse = getValueByPath(fromObject, ["computerUse"]);
  if (fromComputerUse != null) {
    setValueByPath(toObject, ["computerUse"], fromComputerUse);
  }
  const fromFileSearch = getValueByPath(fromObject, ["fileSearch"]);
  if (fromFileSearch != null) {
    setValueByPath(toObject, ["fileSearch"], fromFileSearch);
  }
  const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]);
  if (fromGoogleSearch != null) {
    setValueByPath(toObject, ["googleSearch"], googleSearchToMldev$2(fromGoogleSearch));
  }
  const fromGoogleMaps = getValueByPath(fromObject, ["googleMaps"]);
  if (fromGoogleMaps != null) {
    setValueByPath(toObject, ["googleMaps"], googleMapsToMldev$2(fromGoogleMaps));
  }
  const fromCodeExecution = getValueByPath(fromObject, [
    "codeExecution"
  ]);
  if (fromCodeExecution != null) {
    setValueByPath(toObject, ["codeExecution"], fromCodeExecution);
  }
  if (getValueByPath(fromObject, ["enterpriseWebSearch"]) !== void 0) {
    throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");
  }
  const fromFunctionDeclarations = getValueByPath(fromObject, [
    "functionDeclarations"
  ]);
  if (fromFunctionDeclarations != null) {
    let transformedList = fromFunctionDeclarations;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["functionDeclarations"], transformedList);
  }
  const fromGoogleSearchRetrieval = getValueByPath(fromObject, [
    "googleSearchRetrieval"
  ]);
  if (fromGoogleSearchRetrieval != null) {
    setValueByPath(toObject, ["googleSearchRetrieval"], fromGoogleSearchRetrieval);
  }
  if (getValueByPath(fromObject, ["parallelAiSearch"]) !== void 0) {
    throw new Error("parallelAiSearch parameter is not supported in Gemini API.");
  }
  const fromUrlContext = getValueByPath(fromObject, ["urlContext"]);
  if (fromUrlContext != null) {
    setValueByPath(toObject, ["urlContext"], fromUrlContext);
  }
  const fromMcpServers = getValueByPath(fromObject, ["mcpServers"]);
  if (fromMcpServers != null) {
    let transformedList = fromMcpServers;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["mcpServers"], transformedList);
  }
  return toObject;
}
function toolToVertex$1(fromObject) {
  const toObject = {};
  const fromRetrieval = getValueByPath(fromObject, ["retrieval"]);
  if (fromRetrieval != null) {
    setValueByPath(toObject, ["retrieval"], fromRetrieval);
  }
  const fromComputerUse = getValueByPath(fromObject, ["computerUse"]);
  if (fromComputerUse != null) {
    setValueByPath(toObject, ["computerUse"], fromComputerUse);
  }
  if (getValueByPath(fromObject, ["fileSearch"]) !== void 0) {
    throw new Error("fileSearch parameter is not supported in Vertex AI.");
  }
  const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]);
  if (fromGoogleSearch != null) {
    setValueByPath(toObject, ["googleSearch"], fromGoogleSearch);
  }
  const fromGoogleMaps = getValueByPath(fromObject, ["googleMaps"]);
  if (fromGoogleMaps != null) {
    setValueByPath(toObject, ["googleMaps"], fromGoogleMaps);
  }
  const fromCodeExecution = getValueByPath(fromObject, [
    "codeExecution"
  ]);
  if (fromCodeExecution != null) {
    setValueByPath(toObject, ["codeExecution"], fromCodeExecution);
  }
  const fromEnterpriseWebSearch = getValueByPath(fromObject, [
    "enterpriseWebSearch"
  ]);
  if (fromEnterpriseWebSearch != null) {
    setValueByPath(toObject, ["enterpriseWebSearch"], fromEnterpriseWebSearch);
  }
  const fromFunctionDeclarations = getValueByPath(fromObject, [
    "functionDeclarations"
  ]);
  if (fromFunctionDeclarations != null) {
    let transformedList = fromFunctionDeclarations;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return functionDeclarationToVertex$1(item);
      });
    }
    setValueByPath(toObject, ["functionDeclarations"], transformedList);
  }
  const fromGoogleSearchRetrieval = getValueByPath(fromObject, [
    "googleSearchRetrieval"
  ]);
  if (fromGoogleSearchRetrieval != null) {
    setValueByPath(toObject, ["googleSearchRetrieval"], fromGoogleSearchRetrieval);
  }
  const fromParallelAiSearch = getValueByPath(fromObject, [
    "parallelAiSearch"
  ]);
  if (fromParallelAiSearch != null) {
    setValueByPath(toObject, ["parallelAiSearch"], fromParallelAiSearch);
  }
  const fromUrlContext = getValueByPath(fromObject, ["urlContext"]);
  if (fromUrlContext != null) {
    setValueByPath(toObject, ["urlContext"], fromUrlContext);
  }
  if (getValueByPath(fromObject, ["mcpServers"]) !== void 0) {
    throw new Error("mcpServers parameter is not supported in Vertex AI.");
  }
  return toObject;
}
function usageMetadataFromVertex(fromObject) {
  const toObject = {};
  const fromPromptTokenCount = getValueByPath(fromObject, [
    "promptTokenCount"
  ]);
  if (fromPromptTokenCount != null) {
    setValueByPath(toObject, ["promptTokenCount"], fromPromptTokenCount);
  }
  const fromCachedContentTokenCount = getValueByPath(fromObject, [
    "cachedContentTokenCount"
  ]);
  if (fromCachedContentTokenCount != null) {
    setValueByPath(toObject, ["cachedContentTokenCount"], fromCachedContentTokenCount);
  }
  const fromResponseTokenCount = getValueByPath(fromObject, [
    "candidatesTokenCount"
  ]);
  if (fromResponseTokenCount != null) {
    setValueByPath(toObject, ["responseTokenCount"], fromResponseTokenCount);
  }
  const fromToolUsePromptTokenCount = getValueByPath(fromObject, [
    "toolUsePromptTokenCount"
  ]);
  if (fromToolUsePromptTokenCount != null) {
    setValueByPath(toObject, ["toolUsePromptTokenCount"], fromToolUsePromptTokenCount);
  }
  const fromThoughtsTokenCount = getValueByPath(fromObject, [
    "thoughtsTokenCount"
  ]);
  if (fromThoughtsTokenCount != null) {
    setValueByPath(toObject, ["thoughtsTokenCount"], fromThoughtsTokenCount);
  }
  const fromTotalTokenCount = getValueByPath(fromObject, [
    "totalTokenCount"
  ]);
  if (fromTotalTokenCount != null) {
    setValueByPath(toObject, ["totalTokenCount"], fromTotalTokenCount);
  }
  const fromPromptTokensDetails = getValueByPath(fromObject, [
    "promptTokensDetails"
  ]);
  if (fromPromptTokensDetails != null) {
    let transformedList = fromPromptTokensDetails;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["promptTokensDetails"], transformedList);
  }
  const fromCacheTokensDetails = getValueByPath(fromObject, [
    "cacheTokensDetails"
  ]);
  if (fromCacheTokensDetails != null) {
    let transformedList = fromCacheTokensDetails;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["cacheTokensDetails"], transformedList);
  }
  const fromResponseTokensDetails = getValueByPath(fromObject, [
    "candidatesTokensDetails"
  ]);
  if (fromResponseTokensDetails != null) {
    let transformedList = fromResponseTokensDetails;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["responseTokensDetails"], transformedList);
  }
  const fromToolUsePromptTokensDetails = getValueByPath(fromObject, [
    "toolUsePromptTokensDetails"
  ]);
  if (fromToolUsePromptTokensDetails != null) {
    let transformedList = fromToolUsePromptTokensDetails;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["toolUsePromptTokensDetails"], transformedList);
  }
  const fromTrafficType = getValueByPath(fromObject, ["trafficType"]);
  if (fromTrafficType != null) {
    setValueByPath(toObject, ["trafficType"], fromTrafficType);
  }
  return toObject;
}
function voiceActivityFromVertex(fromObject) {
  const toObject = {};
  const fromVoiceActivityType = getValueByPath(fromObject, ["type"]);
  if (fromVoiceActivityType != null) {
    setValueByPath(toObject, ["voiceActivityType"], fromVoiceActivityType);
  }
  return toObject;
}
function authConfigToMldev$1(fromObject, _rootObject) {
  const toObject = {};
  const fromApiKey = getValueByPath(fromObject, ["apiKey"]);
  if (fromApiKey != null) {
    setValueByPath(toObject, ["apiKey"], fromApiKey);
  }
  if (getValueByPath(fromObject, ["apiKeyConfig"]) !== void 0) {
    throw new Error("apiKeyConfig parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["authType"]) !== void 0) {
    throw new Error("authType parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["googleServiceAccountConfig"]) !== void 0) {
    throw new Error("googleServiceAccountConfig parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["httpBasicAuthConfig"]) !== void 0) {
    throw new Error("httpBasicAuthConfig parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["oauthConfig"]) !== void 0) {
    throw new Error("oauthConfig parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["oidcConfig"]) !== void 0) {
    throw new Error("oidcConfig parameter is not supported in Gemini API.");
  }
  return toObject;
}
function blobToMldev$1(fromObject, _rootObject) {
  const toObject = {};
  const fromData = getValueByPath(fromObject, ["data"]);
  if (fromData != null) {
    setValueByPath(toObject, ["data"], fromData);
  }
  if (getValueByPath(fromObject, ["displayName"]) !== void 0) {
    throw new Error("displayName parameter is not supported in Gemini API.");
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function candidateFromMldev(fromObject, rootObject) {
  const toObject = {};
  const fromContent = getValueByPath(fromObject, ["content"]);
  if (fromContent != null) {
    setValueByPath(toObject, ["content"], fromContent);
  }
  const fromCitationMetadata = getValueByPath(fromObject, [
    "citationMetadata"
  ]);
  if (fromCitationMetadata != null) {
    setValueByPath(toObject, ["citationMetadata"], citationMetadataFromMldev(fromCitationMetadata));
  }
  const fromTokenCount = getValueByPath(fromObject, ["tokenCount"]);
  if (fromTokenCount != null) {
    setValueByPath(toObject, ["tokenCount"], fromTokenCount);
  }
  const fromFinishReason = getValueByPath(fromObject, ["finishReason"]);
  if (fromFinishReason != null) {
    setValueByPath(toObject, ["finishReason"], fromFinishReason);
  }
  const fromGroundingMetadata = getValueByPath(fromObject, [
    "groundingMetadata"
  ]);
  if (fromGroundingMetadata != null) {
    setValueByPath(toObject, ["groundingMetadata"], fromGroundingMetadata);
  }
  const fromAvgLogprobs = getValueByPath(fromObject, ["avgLogprobs"]);
  if (fromAvgLogprobs != null) {
    setValueByPath(toObject, ["avgLogprobs"], fromAvgLogprobs);
  }
  const fromIndex = getValueByPath(fromObject, ["index"]);
  if (fromIndex != null) {
    setValueByPath(toObject, ["index"], fromIndex);
  }
  const fromLogprobsResult = getValueByPath(fromObject, [
    "logprobsResult"
  ]);
  if (fromLogprobsResult != null) {
    setValueByPath(toObject, ["logprobsResult"], fromLogprobsResult);
  }
  const fromSafetyRatings = getValueByPath(fromObject, [
    "safetyRatings"
  ]);
  if (fromSafetyRatings != null) {
    let transformedList = fromSafetyRatings;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["safetyRatings"], transformedList);
  }
  const fromUrlContextMetadata = getValueByPath(fromObject, [
    "urlContextMetadata"
  ]);
  if (fromUrlContextMetadata != null) {
    setValueByPath(toObject, ["urlContextMetadata"], fromUrlContextMetadata);
  }
  return toObject;
}
function citationMetadataFromMldev(fromObject, _rootObject) {
  const toObject = {};
  const fromCitations = getValueByPath(fromObject, ["citationSources"]);
  if (fromCitations != null) {
    let transformedList = fromCitations;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["citations"], transformedList);
  }
  return toObject;
}
function computeTokensParametersToVertex(apiClient, fromObject, _rootObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromContents = getValueByPath(fromObject, ["contents"]);
  if (fromContents != null) {
    let transformedList = tContents(fromContents);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["contents"], transformedList);
  }
  return toObject;
}
function computeTokensResponseFromVertex(fromObject, _rootObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromTokensInfo = getValueByPath(fromObject, ["tokensInfo"]);
  if (fromTokensInfo != null) {
    let transformedList = fromTokensInfo;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["tokensInfo"], transformedList);
  }
  return toObject;
}
function contentEmbeddingFromVertex(fromObject, rootObject) {
  const toObject = {};
  const fromValues = getValueByPath(fromObject, ["values"]);
  if (fromValues != null) {
    setValueByPath(toObject, ["values"], fromValues);
  }
  const fromStatistics = getValueByPath(fromObject, ["statistics"]);
  if (fromStatistics != null) {
    setValueByPath(toObject, ["statistics"], contentEmbeddingStatisticsFromVertex(fromStatistics));
  }
  return toObject;
}
function contentEmbeddingStatisticsFromVertex(fromObject, _rootObject) {
  const toObject = {};
  const fromTruncated = getValueByPath(fromObject, ["truncated"]);
  if (fromTruncated != null) {
    setValueByPath(toObject, ["truncated"], fromTruncated);
  }
  const fromTokenCount = getValueByPath(fromObject, ["token_count"]);
  if (fromTokenCount != null) {
    setValueByPath(toObject, ["tokenCount"], fromTokenCount);
  }
  return toObject;
}
function contentToMldev$1(fromObject, rootObject) {
  const toObject = {};
  const fromParts = getValueByPath(fromObject, ["parts"]);
  if (fromParts != null) {
    let transformedList = fromParts;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return partToMldev$1(item);
      });
    }
    setValueByPath(toObject, ["parts"], transformedList);
  }
  const fromRole = getValueByPath(fromObject, ["role"]);
  if (fromRole != null) {
    setValueByPath(toObject, ["role"], fromRole);
  }
  return toObject;
}
function controlReferenceConfigToVertex(fromObject, _rootObject) {
  const toObject = {};
  const fromControlType = getValueByPath(fromObject, ["controlType"]);
  if (fromControlType != null) {
    setValueByPath(toObject, ["controlType"], fromControlType);
  }
  const fromEnableControlImageComputation = getValueByPath(fromObject, [
    "enableControlImageComputation"
  ]);
  if (fromEnableControlImageComputation != null) {
    setValueByPath(toObject, ["computeControl"], fromEnableControlImageComputation);
  }
  return toObject;
}
function countTokensConfigToMldev(fromObject, _rootObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["systemInstruction"]) !== void 0) {
    throw new Error("systemInstruction parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["tools"]) !== void 0) {
    throw new Error("tools parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["generationConfig"]) !== void 0) {
    throw new Error("generationConfig parameter is not supported in Gemini API.");
  }
  return toObject;
}
function countTokensConfigToVertex(fromObject, parentObject, rootObject) {
  const toObject = {};
  const fromSystemInstruction = getValueByPath(fromObject, [
    "systemInstruction"
  ]);
  if (parentObject !== void 0 && fromSystemInstruction != null) {
    setValueByPath(parentObject, ["systemInstruction"], tContent(fromSystemInstruction));
  }
  const fromTools = getValueByPath(fromObject, ["tools"]);
  if (parentObject !== void 0 && fromTools != null) {
    let transformedList = fromTools;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return toolToVertex(item);
      });
    }
    setValueByPath(parentObject, ["tools"], transformedList);
  }
  const fromGenerationConfig = getValueByPath(fromObject, [
    "generationConfig"
  ]);
  if (parentObject !== void 0 && fromGenerationConfig != null) {
    setValueByPath(parentObject, ["generationConfig"], generationConfigToVertex(fromGenerationConfig));
  }
  return toObject;
}
function countTokensParametersToMldev(apiClient, fromObject, rootObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromContents = getValueByPath(fromObject, ["contents"]);
  if (fromContents != null) {
    let transformedList = tContents(fromContents);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return contentToMldev$1(item);
      });
    }
    setValueByPath(toObject, ["contents"], transformedList);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    countTokensConfigToMldev(fromConfig);
  }
  return toObject;
}
function countTokensParametersToVertex(apiClient, fromObject, rootObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromContents = getValueByPath(fromObject, ["contents"]);
  if (fromContents != null) {
    let transformedList = tContents(fromContents);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["contents"], transformedList);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    countTokensConfigToVertex(fromConfig, toObject);
  }
  return toObject;
}
function countTokensResponseFromMldev(fromObject, _rootObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromTotalTokens = getValueByPath(fromObject, ["totalTokens"]);
  if (fromTotalTokens != null) {
    setValueByPath(toObject, ["totalTokens"], fromTotalTokens);
  }
  const fromCachedContentTokenCount = getValueByPath(fromObject, [
    "cachedContentTokenCount"
  ]);
  if (fromCachedContentTokenCount != null) {
    setValueByPath(toObject, ["cachedContentTokenCount"], fromCachedContentTokenCount);
  }
  return toObject;
}
function countTokensResponseFromVertex(fromObject, _rootObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromTotalTokens = getValueByPath(fromObject, ["totalTokens"]);
  if (fromTotalTokens != null) {
    setValueByPath(toObject, ["totalTokens"], fromTotalTokens);
  }
  return toObject;
}
function deleteModelParametersToMldev(apiClient, fromObject, _rootObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel));
  }
  return toObject;
}
function deleteModelParametersToVertex(apiClient, fromObject, _rootObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel));
  }
  return toObject;
}
function deleteModelResponseFromMldev(fromObject, _rootObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  return toObject;
}
function deleteModelResponseFromVertex(fromObject, _rootObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  return toObject;
}
function editImageConfigToVertex(fromObject, parentObject, _rootObject) {
  const toObject = {};
  const fromOutputGcsUri = getValueByPath(fromObject, ["outputGcsUri"]);
  if (parentObject !== void 0 && fromOutputGcsUri != null) {
    setValueByPath(parentObject, ["parameters", "storageUri"], fromOutputGcsUri);
  }
  const fromNegativePrompt = getValueByPath(fromObject, [
    "negativePrompt"
  ]);
  if (parentObject !== void 0 && fromNegativePrompt != null) {
    setValueByPath(parentObject, ["parameters", "negativePrompt"], fromNegativePrompt);
  }
  const fromNumberOfImages = getValueByPath(fromObject, [
    "numberOfImages"
  ]);
  if (parentObject !== void 0 && fromNumberOfImages != null) {
    setValueByPath(parentObject, ["parameters", "sampleCount"], fromNumberOfImages);
  }
  const fromAspectRatio = getValueByPath(fromObject, ["aspectRatio"]);
  if (parentObject !== void 0 && fromAspectRatio != null) {
    setValueByPath(parentObject, ["parameters", "aspectRatio"], fromAspectRatio);
  }
  const fromGuidanceScale = getValueByPath(fromObject, [
    "guidanceScale"
  ]);
  if (parentObject !== void 0 && fromGuidanceScale != null) {
    setValueByPath(parentObject, ["parameters", "guidanceScale"], fromGuidanceScale);
  }
  const fromSeed = getValueByPath(fromObject, ["seed"]);
  if (parentObject !== void 0 && fromSeed != null) {
    setValueByPath(parentObject, ["parameters", "seed"], fromSeed);
  }
  const fromSafetyFilterLevel = getValueByPath(fromObject, [
    "safetyFilterLevel"
  ]);
  if (parentObject !== void 0 && fromSafetyFilterLevel != null) {
    setValueByPath(parentObject, ["parameters", "safetySetting"], fromSafetyFilterLevel);
  }
  const fromPersonGeneration = getValueByPath(fromObject, [
    "personGeneration"
  ]);
  if (parentObject !== void 0 && fromPersonGeneration != null) {
    setValueByPath(parentObject, ["parameters", "personGeneration"], fromPersonGeneration);
  }
  const fromIncludeSafetyAttributes = getValueByPath(fromObject, [
    "includeSafetyAttributes"
  ]);
  if (parentObject !== void 0 && fromIncludeSafetyAttributes != null) {
    setValueByPath(parentObject, ["parameters", "includeSafetyAttributes"], fromIncludeSafetyAttributes);
  }
  const fromIncludeRaiReason = getValueByPath(fromObject, [
    "includeRaiReason"
  ]);
  if (parentObject !== void 0 && fromIncludeRaiReason != null) {
    setValueByPath(parentObject, ["parameters", "includeRaiReason"], fromIncludeRaiReason);
  }
  const fromLanguage = getValueByPath(fromObject, ["language"]);
  if (parentObject !== void 0 && fromLanguage != null) {
    setValueByPath(parentObject, ["parameters", "language"], fromLanguage);
  }
  const fromOutputMimeType = getValueByPath(fromObject, [
    "outputMimeType"
  ]);
  if (parentObject !== void 0 && fromOutputMimeType != null) {
    setValueByPath(parentObject, ["parameters", "outputOptions", "mimeType"], fromOutputMimeType);
  }
  const fromOutputCompressionQuality = getValueByPath(fromObject, [
    "outputCompressionQuality"
  ]);
  if (parentObject !== void 0 && fromOutputCompressionQuality != null) {
    setValueByPath(parentObject, ["parameters", "outputOptions", "compressionQuality"], fromOutputCompressionQuality);
  }
  const fromAddWatermark = getValueByPath(fromObject, ["addWatermark"]);
  if (parentObject !== void 0 && fromAddWatermark != null) {
    setValueByPath(parentObject, ["parameters", "addWatermark"], fromAddWatermark);
  }
  const fromLabels = getValueByPath(fromObject, ["labels"]);
  if (parentObject !== void 0 && fromLabels != null) {
    setValueByPath(parentObject, ["labels"], fromLabels);
  }
  const fromEditMode = getValueByPath(fromObject, ["editMode"]);
  if (parentObject !== void 0 && fromEditMode != null) {
    setValueByPath(parentObject, ["parameters", "editMode"], fromEditMode);
  }
  const fromBaseSteps = getValueByPath(fromObject, ["baseSteps"]);
  if (parentObject !== void 0 && fromBaseSteps != null) {
    setValueByPath(parentObject, ["parameters", "editConfig", "baseSteps"], fromBaseSteps);
  }
  return toObject;
}
function editImageParametersInternalToVertex(apiClient, fromObject, rootObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromPrompt = getValueByPath(fromObject, ["prompt"]);
  if (fromPrompt != null) {
    setValueByPath(toObject, ["instances[0]", "prompt"], fromPrompt);
  }
  const fromReferenceImages = getValueByPath(fromObject, [
    "referenceImages"
  ]);
  if (fromReferenceImages != null) {
    let transformedList = fromReferenceImages;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return referenceImageAPIInternalToVertex(item);
      });
    }
    setValueByPath(toObject, ["instances[0]", "referenceImages"], transformedList);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    editImageConfigToVertex(fromConfig, toObject);
  }
  return toObject;
}
function editImageResponseFromVertex(fromObject, rootObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromGeneratedImages = getValueByPath(fromObject, [
    "predictions"
  ]);
  if (fromGeneratedImages != null) {
    let transformedList = fromGeneratedImages;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return generatedImageFromVertex(item);
      });
    }
    setValueByPath(toObject, ["generatedImages"], transformedList);
  }
  return toObject;
}
function embedContentConfigToMldev(fromObject, parentObject, _rootObject) {
  const toObject = {};
  const fromTaskType = getValueByPath(fromObject, ["taskType"]);
  if (parentObject !== void 0 && fromTaskType != null) {
    setValueByPath(parentObject, ["requests[]", "taskType"], fromTaskType);
  }
  const fromTitle = getValueByPath(fromObject, ["title"]);
  if (parentObject !== void 0 && fromTitle != null) {
    setValueByPath(parentObject, ["requests[]", "title"], fromTitle);
  }
  const fromOutputDimensionality = getValueByPath(fromObject, [
    "outputDimensionality"
  ]);
  if (parentObject !== void 0 && fromOutputDimensionality != null) {
    setValueByPath(parentObject, ["requests[]", "outputDimensionality"], fromOutputDimensionality);
  }
  if (getValueByPath(fromObject, ["mimeType"]) !== void 0) {
    throw new Error("mimeType parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["autoTruncate"]) !== void 0) {
    throw new Error("autoTruncate parameter is not supported in Gemini API.");
  }
  return toObject;
}
function embedContentConfigToVertex(fromObject, parentObject, rootObject) {
  const toObject = {};
  let discriminatorTaskType = getValueByPath(rootObject, [
    "embeddingApiType"
  ]);
  if (discriminatorTaskType === void 0) {
    discriminatorTaskType = "PREDICT";
  }
  if (discriminatorTaskType === "PREDICT") {
    const fromTaskType = getValueByPath(fromObject, ["taskType"]);
    if (parentObject !== void 0 && fromTaskType != null) {
      setValueByPath(parentObject, ["instances[]", "task_type"], fromTaskType);
    }
  } else if (discriminatorTaskType === "EMBED_CONTENT") {
    const fromTaskType = getValueByPath(fromObject, ["taskType"]);
    if (parentObject !== void 0 && fromTaskType != null) {
      setValueByPath(parentObject, ["taskType"], fromTaskType);
    }
  }
  let discriminatorTitle = getValueByPath(rootObject, [
    "embeddingApiType"
  ]);
  if (discriminatorTitle === void 0) {
    discriminatorTitle = "PREDICT";
  }
  if (discriminatorTitle === "PREDICT") {
    const fromTitle = getValueByPath(fromObject, ["title"]);
    if (parentObject !== void 0 && fromTitle != null) {
      setValueByPath(parentObject, ["instances[]", "title"], fromTitle);
    }
  } else if (discriminatorTitle === "EMBED_CONTENT") {
    const fromTitle = getValueByPath(fromObject, ["title"]);
    if (parentObject !== void 0 && fromTitle != null) {
      setValueByPath(parentObject, ["title"], fromTitle);
    }
  }
  let discriminatorOutputDimensionality = getValueByPath(rootObject, [
    "embeddingApiType"
  ]);
  if (discriminatorOutputDimensionality === void 0) {
    discriminatorOutputDimensionality = "PREDICT";
  }
  if (discriminatorOutputDimensionality === "PREDICT") {
    const fromOutputDimensionality = getValueByPath(fromObject, [
      "outputDimensionality"
    ]);
    if (parentObject !== void 0 && fromOutputDimensionality != null) {
      setValueByPath(parentObject, ["parameters", "outputDimensionality"], fromOutputDimensionality);
    }
  } else if (discriminatorOutputDimensionality === "EMBED_CONTENT") {
    const fromOutputDimensionality = getValueByPath(fromObject, [
      "outputDimensionality"
    ]);
    if (parentObject !== void 0 && fromOutputDimensionality != null) {
      setValueByPath(parentObject, ["outputDimensionality"], fromOutputDimensionality);
    }
  }
  let discriminatorMimeType = getValueByPath(rootObject, [
    "embeddingApiType"
  ]);
  if (discriminatorMimeType === void 0) {
    discriminatorMimeType = "PREDICT";
  }
  if (discriminatorMimeType === "PREDICT") {
    const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
    if (parentObject !== void 0 && fromMimeType != null) {
      setValueByPath(parentObject, ["instances[]", "mimeType"], fromMimeType);
    }
  }
  let discriminatorAutoTruncate = getValueByPath(rootObject, [
    "embeddingApiType"
  ]);
  if (discriminatorAutoTruncate === void 0) {
    discriminatorAutoTruncate = "PREDICT";
  }
  if (discriminatorAutoTruncate === "PREDICT") {
    const fromAutoTruncate = getValueByPath(fromObject, [
      "autoTruncate"
    ]);
    if (parentObject !== void 0 && fromAutoTruncate != null) {
      setValueByPath(parentObject, ["parameters", "autoTruncate"], fromAutoTruncate);
    }
  } else if (discriminatorAutoTruncate === "EMBED_CONTENT") {
    const fromAutoTruncate = getValueByPath(fromObject, [
      "autoTruncate"
    ]);
    if (parentObject !== void 0 && fromAutoTruncate != null) {
      setValueByPath(parentObject, ["autoTruncate"], fromAutoTruncate);
    }
  }
  return toObject;
}
function embedContentParametersPrivateToMldev(apiClient, fromObject, rootObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromContents = getValueByPath(fromObject, ["contents"]);
  if (fromContents != null) {
    let transformedList = tContentsForEmbed(apiClient, fromContents);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["requests[]", "content"], transformedList);
  }
  const fromContent = getValueByPath(fromObject, ["content"]);
  if (fromContent != null) {
    contentToMldev$1(tContent(fromContent));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    embedContentConfigToMldev(fromConfig, toObject);
  }
  const fromModelForEmbedContent = getValueByPath(fromObject, ["model"]);
  if (fromModelForEmbedContent !== void 0) {
    setValueByPath(toObject, ["requests[]", "model"], tModel(apiClient, fromModelForEmbedContent));
  }
  return toObject;
}
function embedContentParametersPrivateToVertex(apiClient, fromObject, rootObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  let discriminatorContents = getValueByPath(rootObject, [
    "embeddingApiType"
  ]);
  if (discriminatorContents === void 0) {
    discriminatorContents = "PREDICT";
  }
  if (discriminatorContents === "PREDICT") {
    const fromContents = getValueByPath(fromObject, ["contents"]);
    if (fromContents != null) {
      let transformedList = tContentsForEmbed(apiClient, fromContents);
      if (Array.isArray(transformedList)) {
        transformedList = transformedList.map((item) => {
          return item;
        });
      }
      setValueByPath(toObject, ["instances[]", "content"], transformedList);
    }
  }
  let discriminatorContent = getValueByPath(rootObject, [
    "embeddingApiType"
  ]);
  if (discriminatorContent === void 0) {
    discriminatorContent = "PREDICT";
  }
  if (discriminatorContent === "EMBED_CONTENT") {
    const fromContent = getValueByPath(fromObject, ["content"]);
    if (fromContent != null) {
      setValueByPath(toObject, ["content"], tContent(fromContent));
    }
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    embedContentConfigToVertex(fromConfig, toObject, rootObject);
  }
  return toObject;
}
function embedContentResponseFromMldev(fromObject, _rootObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromEmbeddings = getValueByPath(fromObject, ["embeddings"]);
  if (fromEmbeddings != null) {
    let transformedList = fromEmbeddings;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["embeddings"], transformedList);
  }
  const fromMetadata = getValueByPath(fromObject, ["metadata"]);
  if (fromMetadata != null) {
    setValueByPath(toObject, ["metadata"], fromMetadata);
  }
  return toObject;
}
function embedContentResponseFromVertex(fromObject, rootObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromEmbeddings = getValueByPath(fromObject, [
    "predictions[]",
    "embeddings"
  ]);
  if (fromEmbeddings != null) {
    let transformedList = fromEmbeddings;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return contentEmbeddingFromVertex(item);
      });
    }
    setValueByPath(toObject, ["embeddings"], transformedList);
  }
  const fromMetadata = getValueByPath(fromObject, ["metadata"]);
  if (fromMetadata != null) {
    setValueByPath(toObject, ["metadata"], fromMetadata);
  }
  if (rootObject && getValueByPath(rootObject, ["embeddingApiType"]) === "EMBED_CONTENT") {
    const embedding = getValueByPath(fromObject, ["embedding"]);
    const usageMetadata = getValueByPath(fromObject, ["usageMetadata"]);
    const truncated = getValueByPath(fromObject, ["truncated"]);
    if (embedding) {
      const stats = {};
      if (usageMetadata && usageMetadata["promptTokenCount"]) {
        stats.tokenCount = usageMetadata["promptTokenCount"];
      }
      if (truncated) {
        stats.truncated = truncated;
      }
      embedding.statistics = stats;
      setValueByPath(toObject, ["embeddings"], [embedding]);
    }
  }
  return toObject;
}
function endpointFromVertex(fromObject, _rootObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["endpoint"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromDeployedModelId = getValueByPath(fromObject, [
    "deployedModelId"
  ]);
  if (fromDeployedModelId != null) {
    setValueByPath(toObject, ["deployedModelId"], fromDeployedModelId);
  }
  return toObject;
}
function fileDataToMldev$1(fromObject, _rootObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["displayName"]) !== void 0) {
    throw new Error("displayName parameter is not supported in Gemini API.");
  }
  const fromFileUri = getValueByPath(fromObject, ["fileUri"]);
  if (fromFileUri != null) {
    setValueByPath(toObject, ["fileUri"], fromFileUri);
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function functionCallToMldev$1(fromObject, _rootObject) {
  const toObject = {};
  const fromId = getValueByPath(fromObject, ["id"]);
  if (fromId != null) {
    setValueByPath(toObject, ["id"], fromId);
  }
  const fromArgs = getValueByPath(fromObject, ["args"]);
  if (fromArgs != null) {
    setValueByPath(toObject, ["args"], fromArgs);
  }
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  if (getValueByPath(fromObject, ["partialArgs"]) !== void 0) {
    throw new Error("partialArgs parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["willContinue"]) !== void 0) {
    throw new Error("willContinue parameter is not supported in Gemini API.");
  }
  return toObject;
}
function functionCallingConfigToMldev(fromObject, _rootObject) {
  const toObject = {};
  const fromAllowedFunctionNames = getValueByPath(fromObject, [
    "allowedFunctionNames"
  ]);
  if (fromAllowedFunctionNames != null) {
    setValueByPath(toObject, ["allowedFunctionNames"], fromAllowedFunctionNames);
  }
  const fromMode = getValueByPath(fromObject, ["mode"]);
  if (fromMode != null) {
    setValueByPath(toObject, ["mode"], fromMode);
  }
  if (getValueByPath(fromObject, ["streamFunctionCallArguments"]) !== void 0) {
    throw new Error("streamFunctionCallArguments parameter is not supported in Gemini API.");
  }
  return toObject;
}
function functionDeclarationToVertex(fromObject, _rootObject) {
  const toObject = {};
  const fromDescription = getValueByPath(fromObject, ["description"]);
  if (fromDescription != null) {
    setValueByPath(toObject, ["description"], fromDescription);
  }
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromParameters = getValueByPath(fromObject, ["parameters"]);
  if (fromParameters != null) {
    setValueByPath(toObject, ["parameters"], fromParameters);
  }
  const fromParametersJsonSchema = getValueByPath(fromObject, [
    "parametersJsonSchema"
  ]);
  if (fromParametersJsonSchema != null) {
    setValueByPath(toObject, ["parametersJsonSchema"], fromParametersJsonSchema);
  }
  const fromResponse = getValueByPath(fromObject, ["response"]);
  if (fromResponse != null) {
    setValueByPath(toObject, ["response"], fromResponse);
  }
  const fromResponseJsonSchema = getValueByPath(fromObject, [
    "responseJsonSchema"
  ]);
  if (fromResponseJsonSchema != null) {
    setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema);
  }
  if (getValueByPath(fromObject, ["behavior"]) !== void 0) {
    throw new Error("behavior parameter is not supported in Vertex AI.");
  }
  return toObject;
}
function generateContentConfigToMldev(apiClient, fromObject, parentObject, rootObject) {
  const toObject = {};
  const fromSystemInstruction = getValueByPath(fromObject, [
    "systemInstruction"
  ]);
  if (parentObject !== void 0 && fromSystemInstruction != null) {
    setValueByPath(parentObject, ["systemInstruction"], contentToMldev$1(tContent(fromSystemInstruction)));
  }
  const fromTemperature = getValueByPath(fromObject, ["temperature"]);
  if (fromTemperature != null) {
    setValueByPath(toObject, ["temperature"], fromTemperature);
  }
  const fromTopP = getValueByPath(fromObject, ["topP"]);
  if (fromTopP != null) {
    setValueByPath(toObject, ["topP"], fromTopP);
  }
  const fromTopK = getValueByPath(fromObject, ["topK"]);
  if (fromTopK != null) {
    setValueByPath(toObject, ["topK"], fromTopK);
  }
  const fromCandidateCount = getValueByPath(fromObject, [
    "candidateCount"
  ]);
  if (fromCandidateCount != null) {
    setValueByPath(toObject, ["candidateCount"], fromCandidateCount);
  }
  const fromMaxOutputTokens = getValueByPath(fromObject, [
    "maxOutputTokens"
  ]);
  if (fromMaxOutputTokens != null) {
    setValueByPath(toObject, ["maxOutputTokens"], fromMaxOutputTokens);
  }
  const fromStopSequences = getValueByPath(fromObject, [
    "stopSequences"
  ]);
  if (fromStopSequences != null) {
    setValueByPath(toObject, ["stopSequences"], fromStopSequences);
  }
  const fromResponseLogprobs = getValueByPath(fromObject, [
    "responseLogprobs"
  ]);
  if (fromResponseLogprobs != null) {
    setValueByPath(toObject, ["responseLogprobs"], fromResponseLogprobs);
  }
  const fromLogprobs = getValueByPath(fromObject, ["logprobs"]);
  if (fromLogprobs != null) {
    setValueByPath(toObject, ["logprobs"], fromLogprobs);
  }
  const fromPresencePenalty = getValueByPath(fromObject, [
    "presencePenalty"
  ]);
  if (fromPresencePenalty != null) {
    setValueByPath(toObject, ["presencePenalty"], fromPresencePenalty);
  }
  const fromFrequencyPenalty = getValueByPath(fromObject, [
    "frequencyPenalty"
  ]);
  if (fromFrequencyPenalty != null) {
    setValueByPath(toObject, ["frequencyPenalty"], fromFrequencyPenalty);
  }
  const fromSeed = getValueByPath(fromObject, ["seed"]);
  if (fromSeed != null) {
    setValueByPath(toObject, ["seed"], fromSeed);
  }
  const fromResponseMimeType = getValueByPath(fromObject, [
    "responseMimeType"
  ]);
  if (fromResponseMimeType != null) {
    setValueByPath(toObject, ["responseMimeType"], fromResponseMimeType);
  }
  const fromResponseSchema = getValueByPath(fromObject, [
    "responseSchema"
  ]);
  if (fromResponseSchema != null) {
    setValueByPath(toObject, ["responseSchema"], tSchema(fromResponseSchema));
  }
  const fromResponseJsonSchema = getValueByPath(fromObject, [
    "responseJsonSchema"
  ]);
  if (fromResponseJsonSchema != null) {
    setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema);
  }
  if (getValueByPath(fromObject, ["routingConfig"]) !== void 0) {
    throw new Error("routingConfig parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["modelSelectionConfig"]) !== void 0) {
    throw new Error("modelSelectionConfig parameter is not supported in Gemini API.");
  }
  const fromSafetySettings = getValueByPath(fromObject, [
    "safetySettings"
  ]);
  if (parentObject !== void 0 && fromSafetySettings != null) {
    let transformedList = fromSafetySettings;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return safetySettingToMldev(item);
      });
    }
    setValueByPath(parentObject, ["safetySettings"], transformedList);
  }
  const fromTools = getValueByPath(fromObject, ["tools"]);
  if (parentObject !== void 0 && fromTools != null) {
    let transformedList = tTools(fromTools);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return toolToMldev$1(tTool(item));
      });
    }
    setValueByPath(parentObject, ["tools"], transformedList);
  }
  const fromToolConfig = getValueByPath(fromObject, ["toolConfig"]);
  if (parentObject !== void 0 && fromToolConfig != null) {
    setValueByPath(parentObject, ["toolConfig"], toolConfigToMldev(fromToolConfig));
  }
  if (getValueByPath(fromObject, ["labels"]) !== void 0) {
    throw new Error("labels parameter is not supported in Gemini API.");
  }
  const fromCachedContent = getValueByPath(fromObject, [
    "cachedContent"
  ]);
  if (parentObject !== void 0 && fromCachedContent != null) {
    setValueByPath(parentObject, ["cachedContent"], tCachedContentName(apiClient, fromCachedContent));
  }
  const fromResponseModalities = getValueByPath(fromObject, [
    "responseModalities"
  ]);
  if (fromResponseModalities != null) {
    setValueByPath(toObject, ["responseModalities"], fromResponseModalities);
  }
  const fromMediaResolution = getValueByPath(fromObject, [
    "mediaResolution"
  ]);
  if (fromMediaResolution != null) {
    setValueByPath(toObject, ["mediaResolution"], fromMediaResolution);
  }
  const fromSpeechConfig = getValueByPath(fromObject, ["speechConfig"]);
  if (fromSpeechConfig != null) {
    setValueByPath(toObject, ["speechConfig"], tSpeechConfig(fromSpeechConfig));
  }
  if (getValueByPath(fromObject, ["audioTimestamp"]) !== void 0) {
    throw new Error("audioTimestamp parameter is not supported in Gemini API.");
  }
  const fromThinkingConfig = getValueByPath(fromObject, [
    "thinkingConfig"
  ]);
  if (fromThinkingConfig != null) {
    setValueByPath(toObject, ["thinkingConfig"], fromThinkingConfig);
  }
  const fromImageConfig = getValueByPath(fromObject, ["imageConfig"]);
  if (fromImageConfig != null) {
    setValueByPath(toObject, ["imageConfig"], imageConfigToMldev(fromImageConfig));
  }
  const fromEnableEnhancedCivicAnswers = getValueByPath(fromObject, [
    "enableEnhancedCivicAnswers"
  ]);
  if (fromEnableEnhancedCivicAnswers != null) {
    setValueByPath(toObject, ["enableEnhancedCivicAnswers"], fromEnableEnhancedCivicAnswers);
  }
  if (getValueByPath(fromObject, ["modelArmorConfig"]) !== void 0) {
    throw new Error("modelArmorConfig parameter is not supported in Gemini API.");
  }
  return toObject;
}
function generateContentConfigToVertex(apiClient, fromObject, parentObject, rootObject) {
  const toObject = {};
  const fromSystemInstruction = getValueByPath(fromObject, [
    "systemInstruction"
  ]);
  if (parentObject !== void 0 && fromSystemInstruction != null) {
    setValueByPath(parentObject, ["systemInstruction"], tContent(fromSystemInstruction));
  }
  const fromTemperature = getValueByPath(fromObject, ["temperature"]);
  if (fromTemperature != null) {
    setValueByPath(toObject, ["temperature"], fromTemperature);
  }
  const fromTopP = getValueByPath(fromObject, ["topP"]);
  if (fromTopP != null) {
    setValueByPath(toObject, ["topP"], fromTopP);
  }
  const fromTopK = getValueByPath(fromObject, ["topK"]);
  if (fromTopK != null) {
    setValueByPath(toObject, ["topK"], fromTopK);
  }
  const fromCandidateCount = getValueByPath(fromObject, [
    "candidateCount"
  ]);
  if (fromCandidateCount != null) {
    setValueByPath(toObject, ["candidateCount"], fromCandidateCount);
  }
  const fromMaxOutputTokens = getValueByPath(fromObject, [
    "maxOutputTokens"
  ]);
  if (fromMaxOutputTokens != null) {
    setValueByPath(toObject, ["maxOutputTokens"], fromMaxOutputTokens);
  }
  const fromStopSequences = getValueByPath(fromObject, [
    "stopSequences"
  ]);
  if (fromStopSequences != null) {
    setValueByPath(toObject, ["stopSequences"], fromStopSequences);
  }
  const fromResponseLogprobs = getValueByPath(fromObject, [
    "responseLogprobs"
  ]);
  if (fromResponseLogprobs != null) {
    setValueByPath(toObject, ["responseLogprobs"], fromResponseLogprobs);
  }
  const fromLogprobs = getValueByPath(fromObject, ["logprobs"]);
  if (fromLogprobs != null) {
    setValueByPath(toObject, ["logprobs"], fromLogprobs);
  }
  const fromPresencePenalty = getValueByPath(fromObject, [
    "presencePenalty"
  ]);
  if (fromPresencePenalty != null) {
    setValueByPath(toObject, ["presencePenalty"], fromPresencePenalty);
  }
  const fromFrequencyPenalty = getValueByPath(fromObject, [
    "frequencyPenalty"
  ]);
  if (fromFrequencyPenalty != null) {
    setValueByPath(toObject, ["frequencyPenalty"], fromFrequencyPenalty);
  }
  const fromSeed = getValueByPath(fromObject, ["seed"]);
  if (fromSeed != null) {
    setValueByPath(toObject, ["seed"], fromSeed);
  }
  const fromResponseMimeType = getValueByPath(fromObject, [
    "responseMimeType"
  ]);
  if (fromResponseMimeType != null) {
    setValueByPath(toObject, ["responseMimeType"], fromResponseMimeType);
  }
  const fromResponseSchema = getValueByPath(fromObject, [
    "responseSchema"
  ]);
  if (fromResponseSchema != null) {
    setValueByPath(toObject, ["responseSchema"], tSchema(fromResponseSchema));
  }
  const fromResponseJsonSchema = getValueByPath(fromObject, [
    "responseJsonSchema"
  ]);
  if (fromResponseJsonSchema != null) {
    setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema);
  }
  const fromRoutingConfig = getValueByPath(fromObject, [
    "routingConfig"
  ]);
  if (fromRoutingConfig != null) {
    setValueByPath(toObject, ["routingConfig"], fromRoutingConfig);
  }
  const fromModelSelectionConfig = getValueByPath(fromObject, [
    "modelSelectionConfig"
  ]);
  if (fromModelSelectionConfig != null) {
    setValueByPath(toObject, ["modelConfig"], fromModelSelectionConfig);
  }
  const fromSafetySettings = getValueByPath(fromObject, [
    "safetySettings"
  ]);
  if (parentObject !== void 0 && fromSafetySettings != null) {
    let transformedList = fromSafetySettings;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(parentObject, ["safetySettings"], transformedList);
  }
  const fromTools = getValueByPath(fromObject, ["tools"]);
  if (parentObject !== void 0 && fromTools != null) {
    let transformedList = tTools(fromTools);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return toolToVertex(tTool(item));
      });
    }
    setValueByPath(parentObject, ["tools"], transformedList);
  }
  const fromToolConfig = getValueByPath(fromObject, ["toolConfig"]);
  if (parentObject !== void 0 && fromToolConfig != null) {
    setValueByPath(parentObject, ["toolConfig"], fromToolConfig);
  }
  const fromLabels = getValueByPath(fromObject, ["labels"]);
  if (parentObject !== void 0 && fromLabels != null) {
    setValueByPath(parentObject, ["labels"], fromLabels);
  }
  const fromCachedContent = getValueByPath(fromObject, [
    "cachedContent"
  ]);
  if (parentObject !== void 0 && fromCachedContent != null) {
    setValueByPath(parentObject, ["cachedContent"], tCachedContentName(apiClient, fromCachedContent));
  }
  const fromResponseModalities = getValueByPath(fromObject, [
    "responseModalities"
  ]);
  if (fromResponseModalities != null) {
    setValueByPath(toObject, ["responseModalities"], fromResponseModalities);
  }
  const fromMediaResolution = getValueByPath(fromObject, [
    "mediaResolution"
  ]);
  if (fromMediaResolution != null) {
    setValueByPath(toObject, ["mediaResolution"], fromMediaResolution);
  }
  const fromSpeechConfig = getValueByPath(fromObject, ["speechConfig"]);
  if (fromSpeechConfig != null) {
    setValueByPath(toObject, ["speechConfig"], tSpeechConfig(fromSpeechConfig));
  }
  const fromAudioTimestamp = getValueByPath(fromObject, [
    "audioTimestamp"
  ]);
  if (fromAudioTimestamp != null) {
    setValueByPath(toObject, ["audioTimestamp"], fromAudioTimestamp);
  }
  const fromThinkingConfig = getValueByPath(fromObject, [
    "thinkingConfig"
  ]);
  if (fromThinkingConfig != null) {
    setValueByPath(toObject, ["thinkingConfig"], fromThinkingConfig);
  }
  const fromImageConfig = getValueByPath(fromObject, ["imageConfig"]);
  if (fromImageConfig != null) {
    setValueByPath(toObject, ["imageConfig"], imageConfigToVertex(fromImageConfig));
  }
  if (getValueByPath(fromObject, ["enableEnhancedCivicAnswers"]) !== void 0) {
    throw new Error("enableEnhancedCivicAnswers parameter is not supported in Vertex AI.");
  }
  const fromModelArmorConfig = getValueByPath(fromObject, [
    "modelArmorConfig"
  ]);
  if (parentObject !== void 0 && fromModelArmorConfig != null) {
    setValueByPath(parentObject, ["modelArmorConfig"], fromModelArmorConfig);
  }
  return toObject;
}
function generateContentParametersToMldev(apiClient, fromObject, rootObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromContents = getValueByPath(fromObject, ["contents"]);
  if (fromContents != null) {
    let transformedList = tContents(fromContents);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return contentToMldev$1(item);
      });
    }
    setValueByPath(toObject, ["contents"], transformedList);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["generationConfig"], generateContentConfigToMldev(apiClient, fromConfig, toObject));
  }
  return toObject;
}
function generateContentParametersToVertex(apiClient, fromObject, rootObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromContents = getValueByPath(fromObject, ["contents"]);
  if (fromContents != null) {
    let transformedList = tContents(fromContents);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["contents"], transformedList);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["generationConfig"], generateContentConfigToVertex(apiClient, fromConfig, toObject));
  }
  return toObject;
}
function generateContentResponseFromMldev(fromObject, rootObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromCandidates = getValueByPath(fromObject, ["candidates"]);
  if (fromCandidates != null) {
    let transformedList = fromCandidates;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return candidateFromMldev(item);
      });
    }
    setValueByPath(toObject, ["candidates"], transformedList);
  }
  const fromModelVersion = getValueByPath(fromObject, ["modelVersion"]);
  if (fromModelVersion != null) {
    setValueByPath(toObject, ["modelVersion"], fromModelVersion);
  }
  const fromPromptFeedback = getValueByPath(fromObject, [
    "promptFeedback"
  ]);
  if (fromPromptFeedback != null) {
    setValueByPath(toObject, ["promptFeedback"], fromPromptFeedback);
  }
  const fromResponseId = getValueByPath(fromObject, ["responseId"]);
  if (fromResponseId != null) {
    setValueByPath(toObject, ["responseId"], fromResponseId);
  }
  const fromUsageMetadata = getValueByPath(fromObject, [
    "usageMetadata"
  ]);
  if (fromUsageMetadata != null) {
    setValueByPath(toObject, ["usageMetadata"], fromUsageMetadata);
  }
  return toObject;
}
function generateContentResponseFromVertex(fromObject, _rootObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromCandidates = getValueByPath(fromObject, ["candidates"]);
  if (fromCandidates != null) {
    let transformedList = fromCandidates;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["candidates"], transformedList);
  }
  const fromCreateTime = getValueByPath(fromObject, ["createTime"]);
  if (fromCreateTime != null) {
    setValueByPath(toObject, ["createTime"], fromCreateTime);
  }
  const fromModelVersion = getValueByPath(fromObject, ["modelVersion"]);
  if (fromModelVersion != null) {
    setValueByPath(toObject, ["modelVersion"], fromModelVersion);
  }
  const fromPromptFeedback = getValueByPath(fromObject, [
    "promptFeedback"
  ]);
  if (fromPromptFeedback != null) {
    setValueByPath(toObject, ["promptFeedback"], fromPromptFeedback);
  }
  const fromResponseId = getValueByPath(fromObject, ["responseId"]);
  if (fromResponseId != null) {
    setValueByPath(toObject, ["responseId"], fromResponseId);
  }
  const fromUsageMetadata = getValueByPath(fromObject, [
    "usageMetadata"
  ]);
  if (fromUsageMetadata != null) {
    setValueByPath(toObject, ["usageMetadata"], fromUsageMetadata);
  }
  return toObject;
}
function generateImagesConfigToMldev(fromObject, parentObject, _rootObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["outputGcsUri"]) !== void 0) {
    throw new Error("outputGcsUri parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["negativePrompt"]) !== void 0) {
    throw new Error("negativePrompt parameter is not supported in Gemini API.");
  }
  const fromNumberOfImages = getValueByPath(fromObject, [
    "numberOfImages"
  ]);
  if (parentObject !== void 0 && fromNumberOfImages != null) {
    setValueByPath(parentObject, ["parameters", "sampleCount"], fromNumberOfImages);
  }
  const fromAspectRatio = getValueByPath(fromObject, ["aspectRatio"]);
  if (parentObject !== void 0 && fromAspectRatio != null) {
    setValueByPath(parentObject, ["parameters", "aspectRatio"], fromAspectRatio);
  }
  const fromGuidanceScale = getValueByPath(fromObject, [
    "guidanceScale"
  ]);
  if (parentObject !== void 0 && fromGuidanceScale != null) {
    setValueByPath(parentObject, ["parameters", "guidanceScale"], fromGuidanceScale);
  }
  if (getValueByPath(fromObject, ["seed"]) !== void 0) {
    throw new Error("seed parameter is not supported in Gemini API.");
  }
  const fromSafetyFilterLevel = getValueByPath(fromObject, [
    "safetyFilterLevel"
  ]);
  if (parentObject !== void 0 && fromSafetyFilterLevel != null) {
    setValueByPath(parentObject, ["parameters", "safetySetting"], fromSafetyFilterLevel);
  }
  const fromPersonGeneration = getValueByPath(fromObject, [
    "personGeneration"
  ]);
  if (parentObject !== void 0 && fromPersonGeneration != null) {
    setValueByPath(parentObject, ["parameters", "personGeneration"], fromPersonGeneration);
  }
  const fromIncludeSafetyAttributes = getValueByPath(fromObject, [
    "includeSafetyAttributes"
  ]);
  if (parentObject !== void 0 && fromIncludeSafetyAttributes != null) {
    setValueByPath(parentObject, ["parameters", "includeSafetyAttributes"], fromIncludeSafetyAttributes);
  }
  const fromIncludeRaiReason = getValueByPath(fromObject, [
    "includeRaiReason"
  ]);
  if (parentObject !== void 0 && fromIncludeRaiReason != null) {
    setValueByPath(parentObject, ["parameters", "includeRaiReason"], fromIncludeRaiReason);
  }
  const fromLanguage = getValueByPath(fromObject, ["language"]);
  if (parentObject !== void 0 && fromLanguage != null) {
    setValueByPath(parentObject, ["parameters", "language"], fromLanguage);
  }
  const fromOutputMimeType = getValueByPath(fromObject, [
    "outputMimeType"
  ]);
  if (parentObject !== void 0 && fromOutputMimeType != null) {
    setValueByPath(parentObject, ["parameters", "outputOptions", "mimeType"], fromOutputMimeType);
  }
  const fromOutputCompressionQuality = getValueByPath(fromObject, [
    "outputCompressionQuality"
  ]);
  if (parentObject !== void 0 && fromOutputCompressionQuality != null) {
    setValueByPath(parentObject, ["parameters", "outputOptions", "compressionQuality"], fromOutputCompressionQuality);
  }
  if (getValueByPath(fromObject, ["addWatermark"]) !== void 0) {
    throw new Error("addWatermark parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["labels"]) !== void 0) {
    throw new Error("labels parameter is not supported in Gemini API.");
  }
  const fromImageSize = getValueByPath(fromObject, ["imageSize"]);
  if (parentObject !== void 0 && fromImageSize != null) {
    setValueByPath(parentObject, ["parameters", "sampleImageSize"], fromImageSize);
  }
  if (getValueByPath(fromObject, ["enhancePrompt"]) !== void 0) {
    throw new Error("enhancePrompt parameter is not supported in Gemini API.");
  }
  return toObject;
}
function generateImagesConfigToVertex(fromObject, parentObject, _rootObject) {
  const toObject = {};
  const fromOutputGcsUri = getValueByPath(fromObject, ["outputGcsUri"]);
  if (parentObject !== void 0 && fromOutputGcsUri != null) {
    setValueByPath(parentObject, ["parameters", "storageUri"], fromOutputGcsUri);
  }
  const fromNegativePrompt = getValueByPath(fromObject, [
    "negativePrompt"
  ]);
  if (parentObject !== void 0 && fromNegativePrompt != null) {
    setValueByPath(parentObject, ["parameters", "negativePrompt"], fromNegativePrompt);
  }
  const fromNumberOfImages = getValueByPath(fromObject, [
    "numberOfImages"
  ]);
  if (parentObject !== void 0 && fromNumberOfImages != null) {
    setValueByPath(parentObject, ["parameters", "sampleCount"], fromNumberOfImages);
  }
  const fromAspectRatio = getValueByPath(fromObject, ["aspectRatio"]);
  if (parentObject !== void 0 && fromAspectRatio != null) {
    setValueByPath(parentObject, ["parameters", "aspectRatio"], fromAspectRatio);
  }
  const fromGuidanceScale = getValueByPath(fromObject, [
    "guidanceScale"
  ]);
  if (parentObject !== void 0 && fromGuidanceScale != null) {
    setValueByPath(parentObject, ["parameters", "guidanceScale"], fromGuidanceScale);
  }
  const fromSeed = getValueByPath(fromObject, ["seed"]);
  if (parentObject !== void 0 && fromSeed != null) {
    setValueByPath(parentObject, ["parameters", "seed"], fromSeed);
  }
  const fromSafetyFilterLevel = getValueByPath(fromObject, [
    "safetyFilterLevel"
  ]);
  if (parentObject !== void 0 && fromSafetyFilterLevel != null) {
    setValueByPath(parentObject, ["parameters", "safetySetting"], fromSafetyFilterLevel);
  }
  const fromPersonGeneration = getValueByPath(fromObject, [
    "personGeneration"
  ]);
  if (parentObject !== void 0 && fromPersonGeneration != null) {
    setValueByPath(parentObject, ["parameters", "personGeneration"], fromPersonGeneration);
  }
  const fromIncludeSafetyAttributes = getValueByPath(fromObject, [
    "includeSafetyAttributes"
  ]);
  if (parentObject !== void 0 && fromIncludeSafetyAttributes != null) {
    setValueByPath(parentObject, ["parameters", "includeSafetyAttributes"], fromIncludeSafetyAttributes);
  }
  const fromIncludeRaiReason = getValueByPath(fromObject, [
    "includeRaiReason"
  ]);
  if (parentObject !== void 0 && fromIncludeRaiReason != null) {
    setValueByPath(parentObject, ["parameters", "includeRaiReason"], fromIncludeRaiReason);
  }
  const fromLanguage = getValueByPath(fromObject, ["language"]);
  if (parentObject !== void 0 && fromLanguage != null) {
    setValueByPath(parentObject, ["parameters", "language"], fromLanguage);
  }
  const fromOutputMimeType = getValueByPath(fromObject, [
    "outputMimeType"
  ]);
  if (parentObject !== void 0 && fromOutputMimeType != null) {
    setValueByPath(parentObject, ["parameters", "outputOptions", "mimeType"], fromOutputMimeType);
  }
  const fromOutputCompressionQuality = getValueByPath(fromObject, [
    "outputCompressionQuality"
  ]);
  if (parentObject !== void 0 && fromOutputCompressionQuality != null) {
    setValueByPath(parentObject, ["parameters", "outputOptions", "compressionQuality"], fromOutputCompressionQuality);
  }
  const fromAddWatermark = getValueByPath(fromObject, ["addWatermark"]);
  if (parentObject !== void 0 && fromAddWatermark != null) {
    setValueByPath(parentObject, ["parameters", "addWatermark"], fromAddWatermark);
  }
  const fromLabels = getValueByPath(fromObject, ["labels"]);
  if (parentObject !== void 0 && fromLabels != null) {
    setValueByPath(parentObject, ["labels"], fromLabels);
  }
  const fromImageSize = getValueByPath(fromObject, ["imageSize"]);
  if (parentObject !== void 0 && fromImageSize != null) {
    setValueByPath(parentObject, ["parameters", "sampleImageSize"], fromImageSize);
  }
  const fromEnhancePrompt = getValueByPath(fromObject, [
    "enhancePrompt"
  ]);
  if (parentObject !== void 0 && fromEnhancePrompt != null) {
    setValueByPath(parentObject, ["parameters", "enhancePrompt"], fromEnhancePrompt);
  }
  return toObject;
}
function generateImagesParametersToMldev(apiClient, fromObject, rootObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromPrompt = getValueByPath(fromObject, ["prompt"]);
  if (fromPrompt != null) {
    setValueByPath(toObject, ["instances[0]", "prompt"], fromPrompt);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    generateImagesConfigToMldev(fromConfig, toObject);
  }
  return toObject;
}
function generateImagesParametersToVertex(apiClient, fromObject, rootObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromPrompt = getValueByPath(fromObject, ["prompt"]);
  if (fromPrompt != null) {
    setValueByPath(toObject, ["instances[0]", "prompt"], fromPrompt);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    generateImagesConfigToVertex(fromConfig, toObject);
  }
  return toObject;
}
function generateImagesResponseFromMldev(fromObject, rootObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromGeneratedImages = getValueByPath(fromObject, [
    "predictions"
  ]);
  if (fromGeneratedImages != null) {
    let transformedList = fromGeneratedImages;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return generatedImageFromMldev(item);
      });
    }
    setValueByPath(toObject, ["generatedImages"], transformedList);
  }
  const fromPositivePromptSafetyAttributes = getValueByPath(fromObject, [
    "positivePromptSafetyAttributes"
  ]);
  if (fromPositivePromptSafetyAttributes != null) {
    setValueByPath(toObject, ["positivePromptSafetyAttributes"], safetyAttributesFromMldev(fromPositivePromptSafetyAttributes));
  }
  return toObject;
}
function generateImagesResponseFromVertex(fromObject, rootObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromGeneratedImages = getValueByPath(fromObject, [
    "predictions"
  ]);
  if (fromGeneratedImages != null) {
    let transformedList = fromGeneratedImages;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return generatedImageFromVertex(item);
      });
    }
    setValueByPath(toObject, ["generatedImages"], transformedList);
  }
  const fromPositivePromptSafetyAttributes = getValueByPath(fromObject, [
    "positivePromptSafetyAttributes"
  ]);
  if (fromPositivePromptSafetyAttributes != null) {
    setValueByPath(toObject, ["positivePromptSafetyAttributes"], safetyAttributesFromVertex(fromPositivePromptSafetyAttributes));
  }
  return toObject;
}
function generateVideosConfigToMldev(fromObject, parentObject, rootObject) {
  const toObject = {};
  const fromNumberOfVideos = getValueByPath(fromObject, [
    "numberOfVideos"
  ]);
  if (parentObject !== void 0 && fromNumberOfVideos != null) {
    setValueByPath(parentObject, ["parameters", "sampleCount"], fromNumberOfVideos);
  }
  if (getValueByPath(fromObject, ["outputGcsUri"]) !== void 0) {
    throw new Error("outputGcsUri parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["fps"]) !== void 0) {
    throw new Error("fps parameter is not supported in Gemini API.");
  }
  const fromDurationSeconds = getValueByPath(fromObject, [
    "durationSeconds"
  ]);
  if (parentObject !== void 0 && fromDurationSeconds != null) {
    setValueByPath(parentObject, ["parameters", "durationSeconds"], fromDurationSeconds);
  }
  if (getValueByPath(fromObject, ["seed"]) !== void 0) {
    throw new Error("seed parameter is not supported in Gemini API.");
  }
  const fromAspectRatio = getValueByPath(fromObject, ["aspectRatio"]);
  if (parentObject !== void 0 && fromAspectRatio != null) {
    setValueByPath(parentObject, ["parameters", "aspectRatio"], fromAspectRatio);
  }
  const fromResolution = getValueByPath(fromObject, ["resolution"]);
  if (parentObject !== void 0 && fromResolution != null) {
    setValueByPath(parentObject, ["parameters", "resolution"], fromResolution);
  }
  const fromPersonGeneration = getValueByPath(fromObject, [
    "personGeneration"
  ]);
  if (parentObject !== void 0 && fromPersonGeneration != null) {
    setValueByPath(parentObject, ["parameters", "personGeneration"], fromPersonGeneration);
  }
  if (getValueByPath(fromObject, ["pubsubTopic"]) !== void 0) {
    throw new Error("pubsubTopic parameter is not supported in Gemini API.");
  }
  const fromNegativePrompt = getValueByPath(fromObject, [
    "negativePrompt"
  ]);
  if (parentObject !== void 0 && fromNegativePrompt != null) {
    setValueByPath(parentObject, ["parameters", "negativePrompt"], fromNegativePrompt);
  }
  const fromEnhancePrompt = getValueByPath(fromObject, [
    "enhancePrompt"
  ]);
  if (parentObject !== void 0 && fromEnhancePrompt != null) {
    setValueByPath(parentObject, ["parameters", "enhancePrompt"], fromEnhancePrompt);
  }
  if (getValueByPath(fromObject, ["generateAudio"]) !== void 0) {
    throw new Error("generateAudio parameter is not supported in Gemini API.");
  }
  const fromLastFrame = getValueByPath(fromObject, ["lastFrame"]);
  if (parentObject !== void 0 && fromLastFrame != null) {
    setValueByPath(parentObject, ["instances[0]", "lastFrame"], imageToMldev(fromLastFrame));
  }
  const fromReferenceImages = getValueByPath(fromObject, [
    "referenceImages"
  ]);
  if (parentObject !== void 0 && fromReferenceImages != null) {
    let transformedList = fromReferenceImages;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return videoGenerationReferenceImageToMldev(item);
      });
    }
    setValueByPath(parentObject, ["instances[0]", "referenceImages"], transformedList);
  }
  if (getValueByPath(fromObject, ["mask"]) !== void 0) {
    throw new Error("mask parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["compressionQuality"]) !== void 0) {
    throw new Error("compressionQuality parameter is not supported in Gemini API.");
  }
  return toObject;
}
function generateVideosConfigToVertex(fromObject, parentObject, rootObject) {
  const toObject = {};
  const fromNumberOfVideos = getValueByPath(fromObject, [
    "numberOfVideos"
  ]);
  if (parentObject !== void 0 && fromNumberOfVideos != null) {
    setValueByPath(parentObject, ["parameters", "sampleCount"], fromNumberOfVideos);
  }
  const fromOutputGcsUri = getValueByPath(fromObject, ["outputGcsUri"]);
  if (parentObject !== void 0 && fromOutputGcsUri != null) {
    setValueByPath(parentObject, ["parameters", "storageUri"], fromOutputGcsUri);
  }
  const fromFps = getValueByPath(fromObject, ["fps"]);
  if (parentObject !== void 0 && fromFps != null) {
    setValueByPath(parentObject, ["parameters", "fps"], fromFps);
  }
  const fromDurationSeconds = getValueByPath(fromObject, [
    "durationSeconds"
  ]);
  if (parentObject !== void 0 && fromDurationSeconds != null) {
    setValueByPath(parentObject, ["parameters", "durationSeconds"], fromDurationSeconds);
  }
  const fromSeed = getValueByPath(fromObject, ["seed"]);
  if (parentObject !== void 0 && fromSeed != null) {
    setValueByPath(parentObject, ["parameters", "seed"], fromSeed);
  }
  const fromAspectRatio = getValueByPath(fromObject, ["aspectRatio"]);
  if (parentObject !== void 0 && fromAspectRatio != null) {
    setValueByPath(parentObject, ["parameters", "aspectRatio"], fromAspectRatio);
  }
  const fromResolution = getValueByPath(fromObject, ["resolution"]);
  if (parentObject !== void 0 && fromResolution != null) {
    setValueByPath(parentObject, ["parameters", "resolution"], fromResolution);
  }
  const fromPersonGeneration = getValueByPath(fromObject, [
    "personGeneration"
  ]);
  if (parentObject !== void 0 && fromPersonGeneration != null) {
    setValueByPath(parentObject, ["parameters", "personGeneration"], fromPersonGeneration);
  }
  const fromPubsubTopic = getValueByPath(fromObject, ["pubsubTopic"]);
  if (parentObject !== void 0 && fromPubsubTopic != null) {
    setValueByPath(parentObject, ["parameters", "pubsubTopic"], fromPubsubTopic);
  }
  const fromNegativePrompt = getValueByPath(fromObject, [
    "negativePrompt"
  ]);
  if (parentObject !== void 0 && fromNegativePrompt != null) {
    setValueByPath(parentObject, ["parameters", "negativePrompt"], fromNegativePrompt);
  }
  const fromEnhancePrompt = getValueByPath(fromObject, [
    "enhancePrompt"
  ]);
  if (parentObject !== void 0 && fromEnhancePrompt != null) {
    setValueByPath(parentObject, ["parameters", "enhancePrompt"], fromEnhancePrompt);
  }
  const fromGenerateAudio = getValueByPath(fromObject, [
    "generateAudio"
  ]);
  if (parentObject !== void 0 && fromGenerateAudio != null) {
    setValueByPath(parentObject, ["parameters", "generateAudio"], fromGenerateAudio);
  }
  const fromLastFrame = getValueByPath(fromObject, ["lastFrame"]);
  if (parentObject !== void 0 && fromLastFrame != null) {
    setValueByPath(parentObject, ["instances[0]", "lastFrame"], imageToVertex(fromLastFrame));
  }
  const fromReferenceImages = getValueByPath(fromObject, [
    "referenceImages"
  ]);
  if (parentObject !== void 0 && fromReferenceImages != null) {
    let transformedList = fromReferenceImages;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return videoGenerationReferenceImageToVertex(item);
      });
    }
    setValueByPath(parentObject, ["instances[0]", "referenceImages"], transformedList);
  }
  const fromMask = getValueByPath(fromObject, ["mask"]);
  if (parentObject !== void 0 && fromMask != null) {
    setValueByPath(parentObject, ["instances[0]", "mask"], videoGenerationMaskToVertex(fromMask));
  }
  const fromCompressionQuality = getValueByPath(fromObject, [
    "compressionQuality"
  ]);
  if (parentObject !== void 0 && fromCompressionQuality != null) {
    setValueByPath(parentObject, ["parameters", "compressionQuality"], fromCompressionQuality);
  }
  return toObject;
}
function generateVideosOperationFromMldev(fromObject, rootObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromMetadata = getValueByPath(fromObject, ["metadata"]);
  if (fromMetadata != null) {
    setValueByPath(toObject, ["metadata"], fromMetadata);
  }
  const fromDone = getValueByPath(fromObject, ["done"]);
  if (fromDone != null) {
    setValueByPath(toObject, ["done"], fromDone);
  }
  const fromError = getValueByPath(fromObject, ["error"]);
  if (fromError != null) {
    setValueByPath(toObject, ["error"], fromError);
  }
  const fromResponse = getValueByPath(fromObject, [
    "response",
    "generateVideoResponse"
  ]);
  if (fromResponse != null) {
    setValueByPath(toObject, ["response"], generateVideosResponseFromMldev(fromResponse));
  }
  return toObject;
}
function generateVideosOperationFromVertex(fromObject, rootObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromMetadata = getValueByPath(fromObject, ["metadata"]);
  if (fromMetadata != null) {
    setValueByPath(toObject, ["metadata"], fromMetadata);
  }
  const fromDone = getValueByPath(fromObject, ["done"]);
  if (fromDone != null) {
    setValueByPath(toObject, ["done"], fromDone);
  }
  const fromError = getValueByPath(fromObject, ["error"]);
  if (fromError != null) {
    setValueByPath(toObject, ["error"], fromError);
  }
  const fromResponse = getValueByPath(fromObject, ["response"]);
  if (fromResponse != null) {
    setValueByPath(toObject, ["response"], generateVideosResponseFromVertex(fromResponse));
  }
  return toObject;
}
function generateVideosParametersToMldev(apiClient, fromObject, rootObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromPrompt = getValueByPath(fromObject, ["prompt"]);
  if (fromPrompt != null) {
    setValueByPath(toObject, ["instances[0]", "prompt"], fromPrompt);
  }
  const fromImage = getValueByPath(fromObject, ["image"]);
  if (fromImage != null) {
    setValueByPath(toObject, ["instances[0]", "image"], imageToMldev(fromImage));
  }
  const fromVideo = getValueByPath(fromObject, ["video"]);
  if (fromVideo != null) {
    setValueByPath(toObject, ["instances[0]", "video"], videoToMldev(fromVideo));
  }
  const fromSource = getValueByPath(fromObject, ["source"]);
  if (fromSource != null) {
    generateVideosSourceToMldev(fromSource, toObject);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    generateVideosConfigToMldev(fromConfig, toObject);
  }
  return toObject;
}
function generateVideosParametersToVertex(apiClient, fromObject, rootObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromPrompt = getValueByPath(fromObject, ["prompt"]);
  if (fromPrompt != null) {
    setValueByPath(toObject, ["instances[0]", "prompt"], fromPrompt);
  }
  const fromImage = getValueByPath(fromObject, ["image"]);
  if (fromImage != null) {
    setValueByPath(toObject, ["instances[0]", "image"], imageToVertex(fromImage));
  }
  const fromVideo = getValueByPath(fromObject, ["video"]);
  if (fromVideo != null) {
    setValueByPath(toObject, ["instances[0]", "video"], videoToVertex(fromVideo));
  }
  const fromSource = getValueByPath(fromObject, ["source"]);
  if (fromSource != null) {
    generateVideosSourceToVertex(fromSource, toObject);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    generateVideosConfigToVertex(fromConfig, toObject);
  }
  return toObject;
}
function generateVideosResponseFromMldev(fromObject, rootObject) {
  const toObject = {};
  const fromGeneratedVideos = getValueByPath(fromObject, [
    "generatedSamples"
  ]);
  if (fromGeneratedVideos != null) {
    let transformedList = fromGeneratedVideos;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return generatedVideoFromMldev(item);
      });
    }
    setValueByPath(toObject, ["generatedVideos"], transformedList);
  }
  const fromRaiMediaFilteredCount = getValueByPath(fromObject, [
    "raiMediaFilteredCount"
  ]);
  if (fromRaiMediaFilteredCount != null) {
    setValueByPath(toObject, ["raiMediaFilteredCount"], fromRaiMediaFilteredCount);
  }
  const fromRaiMediaFilteredReasons = getValueByPath(fromObject, [
    "raiMediaFilteredReasons"
  ]);
  if (fromRaiMediaFilteredReasons != null) {
    setValueByPath(toObject, ["raiMediaFilteredReasons"], fromRaiMediaFilteredReasons);
  }
  return toObject;
}
function generateVideosResponseFromVertex(fromObject, rootObject) {
  const toObject = {};
  const fromGeneratedVideos = getValueByPath(fromObject, ["videos"]);
  if (fromGeneratedVideos != null) {
    let transformedList = fromGeneratedVideos;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return generatedVideoFromVertex(item);
      });
    }
    setValueByPath(toObject, ["generatedVideos"], transformedList);
  }
  const fromRaiMediaFilteredCount = getValueByPath(fromObject, [
    "raiMediaFilteredCount"
  ]);
  if (fromRaiMediaFilteredCount != null) {
    setValueByPath(toObject, ["raiMediaFilteredCount"], fromRaiMediaFilteredCount);
  }
  const fromRaiMediaFilteredReasons = getValueByPath(fromObject, [
    "raiMediaFilteredReasons"
  ]);
  if (fromRaiMediaFilteredReasons != null) {
    setValueByPath(toObject, ["raiMediaFilteredReasons"], fromRaiMediaFilteredReasons);
  }
  return toObject;
}
function generateVideosSourceToMldev(fromObject, parentObject, rootObject) {
  const toObject = {};
  const fromPrompt = getValueByPath(fromObject, ["prompt"]);
  if (parentObject !== void 0 && fromPrompt != null) {
    setValueByPath(parentObject, ["instances[0]", "prompt"], fromPrompt);
  }
  const fromImage = getValueByPath(fromObject, ["image"]);
  if (parentObject !== void 0 && fromImage != null) {
    setValueByPath(parentObject, ["instances[0]", "image"], imageToMldev(fromImage));
  }
  const fromVideo = getValueByPath(fromObject, ["video"]);
  if (parentObject !== void 0 && fromVideo != null) {
    setValueByPath(parentObject, ["instances[0]", "video"], videoToMldev(fromVideo));
  }
  return toObject;
}
function generateVideosSourceToVertex(fromObject, parentObject, rootObject) {
  const toObject = {};
  const fromPrompt = getValueByPath(fromObject, ["prompt"]);
  if (parentObject !== void 0 && fromPrompt != null) {
    setValueByPath(parentObject, ["instances[0]", "prompt"], fromPrompt);
  }
  const fromImage = getValueByPath(fromObject, ["image"]);
  if (parentObject !== void 0 && fromImage != null) {
    setValueByPath(parentObject, ["instances[0]", "image"], imageToVertex(fromImage));
  }
  const fromVideo = getValueByPath(fromObject, ["video"]);
  if (parentObject !== void 0 && fromVideo != null) {
    setValueByPath(parentObject, ["instances[0]", "video"], videoToVertex(fromVideo));
  }
  return toObject;
}
function generatedImageFromMldev(fromObject, rootObject) {
  const toObject = {};
  const fromImage = getValueByPath(fromObject, ["_self"]);
  if (fromImage != null) {
    setValueByPath(toObject, ["image"], imageFromMldev(fromImage));
  }
  const fromRaiFilteredReason = getValueByPath(fromObject, [
    "raiFilteredReason"
  ]);
  if (fromRaiFilteredReason != null) {
    setValueByPath(toObject, ["raiFilteredReason"], fromRaiFilteredReason);
  }
  const fromSafetyAttributes = getValueByPath(fromObject, ["_self"]);
  if (fromSafetyAttributes != null) {
    setValueByPath(toObject, ["safetyAttributes"], safetyAttributesFromMldev(fromSafetyAttributes));
  }
  return toObject;
}
function generatedImageFromVertex(fromObject, rootObject) {
  const toObject = {};
  const fromImage = getValueByPath(fromObject, ["_self"]);
  if (fromImage != null) {
    setValueByPath(toObject, ["image"], imageFromVertex(fromImage));
  }
  const fromRaiFilteredReason = getValueByPath(fromObject, [
    "raiFilteredReason"
  ]);
  if (fromRaiFilteredReason != null) {
    setValueByPath(toObject, ["raiFilteredReason"], fromRaiFilteredReason);
  }
  const fromSafetyAttributes = getValueByPath(fromObject, ["_self"]);
  if (fromSafetyAttributes != null) {
    setValueByPath(toObject, ["safetyAttributes"], safetyAttributesFromVertex(fromSafetyAttributes));
  }
  const fromEnhancedPrompt = getValueByPath(fromObject, ["prompt"]);
  if (fromEnhancedPrompt != null) {
    setValueByPath(toObject, ["enhancedPrompt"], fromEnhancedPrompt);
  }
  return toObject;
}
function generatedImageMaskFromVertex(fromObject, rootObject) {
  const toObject = {};
  const fromMask = getValueByPath(fromObject, ["_self"]);
  if (fromMask != null) {
    setValueByPath(toObject, ["mask"], imageFromVertex(fromMask));
  }
  const fromLabels = getValueByPath(fromObject, ["labels"]);
  if (fromLabels != null) {
    let transformedList = fromLabels;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["labels"], transformedList);
  }
  return toObject;
}
function generatedVideoFromMldev(fromObject, rootObject) {
  const toObject = {};
  const fromVideo = getValueByPath(fromObject, ["video"]);
  if (fromVideo != null) {
    setValueByPath(toObject, ["video"], videoFromMldev(fromVideo));
  }
  return toObject;
}
function generatedVideoFromVertex(fromObject, rootObject) {
  const toObject = {};
  const fromVideo = getValueByPath(fromObject, ["_self"]);
  if (fromVideo != null) {
    setValueByPath(toObject, ["video"], videoFromVertex(fromVideo));
  }
  return toObject;
}
function generationConfigToVertex(fromObject, _rootObject) {
  const toObject = {};
  const fromModelSelectionConfig = getValueByPath(fromObject, [
    "modelSelectionConfig"
  ]);
  if (fromModelSelectionConfig != null) {
    setValueByPath(toObject, ["modelConfig"], fromModelSelectionConfig);
  }
  const fromResponseJsonSchema = getValueByPath(fromObject, [
    "responseJsonSchema"
  ]);
  if (fromResponseJsonSchema != null) {
    setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema);
  }
  const fromAudioTimestamp = getValueByPath(fromObject, [
    "audioTimestamp"
  ]);
  if (fromAudioTimestamp != null) {
    setValueByPath(toObject, ["audioTimestamp"], fromAudioTimestamp);
  }
  const fromCandidateCount = getValueByPath(fromObject, [
    "candidateCount"
  ]);
  if (fromCandidateCount != null) {
    setValueByPath(toObject, ["candidateCount"], fromCandidateCount);
  }
  const fromEnableAffectiveDialog = getValueByPath(fromObject, [
    "enableAffectiveDialog"
  ]);
  if (fromEnableAffectiveDialog != null) {
    setValueByPath(toObject, ["enableAffectiveDialog"], fromEnableAffectiveDialog);
  }
  const fromFrequencyPenalty = getValueByPath(fromObject, [
    "frequencyPenalty"
  ]);
  if (fromFrequencyPenalty != null) {
    setValueByPath(toObject, ["frequencyPenalty"], fromFrequencyPenalty);
  }
  const fromLogprobs = getValueByPath(fromObject, ["logprobs"]);
  if (fromLogprobs != null) {
    setValueByPath(toObject, ["logprobs"], fromLogprobs);
  }
  const fromMaxOutputTokens = getValueByPath(fromObject, [
    "maxOutputTokens"
  ]);
  if (fromMaxOutputTokens != null) {
    setValueByPath(toObject, ["maxOutputTokens"], fromMaxOutputTokens);
  }
  const fromMediaResolution = getValueByPath(fromObject, [
    "mediaResolution"
  ]);
  if (fromMediaResolution != null) {
    setValueByPath(toObject, ["mediaResolution"], fromMediaResolution);
  }
  const fromPresencePenalty = getValueByPath(fromObject, [
    "presencePenalty"
  ]);
  if (fromPresencePenalty != null) {
    setValueByPath(toObject, ["presencePenalty"], fromPresencePenalty);
  }
  const fromResponseLogprobs = getValueByPath(fromObject, [
    "responseLogprobs"
  ]);
  if (fromResponseLogprobs != null) {
    setValueByPath(toObject, ["responseLogprobs"], fromResponseLogprobs);
  }
  const fromResponseMimeType = getValueByPath(fromObject, [
    "responseMimeType"
  ]);
  if (fromResponseMimeType != null) {
    setValueByPath(toObject, ["responseMimeType"], fromResponseMimeType);
  }
  const fromResponseModalities = getValueByPath(fromObject, [
    "responseModalities"
  ]);
  if (fromResponseModalities != null) {
    setValueByPath(toObject, ["responseModalities"], fromResponseModalities);
  }
  const fromResponseSchema = getValueByPath(fromObject, [
    "responseSchema"
  ]);
  if (fromResponseSchema != null) {
    setValueByPath(toObject, ["responseSchema"], fromResponseSchema);
  }
  const fromRoutingConfig = getValueByPath(fromObject, [
    "routingConfig"
  ]);
  if (fromRoutingConfig != null) {
    setValueByPath(toObject, ["routingConfig"], fromRoutingConfig);
  }
  const fromSeed = getValueByPath(fromObject, ["seed"]);
  if (fromSeed != null) {
    setValueByPath(toObject, ["seed"], fromSeed);
  }
  const fromSpeechConfig = getValueByPath(fromObject, ["speechConfig"]);
  if (fromSpeechConfig != null) {
    setValueByPath(toObject, ["speechConfig"], fromSpeechConfig);
  }
  const fromStopSequences = getValueByPath(fromObject, [
    "stopSequences"
  ]);
  if (fromStopSequences != null) {
    setValueByPath(toObject, ["stopSequences"], fromStopSequences);
  }
  const fromTemperature = getValueByPath(fromObject, ["temperature"]);
  if (fromTemperature != null) {
    setValueByPath(toObject, ["temperature"], fromTemperature);
  }
  const fromThinkingConfig = getValueByPath(fromObject, [
    "thinkingConfig"
  ]);
  if (fromThinkingConfig != null) {
    setValueByPath(toObject, ["thinkingConfig"], fromThinkingConfig);
  }
  const fromTopK = getValueByPath(fromObject, ["topK"]);
  if (fromTopK != null) {
    setValueByPath(toObject, ["topK"], fromTopK);
  }
  const fromTopP = getValueByPath(fromObject, ["topP"]);
  if (fromTopP != null) {
    setValueByPath(toObject, ["topP"], fromTopP);
  }
  if (getValueByPath(fromObject, ["enableEnhancedCivicAnswers"]) !== void 0) {
    throw new Error("enableEnhancedCivicAnswers parameter is not supported in Vertex AI.");
  }
  return toObject;
}
function getModelParametersToMldev(apiClient, fromObject, _rootObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel));
  }
  return toObject;
}
function getModelParametersToVertex(apiClient, fromObject, _rootObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel));
  }
  return toObject;
}
function googleMapsToMldev$1(fromObject, rootObject) {
  const toObject = {};
  const fromAuthConfig = getValueByPath(fromObject, ["authConfig"]);
  if (fromAuthConfig != null) {
    setValueByPath(toObject, ["authConfig"], authConfigToMldev$1(fromAuthConfig));
  }
  const fromEnableWidget = getValueByPath(fromObject, ["enableWidget"]);
  if (fromEnableWidget != null) {
    setValueByPath(toObject, ["enableWidget"], fromEnableWidget);
  }
  return toObject;
}
function googleSearchToMldev$1(fromObject, _rootObject) {
  const toObject = {};
  const fromSearchTypes = getValueByPath(fromObject, ["searchTypes"]);
  if (fromSearchTypes != null) {
    setValueByPath(toObject, ["searchTypes"], fromSearchTypes);
  }
  if (getValueByPath(fromObject, ["blockingConfidence"]) !== void 0) {
    throw new Error("blockingConfidence parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["excludeDomains"]) !== void 0) {
    throw new Error("excludeDomains parameter is not supported in Gemini API.");
  }
  const fromTimeRangeFilter = getValueByPath(fromObject, [
    "timeRangeFilter"
  ]);
  if (fromTimeRangeFilter != null) {
    setValueByPath(toObject, ["timeRangeFilter"], fromTimeRangeFilter);
  }
  return toObject;
}
function imageConfigToMldev(fromObject, _rootObject) {
  const toObject = {};
  const fromAspectRatio = getValueByPath(fromObject, ["aspectRatio"]);
  if (fromAspectRatio != null) {
    setValueByPath(toObject, ["aspectRatio"], fromAspectRatio);
  }
  const fromImageSize = getValueByPath(fromObject, ["imageSize"]);
  if (fromImageSize != null) {
    setValueByPath(toObject, ["imageSize"], fromImageSize);
  }
  if (getValueByPath(fromObject, ["personGeneration"]) !== void 0) {
    throw new Error("personGeneration parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["prominentPeople"]) !== void 0) {
    throw new Error("prominentPeople parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["outputMimeType"]) !== void 0) {
    throw new Error("outputMimeType parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["outputCompressionQuality"]) !== void 0) {
    throw new Error("outputCompressionQuality parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["imageOutputOptions"]) !== void 0) {
    throw new Error("imageOutputOptions parameter is not supported in Gemini API.");
  }
  return toObject;
}
function imageConfigToVertex(fromObject, _rootObject) {
  const toObject = {};
  const fromAspectRatio = getValueByPath(fromObject, ["aspectRatio"]);
  if (fromAspectRatio != null) {
    setValueByPath(toObject, ["aspectRatio"], fromAspectRatio);
  }
  const fromImageSize = getValueByPath(fromObject, ["imageSize"]);
  if (fromImageSize != null) {
    setValueByPath(toObject, ["imageSize"], fromImageSize);
  }
  const fromPersonGeneration = getValueByPath(fromObject, [
    "personGeneration"
  ]);
  if (fromPersonGeneration != null) {
    setValueByPath(toObject, ["personGeneration"], fromPersonGeneration);
  }
  const fromProminentPeople = getValueByPath(fromObject, [
    "prominentPeople"
  ]);
  if (fromProminentPeople != null) {
    setValueByPath(toObject, ["prominentPeople"], fromProminentPeople);
  }
  const fromOutputMimeType = getValueByPath(fromObject, [
    "outputMimeType"
  ]);
  if (fromOutputMimeType != null) {
    setValueByPath(toObject, ["imageOutputOptions", "mimeType"], fromOutputMimeType);
  }
  const fromOutputCompressionQuality = getValueByPath(fromObject, [
    "outputCompressionQuality"
  ]);
  if (fromOutputCompressionQuality != null) {
    setValueByPath(toObject, ["imageOutputOptions", "compressionQuality"], fromOutputCompressionQuality);
  }
  const fromImageOutputOptions = getValueByPath(fromObject, [
    "imageOutputOptions"
  ]);
  if (fromImageOutputOptions != null) {
    setValueByPath(toObject, ["imageOutputOptions"], fromImageOutputOptions);
  }
  return toObject;
}
function imageFromMldev(fromObject, _rootObject) {
  const toObject = {};
  const fromImageBytes = getValueByPath(fromObject, [
    "bytesBase64Encoded"
  ]);
  if (fromImageBytes != null) {
    setValueByPath(toObject, ["imageBytes"], tBytes(fromImageBytes));
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function imageFromVertex(fromObject, _rootObject) {
  const toObject = {};
  const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]);
  if (fromGcsUri != null) {
    setValueByPath(toObject, ["gcsUri"], fromGcsUri);
  }
  const fromImageBytes = getValueByPath(fromObject, [
    "bytesBase64Encoded"
  ]);
  if (fromImageBytes != null) {
    setValueByPath(toObject, ["imageBytes"], tBytes(fromImageBytes));
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function imageToMldev(fromObject, _rootObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["gcsUri"]) !== void 0) {
    throw new Error("gcsUri parameter is not supported in Gemini API.");
  }
  const fromImageBytes = getValueByPath(fromObject, ["imageBytes"]);
  if (fromImageBytes != null) {
    setValueByPath(toObject, ["bytesBase64Encoded"], tBytes(fromImageBytes));
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function imageToVertex(fromObject, _rootObject) {
  const toObject = {};
  const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]);
  if (fromGcsUri != null) {
    setValueByPath(toObject, ["gcsUri"], fromGcsUri);
  }
  const fromImageBytes = getValueByPath(fromObject, ["imageBytes"]);
  if (fromImageBytes != null) {
    setValueByPath(toObject, ["bytesBase64Encoded"], tBytes(fromImageBytes));
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function listModelsConfigToMldev(apiClient, fromObject, parentObject, _rootObject) {
  const toObject = {};
  const fromPageSize = getValueByPath(fromObject, ["pageSize"]);
  if (parentObject !== void 0 && fromPageSize != null) {
    setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize);
  }
  const fromPageToken = getValueByPath(fromObject, ["pageToken"]);
  if (parentObject !== void 0 && fromPageToken != null) {
    setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken);
  }
  const fromFilter = getValueByPath(fromObject, ["filter"]);
  if (parentObject !== void 0 && fromFilter != null) {
    setValueByPath(parentObject, ["_query", "filter"], fromFilter);
  }
  const fromQueryBase = getValueByPath(fromObject, ["queryBase"]);
  if (parentObject !== void 0 && fromQueryBase != null) {
    setValueByPath(parentObject, ["_url", "models_url"], tModelsUrl(apiClient, fromQueryBase));
  }
  return toObject;
}
function listModelsConfigToVertex(apiClient, fromObject, parentObject, _rootObject) {
  const toObject = {};
  const fromPageSize = getValueByPath(fromObject, ["pageSize"]);
  if (parentObject !== void 0 && fromPageSize != null) {
    setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize);
  }
  const fromPageToken = getValueByPath(fromObject, ["pageToken"]);
  if (parentObject !== void 0 && fromPageToken != null) {
    setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken);
  }
  const fromFilter = getValueByPath(fromObject, ["filter"]);
  if (parentObject !== void 0 && fromFilter != null) {
    setValueByPath(parentObject, ["_query", "filter"], fromFilter);
  }
  const fromQueryBase = getValueByPath(fromObject, ["queryBase"]);
  if (parentObject !== void 0 && fromQueryBase != null) {
    setValueByPath(parentObject, ["_url", "models_url"], tModelsUrl(apiClient, fromQueryBase));
  }
  return toObject;
}
function listModelsParametersToMldev(apiClient, fromObject, rootObject) {
  const toObject = {};
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    listModelsConfigToMldev(apiClient, fromConfig, toObject);
  }
  return toObject;
}
function listModelsParametersToVertex(apiClient, fromObject, rootObject) {
  const toObject = {};
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    listModelsConfigToVertex(apiClient, fromConfig, toObject);
  }
  return toObject;
}
function listModelsResponseFromMldev(fromObject, rootObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromNextPageToken = getValueByPath(fromObject, [
    "nextPageToken"
  ]);
  if (fromNextPageToken != null) {
    setValueByPath(toObject, ["nextPageToken"], fromNextPageToken);
  }
  const fromModels = getValueByPath(fromObject, ["_self"]);
  if (fromModels != null) {
    let transformedList = tExtractModels(fromModels);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return modelFromMldev(item);
      });
    }
    setValueByPath(toObject, ["models"], transformedList);
  }
  return toObject;
}
function listModelsResponseFromVertex(fromObject, rootObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromNextPageToken = getValueByPath(fromObject, [
    "nextPageToken"
  ]);
  if (fromNextPageToken != null) {
    setValueByPath(toObject, ["nextPageToken"], fromNextPageToken);
  }
  const fromModels = getValueByPath(fromObject, ["_self"]);
  if (fromModels != null) {
    let transformedList = tExtractModels(fromModels);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return modelFromVertex(item);
      });
    }
    setValueByPath(toObject, ["models"], transformedList);
  }
  return toObject;
}
function maskReferenceConfigToVertex(fromObject, _rootObject) {
  const toObject = {};
  const fromMaskMode = getValueByPath(fromObject, ["maskMode"]);
  if (fromMaskMode != null) {
    setValueByPath(toObject, ["maskMode"], fromMaskMode);
  }
  const fromSegmentationClasses = getValueByPath(fromObject, [
    "segmentationClasses"
  ]);
  if (fromSegmentationClasses != null) {
    setValueByPath(toObject, ["maskClasses"], fromSegmentationClasses);
  }
  const fromMaskDilation = getValueByPath(fromObject, ["maskDilation"]);
  if (fromMaskDilation != null) {
    setValueByPath(toObject, ["dilation"], fromMaskDilation);
  }
  return toObject;
}
function modelFromMldev(fromObject, rootObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromDisplayName = getValueByPath(fromObject, ["displayName"]);
  if (fromDisplayName != null) {
    setValueByPath(toObject, ["displayName"], fromDisplayName);
  }
  const fromDescription = getValueByPath(fromObject, ["description"]);
  if (fromDescription != null) {
    setValueByPath(toObject, ["description"], fromDescription);
  }
  const fromVersion = getValueByPath(fromObject, ["version"]);
  if (fromVersion != null) {
    setValueByPath(toObject, ["version"], fromVersion);
  }
  const fromTunedModelInfo = getValueByPath(fromObject, ["_self"]);
  if (fromTunedModelInfo != null) {
    setValueByPath(toObject, ["tunedModelInfo"], tunedModelInfoFromMldev(fromTunedModelInfo));
  }
  const fromInputTokenLimit = getValueByPath(fromObject, [
    "inputTokenLimit"
  ]);
  if (fromInputTokenLimit != null) {
    setValueByPath(toObject, ["inputTokenLimit"], fromInputTokenLimit);
  }
  const fromOutputTokenLimit = getValueByPath(fromObject, [
    "outputTokenLimit"
  ]);
  if (fromOutputTokenLimit != null) {
    setValueByPath(toObject, ["outputTokenLimit"], fromOutputTokenLimit);
  }
  const fromSupportedActions = getValueByPath(fromObject, [
    "supportedGenerationMethods"
  ]);
  if (fromSupportedActions != null) {
    setValueByPath(toObject, ["supportedActions"], fromSupportedActions);
  }
  const fromTemperature = getValueByPath(fromObject, ["temperature"]);
  if (fromTemperature != null) {
    setValueByPath(toObject, ["temperature"], fromTemperature);
  }
  const fromMaxTemperature = getValueByPath(fromObject, [
    "maxTemperature"
  ]);
  if (fromMaxTemperature != null) {
    setValueByPath(toObject, ["maxTemperature"], fromMaxTemperature);
  }
  const fromTopP = getValueByPath(fromObject, ["topP"]);
  if (fromTopP != null) {
    setValueByPath(toObject, ["topP"], fromTopP);
  }
  const fromTopK = getValueByPath(fromObject, ["topK"]);
  if (fromTopK != null) {
    setValueByPath(toObject, ["topK"], fromTopK);
  }
  const fromThinking = getValueByPath(fromObject, ["thinking"]);
  if (fromThinking != null) {
    setValueByPath(toObject, ["thinking"], fromThinking);
  }
  return toObject;
}
function modelFromVertex(fromObject, rootObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromDisplayName = getValueByPath(fromObject, ["displayName"]);
  if (fromDisplayName != null) {
    setValueByPath(toObject, ["displayName"], fromDisplayName);
  }
  const fromDescription = getValueByPath(fromObject, ["description"]);
  if (fromDescription != null) {
    setValueByPath(toObject, ["description"], fromDescription);
  }
  const fromVersion = getValueByPath(fromObject, ["versionId"]);
  if (fromVersion != null) {
    setValueByPath(toObject, ["version"], fromVersion);
  }
  const fromEndpoints = getValueByPath(fromObject, ["deployedModels"]);
  if (fromEndpoints != null) {
    let transformedList = fromEndpoints;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return endpointFromVertex(item);
      });
    }
    setValueByPath(toObject, ["endpoints"], transformedList);
  }
  const fromLabels = getValueByPath(fromObject, ["labels"]);
  if (fromLabels != null) {
    setValueByPath(toObject, ["labels"], fromLabels);
  }
  const fromTunedModelInfo = getValueByPath(fromObject, ["_self"]);
  if (fromTunedModelInfo != null) {
    setValueByPath(toObject, ["tunedModelInfo"], tunedModelInfoFromVertex(fromTunedModelInfo));
  }
  const fromDefaultCheckpointId = getValueByPath(fromObject, [
    "defaultCheckpointId"
  ]);
  if (fromDefaultCheckpointId != null) {
    setValueByPath(toObject, ["defaultCheckpointId"], fromDefaultCheckpointId);
  }
  const fromCheckpoints = getValueByPath(fromObject, ["checkpoints"]);
  if (fromCheckpoints != null) {
    let transformedList = fromCheckpoints;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["checkpoints"], transformedList);
  }
  return toObject;
}
function partToMldev$1(fromObject, rootObject) {
  const toObject = {};
  const fromMediaResolution = getValueByPath(fromObject, [
    "mediaResolution"
  ]);
  if (fromMediaResolution != null) {
    setValueByPath(toObject, ["mediaResolution"], fromMediaResolution);
  }
  const fromCodeExecutionResult = getValueByPath(fromObject, [
    "codeExecutionResult"
  ]);
  if (fromCodeExecutionResult != null) {
    setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult);
  }
  const fromExecutableCode = getValueByPath(fromObject, [
    "executableCode"
  ]);
  if (fromExecutableCode != null) {
    setValueByPath(toObject, ["executableCode"], fromExecutableCode);
  }
  const fromFileData = getValueByPath(fromObject, ["fileData"]);
  if (fromFileData != null) {
    setValueByPath(toObject, ["fileData"], fileDataToMldev$1(fromFileData));
  }
  const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]);
  if (fromFunctionCall != null) {
    setValueByPath(toObject, ["functionCall"], functionCallToMldev$1(fromFunctionCall));
  }
  const fromFunctionResponse = getValueByPath(fromObject, [
    "functionResponse"
  ]);
  if (fromFunctionResponse != null) {
    setValueByPath(toObject, ["functionResponse"], fromFunctionResponse);
  }
  const fromInlineData = getValueByPath(fromObject, ["inlineData"]);
  if (fromInlineData != null) {
    setValueByPath(toObject, ["inlineData"], blobToMldev$1(fromInlineData));
  }
  const fromText = getValueByPath(fromObject, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  const fromThought = getValueByPath(fromObject, ["thought"]);
  if (fromThought != null) {
    setValueByPath(toObject, ["thought"], fromThought);
  }
  const fromThoughtSignature = getValueByPath(fromObject, [
    "thoughtSignature"
  ]);
  if (fromThoughtSignature != null) {
    setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature);
  }
  const fromVideoMetadata = getValueByPath(fromObject, [
    "videoMetadata"
  ]);
  if (fromVideoMetadata != null) {
    setValueByPath(toObject, ["videoMetadata"], fromVideoMetadata);
  }
  return toObject;
}
function productImageToVertex(fromObject, rootObject) {
  const toObject = {};
  const fromProductImage = getValueByPath(fromObject, ["productImage"]);
  if (fromProductImage != null) {
    setValueByPath(toObject, ["image"], imageToVertex(fromProductImage));
  }
  return toObject;
}
function recontextImageConfigToVertex(fromObject, parentObject, _rootObject) {
  const toObject = {};
  const fromNumberOfImages = getValueByPath(fromObject, [
    "numberOfImages"
  ]);
  if (parentObject !== void 0 && fromNumberOfImages != null) {
    setValueByPath(parentObject, ["parameters", "sampleCount"], fromNumberOfImages);
  }
  const fromBaseSteps = getValueByPath(fromObject, ["baseSteps"]);
  if (parentObject !== void 0 && fromBaseSteps != null) {
    setValueByPath(parentObject, ["parameters", "baseSteps"], fromBaseSteps);
  }
  const fromOutputGcsUri = getValueByPath(fromObject, ["outputGcsUri"]);
  if (parentObject !== void 0 && fromOutputGcsUri != null) {
    setValueByPath(parentObject, ["parameters", "storageUri"], fromOutputGcsUri);
  }
  const fromSeed = getValueByPath(fromObject, ["seed"]);
  if (parentObject !== void 0 && fromSeed != null) {
    setValueByPath(parentObject, ["parameters", "seed"], fromSeed);
  }
  const fromSafetyFilterLevel = getValueByPath(fromObject, [
    "safetyFilterLevel"
  ]);
  if (parentObject !== void 0 && fromSafetyFilterLevel != null) {
    setValueByPath(parentObject, ["parameters", "safetySetting"], fromSafetyFilterLevel);
  }
  const fromPersonGeneration = getValueByPath(fromObject, [
    "personGeneration"
  ]);
  if (parentObject !== void 0 && fromPersonGeneration != null) {
    setValueByPath(parentObject, ["parameters", "personGeneration"], fromPersonGeneration);
  }
  const fromAddWatermark = getValueByPath(fromObject, ["addWatermark"]);
  if (parentObject !== void 0 && fromAddWatermark != null) {
    setValueByPath(parentObject, ["parameters", "addWatermark"], fromAddWatermark);
  }
  const fromOutputMimeType = getValueByPath(fromObject, [
    "outputMimeType"
  ]);
  if (parentObject !== void 0 && fromOutputMimeType != null) {
    setValueByPath(parentObject, ["parameters", "outputOptions", "mimeType"], fromOutputMimeType);
  }
  const fromOutputCompressionQuality = getValueByPath(fromObject, [
    "outputCompressionQuality"
  ]);
  if (parentObject !== void 0 && fromOutputCompressionQuality != null) {
    setValueByPath(parentObject, ["parameters", "outputOptions", "compressionQuality"], fromOutputCompressionQuality);
  }
  const fromEnhancePrompt = getValueByPath(fromObject, [
    "enhancePrompt"
  ]);
  if (parentObject !== void 0 && fromEnhancePrompt != null) {
    setValueByPath(parentObject, ["parameters", "enhancePrompt"], fromEnhancePrompt);
  }
  const fromLabels = getValueByPath(fromObject, ["labels"]);
  if (parentObject !== void 0 && fromLabels != null) {
    setValueByPath(parentObject, ["labels"], fromLabels);
  }
  return toObject;
}
function recontextImageParametersToVertex(apiClient, fromObject, rootObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromSource = getValueByPath(fromObject, ["source"]);
  if (fromSource != null) {
    recontextImageSourceToVertex(fromSource, toObject);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    recontextImageConfigToVertex(fromConfig, toObject);
  }
  return toObject;
}
function recontextImageResponseFromVertex(fromObject, rootObject) {
  const toObject = {};
  const fromGeneratedImages = getValueByPath(fromObject, [
    "predictions"
  ]);
  if (fromGeneratedImages != null) {
    let transformedList = fromGeneratedImages;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return generatedImageFromVertex(item);
      });
    }
    setValueByPath(toObject, ["generatedImages"], transformedList);
  }
  return toObject;
}
function recontextImageSourceToVertex(fromObject, parentObject, rootObject) {
  const toObject = {};
  const fromPrompt = getValueByPath(fromObject, ["prompt"]);
  if (parentObject !== void 0 && fromPrompt != null) {
    setValueByPath(parentObject, ["instances[0]", "prompt"], fromPrompt);
  }
  const fromPersonImage = getValueByPath(fromObject, ["personImage"]);
  if (parentObject !== void 0 && fromPersonImage != null) {
    setValueByPath(parentObject, ["instances[0]", "personImage", "image"], imageToVertex(fromPersonImage));
  }
  const fromProductImages = getValueByPath(fromObject, [
    "productImages"
  ]);
  if (parentObject !== void 0 && fromProductImages != null) {
    let transformedList = fromProductImages;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return productImageToVertex(item);
      });
    }
    setValueByPath(parentObject, ["instances[0]", "productImages"], transformedList);
  }
  return toObject;
}
function referenceImageAPIInternalToVertex(fromObject, rootObject) {
  const toObject = {};
  const fromReferenceImage = getValueByPath(fromObject, [
    "referenceImage"
  ]);
  if (fromReferenceImage != null) {
    setValueByPath(toObject, ["referenceImage"], imageToVertex(fromReferenceImage));
  }
  const fromReferenceId = getValueByPath(fromObject, ["referenceId"]);
  if (fromReferenceId != null) {
    setValueByPath(toObject, ["referenceId"], fromReferenceId);
  }
  const fromReferenceType = getValueByPath(fromObject, [
    "referenceType"
  ]);
  if (fromReferenceType != null) {
    setValueByPath(toObject, ["referenceType"], fromReferenceType);
  }
  const fromMaskImageConfig = getValueByPath(fromObject, [
    "maskImageConfig"
  ]);
  if (fromMaskImageConfig != null) {
    setValueByPath(toObject, ["maskImageConfig"], maskReferenceConfigToVertex(fromMaskImageConfig));
  }
  const fromControlImageConfig = getValueByPath(fromObject, [
    "controlImageConfig"
  ]);
  if (fromControlImageConfig != null) {
    setValueByPath(toObject, ["controlImageConfig"], controlReferenceConfigToVertex(fromControlImageConfig));
  }
  const fromStyleImageConfig = getValueByPath(fromObject, [
    "styleImageConfig"
  ]);
  if (fromStyleImageConfig != null) {
    setValueByPath(toObject, ["styleImageConfig"], fromStyleImageConfig);
  }
  const fromSubjectImageConfig = getValueByPath(fromObject, [
    "subjectImageConfig"
  ]);
  if (fromSubjectImageConfig != null) {
    setValueByPath(toObject, ["subjectImageConfig"], fromSubjectImageConfig);
  }
  return toObject;
}
function safetyAttributesFromMldev(fromObject, _rootObject) {
  const toObject = {};
  const fromCategories = getValueByPath(fromObject, [
    "safetyAttributes",
    "categories"
  ]);
  if (fromCategories != null) {
    setValueByPath(toObject, ["categories"], fromCategories);
  }
  const fromScores = getValueByPath(fromObject, [
    "safetyAttributes",
    "scores"
  ]);
  if (fromScores != null) {
    setValueByPath(toObject, ["scores"], fromScores);
  }
  const fromContentType = getValueByPath(fromObject, ["contentType"]);
  if (fromContentType != null) {
    setValueByPath(toObject, ["contentType"], fromContentType);
  }
  return toObject;
}
function safetyAttributesFromVertex(fromObject, _rootObject) {
  const toObject = {};
  const fromCategories = getValueByPath(fromObject, [
    "safetyAttributes",
    "categories"
  ]);
  if (fromCategories != null) {
    setValueByPath(toObject, ["categories"], fromCategories);
  }
  const fromScores = getValueByPath(fromObject, [
    "safetyAttributes",
    "scores"
  ]);
  if (fromScores != null) {
    setValueByPath(toObject, ["scores"], fromScores);
  }
  const fromContentType = getValueByPath(fromObject, ["contentType"]);
  if (fromContentType != null) {
    setValueByPath(toObject, ["contentType"], fromContentType);
  }
  return toObject;
}
function safetySettingToMldev(fromObject, _rootObject) {
  const toObject = {};
  const fromCategory = getValueByPath(fromObject, ["category"]);
  if (fromCategory != null) {
    setValueByPath(toObject, ["category"], fromCategory);
  }
  if (getValueByPath(fromObject, ["method"]) !== void 0) {
    throw new Error("method parameter is not supported in Gemini API.");
  }
  const fromThreshold = getValueByPath(fromObject, ["threshold"]);
  if (fromThreshold != null) {
    setValueByPath(toObject, ["threshold"], fromThreshold);
  }
  return toObject;
}
function scribbleImageToVertex(fromObject, rootObject) {
  const toObject = {};
  const fromImage = getValueByPath(fromObject, ["image"]);
  if (fromImage != null) {
    setValueByPath(toObject, ["image"], imageToVertex(fromImage));
  }
  return toObject;
}
function segmentImageConfigToVertex(fromObject, parentObject, _rootObject) {
  const toObject = {};
  const fromMode = getValueByPath(fromObject, ["mode"]);
  if (parentObject !== void 0 && fromMode != null) {
    setValueByPath(parentObject, ["parameters", "mode"], fromMode);
  }
  const fromMaxPredictions = getValueByPath(fromObject, [
    "maxPredictions"
  ]);
  if (parentObject !== void 0 && fromMaxPredictions != null) {
    setValueByPath(parentObject, ["parameters", "maxPredictions"], fromMaxPredictions);
  }
  const fromConfidenceThreshold = getValueByPath(fromObject, [
    "confidenceThreshold"
  ]);
  if (parentObject !== void 0 && fromConfidenceThreshold != null) {
    setValueByPath(parentObject, ["parameters", "confidenceThreshold"], fromConfidenceThreshold);
  }
  const fromMaskDilation = getValueByPath(fromObject, ["maskDilation"]);
  if (parentObject !== void 0 && fromMaskDilation != null) {
    setValueByPath(parentObject, ["parameters", "maskDilation"], fromMaskDilation);
  }
  const fromBinaryColorThreshold = getValueByPath(fromObject, [
    "binaryColorThreshold"
  ]);
  if (parentObject !== void 0 && fromBinaryColorThreshold != null) {
    setValueByPath(parentObject, ["parameters", "binaryColorThreshold"], fromBinaryColorThreshold);
  }
  const fromLabels = getValueByPath(fromObject, ["labels"]);
  if (parentObject !== void 0 && fromLabels != null) {
    setValueByPath(parentObject, ["labels"], fromLabels);
  }
  return toObject;
}
function segmentImageParametersToVertex(apiClient, fromObject, rootObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromSource = getValueByPath(fromObject, ["source"]);
  if (fromSource != null) {
    segmentImageSourceToVertex(fromSource, toObject);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    segmentImageConfigToVertex(fromConfig, toObject);
  }
  return toObject;
}
function segmentImageResponseFromVertex(fromObject, rootObject) {
  const toObject = {};
  const fromGeneratedMasks = getValueByPath(fromObject, ["predictions"]);
  if (fromGeneratedMasks != null) {
    let transformedList = fromGeneratedMasks;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return generatedImageMaskFromVertex(item);
      });
    }
    setValueByPath(toObject, ["generatedMasks"], transformedList);
  }
  return toObject;
}
function segmentImageSourceToVertex(fromObject, parentObject, rootObject) {
  const toObject = {};
  const fromPrompt = getValueByPath(fromObject, ["prompt"]);
  if (parentObject !== void 0 && fromPrompt != null) {
    setValueByPath(parentObject, ["instances[0]", "prompt"], fromPrompt);
  }
  const fromImage = getValueByPath(fromObject, ["image"]);
  if (parentObject !== void 0 && fromImage != null) {
    setValueByPath(parentObject, ["instances[0]", "image"], imageToVertex(fromImage));
  }
  const fromScribbleImage = getValueByPath(fromObject, [
    "scribbleImage"
  ]);
  if (parentObject !== void 0 && fromScribbleImage != null) {
    setValueByPath(parentObject, ["instances[0]", "scribble"], scribbleImageToVertex(fromScribbleImage));
  }
  return toObject;
}
function toolConfigToMldev(fromObject, rootObject) {
  const toObject = {};
  const fromRetrievalConfig = getValueByPath(fromObject, [
    "retrievalConfig"
  ]);
  if (fromRetrievalConfig != null) {
    setValueByPath(toObject, ["retrievalConfig"], fromRetrievalConfig);
  }
  const fromFunctionCallingConfig = getValueByPath(fromObject, [
    "functionCallingConfig"
  ]);
  if (fromFunctionCallingConfig != null) {
    setValueByPath(toObject, ["functionCallingConfig"], functionCallingConfigToMldev(fromFunctionCallingConfig));
  }
  return toObject;
}
function toolToMldev$1(fromObject, rootObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["retrieval"]) !== void 0) {
    throw new Error("retrieval parameter is not supported in Gemini API.");
  }
  const fromComputerUse = getValueByPath(fromObject, ["computerUse"]);
  if (fromComputerUse != null) {
    setValueByPath(toObject, ["computerUse"], fromComputerUse);
  }
  const fromFileSearch = getValueByPath(fromObject, ["fileSearch"]);
  if (fromFileSearch != null) {
    setValueByPath(toObject, ["fileSearch"], fromFileSearch);
  }
  const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]);
  if (fromGoogleSearch != null) {
    setValueByPath(toObject, ["googleSearch"], googleSearchToMldev$1(fromGoogleSearch));
  }
  const fromGoogleMaps = getValueByPath(fromObject, ["googleMaps"]);
  if (fromGoogleMaps != null) {
    setValueByPath(toObject, ["googleMaps"], googleMapsToMldev$1(fromGoogleMaps));
  }
  const fromCodeExecution = getValueByPath(fromObject, [
    "codeExecution"
  ]);
  if (fromCodeExecution != null) {
    setValueByPath(toObject, ["codeExecution"], fromCodeExecution);
  }
  if (getValueByPath(fromObject, ["enterpriseWebSearch"]) !== void 0) {
    throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");
  }
  const fromFunctionDeclarations = getValueByPath(fromObject, [
    "functionDeclarations"
  ]);
  if (fromFunctionDeclarations != null) {
    let transformedList = fromFunctionDeclarations;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["functionDeclarations"], transformedList);
  }
  const fromGoogleSearchRetrieval = getValueByPath(fromObject, [
    "googleSearchRetrieval"
  ]);
  if (fromGoogleSearchRetrieval != null) {
    setValueByPath(toObject, ["googleSearchRetrieval"], fromGoogleSearchRetrieval);
  }
  if (getValueByPath(fromObject, ["parallelAiSearch"]) !== void 0) {
    throw new Error("parallelAiSearch parameter is not supported in Gemini API.");
  }
  const fromUrlContext = getValueByPath(fromObject, ["urlContext"]);
  if (fromUrlContext != null) {
    setValueByPath(toObject, ["urlContext"], fromUrlContext);
  }
  const fromMcpServers = getValueByPath(fromObject, ["mcpServers"]);
  if (fromMcpServers != null) {
    let transformedList = fromMcpServers;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["mcpServers"], transformedList);
  }
  return toObject;
}
function toolToVertex(fromObject, rootObject) {
  const toObject = {};
  const fromRetrieval = getValueByPath(fromObject, ["retrieval"]);
  if (fromRetrieval != null) {
    setValueByPath(toObject, ["retrieval"], fromRetrieval);
  }
  const fromComputerUse = getValueByPath(fromObject, ["computerUse"]);
  if (fromComputerUse != null) {
    setValueByPath(toObject, ["computerUse"], fromComputerUse);
  }
  if (getValueByPath(fromObject, ["fileSearch"]) !== void 0) {
    throw new Error("fileSearch parameter is not supported in Vertex AI.");
  }
  const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]);
  if (fromGoogleSearch != null) {
    setValueByPath(toObject, ["googleSearch"], fromGoogleSearch);
  }
  const fromGoogleMaps = getValueByPath(fromObject, ["googleMaps"]);
  if (fromGoogleMaps != null) {
    setValueByPath(toObject, ["googleMaps"], fromGoogleMaps);
  }
  const fromCodeExecution = getValueByPath(fromObject, [
    "codeExecution"
  ]);
  if (fromCodeExecution != null) {
    setValueByPath(toObject, ["codeExecution"], fromCodeExecution);
  }
  const fromEnterpriseWebSearch = getValueByPath(fromObject, [
    "enterpriseWebSearch"
  ]);
  if (fromEnterpriseWebSearch != null) {
    setValueByPath(toObject, ["enterpriseWebSearch"], fromEnterpriseWebSearch);
  }
  const fromFunctionDeclarations = getValueByPath(fromObject, [
    "functionDeclarations"
  ]);
  if (fromFunctionDeclarations != null) {
    let transformedList = fromFunctionDeclarations;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return functionDeclarationToVertex(item);
      });
    }
    setValueByPath(toObject, ["functionDeclarations"], transformedList);
  }
  const fromGoogleSearchRetrieval = getValueByPath(fromObject, [
    "googleSearchRetrieval"
  ]);
  if (fromGoogleSearchRetrieval != null) {
    setValueByPath(toObject, ["googleSearchRetrieval"], fromGoogleSearchRetrieval);
  }
  const fromParallelAiSearch = getValueByPath(fromObject, [
    "parallelAiSearch"
  ]);
  if (fromParallelAiSearch != null) {
    setValueByPath(toObject, ["parallelAiSearch"], fromParallelAiSearch);
  }
  const fromUrlContext = getValueByPath(fromObject, ["urlContext"]);
  if (fromUrlContext != null) {
    setValueByPath(toObject, ["urlContext"], fromUrlContext);
  }
  if (getValueByPath(fromObject, ["mcpServers"]) !== void 0) {
    throw new Error("mcpServers parameter is not supported in Vertex AI.");
  }
  return toObject;
}
function tunedModelInfoFromMldev(fromObject, _rootObject) {
  const toObject = {};
  const fromBaseModel = getValueByPath(fromObject, ["baseModel"]);
  if (fromBaseModel != null) {
    setValueByPath(toObject, ["baseModel"], fromBaseModel);
  }
  const fromCreateTime = getValueByPath(fromObject, ["createTime"]);
  if (fromCreateTime != null) {
    setValueByPath(toObject, ["createTime"], fromCreateTime);
  }
  const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]);
  if (fromUpdateTime != null) {
    setValueByPath(toObject, ["updateTime"], fromUpdateTime);
  }
  return toObject;
}
function tunedModelInfoFromVertex(fromObject, _rootObject) {
  const toObject = {};
  const fromBaseModel = getValueByPath(fromObject, [
    "labels",
    "google-vertex-llm-tuning-base-model-id"
  ]);
  if (fromBaseModel != null) {
    setValueByPath(toObject, ["baseModel"], fromBaseModel);
  }
  const fromCreateTime = getValueByPath(fromObject, ["createTime"]);
  if (fromCreateTime != null) {
    setValueByPath(toObject, ["createTime"], fromCreateTime);
  }
  const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]);
  if (fromUpdateTime != null) {
    setValueByPath(toObject, ["updateTime"], fromUpdateTime);
  }
  return toObject;
}
function updateModelConfigToMldev(fromObject, parentObject, _rootObject) {
  const toObject = {};
  const fromDisplayName = getValueByPath(fromObject, ["displayName"]);
  if (parentObject !== void 0 && fromDisplayName != null) {
    setValueByPath(parentObject, ["displayName"], fromDisplayName);
  }
  const fromDescription = getValueByPath(fromObject, ["description"]);
  if (parentObject !== void 0 && fromDescription != null) {
    setValueByPath(parentObject, ["description"], fromDescription);
  }
  const fromDefaultCheckpointId = getValueByPath(fromObject, [
    "defaultCheckpointId"
  ]);
  if (parentObject !== void 0 && fromDefaultCheckpointId != null) {
    setValueByPath(parentObject, ["defaultCheckpointId"], fromDefaultCheckpointId);
  }
  return toObject;
}
function updateModelConfigToVertex(fromObject, parentObject, _rootObject) {
  const toObject = {};
  const fromDisplayName = getValueByPath(fromObject, ["displayName"]);
  if (parentObject !== void 0 && fromDisplayName != null) {
    setValueByPath(parentObject, ["displayName"], fromDisplayName);
  }
  const fromDescription = getValueByPath(fromObject, ["description"]);
  if (parentObject !== void 0 && fromDescription != null) {
    setValueByPath(parentObject, ["description"], fromDescription);
  }
  const fromDefaultCheckpointId = getValueByPath(fromObject, [
    "defaultCheckpointId"
  ]);
  if (parentObject !== void 0 && fromDefaultCheckpointId != null) {
    setValueByPath(parentObject, ["defaultCheckpointId"], fromDefaultCheckpointId);
  }
  return toObject;
}
function updateModelParametersToMldev(apiClient, fromObject, rootObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    updateModelConfigToMldev(fromConfig, toObject);
  }
  return toObject;
}
function updateModelParametersToVertex(apiClient, fromObject, rootObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    updateModelConfigToVertex(fromConfig, toObject);
  }
  return toObject;
}
function upscaleImageAPIConfigInternalToVertex(fromObject, parentObject, _rootObject) {
  const toObject = {};
  const fromOutputGcsUri = getValueByPath(fromObject, ["outputGcsUri"]);
  if (parentObject !== void 0 && fromOutputGcsUri != null) {
    setValueByPath(parentObject, ["parameters", "storageUri"], fromOutputGcsUri);
  }
  const fromSafetyFilterLevel = getValueByPath(fromObject, [
    "safetyFilterLevel"
  ]);
  if (parentObject !== void 0 && fromSafetyFilterLevel != null) {
    setValueByPath(parentObject, ["parameters", "safetySetting"], fromSafetyFilterLevel);
  }
  const fromPersonGeneration = getValueByPath(fromObject, [
    "personGeneration"
  ]);
  if (parentObject !== void 0 && fromPersonGeneration != null) {
    setValueByPath(parentObject, ["parameters", "personGeneration"], fromPersonGeneration);
  }
  const fromIncludeRaiReason = getValueByPath(fromObject, [
    "includeRaiReason"
  ]);
  if (parentObject !== void 0 && fromIncludeRaiReason != null) {
    setValueByPath(parentObject, ["parameters", "includeRaiReason"], fromIncludeRaiReason);
  }
  const fromOutputMimeType = getValueByPath(fromObject, [
    "outputMimeType"
  ]);
  if (parentObject !== void 0 && fromOutputMimeType != null) {
    setValueByPath(parentObject, ["parameters", "outputOptions", "mimeType"], fromOutputMimeType);
  }
  const fromOutputCompressionQuality = getValueByPath(fromObject, [
    "outputCompressionQuality"
  ]);
  if (parentObject !== void 0 && fromOutputCompressionQuality != null) {
    setValueByPath(parentObject, ["parameters", "outputOptions", "compressionQuality"], fromOutputCompressionQuality);
  }
  const fromEnhanceInputImage = getValueByPath(fromObject, [
    "enhanceInputImage"
  ]);
  if (parentObject !== void 0 && fromEnhanceInputImage != null) {
    setValueByPath(parentObject, ["parameters", "upscaleConfig", "enhanceInputImage"], fromEnhanceInputImage);
  }
  const fromImagePreservationFactor = getValueByPath(fromObject, [
    "imagePreservationFactor"
  ]);
  if (parentObject !== void 0 && fromImagePreservationFactor != null) {
    setValueByPath(parentObject, ["parameters", "upscaleConfig", "imagePreservationFactor"], fromImagePreservationFactor);
  }
  const fromLabels = getValueByPath(fromObject, ["labels"]);
  if (parentObject !== void 0 && fromLabels != null) {
    setValueByPath(parentObject, ["labels"], fromLabels);
  }
  const fromNumberOfImages = getValueByPath(fromObject, [
    "numberOfImages"
  ]);
  if (parentObject !== void 0 && fromNumberOfImages != null) {
    setValueByPath(parentObject, ["parameters", "sampleCount"], fromNumberOfImages);
  }
  const fromMode = getValueByPath(fromObject, ["mode"]);
  if (parentObject !== void 0 && fromMode != null) {
    setValueByPath(parentObject, ["parameters", "mode"], fromMode);
  }
  return toObject;
}
function upscaleImageAPIParametersInternalToVertex(apiClient, fromObject, rootObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromImage = getValueByPath(fromObject, ["image"]);
  if (fromImage != null) {
    setValueByPath(toObject, ["instances[0]", "image"], imageToVertex(fromImage));
  }
  const fromUpscaleFactor = getValueByPath(fromObject, [
    "upscaleFactor"
  ]);
  if (fromUpscaleFactor != null) {
    setValueByPath(toObject, ["parameters", "upscaleConfig", "upscaleFactor"], fromUpscaleFactor);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    upscaleImageAPIConfigInternalToVertex(fromConfig, toObject);
  }
  return toObject;
}
function upscaleImageResponseFromVertex(fromObject, rootObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromGeneratedImages = getValueByPath(fromObject, [
    "predictions"
  ]);
  if (fromGeneratedImages != null) {
    let transformedList = fromGeneratedImages;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return generatedImageFromVertex(item);
      });
    }
    setValueByPath(toObject, ["generatedImages"], transformedList);
  }
  return toObject;
}
function videoFromMldev(fromObject, _rootObject) {
  const toObject = {};
  const fromUri = getValueByPath(fromObject, ["uri"]);
  if (fromUri != null) {
    setValueByPath(toObject, ["uri"], fromUri);
  }
  const fromVideoBytes = getValueByPath(fromObject, ["encodedVideo"]);
  if (fromVideoBytes != null) {
    setValueByPath(toObject, ["videoBytes"], tBytes(fromVideoBytes));
  }
  const fromMimeType = getValueByPath(fromObject, ["encoding"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function videoFromVertex(fromObject, _rootObject) {
  const toObject = {};
  const fromUri = getValueByPath(fromObject, ["gcsUri"]);
  if (fromUri != null) {
    setValueByPath(toObject, ["uri"], fromUri);
  }
  const fromVideoBytes = getValueByPath(fromObject, [
    "bytesBase64Encoded"
  ]);
  if (fromVideoBytes != null) {
    setValueByPath(toObject, ["videoBytes"], tBytes(fromVideoBytes));
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function videoGenerationMaskToVertex(fromObject, rootObject) {
  const toObject = {};
  const fromImage = getValueByPath(fromObject, ["image"]);
  if (fromImage != null) {
    setValueByPath(toObject, ["_self"], imageToVertex(fromImage));
  }
  const fromMaskMode = getValueByPath(fromObject, ["maskMode"]);
  if (fromMaskMode != null) {
    setValueByPath(toObject, ["maskMode"], fromMaskMode);
  }
  return toObject;
}
function videoGenerationReferenceImageToMldev(fromObject, rootObject) {
  const toObject = {};
  const fromImage = getValueByPath(fromObject, ["image"]);
  if (fromImage != null) {
    setValueByPath(toObject, ["image"], imageToMldev(fromImage));
  }
  const fromReferenceType = getValueByPath(fromObject, [
    "referenceType"
  ]);
  if (fromReferenceType != null) {
    setValueByPath(toObject, ["referenceType"], fromReferenceType);
  }
  return toObject;
}
function videoGenerationReferenceImageToVertex(fromObject, rootObject) {
  const toObject = {};
  const fromImage = getValueByPath(fromObject, ["image"]);
  if (fromImage != null) {
    setValueByPath(toObject, ["image"], imageToVertex(fromImage));
  }
  const fromReferenceType = getValueByPath(fromObject, [
    "referenceType"
  ]);
  if (fromReferenceType != null) {
    setValueByPath(toObject, ["referenceType"], fromReferenceType);
  }
  return toObject;
}
function videoToMldev(fromObject, _rootObject) {
  const toObject = {};
  const fromUri = getValueByPath(fromObject, ["uri"]);
  if (fromUri != null) {
    setValueByPath(toObject, ["uri"], fromUri);
  }
  const fromVideoBytes = getValueByPath(fromObject, ["videoBytes"]);
  if (fromVideoBytes != null) {
    setValueByPath(toObject, ["encodedVideo"], tBytes(fromVideoBytes));
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["encoding"], fromMimeType);
  }
  return toObject;
}
function videoToVertex(fromObject, _rootObject) {
  const toObject = {};
  const fromUri = getValueByPath(fromObject, ["uri"]);
  if (fromUri != null) {
    setValueByPath(toObject, ["gcsUri"], fromUri);
  }
  const fromVideoBytes = getValueByPath(fromObject, ["videoBytes"]);
  if (fromVideoBytes != null) {
    setValueByPath(toObject, ["bytesBase64Encoded"], tBytes(fromVideoBytes));
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function createFileSearchStoreConfigToMldev(fromObject, parentObject) {
  const toObject = {};
  const fromDisplayName = getValueByPath(fromObject, ["displayName"]);
  if (parentObject !== void 0 && fromDisplayName != null) {
    setValueByPath(parentObject, ["displayName"], fromDisplayName);
  }
  return toObject;
}
function createFileSearchStoreParametersToMldev(fromObject) {
  const toObject = {};
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    createFileSearchStoreConfigToMldev(fromConfig, toObject);
  }
  return toObject;
}
function deleteFileSearchStoreConfigToMldev(fromObject, parentObject) {
  const toObject = {};
  const fromForce = getValueByPath(fromObject, ["force"]);
  if (parentObject !== void 0 && fromForce != null) {
    setValueByPath(parentObject, ["_query", "force"], fromForce);
  }
  return toObject;
}
function deleteFileSearchStoreParametersToMldev(fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], fromName);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    deleteFileSearchStoreConfigToMldev(fromConfig, toObject);
  }
  return toObject;
}
function getFileSearchStoreParametersToMldev(fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], fromName);
  }
  return toObject;
}
function importFileConfigToMldev(fromObject, parentObject) {
  const toObject = {};
  const fromCustomMetadata = getValueByPath(fromObject, [
    "customMetadata"
  ]);
  if (parentObject !== void 0 && fromCustomMetadata != null) {
    let transformedList = fromCustomMetadata;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(parentObject, ["customMetadata"], transformedList);
  }
  const fromChunkingConfig = getValueByPath(fromObject, [
    "chunkingConfig"
  ]);
  if (parentObject !== void 0 && fromChunkingConfig != null) {
    setValueByPath(parentObject, ["chunkingConfig"], fromChunkingConfig);
  }
  return toObject;
}
function importFileOperationFromMldev(fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromMetadata = getValueByPath(fromObject, ["metadata"]);
  if (fromMetadata != null) {
    setValueByPath(toObject, ["metadata"], fromMetadata);
  }
  const fromDone = getValueByPath(fromObject, ["done"]);
  if (fromDone != null) {
    setValueByPath(toObject, ["done"], fromDone);
  }
  const fromError = getValueByPath(fromObject, ["error"]);
  if (fromError != null) {
    setValueByPath(toObject, ["error"], fromError);
  }
  const fromResponse = getValueByPath(fromObject, ["response"]);
  if (fromResponse != null) {
    setValueByPath(toObject, ["response"], importFileResponseFromMldev(fromResponse));
  }
  return toObject;
}
function importFileParametersToMldev(fromObject) {
  const toObject = {};
  const fromFileSearchStoreName = getValueByPath(fromObject, [
    "fileSearchStoreName"
  ]);
  if (fromFileSearchStoreName != null) {
    setValueByPath(toObject, ["_url", "file_search_store_name"], fromFileSearchStoreName);
  }
  const fromFileName = getValueByPath(fromObject, ["fileName"]);
  if (fromFileName != null) {
    setValueByPath(toObject, ["fileName"], fromFileName);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    importFileConfigToMldev(fromConfig, toObject);
  }
  return toObject;
}
function importFileResponseFromMldev(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromParent = getValueByPath(fromObject, ["parent"]);
  if (fromParent != null) {
    setValueByPath(toObject, ["parent"], fromParent);
  }
  const fromDocumentName = getValueByPath(fromObject, ["documentName"]);
  if (fromDocumentName != null) {
    setValueByPath(toObject, ["documentName"], fromDocumentName);
  }
  return toObject;
}
function listFileSearchStoresConfigToMldev(fromObject, parentObject) {
  const toObject = {};
  const fromPageSize = getValueByPath(fromObject, ["pageSize"]);
  if (parentObject !== void 0 && fromPageSize != null) {
    setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize);
  }
  const fromPageToken = getValueByPath(fromObject, ["pageToken"]);
  if (parentObject !== void 0 && fromPageToken != null) {
    setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken);
  }
  return toObject;
}
function listFileSearchStoresParametersToMldev(fromObject) {
  const toObject = {};
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    listFileSearchStoresConfigToMldev(fromConfig, toObject);
  }
  return toObject;
}
function listFileSearchStoresResponseFromMldev(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromNextPageToken = getValueByPath(fromObject, [
    "nextPageToken"
  ]);
  if (fromNextPageToken != null) {
    setValueByPath(toObject, ["nextPageToken"], fromNextPageToken);
  }
  const fromFileSearchStores = getValueByPath(fromObject, [
    "fileSearchStores"
  ]);
  if (fromFileSearchStores != null) {
    let transformedList = fromFileSearchStores;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["fileSearchStores"], transformedList);
  }
  return toObject;
}
function uploadToFileSearchStoreConfigToMldev(fromObject, parentObject) {
  const toObject = {};
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (parentObject !== void 0 && fromMimeType != null) {
    setValueByPath(parentObject, ["mimeType"], fromMimeType);
  }
  const fromDisplayName = getValueByPath(fromObject, ["displayName"]);
  if (parentObject !== void 0 && fromDisplayName != null) {
    setValueByPath(parentObject, ["displayName"], fromDisplayName);
  }
  const fromCustomMetadata = getValueByPath(fromObject, [
    "customMetadata"
  ]);
  if (parentObject !== void 0 && fromCustomMetadata != null) {
    let transformedList = fromCustomMetadata;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(parentObject, ["customMetadata"], transformedList);
  }
  const fromChunkingConfig = getValueByPath(fromObject, [
    "chunkingConfig"
  ]);
  if (parentObject !== void 0 && fromChunkingConfig != null) {
    setValueByPath(parentObject, ["chunkingConfig"], fromChunkingConfig);
  }
  return toObject;
}
function uploadToFileSearchStoreParametersToMldev(fromObject) {
  const toObject = {};
  const fromFileSearchStoreName = getValueByPath(fromObject, [
    "fileSearchStoreName"
  ]);
  if (fromFileSearchStoreName != null) {
    setValueByPath(toObject, ["_url", "file_search_store_name"], fromFileSearchStoreName);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    uploadToFileSearchStoreConfigToMldev(fromConfig, toObject);
  }
  return toObject;
}
function uploadToFileSearchStoreResumableResponseFromMldev(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  return toObject;
}
var CONTENT_TYPE_HEADER = "Content-Type";
var SERVER_TIMEOUT_HEADER = "X-Server-Timeout";
var USER_AGENT_HEADER = "User-Agent";
var GOOGLE_API_CLIENT_HEADER = "x-goog-api-client";
var SDK_VERSION = "1.45.0";
var LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`;
var VERTEX_AI_API_DEFAULT_VERSION = "v1beta1";
var GOOGLE_AI_API_DEFAULT_VERSION = "v1beta";
var DEFAULT_RETRY_ATTEMPTS = 5;
var DEFAULT_RETRY_HTTP_STATUS_CODES = [
  408,
  // Request timeout
  429,
  // Too many requests
  500,
  // Internal server error
  502,
  // Bad gateway
  503,
  // Service unavailable
  504
  // Gateway timeout
];
var ApiClient = class {
  constructor(opts) {
    var _a7, _b, _c;
    this.clientOptions = Object.assign({}, opts);
    this.customBaseUrl = (_a7 = opts.httpOptions) === null || _a7 === void 0 ? void 0 : _a7.baseUrl;
    if (this.clientOptions.vertexai) {
      if (this.clientOptions.project && this.clientOptions.location) {
        this.clientOptions.apiKey = void 0;
      } else if (this.clientOptions.apiKey) {
        this.clientOptions.project = void 0;
        this.clientOptions.location = void 0;
      }
    }
    const initHttpOptions = {};
    if (this.clientOptions.vertexai) {
      if (!this.clientOptions.location && !this.clientOptions.apiKey && !this.customBaseUrl) {
        this.clientOptions.location = "global";
      }
      const hasSufficientAuth = this.clientOptions.project && this.clientOptions.location || this.clientOptions.apiKey;
      if (!hasSufficientAuth && !this.customBaseUrl) {
        throw new Error("Authentication is not set up. Please provide either a project and location, or an API key, or a custom base URL.");
      }
      const hasConstructorAuth = opts.project && opts.location || !!opts.apiKey;
      if (this.customBaseUrl && !hasConstructorAuth) {
        initHttpOptions.baseUrl = this.customBaseUrl;
        this.clientOptions.project = void 0;
        this.clientOptions.location = void 0;
      } else if (this.clientOptions.apiKey || this.clientOptions.location === "global") {
        initHttpOptions.baseUrl = "https://aiplatform.googleapis.com/";
      } else if (this.clientOptions.project && this.clientOptions.location) {
        initHttpOptions.baseUrl = `https://${this.clientOptions.location}-aiplatform.googleapis.com/`;
      }
      initHttpOptions.apiVersion = (_b = this.clientOptions.apiVersion) !== null && _b !== void 0 ? _b : VERTEX_AI_API_DEFAULT_VERSION;
    } else {
      if (!this.clientOptions.apiKey) {
        console.warn("API key should be set when using the Gemini API.");
      }
      initHttpOptions.apiVersion = (_c = this.clientOptions.apiVersion) !== null && _c !== void 0 ? _c : GOOGLE_AI_API_DEFAULT_VERSION;
      initHttpOptions.baseUrl = `https://generativelanguage.googleapis.com/`;
    }
    initHttpOptions.headers = this.getDefaultHeaders();
    this.clientOptions.httpOptions = initHttpOptions;
    if (opts.httpOptions) {
      this.clientOptions.httpOptions = this.patchHttpOptions(initHttpOptions, opts.httpOptions);
    }
  }
  isVertexAI() {
    var _a7;
    return (_a7 = this.clientOptions.vertexai) !== null && _a7 !== void 0 ? _a7 : false;
  }
  getProject() {
    return this.clientOptions.project;
  }
  getLocation() {
    return this.clientOptions.location;
  }
  getCustomBaseUrl() {
    return this.customBaseUrl;
  }
  async getAuthHeaders() {
    const headers = new Headers();
    await this.clientOptions.auth.addAuthHeaders(headers);
    return headers;
  }
  getApiVersion() {
    if (this.clientOptions.httpOptions && this.clientOptions.httpOptions.apiVersion !== void 0) {
      return this.clientOptions.httpOptions.apiVersion;
    }
    throw new Error("API version is not set.");
  }
  getBaseUrl() {
    if (this.clientOptions.httpOptions && this.clientOptions.httpOptions.baseUrl !== void 0) {
      return this.clientOptions.httpOptions.baseUrl;
    }
    throw new Error("Base URL is not set.");
  }
  getRequestUrl() {
    return this.getRequestUrlInternal(this.clientOptions.httpOptions);
  }
  getHeaders() {
    if (this.clientOptions.httpOptions && this.clientOptions.httpOptions.headers !== void 0) {
      return this.clientOptions.httpOptions.headers;
    } else {
      throw new Error("Headers are not set.");
    }
  }
  getRequestUrlInternal(httpOptions) {
    if (!httpOptions || httpOptions.baseUrl === void 0 || httpOptions.apiVersion === void 0) {
      throw new Error("HTTP options are not correctly set.");
    }
    const baseUrl = httpOptions.baseUrl.endsWith("/") ? httpOptions.baseUrl.slice(0, -1) : httpOptions.baseUrl;
    const urlElement = [baseUrl];
    if (httpOptions.apiVersion && httpOptions.apiVersion !== "") {
      urlElement.push(httpOptions.apiVersion);
    }
    return urlElement.join("/");
  }
  getBaseResourcePath() {
    return `projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`;
  }
  getApiKey() {
    return this.clientOptions.apiKey;
  }
  getWebsocketBaseUrl() {
    const baseUrl = this.getBaseUrl();
    const urlParts = new URL(baseUrl);
    urlParts.protocol = urlParts.protocol == "http:" ? "ws" : "wss";
    return urlParts.toString();
  }
  setBaseUrl(url) {
    if (this.clientOptions.httpOptions) {
      this.clientOptions.httpOptions.baseUrl = url;
    } else {
      throw new Error("HTTP options are not correctly set.");
    }
  }
  constructUrl(path6, httpOptions, prependProjectLocation) {
    const urlElement = [this.getRequestUrlInternal(httpOptions)];
    if (prependProjectLocation) {
      urlElement.push(this.getBaseResourcePath());
    }
    if (path6 !== "") {
      urlElement.push(path6);
    }
    const url = new URL(`${urlElement.join("/")}`);
    return url;
  }
  shouldPrependVertexProjectPath(request, httpOptions) {
    if (httpOptions.baseUrl && httpOptions.baseUrlResourceScope === ResourceScope.COLLECTION) {
      return false;
    }
    if (this.clientOptions.apiKey) {
      return false;
    }
    if (!this.clientOptions.vertexai) {
      return false;
    }
    if (request.path.startsWith("projects/")) {
      return false;
    }
    if (request.httpMethod === "GET" && request.path.startsWith("publishers/google/models")) {
      return false;
    }
    return true;
  }
  async request(request) {
    let patchedHttpOptions = this.clientOptions.httpOptions;
    if (request.httpOptions) {
      patchedHttpOptions = this.patchHttpOptions(this.clientOptions.httpOptions, request.httpOptions);
    }
    const prependProjectLocation = this.shouldPrependVertexProjectPath(request, patchedHttpOptions);
    const url = this.constructUrl(request.path, patchedHttpOptions, prependProjectLocation);
    if (request.queryParams) {
      for (const [key, value] of Object.entries(request.queryParams)) {
        url.searchParams.append(key, String(value));
      }
    }
    let requestInit = {};
    if (request.httpMethod === "GET") {
      if (request.body && request.body !== "{}") {
        throw new Error("Request body should be empty for GET request, but got non empty request body");
      }
    } else {
      requestInit.body = request.body;
    }
    requestInit = await this.includeExtraHttpOptionsToRequestInit(requestInit, patchedHttpOptions, url.toString(), request.abortSignal);
    return this.unaryApiCall(url, requestInit, request.httpMethod);
  }
  patchHttpOptions(baseHttpOptions, requestHttpOptions) {
    const patchedHttpOptions = JSON.parse(JSON.stringify(baseHttpOptions));
    for (const [key, value] of Object.entries(requestHttpOptions)) {
      if (typeof value === "object") {
        patchedHttpOptions[key] = Object.assign(Object.assign({}, patchedHttpOptions[key]), value);
      } else if (value !== void 0) {
        patchedHttpOptions[key] = value;
      }
    }
    return patchedHttpOptions;
  }
  async requestStream(request) {
    let patchedHttpOptions = this.clientOptions.httpOptions;
    if (request.httpOptions) {
      patchedHttpOptions = this.patchHttpOptions(this.clientOptions.httpOptions, request.httpOptions);
    }
    const prependProjectLocation = this.shouldPrependVertexProjectPath(request, patchedHttpOptions);
    const url = this.constructUrl(request.path, patchedHttpOptions, prependProjectLocation);
    if (!url.searchParams.has("alt") || url.searchParams.get("alt") !== "sse") {
      url.searchParams.set("alt", "sse");
    }
    let requestInit = {};
    requestInit.body = request.body;
    requestInit = await this.includeExtraHttpOptionsToRequestInit(requestInit, patchedHttpOptions, url.toString(), request.abortSignal);
    return this.streamApiCall(url, requestInit, request.httpMethod);
  }
  async includeExtraHttpOptionsToRequestInit(requestInit, httpOptions, url, abortSignal) {
    if (httpOptions && httpOptions.timeout || abortSignal) {
      const abortController = new AbortController();
      const signal = abortController.signal;
      if (httpOptions.timeout && (httpOptions === null || httpOptions === void 0 ? void 0 : httpOptions.timeout) > 0) {
        const timeoutHandle = setTimeout(() => abortController.abort(), httpOptions.timeout);
        if (timeoutHandle && typeof timeoutHandle.unref === "function") {
          timeoutHandle.unref();
        }
      }
      if (abortSignal) {
        abortSignal.addEventListener("abort", () => {
          abortController.abort();
        });
      }
      requestInit.signal = signal;
    }
    if (httpOptions && httpOptions.extraBody !== null) {
      includeExtraBodyToRequestInit(requestInit, httpOptions.extraBody);
    }
    requestInit.headers = await this.getHeadersInternal(httpOptions, url);
    return requestInit;
  }
  async unaryApiCall(url, requestInit, httpMethod) {
    return this.apiCall(url.toString(), Object.assign(Object.assign({}, requestInit), { method: httpMethod })).then(async (response) => {
      await throwErrorIfNotOK(response);
      return new HttpResponse(response);
    }).catch((e9) => {
      if (e9 instanceof Error) {
        throw e9;
      } else {
        throw new Error(JSON.stringify(e9));
      }
    });
  }
  async streamApiCall(url, requestInit, httpMethod) {
    return this.apiCall(url.toString(), Object.assign(Object.assign({}, requestInit), { method: httpMethod })).then(async (response) => {
      await throwErrorIfNotOK(response);
      return this.processStreamResponse(response);
    }).catch((e9) => {
      if (e9 instanceof Error) {
        throw e9;
      } else {
        throw new Error(JSON.stringify(e9));
      }
    });
  }
  processStreamResponse(response) {
    return __asyncGenerator(this, arguments, function* processStreamResponse_1() {
      var _a7;
      const reader = (_a7 = response === null || response === void 0 ? void 0 : response.body) === null || _a7 === void 0 ? void 0 : _a7.getReader();
      const decoder = new TextDecoder("utf-8");
      if (!reader) {
        throw new Error("Response body is empty");
      }
      try {
        let buffer = "";
        const dataPrefix = "data:";
        const delimiters2 = ["\n\n", "\r\r", "\r\n\r\n"];
        while (true) {
          const { done, value } = yield __await(reader.read());
          if (done) {
            if (buffer.trim().length > 0) {
              throw new Error("Incomplete JSON segment at the end");
            }
            break;
          }
          const chunkString = decoder.decode(value, { stream: true });
          try {
            const chunkJson = JSON.parse(chunkString);
            if ("error" in chunkJson) {
              const errorJson = JSON.parse(JSON.stringify(chunkJson["error"]));
              const status = errorJson["status"];
              const code = errorJson["code"];
              const errorMessage = `got status: ${status}. ${JSON.stringify(chunkJson)}`;
              if (code >= 400 && code < 600) {
                const apiError = new ApiError({
                  message: errorMessage,
                  status: code
                });
                throw apiError;
              }
            }
          } catch (e9) {
            const error = e9;
            if (error.name === "ApiError") {
              throw e9;
            }
          }
          buffer += chunkString;
          let delimiterIndex = -1;
          let delimiterLength = 0;
          while (true) {
            delimiterIndex = -1;
            delimiterLength = 0;
            for (const delimiter2 of delimiters2) {
              const index = buffer.indexOf(delimiter2);
              if (index !== -1 && (delimiterIndex === -1 || index < delimiterIndex)) {
                delimiterIndex = index;
                delimiterLength = delimiter2.length;
              }
            }
            if (delimiterIndex === -1) {
              break;
            }
            const eventString = buffer.substring(0, delimiterIndex);
            buffer = buffer.substring(delimiterIndex + delimiterLength);
            const trimmedEvent = eventString.trim();
            if (trimmedEvent.startsWith(dataPrefix)) {
              const processedChunkString = trimmedEvent.substring(dataPrefix.length).trim();
              try {
                const partialResponse = new Response(processedChunkString, {
                  headers: response === null || response === void 0 ? void 0 : response.headers,
                  status: response === null || response === void 0 ? void 0 : response.status,
                  statusText: response === null || response === void 0 ? void 0 : response.statusText
                });
                yield yield __await(new HttpResponse(partialResponse));
              } catch (e9) {
                throw new Error(`exception parsing stream chunk ${processedChunkString}. ${e9}`);
              }
            }
          }
        }
      } finally {
        reader.releaseLock();
      }
    });
  }
  async apiCall(url, requestInit) {
    var _a7;
    if (!this.clientOptions.httpOptions || !this.clientOptions.httpOptions.retryOptions) {
      return fetch(url, requestInit);
    }
    const retryOptions = this.clientOptions.httpOptions.retryOptions;
    const runFetch = async () => {
      const response = await fetch(url, requestInit);
      if (response.ok) {
        return response;
      }
      if (DEFAULT_RETRY_HTTP_STATUS_CODES.includes(response.status)) {
        throw new Error(`Retryable HTTP Error: ${response.statusText}`);
      }
      throw new import_p_retry.AbortError(`Non-retryable exception ${response.statusText} sending request`);
    };
    return (0, import_p_retry.default)(runFetch, {
      // Retry attempts is one less than the number of total attempts.
      retries: ((_a7 = retryOptions.attempts) !== null && _a7 !== void 0 ? _a7 : DEFAULT_RETRY_ATTEMPTS) - 1
    });
  }
  getDefaultHeaders() {
    const headers = {};
    const versionHeaderValue = LIBRARY_LABEL + " " + this.clientOptions.userAgentExtra;
    headers[USER_AGENT_HEADER] = versionHeaderValue;
    headers[GOOGLE_API_CLIENT_HEADER] = versionHeaderValue;
    headers[CONTENT_TYPE_HEADER] = "application/json";
    return headers;
  }
  async getHeadersInternal(httpOptions, url) {
    const headers = new Headers();
    if (httpOptions && httpOptions.headers) {
      for (const [key, value] of Object.entries(httpOptions.headers)) {
        headers.append(key, value);
      }
      if (httpOptions.timeout && httpOptions.timeout > 0) {
        headers.append(SERVER_TIMEOUT_HEADER, String(Math.ceil(httpOptions.timeout / 1e3)));
      }
    }
    await this.clientOptions.auth.addAuthHeaders(headers, url);
    return headers;
  }
  getFileName(file) {
    var _a7;
    let fileName = "";
    if (typeof file === "string") {
      fileName = file.replace(/[/\\]+$/, "");
      fileName = (_a7 = fileName.split(/[/\\]/).pop()) !== null && _a7 !== void 0 ? _a7 : "";
    }
    return fileName;
  }
  /**
   * Uploads a file asynchronously using Gemini API only, this is not supported
   * in Vertex AI.
   *
   * @param file The string path to the file to be uploaded or a Blob object.
   * @param config Optional parameters specified in the `UploadFileConfig`
   *     interface. @see {@link types.UploadFileConfig}
   * @return A promise that resolves to a `File` object.
   * @throws An error if called on a Vertex AI client.
   * @throws An error if the `mimeType` is not provided and can not be inferred,
   */
  async uploadFile(file, config) {
    var _a7;
    const fileToUpload = {};
    if (config != null) {
      fileToUpload.mimeType = config.mimeType;
      fileToUpload.name = config.name;
      fileToUpload.displayName = config.displayName;
    }
    if (fileToUpload.name && !fileToUpload.name.startsWith("files/")) {
      fileToUpload.name = `files/${fileToUpload.name}`;
    }
    const uploader = this.clientOptions.uploader;
    const fileStat = await uploader.stat(file);
    fileToUpload.sizeBytes = String(fileStat.size);
    const mimeType = (_a7 = config === null || config === void 0 ? void 0 : config.mimeType) !== null && _a7 !== void 0 ? _a7 : fileStat.type;
    if (mimeType === void 0 || mimeType === "") {
      throw new Error("Can not determine mimeType. Please provide mimeType in the config.");
    }
    fileToUpload.mimeType = mimeType;
    const body = {
      file: fileToUpload
    };
    const fileName = this.getFileName(file);
    const path6 = formatMap("upload/v1beta/files", body["_url"]);
    const uploadUrl = await this.fetchUploadUrl(path6, fileToUpload.sizeBytes, fileToUpload.mimeType, fileName, body, config === null || config === void 0 ? void 0 : config.httpOptions);
    return uploader.upload(file, uploadUrl, this);
  }
  /**
   * Uploads a file to a given file search store asynchronously using Gemini API only, this is not supported
   * in Vertex AI.
   *
   * @param fileSearchStoreName The name of the file search store to upload the file to.
   * @param file The string path to the file to be uploaded or a Blob object.
   * @param config Optional parameters specified in the `UploadFileConfig`
   *     interface. @see {@link UploadFileConfig}
   * @return A promise that resolves to a `File` object.
   * @throws An error if called on a Vertex AI client.
   * @throws An error if the `mimeType` is not provided and can not be inferred,
   */
  async uploadFileToFileSearchStore(fileSearchStoreName, file, config) {
    var _a7;
    const uploader = this.clientOptions.uploader;
    const fileStat = await uploader.stat(file);
    const sizeBytes = String(fileStat.size);
    const mimeType = (_a7 = config === null || config === void 0 ? void 0 : config.mimeType) !== null && _a7 !== void 0 ? _a7 : fileStat.type;
    if (mimeType === void 0 || mimeType === "") {
      throw new Error("Can not determine mimeType. Please provide mimeType in the config.");
    }
    const path6 = `upload/v1beta/${fileSearchStoreName}:uploadToFileSearchStore`;
    const fileName = this.getFileName(file);
    const body = {};
    if (config != null) {
      uploadToFileSearchStoreConfigToMldev(config, body);
    }
    const uploadUrl = await this.fetchUploadUrl(path6, sizeBytes, mimeType, fileName, body, config === null || config === void 0 ? void 0 : config.httpOptions);
    return uploader.uploadToFileSearchStore(file, uploadUrl, this);
  }
  /**
   * Downloads a file asynchronously to the specified path.
   *
   * @params params - The parameters for the download request, see {@link
   * types.DownloadFileParameters}
   */
  async downloadFile(params) {
    const downloader = this.clientOptions.downloader;
    await downloader.download(params, this);
  }
  async fetchUploadUrl(path6, sizeBytes, mimeType, fileName, body, configHttpOptions) {
    var _a7;
    let httpOptions = {};
    if (configHttpOptions) {
      httpOptions = configHttpOptions;
    } else {
      httpOptions = {
        apiVersion: "",
        // api-version is set in the path.
        headers: Object.assign({ "Content-Type": "application/json", "X-Goog-Upload-Protocol": "resumable", "X-Goog-Upload-Command": "start", "X-Goog-Upload-Header-Content-Length": `${sizeBytes}`, "X-Goog-Upload-Header-Content-Type": `${mimeType}` }, fileName ? { "X-Goog-Upload-File-Name": fileName } : {})
      };
    }
    const httpResponse = await this.request({
      path: path6,
      body: JSON.stringify(body),
      httpMethod: "POST",
      httpOptions
    });
    if (!httpResponse || !(httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.headers)) {
      throw new Error("Server did not return an HttpResponse or the returned HttpResponse did not have headers.");
    }
    const uploadUrl = (_a7 = httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.headers) === null || _a7 === void 0 ? void 0 : _a7["x-goog-upload-url"];
    if (uploadUrl === void 0) {
      throw new Error("Failed to get upload url. Server did not return the x-google-upload-url in the headers");
    }
    return uploadUrl;
  }
};
async function throwErrorIfNotOK(response) {
  var _a7;
  if (response === void 0) {
    throw new Error("response is undefined");
  }
  if (!response.ok) {
    const status = response.status;
    let errorBody;
    if ((_a7 = response.headers.get("content-type")) === null || _a7 === void 0 ? void 0 : _a7.includes("application/json")) {
      errorBody = await response.json();
    } else {
      errorBody = {
        error: {
          message: await response.text(),
          code: response.status,
          status: response.statusText
        }
      };
    }
    const errorMessage = JSON.stringify(errorBody);
    if (status >= 400 && status < 600) {
      const apiError = new ApiError({
        message: errorMessage,
        status
      });
      throw apiError;
    }
    throw new Error(errorMessage);
  }
}
function includeExtraBodyToRequestInit(requestInit, extraBody) {
  if (!extraBody || Object.keys(extraBody).length === 0) {
    return;
  }
  if (requestInit.body instanceof Blob) {
    console.warn("includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.");
    return;
  }
  let currentBodyObject = {};
  if (typeof requestInit.body === "string" && requestInit.body.length > 0) {
    try {
      const parsedBody = JSON.parse(requestInit.body);
      if (typeof parsedBody === "object" && parsedBody !== null && !Array.isArray(parsedBody)) {
        currentBodyObject = parsedBody;
      } else {
        console.warn("includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.");
        return;
      }
    } catch (e9) {
      console.warn("includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.");
      return;
    }
  }
  function deepMerge(target, source) {
    const output = Object.assign({}, target);
    for (const key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        const sourceValue = source[key];
        const targetValue = output[key];
        if (sourceValue && typeof sourceValue === "object" && !Array.isArray(sourceValue) && targetValue && typeof targetValue === "object" && !Array.isArray(targetValue)) {
          output[key] = deepMerge(targetValue, sourceValue);
        } else {
          if (targetValue && sourceValue && typeof targetValue !== typeof sourceValue) {
            console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${key}". Original type: ${typeof targetValue}, New type: ${typeof sourceValue}. Overwriting.`);
          }
          output[key] = sourceValue;
        }
      }
    }
    return output;
  }
  const mergedBody = deepMerge(currentBodyObject, extraBody);
  requestInit.body = JSON.stringify(mergedBody);
}
var MCP_LABEL = "mcp_used/unknown";
var hasMcpToolUsageFromMcpToTool = false;
function hasMcpToolUsage(tools) {
  for (const tool of tools) {
    if (isMcpCallableTool(tool)) {
      return true;
    }
    if (typeof tool === "object" && "inputSchema" in tool) {
      return true;
    }
  }
  return hasMcpToolUsageFromMcpToTool;
}
function setMcpUsageHeader(headers) {
  var _a7;
  const existingHeader = (_a7 = headers[GOOGLE_API_CLIENT_HEADER]) !== null && _a7 !== void 0 ? _a7 : "";
  headers[GOOGLE_API_CLIENT_HEADER] = (existingHeader + ` ${MCP_LABEL}`).trimStart();
}
function isMcpCallableTool(object) {
  return object !== null && typeof object === "object" && object instanceof McpCallableTool;
}
function listAllTools(mcpClient_1) {
  return __asyncGenerator(this, arguments, function* listAllTools_1(mcpClient, maxTools = 100) {
    let cursor = void 0;
    let numTools = 0;
    while (numTools < maxTools) {
      const t6 = yield __await(mcpClient.listTools({ cursor }));
      for (const tool of t6.tools) {
        yield yield __await(tool);
        numTools++;
      }
      if (!t6.nextCursor) {
        break;
      }
      cursor = t6.nextCursor;
    }
  });
}
var McpCallableTool = class _McpCallableTool {
  constructor(mcpClients = [], config) {
    this.mcpTools = [];
    this.functionNameToMcpClient = {};
    this.mcpClients = mcpClients;
    this.config = config;
  }
  /**
   * Creates a McpCallableTool.
   */
  static create(mcpClients, config) {
    return new _McpCallableTool(mcpClients, config);
  }
  /**
   * Validates the function names are not duplicate and initialize the function
   * name to MCP client mapping.
   *
   * @throws {Error} if the MCP tools from the MCP clients have duplicate tool
   *     names.
   */
  async initialize() {
    var _a7, e_1, _b, _c;
    if (this.mcpTools.length > 0) {
      return;
    }
    const functionMap = {};
    const mcpTools = [];
    for (const mcpClient of this.mcpClients) {
      try {
        for (var _d = true, _e2 = (e_1 = void 0, __asyncValues(listAllTools(mcpClient))), _f; _f = await _e2.next(), _a7 = _f.done, !_a7; _d = true) {
          _c = _f.value;
          _d = false;
          const mcpTool = _c;
          mcpTools.push(mcpTool);
          const mcpToolName = mcpTool.name;
          if (functionMap[mcpToolName]) {
            throw new Error(`Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`);
          }
          functionMap[mcpToolName] = mcpClient;
        }
      } catch (e_1_1) {
        e_1 = { error: e_1_1 };
      } finally {
        try {
          if (!_d && !_a7 && (_b = _e2.return)) await _b.call(_e2);
        } finally {
          if (e_1) throw e_1.error;
        }
      }
    }
    this.mcpTools = mcpTools;
    this.functionNameToMcpClient = functionMap;
  }
  async tool() {
    await this.initialize();
    return mcpToolsToGeminiTool(this.mcpTools, this.config);
  }
  async callTool(functionCalls) {
    await this.initialize();
    const functionCallResponseParts = [];
    for (const functionCall of functionCalls) {
      if (functionCall.name in this.functionNameToMcpClient) {
        const mcpClient = this.functionNameToMcpClient[functionCall.name];
        let requestOptions = void 0;
        if (this.config.timeout) {
          requestOptions = {
            timeout: this.config.timeout
          };
        }
        const callToolResponse = await mcpClient.callTool(
          {
            name: functionCall.name,
            arguments: functionCall.args
          },
          // Set the result schema to undefined to allow MCP to rely on the
          // default schema.
          void 0,
          requestOptions
        );
        functionCallResponseParts.push({
          functionResponse: {
            name: functionCall.name,
            response: callToolResponse.isError ? { error: callToolResponse } : callToolResponse
          }
        });
      }
    }
    return functionCallResponseParts;
  }
};
async function handleWebSocketMessage$1(apiClient, onmessage, event) {
  const serverMessage = new LiveMusicServerMessage();
  let data;
  if (event.data instanceof Blob) {
    data = JSON.parse(await event.data.text());
  } else {
    data = JSON.parse(event.data);
  }
  Object.assign(serverMessage, data);
  onmessage(serverMessage);
}
var LiveMusic = class {
  constructor(apiClient, auth, webSocketFactory) {
    this.apiClient = apiClient;
    this.auth = auth;
    this.webSocketFactory = webSocketFactory;
  }
  /**
       Establishes a connection to the specified model and returns a
       LiveMusicSession object representing that connection.
  
       @experimental
  
       @remarks
  
       @param params - The parameters for establishing a connection to the model.
       @return A live session.
  
       @example
       ```ts
       let model = 'models/lyria-realtime-exp';
       const session = await ai.live.music.connect({
         model: model,
         callbacks: {
           onmessage: (e: MessageEvent) => {
             console.log('Received message from the server: %s\n', debug(e.data));
           },
           onerror: (e: ErrorEvent) => {
             console.log('Error occurred: %s\n', debug(e.error));
           },
           onclose: (e: CloseEvent) => {
             console.log('Connection closed.');
           },
         },
       });
       ```
      */
  async connect(params) {
    var _a7, _b;
    if (this.apiClient.isVertexAI()) {
      throw new Error("Live music is not supported for Vertex AI.");
    }
    console.warn("Live music generation is experimental and may change in future versions.");
    const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl();
    const apiVersion = this.apiClient.getApiVersion();
    const headers = mapToHeaders$1(this.apiClient.getDefaultHeaders());
    const apiKey = this.apiClient.getApiKey();
    const url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.BidiGenerateMusic?key=${apiKey}`;
    let onopenResolve = () => {
    };
    const onopenPromise = new Promise((resolve) => {
      onopenResolve = resolve;
    });
    const callbacks = params.callbacks;
    const onopenAwaitedCallback = function() {
      onopenResolve({});
    };
    const apiClient = this.apiClient;
    const websocketCallbacks = {
      onopen: onopenAwaitedCallback,
      onmessage: (event) => {
        void handleWebSocketMessage$1(apiClient, callbacks.onmessage, event);
      },
      onerror: (_a7 = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onerror) !== null && _a7 !== void 0 ? _a7 : function(e9) {
      },
      onclose: (_b = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onclose) !== null && _b !== void 0 ? _b : function(e9) {
      }
    };
    const conn = this.webSocketFactory.create(url, headersToMap$1(headers), websocketCallbacks);
    conn.connect();
    await onopenPromise;
    const model = tModel(this.apiClient, params.model);
    const setup = { model };
    const clientMessage = { setup };
    conn.send(JSON.stringify(clientMessage));
    return new LiveMusicSession(conn, this.apiClient);
  }
};
var LiveMusicSession = class {
  constructor(conn, apiClient) {
    this.conn = conn;
    this.apiClient = apiClient;
  }
  /**
      Sets inputs to steer music generation. Updates the session's current
      weighted prompts.
  
      @param params - Contains one property, `weightedPrompts`.
  
        - `weightedPrompts` to send to the model; weights are normalized to
          sum to 1.0.
  
      @experimental
     */
  async setWeightedPrompts(params) {
    if (!params.weightedPrompts || Object.keys(params.weightedPrompts).length === 0) {
      throw new Error("Weighted prompts must be set and contain at least one entry.");
    }
    const clientContent = liveMusicSetWeightedPromptsParametersToMldev(params);
    this.conn.send(JSON.stringify({ clientContent }));
  }
  /**
      Sets a configuration to the model. Updates the session's current
      music generation config.
  
      @param params - Contains one property, `musicGenerationConfig`.
  
        - `musicGenerationConfig` to set in the model. Passing an empty or
      undefined config to the model will reset the config to defaults.
  
      @experimental
     */
  async setMusicGenerationConfig(params) {
    if (!params.musicGenerationConfig) {
      params.musicGenerationConfig = {};
    }
    const setConfigParameters = liveMusicSetConfigParametersToMldev(params);
    this.conn.send(JSON.stringify(setConfigParameters));
  }
  sendPlaybackControl(playbackControl) {
    const clientMessage = { playbackControl };
    this.conn.send(JSON.stringify(clientMessage));
  }
  /**
   * Start the music stream.
   *
   * @experimental
   */
  play() {
    this.sendPlaybackControl(LiveMusicPlaybackControl.PLAY);
  }
  /**
   * Temporarily halt the music stream. Use `play` to resume from the current
   * position.
   *
   * @experimental
   */
  pause() {
    this.sendPlaybackControl(LiveMusicPlaybackControl.PAUSE);
  }
  /**
   * Stop the music stream and reset the state. Retains the current prompts
   * and config.
   *
   * @experimental
   */
  stop() {
    this.sendPlaybackControl(LiveMusicPlaybackControl.STOP);
  }
  /**
   * Resets the context of the music generation without stopping it.
   * Retains the current prompts and config.
   *
   * @experimental
   */
  resetContext() {
    this.sendPlaybackControl(LiveMusicPlaybackControl.RESET_CONTEXT);
  }
  /**
       Terminates the WebSocket connection.
  
       @experimental
     */
  close() {
    this.conn.close();
  }
};
function headersToMap$1(headers) {
  const headerMap = {};
  headers.forEach((value, key) => {
    headerMap[key] = value;
  });
  return headerMap;
}
function mapToHeaders$1(map) {
  const headers = new Headers();
  for (const [key, value] of Object.entries(map)) {
    headers.append(key, value);
  }
  return headers;
}
var FUNCTION_RESPONSE_REQUIRES_ID = "FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.";
async function handleWebSocketMessage(apiClient, onmessage, event) {
  const serverMessage = new LiveServerMessage();
  let jsonData;
  if (event.data instanceof Blob) {
    jsonData = await event.data.text();
  } else if (event.data instanceof ArrayBuffer) {
    jsonData = new TextDecoder().decode(event.data);
  } else {
    jsonData = event.data;
  }
  const data = JSON.parse(jsonData);
  if (apiClient.isVertexAI()) {
    const resp = liveServerMessageFromVertex(data);
    Object.assign(serverMessage, resp);
  } else {
    const resp = data;
    Object.assign(serverMessage, resp);
  }
  onmessage(serverMessage);
}
var Live = class {
  constructor(apiClient, auth, webSocketFactory) {
    this.apiClient = apiClient;
    this.auth = auth;
    this.webSocketFactory = webSocketFactory;
    this.music = new LiveMusic(this.apiClient, this.auth, this.webSocketFactory);
  }
  /**
       Establishes a connection to the specified model with the given
       configuration and returns a Session object representing that connection.
  
       @experimental Built-in MCP support is an experimental feature, may change in
       future versions.
  
       @remarks
  
       @param params - The parameters for establishing a connection to the model.
       @return A live session.
  
       @example
       ```ts
       let model: string;
       if (GOOGLE_GENAI_USE_VERTEXAI) {
         model = 'gemini-2.0-flash-live-preview-04-09';
       } else {
         model = 'gemini-live-2.5-flash-preview';
       }
       const session = await ai.live.connect({
         model: model,
         config: {
           responseModalities: [Modality.AUDIO],
         },
         callbacks: {
           onopen: () => {
             console.log('Connected to the socket.');
           },
           onmessage: (e: MessageEvent) => {
             console.log('Received message from the server: %s\n', debug(e.data));
           },
           onerror: (e: ErrorEvent) => {
             console.log('Error occurred: %s\n', debug(e.error));
           },
           onclose: (e: CloseEvent) => {
             console.log('Connection closed.');
           },
         },
       });
       ```
      */
  async connect(params) {
    var _a7, _b, _c, _d, _e2, _f;
    if (params.config && params.config.httpOptions) {
      throw new Error("The Live module does not support httpOptions at request-level in LiveConnectConfig yet. Please use the client-level httpOptions configuration instead.");
    }
    const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl();
    const apiVersion = this.apiClient.getApiVersion();
    let url;
    const clientHeaders = this.apiClient.getHeaders();
    if (params.config && params.config.tools && hasMcpToolUsage(params.config.tools)) {
      setMcpUsageHeader(clientHeaders);
    }
    const headers = mapToHeaders(clientHeaders);
    if (this.apiClient.isVertexAI()) {
      const project = this.apiClient.getProject();
      const location = this.apiClient.getLocation();
      const apiKey = this.apiClient.getApiKey();
      const hasStandardAuth = !!project && !!location || !!apiKey;
      if (this.apiClient.getCustomBaseUrl() && !hasStandardAuth) {
        url = websocketBaseUrl;
      } else {
        url = `${websocketBaseUrl}/ws/google.cloud.aiplatform.${apiVersion}.LlmBidiService/BidiGenerateContent`;
        await this.auth.addAuthHeaders(headers, url);
      }
    } else {
      const apiKey = this.apiClient.getApiKey();
      let method = "BidiGenerateContent";
      let keyName = "key";
      if (apiKey === null || apiKey === void 0 ? void 0 : apiKey.startsWith("auth_tokens/")) {
        console.warn("Warning: Ephemeral token support is experimental and may change in future versions.");
        if (apiVersion !== "v1alpha") {
          console.warn("Warning: The SDK's ephemeral token support is in v1alpha only. Please use const ai = new GoogleGenAI({apiKey: token.name, httpOptions: { apiVersion: 'v1alpha' }}); before session connection.");
        }
        method = "BidiGenerateContentConstrained";
        keyName = "access_token";
      }
      url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.${method}?${keyName}=${apiKey}`;
    }
    let onopenResolve = () => {
    };
    const onopenPromise = new Promise((resolve) => {
      onopenResolve = resolve;
    });
    const callbacks = params.callbacks;
    const onopenAwaitedCallback = function() {
      var _a8;
      (_a8 = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onopen) === null || _a8 === void 0 ? void 0 : _a8.call(callbacks);
      onopenResolve({});
    };
    const apiClient = this.apiClient;
    const websocketCallbacks = {
      onopen: onopenAwaitedCallback,
      onmessage: (event) => {
        void handleWebSocketMessage(apiClient, callbacks.onmessage, event);
      },
      onerror: (_a7 = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onerror) !== null && _a7 !== void 0 ? _a7 : function(e9) {
      },
      onclose: (_b = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onclose) !== null && _b !== void 0 ? _b : function(e9) {
      }
    };
    const conn = this.webSocketFactory.create(url, headersToMap(headers), websocketCallbacks);
    conn.connect();
    await onopenPromise;
    let transformedModel = tModel(this.apiClient, params.model);
    if (this.apiClient.isVertexAI() && transformedModel.startsWith("publishers/")) {
      const project = this.apiClient.getProject();
      const location = this.apiClient.getLocation();
      if (project && location) {
        transformedModel = `projects/${project}/locations/${location}/` + transformedModel;
      }
    }
    let clientMessage = {};
    if (this.apiClient.isVertexAI() && ((_c = params.config) === null || _c === void 0 ? void 0 : _c.responseModalities) === void 0) {
      if (params.config === void 0) {
        params.config = { responseModalities: [Modality.AUDIO] };
      } else {
        params.config.responseModalities = [Modality.AUDIO];
      }
    }
    if ((_d = params.config) === null || _d === void 0 ? void 0 : _d.generationConfig) {
      console.warn("Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. This will become an error in a future version (not before Q3 2025).");
    }
    const inputTools = (_f = (_e2 = params.config) === null || _e2 === void 0 ? void 0 : _e2.tools) !== null && _f !== void 0 ? _f : [];
    const convertedTools = [];
    for (const tool of inputTools) {
      if (this.isCallableTool(tool)) {
        const callableTool = tool;
        convertedTools.push(await callableTool.tool());
      } else {
        convertedTools.push(tool);
      }
    }
    if (convertedTools.length > 0) {
      params.config.tools = convertedTools;
    }
    const liveConnectParameters = {
      model: transformedModel,
      config: params.config,
      callbacks: params.callbacks
    };
    if (this.apiClient.isVertexAI()) {
      clientMessage = liveConnectParametersToVertex(this.apiClient, liveConnectParameters);
    } else {
      clientMessage = liveConnectParametersToMldev(this.apiClient, liveConnectParameters);
    }
    delete clientMessage["config"];
    conn.send(JSON.stringify(clientMessage));
    return new Session(conn, this.apiClient);
  }
  // TODO: b/416041229 - Abstract this method to a common place.
  isCallableTool(tool) {
    return "callTool" in tool && typeof tool.callTool === "function";
  }
};
var defaultLiveSendClientContentParamerters = {
  turnComplete: true
};
var Session = class {
  constructor(conn, apiClient) {
    this.conn = conn;
    this.apiClient = apiClient;
  }
  tLiveClientContent(apiClient, params) {
    if (params.turns !== null && params.turns !== void 0) {
      let contents = [];
      try {
        contents = tContents(params.turns);
        if (!apiClient.isVertexAI()) {
          contents = contents.map((item) => contentToMldev$1(item));
        }
      } catch (_a7) {
        throw new Error(`Failed to parse client content "turns", type: '${typeof params.turns}'`);
      }
      return {
        clientContent: { turns: contents, turnComplete: params.turnComplete }
      };
    }
    return {
      clientContent: { turnComplete: params.turnComplete }
    };
  }
  tLiveClienttToolResponse(apiClient, params) {
    let functionResponses = [];
    if (params.functionResponses == null) {
      throw new Error("functionResponses is required.");
    }
    if (!Array.isArray(params.functionResponses)) {
      functionResponses = [params.functionResponses];
    } else {
      functionResponses = params.functionResponses;
    }
    if (functionResponses.length === 0) {
      throw new Error("functionResponses is required.");
    }
    for (const functionResponse of functionResponses) {
      if (typeof functionResponse !== "object" || functionResponse === null || !("name" in functionResponse) || !("response" in functionResponse)) {
        throw new Error(`Could not parse function response, type '${typeof functionResponse}'.`);
      }
      if (!apiClient.isVertexAI() && !("id" in functionResponse)) {
        throw new Error(FUNCTION_RESPONSE_REQUIRES_ID);
      }
    }
    const clientMessage = {
      toolResponse: { functionResponses }
    };
    return clientMessage;
  }
  /**
      Send a message over the established connection.
  
      @param params - Contains two **optional** properties, `turns` and
          `turnComplete`.
  
        - `turns` will be converted to a `Content[]`
        - `turnComplete: true` [default] indicates that you are done sending
          content and expect a response. If `turnComplete: false`, the server
          will wait for additional messages before starting generation.
  
      @experimental
  
      @remarks
      There are two ways to send messages to the live API:
      `sendClientContent` and `sendRealtimeInput`.
  
      `sendClientContent` messages are added to the model context **in order**.
      Having a conversation using `sendClientContent` messages is roughly
      equivalent to using the `Chat.sendMessageStream`, except that the state of
      the `chat` history is stored on the API server instead of locally.
  
      Because of `sendClientContent`'s order guarantee, the model cannot respons
      as quickly to `sendClientContent` messages as to `sendRealtimeInput`
      messages. This makes the biggest difference when sending objects that have
      significant preprocessing time (typically images).
  
      The `sendClientContent` message sends a `Content[]`
      which has more options than the `Blob` sent by `sendRealtimeInput`.
  
      So the main use-cases for `sendClientContent` over `sendRealtimeInput` are:
  
      - Sending anything that can't be represented as a `Blob` (text,
      `sendClientContent({turns="Hello?"}`)).
      - Managing turns when not using audio input and voice activity detection.
        (`sendClientContent({turnComplete:true})` or the short form
      `sendClientContent()`)
      - Prefilling a conversation context
        ```
        sendClientContent({
            turns: [
              Content({role:user, parts:...}),
              Content({role:user, parts:...}),
              ...
            ]
        })
        ```
      @experimental
     */
  sendClientContent(params) {
    params = Object.assign(Object.assign({}, defaultLiveSendClientContentParamerters), params);
    const clientMessage = this.tLiveClientContent(this.apiClient, params);
    this.conn.send(JSON.stringify(clientMessage));
  }
  /**
      Send a realtime message over the established connection.
  
      @param params - Contains one property, `media`.
  
        - `media` will be converted to a `Blob`
  
      @experimental
  
      @remarks
      Use `sendRealtimeInput` for realtime audio chunks and video frames (images).
  
      With `sendRealtimeInput` the api will respond to audio automatically
      based on voice activity detection (VAD).
  
      `sendRealtimeInput` is optimized for responsivness at the expense of
      deterministic ordering guarantees. Audio and video tokens are to the
      context when they become available.
  
      Note: The Call signature expects a `Blob` object, but only a subset
      of audio and image mimetypes are allowed.
     */
  sendRealtimeInput(params) {
    let clientMessage = {};
    if (this.apiClient.isVertexAI()) {
      clientMessage = {
        "realtimeInput": liveSendRealtimeInputParametersToVertex(params)
      };
    } else {
      clientMessage = {
        "realtimeInput": liveSendRealtimeInputParametersToMldev(params)
      };
    }
    this.conn.send(JSON.stringify(clientMessage));
  }
  /**
      Send a function response message over the established connection.
  
      @param params - Contains property `functionResponses`.
  
        - `functionResponses` will be converted to a `functionResponses[]`
  
      @remarks
      Use `sendFunctionResponse` to reply to `LiveServerToolCall` from the server.
  
      Use {@link types.LiveConnectConfig#tools} to configure the callable functions.
  
      @experimental
     */
  sendToolResponse(params) {
    if (params.functionResponses == null) {
      throw new Error("Tool response parameters are required.");
    }
    const clientMessage = this.tLiveClienttToolResponse(this.apiClient, params);
    this.conn.send(JSON.stringify(clientMessage));
  }
  /**
       Terminates the WebSocket connection.
  
       @experimental
  
       @example
       ```ts
       let model: string;
       if (GOOGLE_GENAI_USE_VERTEXAI) {
         model = 'gemini-2.0-flash-live-preview-04-09';
       } else {
         model = 'gemini-live-2.5-flash-preview';
       }
       const session = await ai.live.connect({
         model: model,
         config: {
           responseModalities: [Modality.AUDIO],
         }
       });
  
       session.close();
       ```
     */
  close() {
    this.conn.close();
  }
};
function headersToMap(headers) {
  const headerMap = {};
  headers.forEach((value, key) => {
    headerMap[key] = value;
  });
  return headerMap;
}
function mapToHeaders(map) {
  const headers = new Headers();
  for (const [key, value] of Object.entries(map)) {
    headers.append(key, value);
  }
  return headers;
}
var DEFAULT_MAX_REMOTE_CALLS = 10;
function shouldDisableAfc(config) {
  var _a7, _b, _c;
  if ((_a7 = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _a7 === void 0 ? void 0 : _a7.disable) {
    return true;
  }
  let callableToolsPresent = false;
  for (const tool of (_b = config === null || config === void 0 ? void 0 : config.tools) !== null && _b !== void 0 ? _b : []) {
    if (isCallableTool(tool)) {
      callableToolsPresent = true;
      break;
    }
  }
  if (!callableToolsPresent) {
    return true;
  }
  const maxCalls = (_c = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _c === void 0 ? void 0 : _c.maximumRemoteCalls;
  if (maxCalls && (maxCalls < 0 || !Number.isInteger(maxCalls)) || maxCalls == 0) {
    console.warn("Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:", maxCalls);
    return true;
  }
  return false;
}
function isCallableTool(tool) {
  return "callTool" in tool && typeof tool.callTool === "function";
}
function hasCallableTools(params) {
  var _a7, _b, _c;
  return (_c = (_b = (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.tools) === null || _b === void 0 ? void 0 : _b.some((tool) => isCallableTool(tool))) !== null && _c !== void 0 ? _c : false;
}
function findAfcIncompatibleToolIndexes(params) {
  var _a7;
  const afcIncompatibleToolIndexes = [];
  if (!((_a7 = params === null || params === void 0 ? void 0 : params.config) === null || _a7 === void 0 ? void 0 : _a7.tools)) {
    return afcIncompatibleToolIndexes;
  }
  params.config.tools.forEach((tool, index) => {
    if (isCallableTool(tool)) {
      return;
    }
    const geminiTool = tool;
    if (geminiTool.functionDeclarations && geminiTool.functionDeclarations.length > 0) {
      afcIncompatibleToolIndexes.push(index);
    }
  });
  return afcIncompatibleToolIndexes;
}
function shouldAppendAfcHistory(config) {
  var _a7;
  return !((_a7 = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _a7 === void 0 ? void 0 : _a7.ignoreCallHistory);
}
var Models4 = class extends BaseModule {
  constructor(apiClient) {
    super();
    this.apiClient = apiClient;
    this.embedContent = async (params) => {
      if (!this.apiClient.isVertexAI()) {
        return await this.embedContentInternal(params);
      }
      const isVertexEmbedContentModel = params.model.includes("gemini") && params.model !== "gemini-embedding-001" || params.model.includes("maas");
      if (isVertexEmbedContentModel) {
        const contents = tContents(params.contents);
        if (contents.length > 1) {
          throw new Error("The embedContent API for this model only supports one content at a time.");
        }
        const paramsPrivate = Object.assign(Object.assign({}, params), { content: contents[0], embeddingApiType: EmbeddingApiType.EMBED_CONTENT });
        return await this.embedContentInternal(paramsPrivate);
      } else {
        const paramsPrivate = Object.assign(Object.assign({}, params), { embeddingApiType: EmbeddingApiType.PREDICT });
        return await this.embedContentInternal(paramsPrivate);
      }
    };
    this.generateContent = async (params) => {
      var _a7, _b, _c, _d, _e2;
      const transformedParams = await this.processParamsMaybeAddMcpUsage(params);
      this.maybeMoveToResponseJsonSchem(params);
      if (!hasCallableTools(params) || shouldDisableAfc(params.config)) {
        return await this.generateContentInternal(transformedParams);
      }
      const incompatibleToolIndexes = findAfcIncompatibleToolIndexes(params);
      if (incompatibleToolIndexes.length > 0) {
        const formattedIndexes = incompatibleToolIndexes.map((index) => `tools[${index}]`).join(", ");
        throw new Error(`Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations is not yet supported. Incompatible tools found at ${formattedIndexes}.`);
      }
      let response;
      let functionResponseContent;
      const automaticFunctionCallingHistory = tContents(transformedParams.contents);
      const maxRemoteCalls = (_c = (_b = (_a7 = transformedParams.config) === null || _a7 === void 0 ? void 0 : _a7.automaticFunctionCalling) === null || _b === void 0 ? void 0 : _b.maximumRemoteCalls) !== null && _c !== void 0 ? _c : DEFAULT_MAX_REMOTE_CALLS;
      let remoteCalls = 0;
      while (remoteCalls < maxRemoteCalls) {
        response = await this.generateContentInternal(transformedParams);
        if (!response.functionCalls || response.functionCalls.length === 0) {
          break;
        }
        const responseContent = response.candidates[0].content;
        const functionResponseParts = [];
        for (const tool of (_e2 = (_d = params.config) === null || _d === void 0 ? void 0 : _d.tools) !== null && _e2 !== void 0 ? _e2 : []) {
          if (isCallableTool(tool)) {
            const callableTool = tool;
            const parts = await callableTool.callTool(response.functionCalls);
            functionResponseParts.push(...parts);
          }
        }
        remoteCalls++;
        functionResponseContent = {
          role: "user",
          parts: functionResponseParts
        };
        transformedParams.contents = tContents(transformedParams.contents);
        transformedParams.contents.push(responseContent);
        transformedParams.contents.push(functionResponseContent);
        if (shouldAppendAfcHistory(transformedParams.config)) {
          automaticFunctionCallingHistory.push(responseContent);
          automaticFunctionCallingHistory.push(functionResponseContent);
        }
      }
      if (shouldAppendAfcHistory(transformedParams.config)) {
        response.automaticFunctionCallingHistory = automaticFunctionCallingHistory;
      }
      return response;
    };
    this.generateContentStream = async (params) => {
      var _a7, _b, _c, _d, _e2;
      this.maybeMoveToResponseJsonSchem(params);
      if (shouldDisableAfc(params.config)) {
        const transformedParams = await this.processParamsMaybeAddMcpUsage(params);
        return await this.generateContentStreamInternal(transformedParams);
      }
      const incompatibleToolIndexes = findAfcIncompatibleToolIndexes(params);
      if (incompatibleToolIndexes.length > 0) {
        const formattedIndexes = incompatibleToolIndexes.map((index) => `tools[${index}]`).join(", ");
        throw new Error(`Incompatible tools found at ${formattedIndexes}. Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations" is not yet supported.`);
      }
      const streamFunctionCall = (_c = (_b = (_a7 = params === null || params === void 0 ? void 0 : params.config) === null || _a7 === void 0 ? void 0 : _a7.toolConfig) === null || _b === void 0 ? void 0 : _b.functionCallingConfig) === null || _c === void 0 ? void 0 : _c.streamFunctionCallArguments;
      const disableAfc = (_e2 = (_d = params === null || params === void 0 ? void 0 : params.config) === null || _d === void 0 ? void 0 : _d.automaticFunctionCalling) === null || _e2 === void 0 ? void 0 : _e2.disable;
      if (streamFunctionCall && !disableAfc) {
        throw new Error("Running in streaming mode with 'streamFunctionCallArguments' enabled, this feature is not compatible with automatic function calling (AFC). Please set 'config.automaticFunctionCalling.disable' to true to disable AFC or leave 'config.toolConfig.functionCallingConfig.streamFunctionCallArguments' to be undefined or set to false to disable streaming function call arguments feature.");
      }
      return await this.processAfcStream(params);
    };
    this.generateImages = async (params) => {
      return await this.generateImagesInternal(params).then((apiResponse) => {
        var _a7;
        let positivePromptSafetyAttributes;
        const generatedImages = [];
        if (apiResponse === null || apiResponse === void 0 ? void 0 : apiResponse.generatedImages) {
          for (const generatedImage of apiResponse.generatedImages) {
            if (generatedImage && (generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes) && ((_a7 = generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes) === null || _a7 === void 0 ? void 0 : _a7.contentType) === "Positive Prompt") {
              positivePromptSafetyAttributes = generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes;
            } else {
              generatedImages.push(generatedImage);
            }
          }
        }
        let response;
        if (positivePromptSafetyAttributes) {
          response = {
            generatedImages,
            positivePromptSafetyAttributes,
            sdkHttpResponse: apiResponse.sdkHttpResponse
          };
        } else {
          response = {
            generatedImages,
            sdkHttpResponse: apiResponse.sdkHttpResponse
          };
        }
        return response;
      });
    };
    this.list = async (params) => {
      var _a7;
      const defaultConfig = {
        queryBase: true
      };
      const actualConfig = Object.assign(Object.assign({}, defaultConfig), params === null || params === void 0 ? void 0 : params.config);
      const actualParams = {
        config: actualConfig
      };
      if (this.apiClient.isVertexAI()) {
        if (!actualParams.config.queryBase) {
          if ((_a7 = actualParams.config) === null || _a7 === void 0 ? void 0 : _a7.filter) {
            throw new Error("Filtering tuned models list for Vertex AI is not currently supported");
          } else {
            actualParams.config.filter = "labels.tune-type:*";
          }
        }
      }
      return new Pager(PagedItem.PAGED_ITEM_MODELS, (x2) => this.listInternal(x2), await this.listInternal(actualParams), actualParams);
    };
    this.editImage = async (params) => {
      const paramsInternal = {
        model: params.model,
        prompt: params.prompt,
        referenceImages: [],
        config: params.config
      };
      if (params.referenceImages) {
        if (params.referenceImages) {
          paramsInternal.referenceImages = params.referenceImages.map((img) => img.toReferenceImageAPI());
        }
      }
      return await this.editImageInternal(paramsInternal);
    };
    this.upscaleImage = async (params) => {
      let apiConfig = {
        numberOfImages: 1,
        mode: "upscale"
      };
      if (params.config) {
        apiConfig = Object.assign(Object.assign({}, apiConfig), params.config);
      }
      const apiParams = {
        model: params.model,
        image: params.image,
        upscaleFactor: params.upscaleFactor,
        config: apiConfig
      };
      return await this.upscaleImageInternal(apiParams);
    };
    this.generateVideos = async (params) => {
      var _a7, _b, _c, _d, _e2, _f;
      if ((params.prompt || params.image || params.video) && params.source) {
        throw new Error("Source and prompt/image/video are mutually exclusive. Please only use source.");
      }
      if (!this.apiClient.isVertexAI()) {
        if (((_a7 = params.video) === null || _a7 === void 0 ? void 0 : _a7.uri) && ((_b = params.video) === null || _b === void 0 ? void 0 : _b.videoBytes)) {
          params.video = {
            uri: params.video.uri,
            mimeType: params.video.mimeType
          };
        } else if (((_d = (_c = params.source) === null || _c === void 0 ? void 0 : _c.video) === null || _d === void 0 ? void 0 : _d.uri) && ((_f = (_e2 = params.source) === null || _e2 === void 0 ? void 0 : _e2.video) === null || _f === void 0 ? void 0 : _f.videoBytes)) {
          params.source.video = {
            uri: params.source.video.uri,
            mimeType: params.source.video.mimeType
          };
        }
      }
      return await this.generateVideosInternal(params);
    };
  }
  /**
   * This logic is needed for GenerateContentConfig only.
   * Previously we made GenerateContentConfig.responseSchema field to accept
   * unknown. Since v1.9.0, we switch to use backend JSON schema support.
   * To maintain backward compatibility, we move the data that was treated as
   * JSON schema from the responseSchema field to the responseJsonSchema field.
   */
  maybeMoveToResponseJsonSchem(params) {
    if (params.config && params.config.responseSchema) {
      if (!params.config.responseJsonSchema) {
        if (Object.keys(params.config.responseSchema).includes("$schema")) {
          params.config.responseJsonSchema = params.config.responseSchema;
          delete params.config.responseSchema;
        }
      }
    }
    return;
  }
  /**
   * Transforms the CallableTools in the parameters to be simply Tools, it
   * copies the params into a new object and replaces the tools, it does not
   * modify the original params. Also sets the MCP usage header if there are
   * MCP tools in the parameters.
   */
  async processParamsMaybeAddMcpUsage(params) {
    var _a7, _b, _c;
    const tools = (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.tools;
    if (!tools) {
      return params;
    }
    const transformedTools = await Promise.all(tools.map(async (tool) => {
      if (isCallableTool(tool)) {
        const callableTool = tool;
        return await callableTool.tool();
      }
      return tool;
    }));
    const newParams = {
      model: params.model,
      contents: params.contents,
      config: Object.assign(Object.assign({}, params.config), { tools: transformedTools })
    };
    newParams.config.tools = transformedTools;
    if (params.config && params.config.tools && hasMcpToolUsage(params.config.tools)) {
      const headers = (_c = (_b = params.config.httpOptions) === null || _b === void 0 ? void 0 : _b.headers) !== null && _c !== void 0 ? _c : {};
      let newHeaders = Object.assign({}, headers);
      if (Object.keys(newHeaders).length === 0) {
        newHeaders = this.apiClient.getDefaultHeaders();
      }
      setMcpUsageHeader(newHeaders);
      newParams.config.httpOptions = Object.assign(Object.assign({}, params.config.httpOptions), { headers: newHeaders });
    }
    return newParams;
  }
  async initAfcToolsMap(params) {
    var _a7, _b, _c;
    const afcTools = /* @__PURE__ */ new Map();
    for (const tool of (_b = (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.tools) !== null && _b !== void 0 ? _b : []) {
      if (isCallableTool(tool)) {
        const callableTool = tool;
        const toolDeclaration = await callableTool.tool();
        for (const declaration of (_c = toolDeclaration.functionDeclarations) !== null && _c !== void 0 ? _c : []) {
          if (!declaration.name) {
            throw new Error("Function declaration name is required.");
          }
          if (afcTools.has(declaration.name)) {
            throw new Error(`Duplicate tool declaration name: ${declaration.name}`);
          }
          afcTools.set(declaration.name, callableTool);
        }
      }
    }
    return afcTools;
  }
  async processAfcStream(params) {
    var _a7, _b, _c;
    const maxRemoteCalls = (_c = (_b = (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.automaticFunctionCalling) === null || _b === void 0 ? void 0 : _b.maximumRemoteCalls) !== null && _c !== void 0 ? _c : DEFAULT_MAX_REMOTE_CALLS;
    let wereFunctionsCalled = false;
    let remoteCallCount = 0;
    const afcToolsMap = await this.initAfcToolsMap(params);
    return (function(models2, afcTools, params2) {
      return __asyncGenerator(this, arguments, function* () {
        var _a8, e_1, _b2, _c2;
        var _d, _e2;
        while (remoteCallCount < maxRemoteCalls) {
          if (wereFunctionsCalled) {
            remoteCallCount++;
            wereFunctionsCalled = false;
          }
          const transformedParams = yield __await(models2.processParamsMaybeAddMcpUsage(params2));
          const response = yield __await(models2.generateContentStreamInternal(transformedParams));
          const functionResponses = [];
          const responseContents = [];
          try {
            for (var _f = true, response_1 = (e_1 = void 0, __asyncValues(response)), response_1_1; response_1_1 = yield __await(response_1.next()), _a8 = response_1_1.done, !_a8; _f = true) {
              _c2 = response_1_1.value;
              _f = false;
              const chunk = _c2;
              yield yield __await(chunk);
              if (chunk.candidates && ((_d = chunk.candidates[0]) === null || _d === void 0 ? void 0 : _d.content)) {
                responseContents.push(chunk.candidates[0].content);
                for (const part of (_e2 = chunk.candidates[0].content.parts) !== null && _e2 !== void 0 ? _e2 : []) {
                  if (remoteCallCount < maxRemoteCalls && part.functionCall) {
                    if (!part.functionCall.name) {
                      throw new Error("Function call name was not returned by the model.");
                    }
                    if (!afcTools.has(part.functionCall.name)) {
                      throw new Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${afcTools.keys()}, mising tool: ${part.functionCall.name}`);
                    } else {
                      const responseParts = yield __await(afcTools.get(part.functionCall.name).callTool([part.functionCall]));
                      functionResponses.push(...responseParts);
                    }
                  }
                }
              }
            }
          } catch (e_1_1) {
            e_1 = { error: e_1_1 };
          } finally {
            try {
              if (!_f && !_a8 && (_b2 = response_1.return)) yield __await(_b2.call(response_1));
            } finally {
              if (e_1) throw e_1.error;
            }
          }
          if (functionResponses.length > 0) {
            wereFunctionsCalled = true;
            const typedResponseChunk = new GenerateContentResponse();
            typedResponseChunk.candidates = [
              {
                content: {
                  role: "user",
                  parts: functionResponses
                }
              }
            ];
            yield yield __await(typedResponseChunk);
            const newContents = [];
            newContents.push(...responseContents);
            newContents.push({
              role: "user",
              parts: functionResponses
            });
            const updatedContents = tContents(params2.contents).concat(newContents);
            params2.contents = updatedContents;
          } else {
            break;
          }
        }
      });
    })(this, afcToolsMap, params);
  }
  async generateContentInternal(params) {
    var _a7, _b, _c, _d;
    let response;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = generateContentParametersToVertex(this.apiClient, params);
      path6 = formatMap("{model}:generateContent", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = generateContentResponseFromVertex(apiResponse);
        const typedResp = new GenerateContentResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    } else {
      const body = generateContentParametersToMldev(this.apiClient, params);
      path6 = formatMap("{model}:generateContent", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,
        abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = generateContentResponseFromMldev(apiResponse);
        const typedResp = new GenerateContentResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    }
  }
  async generateContentStreamInternal(params) {
    var _a7, _b, _c, _d;
    let response;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = generateContentParametersToVertex(this.apiClient, params);
      path6 = formatMap("{model}:streamGenerateContent?alt=sse", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      const apiClient = this.apiClient;
      response = apiClient.requestStream({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      });
      return response.then(function(apiResponse) {
        return __asyncGenerator(this, arguments, function* () {
          var _a8, e_2, _b2, _c2;
          try {
            for (var _d2 = true, apiResponse_1 = __asyncValues(apiResponse), apiResponse_1_1; apiResponse_1_1 = yield __await(apiResponse_1.next()), _a8 = apiResponse_1_1.done, !_a8; _d2 = true) {
              _c2 = apiResponse_1_1.value;
              _d2 = false;
              const chunk = _c2;
              const resp = generateContentResponseFromVertex(yield __await(chunk.json()), params);
              resp["sdkHttpResponse"] = {
                headers: chunk.headers
              };
              const typedResp = new GenerateContentResponse();
              Object.assign(typedResp, resp);
              yield yield __await(typedResp);
            }
          } catch (e_2_1) {
            e_2 = { error: e_2_1 };
          } finally {
            try {
              if (!_d2 && !_a8 && (_b2 = apiResponse_1.return)) yield __await(_b2.call(apiResponse_1));
            } finally {
              if (e_2) throw e_2.error;
            }
          }
        });
      });
    } else {
      const body = generateContentParametersToMldev(this.apiClient, params);
      path6 = formatMap("{model}:streamGenerateContent?alt=sse", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      const apiClient = this.apiClient;
      response = apiClient.requestStream({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,
        abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
      });
      return response.then(function(apiResponse) {
        return __asyncGenerator(this, arguments, function* () {
          var _a8, e_3, _b2, _c2;
          try {
            for (var _d2 = true, apiResponse_2 = __asyncValues(apiResponse), apiResponse_2_1; apiResponse_2_1 = yield __await(apiResponse_2.next()), _a8 = apiResponse_2_1.done, !_a8; _d2 = true) {
              _c2 = apiResponse_2_1.value;
              _d2 = false;
              const chunk = _c2;
              const resp = generateContentResponseFromMldev(yield __await(chunk.json()), params);
              resp["sdkHttpResponse"] = {
                headers: chunk.headers
              };
              const typedResp = new GenerateContentResponse();
              Object.assign(typedResp, resp);
              yield yield __await(typedResp);
            }
          } catch (e_3_1) {
            e_3 = { error: e_3_1 };
          } finally {
            try {
              if (!_d2 && !_a8 && (_b2 = apiResponse_2.return)) yield __await(_b2.call(apiResponse_2));
            } finally {
              if (e_3) throw e_3.error;
            }
          }
        });
      });
    }
  }
  /**
   * Calculates embeddings for the given contents. Only text is supported.
   *
   * @param params - The parameters for embedding contents.
   * @return The response from the API.
   *
   * @example
   * ```ts
   * const response = await ai.models.embedContent({
   *  model: 'text-embedding-004',
   *  contents: [
   *    'What is your name?',
   *    'What is your favorite color?',
   *  ],
   *  config: {
   *    outputDimensionality: 64,
   *  },
   * });
   * console.log(response);
   * ```
   */
  async embedContentInternal(params) {
    var _a7, _b, _c, _d;
    let response;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = embedContentParametersPrivateToVertex(this.apiClient, params, params);
      const endpointUrl = tIsVertexEmbedContentModel(params.model) ? "{model}:embedContent" : "{model}:predict";
      path6 = formatMap(endpointUrl, body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = embedContentResponseFromVertex(apiResponse, params);
        const typedResp = new EmbedContentResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    } else {
      const body = embedContentParametersPrivateToMldev(this.apiClient, params);
      path6 = formatMap("{model}:batchEmbedContents", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,
        abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = embedContentResponseFromMldev(apiResponse);
        const typedResp = new EmbedContentResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    }
  }
  /**
   * Private method for generating images.
   */
  async generateImagesInternal(params) {
    var _a7, _b, _c, _d;
    let response;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = generateImagesParametersToVertex(this.apiClient, params);
      path6 = formatMap("{model}:predict", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = generateImagesResponseFromVertex(apiResponse);
        const typedResp = new GenerateImagesResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    } else {
      const body = generateImagesParametersToMldev(this.apiClient, params);
      path6 = formatMap("{model}:predict", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,
        abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = generateImagesResponseFromMldev(apiResponse);
        const typedResp = new GenerateImagesResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    }
  }
  /**
   * Private method for editing an image.
   */
  async editImageInternal(params) {
    var _a7, _b;
    let response;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = editImageParametersInternalToVertex(this.apiClient, params);
      path6 = formatMap("{model}:predict", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = editImageResponseFromVertex(apiResponse);
        const typedResp = new EditImageResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    } else {
      throw new Error("This method is only supported by the Vertex AI.");
    }
  }
  /**
   * Private method for upscaling an image.
   */
  async upscaleImageInternal(params) {
    var _a7, _b;
    let response;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = upscaleImageAPIParametersInternalToVertex(this.apiClient, params);
      path6 = formatMap("{model}:predict", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = upscaleImageResponseFromVertex(apiResponse);
        const typedResp = new UpscaleImageResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    } else {
      throw new Error("This method is only supported by the Vertex AI.");
    }
  }
  /**
   * Recontextualizes an image.
   *
   * There are two types of recontextualization currently supported:
   * 1) Imagen Product Recontext - Generate images of products in new scenes
   *    and contexts.
   * 2) Virtual Try-On: Generate images of persons modeling fashion products.
   *
   * @param params - The parameters for recontextualizing an image.
   * @return The response from the API.
   *
   * @example
   * ```ts
   * const response1 = await ai.models.recontextImage({
   *  model: 'imagen-product-recontext-preview-06-30',
   *  source: {
   *    prompt: 'In a modern kitchen setting.',
   *    productImages: [productImage],
   *  },
   *  config: {
   *    numberOfImages: 1,
   *  },
   * });
   * console.log(response1?.generatedImages?.[0]?.image?.imageBytes);
   *
   * const response2 = await ai.models.recontextImage({
   *  model: 'virtual-try-on-001',
   *  source: {
   *    personImage: personImage,
   *    productImages: [productImage],
   *  },
   *  config: {
   *    numberOfImages: 1,
   *  },
   * });
   * console.log(response2?.generatedImages?.[0]?.image?.imageBytes);
   * ```
   */
  async recontextImage(params) {
    var _a7, _b;
    let response;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = recontextImageParametersToVertex(this.apiClient, params);
      path6 = formatMap("{model}:predict", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((apiResponse) => {
        const resp = recontextImageResponseFromVertex(apiResponse);
        const typedResp = new RecontextImageResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    } else {
      throw new Error("This method is only supported by the Vertex AI.");
    }
  }
  /**
   * Segments an image, creating a mask of a specified area.
   *
   * @param params - The parameters for segmenting an image.
   * @return The response from the API.
   *
   * @example
   * ```ts
   * const response = await ai.models.segmentImage({
   *  model: 'image-segmentation-001',
   *  source: {
   *    image: image,
   *  },
   *  config: {
   *    mode: 'foreground',
   *  },
   * });
   * console.log(response?.generatedMasks?.[0]?.mask?.imageBytes);
   * ```
   */
  async segmentImage(params) {
    var _a7, _b;
    let response;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = segmentImageParametersToVertex(this.apiClient, params);
      path6 = formatMap("{model}:predict", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((apiResponse) => {
        const resp = segmentImageResponseFromVertex(apiResponse);
        const typedResp = new SegmentImageResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    } else {
      throw new Error("This method is only supported by the Vertex AI.");
    }
  }
  /**
   * Fetches information about a model by name.
   *
   * @example
   * ```ts
   * const modelInfo = await ai.models.get({model: 'gemini-2.0-flash'});
   * ```
   */
  async get(params) {
    var _a7, _b, _c, _d;
    let response;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = getModelParametersToVertex(this.apiClient, params);
      path6 = formatMap("{name}", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "GET",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((apiResponse) => {
        const resp = modelFromVertex(apiResponse);
        return resp;
      });
    } else {
      const body = getModelParametersToMldev(this.apiClient, params);
      path6 = formatMap("{name}", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "GET",
        httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,
        abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((apiResponse) => {
        const resp = modelFromMldev(apiResponse);
        return resp;
      });
    }
  }
  async listInternal(params) {
    var _a7, _b, _c, _d;
    let response;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = listModelsParametersToVertex(this.apiClient, params);
      path6 = formatMap("{models_url}", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "GET",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = listModelsResponseFromVertex(apiResponse);
        const typedResp = new ListModelsResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    } else {
      const body = listModelsParametersToMldev(this.apiClient, params);
      path6 = formatMap("{models_url}", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "GET",
        httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,
        abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = listModelsResponseFromMldev(apiResponse);
        const typedResp = new ListModelsResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    }
  }
  /**
   * Updates a tuned model by its name.
   *
   * @param params - The parameters for updating the model.
   * @return The response from the API.
   *
   * @example
   * ```ts
   * const response = await ai.models.update({
   *   model: 'tuned-model-name',
   *   config: {
   *     displayName: 'New display name',
   *     description: 'New description',
   *   },
   * });
   * ```
   */
  async update(params) {
    var _a7, _b, _c, _d;
    let response;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = updateModelParametersToVertex(this.apiClient, params);
      path6 = formatMap("{model}", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "PATCH",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((apiResponse) => {
        const resp = modelFromVertex(apiResponse);
        return resp;
      });
    } else {
      const body = updateModelParametersToMldev(this.apiClient, params);
      path6 = formatMap("{name}", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "PATCH",
        httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,
        abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((apiResponse) => {
        const resp = modelFromMldev(apiResponse);
        return resp;
      });
    }
  }
  /**
   * Deletes a tuned model by its name.
   *
   * @param params - The parameters for deleting the model.
   * @return The response from the API.
   *
   * @example
   * ```ts
   * const response = await ai.models.delete({model: 'tuned-model-name'});
   * ```
   */
  async delete(params) {
    var _a7, _b, _c, _d;
    let response;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = deleteModelParametersToVertex(this.apiClient, params);
      path6 = formatMap("{name}", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "DELETE",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = deleteModelResponseFromVertex(apiResponse);
        const typedResp = new DeleteModelResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    } else {
      const body = deleteModelParametersToMldev(this.apiClient, params);
      path6 = formatMap("{name}", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "DELETE",
        httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,
        abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = deleteModelResponseFromMldev(apiResponse);
        const typedResp = new DeleteModelResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    }
  }
  /**
   * Counts the number of tokens in the given contents. Multimodal input is
   * supported for Gemini models.
   *
   * @param params - The parameters for counting tokens.
   * @return The response from the API.
   *
   * @example
   * ```ts
   * const response = await ai.models.countTokens({
   *  model: 'gemini-2.0-flash',
   *  contents: 'The quick brown fox jumps over the lazy dog.'
   * });
   * console.log(response);
   * ```
   */
  async countTokens(params) {
    var _a7, _b, _c, _d;
    let response;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = countTokensParametersToVertex(this.apiClient, params);
      path6 = formatMap("{model}:countTokens", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = countTokensResponseFromVertex(apiResponse);
        const typedResp = new CountTokensResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    } else {
      const body = countTokensParametersToMldev(this.apiClient, params);
      path6 = formatMap("{model}:countTokens", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,
        abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = countTokensResponseFromMldev(apiResponse);
        const typedResp = new CountTokensResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    }
  }
  /**
   * Given a list of contents, returns a corresponding TokensInfo containing
   * the list of tokens and list of token ids.
   *
   * This method is not supported by the Gemini Developer API.
   *
   * @param params - The parameters for computing tokens.
   * @return The response from the API.
   *
   * @example
   * ```ts
   * const response = await ai.models.computeTokens({
   *  model: 'gemini-2.0-flash',
   *  contents: 'What is your name?'
   * });
   * console.log(response);
   * ```
   */
  async computeTokens(params) {
    var _a7, _b;
    let response;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = computeTokensParametersToVertex(this.apiClient, params);
      path6 = formatMap("{model}:computeTokens", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = computeTokensResponseFromVertex(apiResponse);
        const typedResp = new ComputeTokensResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    } else {
      throw new Error("This method is only supported by the Vertex AI.");
    }
  }
  /**
   * Private method for generating videos.
   */
  async generateVideosInternal(params) {
    var _a7, _b, _c, _d;
    let response;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = generateVideosParametersToVertex(this.apiClient, params);
      path6 = formatMap("{model}:predictLongRunning", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((apiResponse) => {
        const resp = generateVideosOperationFromVertex(apiResponse);
        const typedResp = new GenerateVideosOperation();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    } else {
      const body = generateVideosParametersToMldev(this.apiClient, params);
      path6 = formatMap("{model}:predictLongRunning", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,
        abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((apiResponse) => {
        const resp = generateVideosOperationFromMldev(apiResponse);
        const typedResp = new GenerateVideosOperation();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    }
  }
};
var Operations = class extends BaseModule {
  constructor(apiClient) {
    super();
    this.apiClient = apiClient;
  }
  /**
   * Gets the status of a long-running operation.
   *
   * @param parameters The parameters for the get operation request.
   * @return The updated Operation object, with the latest status or result.
   */
  async getVideosOperation(parameters) {
    const operation = parameters.operation;
    const config = parameters.config;
    if (operation.name === void 0 || operation.name === "") {
      throw new Error("Operation name is required.");
    }
    if (this.apiClient.isVertexAI()) {
      const resourceName2 = operation.name.split("/operations/")[0];
      let httpOptions = void 0;
      if (config && "httpOptions" in config) {
        httpOptions = config.httpOptions;
      }
      const rawOperation = await this.fetchPredictVideosOperationInternal({
        operationName: operation.name,
        resourceName: resourceName2,
        config: { httpOptions }
      });
      return operation._fromAPIResponse({
        apiResponse: rawOperation,
        _isVertexAI: true
      });
    } else {
      const rawOperation = await this.getVideosOperationInternal({
        operationName: operation.name,
        config
      });
      return operation._fromAPIResponse({
        apiResponse: rawOperation,
        _isVertexAI: false
      });
    }
  }
  /**
   * Gets the status of a long-running operation.
   *
   * @param parameters The parameters for the get operation request.
   * @return The updated Operation object, with the latest status or result.
   */
  async get(parameters) {
    const operation = parameters.operation;
    const config = parameters.config;
    if (operation.name === void 0 || operation.name === "") {
      throw new Error("Operation name is required.");
    }
    if (this.apiClient.isVertexAI()) {
      const resourceName2 = operation.name.split("/operations/")[0];
      let httpOptions = void 0;
      if (config && "httpOptions" in config) {
        httpOptions = config.httpOptions;
      }
      const rawOperation = await this.fetchPredictVideosOperationInternal({
        operationName: operation.name,
        resourceName: resourceName2,
        config: { httpOptions }
      });
      return operation._fromAPIResponse({
        apiResponse: rawOperation,
        _isVertexAI: true
      });
    } else {
      const rawOperation = await this.getVideosOperationInternal({
        operationName: operation.name,
        config
      });
      return operation._fromAPIResponse({
        apiResponse: rawOperation,
        _isVertexAI: false
      });
    }
  }
  async getVideosOperationInternal(params) {
    var _a7, _b, _c, _d;
    let response;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = getOperationParametersToVertex(params);
      path6 = formatMap("{operationName}", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "GET",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response;
    } else {
      const body = getOperationParametersToMldev(params);
      path6 = formatMap("{operationName}", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "GET",
        httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,
        abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response;
    }
  }
  async fetchPredictVideosOperationInternal(params) {
    var _a7, _b;
    let response;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = fetchPredictOperationParametersToVertex(params);
      path6 = formatMap("{resourceName}:fetchPredictOperation", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response;
    } else {
      throw new Error("This method is only supported by the Vertex AI.");
    }
  }
};
function audioTranscriptionConfigToMldev(fromObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["languageCodes"]) !== void 0) {
    throw new Error("languageCodes parameter is not supported in Gemini API.");
  }
  return toObject;
}
function authConfigToMldev(fromObject) {
  const toObject = {};
  const fromApiKey = getValueByPath(fromObject, ["apiKey"]);
  if (fromApiKey != null) {
    setValueByPath(toObject, ["apiKey"], fromApiKey);
  }
  if (getValueByPath(fromObject, ["apiKeyConfig"]) !== void 0) {
    throw new Error("apiKeyConfig parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["authType"]) !== void 0) {
    throw new Error("authType parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["googleServiceAccountConfig"]) !== void 0) {
    throw new Error("googleServiceAccountConfig parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["httpBasicAuthConfig"]) !== void 0) {
    throw new Error("httpBasicAuthConfig parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["oauthConfig"]) !== void 0) {
    throw new Error("oauthConfig parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["oidcConfig"]) !== void 0) {
    throw new Error("oidcConfig parameter is not supported in Gemini API.");
  }
  return toObject;
}
function blobToMldev(fromObject) {
  const toObject = {};
  const fromData = getValueByPath(fromObject, ["data"]);
  if (fromData != null) {
    setValueByPath(toObject, ["data"], fromData);
  }
  if (getValueByPath(fromObject, ["displayName"]) !== void 0) {
    throw new Error("displayName parameter is not supported in Gemini API.");
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function contentToMldev(fromObject) {
  const toObject = {};
  const fromParts = getValueByPath(fromObject, ["parts"]);
  if (fromParts != null) {
    let transformedList = fromParts;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return partToMldev(item);
      });
    }
    setValueByPath(toObject, ["parts"], transformedList);
  }
  const fromRole = getValueByPath(fromObject, ["role"]);
  if (fromRole != null) {
    setValueByPath(toObject, ["role"], fromRole);
  }
  return toObject;
}
function createAuthTokenConfigToMldev(apiClient, fromObject, parentObject) {
  const toObject = {};
  const fromExpireTime = getValueByPath(fromObject, ["expireTime"]);
  if (parentObject !== void 0 && fromExpireTime != null) {
    setValueByPath(parentObject, ["expireTime"], fromExpireTime);
  }
  const fromNewSessionExpireTime = getValueByPath(fromObject, [
    "newSessionExpireTime"
  ]);
  if (parentObject !== void 0 && fromNewSessionExpireTime != null) {
    setValueByPath(parentObject, ["newSessionExpireTime"], fromNewSessionExpireTime);
  }
  const fromUses = getValueByPath(fromObject, ["uses"]);
  if (parentObject !== void 0 && fromUses != null) {
    setValueByPath(parentObject, ["uses"], fromUses);
  }
  const fromLiveConnectConstraints = getValueByPath(fromObject, [
    "liveConnectConstraints"
  ]);
  if (parentObject !== void 0 && fromLiveConnectConstraints != null) {
    setValueByPath(parentObject, ["bidiGenerateContentSetup"], liveConnectConstraintsToMldev(apiClient, fromLiveConnectConstraints));
  }
  const fromLockAdditionalFields = getValueByPath(fromObject, [
    "lockAdditionalFields"
  ]);
  if (parentObject !== void 0 && fromLockAdditionalFields != null) {
    setValueByPath(parentObject, ["fieldMask"], fromLockAdditionalFields);
  }
  return toObject;
}
function createAuthTokenParametersToMldev(apiClient, fromObject) {
  const toObject = {};
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], createAuthTokenConfigToMldev(apiClient, fromConfig, toObject));
  }
  return toObject;
}
function fileDataToMldev(fromObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["displayName"]) !== void 0) {
    throw new Error("displayName parameter is not supported in Gemini API.");
  }
  const fromFileUri = getValueByPath(fromObject, ["fileUri"]);
  if (fromFileUri != null) {
    setValueByPath(toObject, ["fileUri"], fromFileUri);
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function functionCallToMldev(fromObject) {
  const toObject = {};
  const fromId = getValueByPath(fromObject, ["id"]);
  if (fromId != null) {
    setValueByPath(toObject, ["id"], fromId);
  }
  const fromArgs = getValueByPath(fromObject, ["args"]);
  if (fromArgs != null) {
    setValueByPath(toObject, ["args"], fromArgs);
  }
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  if (getValueByPath(fromObject, ["partialArgs"]) !== void 0) {
    throw new Error("partialArgs parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["willContinue"]) !== void 0) {
    throw new Error("willContinue parameter is not supported in Gemini API.");
  }
  return toObject;
}
function googleMapsToMldev(fromObject) {
  const toObject = {};
  const fromAuthConfig = getValueByPath(fromObject, ["authConfig"]);
  if (fromAuthConfig != null) {
    setValueByPath(toObject, ["authConfig"], authConfigToMldev(fromAuthConfig));
  }
  const fromEnableWidget = getValueByPath(fromObject, ["enableWidget"]);
  if (fromEnableWidget != null) {
    setValueByPath(toObject, ["enableWidget"], fromEnableWidget);
  }
  return toObject;
}
function googleSearchToMldev(fromObject) {
  const toObject = {};
  const fromSearchTypes = getValueByPath(fromObject, ["searchTypes"]);
  if (fromSearchTypes != null) {
    setValueByPath(toObject, ["searchTypes"], fromSearchTypes);
  }
  if (getValueByPath(fromObject, ["blockingConfidence"]) !== void 0) {
    throw new Error("blockingConfidence parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["excludeDomains"]) !== void 0) {
    throw new Error("excludeDomains parameter is not supported in Gemini API.");
  }
  const fromTimeRangeFilter = getValueByPath(fromObject, [
    "timeRangeFilter"
  ]);
  if (fromTimeRangeFilter != null) {
    setValueByPath(toObject, ["timeRangeFilter"], fromTimeRangeFilter);
  }
  return toObject;
}
function liveConnectConfigToMldev(fromObject, parentObject) {
  const toObject = {};
  const fromGenerationConfig = getValueByPath(fromObject, [
    "generationConfig"
  ]);
  if (parentObject !== void 0 && fromGenerationConfig != null) {
    setValueByPath(parentObject, ["setup", "generationConfig"], fromGenerationConfig);
  }
  const fromResponseModalities = getValueByPath(fromObject, [
    "responseModalities"
  ]);
  if (parentObject !== void 0 && fromResponseModalities != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "responseModalities"], fromResponseModalities);
  }
  const fromTemperature = getValueByPath(fromObject, ["temperature"]);
  if (parentObject !== void 0 && fromTemperature != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "temperature"], fromTemperature);
  }
  const fromTopP = getValueByPath(fromObject, ["topP"]);
  if (parentObject !== void 0 && fromTopP != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "topP"], fromTopP);
  }
  const fromTopK = getValueByPath(fromObject, ["topK"]);
  if (parentObject !== void 0 && fromTopK != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "topK"], fromTopK);
  }
  const fromMaxOutputTokens = getValueByPath(fromObject, [
    "maxOutputTokens"
  ]);
  if (parentObject !== void 0 && fromMaxOutputTokens != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "maxOutputTokens"], fromMaxOutputTokens);
  }
  const fromMediaResolution = getValueByPath(fromObject, [
    "mediaResolution"
  ]);
  if (parentObject !== void 0 && fromMediaResolution != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "mediaResolution"], fromMediaResolution);
  }
  const fromSeed = getValueByPath(fromObject, ["seed"]);
  if (parentObject !== void 0 && fromSeed != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "seed"], fromSeed);
  }
  const fromSpeechConfig = getValueByPath(fromObject, ["speechConfig"]);
  if (parentObject !== void 0 && fromSpeechConfig != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "speechConfig"], tLiveSpeechConfig(fromSpeechConfig));
  }
  const fromThinkingConfig = getValueByPath(fromObject, [
    "thinkingConfig"
  ]);
  if (parentObject !== void 0 && fromThinkingConfig != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "thinkingConfig"], fromThinkingConfig);
  }
  const fromEnableAffectiveDialog = getValueByPath(fromObject, [
    "enableAffectiveDialog"
  ]);
  if (parentObject !== void 0 && fromEnableAffectiveDialog != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "enableAffectiveDialog"], fromEnableAffectiveDialog);
  }
  const fromSystemInstruction = getValueByPath(fromObject, [
    "systemInstruction"
  ]);
  if (parentObject !== void 0 && fromSystemInstruction != null) {
    setValueByPath(parentObject, ["setup", "systemInstruction"], contentToMldev(tContent(fromSystemInstruction)));
  }
  const fromTools = getValueByPath(fromObject, ["tools"]);
  if (parentObject !== void 0 && fromTools != null) {
    let transformedList = tTools(fromTools);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return toolToMldev(tTool(item));
      });
    }
    setValueByPath(parentObject, ["setup", "tools"], transformedList);
  }
  const fromSessionResumption = getValueByPath(fromObject, [
    "sessionResumption"
  ]);
  if (parentObject !== void 0 && fromSessionResumption != null) {
    setValueByPath(parentObject, ["setup", "sessionResumption"], sessionResumptionConfigToMldev(fromSessionResumption));
  }
  const fromInputAudioTranscription = getValueByPath(fromObject, [
    "inputAudioTranscription"
  ]);
  if (parentObject !== void 0 && fromInputAudioTranscription != null) {
    setValueByPath(parentObject, ["setup", "inputAudioTranscription"], audioTranscriptionConfigToMldev(fromInputAudioTranscription));
  }
  const fromOutputAudioTranscription = getValueByPath(fromObject, [
    "outputAudioTranscription"
  ]);
  if (parentObject !== void 0 && fromOutputAudioTranscription != null) {
    setValueByPath(parentObject, ["setup", "outputAudioTranscription"], audioTranscriptionConfigToMldev(fromOutputAudioTranscription));
  }
  const fromRealtimeInputConfig = getValueByPath(fromObject, [
    "realtimeInputConfig"
  ]);
  if (parentObject !== void 0 && fromRealtimeInputConfig != null) {
    setValueByPath(parentObject, ["setup", "realtimeInputConfig"], fromRealtimeInputConfig);
  }
  const fromContextWindowCompression = getValueByPath(fromObject, [
    "contextWindowCompression"
  ]);
  if (parentObject !== void 0 && fromContextWindowCompression != null) {
    setValueByPath(parentObject, ["setup", "contextWindowCompression"], fromContextWindowCompression);
  }
  const fromProactivity = getValueByPath(fromObject, ["proactivity"]);
  if (parentObject !== void 0 && fromProactivity != null) {
    setValueByPath(parentObject, ["setup", "proactivity"], fromProactivity);
  }
  if (getValueByPath(fromObject, ["explicitVadSignal"]) !== void 0) {
    throw new Error("explicitVadSignal parameter is not supported in Gemini API.");
  }
  return toObject;
}
function liveConnectConstraintsToMldev(apiClient, fromObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["setup", "model"], tModel(apiClient, fromModel));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], liveConnectConfigToMldev(fromConfig, toObject));
  }
  return toObject;
}
function partToMldev(fromObject) {
  const toObject = {};
  const fromMediaResolution = getValueByPath(fromObject, [
    "mediaResolution"
  ]);
  if (fromMediaResolution != null) {
    setValueByPath(toObject, ["mediaResolution"], fromMediaResolution);
  }
  const fromCodeExecutionResult = getValueByPath(fromObject, [
    "codeExecutionResult"
  ]);
  if (fromCodeExecutionResult != null) {
    setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult);
  }
  const fromExecutableCode = getValueByPath(fromObject, [
    "executableCode"
  ]);
  if (fromExecutableCode != null) {
    setValueByPath(toObject, ["executableCode"], fromExecutableCode);
  }
  const fromFileData = getValueByPath(fromObject, ["fileData"]);
  if (fromFileData != null) {
    setValueByPath(toObject, ["fileData"], fileDataToMldev(fromFileData));
  }
  const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]);
  if (fromFunctionCall != null) {
    setValueByPath(toObject, ["functionCall"], functionCallToMldev(fromFunctionCall));
  }
  const fromFunctionResponse = getValueByPath(fromObject, [
    "functionResponse"
  ]);
  if (fromFunctionResponse != null) {
    setValueByPath(toObject, ["functionResponse"], fromFunctionResponse);
  }
  const fromInlineData = getValueByPath(fromObject, ["inlineData"]);
  if (fromInlineData != null) {
    setValueByPath(toObject, ["inlineData"], blobToMldev(fromInlineData));
  }
  const fromText = getValueByPath(fromObject, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  const fromThought = getValueByPath(fromObject, ["thought"]);
  if (fromThought != null) {
    setValueByPath(toObject, ["thought"], fromThought);
  }
  const fromThoughtSignature = getValueByPath(fromObject, [
    "thoughtSignature"
  ]);
  if (fromThoughtSignature != null) {
    setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature);
  }
  const fromVideoMetadata = getValueByPath(fromObject, [
    "videoMetadata"
  ]);
  if (fromVideoMetadata != null) {
    setValueByPath(toObject, ["videoMetadata"], fromVideoMetadata);
  }
  return toObject;
}
function sessionResumptionConfigToMldev(fromObject) {
  const toObject = {};
  const fromHandle = getValueByPath(fromObject, ["handle"]);
  if (fromHandle != null) {
    setValueByPath(toObject, ["handle"], fromHandle);
  }
  if (getValueByPath(fromObject, ["transparent"]) !== void 0) {
    throw new Error("transparent parameter is not supported in Gemini API.");
  }
  return toObject;
}
function toolToMldev(fromObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["retrieval"]) !== void 0) {
    throw new Error("retrieval parameter is not supported in Gemini API.");
  }
  const fromComputerUse = getValueByPath(fromObject, ["computerUse"]);
  if (fromComputerUse != null) {
    setValueByPath(toObject, ["computerUse"], fromComputerUse);
  }
  const fromFileSearch = getValueByPath(fromObject, ["fileSearch"]);
  if (fromFileSearch != null) {
    setValueByPath(toObject, ["fileSearch"], fromFileSearch);
  }
  const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]);
  if (fromGoogleSearch != null) {
    setValueByPath(toObject, ["googleSearch"], googleSearchToMldev(fromGoogleSearch));
  }
  const fromGoogleMaps = getValueByPath(fromObject, ["googleMaps"]);
  if (fromGoogleMaps != null) {
    setValueByPath(toObject, ["googleMaps"], googleMapsToMldev(fromGoogleMaps));
  }
  const fromCodeExecution = getValueByPath(fromObject, [
    "codeExecution"
  ]);
  if (fromCodeExecution != null) {
    setValueByPath(toObject, ["codeExecution"], fromCodeExecution);
  }
  if (getValueByPath(fromObject, ["enterpriseWebSearch"]) !== void 0) {
    throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");
  }
  const fromFunctionDeclarations = getValueByPath(fromObject, [
    "functionDeclarations"
  ]);
  if (fromFunctionDeclarations != null) {
    let transformedList = fromFunctionDeclarations;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["functionDeclarations"], transformedList);
  }
  const fromGoogleSearchRetrieval = getValueByPath(fromObject, [
    "googleSearchRetrieval"
  ]);
  if (fromGoogleSearchRetrieval != null) {
    setValueByPath(toObject, ["googleSearchRetrieval"], fromGoogleSearchRetrieval);
  }
  if (getValueByPath(fromObject, ["parallelAiSearch"]) !== void 0) {
    throw new Error("parallelAiSearch parameter is not supported in Gemini API.");
  }
  const fromUrlContext = getValueByPath(fromObject, ["urlContext"]);
  if (fromUrlContext != null) {
    setValueByPath(toObject, ["urlContext"], fromUrlContext);
  }
  const fromMcpServers = getValueByPath(fromObject, ["mcpServers"]);
  if (fromMcpServers != null) {
    let transformedList = fromMcpServers;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["mcpServers"], transformedList);
  }
  return toObject;
}
function getFieldMasks(setup) {
  const fields = [];
  for (const key in setup) {
    if (Object.prototype.hasOwnProperty.call(setup, key)) {
      const value = setup[key];
      if (typeof value === "object" && value != null && Object.keys(value).length > 0) {
        const field = Object.keys(value).map((kk) => `${key}.${kk}`);
        fields.push(...field);
      } else {
        fields.push(key);
      }
    }
  }
  return fields.join(",");
}
function convertBidiSetupToTokenSetup(requestDict, config) {
  let setupForMaskGeneration = null;
  const bidiGenerateContentSetupValue = requestDict["bidiGenerateContentSetup"];
  if (typeof bidiGenerateContentSetupValue === "object" && bidiGenerateContentSetupValue !== null && "setup" in bidiGenerateContentSetupValue) {
    const innerSetup = bidiGenerateContentSetupValue.setup;
    if (typeof innerSetup === "object" && innerSetup !== null) {
      requestDict["bidiGenerateContentSetup"] = innerSetup;
      setupForMaskGeneration = innerSetup;
    } else {
      delete requestDict["bidiGenerateContentSetup"];
    }
  } else if (bidiGenerateContentSetupValue !== void 0) {
    delete requestDict["bidiGenerateContentSetup"];
  }
  const preExistingFieldMask = requestDict["fieldMask"];
  if (setupForMaskGeneration) {
    const generatedMaskFromBidi = getFieldMasks(setupForMaskGeneration);
    if (Array.isArray(config === null || config === void 0 ? void 0 : config.lockAdditionalFields) && (config === null || config === void 0 ? void 0 : config.lockAdditionalFields.length) === 0) {
      if (generatedMaskFromBidi) {
        requestDict["fieldMask"] = generatedMaskFromBidi;
      } else {
        delete requestDict["fieldMask"];
      }
    } else if ((config === null || config === void 0 ? void 0 : config.lockAdditionalFields) && config.lockAdditionalFields.length > 0 && preExistingFieldMask !== null && Array.isArray(preExistingFieldMask) && preExistingFieldMask.length > 0) {
      const generationConfigFields = [
        "temperature",
        "topK",
        "topP",
        "maxOutputTokens",
        "responseModalities",
        "seed",
        "speechConfig"
      ];
      let mappedFieldsFromPreExisting = [];
      if (preExistingFieldMask.length > 0) {
        mappedFieldsFromPreExisting = preExistingFieldMask.map((field) => {
          if (generationConfigFields.includes(field)) {
            return `generationConfig.${field}`;
          }
          return field;
        });
      }
      const finalMaskParts = [];
      if (generatedMaskFromBidi) {
        finalMaskParts.push(generatedMaskFromBidi);
      }
      if (mappedFieldsFromPreExisting.length > 0) {
        finalMaskParts.push(...mappedFieldsFromPreExisting);
      }
      if (finalMaskParts.length > 0) {
        requestDict["fieldMask"] = finalMaskParts.join(",");
      } else {
        delete requestDict["fieldMask"];
      }
    } else {
      delete requestDict["fieldMask"];
    }
  } else {
    if (preExistingFieldMask !== null && Array.isArray(preExistingFieldMask) && preExistingFieldMask.length > 0) {
      requestDict["fieldMask"] = preExistingFieldMask.join(",");
    } else {
      delete requestDict["fieldMask"];
    }
  }
  return requestDict;
}
var Tokens = class extends BaseModule {
  constructor(apiClient) {
    super();
    this.apiClient = apiClient;
  }
  /**
   * Creates an ephemeral auth token resource.
   *
   * @experimental
   *
   * @remarks
   * Ephemeral auth tokens is only supported in the Gemini Developer API.
   * It can be used for the session connection to the Live constrained API.
   * Support in v1alpha only.
   *
   * @param params - The parameters for the create request.
   * @return The created auth token.
   *
   * @example
   * ```ts
   * const ai = new GoogleGenAI({
   *     apiKey: token.name,
   *     httpOptions: { apiVersion: 'v1alpha' }  // Support in v1alpha only.
   * });
   *
   * // Case 1: If LiveEphemeralParameters is unset, unlock LiveConnectConfig
   * // when using the token in Live API sessions. Each session connection can
   * // use a different configuration.
   * const config: CreateAuthTokenConfig = {
   *     uses: 3,
   *     expireTime: '2025-05-01T00:00:00Z',
   * }
   * const token = await ai.tokens.create(config);
   *
   * // Case 2: If LiveEphemeralParameters is set, lock all fields in
   * // LiveConnectConfig when using the token in Live API sessions. For
   * // example, changing `outputAudioTranscription` in the Live API
   * // connection will be ignored by the API.
   * const config: CreateAuthTokenConfig =
   *     uses: 3,
   *     expireTime: '2025-05-01T00:00:00Z',
   *     LiveEphemeralParameters: {
   *        model: 'gemini-2.0-flash-001',
   *        config: {
   *           'responseModalities': ['AUDIO'],
   *           'systemInstruction': 'Always answer in English.',
   *        }
   *     }
   * }
   * const token = await ai.tokens.create(config);
   *
   * // Case 3: If LiveEphemeralParameters is set and lockAdditionalFields is
   * // set, lock LiveConnectConfig with set and additional fields (e.g.
   * // responseModalities, systemInstruction, temperature in this example) when
   * // using the token in Live API sessions.
   * const config: CreateAuthTokenConfig =
   *     uses: 3,
   *     expireTime: '2025-05-01T00:00:00Z',
   *     LiveEphemeralParameters: {
   *        model: 'gemini-2.0-flash-001',
   *        config: {
   *           'responseModalities': ['AUDIO'],
   *           'systemInstruction': 'Always answer in English.',
   *        }
   *     },
   *     lockAdditionalFields: ['temperature'],
   * }
   * const token = await ai.tokens.create(config);
   *
   * // Case 4: If LiveEphemeralParameters is set and lockAdditionalFields is
   * // empty array, lock LiveConnectConfig with set fields (e.g.
   * // responseModalities, systemInstruction in this example) when using the
   * // token in Live API sessions.
   * const config: CreateAuthTokenConfig =
   *     uses: 3,
   *     expireTime: '2025-05-01T00:00:00Z',
   *     LiveEphemeralParameters: {
   *        model: 'gemini-2.0-flash-001',
   *        config: {
   *           'responseModalities': ['AUDIO'],
   *           'systemInstruction': 'Always answer in English.',
   *        }
   *     },
   *     lockAdditionalFields: [],
   * }
   * const token = await ai.tokens.create(config);
   * ```
   */
  async create(params) {
    var _a7, _b;
    let response;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      throw new Error("The client.tokens.create method is only supported by the Gemini Developer API.");
    } else {
      const body = createAuthTokenParametersToMldev(this.apiClient, params);
      path6 = formatMap("auth_tokens", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      const transformedBody = convertBidiSetupToTokenSetup(body, params.config);
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(transformedBody),
        httpMethod: "POST",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((resp) => {
        return resp;
      });
    }
  }
};
function deleteDocumentConfigToMldev(fromObject, parentObject) {
  const toObject = {};
  const fromForce = getValueByPath(fromObject, ["force"]);
  if (parentObject !== void 0 && fromForce != null) {
    setValueByPath(parentObject, ["_query", "force"], fromForce);
  }
  return toObject;
}
function deleteDocumentParametersToMldev(fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], fromName);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    deleteDocumentConfigToMldev(fromConfig, toObject);
  }
  return toObject;
}
function getDocumentParametersToMldev(fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], fromName);
  }
  return toObject;
}
function listDocumentsConfigToMldev(fromObject, parentObject) {
  const toObject = {};
  const fromPageSize = getValueByPath(fromObject, ["pageSize"]);
  if (parentObject !== void 0 && fromPageSize != null) {
    setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize);
  }
  const fromPageToken = getValueByPath(fromObject, ["pageToken"]);
  if (parentObject !== void 0 && fromPageToken != null) {
    setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken);
  }
  return toObject;
}
function listDocumentsParametersToMldev(fromObject) {
  const toObject = {};
  const fromParent = getValueByPath(fromObject, ["parent"]);
  if (fromParent != null) {
    setValueByPath(toObject, ["_url", "parent"], fromParent);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    listDocumentsConfigToMldev(fromConfig, toObject);
  }
  return toObject;
}
function listDocumentsResponseFromMldev(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromNextPageToken = getValueByPath(fromObject, [
    "nextPageToken"
  ]);
  if (fromNextPageToken != null) {
    setValueByPath(toObject, ["nextPageToken"], fromNextPageToken);
  }
  const fromDocuments = getValueByPath(fromObject, ["documents"]);
  if (fromDocuments != null) {
    let transformedList = fromDocuments;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["documents"], transformedList);
  }
  return toObject;
}
var Documents = class extends BaseModule {
  constructor(apiClient) {
    super();
    this.apiClient = apiClient;
    this.list = async (params) => {
      return new Pager(PagedItem.PAGED_ITEM_DOCUMENTS, (x2) => this.listInternal({ parent: params.parent, config: x2.config }), await this.listInternal(params), params);
    };
  }
  /**
   * Gets a Document.
   *
   * @param params - The parameters for getting a document.
   * @return Document.
   */
  async get(params) {
    var _a7, _b;
    let response;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      throw new Error("This method is only supported by the Gemini Developer API.");
    } else {
      const body = getDocumentParametersToMldev(params);
      path6 = formatMap("{name}", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "GET",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((resp) => {
        return resp;
      });
    }
  }
  /**
   * Deletes a Document.
   *
   * @param params - The parameters for deleting a document.
   */
  async delete(params) {
    var _a7, _b;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      throw new Error("This method is only supported by the Gemini Developer API.");
    } else {
      const body = deleteDocumentParametersToMldev(params);
      path6 = formatMap("{name}", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      await this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "DELETE",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      });
    }
  }
  async listInternal(params) {
    var _a7, _b;
    let response;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      throw new Error("This method is only supported by the Gemini Developer API.");
    } else {
      const body = listDocumentsParametersToMldev(params);
      path6 = formatMap("{parent}/documents", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "GET",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((apiResponse) => {
        const resp = listDocumentsResponseFromMldev(apiResponse);
        const typedResp = new ListDocumentsResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    }
  }
};
var FileSearchStores = class extends BaseModule {
  constructor(apiClient, documents = new Documents(apiClient)) {
    super();
    this.apiClient = apiClient;
    this.documents = documents;
    this.list = async (params = {}) => {
      return new Pager(PagedItem.PAGED_ITEM_FILE_SEARCH_STORES, (x2) => this.listInternal(x2), await this.listInternal(params), params);
    };
  }
  /**
   * Uploads a file asynchronously to a given File Search Store.
   * This method is not available in Vertex AI.
   * Supported upload sources:
   * - Node.js: File path (string) or Blob object.
   * - Browser: Blob object (e.g., File).
   *
   * @remarks
   * The `mimeType` can be specified in the `config` parameter. If omitted:
   *  - For file path (string) inputs, the `mimeType` will be inferred from the
   *     file extension.
   *  - For Blob object inputs, the `mimeType` will be set to the Blob's `type`
   *     property.
   *
   * This section can contain multiple paragraphs and code examples.
   *
   * @param params - Optional parameters specified in the
   *        `types.UploadToFileSearchStoreParameters` interface.
   *         @see {@link types.UploadToFileSearchStoreParameters#config} for the optional
   *         config in the parameters.
   * @return A promise that resolves to a long running operation.
   * @throws An error if called on a Vertex AI client.
   * @throws An error if the `mimeType` is not provided and can not be inferred,
   * the `mimeType` can be provided in the `params.config` parameter.
   * @throws An error occurs if a suitable upload location cannot be established.
   *
   * @example
   * The following code uploads a file to a given file search store.
   *
   * ```ts
   * const operation = await ai.fileSearchStores.upload({fileSearchStoreName: 'fileSearchStores/foo-bar', file: 'file.txt', config: {
   *   mimeType: 'text/plain',
   * }});
   * console.log(operation.name);
   * ```
   */
  async uploadToFileSearchStore(params) {
    if (this.apiClient.isVertexAI()) {
      throw new Error("Vertex AI does not support uploading files to a file search store.");
    }
    return this.apiClient.uploadFileToFileSearchStore(params.fileSearchStoreName, params.file, params.config);
  }
  /**
   * Creates a File Search Store.
   *
   * @param params - The parameters for creating a File Search Store.
   * @return FileSearchStore.
   */
  async create(params) {
    var _a7, _b;
    let response;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      throw new Error("This method is only supported by the Gemini Developer API.");
    } else {
      const body = createFileSearchStoreParametersToMldev(params);
      path6 = formatMap("fileSearchStores", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((resp) => {
        return resp;
      });
    }
  }
  /**
   * Gets a File Search Store.
   *
   * @param params - The parameters for getting a File Search Store.
   * @return FileSearchStore.
   */
  async get(params) {
    var _a7, _b;
    let response;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      throw new Error("This method is only supported by the Gemini Developer API.");
    } else {
      const body = getFileSearchStoreParametersToMldev(params);
      path6 = formatMap("{name}", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "GET",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((resp) => {
        return resp;
      });
    }
  }
  /**
   * Deletes a File Search Store.
   *
   * @param params - The parameters for deleting a File Search Store.
   */
  async delete(params) {
    var _a7, _b;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      throw new Error("This method is only supported by the Gemini Developer API.");
    } else {
      const body = deleteFileSearchStoreParametersToMldev(params);
      path6 = formatMap("{name}", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      await this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "DELETE",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      });
    }
  }
  async listInternal(params) {
    var _a7, _b;
    let response;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      throw new Error("This method is only supported by the Gemini Developer API.");
    } else {
      const body = listFileSearchStoresParametersToMldev(params);
      path6 = formatMap("fileSearchStores", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "GET",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((apiResponse) => {
        const resp = listFileSearchStoresResponseFromMldev(apiResponse);
        const typedResp = new ListFileSearchStoresResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    }
  }
  async uploadToFileSearchStoreInternal(params) {
    var _a7, _b;
    let response;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      throw new Error("This method is only supported by the Gemini Developer API.");
    } else {
      const body = uploadToFileSearchStoreParametersToMldev(params);
      path6 = formatMap("upload/v1beta/{file_search_store_name}:uploadToFileSearchStore", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((apiResponse) => {
        const resp = uploadToFileSearchStoreResumableResponseFromMldev(apiResponse);
        const typedResp = new UploadToFileSearchStoreResumableResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    }
  }
  /**
   * Imports a File from File Service to a FileSearchStore.
   *
   * This is a long-running operation, see aip.dev/151
   *
   * @param params - The parameters for importing a file to a file search store.
   * @return ImportFileOperation.
   */
  async importFile(params) {
    var _a7, _b;
    let response;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      throw new Error("This method is only supported by the Gemini Developer API.");
    } else {
      const body = importFileParametersToMldev(params);
      path6 = formatMap("{file_search_store_name}:importFile", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((apiResponse) => {
        const resp = importFileOperationFromMldev(apiResponse);
        const typedResp = new ImportFileOperation();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    }
  }
};
var uuid4Internal = function() {
  const { crypto: crypto2 } = globalThis;
  if (crypto2 === null || crypto2 === void 0 ? void 0 : crypto2.randomUUID) {
    uuid4Internal = crypto2.randomUUID.bind(crypto2);
    return crypto2.randomUUID();
  }
  const u8 = new Uint8Array(1);
  const randomByte = crypto2 ? () => crypto2.getRandomValues(u8)[0] : () => Math.random() * 255 & 255;
  return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c6) => (+c6 ^ randomByte() & 15 >> +c6 / 4).toString(16));
};
var uuid43 = () => uuid4Internal();
function isAbortError3(err) {
  return typeof err === "object" && err !== null && // Spec-compliant fetch implementations
  ("name" in err && err.name === "AbortError" || // Expo fetch
  "message" in err && String(err.message).includes("FetchRequestCanceledException"));
}
var castToError3 = (err) => {
  if (err instanceof Error)
    return err;
  if (typeof err === "object" && err !== null) {
    try {
      if (Object.prototype.toString.call(err) === "[object Error]") {
        const error = new Error(err.message, err.cause ? { cause: err.cause } : {});
        if (err.stack)
          error.stack = err.stack;
        if (err.cause && !error.cause)
          error.cause = err.cause;
        if (err.name)
          error.name = err.name;
        return error;
      }
    } catch (_a7) {
    }
    try {
      return new Error(JSON.stringify(err));
    } catch (_b) {
    }
  }
  return new Error(err);
};
var GeminiNextGenAPIClientError = class extends Error {
};
var APIError3 = class _APIError extends GeminiNextGenAPIClientError {
  constructor(status, error, message, headers) {
    super(`${_APIError.makeMessage(status, error, message)}`);
    this.status = status;
    this.headers = headers;
    this.error = error;
  }
  static makeMessage(status, error, message) {
    const msg = (error === null || error === void 0 ? void 0 : error.message) ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
    if (status && msg) {
      return `${status} ${msg}`;
    }
    if (status) {
      return `${status} status code (no body)`;
    }
    if (msg) {
      return msg;
    }
    return "(no status code or body)";
  }
  static generate(status, errorResponse, message, headers) {
    if (!status || !headers) {
      return new APIConnectionError3({ message, cause: castToError3(errorResponse) });
    }
    const error = errorResponse;
    if (status === 400) {
      return new BadRequestError3(status, error, message, headers);
    }
    if (status === 401) {
      return new AuthenticationError3(status, error, message, headers);
    }
    if (status === 403) {
      return new PermissionDeniedError3(status, error, message, headers);
    }
    if (status === 404) {
      return new NotFoundError3(status, error, message, headers);
    }
    if (status === 409) {
      return new ConflictError3(status, error, message, headers);
    }
    if (status === 422) {
      return new UnprocessableEntityError3(status, error, message, headers);
    }
    if (status === 429) {
      return new RateLimitError3(status, error, message, headers);
    }
    if (status >= 500) {
      return new InternalServerError3(status, error, message, headers);
    }
    return new _APIError(status, error, message, headers);
  }
};
var APIUserAbortError3 = class extends APIError3 {
  constructor({ message } = {}) {
    super(void 0, void 0, message || "Request was aborted.", void 0);
  }
};
var APIConnectionError3 = class extends APIError3 {
  constructor({ message, cause }) {
    super(void 0, void 0, message || "Connection error.", void 0);
    if (cause)
      this.cause = cause;
  }
};
var APIConnectionTimeoutError3 = class extends APIConnectionError3 {
  constructor({ message } = {}) {
    super({ message: message !== null && message !== void 0 ? message : "Request timed out." });
  }
};
var BadRequestError3 = class extends APIError3 {
};
var AuthenticationError3 = class extends APIError3 {
};
var PermissionDeniedError3 = class extends APIError3 {
};
var NotFoundError3 = class extends APIError3 {
};
var ConflictError3 = class extends APIError3 {
};
var UnprocessableEntityError3 = class extends APIError3 {
};
var RateLimitError3 = class extends APIError3 {
};
var InternalServerError3 = class extends APIError3 {
};
var startsWithSchemeRegexp3 = /^[a-z][a-z0-9+.-]*:/i;
var isAbsoluteURL3 = (url) => {
  return startsWithSchemeRegexp3.test(url);
};
var isArrayInternal = (val2) => (isArrayInternal = Array.isArray, isArrayInternal(val2));
var isArray3 = isArrayInternal;
var isReadonlyArrayInternal = isArray3;
var isReadonlyArray3 = isReadonlyArrayInternal;
function isEmptyObj3(obj) {
  if (!obj)
    return true;
  for (const _k in obj)
    return false;
  return true;
}
function hasOwn3(obj, key) {
  return Object.prototype.hasOwnProperty.call(obj, key);
}
var validatePositiveInteger3 = (name, n7) => {
  if (typeof n7 !== "number" || !Number.isInteger(n7)) {
    throw new GeminiNextGenAPIClientError(`${name} must be an integer`);
  }
  if (n7 < 0) {
    throw new GeminiNextGenAPIClientError(`${name} must be a positive integer`);
  }
  return n7;
};
var safeJSON3 = (text3) => {
  try {
    return JSON.parse(text3);
  } catch (err) {
    return void 0;
  }
};
var sleep$1 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
function getDefaultFetch3() {
  if (typeof fetch !== "undefined") {
    return fetch;
  }
  throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new GeminiNextGenAPIClient({ fetch })` or polyfill the global, `globalThis.fetch = fetch`");
}
function makeReadableStream3(...args) {
  const ReadableStream2 = globalThis.ReadableStream;
  if (typeof ReadableStream2 === "undefined") {
    throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");
  }
  return new ReadableStream2(...args);
}
function ReadableStreamFrom3(iterable) {
  let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator]();
  return makeReadableStream3({
    start() {
    },
    async pull(controller) {
      const { done, value } = await iter.next();
      if (done) {
        controller.close();
      } else {
        controller.enqueue(value);
      }
    },
    async cancel() {
      var _a7;
      await ((_a7 = iter.return) === null || _a7 === void 0 ? void 0 : _a7.call(iter));
    }
  });
}
function ReadableStreamToAsyncIterable3(stream2) {
  if (stream2[Symbol.asyncIterator])
    return stream2;
  const reader = stream2.getReader();
  return {
    async next() {
      try {
        const result = await reader.read();
        if (result === null || result === void 0 ? void 0 : result.done)
          reader.releaseLock();
        return result;
      } catch (e9) {
        reader.releaseLock();
        throw e9;
      }
    },
    async return() {
      const cancelPromise = reader.cancel();
      reader.releaseLock();
      await cancelPromise;
      return { done: true, value: void 0 };
    },
    [Symbol.asyncIterator]() {
      return this;
    }
  };
}
async function CancelReadableStream3(stream2) {
  var _a7, _b;
  if (stream2 === null || typeof stream2 !== "object")
    return;
  if (stream2[Symbol.asyncIterator]) {
    await ((_b = (_a7 = stream2[Symbol.asyncIterator]()).return) === null || _b === void 0 ? void 0 : _b.call(_a7));
    return;
  }
  const reader = stream2.getReader();
  const cancelPromise = reader.cancel();
  reader.releaseLock();
  await cancelPromise;
}
var FallbackEncoder3 = ({ headers, body }) => {
  return {
    bodyHeaders: {
      "content-type": "application/json"
    },
    body: JSON.stringify(body)
  };
};
function stringifyQuery2(query) {
  return Object.entries(query).filter(([_3, value]) => typeof value !== "undefined").map(([key, value]) => {
    if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
      return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
    }
    if (value === null) {
      return `${encodeURIComponent(key)}=`;
    }
    throw new GeminiNextGenAPIClientError(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`);
  }).join("&");
}
var VERSION3 = "0.0.1";
var checkFileSupport3 = () => {
  var _a7;
  if (typeof File === "undefined") {
    const { process: process2 } = globalThis;
    const isOldNode = typeof ((_a7 = process2 === null || process2 === void 0 ? void 0 : process2.versions) === null || _a7 === void 0 ? void 0 : _a7.node) === "string" && parseInt(process2.versions.node.split(".")) < 20;
    throw new Error("`File` is not defined as a global, which is required for file uploads." + (isOldNode ? " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`." : ""));
  }
};
function makeFile3(fileBits, fileName, options) {
  checkFileSupport3();
  return new File(fileBits, fileName !== null && fileName !== void 0 ? fileName : "unknown_file", options);
}
function getName3(value) {
  return (typeof value === "object" && value !== null && ("name" in value && value.name && String(value.name) || "url" in value && value.url && String(value.url) || "filename" in value && value.filename && String(value.filename) || "path" in value && value.path && String(value.path)) || "").split(/[\\/]/).pop() || void 0;
}
var isAsyncIterable3 = (value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function";
var isBlobLike3 = (value) => value != null && typeof value === "object" && typeof value.size === "number" && typeof value.type === "string" && typeof value.text === "function" && typeof value.slice === "function" && typeof value.arrayBuffer === "function";
var isFileLike3 = (value) => value != null && typeof value === "object" && typeof value.name === "string" && typeof value.lastModified === "number" && isBlobLike3(value);
var isResponseLike3 = (value) => value != null && typeof value === "object" && typeof value.url === "string" && typeof value.blob === "function";
async function toFile3(value, name, options) {
  checkFileSupport3();
  value = await value;
  if (isFileLike3(value)) {
    if (value instanceof File) {
      return value;
    }
    return makeFile3([await value.arrayBuffer()], value.name);
  }
  if (isResponseLike3(value)) {
    const blob = await value.blob();
    name || (name = new URL(value.url).pathname.split(/[\\/]/).pop());
    return makeFile3(await getBytes3(blob), name, options);
  }
  const parts = await getBytes3(value);
  name || (name = getName3(value));
  if (!(options === null || options === void 0 ? void 0 : options.type)) {
    const type = parts.find((part) => typeof part === "object" && "type" in part && part.type);
    if (typeof type === "string") {
      options = Object.assign(Object.assign({}, options), { type });
    }
  }
  return makeFile3(parts, name, options);
}
async function getBytes3(value) {
  var _a7, e_1, _b, _c;
  var _d;
  let parts = [];
  if (typeof value === "string" || ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc.
  value instanceof ArrayBuffer) {
    parts.push(value);
  } else if (isBlobLike3(value)) {
    parts.push(value instanceof Blob ? value : await value.arrayBuffer());
  } else if (isAsyncIterable3(value)) {
    try {
      for (var _e2 = true, value_1 = __asyncValues(value), value_1_1; value_1_1 = await value_1.next(), _a7 = value_1_1.done, !_a7; _e2 = true) {
        _c = value_1_1.value;
        _e2 = false;
        const chunk = _c;
        parts.push(...await getBytes3(chunk));
      }
    } catch (e_1_1) {
      e_1 = { error: e_1_1 };
    } finally {
      try {
        if (!_e2 && !_a7 && (_b = value_1.return)) await _b.call(value_1);
      } finally {
        if (e_1) throw e_1.error;
      }
    }
  } else {
    const constructor = (_d = value === null || value === void 0 ? void 0 : value.constructor) === null || _d === void 0 ? void 0 : _d.name;
    throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ""}${propsForError3(value)}`);
  }
  return parts;
}
function propsForError3(value) {
  if (typeof value !== "object" || value === null)
    return "";
  const props = Object.getOwnPropertyNames(value);
  return `; props: [${props.map((p4) => `"${p4}"`).join(", ")}]`;
}
var APIResource3 = class {
  constructor(client) {
    this._client = client;
  }
};
APIResource3._key = [];
function encodeURIPath3(str2) {
  return str2.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent);
}
var EMPTY3 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null));
var createPathTagFunction3 = (pathEncoder = encodeURIPath3) => (function path6(statics, ...params) {
  if (statics.length === 1)
    return statics[0];
  let postPath = false;
  const invalidSegments = [];
  const path7 = statics.reduce((previousValue, currentValue, index) => {
    var _a7, _b, _c;
    if (/[?#]/.test(currentValue)) {
      postPath = true;
    }
    const value = params[index];
    let encoded = (postPath ? encodeURIComponent : pathEncoder)("" + value);
    if (index !== params.length && (value == null || typeof value === "object" && // handle values from other realms
    value.toString === ((_c = Object.getPrototypeOf((_b = Object.getPrototypeOf((_a7 = value.hasOwnProperty) !== null && _a7 !== void 0 ? _a7 : EMPTY3)) !== null && _b !== void 0 ? _b : EMPTY3)) === null || _c === void 0 ? void 0 : _c.toString))) {
      encoded = value + "";
      invalidSegments.push({
        start: previousValue.length + currentValue.length,
        length: encoded.length,
        error: `Value of type ${Object.prototype.toString.call(value).slice(8, -1)} is not a valid path parameter`
      });
    }
    return previousValue + currentValue + (index === params.length ? "" : encoded);
  }, "");
  const pathOnly = path7.split(/[?#]/, 1)[0];
  const invalidSegmentPattern = /(^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;
  let match2;
  while ((match2 = invalidSegmentPattern.exec(pathOnly)) !== null) {
    const hasLeadingSlash = match2[0].startsWith("/");
    const offset = hasLeadingSlash ? 1 : 0;
    const cleanMatch = hasLeadingSlash ? match2[0].slice(1) : match2[0];
    invalidSegments.push({
      start: match2.index + offset,
      length: cleanMatch.length,
      error: `Value "${cleanMatch}" can't be safely passed as a path parameter`
    });
  }
  invalidSegments.sort((a3, b4) => a3.start - b4.start);
  if (invalidSegments.length > 0) {
    let lastEnd = 0;
    const underline = invalidSegments.reduce((acc, segment) => {
      const spaces = " ".repeat(segment.start - lastEnd);
      const arrows = "^".repeat(segment.length);
      lastEnd = segment.start + segment.length;
      return acc + spaces + arrows;
    }, "");
    throw new GeminiNextGenAPIClientError(`Path parameters result in path with invalid segments:
${invalidSegments.map((e9) => e9.error).join("\n")}
${path7}
${underline}`);
  }
  return path7;
});
var path3 = /* @__PURE__ */ createPathTagFunction3(encodeURIPath3);
var BaseInteractions = class extends APIResource3 {
  create(params, options) {
    var _a7;
    const { api_version = this._client.apiVersion } = params, body = __rest(params, ["api_version"]);
    if ("model" in body && "agent_config" in body) {
      throw new GeminiNextGenAPIClientError(`Invalid request: specified \`model\` and \`agent_config\`. If specifying \`model\`, use \`generation_config\`.`);
    }
    if ("agent" in body && "generation_config" in body) {
      throw new GeminiNextGenAPIClientError(`Invalid request: specified \`agent\` and \`generation_config\`. If specifying \`agent\`, use \`agent_config\`.`);
    }
    return this._client.post(path3`/${api_version}/interactions`, Object.assign(Object.assign({ body }, options), { stream: (_a7 = params.stream) !== null && _a7 !== void 0 ? _a7 : false }));
  }
  /**
   * Deletes the interaction by id.
   *
   * @example
   * ```ts
   * const interaction = await client.interactions.delete('id', {
   *   api_version: 'api_version',
   * });
   * ```
   */
  delete(id, params = {}, options) {
    const { api_version = this._client.apiVersion } = params !== null && params !== void 0 ? params : {};
    return this._client.delete(path3`/${api_version}/interactions/${id}`, options);
  }
  /**
   * Cancels an interaction by id. This only applies to background interactions that are still running.
   *
   * @example
   * ```ts
   * const interaction = await client.interactions.cancel('id', {
   *   api_version: 'api_version',
   * });
   * ```
   */
  cancel(id, params = {}, options) {
    const { api_version = this._client.apiVersion } = params !== null && params !== void 0 ? params : {};
    return this._client.post(path3`/${api_version}/interactions/${id}/cancel`, options);
  }
  get(id, params = {}, options) {
    var _a7;
    const _b = params !== null && params !== void 0 ? params : {}, { api_version = this._client.apiVersion } = _b, query = __rest(_b, ["api_version"]);
    return this._client.get(path3`/${api_version}/interactions/${id}`, Object.assign(Object.assign({ query }, options), { stream: (_a7 = params === null || params === void 0 ? void 0 : params.stream) !== null && _a7 !== void 0 ? _a7 : false }));
  }
};
BaseInteractions._key = Object.freeze(["interactions"]);
var Interactions = class extends BaseInteractions {
};
function concatBytes3(buffers) {
  let length = 0;
  for (const buffer of buffers) {
    length += buffer.length;
  }
  const output = new Uint8Array(length);
  let index = 0;
  for (const buffer of buffers) {
    output.set(buffer, index);
    index += buffer.length;
  }
  return output;
}
var encodeUTF8_3;
function encodeUTF83(str2) {
  let encoder;
  return (encodeUTF8_3 !== null && encodeUTF8_3 !== void 0 ? encodeUTF8_3 : (encoder = new globalThis.TextEncoder(), encodeUTF8_3 = encoder.encode.bind(encoder)))(str2);
}
var decodeUTF8_3;
function decodeUTF83(bytes) {
  let decoder;
  return (decodeUTF8_3 !== null && decodeUTF8_3 !== void 0 ? decodeUTF8_3 : (decoder = new globalThis.TextDecoder(), decodeUTF8_3 = decoder.decode.bind(decoder)))(bytes);
}
var LineDecoder3 = class {
  constructor() {
    this.buffer = new Uint8Array();
    this.carriageReturnIndex = null;
    this.searchIndex = 0;
  }
  decode(chunk) {
    var _a7;
    if (chunk == null) {
      return [];
    }
    const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? encodeUTF83(chunk) : chunk;
    this.buffer = concatBytes3([this.buffer, binaryChunk]);
    const lines = [];
    let patternIndex;
    while ((patternIndex = findNewlineIndex3(this.buffer, (_a7 = this.carriageReturnIndex) !== null && _a7 !== void 0 ? _a7 : this.searchIndex)) != null) {
      if (patternIndex.carriage && this.carriageReturnIndex == null) {
        this.carriageReturnIndex = patternIndex.index;
        continue;
      }
      if (this.carriageReturnIndex != null && (patternIndex.index !== this.carriageReturnIndex + 1 || patternIndex.carriage)) {
        lines.push(decodeUTF83(this.buffer.subarray(0, this.carriageReturnIndex - 1)));
        this.buffer = this.buffer.subarray(this.carriageReturnIndex);
        this.carriageReturnIndex = null;
        this.searchIndex = 0;
        continue;
      }
      const endIndex = this.carriageReturnIndex !== null ? patternIndex.preceding - 1 : patternIndex.preceding;
      const line = decodeUTF83(this.buffer.subarray(0, endIndex));
      lines.push(line);
      this.buffer = this.buffer.subarray(patternIndex.index);
      this.carriageReturnIndex = null;
      this.searchIndex = 0;
    }
    this.searchIndex = Math.max(0, this.buffer.length - 1);
    return lines;
  }
  flush() {
    if (!this.buffer.length) {
      return [];
    }
    return this.decode("\n");
  }
};
LineDecoder3.NEWLINE_CHARS = /* @__PURE__ */ new Set(["\n", "\r"]);
LineDecoder3.NEWLINE_REGEXP = /\r\n|[\n\r]/g;
function findNewlineIndex3(buffer, startIndex) {
  const newline = 10;
  const carriage = 13;
  const start = startIndex !== null && startIndex !== void 0 ? startIndex : 0;
  const nextNewline = buffer.indexOf(newline, start);
  const nextCarriage = buffer.indexOf(carriage, start);
  if (nextNewline === -1 && nextCarriage === -1) {
    return null;
  }
  let i7;
  if (nextNewline !== -1 && nextCarriage !== -1) {
    i7 = Math.min(nextNewline, nextCarriage);
  } else {
    i7 = nextNewline !== -1 ? nextNewline : nextCarriage;
  }
  if (buffer[i7] === newline) {
    return { preceding: i7, index: i7 + 1, carriage: false };
  }
  return { preceding: i7, index: i7 + 1, carriage: true };
}
var levelNumbers3 = {
  off: 0,
  error: 200,
  warn: 300,
  info: 400,
  debug: 500
};
var parseLogLevel3 = (maybeLevel, sourceName, client) => {
  if (!maybeLevel) {
    return void 0;
  }
  if (hasOwn3(levelNumbers3, maybeLevel)) {
    return maybeLevel;
  }
  loggerFor3(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers3))}`);
  return void 0;
};
function noop3() {
}
function makeLogFn3(fnLevel, logger2, logLevel) {
  if (!logger2 || levelNumbers3[fnLevel] > levelNumbers3[logLevel]) {
    return noop3;
  } else {
    return logger2[fnLevel].bind(logger2);
  }
}
var noopLogger3 = {
  error: noop3,
  warn: noop3,
  info: noop3,
  debug: noop3
};
var cachedLoggers3 = /* @__PURE__ */ new WeakMap();
function loggerFor3(client) {
  var _a7;
  const logger2 = client.logger;
  const logLevel = (_a7 = client.logLevel) !== null && _a7 !== void 0 ? _a7 : "off";
  if (!logger2) {
    return noopLogger3;
  }
  const cachedLogger = cachedLoggers3.get(logger2);
  if (cachedLogger && cachedLogger[0] === logLevel) {
    return cachedLogger[1];
  }
  const levelLogger = {
    error: makeLogFn3("error", logger2, logLevel),
    warn: makeLogFn3("warn", logger2, logLevel),
    info: makeLogFn3("info", logger2, logLevel),
    debug: makeLogFn3("debug", logger2, logLevel)
  };
  cachedLoggers3.set(logger2, [logLevel, levelLogger]);
  return levelLogger;
}
var formatRequestDetails3 = (details) => {
  if (details.options) {
    details.options = Object.assign({}, details.options);
    delete details.options["headers"];
  }
  if (details.headers) {
    details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [
      name,
      name.toLowerCase() === "x-goog-api-key" || name.toLowerCase() === "authorization" || name.toLowerCase() === "cookie" || name.toLowerCase() === "set-cookie" ? "***" : value
    ]));
  }
  if ("retryOfRequestLogID" in details) {
    if (details.retryOfRequestLogID) {
      details.retryOf = details.retryOfRequestLogID;
    }
    delete details.retryOfRequestLogID;
  }
  return details;
};
var Stream3 = class _Stream {
  constructor(iterator, controller, client) {
    this.iterator = iterator;
    this.controller = controller;
    this.client = client;
  }
  static fromSSEResponse(response, controller, client) {
    let consumed2 = false;
    const logger2 = client ? loggerFor3(client) : console;
    function iterator() {
      return __asyncGenerator(this, arguments, function* iterator_1() {
        var _a7, e_1, _b, _c;
        if (consumed2) {
          throw new GeminiNextGenAPIClientError("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
        }
        consumed2 = true;
        let done = false;
        try {
          try {
            for (var _d = true, _e2 = __asyncValues(_iterSSEMessages3(response, controller)), _f; _f = yield __await(_e2.next()), _a7 = _f.done, !_a7; _d = true) {
              _c = _f.value;
              _d = false;
              const sse = _c;
              if (done)
                continue;
              if (sse.data.startsWith("[DONE]")) {
                done = true;
                continue;
              } else {
                try {
                  yield yield __await(JSON.parse(sse.data));
                } catch (e9) {
                  logger2.error(`Could not parse message into JSON:`, sse.data);
                  logger2.error(`From chunk:`, sse.raw);
                  throw e9;
                }
              }
            }
          } catch (e_1_1) {
            e_1 = { error: e_1_1 };
          } finally {
            try {
              if (!_d && !_a7 && (_b = _e2.return)) yield __await(_b.call(_e2));
            } finally {
              if (e_1) throw e_1.error;
            }
          }
          done = true;
        } catch (e9) {
          if (isAbortError3(e9))
            return yield __await(void 0);
          throw e9;
        } finally {
          if (!done)
            controller.abort();
        }
      });
    }
    return new _Stream(iterator, controller, client);
  }
  /**
   * Generates a Stream from a newline-separated ReadableStream
   * where each item is a JSON value.
   */
  static fromReadableStream(readableStream, controller, client) {
    let consumed2 = false;
    function iterLines() {
      return __asyncGenerator(this, arguments, function* iterLines_1() {
        var _a7, e_2, _b, _c;
        const lineDecoder = new LineDecoder3();
        const iter = ReadableStreamToAsyncIterable3(readableStream);
        try {
          for (var _d = true, iter_1 = __asyncValues(iter), iter_1_1; iter_1_1 = yield __await(iter_1.next()), _a7 = iter_1_1.done, !_a7; _d = true) {
            _c = iter_1_1.value;
            _d = false;
            const chunk = _c;
            for (const line of lineDecoder.decode(chunk)) {
              yield yield __await(line);
            }
          }
        } catch (e_2_1) {
          e_2 = { error: e_2_1 };
        } finally {
          try {
            if (!_d && !_a7 && (_b = iter_1.return)) yield __await(_b.call(iter_1));
          } finally {
            if (e_2) throw e_2.error;
          }
        }
        for (const line of lineDecoder.flush()) {
          yield yield __await(line);
        }
      });
    }
    function iterator() {
      return __asyncGenerator(this, arguments, function* iterator_2() {
        var _a7, e_3, _b, _c;
        if (consumed2) {
          throw new GeminiNextGenAPIClientError("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
        }
        consumed2 = true;
        let done = false;
        try {
          try {
            for (var _d = true, _e2 = __asyncValues(iterLines()), _f; _f = yield __await(_e2.next()), _a7 = _f.done, !_a7; _d = true) {
              _c = _f.value;
              _d = false;
              const line = _c;
              if (done)
                continue;
              if (line)
                yield yield __await(JSON.parse(line));
            }
          } catch (e_3_1) {
            e_3 = { error: e_3_1 };
          } finally {
            try {
              if (!_d && !_a7 && (_b = _e2.return)) yield __await(_b.call(_e2));
            } finally {
              if (e_3) throw e_3.error;
            }
          }
          done = true;
        } catch (e9) {
          if (isAbortError3(e9))
            return yield __await(void 0);
          throw e9;
        } finally {
          if (!done)
            controller.abort();
        }
      });
    }
    return new _Stream(iterator, controller, client);
  }
  [Symbol.asyncIterator]() {
    return this.iterator();
  }
  /**
   * Splits the stream into two streams which can be
   * independently read from at different speeds.
   */
  tee() {
    const left = [];
    const right = [];
    const iterator = this.iterator();
    const teeIterator = (queue) => {
      return {
        next: () => {
          if (queue.length === 0) {
            const result = iterator.next();
            left.push(result);
            right.push(result);
          }
          return queue.shift();
        }
      };
    };
    return [
      new _Stream(() => teeIterator(left), this.controller, this.client),
      new _Stream(() => teeIterator(right), this.controller, this.client)
    ];
  }
  /**
   * Converts this stream to a newline-separated ReadableStream of
   * JSON stringified values in the stream
   * which can be turned back into a Stream with `Stream.fromReadableStream()`.
   */
  toReadableStream() {
    const self2 = this;
    let iter;
    return makeReadableStream3({
      async start() {
        iter = self2[Symbol.asyncIterator]();
      },
      async pull(ctrl) {
        try {
          const { value, done } = await iter.next();
          if (done)
            return ctrl.close();
          const bytes = encodeUTF83(JSON.stringify(value) + "\n");
          ctrl.enqueue(bytes);
        } catch (err) {
          ctrl.error(err);
        }
      },
      async cancel() {
        var _a7;
        await ((_a7 = iter.return) === null || _a7 === void 0 ? void 0 : _a7.call(iter));
      }
    });
  }
};
function _iterSSEMessages3(response, controller) {
  return __asyncGenerator(this, arguments, function* _iterSSEMessages_1() {
    var _a7, e_4, _b, _c;
    if (!response.body) {
      controller.abort();
      if (typeof globalThis.navigator !== "undefined" && globalThis.navigator.product === "ReactNative") {
        throw new GeminiNextGenAPIClientError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`);
      }
      throw new GeminiNextGenAPIClientError(`Attempted to iterate over a response with no body`);
    }
    const sseDecoder = new SSEDecoder3();
    const lineDecoder = new LineDecoder3();
    const iter = ReadableStreamToAsyncIterable3(response.body);
    try {
      for (var _d = true, _e2 = __asyncValues(iterBinaryChunks(iter)), _f; _f = yield __await(_e2.next()), _a7 = _f.done, !_a7; _d = true) {
        _c = _f.value;
        _d = false;
        const sseChunk = _c;
        for (const line of lineDecoder.decode(sseChunk)) {
          const sse = sseDecoder.decode(line);
          if (sse)
            yield yield __await(sse);
        }
      }
    } catch (e_4_1) {
      e_4 = { error: e_4_1 };
    } finally {
      try {
        if (!_d && !_a7 && (_b = _e2.return)) yield __await(_b.call(_e2));
      } finally {
        if (e_4) throw e_4.error;
      }
    }
    for (const line of lineDecoder.flush()) {
      const sse = sseDecoder.decode(line);
      if (sse)
        yield yield __await(sse);
    }
  });
}
function iterBinaryChunks(iterator) {
  return __asyncGenerator(this, arguments, function* iterBinaryChunks_1() {
    var _a7, e_5, _b, _c;
    try {
      for (var _d = true, iterator_3 = __asyncValues(iterator), iterator_3_1; iterator_3_1 = yield __await(iterator_3.next()), _a7 = iterator_3_1.done, !_a7; _d = true) {
        _c = iterator_3_1.value;
        _d = false;
        const chunk = _c;
        if (chunk == null) {
          continue;
        }
        const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? encodeUTF83(chunk) : chunk;
        yield yield __await(binaryChunk);
      }
    } catch (e_5_1) {
      e_5 = { error: e_5_1 };
    } finally {
      try {
        if (!_d && !_a7 && (_b = iterator_3.return)) yield __await(_b.call(iterator_3));
      } finally {
        if (e_5) throw e_5.error;
      }
    }
  });
}
var SSEDecoder3 = class {
  constructor() {
    this.event = null;
    this.data = [];
    this.chunks = [];
  }
  decode(line) {
    if (line.endsWith("\r")) {
      line = line.substring(0, line.length - 1);
    }
    if (!line) {
      if (!this.event && !this.data.length)
        return null;
      const sse = {
        event: this.event,
        data: this.data.join("\n"),
        raw: this.chunks
      };
      this.event = null;
      this.data = [];
      this.chunks = [];
      return sse;
    }
    this.chunks.push(line);
    if (line.startsWith(":")) {
      return null;
    }
    let [fieldname, _3, value] = partition3(line, ":");
    if (value.startsWith(" ")) {
      value = value.substring(1);
    }
    if (fieldname === "event") {
      this.event = value;
    } else if (fieldname === "data") {
      this.data.push(value);
    }
    return null;
  }
};
function partition3(str2, delimiter2) {
  const index = str2.indexOf(delimiter2);
  if (index !== -1) {
    return [str2.substring(0, index), delimiter2, str2.substring(index + delimiter2.length)];
  }
  return [str2, "", ""];
}
async function defaultParseResponse3(client, props) {
  const { response, requestLogID, retryOfRequestLogID, startTime } = props;
  const body = await (async () => {
    var _a7;
    if (props.options.stream) {
      loggerFor3(client).debug("response", response.status, response.url, response.headers, response.body);
      if (props.options.__streamClass) {
        return props.options.__streamClass.fromSSEResponse(response, props.controller, client);
      }
      return Stream3.fromSSEResponse(response, props.controller, client);
    }
    if (response.status === 204) {
      return null;
    }
    if (props.options.__binaryResponse) {
      return response;
    }
    const contentType = response.headers.get("content-type");
    const mediaType = (_a7 = contentType === null || contentType === void 0 ? void 0 : contentType.split(";")[0]) === null || _a7 === void 0 ? void 0 : _a7.trim();
    const isJSON = (mediaType === null || mediaType === void 0 ? void 0 : mediaType.includes("application/json")) || (mediaType === null || mediaType === void 0 ? void 0 : mediaType.endsWith("+json"));
    if (isJSON) {
      const contentLength = response.headers.get("content-length");
      if (contentLength === "0") {
        return void 0;
      }
      const json2 = await response.json();
      return json2;
    }
    const text3 = await response.text();
    return text3;
  })();
  loggerFor3(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails3({
    retryOfRequestLogID,
    url: response.url,
    status: response.status,
    body,
    durationMs: Date.now() - startTime
  }));
  return body;
}
var APIPromise3 = class _APIPromise extends Promise {
  constructor(client, responsePromise, parseResponse2 = defaultParseResponse3) {
    super((resolve) => {
      resolve(null);
    });
    this.responsePromise = responsePromise;
    this.parseResponse = parseResponse2;
    this.client = client;
  }
  _thenUnwrap(transform) {
    return new _APIPromise(this.client, this.responsePromise, async (client, props) => transform(await this.parseResponse(client, props), props));
  }
  /**
   * Gets the raw `Response` instance instead of parsing the response
   * data.
   *
   * If you want to parse the response body but still get the `Response`
   * instance, you can use {@link withResponse()}.
   *
   * 👋 Getting the wrong TypeScript type for `Response`?
   * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
   * to your `tsconfig.json`.
   */
  asResponse() {
    return this.responsePromise.then((p4) => p4.response);
  }
  /**
   * Gets the parsed response data and the raw `Response` instance.
   *
   * If you just want to get the raw `Response` instance without parsing it,
   * you can use {@link asResponse()}.
   *
   * 👋 Getting the wrong TypeScript type for `Response`?
   * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
   * to your `tsconfig.json`.
   */
  async withResponse() {
    const [data, response] = await Promise.all([this.parse(), this.asResponse()]);
    return { data, response };
  }
  parse() {
    if (!this.parsedPromise) {
      this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(this.client, data));
    }
    return this.parsedPromise;
  }
  then(onfulfilled, onrejected) {
    return this.parse().then(onfulfilled, onrejected);
  }
  catch(onrejected) {
    return this.parse().catch(onrejected);
  }
  finally(onfinally) {
    return this.parse().finally(onfinally);
  }
};
var brand_privateNullableHeaders3 = /* @__PURE__ */ Symbol("brand.privateNullableHeaders");
function* iterateHeaders3(headers) {
  if (!headers)
    return;
  if (brand_privateNullableHeaders3 in headers) {
    const { values: values2, nulls } = headers;
    yield* values2.entries();
    for (const name of nulls) {
      yield [name, null];
    }
    return;
  }
  let shouldClear = false;
  let iter;
  if (headers instanceof Headers) {
    iter = headers.entries();
  } else if (isReadonlyArray3(headers)) {
    iter = headers;
  } else {
    shouldClear = true;
    iter = Object.entries(headers !== null && headers !== void 0 ? headers : {});
  }
  for (let row of iter) {
    const name = row[0];
    if (typeof name !== "string")
      throw new TypeError("expected header name to be a string");
    const values2 = isReadonlyArray3(row[1]) ? row[1] : [row[1]];
    let didClear = false;
    for (const value of values2) {
      if (value === void 0)
        continue;
      if (shouldClear && !didClear) {
        didClear = true;
        yield [name, null];
      }
      yield [name, value];
    }
  }
}
var buildHeaders3 = (newHeaders) => {
  const targetHeaders = new Headers();
  const nullHeaders = /* @__PURE__ */ new Set();
  for (const headers of newHeaders) {
    const seenHeaders = /* @__PURE__ */ new Set();
    for (const [name, value] of iterateHeaders3(headers)) {
      const lowerName = name.toLowerCase();
      if (!seenHeaders.has(lowerName)) {
        targetHeaders.delete(name);
        seenHeaders.add(lowerName);
      }
      if (value === null) {
        targetHeaders.delete(name);
        nullHeaders.add(lowerName);
      } else {
        targetHeaders.append(name, value);
        nullHeaders.delete(lowerName);
      }
    }
  }
  return { [brand_privateNullableHeaders3]: true, values: targetHeaders, nulls: nullHeaders };
};
var readEnv3 = (env) => {
  var _a7, _b, _c, _d, _e2, _f;
  if (typeof globalThis.process !== "undefined") {
    return (_c = (_b = (_a7 = globalThis.process.env) === null || _a7 === void 0 ? void 0 : _a7[env]) === null || _b === void 0 ? void 0 : _b.trim()) !== null && _c !== void 0 ? _c : void 0;
  }
  if (typeof globalThis.Deno !== "undefined") {
    return (_f = (_e2 = (_d = globalThis.Deno.env) === null || _d === void 0 ? void 0 : _d.get) === null || _e2 === void 0 ? void 0 : _e2.call(_d, env)) === null || _f === void 0 ? void 0 : _f.trim();
  }
  return void 0;
};
var _a4;
var BaseGeminiNextGenAPIClient = class _BaseGeminiNextGenAPIClient {
  /**
   * API Client for interfacing with the Gemini Next Gen API API.
   *
   * @param {string | null | undefined} [opts.apiKey=process.env['GEMINI_API_KEY'] ?? null]
   * @param {string | undefined} [opts.apiVersion=v1beta]
   * @param {string} [opts.baseURL=process.env['GEMINI_NEXT_GEN_API_BASE_URL'] ?? https://generativelanguage.googleapis.com] - Override the default base URL for the API.
   * @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
   * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.
   * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
   * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
   * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
   * @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.
   */
  constructor(_b) {
    var _c, _d, _e2, _f, _g, _h, _j;
    var { baseURL = readEnv3("GEMINI_NEXT_GEN_API_BASE_URL"), apiKey = (_c = readEnv3("GEMINI_API_KEY")) !== null && _c !== void 0 ? _c : null, apiVersion = "v1beta" } = _b, opts = __rest(_b, ["baseURL", "apiKey", "apiVersion"]);
    const options = Object.assign(Object.assign({
      apiKey,
      apiVersion
    }, opts), { baseURL: baseURL || `https://generativelanguage.googleapis.com` });
    this.baseURL = options.baseURL;
    this.timeout = (_d = options.timeout) !== null && _d !== void 0 ? _d : _BaseGeminiNextGenAPIClient.DEFAULT_TIMEOUT;
    this.logger = (_e2 = options.logger) !== null && _e2 !== void 0 ? _e2 : console;
    const defaultLogLevel = "warn";
    this.logLevel = defaultLogLevel;
    this.logLevel = (_g = (_f = parseLogLevel3(options.logLevel, "ClientOptions.logLevel", this)) !== null && _f !== void 0 ? _f : parseLogLevel3(readEnv3("GEMINI_NEXT_GEN_API_LOG"), "process.env['GEMINI_NEXT_GEN_API_LOG']", this)) !== null && _g !== void 0 ? _g : defaultLogLevel;
    this.fetchOptions = options.fetchOptions;
    this.maxRetries = (_h = options.maxRetries) !== null && _h !== void 0 ? _h : 2;
    this.fetch = (_j = options.fetch) !== null && _j !== void 0 ? _j : getDefaultFetch3();
    this.encoder = FallbackEncoder3;
    this._options = options;
    this.apiKey = apiKey;
    this.apiVersion = apiVersion;
    this.clientAdapter = options.clientAdapter;
  }
  /**
   * Create a new client instance re-using the same options given to the current client with optional overriding.
   */
  withOptions(options) {
    const client = new this.constructor(Object.assign(Object.assign(Object.assign({}, this._options), { baseURL: this.baseURL, maxRetries: this.maxRetries, timeout: this.timeout, logger: this.logger, logLevel: this.logLevel, fetch: this.fetch, fetchOptions: this.fetchOptions, apiKey: this.apiKey, apiVersion: this.apiVersion }), options));
    return client;
  }
  /**
   * Check whether the base URL is set to its default.
   */
  baseURLOverridden() {
    return this.baseURL !== "https://generativelanguage.googleapis.com";
  }
  defaultQuery() {
    return this._options.defaultQuery;
  }
  validateHeaders({ values: values2, nulls }) {
    if (values2.has("authorization") || values2.has("x-goog-api-key")) {
      return;
    }
    if (this.apiKey && values2.get("x-goog-api-key")) {
      return;
    }
    if (nulls.has("x-goog-api-key")) {
      return;
    }
    throw new Error('Could not resolve authentication method. Expected the apiKey to be set. Or for the "x-goog-api-key" headers to be explicitly omitted');
  }
  async authHeaders(opts) {
    const existingHeaders = buildHeaders3([opts.headers]);
    if (existingHeaders.values.has("authorization") || existingHeaders.values.has("x-goog-api-key")) {
      return void 0;
    }
    if (this.apiKey) {
      return buildHeaders3([{ "x-goog-api-key": this.apiKey }]);
    }
    if (this.clientAdapter.isVertexAI()) {
      return buildHeaders3([await this.clientAdapter.getAuthHeaders()]);
    }
    return void 0;
  }
  /**
   * Basic re-implementation of `qs.stringify` for primitive types.
   */
  stringifyQuery(query) {
    return stringifyQuery2(query);
  }
  getUserAgent() {
    return `${this.constructor.name}/JS ${VERSION3}`;
  }
  defaultIdempotencyKey() {
    return `stainless-node-retry-${uuid43()}`;
  }
  makeStatusError(status, error, message, headers) {
    return APIError3.generate(status, error, message, headers);
  }
  buildURL(path6, query, defaultBaseURL) {
    const baseURL = !this.baseURLOverridden() && defaultBaseURL || this.baseURL;
    const url = isAbsoluteURL3(path6) ? new URL(path6) : new URL(baseURL + (baseURL.endsWith("/") && path6.startsWith("/") ? path6.slice(1) : path6));
    const defaultQuery = this.defaultQuery();
    const pathQuery = Object.fromEntries(url.searchParams);
    if (!isEmptyObj3(defaultQuery) || !isEmptyObj3(pathQuery)) {
      query = Object.assign(Object.assign(Object.assign({}, pathQuery), defaultQuery), query);
    }
    if (typeof query === "object" && query && !Array.isArray(query)) {
      url.search = this.stringifyQuery(query);
    }
    return url.toString();
  }
  /**
     * Used as a callback for mutating the given `FinalRequestOptions` object.
  
     */
  async prepareOptions(options) {
    if (this.clientAdapter && this.clientAdapter.isVertexAI() && !options.path.startsWith(`/${this.apiVersion}/projects/`)) {
      const oldPath = options.path.slice(this.apiVersion.length + 1);
      options.path = `/${this.apiVersion}/projects/${this.clientAdapter.getProject()}/locations/${this.clientAdapter.getLocation()}${oldPath}`;
    }
  }
  /**
   * Used as a callback for mutating the given `RequestInit` object.
   *
   * This is useful for cases where you want to add certain headers based off of
   * the request properties, e.g. `method` or `url`.
   */
  async prepareRequest(request, { url, options }) {
  }
  get(path6, opts) {
    return this.methodRequest("get", path6, opts);
  }
  post(path6, opts) {
    return this.methodRequest("post", path6, opts);
  }
  patch(path6, opts) {
    return this.methodRequest("patch", path6, opts);
  }
  put(path6, opts) {
    return this.methodRequest("put", path6, opts);
  }
  delete(path6, opts) {
    return this.methodRequest("delete", path6, opts);
  }
  methodRequest(method, path6, opts) {
    return this.request(Promise.resolve(opts).then((opts2) => {
      return Object.assign({ method, path: path6 }, opts2);
    }));
  }
  request(options, remainingRetries = null) {
    return new APIPromise3(this, this.makeRequest(options, remainingRetries, void 0));
  }
  async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {
    var _b, _c, _d;
    const options = await optionsInput;
    const maxRetries = (_b = options.maxRetries) !== null && _b !== void 0 ? _b : this.maxRetries;
    if (retriesRemaining == null) {
      retriesRemaining = maxRetries;
    }
    await this.prepareOptions(options);
    const { req, url, timeout } = await this.buildRequest(options, {
      retryCount: maxRetries - retriesRemaining
    });
    await this.prepareRequest(req, { url, options });
    const requestLogID = "log_" + (Math.random() * (1 << 24) | 0).toString(16).padStart(6, "0");
    const retryLogStr = retryOfRequestLogID === void 0 ? "" : `, retryOf: ${retryOfRequestLogID}`;
    const startTime = Date.now();
    loggerFor3(this).debug(`[${requestLogID}] sending request`, formatRequestDetails3({
      retryOfRequestLogID,
      method: options.method,
      url,
      options,
      headers: req.headers
    }));
    if ((_c = options.signal) === null || _c === void 0 ? void 0 : _c.aborted) {
      throw new APIUserAbortError3();
    }
    const controller = new AbortController();
    const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError3);
    const headersTime = Date.now();
    if (response instanceof globalThis.Error) {
      const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
      if ((_d = options.signal) === null || _d === void 0 ? void 0 : _d.aborted) {
        throw new APIUserAbortError3();
      }
      const isTimeout = isAbortError3(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : ""));
      if (retriesRemaining) {
        loggerFor3(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`);
        loggerFor3(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails3({
          retryOfRequestLogID,
          url,
          durationMs: headersTime - startTime,
          message: response.message
        }));
        return this.retryRequest(options, retriesRemaining, retryOfRequestLogID !== null && retryOfRequestLogID !== void 0 ? retryOfRequestLogID : requestLogID);
      }
      loggerFor3(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - error; no more retries left`);
      loggerFor3(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (error; no more retries left)`, formatRequestDetails3({
        retryOfRequestLogID,
        url,
        durationMs: headersTime - startTime,
        message: response.message
      }));
      if (isTimeout) {
        throw new APIConnectionTimeoutError3();
      }
      throw new APIConnectionError3({ cause: response });
    }
    const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${response.ok ? "succeeded" : "failed"} with status ${response.status} in ${headersTime - startTime}ms`;
    if (!response.ok) {
      const shouldRetry = await this.shouldRetry(response);
      if (retriesRemaining && shouldRetry) {
        const retryMessage2 = `retrying, ${retriesRemaining} attempts remaining`;
        await CancelReadableStream3(response.body);
        loggerFor3(this).info(`${responseInfo} - ${retryMessage2}`);
        loggerFor3(this).debug(`[${requestLogID}] response error (${retryMessage2})`, formatRequestDetails3({
          retryOfRequestLogID,
          url: response.url,
          status: response.status,
          headers: response.headers,
          durationMs: headersTime - startTime
        }));
        return this.retryRequest(options, retriesRemaining, retryOfRequestLogID !== null && retryOfRequestLogID !== void 0 ? retryOfRequestLogID : requestLogID, response.headers);
      }
      const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
      loggerFor3(this).info(`${responseInfo} - ${retryMessage}`);
      const errText = await response.text().catch((err2) => castToError3(err2).message);
      const errJSON = safeJSON3(errText);
      const errMessage = errJSON ? void 0 : errText;
      loggerFor3(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails3({
        retryOfRequestLogID,
        url: response.url,
        status: response.status,
        headers: response.headers,
        message: errMessage,
        durationMs: Date.now() - startTime
      }));
      const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);
      throw err;
    }
    loggerFor3(this).info(responseInfo);
    loggerFor3(this).debug(`[${requestLogID}] response start`, formatRequestDetails3({
      retryOfRequestLogID,
      url: response.url,
      status: response.status,
      headers: response.headers,
      durationMs: headersTime - startTime
    }));
    return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };
  }
  async fetchWithTimeout(url, init, ms, controller) {
    const _b = init || {}, { signal, method } = _b, options = __rest(_b, ["signal", "method"]);
    const abort = this._makeAbort(controller);
    if (signal)
      signal.addEventListener("abort", abort, { once: true });
    const timeout = setTimeout(abort, ms);
    const isReadableBody = globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream || typeof options.body === "object" && options.body !== null && Symbol.asyncIterator in options.body;
    const fetchOptions = Object.assign(Object.assign(Object.assign({ signal: controller.signal }, isReadableBody ? { duplex: "half" } : {}), { method: "GET" }), options);
    if (method) {
      fetchOptions.method = method.toUpperCase();
    }
    try {
      return await this.fetch.call(void 0, url, fetchOptions);
    } finally {
      clearTimeout(timeout);
    }
  }
  async shouldRetry(response) {
    const shouldRetryHeader = response.headers.get("x-should-retry");
    if (shouldRetryHeader === "true")
      return true;
    if (shouldRetryHeader === "false")
      return false;
    if (response.status === 408)
      return true;
    if (response.status === 409)
      return true;
    if (response.status === 429)
      return true;
    if (response.status >= 500)
      return true;
    return false;
  }
  async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) {
    var _b;
    let timeoutMillis;
    const retryAfterMillisHeader = responseHeaders === null || responseHeaders === void 0 ? void 0 : responseHeaders.get("retry-after-ms");
    if (retryAfterMillisHeader) {
      const timeoutMs = parseFloat(retryAfterMillisHeader);
      if (!Number.isNaN(timeoutMs)) {
        timeoutMillis = timeoutMs;
      }
    }
    const retryAfterHeader = responseHeaders === null || responseHeaders === void 0 ? void 0 : responseHeaders.get("retry-after");
    if (retryAfterHeader && !timeoutMillis) {
      const timeoutSeconds = parseFloat(retryAfterHeader);
      if (!Number.isNaN(timeoutSeconds)) {
        timeoutMillis = timeoutSeconds * 1e3;
      } else {
        timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
      }
    }
    if (timeoutMillis === void 0) {
      const maxRetries = (_b = options.maxRetries) !== null && _b !== void 0 ? _b : this.maxRetries;
      timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
    }
    await sleep$1(timeoutMillis);
    return this.makeRequest(options, retriesRemaining - 1, requestLogID);
  }
  calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
    const initialRetryDelay = 0.5;
    const maxRetryDelay = 8;
    const numRetries = maxRetries - retriesRemaining;
    const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
    const jitter = 1 - Math.random() * 0.25;
    return sleepSeconds * jitter * 1e3;
  }
  async buildRequest(inputOptions, { retryCount = 0 } = {}) {
    var _b, _c, _d;
    const options = Object.assign({}, inputOptions);
    const { method, path: path6, query, defaultBaseURL } = options;
    const url = this.buildURL(path6, query, defaultBaseURL);
    if ("timeout" in options)
      validatePositiveInteger3("timeout", options.timeout);
    options.timeout = (_b = options.timeout) !== null && _b !== void 0 ? _b : this.timeout;
    const { bodyHeaders, body } = this.buildBody({ options });
    const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
    const req = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ method, headers: reqHeaders }, options.signal && { signal: options.signal }), globalThis.ReadableStream && body instanceof globalThis.ReadableStream && { duplex: "half" }), body && { body }), (_c = this.fetchOptions) !== null && _c !== void 0 ? _c : {}), (_d = options.fetchOptions) !== null && _d !== void 0 ? _d : {});
    return { req, url, timeout: options.timeout };
  }
  async buildHeaders({ options, method, bodyHeaders, retryCount }) {
    let idempotencyHeaders = {};
    if (this.idempotencyHeader && method !== "get") {
      if (!options.idempotencyKey)
        options.idempotencyKey = this.defaultIdempotencyKey();
      idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey;
    }
    const authHeaders = await this.authHeaders(options);
    let headers = buildHeaders3([
      idempotencyHeaders,
      { Accept: "application/json", "User-Agent": this.getUserAgent() },
      this._options.defaultHeaders,
      bodyHeaders,
      options.headers,
      authHeaders
    ]);
    this.validateHeaders(headers);
    return headers.values;
  }
  _makeAbort(controller) {
    return () => controller.abort();
  }
  buildBody({ options: { body, headers: rawHeaders } }) {
    if (!body) {
      return { bodyHeaders: void 0, body: void 0 };
    }
    const headers = buildHeaders3([rawHeaders]);
    if (
      // Pass raw type verbatim
      ArrayBuffer.isView(body) || body instanceof ArrayBuffer || body instanceof DataView || typeof body === "string" && // Preserve legacy string encoding behavior for now
      headers.values.has("content-type") || // `Blob` is superset of `File`
      globalThis.Blob && body instanceof globalThis.Blob || // `FormData` -> `multipart/form-data`
      body instanceof FormData || // `URLSearchParams` -> `application/x-www-form-urlencoded`
      body instanceof URLSearchParams || // Send chunked stream (each chunk has own `length`)
      globalThis.ReadableStream && body instanceof globalThis.ReadableStream
    ) {
      return { bodyHeaders: void 0, body };
    } else if (typeof body === "object" && (Symbol.asyncIterator in body || Symbol.iterator in body && "next" in body && typeof body.next === "function")) {
      return { bodyHeaders: void 0, body: ReadableStreamFrom3(body) };
    } else if (typeof body === "object" && headers.values.get("content-type") === "application/x-www-form-urlencoded") {
      return {
        bodyHeaders: { "content-type": "application/x-www-form-urlencoded" },
        body: this.stringifyQuery(body)
      };
    } else {
      return this.encoder({ body, headers });
    }
  }
};
BaseGeminiNextGenAPIClient.DEFAULT_TIMEOUT = 6e4;
var GeminiNextGenAPIClient = class extends BaseGeminiNextGenAPIClient {
  constructor() {
    super(...arguments);
    this.interactions = new Interactions(this);
  }
};
_a4 = GeminiNextGenAPIClient;
GeminiNextGenAPIClient.GeminiNextGenAPIClient = _a4;
GeminiNextGenAPIClient.GeminiNextGenAPIClientError = GeminiNextGenAPIClientError;
GeminiNextGenAPIClient.APIError = APIError3;
GeminiNextGenAPIClient.APIConnectionError = APIConnectionError3;
GeminiNextGenAPIClient.APIConnectionTimeoutError = APIConnectionTimeoutError3;
GeminiNextGenAPIClient.APIUserAbortError = APIUserAbortError3;
GeminiNextGenAPIClient.NotFoundError = NotFoundError3;
GeminiNextGenAPIClient.ConflictError = ConflictError3;
GeminiNextGenAPIClient.RateLimitError = RateLimitError3;
GeminiNextGenAPIClient.BadRequestError = BadRequestError3;
GeminiNextGenAPIClient.AuthenticationError = AuthenticationError3;
GeminiNextGenAPIClient.InternalServerError = InternalServerError3;
GeminiNextGenAPIClient.PermissionDeniedError = PermissionDeniedError3;
GeminiNextGenAPIClient.UnprocessableEntityError = UnprocessableEntityError3;
GeminiNextGenAPIClient.toFile = toFile3;
GeminiNextGenAPIClient.Interactions = Interactions;
function cancelTuningJobParametersToMldev(fromObject, _rootObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], fromName);
  }
  return toObject;
}
function cancelTuningJobParametersToVertex(fromObject, _rootObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], fromName);
  }
  return toObject;
}
function cancelTuningJobResponseFromMldev(fromObject, _rootObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  return toObject;
}
function cancelTuningJobResponseFromVertex(fromObject, _rootObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  return toObject;
}
function createTuningJobConfigToMldev(fromObject, parentObject, _rootObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["validationDataset"]) !== void 0) {
    throw new Error("validationDataset parameter is not supported in Gemini API.");
  }
  const fromTunedModelDisplayName = getValueByPath(fromObject, [
    "tunedModelDisplayName"
  ]);
  if (parentObject !== void 0 && fromTunedModelDisplayName != null) {
    setValueByPath(parentObject, ["displayName"], fromTunedModelDisplayName);
  }
  if (getValueByPath(fromObject, ["description"]) !== void 0) {
    throw new Error("description parameter is not supported in Gemini API.");
  }
  const fromEpochCount = getValueByPath(fromObject, ["epochCount"]);
  if (parentObject !== void 0 && fromEpochCount != null) {
    setValueByPath(parentObject, ["tuningTask", "hyperparameters", "epochCount"], fromEpochCount);
  }
  const fromLearningRateMultiplier = getValueByPath(fromObject, [
    "learningRateMultiplier"
  ]);
  if (fromLearningRateMultiplier != null) {
    setValueByPath(toObject, ["tuningTask", "hyperparameters", "learningRateMultiplier"], fromLearningRateMultiplier);
  }
  if (getValueByPath(fromObject, ["exportLastCheckpointOnly"]) !== void 0) {
    throw new Error("exportLastCheckpointOnly parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["preTunedModelCheckpointId"]) !== void 0) {
    throw new Error("preTunedModelCheckpointId parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["adapterSize"]) !== void 0) {
    throw new Error("adapterSize parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["tuningMode"]) !== void 0) {
    throw new Error("tuningMode parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["customBaseModel"]) !== void 0) {
    throw new Error("customBaseModel parameter is not supported in Gemini API.");
  }
  const fromBatchSize = getValueByPath(fromObject, ["batchSize"]);
  if (parentObject !== void 0 && fromBatchSize != null) {
    setValueByPath(parentObject, ["tuningTask", "hyperparameters", "batchSize"], fromBatchSize);
  }
  const fromLearningRate = getValueByPath(fromObject, ["learningRate"]);
  if (parentObject !== void 0 && fromLearningRate != null) {
    setValueByPath(parentObject, ["tuningTask", "hyperparameters", "learningRate"], fromLearningRate);
  }
  if (getValueByPath(fromObject, ["labels"]) !== void 0) {
    throw new Error("labels parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["beta"]) !== void 0) {
    throw new Error("beta parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["baseTeacherModel"]) !== void 0) {
    throw new Error("baseTeacherModel parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["tunedTeacherModelSource"]) !== void 0) {
    throw new Error("tunedTeacherModelSource parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["sftLossWeightMultiplier"]) !== void 0) {
    throw new Error("sftLossWeightMultiplier parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["outputUri"]) !== void 0) {
    throw new Error("outputUri parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["encryptionSpec"]) !== void 0) {
    throw new Error("encryptionSpec parameter is not supported in Gemini API.");
  }
  return toObject;
}
function createTuningJobConfigToVertex(fromObject, parentObject, rootObject) {
  const toObject = {};
  let discriminatorValidationDataset = getValueByPath(rootObject, [
    "config",
    "method"
  ]);
  if (discriminatorValidationDataset === void 0) {
    discriminatorValidationDataset = "SUPERVISED_FINE_TUNING";
  }
  if (discriminatorValidationDataset === "SUPERVISED_FINE_TUNING") {
    const fromValidationDataset = getValueByPath(fromObject, [
      "validationDataset"
    ]);
    if (parentObject !== void 0 && fromValidationDataset != null) {
      setValueByPath(parentObject, ["supervisedTuningSpec"], tuningValidationDatasetToVertex(fromValidationDataset));
    }
  } else if (discriminatorValidationDataset === "PREFERENCE_TUNING") {
    const fromValidationDataset = getValueByPath(fromObject, [
      "validationDataset"
    ]);
    if (parentObject !== void 0 && fromValidationDataset != null) {
      setValueByPath(parentObject, ["preferenceOptimizationSpec"], tuningValidationDatasetToVertex(fromValidationDataset));
    }
  } else if (discriminatorValidationDataset === "DISTILLATION") {
    const fromValidationDataset = getValueByPath(fromObject, [
      "validationDataset"
    ]);
    if (parentObject !== void 0 && fromValidationDataset != null) {
      setValueByPath(parentObject, ["distillationSpec"], tuningValidationDatasetToVertex(fromValidationDataset));
    }
  }
  const fromTunedModelDisplayName = getValueByPath(fromObject, [
    "tunedModelDisplayName"
  ]);
  if (parentObject !== void 0 && fromTunedModelDisplayName != null) {
    setValueByPath(parentObject, ["tunedModelDisplayName"], fromTunedModelDisplayName);
  }
  const fromDescription = getValueByPath(fromObject, ["description"]);
  if (parentObject !== void 0 && fromDescription != null) {
    setValueByPath(parentObject, ["description"], fromDescription);
  }
  let discriminatorEpochCount = getValueByPath(rootObject, [
    "config",
    "method"
  ]);
  if (discriminatorEpochCount === void 0) {
    discriminatorEpochCount = "SUPERVISED_FINE_TUNING";
  }
  if (discriminatorEpochCount === "SUPERVISED_FINE_TUNING") {
    const fromEpochCount = getValueByPath(fromObject, ["epochCount"]);
    if (parentObject !== void 0 && fromEpochCount != null) {
      setValueByPath(parentObject, ["supervisedTuningSpec", "hyperParameters", "epochCount"], fromEpochCount);
    }
  } else if (discriminatorEpochCount === "PREFERENCE_TUNING") {
    const fromEpochCount = getValueByPath(fromObject, ["epochCount"]);
    if (parentObject !== void 0 && fromEpochCount != null) {
      setValueByPath(parentObject, ["preferenceOptimizationSpec", "hyperParameters", "epochCount"], fromEpochCount);
    }
  } else if (discriminatorEpochCount === "DISTILLATION") {
    const fromEpochCount = getValueByPath(fromObject, ["epochCount"]);
    if (parentObject !== void 0 && fromEpochCount != null) {
      setValueByPath(parentObject, ["distillationSpec", "hyperParameters", "epochCount"], fromEpochCount);
    }
  }
  let discriminatorLearningRateMultiplier = getValueByPath(rootObject, [
    "config",
    "method"
  ]);
  if (discriminatorLearningRateMultiplier === void 0) {
    discriminatorLearningRateMultiplier = "SUPERVISED_FINE_TUNING";
  }
  if (discriminatorLearningRateMultiplier === "SUPERVISED_FINE_TUNING") {
    const fromLearningRateMultiplier = getValueByPath(fromObject, [
      "learningRateMultiplier"
    ]);
    if (parentObject !== void 0 && fromLearningRateMultiplier != null) {
      setValueByPath(parentObject, ["supervisedTuningSpec", "hyperParameters", "learningRateMultiplier"], fromLearningRateMultiplier);
    }
  } else if (discriminatorLearningRateMultiplier === "PREFERENCE_TUNING") {
    const fromLearningRateMultiplier = getValueByPath(fromObject, [
      "learningRateMultiplier"
    ]);
    if (parentObject !== void 0 && fromLearningRateMultiplier != null) {
      setValueByPath(parentObject, [
        "preferenceOptimizationSpec",
        "hyperParameters",
        "learningRateMultiplier"
      ], fromLearningRateMultiplier);
    }
  } else if (discriminatorLearningRateMultiplier === "DISTILLATION") {
    const fromLearningRateMultiplier = getValueByPath(fromObject, [
      "learningRateMultiplier"
    ]);
    if (parentObject !== void 0 && fromLearningRateMultiplier != null) {
      setValueByPath(parentObject, ["distillationSpec", "hyperParameters", "learningRateMultiplier"], fromLearningRateMultiplier);
    }
  }
  let discriminatorExportLastCheckpointOnly = getValueByPath(rootObject, ["config", "method"]);
  if (discriminatorExportLastCheckpointOnly === void 0) {
    discriminatorExportLastCheckpointOnly = "SUPERVISED_FINE_TUNING";
  }
  if (discriminatorExportLastCheckpointOnly === "SUPERVISED_FINE_TUNING") {
    const fromExportLastCheckpointOnly = getValueByPath(fromObject, [
      "exportLastCheckpointOnly"
    ]);
    if (parentObject !== void 0 && fromExportLastCheckpointOnly != null) {
      setValueByPath(parentObject, ["supervisedTuningSpec", "exportLastCheckpointOnly"], fromExportLastCheckpointOnly);
    }
  } else if (discriminatorExportLastCheckpointOnly === "PREFERENCE_TUNING") {
    const fromExportLastCheckpointOnly = getValueByPath(fromObject, [
      "exportLastCheckpointOnly"
    ]);
    if (parentObject !== void 0 && fromExportLastCheckpointOnly != null) {
      setValueByPath(parentObject, ["preferenceOptimizationSpec", "exportLastCheckpointOnly"], fromExportLastCheckpointOnly);
    }
  } else if (discriminatorExportLastCheckpointOnly === "DISTILLATION") {
    const fromExportLastCheckpointOnly = getValueByPath(fromObject, [
      "exportLastCheckpointOnly"
    ]);
    if (parentObject !== void 0 && fromExportLastCheckpointOnly != null) {
      setValueByPath(parentObject, ["distillationSpec", "exportLastCheckpointOnly"], fromExportLastCheckpointOnly);
    }
  }
  let discriminatorAdapterSize = getValueByPath(rootObject, [
    "config",
    "method"
  ]);
  if (discriminatorAdapterSize === void 0) {
    discriminatorAdapterSize = "SUPERVISED_FINE_TUNING";
  }
  if (discriminatorAdapterSize === "SUPERVISED_FINE_TUNING") {
    const fromAdapterSize = getValueByPath(fromObject, ["adapterSize"]);
    if (parentObject !== void 0 && fromAdapterSize != null) {
      setValueByPath(parentObject, ["supervisedTuningSpec", "hyperParameters", "adapterSize"], fromAdapterSize);
    }
  } else if (discriminatorAdapterSize === "PREFERENCE_TUNING") {
    const fromAdapterSize = getValueByPath(fromObject, ["adapterSize"]);
    if (parentObject !== void 0 && fromAdapterSize != null) {
      setValueByPath(parentObject, ["preferenceOptimizationSpec", "hyperParameters", "adapterSize"], fromAdapterSize);
    }
  } else if (discriminatorAdapterSize === "DISTILLATION") {
    const fromAdapterSize = getValueByPath(fromObject, ["adapterSize"]);
    if (parentObject !== void 0 && fromAdapterSize != null) {
      setValueByPath(parentObject, ["distillationSpec", "hyperParameters", "adapterSize"], fromAdapterSize);
    }
  }
  let discriminatorTuningMode = getValueByPath(rootObject, [
    "config",
    "method"
  ]);
  if (discriminatorTuningMode === void 0) {
    discriminatorTuningMode = "SUPERVISED_FINE_TUNING";
  }
  if (discriminatorTuningMode === "SUPERVISED_FINE_TUNING") {
    const fromTuningMode = getValueByPath(fromObject, ["tuningMode"]);
    if (parentObject !== void 0 && fromTuningMode != null) {
      setValueByPath(parentObject, ["supervisedTuningSpec", "tuningMode"], fromTuningMode);
    }
  }
  const fromCustomBaseModel = getValueByPath(fromObject, [
    "customBaseModel"
  ]);
  if (parentObject !== void 0 && fromCustomBaseModel != null) {
    setValueByPath(parentObject, ["customBaseModel"], fromCustomBaseModel);
  }
  let discriminatorBatchSize = getValueByPath(rootObject, [
    "config",
    "method"
  ]);
  if (discriminatorBatchSize === void 0) {
    discriminatorBatchSize = "SUPERVISED_FINE_TUNING";
  }
  if (discriminatorBatchSize === "SUPERVISED_FINE_TUNING") {
    const fromBatchSize = getValueByPath(fromObject, ["batchSize"]);
    if (parentObject !== void 0 && fromBatchSize != null) {
      setValueByPath(parentObject, ["supervisedTuningSpec", "hyperParameters", "batchSize"], fromBatchSize);
    }
  }
  let discriminatorLearningRate = getValueByPath(rootObject, [
    "config",
    "method"
  ]);
  if (discriminatorLearningRate === void 0) {
    discriminatorLearningRate = "SUPERVISED_FINE_TUNING";
  }
  if (discriminatorLearningRate === "SUPERVISED_FINE_TUNING") {
    const fromLearningRate = getValueByPath(fromObject, [
      "learningRate"
    ]);
    if (parentObject !== void 0 && fromLearningRate != null) {
      setValueByPath(parentObject, ["supervisedTuningSpec", "hyperParameters", "learningRate"], fromLearningRate);
    }
  }
  const fromLabels = getValueByPath(fromObject, ["labels"]);
  if (parentObject !== void 0 && fromLabels != null) {
    setValueByPath(parentObject, ["labels"], fromLabels);
  }
  const fromBeta = getValueByPath(fromObject, ["beta"]);
  if (parentObject !== void 0 && fromBeta != null) {
    setValueByPath(parentObject, ["preferenceOptimizationSpec", "hyperParameters", "beta"], fromBeta);
  }
  const fromBaseTeacherModel = getValueByPath(fromObject, [
    "baseTeacherModel"
  ]);
  if (parentObject !== void 0 && fromBaseTeacherModel != null) {
    setValueByPath(parentObject, ["distillationSpec", "baseTeacherModel"], fromBaseTeacherModel);
  }
  const fromTunedTeacherModelSource = getValueByPath(fromObject, [
    "tunedTeacherModelSource"
  ]);
  if (parentObject !== void 0 && fromTunedTeacherModelSource != null) {
    setValueByPath(parentObject, ["distillationSpec", "tunedTeacherModelSource"], fromTunedTeacherModelSource);
  }
  const fromSftLossWeightMultiplier = getValueByPath(fromObject, [
    "sftLossWeightMultiplier"
  ]);
  if (parentObject !== void 0 && fromSftLossWeightMultiplier != null) {
    setValueByPath(parentObject, ["distillationSpec", "hyperParameters", "sftLossWeightMultiplier"], fromSftLossWeightMultiplier);
  }
  const fromOutputUri = getValueByPath(fromObject, ["outputUri"]);
  if (parentObject !== void 0 && fromOutputUri != null) {
    setValueByPath(parentObject, ["outputUri"], fromOutputUri);
  }
  const fromEncryptionSpec = getValueByPath(fromObject, [
    "encryptionSpec"
  ]);
  if (parentObject !== void 0 && fromEncryptionSpec != null) {
    setValueByPath(parentObject, ["encryptionSpec"], fromEncryptionSpec);
  }
  return toObject;
}
function createTuningJobParametersPrivateToMldev(fromObject, rootObject) {
  const toObject = {};
  const fromBaseModel = getValueByPath(fromObject, ["baseModel"]);
  if (fromBaseModel != null) {
    setValueByPath(toObject, ["baseModel"], fromBaseModel);
  }
  const fromPreTunedModel = getValueByPath(fromObject, [
    "preTunedModel"
  ]);
  if (fromPreTunedModel != null) {
    setValueByPath(toObject, ["preTunedModel"], fromPreTunedModel);
  }
  const fromTrainingDataset = getValueByPath(fromObject, [
    "trainingDataset"
  ]);
  if (fromTrainingDataset != null) {
    tuningDatasetToMldev(fromTrainingDataset);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    createTuningJobConfigToMldev(fromConfig, toObject);
  }
  return toObject;
}
function createTuningJobParametersPrivateToVertex(fromObject, rootObject) {
  const toObject = {};
  const fromBaseModel = getValueByPath(fromObject, ["baseModel"]);
  if (fromBaseModel != null) {
    setValueByPath(toObject, ["baseModel"], fromBaseModel);
  }
  const fromPreTunedModel = getValueByPath(fromObject, [
    "preTunedModel"
  ]);
  if (fromPreTunedModel != null) {
    setValueByPath(toObject, ["preTunedModel"], fromPreTunedModel);
  }
  const fromTrainingDataset = getValueByPath(fromObject, [
    "trainingDataset"
  ]);
  if (fromTrainingDataset != null) {
    tuningDatasetToVertex(fromTrainingDataset, toObject, rootObject);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    createTuningJobConfigToVertex(fromConfig, toObject, rootObject);
  }
  return toObject;
}
function getTuningJobParametersToMldev(fromObject, _rootObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], fromName);
  }
  return toObject;
}
function getTuningJobParametersToVertex(fromObject, _rootObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], fromName);
  }
  return toObject;
}
function listTuningJobsConfigToMldev(fromObject, parentObject, _rootObject) {
  const toObject = {};
  const fromPageSize = getValueByPath(fromObject, ["pageSize"]);
  if (parentObject !== void 0 && fromPageSize != null) {
    setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize);
  }
  const fromPageToken = getValueByPath(fromObject, ["pageToken"]);
  if (parentObject !== void 0 && fromPageToken != null) {
    setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken);
  }
  const fromFilter = getValueByPath(fromObject, ["filter"]);
  if (parentObject !== void 0 && fromFilter != null) {
    setValueByPath(parentObject, ["_query", "filter"], fromFilter);
  }
  return toObject;
}
function listTuningJobsConfigToVertex(fromObject, parentObject, _rootObject) {
  const toObject = {};
  const fromPageSize = getValueByPath(fromObject, ["pageSize"]);
  if (parentObject !== void 0 && fromPageSize != null) {
    setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize);
  }
  const fromPageToken = getValueByPath(fromObject, ["pageToken"]);
  if (parentObject !== void 0 && fromPageToken != null) {
    setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken);
  }
  const fromFilter = getValueByPath(fromObject, ["filter"]);
  if (parentObject !== void 0 && fromFilter != null) {
    setValueByPath(parentObject, ["_query", "filter"], fromFilter);
  }
  return toObject;
}
function listTuningJobsParametersToMldev(fromObject, rootObject) {
  const toObject = {};
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    listTuningJobsConfigToMldev(fromConfig, toObject);
  }
  return toObject;
}
function listTuningJobsParametersToVertex(fromObject, rootObject) {
  const toObject = {};
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    listTuningJobsConfigToVertex(fromConfig, toObject);
  }
  return toObject;
}
function listTuningJobsResponseFromMldev(fromObject, rootObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromNextPageToken = getValueByPath(fromObject, [
    "nextPageToken"
  ]);
  if (fromNextPageToken != null) {
    setValueByPath(toObject, ["nextPageToken"], fromNextPageToken);
  }
  const fromTuningJobs = getValueByPath(fromObject, ["tunedModels"]);
  if (fromTuningJobs != null) {
    let transformedList = fromTuningJobs;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return tuningJobFromMldev(item);
      });
    }
    setValueByPath(toObject, ["tuningJobs"], transformedList);
  }
  return toObject;
}
function listTuningJobsResponseFromVertex(fromObject, rootObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromNextPageToken = getValueByPath(fromObject, [
    "nextPageToken"
  ]);
  if (fromNextPageToken != null) {
    setValueByPath(toObject, ["nextPageToken"], fromNextPageToken);
  }
  const fromTuningJobs = getValueByPath(fromObject, ["tuningJobs"]);
  if (fromTuningJobs != null) {
    let transformedList = fromTuningJobs;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return tuningJobFromVertex(item);
      });
    }
    setValueByPath(toObject, ["tuningJobs"], transformedList);
  }
  return toObject;
}
function tunedModelFromMldev(fromObject, _rootObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["name"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["model"], fromModel);
  }
  const fromEndpoint = getValueByPath(fromObject, ["name"]);
  if (fromEndpoint != null) {
    setValueByPath(toObject, ["endpoint"], fromEndpoint);
  }
  return toObject;
}
function tuningDatasetToMldev(fromObject, _rootObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["gcsUri"]) !== void 0) {
    throw new Error("gcsUri parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["vertexDatasetResource"]) !== void 0) {
    throw new Error("vertexDatasetResource parameter is not supported in Gemini API.");
  }
  const fromExamples = getValueByPath(fromObject, ["examples"]);
  if (fromExamples != null) {
    let transformedList = fromExamples;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["examples", "examples"], transformedList);
  }
  return toObject;
}
function tuningDatasetToVertex(fromObject, parentObject, rootObject) {
  const toObject = {};
  let discriminatorGcsUri = getValueByPath(rootObject, [
    "config",
    "method"
  ]);
  if (discriminatorGcsUri === void 0) {
    discriminatorGcsUri = "SUPERVISED_FINE_TUNING";
  }
  if (discriminatorGcsUri === "SUPERVISED_FINE_TUNING") {
    const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]);
    if (parentObject !== void 0 && fromGcsUri != null) {
      setValueByPath(parentObject, ["supervisedTuningSpec", "trainingDatasetUri"], fromGcsUri);
    }
  } else if (discriminatorGcsUri === "PREFERENCE_TUNING") {
    const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]);
    if (parentObject !== void 0 && fromGcsUri != null) {
      setValueByPath(parentObject, ["preferenceOptimizationSpec", "trainingDatasetUri"], fromGcsUri);
    }
  } else if (discriminatorGcsUri === "DISTILLATION") {
    const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]);
    if (parentObject !== void 0 && fromGcsUri != null) {
      setValueByPath(parentObject, ["distillationSpec", "promptDatasetUri"], fromGcsUri);
    }
  }
  let discriminatorVertexDatasetResource = getValueByPath(rootObject, [
    "config",
    "method"
  ]);
  if (discriminatorVertexDatasetResource === void 0) {
    discriminatorVertexDatasetResource = "SUPERVISED_FINE_TUNING";
  }
  if (discriminatorVertexDatasetResource === "SUPERVISED_FINE_TUNING") {
    const fromVertexDatasetResource = getValueByPath(fromObject, [
      "vertexDatasetResource"
    ]);
    if (parentObject !== void 0 && fromVertexDatasetResource != null) {
      setValueByPath(parentObject, ["supervisedTuningSpec", "trainingDatasetUri"], fromVertexDatasetResource);
    }
  } else if (discriminatorVertexDatasetResource === "PREFERENCE_TUNING") {
    const fromVertexDatasetResource = getValueByPath(fromObject, [
      "vertexDatasetResource"
    ]);
    if (parentObject !== void 0 && fromVertexDatasetResource != null) {
      setValueByPath(parentObject, ["preferenceOptimizationSpec", "trainingDatasetUri"], fromVertexDatasetResource);
    }
  } else if (discriminatorVertexDatasetResource === "DISTILLATION") {
    const fromVertexDatasetResource = getValueByPath(fromObject, [
      "vertexDatasetResource"
    ]);
    if (parentObject !== void 0 && fromVertexDatasetResource != null) {
      setValueByPath(parentObject, ["distillationSpec", "promptDatasetUri"], fromVertexDatasetResource);
    }
  }
  if (getValueByPath(fromObject, ["examples"]) !== void 0) {
    throw new Error("examples parameter is not supported in Vertex AI.");
  }
  return toObject;
}
function tuningJobFromMldev(fromObject, rootObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromState = getValueByPath(fromObject, ["state"]);
  if (fromState != null) {
    setValueByPath(toObject, ["state"], tTuningJobStatus(fromState));
  }
  const fromCreateTime = getValueByPath(fromObject, ["createTime"]);
  if (fromCreateTime != null) {
    setValueByPath(toObject, ["createTime"], fromCreateTime);
  }
  const fromStartTime = getValueByPath(fromObject, [
    "tuningTask",
    "startTime"
  ]);
  if (fromStartTime != null) {
    setValueByPath(toObject, ["startTime"], fromStartTime);
  }
  const fromEndTime = getValueByPath(fromObject, [
    "tuningTask",
    "completeTime"
  ]);
  if (fromEndTime != null) {
    setValueByPath(toObject, ["endTime"], fromEndTime);
  }
  const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]);
  if (fromUpdateTime != null) {
    setValueByPath(toObject, ["updateTime"], fromUpdateTime);
  }
  const fromDescription = getValueByPath(fromObject, ["description"]);
  if (fromDescription != null) {
    setValueByPath(toObject, ["description"], fromDescription);
  }
  const fromBaseModel = getValueByPath(fromObject, ["baseModel"]);
  if (fromBaseModel != null) {
    setValueByPath(toObject, ["baseModel"], fromBaseModel);
  }
  const fromTunedModel = getValueByPath(fromObject, ["_self"]);
  if (fromTunedModel != null) {
    setValueByPath(toObject, ["tunedModel"], tunedModelFromMldev(fromTunedModel));
  }
  return toObject;
}
function tuningJobFromVertex(fromObject, _rootObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromState = getValueByPath(fromObject, ["state"]);
  if (fromState != null) {
    setValueByPath(toObject, ["state"], tTuningJobStatus(fromState));
  }
  const fromCreateTime = getValueByPath(fromObject, ["createTime"]);
  if (fromCreateTime != null) {
    setValueByPath(toObject, ["createTime"], fromCreateTime);
  }
  const fromStartTime = getValueByPath(fromObject, ["startTime"]);
  if (fromStartTime != null) {
    setValueByPath(toObject, ["startTime"], fromStartTime);
  }
  const fromEndTime = getValueByPath(fromObject, ["endTime"]);
  if (fromEndTime != null) {
    setValueByPath(toObject, ["endTime"], fromEndTime);
  }
  const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]);
  if (fromUpdateTime != null) {
    setValueByPath(toObject, ["updateTime"], fromUpdateTime);
  }
  const fromError = getValueByPath(fromObject, ["error"]);
  if (fromError != null) {
    setValueByPath(toObject, ["error"], fromError);
  }
  const fromDescription = getValueByPath(fromObject, ["description"]);
  if (fromDescription != null) {
    setValueByPath(toObject, ["description"], fromDescription);
  }
  const fromBaseModel = getValueByPath(fromObject, ["baseModel"]);
  if (fromBaseModel != null) {
    setValueByPath(toObject, ["baseModel"], fromBaseModel);
  }
  const fromTunedModel = getValueByPath(fromObject, ["tunedModel"]);
  if (fromTunedModel != null) {
    setValueByPath(toObject, ["tunedModel"], fromTunedModel);
  }
  const fromPreTunedModel = getValueByPath(fromObject, [
    "preTunedModel"
  ]);
  if (fromPreTunedModel != null) {
    setValueByPath(toObject, ["preTunedModel"], fromPreTunedModel);
  }
  const fromSupervisedTuningSpec = getValueByPath(fromObject, [
    "supervisedTuningSpec"
  ]);
  if (fromSupervisedTuningSpec != null) {
    setValueByPath(toObject, ["supervisedTuningSpec"], fromSupervisedTuningSpec);
  }
  const fromPreferenceOptimizationSpec = getValueByPath(fromObject, [
    "preferenceOptimizationSpec"
  ]);
  if (fromPreferenceOptimizationSpec != null) {
    setValueByPath(toObject, ["preferenceOptimizationSpec"], fromPreferenceOptimizationSpec);
  }
  const fromDistillationSpec = getValueByPath(fromObject, [
    "distillationSpec"
  ]);
  if (fromDistillationSpec != null) {
    setValueByPath(toObject, ["distillationSpec"], fromDistillationSpec);
  }
  const fromTuningDataStats = getValueByPath(fromObject, [
    "tuningDataStats"
  ]);
  if (fromTuningDataStats != null) {
    setValueByPath(toObject, ["tuningDataStats"], fromTuningDataStats);
  }
  const fromEncryptionSpec = getValueByPath(fromObject, [
    "encryptionSpec"
  ]);
  if (fromEncryptionSpec != null) {
    setValueByPath(toObject, ["encryptionSpec"], fromEncryptionSpec);
  }
  const fromPartnerModelTuningSpec = getValueByPath(fromObject, [
    "partnerModelTuningSpec"
  ]);
  if (fromPartnerModelTuningSpec != null) {
    setValueByPath(toObject, ["partnerModelTuningSpec"], fromPartnerModelTuningSpec);
  }
  const fromCustomBaseModel = getValueByPath(fromObject, [
    "customBaseModel"
  ]);
  if (fromCustomBaseModel != null) {
    setValueByPath(toObject, ["customBaseModel"], fromCustomBaseModel);
  }
  const fromEvaluateDatasetRuns = getValueByPath(fromObject, [
    "evaluateDatasetRuns"
  ]);
  if (fromEvaluateDatasetRuns != null) {
    let transformedList = fromEvaluateDatasetRuns;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["evaluateDatasetRuns"], transformedList);
  }
  const fromExperiment = getValueByPath(fromObject, ["experiment"]);
  if (fromExperiment != null) {
    setValueByPath(toObject, ["experiment"], fromExperiment);
  }
  const fromFullFineTuningSpec = getValueByPath(fromObject, [
    "fullFineTuningSpec"
  ]);
  if (fromFullFineTuningSpec != null) {
    setValueByPath(toObject, ["fullFineTuningSpec"], fromFullFineTuningSpec);
  }
  const fromLabels = getValueByPath(fromObject, ["labels"]);
  if (fromLabels != null) {
    setValueByPath(toObject, ["labels"], fromLabels);
  }
  const fromOutputUri = getValueByPath(fromObject, ["outputUri"]);
  if (fromOutputUri != null) {
    setValueByPath(toObject, ["outputUri"], fromOutputUri);
  }
  const fromPipelineJob = getValueByPath(fromObject, ["pipelineJob"]);
  if (fromPipelineJob != null) {
    setValueByPath(toObject, ["pipelineJob"], fromPipelineJob);
  }
  const fromServiceAccount = getValueByPath(fromObject, [
    "serviceAccount"
  ]);
  if (fromServiceAccount != null) {
    setValueByPath(toObject, ["serviceAccount"], fromServiceAccount);
  }
  const fromTunedModelDisplayName = getValueByPath(fromObject, [
    "tunedModelDisplayName"
  ]);
  if (fromTunedModelDisplayName != null) {
    setValueByPath(toObject, ["tunedModelDisplayName"], fromTunedModelDisplayName);
  }
  const fromTuningJobState = getValueByPath(fromObject, [
    "tuningJobState"
  ]);
  if (fromTuningJobState != null) {
    setValueByPath(toObject, ["tuningJobState"], fromTuningJobState);
  }
  const fromVeoTuningSpec = getValueByPath(fromObject, [
    "veoTuningSpec"
  ]);
  if (fromVeoTuningSpec != null) {
    setValueByPath(toObject, ["veoTuningSpec"], fromVeoTuningSpec);
  }
  return toObject;
}
function tuningOperationFromMldev(fromObject, _rootObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromMetadata = getValueByPath(fromObject, ["metadata"]);
  if (fromMetadata != null) {
    setValueByPath(toObject, ["metadata"], fromMetadata);
  }
  const fromDone = getValueByPath(fromObject, ["done"]);
  if (fromDone != null) {
    setValueByPath(toObject, ["done"], fromDone);
  }
  const fromError = getValueByPath(fromObject, ["error"]);
  if (fromError != null) {
    setValueByPath(toObject, ["error"], fromError);
  }
  return toObject;
}
function tuningValidationDatasetToVertex(fromObject, _rootObject) {
  const toObject = {};
  const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]);
  if (fromGcsUri != null) {
    setValueByPath(toObject, ["validationDatasetUri"], fromGcsUri);
  }
  const fromVertexDatasetResource = getValueByPath(fromObject, [
    "vertexDatasetResource"
  ]);
  if (fromVertexDatasetResource != null) {
    setValueByPath(toObject, ["validationDatasetUri"], fromVertexDatasetResource);
  }
  return toObject;
}
var Tunings = class extends BaseModule {
  constructor(apiClient) {
    super();
    this.apiClient = apiClient;
    this.list = async (params = {}) => {
      return new Pager(PagedItem.PAGED_ITEM_TUNING_JOBS, (x2) => this.listInternal(x2), await this.listInternal(params), params);
    };
    this.get = async (params) => {
      return await this.getInternal(params);
    };
    this.tune = async (params) => {
      var _a7;
      if (this.apiClient.isVertexAI()) {
        if (params.baseModel.startsWith("projects/")) {
          const preTunedModel = {
            tunedModelName: params.baseModel
          };
          if ((_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.preTunedModelCheckpointId) {
            preTunedModel.checkpointId = params.config.preTunedModelCheckpointId;
          }
          const paramsPrivate = Object.assign(Object.assign({}, params), { preTunedModel });
          paramsPrivate.baseModel = void 0;
          return await this.tuneInternal(paramsPrivate);
        } else {
          const paramsPrivate = Object.assign({}, params);
          return await this.tuneInternal(paramsPrivate);
        }
      } else {
        const paramsPrivate = Object.assign({}, params);
        const operation = await this.tuneMldevInternal(paramsPrivate);
        let tunedModelName = "";
        if (operation["metadata"] !== void 0 && operation["metadata"]["tunedModel"] !== void 0) {
          tunedModelName = operation["metadata"]["tunedModel"];
        } else if (operation["name"] !== void 0 && operation["name"].includes("/operations/")) {
          tunedModelName = operation["name"].split("/operations/")[0];
        }
        const tuningJob = {
          name: tunedModelName,
          state: JobState.JOB_STATE_QUEUED
        };
        return tuningJob;
      }
    };
  }
  async getInternal(params) {
    var _a7, _b, _c, _d;
    let response;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = getTuningJobParametersToVertex(params);
      path6 = formatMap("{name}", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "GET",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = tuningJobFromVertex(apiResponse);
        return resp;
      });
    } else {
      const body = getTuningJobParametersToMldev(params);
      path6 = formatMap("{name}", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "GET",
        httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,
        abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = tuningJobFromMldev(apiResponse);
        return resp;
      });
    }
  }
  async listInternal(params) {
    var _a7, _b, _c, _d;
    let response;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = listTuningJobsParametersToVertex(params);
      path6 = formatMap("tuningJobs", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "GET",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = listTuningJobsResponseFromVertex(apiResponse);
        const typedResp = new ListTuningJobsResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    } else {
      const body = listTuningJobsParametersToMldev(params);
      path6 = formatMap("tunedModels", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "GET",
        httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,
        abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = listTuningJobsResponseFromMldev(apiResponse);
        const typedResp = new ListTuningJobsResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    }
  }
  /**
   * Cancels a tuning job.
   *
   * @param params - The parameters for the cancel request.
   * @return The empty response returned by the API.
   *
   * @example
   * ```ts
   * await ai.tunings.cancel({name: '...'}); // The server-generated resource name.
   * ```
   */
  async cancel(params) {
    var _a7, _b, _c, _d;
    let response;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = cancelTuningJobParametersToVertex(params);
      path6 = formatMap("{name}:cancel", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = cancelTuningJobResponseFromVertex(apiResponse);
        const typedResp = new CancelTuningJobResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    } else {
      const body = cancelTuningJobParametersToMldev(params);
      path6 = formatMap("{name}:cancel", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,
        abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = cancelTuningJobResponseFromMldev(apiResponse);
        const typedResp = new CancelTuningJobResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    }
  }
  async tuneInternal(params) {
    var _a7, _b;
    let response;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = createTuningJobParametersPrivateToVertex(params, params);
      path6 = formatMap("tuningJobs", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = tuningJobFromVertex(apiResponse);
        return resp;
      });
    } else {
      throw new Error("This method is only supported by the Vertex AI.");
    }
  }
  async tuneMldevInternal(params) {
    var _a7, _b;
    let response;
    let path6 = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      throw new Error("This method is only supported by the Gemini Developer API.");
    } else {
      const body = createTuningJobParametersPrivateToMldev(params);
      path6 = formatMap("tunedModels", body["_url"]);
      queryParams = body["_query"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path: path6,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
        abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = tuningOperationFromMldev(apiResponse);
        return resp;
      });
    }
  }
};
var BrowserDownloader = class {
  async download(_params, _apiClient) {
    throw new Error("Download to file is not supported in the browser, please use a browser compliant download like an <a> tag.");
  }
};
var MAX_CHUNK_SIZE = 1024 * 1024 * 8;
var MAX_RETRY_COUNT = 3;
var INITIAL_RETRY_DELAY_MS = 1e3;
var DELAY_MULTIPLIER = 2;
var X_GOOG_UPLOAD_STATUS_HEADER_FIELD = "x-goog-upload-status";
async function uploadBlob(file, uploadUrl, apiClient) {
  var _a7;
  const response = await uploadBlobInternal(file, uploadUrl, apiClient);
  const responseJson = await (response === null || response === void 0 ? void 0 : response.json());
  if (((_a7 = response === null || response === void 0 ? void 0 : response.headers) === null || _a7 === void 0 ? void 0 : _a7[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== "final") {
    throw new Error("Failed to upload file: Upload status is not finalized.");
  }
  return responseJson["file"];
}
async function uploadBlobToFileSearchStore(file, uploadUrl, apiClient) {
  var _a7;
  const response = await uploadBlobInternal(file, uploadUrl, apiClient);
  const responseJson = await (response === null || response === void 0 ? void 0 : response.json());
  if (((_a7 = response === null || response === void 0 ? void 0 : response.headers) === null || _a7 === void 0 ? void 0 : _a7[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== "final") {
    throw new Error("Failed to upload file: Upload status is not finalized.");
  }
  const resp = uploadToFileSearchStoreOperationFromMldev(responseJson);
  const typedResp = new UploadToFileSearchStoreOperation();
  Object.assign(typedResp, resp);
  return typedResp;
}
async function uploadBlobInternal(file, uploadUrl, apiClient) {
  var _a7, _b;
  let fileSize = 0;
  let offset = 0;
  let response = new HttpResponse(new Response());
  let uploadCommand = "upload";
  fileSize = file.size;
  while (offset < fileSize) {
    const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset);
    const chunk = file.slice(offset, offset + chunkSize);
    if (offset + chunkSize >= fileSize) {
      uploadCommand += ", finalize";
    }
    let retryCount = 0;
    let currentDelayMs = INITIAL_RETRY_DELAY_MS;
    while (retryCount < MAX_RETRY_COUNT) {
      response = await apiClient.request({
        path: "",
        body: chunk,
        httpMethod: "POST",
        httpOptions: {
          apiVersion: "",
          baseUrl: uploadUrl,
          headers: {
            "X-Goog-Upload-Command": uploadCommand,
            "X-Goog-Upload-Offset": String(offset),
            "Content-Length": String(chunkSize)
          }
        }
      });
      if ((_a7 = response === null || response === void 0 ? void 0 : response.headers) === null || _a7 === void 0 ? void 0 : _a7[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) {
        break;
      }
      retryCount++;
      await sleep3(currentDelayMs);
      currentDelayMs = currentDelayMs * DELAY_MULTIPLIER;
    }
    offset += chunkSize;
    if (((_b = response === null || response === void 0 ? void 0 : response.headers) === null || _b === void 0 ? void 0 : _b[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== "active") {
      break;
    }
    if (fileSize <= offset) {
      throw new Error("All content has been uploaded, but the upload status is not finalized.");
    }
  }
  return response;
}
async function getBlobStat(file) {
  const fileStat = { size: file.size, type: file.type };
  return fileStat;
}
function sleep3(ms) {
  return new Promise((resolvePromise) => setTimeout(resolvePromise, ms));
}
var BrowserUploader = class {
  async upload(file, uploadUrl, apiClient) {
    if (typeof file === "string") {
      throw new Error("File path is not supported in browser uploader.");
    }
    return await uploadBlob(file, uploadUrl, apiClient);
  }
  async uploadToFileSearchStore(file, uploadUrl, apiClient) {
    if (typeof file === "string") {
      throw new Error("File path is not supported in browser uploader.");
    }
    return await uploadBlobToFileSearchStore(file, uploadUrl, apiClient);
  }
  async stat(file) {
    if (typeof file === "string") {
      throw new Error("File path is not supported in browser uploader.");
    } else {
      return await getBlobStat(file);
    }
  }
};
var BrowserWebSocketFactory = class {
  create(url, headers, callbacks) {
    return new BrowserWebSocket(url, headers, callbacks);
  }
};
var BrowserWebSocket = class {
  constructor(url, headers, callbacks) {
    this.url = url;
    this.headers = headers;
    this.callbacks = callbacks;
  }
  connect() {
    this.ws = new WebSocket(this.url);
    this.ws.onopen = this.callbacks.onopen;
    this.ws.onerror = this.callbacks.onerror;
    this.ws.onclose = this.callbacks.onclose;
    this.ws.onmessage = this.callbacks.onmessage;
  }
  send(message) {
    if (this.ws === void 0) {
      throw new Error("WebSocket is not connected");
    }
    this.ws.send(message);
  }
  close() {
    if (this.ws === void 0) {
      throw new Error("WebSocket is not connected");
    }
    this.ws.close();
  }
};
var GOOGLE_API_KEY_HEADER = "x-goog-api-key";
var WebAuth = class {
  constructor(apiKey) {
    this.apiKey = apiKey;
  }
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  async addAuthHeaders(headers, url) {
    if (headers.get(GOOGLE_API_KEY_HEADER) !== null) {
      return;
    }
    if (this.apiKey.startsWith("auth_tokens/")) {
      throw new Error("Ephemeral tokens are only supported by the live API.");
    }
    if (!this.apiKey) {
      throw new Error("API key is missing. Please provide a valid API key.");
    }
    headers.append(GOOGLE_API_KEY_HEADER, this.apiKey);
  }
};
var LANGUAGE_LABEL_PREFIX = "gl-node/";
var GoogleGenAI = class {
  get interactions() {
    var _a7;
    if (this._interactions !== void 0) {
      return this._interactions;
    }
    console.warn("GoogleGenAI.interactions: Interactions usage is experimental and may change in future versions.");
    const httpOpts = this.httpOptions;
    if (httpOpts === null || httpOpts === void 0 ? void 0 : httpOpts.extraBody) {
      console.warn("GoogleGenAI.interactions: Client level httpOptions.extraBody is not supported by the interactions client and will be ignored.");
    }
    const nextGenClient = new GeminiNextGenAPIClient({
      baseURL: this.apiClient.getBaseUrl(),
      apiKey: this.apiKey,
      apiVersion: this.apiClient.getApiVersion(),
      clientAdapter: this.apiClient,
      defaultHeaders: this.apiClient.getDefaultHeaders(),
      timeout: httpOpts === null || httpOpts === void 0 ? void 0 : httpOpts.timeout,
      maxRetries: (_a7 = httpOpts === null || httpOpts === void 0 ? void 0 : httpOpts.retryOptions) === null || _a7 === void 0 ? void 0 : _a7.attempts
    });
    this._interactions = nextGenClient.interactions;
    return this._interactions;
  }
  constructor(options) {
    var _a7;
    if (options.apiKey == null) {
      throw new Error("An API Key must be set when running in a browser");
    }
    if (options.project || options.location) {
      throw new Error("Vertex AI project based authentication is not supported on browser runtimes. Please do not provide a project or location.");
    }
    this.vertexai = (_a7 = options.vertexai) !== null && _a7 !== void 0 ? _a7 : false;
    this.apiKey = options.apiKey;
    const baseUrl = getBaseUrl(
      options.httpOptions,
      options.vertexai,
      /*vertexBaseUrlFromEnv*/
      void 0,
      /*geminiBaseUrlFromEnv*/
      void 0
    );
    if (baseUrl) {
      if (options.httpOptions) {
        options.httpOptions.baseUrl = baseUrl;
      } else {
        options.httpOptions = { baseUrl };
      }
    }
    this.apiVersion = options.apiVersion;
    this.httpOptions = options.httpOptions;
    const auth = new WebAuth(this.apiKey);
    this.apiClient = new ApiClient({
      auth,
      apiVersion: this.apiVersion,
      apiKey: this.apiKey,
      vertexai: this.vertexai,
      httpOptions: this.httpOptions,
      userAgentExtra: LANGUAGE_LABEL_PREFIX + "web",
      uploader: new BrowserUploader(),
      downloader: new BrowserDownloader()
    });
    this.models = new Models4(this.apiClient);
    this.live = new Live(this.apiClient, auth, new BrowserWebSocketFactory());
    this.batches = new Batches4(this.apiClient);
    this.chats = new Chats(this.models, this.apiClient);
    this.caches = new Caches(this.apiClient);
    this.files = new Files5(this.apiClient);
    this.operations = new Operations(this.apiClient);
    this.authTokens = new Tokens(this.apiClient);
    this.tunings = new Tunings(this.apiClient);
    this.fileSearchStores = new FileSearchStores(this.apiClient);
  }
};

// ../pi-mono/packages/ai/dist/providers/google-shared.js
init_process_shim();
function isThinkingPart(part) {
  return part.thought === true;
}
function retainThoughtSignature(existing, incoming) {
  if (typeof incoming === "string" && incoming.length > 0)
    return incoming;
  return existing;
}
var base64SignaturePattern = /^[A-Za-z0-9+/]+={0,2}$/;
var SKIP_THOUGHT_SIGNATURE = "skip_thought_signature_validator";
function isValidThoughtSignature(signature) {
  if (!signature)
    return false;
  if (signature.length % 4 !== 0)
    return false;
  return base64SignaturePattern.test(signature);
}
function resolveThoughtSignature(isSameProviderAndModel, signature) {
  return isSameProviderAndModel && isValidThoughtSignature(signature) ? signature : void 0;
}
function requiresToolCallId(modelId) {
  return modelId.startsWith("claude-") || modelId.startsWith("gpt-oss-");
}
function convertMessages2(model, context) {
  const contents = [];
  const normalizeToolCallId2 = (id) => {
    if (!requiresToolCallId(model.id))
      return id;
    return id.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 64);
  };
  const transformedMessages = transformMessages(context.messages, model, normalizeToolCallId2);
  for (const msg of transformedMessages) {
    if (msg.role === "user") {
      if (typeof msg.content === "string") {
        contents.push({
          role: "user",
          parts: [{ text: sanitizeSurrogates(msg.content) }]
        });
      } else {
        const parts = msg.content.map((item) => {
          if (item.type === "text") {
            return { text: sanitizeSurrogates(item.text) };
          } else {
            return {
              inlineData: {
                mimeType: item.mimeType,
                data: item.data
              }
            };
          }
        });
        const filteredParts = !model.input.includes("image") ? parts.filter((p4) => p4.text !== void 0) : parts;
        if (filteredParts.length === 0)
          continue;
        contents.push({
          role: "user",
          parts: filteredParts
        });
      }
    } else if (msg.role === "assistant") {
      const parts = [];
      const isSameProviderAndModel = msg.provider === model.provider && msg.model === model.id;
      for (const block of msg.content) {
        if (block.type === "text") {
          if (!block.text || block.text.trim() === "")
            continue;
          const thoughtSignature = resolveThoughtSignature(isSameProviderAndModel, block.textSignature);
          parts.push({
            text: sanitizeSurrogates(block.text),
            ...thoughtSignature && { thoughtSignature }
          });
        } else if (block.type === "thinking") {
          if (!block.thinking || block.thinking.trim() === "")
            continue;
          if (isSameProviderAndModel) {
            const thoughtSignature = resolveThoughtSignature(isSameProviderAndModel, block.thinkingSignature);
            parts.push({
              thought: true,
              text: sanitizeSurrogates(block.thinking),
              ...thoughtSignature && { thoughtSignature }
            });
          } else {
            parts.push({
              text: sanitizeSurrogates(block.thinking)
            });
          }
        } else if (block.type === "toolCall") {
          const thoughtSignature = resolveThoughtSignature(isSameProviderAndModel, block.thoughtSignature);
          const isGemini3 = model.id.toLowerCase().includes("gemini-3");
          const effectiveSignature = thoughtSignature || (isGemini3 ? SKIP_THOUGHT_SIGNATURE : void 0);
          const part = {
            functionCall: {
              name: block.name,
              args: block.arguments ?? {},
              ...requiresToolCallId(model.id) ? { id: block.id } : {}
            },
            ...effectiveSignature && { thoughtSignature: effectiveSignature }
          };
          parts.push(part);
        }
      }
      if (parts.length === 0)
        continue;
      contents.push({
        role: "model",
        parts
      });
    } else if (msg.role === "toolResult") {
      const textContent = msg.content.filter((c6) => c6.type === "text");
      const textResult = textContent.map((c6) => c6.text).join("\n");
      const imageContent = model.input.includes("image") ? msg.content.filter((c6) => c6.type === "image") : [];
      const hasText = textResult.length > 0;
      const hasImages = imageContent.length > 0;
      const supportsMultimodalFunctionResponse = model.id.includes("gemini-3");
      const responseValue = hasText ? sanitizeSurrogates(textResult) : hasImages ? "(see attached image)" : "";
      const imageParts = imageContent.map((imageBlock) => ({
        inlineData: {
          mimeType: imageBlock.mimeType,
          data: imageBlock.data
        }
      }));
      const includeId = requiresToolCallId(model.id);
      const functionResponsePart = {
        functionResponse: {
          name: msg.toolName,
          response: msg.isError ? { error: responseValue } : { output: responseValue },
          // Nest images inside functionResponse.parts for Gemini 3
          ...hasImages && supportsMultimodalFunctionResponse && { parts: imageParts },
          ...includeId ? { id: msg.toolCallId } : {}
        }
      };
      const lastContent = contents[contents.length - 1];
      if (lastContent?.role === "user" && lastContent.parts?.some((p4) => p4.functionResponse)) {
        lastContent.parts.push(functionResponsePart);
      } else {
        contents.push({
          role: "user",
          parts: [functionResponsePart]
        });
      }
      if (hasImages && !supportsMultimodalFunctionResponse) {
        contents.push({
          role: "user",
          parts: [{ text: "Tool result image:" }, ...imageParts]
        });
      }
    }
  }
  return contents;
}
function convertTools2(tools, useParameters = false) {
  if (tools.length === 0)
    return void 0;
  return [
    {
      functionDeclarations: tools.map((tool) => ({
        name: tool.name,
        description: tool.description,
        ...useParameters ? { parameters: tool.parameters } : { parametersJsonSchema: tool.parameters }
      }))
    }
  ];
}
function mapToolChoice(choice) {
  switch (choice) {
    case "auto":
      return FunctionCallingConfigMode.AUTO;
    case "none":
      return FunctionCallingConfigMode.NONE;
    case "any":
      return FunctionCallingConfigMode.ANY;
    default:
      return FunctionCallingConfigMode.AUTO;
  }
}
function mapStopReason3(reason) {
  switch (reason) {
    case FinishReason.STOP:
      return "stop";
    case FinishReason.MAX_TOKENS:
      return "length";
    case FinishReason.BLOCKLIST:
    case FinishReason.PROHIBITED_CONTENT:
    case FinishReason.SPII:
    case FinishReason.SAFETY:
    case FinishReason.IMAGE_SAFETY:
    case FinishReason.IMAGE_PROHIBITED_CONTENT:
    case FinishReason.IMAGE_RECITATION:
    case FinishReason.IMAGE_OTHER:
    case FinishReason.RECITATION:
    case FinishReason.FINISH_REASON_UNSPECIFIED:
    case FinishReason.OTHER:
    case FinishReason.LANGUAGE:
    case FinishReason.MALFORMED_FUNCTION_CALL:
    case FinishReason.UNEXPECTED_TOOL_CALL:
    case FinishReason.NO_IMAGE:
      return "error";
    default: {
      const _exhaustive = reason;
      throw new Error(`Unhandled stop reason: ${_exhaustive}`);
    }
  }
}
function mapStopReasonString(reason) {
  switch (reason) {
    case "STOP":
      return "stop";
    case "MAX_TOKENS":
      return "length";
    default:
      return "error";
  }
}

// ../pi-mono/packages/ai/dist/providers/google.js
var toolCallCounter = 0;
var streamGoogle = (model, context, options) => {
  const stream2 = new AssistantMessageEventStream();
  (async () => {
    const output = {
      role: "assistant",
      content: [],
      api: "google-generative-ai",
      provider: model.provider,
      model: model.id,
      usage: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0,
        totalTokens: 0,
        cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
      },
      stopReason: "stop",
      timestamp: Date.now()
    };
    try {
      const apiKey = options?.apiKey || getEnvApiKey(model.provider) || "";
      const client = createClient3(model, apiKey, options?.headers);
      let params = buildParams3(model, context, options);
      const nextParams = await options?.onPayload?.(params, model);
      if (nextParams !== void 0) {
        params = nextParams;
      }
      const googleStream = await client.models.generateContentStream(params);
      stream2.push({ type: "start", partial: output });
      let currentBlock = null;
      const blocks = output.content;
      const blockIndex = () => blocks.length - 1;
      for await (const chunk of googleStream) {
        const candidate = chunk.candidates?.[0];
        if (candidate?.content?.parts) {
          for (const part of candidate.content.parts) {
            if (part.text !== void 0) {
              const isThinking = isThinkingPart(part);
              if (!currentBlock || isThinking && currentBlock.type !== "thinking" || !isThinking && currentBlock.type !== "text") {
                if (currentBlock) {
                  if (currentBlock.type === "text") {
                    stream2.push({
                      type: "text_end",
                      contentIndex: blocks.length - 1,
                      content: currentBlock.text,
                      partial: output
                    });
                  } else {
                    stream2.push({
                      type: "thinking_end",
                      contentIndex: blockIndex(),
                      content: currentBlock.thinking,
                      partial: output
                    });
                  }
                }
                if (isThinking) {
                  currentBlock = { type: "thinking", thinking: "", thinkingSignature: void 0 };
                  output.content.push(currentBlock);
                  stream2.push({ type: "thinking_start", contentIndex: blockIndex(), partial: output });
                } else {
                  currentBlock = { type: "text", text: "" };
                  output.content.push(currentBlock);
                  stream2.push({ type: "text_start", contentIndex: blockIndex(), partial: output });
                }
              }
              if (currentBlock.type === "thinking") {
                currentBlock.thinking += part.text;
                currentBlock.thinkingSignature = retainThoughtSignature(currentBlock.thinkingSignature, part.thoughtSignature);
                stream2.push({
                  type: "thinking_delta",
                  contentIndex: blockIndex(),
                  delta: part.text,
                  partial: output
                });
              } else {
                currentBlock.text += part.text;
                currentBlock.textSignature = retainThoughtSignature(currentBlock.textSignature, part.thoughtSignature);
                stream2.push({
                  type: "text_delta",
                  contentIndex: blockIndex(),
                  delta: part.text,
                  partial: output
                });
              }
            }
            if (part.functionCall) {
              if (currentBlock) {
                if (currentBlock.type === "text") {
                  stream2.push({
                    type: "text_end",
                    contentIndex: blockIndex(),
                    content: currentBlock.text,
                    partial: output
                  });
                } else {
                  stream2.push({
                    type: "thinking_end",
                    contentIndex: blockIndex(),
                    content: currentBlock.thinking,
                    partial: output
                  });
                }
                currentBlock = null;
              }
              const providedId = part.functionCall.id;
              const needsNewId = !providedId || output.content.some((b4) => b4.type === "toolCall" && b4.id === providedId);
              const toolCallId = needsNewId ? `${part.functionCall.name}_${Date.now()}_${++toolCallCounter}` : providedId;
              const toolCall = {
                type: "toolCall",
                id: toolCallId,
                name: part.functionCall.name || "",
                arguments: part.functionCall.args ?? {},
                ...part.thoughtSignature && { thoughtSignature: part.thoughtSignature }
              };
              output.content.push(toolCall);
              stream2.push({ type: "toolcall_start", contentIndex: blockIndex(), partial: output });
              stream2.push({
                type: "toolcall_delta",
                contentIndex: blockIndex(),
                delta: JSON.stringify(toolCall.arguments),
                partial: output
              });
              stream2.push({ type: "toolcall_end", contentIndex: blockIndex(), toolCall, partial: output });
            }
          }
        }
        if (candidate?.finishReason) {
          output.stopReason = mapStopReason3(candidate.finishReason);
          if (output.content.some((b4) => b4.type === "toolCall")) {
            output.stopReason = "toolUse";
          }
        }
        if (chunk.usageMetadata) {
          output.usage = {
            input: chunk.usageMetadata.promptTokenCount || 0,
            output: (chunk.usageMetadata.candidatesTokenCount || 0) + (chunk.usageMetadata.thoughtsTokenCount || 0),
            cacheRead: chunk.usageMetadata.cachedContentTokenCount || 0,
            cacheWrite: 0,
            totalTokens: chunk.usageMetadata.totalTokenCount || 0,
            cost: {
              input: 0,
              output: 0,
              cacheRead: 0,
              cacheWrite: 0,
              total: 0
            }
          };
          calculateCost(model, output.usage);
        }
      }
      if (currentBlock) {
        if (currentBlock.type === "text") {
          stream2.push({
            type: "text_end",
            contentIndex: blockIndex(),
            content: currentBlock.text,
            partial: output
          });
        } else {
          stream2.push({
            type: "thinking_end",
            contentIndex: blockIndex(),
            content: currentBlock.thinking,
            partial: output
          });
        }
      }
      if (options?.signal?.aborted) {
        throw new Error("Request was aborted");
      }
      if (output.stopReason === "aborted" || output.stopReason === "error") {
        throw new Error("An unknown error occurred");
      }
      stream2.push({ type: "done", reason: output.stopReason, message: output });
      stream2.end();
    } catch (error) {
      for (const block of output.content) {
        if ("index" in block) {
          delete block.index;
        }
      }
      output.stopReason = options?.signal?.aborted ? "aborted" : "error";
      output.errorMessage = error instanceof Error ? error.message : JSON.stringify(error);
      stream2.push({ type: "error", reason: output.stopReason, error: output });
      stream2.end();
    }
  })();
  return stream2;
};
var streamSimpleGoogle = (model, context, options) => {
  const apiKey = options?.apiKey || getEnvApiKey(model.provider);
  if (!apiKey) {
    throw new Error(`No API key for provider: ${model.provider}`);
  }
  const base = buildBaseOptions(model, options, apiKey);
  if (!options?.reasoning) {
    return streamGoogle(model, context, { ...base, thinking: { enabled: false } });
  }
  const effort = clampReasoning(options.reasoning);
  const googleModel = model;
  if (isGemini3ProModel(googleModel) || isGemini3FlashModel(googleModel)) {
    return streamGoogle(model, context, {
      ...base,
      thinking: {
        enabled: true,
        level: getGemini3ThinkingLevel(effort, googleModel)
      }
    });
  }
  return streamGoogle(model, context, {
    ...base,
    thinking: {
      enabled: true,
      budgetTokens: getGoogleBudget(googleModel, effort, options.thinkingBudgets)
    }
  });
};
function createClient3(model, apiKey, optionsHeaders) {
  const httpOptions = {};
  if (model.baseUrl) {
    httpOptions.baseUrl = model.baseUrl;
    httpOptions.apiVersion = "";
  }
  if (model.headers || optionsHeaders) {
    httpOptions.headers = { ...model.headers, ...optionsHeaders };
  }
  return new GoogleGenAI({
    apiKey,
    httpOptions: Object.keys(httpOptions).length > 0 ? httpOptions : void 0
  });
}
function buildParams3(model, context, options = {}) {
  const contents = convertMessages2(model, context);
  const generationConfig = {};
  if (options.temperature !== void 0) {
    generationConfig.temperature = options.temperature;
  }
  if (options.maxTokens !== void 0) {
    generationConfig.maxOutputTokens = options.maxTokens;
  }
  const config = {
    ...Object.keys(generationConfig).length > 0 && generationConfig,
    ...context.systemPrompt && { systemInstruction: sanitizeSurrogates(context.systemPrompt) },
    ...context.tools && context.tools.length > 0 && { tools: convertTools2(context.tools) }
  };
  if (context.tools && context.tools.length > 0 && options.toolChoice) {
    config.toolConfig = {
      functionCallingConfig: {
        mode: mapToolChoice(options.toolChoice)
      }
    };
  } else {
    config.toolConfig = void 0;
  }
  if (options.thinking?.enabled && model.reasoning) {
    const thinkingConfig = { includeThoughts: true };
    if (options.thinking.level !== void 0) {
      thinkingConfig.thinkingLevel = options.thinking.level;
    } else if (options.thinking.budgetTokens !== void 0) {
      thinkingConfig.thinkingBudget = options.thinking.budgetTokens;
    }
    config.thinkingConfig = thinkingConfig;
  }
  if (options.signal) {
    if (options.signal.aborted) {
      throw new Error("Request aborted");
    }
    config.abortSignal = options.signal;
  }
  const params = {
    model: model.id,
    contents,
    config
  };
  return params;
}
function isGemini3ProModel(model) {
  return /gemini-3(?:\.\d+)?-pro/.test(model.id.toLowerCase());
}
function isGemini3FlashModel(model) {
  return /gemini-3(?:\.\d+)?-flash/.test(model.id.toLowerCase());
}
function getGemini3ThinkingLevel(effort, model) {
  if (isGemini3ProModel(model)) {
    switch (effort) {
      case "minimal":
      case "low":
        return "LOW";
      case "medium":
      case "high":
        return "HIGH";
    }
  }
  switch (effort) {
    case "minimal":
      return "MINIMAL";
    case "low":
      return "LOW";
    case "medium":
      return "MEDIUM";
    case "high":
      return "HIGH";
  }
}
function getGoogleBudget(model, effort, customBudgets) {
  if (customBudgets?.[effort] !== void 0) {
    return customBudgets[effort];
  }
  if (model.id.includes("2.5-pro")) {
    const budgets = {
      minimal: 128,
      low: 2048,
      medium: 8192,
      high: 32768
    };
    return budgets[effort];
  }
  if (model.id.includes("2.5-flash")) {
    const budgets = {
      minimal: 128,
      low: 2048,
      medium: 8192,
      high: 24576
    };
    return budgets[effort];
  }
  return -1;
}

// ../pi-mono/packages/ai/dist/providers/google-gemini-cli.js
init_process_shim();
var DEFAULT_ENDPOINT = "https://cloudcode-pa.googleapis.com";
var ANTIGRAVITY_DAILY_ENDPOINT = "https://daily-cloudcode-pa.sandbox.googleapis.com";
var ANTIGRAVITY_AUTOPUSH_ENDPOINT = "https://autopush-cloudcode-pa.sandbox.googleapis.com";
var ANTIGRAVITY_ENDPOINT_FALLBACKS = [
  ANTIGRAVITY_DAILY_ENDPOINT,
  ANTIGRAVITY_AUTOPUSH_ENDPOINT,
  DEFAULT_ENDPOINT
];
var GEMINI_CLI_HEADERS = {
  "User-Agent": "google-cloud-sdk vscode_cloudshelleditor/0.1",
  "X-Goog-Api-Client": "gl-node/22.17.0",
  "Client-Metadata": JSON.stringify({
    ideType: "IDE_UNSPECIFIED",
    platform: "PLATFORM_UNSPECIFIED",
    pluginType: "GEMINI"
  })
};
var DEFAULT_ANTIGRAVITY_VERSION = "1.18.4";
function getAntigravityHeaders() {
  const version5 = process.env.PI_AI_ANTIGRAVITY_VERSION || DEFAULT_ANTIGRAVITY_VERSION;
  return {
    "User-Agent": `antigravity/${version5} darwin/arm64`
  };
}
var ANTIGRAVITY_SYSTEM_INSTRUCTION = "You are Antigravity, a powerful agentic AI coding assistant designed by the Google Deepmind team working on Advanced Agentic Coding.You are pair programming with a USER to solve their coding task. The task may require creating a new codebase, modifying or debugging an existing codebase, or simply answering a question.**Absolute paths only****Proactiveness**";
var toolCallCounter2 = 0;
var MAX_RETRIES = 3;
var BASE_DELAY_MS = 1e3;
var MAX_EMPTY_STREAM_RETRIES = 2;
var EMPTY_STREAM_BASE_DELAY_MS = 500;
var CLAUDE_THINKING_BETA_HEADER = "interleaved-thinking-2025-05-14";
function extractRetryDelay(errorText, response) {
  const normalizeDelay = (ms) => ms > 0 ? Math.ceil(ms + 1e3) : void 0;
  const headers = response instanceof Headers ? response : response?.headers;
  if (headers) {
    const retryAfter = headers.get("retry-after");
    if (retryAfter) {
      const retryAfterSeconds = Number(retryAfter);
      if (Number.isFinite(retryAfterSeconds)) {
        const delay = normalizeDelay(retryAfterSeconds * 1e3);
        if (delay !== void 0) {
          return delay;
        }
      }
      const retryAfterDate = new Date(retryAfter);
      const retryAfterMs = retryAfterDate.getTime();
      if (!Number.isNaN(retryAfterMs)) {
        const delay = normalizeDelay(retryAfterMs - Date.now());
        if (delay !== void 0) {
          return delay;
        }
      }
    }
    const rateLimitReset = headers.get("x-ratelimit-reset");
    if (rateLimitReset) {
      const resetSeconds = Number.parseInt(rateLimitReset, 10);
      if (!Number.isNaN(resetSeconds)) {
        const delay = normalizeDelay(resetSeconds * 1e3 - Date.now());
        if (delay !== void 0) {
          return delay;
        }
      }
    }
    const rateLimitResetAfter = headers.get("x-ratelimit-reset-after");
    if (rateLimitResetAfter) {
      const resetAfterSeconds = Number(rateLimitResetAfter);
      if (Number.isFinite(resetAfterSeconds)) {
        const delay = normalizeDelay(resetAfterSeconds * 1e3);
        if (delay !== void 0) {
          return delay;
        }
      }
    }
  }
  const durationMatch = errorText.match(/reset after (?:(\d+)h)?(?:(\d+)m)?(\d+(?:\.\d+)?)s/i);
  if (durationMatch) {
    const hours = durationMatch[1] ? parseInt(durationMatch[1], 10) : 0;
    const minutes = durationMatch[2] ? parseInt(durationMatch[2], 10) : 0;
    const seconds = parseFloat(durationMatch[3]);
    if (!Number.isNaN(seconds)) {
      const totalMs = ((hours * 60 + minutes) * 60 + seconds) * 1e3;
      const delay = normalizeDelay(totalMs);
      if (delay !== void 0) {
        return delay;
      }
    }
  }
  const retryInMatch = errorText.match(/Please retry in ([0-9.]+)(ms|s)/i);
  if (retryInMatch?.[1]) {
    const value = parseFloat(retryInMatch[1]);
    if (!Number.isNaN(value) && value > 0) {
      const ms = retryInMatch[2].toLowerCase() === "ms" ? value : value * 1e3;
      const delay = normalizeDelay(ms);
      if (delay !== void 0) {
        return delay;
      }
    }
  }
  const retryDelayMatch = errorText.match(/"retryDelay":\s*"([0-9.]+)(ms|s)"/i);
  if (retryDelayMatch?.[1]) {
    const value = parseFloat(retryDelayMatch[1]);
    if (!Number.isNaN(value) && value > 0) {
      const ms = retryDelayMatch[2].toLowerCase() === "ms" ? value : value * 1e3;
      const delay = normalizeDelay(ms);
      if (delay !== void 0) {
        return delay;
      }
    }
  }
  return void 0;
}
function needsClaudeThinkingBetaHeader(model) {
  return model.provider === "google-antigravity" && model.id.startsWith("claude-") && model.reasoning;
}
function isGemini3ProModel2(modelId) {
  return /gemini-3(?:\.1)?-pro/.test(modelId.toLowerCase());
}
function isGemini3FlashModel2(modelId) {
  return /gemini-3(?:\.1)?-flash/.test(modelId.toLowerCase());
}
function isGemini3Model(modelId) {
  return isGemini3ProModel2(modelId) || isGemini3FlashModel2(modelId);
}
function isRetryableError(status, errorText) {
  if (status === 429 || status === 500 || status === 502 || status === 503 || status === 504) {
    return true;
  }
  return /resource.?exhausted|rate.?limit|overloaded|service.?unavailable|other.?side.?closed/i.test(errorText);
}
function extractErrorMessage(errorText) {
  try {
    const parsed = JSON.parse(errorText);
    if (parsed.error?.message) {
      return parsed.error.message;
    }
  } catch {
  }
  return errorText;
}
function sleep4(ms, signal) {
  return new Promise((resolve, reject) => {
    if (signal?.aborted) {
      reject(new Error("Request was aborted"));
      return;
    }
    const timeout = setTimeout(resolve, ms);
    signal?.addEventListener("abort", () => {
      clearTimeout(timeout);
      reject(new Error("Request was aborted"));
    });
  });
}
var streamGoogleGeminiCli = (model, context, options) => {
  const stream2 = new AssistantMessageEventStream();
  (async () => {
    const output = {
      role: "assistant",
      content: [],
      api: "google-gemini-cli",
      provider: model.provider,
      model: model.id,
      usage: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0,
        totalTokens: 0,
        cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
      },
      stopReason: "stop",
      timestamp: Date.now()
    };
    try {
      const apiKeyRaw = options?.apiKey;
      if (!apiKeyRaw) {
        throw new Error("Google Cloud Code Assist requires OAuth authentication. Use /login to authenticate.");
      }
      let accessToken;
      let projectId;
      try {
        const parsed = JSON.parse(apiKeyRaw);
        accessToken = parsed.token;
        projectId = parsed.projectId;
      } catch {
        throw new Error("Invalid Google Cloud Code Assist credentials. Use /login to re-authenticate.");
      }
      if (!accessToken || !projectId) {
        throw new Error("Missing token or projectId in Google Cloud credentials. Use /login to re-authenticate.");
      }
      const isAntigravity = model.provider === "google-antigravity";
      const baseUrl = model.baseUrl?.trim();
      const endpoints = baseUrl ? [baseUrl] : isAntigravity ? ANTIGRAVITY_ENDPOINT_FALLBACKS : [DEFAULT_ENDPOINT];
      let requestBody = buildRequest(model, context, projectId, options, isAntigravity);
      const nextRequestBody = await options?.onPayload?.(requestBody, model);
      if (nextRequestBody !== void 0) {
        requestBody = nextRequestBody;
      }
      const headers = isAntigravity ? getAntigravityHeaders() : GEMINI_CLI_HEADERS;
      const requestHeaders = {
        Authorization: `Bearer ${accessToken}`,
        "Content-Type": "application/json",
        Accept: "text/event-stream",
        ...headers,
        ...needsClaudeThinkingBetaHeader(model) ? { "anthropic-beta": CLAUDE_THINKING_BETA_HEADER } : {},
        ...options?.headers
      };
      const requestBodyJson = JSON.stringify(requestBody);
      let response;
      let lastError;
      let requestUrl;
      let endpointIndex = 0;
      for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
        if (options?.signal?.aborted) {
          throw new Error("Request was aborted");
        }
        try {
          const endpoint = endpoints[endpointIndex];
          requestUrl = `${endpoint}/v1internal:streamGenerateContent?alt=sse`;
          response = await fetch(requestUrl, {
            method: "POST",
            headers: requestHeaders,
            body: requestBodyJson,
            signal: options?.signal
          });
          if (response.ok) {
            break;
          }
          const errorText = await response.text();
          if ((response.status === 403 || response.status === 404) && endpointIndex < endpoints.length - 1) {
            endpointIndex++;
            continue;
          }
          if (attempt < MAX_RETRIES && isRetryableError(response.status, errorText)) {
            if (endpointIndex < endpoints.length - 1) {
              endpointIndex++;
            }
            const serverDelay = extractRetryDelay(errorText, response);
            const delayMs = serverDelay ?? BASE_DELAY_MS * 2 ** attempt;
            const maxDelayMs = options?.maxRetryDelayMs ?? 6e4;
            if (maxDelayMs > 0 && serverDelay && serverDelay > maxDelayMs) {
              const delaySeconds = Math.ceil(serverDelay / 1e3);
              throw new Error(`Server requested ${delaySeconds}s retry delay (max: ${Math.ceil(maxDelayMs / 1e3)}s). ${extractErrorMessage(errorText)}`);
            }
            await sleep4(delayMs, options?.signal);
            continue;
          }
          throw new Error(`Cloud Code Assist API error (${response.status}): ${extractErrorMessage(errorText)}`);
        } catch (error) {
          if (error instanceof Error) {
            if (error.name === "AbortError" || error.message === "Request was aborted") {
              throw new Error("Request was aborted");
            }
          }
          lastError = error instanceof Error ? error : new Error(String(error));
          if (lastError.message === "fetch failed" && lastError.cause instanceof Error) {
            lastError = new Error(`Network error: ${lastError.cause.message}`);
          }
          if (attempt < MAX_RETRIES) {
            const delayMs = BASE_DELAY_MS * 2 ** attempt;
            await sleep4(delayMs, options?.signal);
            continue;
          }
          throw lastError;
        }
      }
      if (!response || !response.ok) {
        throw lastError ?? new Error("Failed to get response after retries");
      }
      let started = false;
      const ensureStarted = () => {
        if (!started) {
          stream2.push({ type: "start", partial: output });
          started = true;
        }
      };
      const resetOutput = () => {
        output.content = [];
        output.usage = {
          input: 0,
          output: 0,
          cacheRead: 0,
          cacheWrite: 0,
          totalTokens: 0,
          cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
        };
        output.stopReason = "stop";
        output.errorMessage = void 0;
        output.timestamp = Date.now();
        started = false;
      };
      const streamResponse = async (activeResponse) => {
        if (!activeResponse.body) {
          throw new Error("No response body");
        }
        let hasContent = false;
        let currentBlock = null;
        const blocks = output.content;
        const blockIndex = () => blocks.length - 1;
        const reader = activeResponse.body.getReader();
        const decoder = new TextDecoder();
        let buffer = "";
        const abortHandler = () => {
          void reader.cancel().catch(() => {
          });
        };
        options?.signal?.addEventListener("abort", abortHandler);
        try {
          while (true) {
            if (options?.signal?.aborted) {
              throw new Error("Request was aborted");
            }
            const { done, value } = await reader.read();
            if (done)
              break;
            buffer += decoder.decode(value, { stream: true });
            const lines = buffer.split("\n");
            buffer = lines.pop() || "";
            for (const line of lines) {
              if (!line.startsWith("data:"))
                continue;
              const jsonStr = line.slice(5).trim();
              if (!jsonStr)
                continue;
              let chunk;
              try {
                chunk = JSON.parse(jsonStr);
              } catch {
                continue;
              }
              const responseData = chunk.response;
              if (!responseData)
                continue;
              const candidate = responseData.candidates?.[0];
              if (candidate?.content?.parts) {
                for (const part of candidate.content.parts) {
                  if (part.text !== void 0) {
                    hasContent = true;
                    const isThinking = isThinkingPart(part);
                    if (!currentBlock || isThinking && currentBlock.type !== "thinking" || !isThinking && currentBlock.type !== "text") {
                      if (currentBlock) {
                        if (currentBlock.type === "text") {
                          stream2.push({
                            type: "text_end",
                            contentIndex: blocks.length - 1,
                            content: currentBlock.text,
                            partial: output
                          });
                        } else {
                          stream2.push({
                            type: "thinking_end",
                            contentIndex: blockIndex(),
                            content: currentBlock.thinking,
                            partial: output
                          });
                        }
                      }
                      if (isThinking) {
                        currentBlock = { type: "thinking", thinking: "", thinkingSignature: void 0 };
                        output.content.push(currentBlock);
                        ensureStarted();
                        stream2.push({
                          type: "thinking_start",
                          contentIndex: blockIndex(),
                          partial: output
                        });
                      } else {
                        currentBlock = { type: "text", text: "" };
                        output.content.push(currentBlock);
                        ensureStarted();
                        stream2.push({ type: "text_start", contentIndex: blockIndex(), partial: output });
                      }
                    }
                    if (currentBlock.type === "thinking") {
                      currentBlock.thinking += part.text;
                      currentBlock.thinkingSignature = retainThoughtSignature(currentBlock.thinkingSignature, part.thoughtSignature);
                      stream2.push({
                        type: "thinking_delta",
                        contentIndex: blockIndex(),
                        delta: part.text,
                        partial: output
                      });
                    } else {
                      currentBlock.text += part.text;
                      currentBlock.textSignature = retainThoughtSignature(currentBlock.textSignature, part.thoughtSignature);
                      stream2.push({
                        type: "text_delta",
                        contentIndex: blockIndex(),
                        delta: part.text,
                        partial: output
                      });
                    }
                  }
                  if (part.functionCall) {
                    hasContent = true;
                    if (currentBlock) {
                      if (currentBlock.type === "text") {
                        stream2.push({
                          type: "text_end",
                          contentIndex: blockIndex(),
                          content: currentBlock.text,
                          partial: output
                        });
                      } else {
                        stream2.push({
                          type: "thinking_end",
                          contentIndex: blockIndex(),
                          content: currentBlock.thinking,
                          partial: output
                        });
                      }
                      currentBlock = null;
                    }
                    const providedId = part.functionCall.id;
                    const needsNewId = !providedId || output.content.some((b4) => b4.type === "toolCall" && b4.id === providedId);
                    const toolCallId = needsNewId ? `${part.functionCall.name}_${Date.now()}_${++toolCallCounter2}` : providedId;
                    const toolCall = {
                      type: "toolCall",
                      id: toolCallId,
                      name: part.functionCall.name || "",
                      arguments: part.functionCall.args ?? {},
                      ...part.thoughtSignature && { thoughtSignature: part.thoughtSignature }
                    };
                    output.content.push(toolCall);
                    ensureStarted();
                    stream2.push({ type: "toolcall_start", contentIndex: blockIndex(), partial: output });
                    stream2.push({
                      type: "toolcall_delta",
                      contentIndex: blockIndex(),
                      delta: JSON.stringify(toolCall.arguments),
                      partial: output
                    });
                    stream2.push({
                      type: "toolcall_end",
                      contentIndex: blockIndex(),
                      toolCall,
                      partial: output
                    });
                  }
                }
              }
              if (candidate?.finishReason) {
                output.stopReason = mapStopReasonString(candidate.finishReason);
                if (output.content.some((b4) => b4.type === "toolCall")) {
                  output.stopReason = "toolUse";
                }
              }
              if (responseData.usageMetadata) {
                const promptTokens = responseData.usageMetadata.promptTokenCount || 0;
                const cacheReadTokens = responseData.usageMetadata.cachedContentTokenCount || 0;
                output.usage = {
                  input: promptTokens - cacheReadTokens,
                  output: (responseData.usageMetadata.candidatesTokenCount || 0) + (responseData.usageMetadata.thoughtsTokenCount || 0),
                  cacheRead: cacheReadTokens,
                  cacheWrite: 0,
                  totalTokens: responseData.usageMetadata.totalTokenCount || 0,
                  cost: {
                    input: 0,
                    output: 0,
                    cacheRead: 0,
                    cacheWrite: 0,
                    total: 0
                  }
                };
                calculateCost(model, output.usage);
              }
            }
          }
        } finally {
          options?.signal?.removeEventListener("abort", abortHandler);
        }
        if (currentBlock) {
          if (currentBlock.type === "text") {
            stream2.push({
              type: "text_end",
              contentIndex: blockIndex(),
              content: currentBlock.text,
              partial: output
            });
          } else {
            stream2.push({
              type: "thinking_end",
              contentIndex: blockIndex(),
              content: currentBlock.thinking,
              partial: output
            });
          }
        }
        return hasContent;
      };
      let receivedContent = false;
      let currentResponse = response;
      for (let emptyAttempt = 0; emptyAttempt <= MAX_EMPTY_STREAM_RETRIES; emptyAttempt++) {
        if (options?.signal?.aborted) {
          throw new Error("Request was aborted");
        }
        if (emptyAttempt > 0) {
          const backoffMs = EMPTY_STREAM_BASE_DELAY_MS * 2 ** (emptyAttempt - 1);
          await sleep4(backoffMs, options?.signal);
          if (!requestUrl) {
            throw new Error("Missing request URL");
          }
          currentResponse = await fetch(requestUrl, {
            method: "POST",
            headers: requestHeaders,
            body: requestBodyJson,
            signal: options?.signal
          });
          if (!currentResponse.ok) {
            const retryErrorText = await currentResponse.text();
            throw new Error(`Cloud Code Assist API error (${currentResponse.status}): ${retryErrorText}`);
          }
        }
        const streamed = await streamResponse(currentResponse);
        if (streamed) {
          receivedContent = true;
          break;
        }
        if (emptyAttempt < MAX_EMPTY_STREAM_RETRIES) {
          resetOutput();
        }
      }
      if (!receivedContent) {
        throw new Error("Cloud Code Assist API returned an empty response");
      }
      if (options?.signal?.aborted) {
        throw new Error("Request was aborted");
      }
      if (output.stopReason === "aborted" || output.stopReason === "error") {
        throw new Error("An unknown error occurred");
      }
      stream2.push({ type: "done", reason: output.stopReason, message: output });
      stream2.end();
    } catch (error) {
      for (const block of output.content) {
        if ("index" in block) {
          delete block.index;
        }
      }
      output.stopReason = options?.signal?.aborted ? "aborted" : "error";
      output.errorMessage = error instanceof Error ? error.message : JSON.stringify(error);
      stream2.push({ type: "error", reason: output.stopReason, error: output });
      stream2.end();
    }
  })();
  return stream2;
};
var streamSimpleGoogleGeminiCli = (model, context, options) => {
  const apiKey = options?.apiKey;
  if (!apiKey) {
    throw new Error("Google Cloud Code Assist requires OAuth authentication. Use /login to authenticate.");
  }
  const base = buildBaseOptions(model, options, apiKey);
  if (!options?.reasoning) {
    return streamGoogleGeminiCli(model, context, {
      ...base,
      thinking: { enabled: false }
    });
  }
  const effort = clampReasoning(options.reasoning);
  if (isGemini3Model(model.id)) {
    return streamGoogleGeminiCli(model, context, {
      ...base,
      thinking: {
        enabled: true,
        level: getGeminiCliThinkingLevel(effort, model.id)
      }
    });
  }
  const defaultBudgets = {
    minimal: 1024,
    low: 2048,
    medium: 8192,
    high: 16384
  };
  const budgets = { ...defaultBudgets, ...options.thinkingBudgets };
  const minOutputTokens = 1024;
  let thinkingBudget = budgets[effort];
  const maxTokens = Math.min((base.maxTokens || 0) + thinkingBudget, model.maxTokens);
  if (maxTokens <= thinkingBudget) {
    thinkingBudget = Math.max(0, maxTokens - minOutputTokens);
  }
  return streamGoogleGeminiCli(model, context, {
    ...base,
    maxTokens,
    thinking: {
      enabled: true,
      budgetTokens: thinkingBudget
    }
  });
};
function buildRequest(model, context, projectId, options = {}, isAntigravity = false) {
  const contents = convertMessages2(model, context);
  const generationConfig = {};
  if (options.temperature !== void 0) {
    generationConfig.temperature = options.temperature;
  }
  if (options.maxTokens !== void 0) {
    generationConfig.maxOutputTokens = options.maxTokens;
  }
  if (options.thinking?.enabled && model.reasoning) {
    generationConfig.thinkingConfig = {
      includeThoughts: true
    };
    if (options.thinking.level !== void 0) {
      generationConfig.thinkingConfig.thinkingLevel = options.thinking.level;
    } else if (options.thinking.budgetTokens !== void 0) {
      generationConfig.thinkingConfig.thinkingBudget = options.thinking.budgetTokens;
    }
  }
  const request = {
    contents
  };
  request.sessionId = options.sessionId;
  if (context.systemPrompt) {
    request.systemInstruction = {
      parts: [{ text: sanitizeSurrogates(context.systemPrompt) }]
    };
  }
  if (Object.keys(generationConfig).length > 0) {
    request.generationConfig = generationConfig;
  }
  if (context.tools && context.tools.length > 0) {
    const useParameters = model.id.startsWith("claude-");
    request.tools = convertTools2(context.tools, useParameters);
    if (options.toolChoice) {
      request.toolConfig = {
        functionCallingConfig: {
          mode: mapToolChoice(options.toolChoice)
        }
      };
    }
  }
  if (isAntigravity) {
    const existingParts = request.systemInstruction?.parts ?? [];
    request.systemInstruction = {
      role: "user",
      parts: [
        { text: ANTIGRAVITY_SYSTEM_INSTRUCTION },
        { text: `Please ignore following [ignore]${ANTIGRAVITY_SYSTEM_INSTRUCTION}[/ignore]` },
        ...existingParts
      ]
    };
  }
  return {
    project: projectId,
    model: model.id,
    request,
    ...isAntigravity ? { requestType: "agent" } : {},
    userAgent: isAntigravity ? "antigravity" : "pi-coding-agent",
    requestId: `${isAntigravity ? "agent" : "pi"}-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`
  };
}
function getGeminiCliThinkingLevel(effort, modelId) {
  if (isGemini3ProModel2(modelId)) {
    switch (effort) {
      case "minimal":
      case "low":
        return "LOW";
      case "medium":
      case "high":
        return "HIGH";
    }
  }
  switch (effort) {
    case "minimal":
      return "MINIMAL";
    case "low":
      return "LOW";
    case "medium":
      return "MEDIUM";
    case "high":
      return "HIGH";
  }
}

// ../pi-mono/packages/ai/dist/providers/google-vertex.js
init_process_shim();
var API_VERSION = "v1";
var THINKING_LEVEL_MAP = {
  THINKING_LEVEL_UNSPECIFIED: ThinkingLevel.THINKING_LEVEL_UNSPECIFIED,
  MINIMAL: ThinkingLevel.MINIMAL,
  LOW: ThinkingLevel.LOW,
  MEDIUM: ThinkingLevel.MEDIUM,
  HIGH: ThinkingLevel.HIGH
};
var toolCallCounter3 = 0;
var streamGoogleVertex = (model, context, options) => {
  const stream2 = new AssistantMessageEventStream();
  (async () => {
    const output = {
      role: "assistant",
      content: [],
      api: "google-vertex",
      provider: model.provider,
      model: model.id,
      usage: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0,
        totalTokens: 0,
        cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
      },
      stopReason: "stop",
      timestamp: Date.now()
    };
    try {
      const apiKey = resolveApiKey(options);
      const client = apiKey ? createClientWithApiKey(model, apiKey, options?.headers) : createClient4(model, resolveProject(options), resolveLocation(options), options?.headers);
      let params = buildParams4(model, context, options);
      const nextParams = await options?.onPayload?.(params, model);
      if (nextParams !== void 0) {
        params = nextParams;
      }
      const googleStream = await client.models.generateContentStream(params);
      stream2.push({ type: "start", partial: output });
      let currentBlock = null;
      const blocks = output.content;
      const blockIndex = () => blocks.length - 1;
      for await (const chunk of googleStream) {
        const candidate = chunk.candidates?.[0];
        if (candidate?.content?.parts) {
          for (const part of candidate.content.parts) {
            if (part.text !== void 0) {
              const isThinking = isThinkingPart(part);
              if (!currentBlock || isThinking && currentBlock.type !== "thinking" || !isThinking && currentBlock.type !== "text") {
                if (currentBlock) {
                  if (currentBlock.type === "text") {
                    stream2.push({
                      type: "text_end",
                      contentIndex: blocks.length - 1,
                      content: currentBlock.text,
                      partial: output
                    });
                  } else {
                    stream2.push({
                      type: "thinking_end",
                      contentIndex: blockIndex(),
                      content: currentBlock.thinking,
                      partial: output
                    });
                  }
                }
                if (isThinking) {
                  currentBlock = { type: "thinking", thinking: "", thinkingSignature: void 0 };
                  output.content.push(currentBlock);
                  stream2.push({ type: "thinking_start", contentIndex: blockIndex(), partial: output });
                } else {
                  currentBlock = { type: "text", text: "" };
                  output.content.push(currentBlock);
                  stream2.push({ type: "text_start", contentIndex: blockIndex(), partial: output });
                }
              }
              if (currentBlock.type === "thinking") {
                currentBlock.thinking += part.text;
                currentBlock.thinkingSignature = retainThoughtSignature(currentBlock.thinkingSignature, part.thoughtSignature);
                stream2.push({
                  type: "thinking_delta",
                  contentIndex: blockIndex(),
                  delta: part.text,
                  partial: output
                });
              } else {
                currentBlock.text += part.text;
                currentBlock.textSignature = retainThoughtSignature(currentBlock.textSignature, part.thoughtSignature);
                stream2.push({
                  type: "text_delta",
                  contentIndex: blockIndex(),
                  delta: part.text,
                  partial: output
                });
              }
            }
            if (part.functionCall) {
              if (currentBlock) {
                if (currentBlock.type === "text") {
                  stream2.push({
                    type: "text_end",
                    contentIndex: blockIndex(),
                    content: currentBlock.text,
                    partial: output
                  });
                } else {
                  stream2.push({
                    type: "thinking_end",
                    contentIndex: blockIndex(),
                    content: currentBlock.thinking,
                    partial: output
                  });
                }
                currentBlock = null;
              }
              const providedId = part.functionCall.id;
              const needsNewId = !providedId || output.content.some((b4) => b4.type === "toolCall" && b4.id === providedId);
              const toolCallId = needsNewId ? `${part.functionCall.name}_${Date.now()}_${++toolCallCounter3}` : providedId;
              const toolCall = {
                type: "toolCall",
                id: toolCallId,
                name: part.functionCall.name || "",
                arguments: part.functionCall.args ?? {},
                ...part.thoughtSignature && { thoughtSignature: part.thoughtSignature }
              };
              output.content.push(toolCall);
              stream2.push({ type: "toolcall_start", contentIndex: blockIndex(), partial: output });
              stream2.push({
                type: "toolcall_delta",
                contentIndex: blockIndex(),
                delta: JSON.stringify(toolCall.arguments),
                partial: output
              });
              stream2.push({ type: "toolcall_end", contentIndex: blockIndex(), toolCall, partial: output });
            }
          }
        }
        if (candidate?.finishReason) {
          output.stopReason = mapStopReason3(candidate.finishReason);
          if (output.content.some((b4) => b4.type === "toolCall")) {
            output.stopReason = "toolUse";
          }
        }
        if (chunk.usageMetadata) {
          output.usage = {
            input: chunk.usageMetadata.promptTokenCount || 0,
            output: (chunk.usageMetadata.candidatesTokenCount || 0) + (chunk.usageMetadata.thoughtsTokenCount || 0),
            cacheRead: chunk.usageMetadata.cachedContentTokenCount || 0,
            cacheWrite: 0,
            totalTokens: chunk.usageMetadata.totalTokenCount || 0,
            cost: {
              input: 0,
              output: 0,
              cacheRead: 0,
              cacheWrite: 0,
              total: 0
            }
          };
          calculateCost(model, output.usage);
        }
      }
      if (currentBlock) {
        if (currentBlock.type === "text") {
          stream2.push({
            type: "text_end",
            contentIndex: blockIndex(),
            content: currentBlock.text,
            partial: output
          });
        } else {
          stream2.push({
            type: "thinking_end",
            contentIndex: blockIndex(),
            content: currentBlock.thinking,
            partial: output
          });
        }
      }
      if (options?.signal?.aborted) {
        throw new Error("Request was aborted");
      }
      if (output.stopReason === "aborted" || output.stopReason === "error") {
        throw new Error("An unknown error occurred");
      }
      stream2.push({ type: "done", reason: output.stopReason, message: output });
      stream2.end();
    } catch (error) {
      for (const block of output.content) {
        if ("index" in block) {
          delete block.index;
        }
      }
      output.stopReason = options?.signal?.aborted ? "aborted" : "error";
      output.errorMessage = error instanceof Error ? error.message : JSON.stringify(error);
      stream2.push({ type: "error", reason: output.stopReason, error: output });
      stream2.end();
    }
  })();
  return stream2;
};
var streamSimpleGoogleVertex = (model, context, options) => {
  const base = buildBaseOptions(model, options, void 0);
  if (!options?.reasoning) {
    return streamGoogleVertex(model, context, {
      ...base,
      thinking: { enabled: false }
    });
  }
  const effort = clampReasoning(options.reasoning);
  const geminiModel = model;
  if (isGemini3ProModel3(geminiModel) || isGemini3FlashModel3(geminiModel)) {
    return streamGoogleVertex(model, context, {
      ...base,
      thinking: {
        enabled: true,
        level: getGemini3ThinkingLevel2(effort, geminiModel)
      }
    });
  }
  return streamGoogleVertex(model, context, {
    ...base,
    thinking: {
      enabled: true,
      budgetTokens: getGoogleBudget2(geminiModel, effort, options.thinkingBudgets)
    }
  });
};
function createClient4(model, project, location, optionsHeaders) {
  const httpOptions = {};
  if (model.headers || optionsHeaders) {
    httpOptions.headers = { ...model.headers, ...optionsHeaders };
  }
  const hasHttpOptions = Object.values(httpOptions).some(Boolean);
  return new GoogleGenAI({
    vertexai: true,
    project,
    location,
    apiVersion: API_VERSION,
    httpOptions: hasHttpOptions ? httpOptions : void 0
  });
}
function createClientWithApiKey(model, apiKey, optionsHeaders) {
  const httpOptions = {};
  if (model.headers || optionsHeaders) {
    httpOptions.headers = { ...model.headers, ...optionsHeaders };
  }
  const hasHttpOptions = Object.values(httpOptions).some(Boolean);
  return new GoogleGenAI({
    vertexai: true,
    apiKey,
    apiVersion: API_VERSION,
    httpOptions: hasHttpOptions ? httpOptions : void 0
  });
}
function resolveApiKey(options) {
  return options?.apiKey || process.env.GOOGLE_CLOUD_API_KEY;
}
function resolveProject(options) {
  const project = options?.project || process.env.GOOGLE_CLOUD_PROJECT || process.env.GCLOUD_PROJECT;
  if (!project) {
    throw new Error("Vertex AI requires a project ID. Set GOOGLE_CLOUD_PROJECT/GCLOUD_PROJECT or pass project in options.");
  }
  return project;
}
function resolveLocation(options) {
  const location = options?.location || process.env.GOOGLE_CLOUD_LOCATION;
  if (!location) {
    throw new Error("Vertex AI requires a location. Set GOOGLE_CLOUD_LOCATION or pass location in options.");
  }
  return location;
}
function buildParams4(model, context, options = {}) {
  const contents = convertMessages2(model, context);
  const generationConfig = {};
  if (options.temperature !== void 0) {
    generationConfig.temperature = options.temperature;
  }
  if (options.maxTokens !== void 0) {
    generationConfig.maxOutputTokens = options.maxTokens;
  }
  const config = {
    ...Object.keys(generationConfig).length > 0 && generationConfig,
    ...context.systemPrompt && { systemInstruction: sanitizeSurrogates(context.systemPrompt) },
    ...context.tools && context.tools.length > 0 && { tools: convertTools2(context.tools) }
  };
  if (context.tools && context.tools.length > 0 && options.toolChoice) {
    config.toolConfig = {
      functionCallingConfig: {
        mode: mapToolChoice(options.toolChoice)
      }
    };
  } else {
    config.toolConfig = void 0;
  }
  if (options.thinking?.enabled && model.reasoning) {
    const thinkingConfig = { includeThoughts: true };
    if (options.thinking.level !== void 0) {
      thinkingConfig.thinkingLevel = THINKING_LEVEL_MAP[options.thinking.level];
    } else if (options.thinking.budgetTokens !== void 0) {
      thinkingConfig.thinkingBudget = options.thinking.budgetTokens;
    }
    config.thinkingConfig = thinkingConfig;
  }
  if (options.signal) {
    if (options.signal.aborted) {
      throw new Error("Request aborted");
    }
    config.abortSignal = options.signal;
  }
  const params = {
    model: model.id,
    contents,
    config
  };
  return params;
}
function isGemini3ProModel3(model) {
  return /gemini-3(?:\.\d+)?-pro/.test(model.id.toLowerCase());
}
function isGemini3FlashModel3(model) {
  return /gemini-3(?:\.\d+)?-flash/.test(model.id.toLowerCase());
}
function getGemini3ThinkingLevel2(effort, model) {
  if (isGemini3ProModel3(model)) {
    switch (effort) {
      case "minimal":
      case "low":
        return "LOW";
      case "medium":
      case "high":
        return "HIGH";
    }
  }
  switch (effort) {
    case "minimal":
      return "MINIMAL";
    case "low":
      return "LOW";
    case "medium":
      return "MEDIUM";
    case "high":
      return "HIGH";
  }
}
function getGoogleBudget2(model, effort, customBudgets) {
  if (customBudgets?.[effort] !== void 0) {
    return customBudgets[effort];
  }
  if (model.id.includes("2.5-pro")) {
    const budgets = {
      minimal: 128,
      low: 2048,
      medium: 8192,
      high: 32768
    };
    return budgets[effort];
  }
  if (model.id.includes("2.5-flash")) {
    const budgets = {
      minimal: 128,
      low: 2048,
      medium: 8192,
      high: 24576
    };
    return budgets[effort];
  }
  return -1;
}

// ../pi-mono/packages/ai/dist/providers/mistral.js
init_process_shim();
var import_mistralai = __toESM(require_mistralai(), 1);
var MISTRAL_TOOL_CALL_ID_LENGTH = 9;
var MAX_MISTRAL_ERROR_BODY_CHARS = 4e3;
var streamMistral = (model, context, options) => {
  const stream2 = new AssistantMessageEventStream();
  (async () => {
    const output = createOutput(model);
    try {
      const apiKey = options?.apiKey || getEnvApiKey(model.provider);
      if (!apiKey) {
        throw new Error(`No API key for provider: ${model.provider}`);
      }
      const mistral = new import_mistralai.Mistral({
        apiKey,
        serverURL: model.baseUrl
      });
      const normalizeMistralToolCallId = createMistralToolCallIdNormalizer();
      const transformedMessages = transformMessages(context.messages, model, (id) => normalizeMistralToolCallId(id));
      let payload = buildChatPayload(model, context, transformedMessages, options);
      const nextPayload = await options?.onPayload?.(payload, model);
      if (nextPayload !== void 0) {
        payload = nextPayload;
      }
      const mistralStream = await mistral.chat.stream(payload, buildRequestOptions(model, options));
      stream2.push({ type: "start", partial: output });
      await consumeChatStream(model, output, stream2, mistralStream);
      if (options?.signal?.aborted) {
        throw new Error("Request was aborted");
      }
      if (output.stopReason === "aborted" || output.stopReason === "error") {
        throw new Error("An unknown error occurred");
      }
      stream2.push({ type: "done", reason: output.stopReason, message: output });
      stream2.end();
    } catch (error) {
      output.stopReason = options?.signal?.aborted ? "aborted" : "error";
      output.errorMessage = formatMistralError(error);
      stream2.push({ type: "error", reason: output.stopReason, error: output });
      stream2.end();
    }
  })();
  return stream2;
};
var streamSimpleMistral = (model, context, options) => {
  const apiKey = options?.apiKey || getEnvApiKey(model.provider);
  if (!apiKey) {
    throw new Error(`No API key for provider: ${model.provider}`);
  }
  const base = buildBaseOptions(model, options, apiKey);
  const reasoning = clampReasoning(options?.reasoning);
  return streamMistral(model, context, {
    ...base,
    promptMode: model.reasoning && reasoning ? "reasoning" : void 0
  });
};
function createOutput(model) {
  return {
    role: "assistant",
    content: [],
    api: model.api,
    provider: model.provider,
    model: model.id,
    usage: {
      input: 0,
      output: 0,
      cacheRead: 0,
      cacheWrite: 0,
      totalTokens: 0,
      cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
    },
    stopReason: "stop",
    timestamp: Date.now()
  };
}
function createMistralToolCallIdNormalizer() {
  const idMap = /* @__PURE__ */ new Map();
  const reverseMap = /* @__PURE__ */ new Map();
  return (id) => {
    const existing = idMap.get(id);
    if (existing)
      return existing;
    let attempt = 0;
    while (true) {
      const candidate = deriveMistralToolCallId(id, attempt);
      const owner = reverseMap.get(candidate);
      if (!owner || owner === id) {
        idMap.set(id, candidate);
        reverseMap.set(candidate, id);
        return candidate;
      }
      attempt++;
    }
  };
}
function deriveMistralToolCallId(id, attempt) {
  const normalized = id.replace(/[^a-zA-Z0-9]/g, "");
  if (attempt === 0 && normalized.length === MISTRAL_TOOL_CALL_ID_LENGTH)
    return normalized;
  const seedBase = normalized || id;
  const seed = attempt === 0 ? seedBase : `${seedBase}:${attempt}`;
  return shortHash(seed).replace(/[^a-zA-Z0-9]/g, "").slice(0, MISTRAL_TOOL_CALL_ID_LENGTH);
}
function formatMistralError(error) {
  if (error instanceof Error) {
    const sdkError = error;
    const statusCode = typeof sdkError.statusCode === "number" ? sdkError.statusCode : void 0;
    const bodyText = typeof sdkError.body === "string" ? sdkError.body.trim() : void 0;
    if (statusCode !== void 0 && bodyText) {
      return `Mistral API error (${statusCode}): ${truncateErrorText(bodyText, MAX_MISTRAL_ERROR_BODY_CHARS)}`;
    }
    if (statusCode !== void 0)
      return `Mistral API error (${statusCode}): ${error.message}`;
    return error.message;
  }
  return safeJsonStringify(error);
}
function truncateErrorText(text3, maxChars) {
  if (text3.length <= maxChars)
    return text3;
  return `${text3.slice(0, maxChars)}... [truncated ${text3.length - maxChars} chars]`;
}
function safeJsonStringify(value) {
  try {
    const serialized = JSON.stringify(value);
    return serialized === void 0 ? String(value) : serialized;
  } catch {
    return String(value);
  }
}
function buildRequestOptions(model, options) {
  const requestOptions = {};
  if (options?.signal)
    requestOptions.signal = options.signal;
  requestOptions.retries = { strategy: "none" };
  const headers = {};
  if (model.headers)
    Object.assign(headers, model.headers);
  if (options?.headers)
    Object.assign(headers, options.headers);
  if (options?.sessionId && !headers["x-affinity"]) {
    headers["x-affinity"] = options.sessionId;
  }
  if (Object.keys(headers).length > 0) {
    requestOptions.headers = headers;
  }
  return requestOptions;
}
function buildChatPayload(model, context, messages, options) {
  const payload = {
    model: model.id,
    stream: true,
    messages: toChatMessages(messages, model.input.includes("image"))
  };
  if (context.tools?.length)
    payload.tools = toFunctionTools(context.tools);
  if (options?.temperature !== void 0)
    payload.temperature = options.temperature;
  if (options?.maxTokens !== void 0)
    payload.maxTokens = options.maxTokens;
  if (options?.toolChoice)
    payload.toolChoice = mapToolChoice2(options.toolChoice);
  if (options?.promptMode)
    payload.promptMode = options.promptMode;
  if (context.systemPrompt) {
    payload.messages.unshift({
      role: "system",
      content: sanitizeSurrogates(context.systemPrompt)
    });
  }
  return payload;
}
async function consumeChatStream(model, output, stream2, mistralStream) {
  let currentBlock = null;
  const blocks = output.content;
  const blockIndex = () => blocks.length - 1;
  const toolBlocksByKey = /* @__PURE__ */ new Map();
  const finishCurrentBlock = (block) => {
    if (!block)
      return;
    if (block.type === "text") {
      stream2.push({
        type: "text_end",
        contentIndex: blockIndex(),
        content: block.text,
        partial: output
      });
      return;
    }
    if (block.type === "thinking") {
      stream2.push({
        type: "thinking_end",
        contentIndex: blockIndex(),
        content: block.thinking,
        partial: output
      });
    }
  };
  for await (const event of mistralStream) {
    const chunk = event.data;
    if (chunk.usage) {
      output.usage.input = chunk.usage.promptTokens || 0;
      output.usage.output = chunk.usage.completionTokens || 0;
      output.usage.cacheRead = 0;
      output.usage.cacheWrite = 0;
      output.usage.totalTokens = chunk.usage.totalTokens || output.usage.input + output.usage.output;
      calculateCost(model, output.usage);
    }
    const choice = chunk.choices[0];
    if (!choice)
      continue;
    if (choice.finishReason) {
      output.stopReason = mapChatStopReason(choice.finishReason);
    }
    const delta = choice.delta;
    if (delta.content !== null && delta.content !== void 0) {
      const contentItems = typeof delta.content === "string" ? [delta.content] : delta.content;
      for (const item of contentItems) {
        if (typeof item === "string") {
          const textDelta = sanitizeSurrogates(item);
          if (!currentBlock || currentBlock.type !== "text") {
            finishCurrentBlock(currentBlock);
            currentBlock = { type: "text", text: "" };
            output.content.push(currentBlock);
            stream2.push({ type: "text_start", contentIndex: blockIndex(), partial: output });
          }
          currentBlock.text += textDelta;
          stream2.push({
            type: "text_delta",
            contentIndex: blockIndex(),
            delta: textDelta,
            partial: output
          });
          continue;
        }
        if (item.type === "thinking") {
          const deltaText = item.thinking.map((part) => "text" in part ? part.text : "").filter((text3) => text3.length > 0).join("");
          const thinkingDelta = sanitizeSurrogates(deltaText);
          if (!thinkingDelta)
            continue;
          if (!currentBlock || currentBlock.type !== "thinking") {
            finishCurrentBlock(currentBlock);
            currentBlock = { type: "thinking", thinking: "" };
            output.content.push(currentBlock);
            stream2.push({ type: "thinking_start", contentIndex: blockIndex(), partial: output });
          }
          currentBlock.thinking += thinkingDelta;
          stream2.push({
            type: "thinking_delta",
            contentIndex: blockIndex(),
            delta: thinkingDelta,
            partial: output
          });
          continue;
        }
        if (item.type === "text") {
          const textDelta = sanitizeSurrogates(item.text);
          if (!currentBlock || currentBlock.type !== "text") {
            finishCurrentBlock(currentBlock);
            currentBlock = { type: "text", text: "" };
            output.content.push(currentBlock);
            stream2.push({ type: "text_start", contentIndex: blockIndex(), partial: output });
          }
          currentBlock.text += textDelta;
          stream2.push({
            type: "text_delta",
            contentIndex: blockIndex(),
            delta: textDelta,
            partial: output
          });
        }
      }
    }
    const toolCalls = delta.toolCalls || [];
    for (const toolCall of toolCalls) {
      if (currentBlock) {
        finishCurrentBlock(currentBlock);
        currentBlock = null;
      }
      const callId = toolCall.id && toolCall.id !== "null" ? toolCall.id : deriveMistralToolCallId(`toolcall:${toolCall.index ?? 0}`, 0);
      const key = `${callId}:${toolCall.index || 0}`;
      const existingIndex = toolBlocksByKey.get(key);
      let block;
      if (existingIndex !== void 0) {
        const existing = output.content[existingIndex];
        if (existing?.type === "toolCall") {
          block = existing;
        }
      }
      if (!block) {
        block = {
          type: "toolCall",
          id: callId,
          name: toolCall.function.name,
          arguments: {},
          partialArgs: ""
        };
        output.content.push(block);
        toolBlocksByKey.set(key, output.content.length - 1);
        stream2.push({ type: "toolcall_start", contentIndex: output.content.length - 1, partial: output });
      }
      const argsDelta = typeof toolCall.function.arguments === "string" ? toolCall.function.arguments : JSON.stringify(toolCall.function.arguments || {});
      block.partialArgs = (block.partialArgs || "") + argsDelta;
      block.arguments = parseStreamingJson(block.partialArgs);
      stream2.push({
        type: "toolcall_delta",
        contentIndex: toolBlocksByKey.get(key),
        delta: argsDelta,
        partial: output
      });
    }
  }
  finishCurrentBlock(currentBlock);
  for (const index of toolBlocksByKey.values()) {
    const block = output.content[index];
    if (block.type !== "toolCall")
      continue;
    const toolBlock = block;
    toolBlock.arguments = parseStreamingJson(toolBlock.partialArgs);
    delete toolBlock.partialArgs;
    stream2.push({
      type: "toolcall_end",
      contentIndex: index,
      toolCall: toolBlock,
      partial: output
    });
  }
}
function toFunctionTools(tools) {
  return tools.map((tool) => ({
    type: "function",
    function: {
      name: tool.name,
      description: tool.description,
      parameters: tool.parameters,
      strict: false
    }
  }));
}
function toChatMessages(messages, supportsImages) {
  const result = [];
  for (const msg of messages) {
    if (msg.role === "user") {
      if (typeof msg.content === "string") {
        result.push({ role: "user", content: sanitizeSurrogates(msg.content) });
        continue;
      }
      const hadImages = msg.content.some((item) => item.type === "image");
      const content = msg.content.filter((item) => item.type === "text" || supportsImages).map((item) => {
        if (item.type === "text")
          return { type: "text", text: sanitizeSurrogates(item.text) };
        return { type: "image_url", imageUrl: `data:${item.mimeType};base64,${item.data}` };
      });
      if (content.length > 0) {
        result.push({ role: "user", content });
        continue;
      }
      if (hadImages && !supportsImages) {
        result.push({ role: "user", content: "(image omitted: model does not support images)" });
      }
      continue;
    }
    if (msg.role === "assistant") {
      const contentParts = [];
      const toolCalls = [];
      for (const block of msg.content) {
        if (block.type === "text") {
          if (block.text.trim().length > 0) {
            contentParts.push({ type: "text", text: sanitizeSurrogates(block.text) });
          }
          continue;
        }
        if (block.type === "thinking") {
          if (block.thinking.trim().length > 0) {
            contentParts.push({
              type: "thinking",
              thinking: [{ type: "text", text: sanitizeSurrogates(block.thinking) }]
            });
          }
          continue;
        }
        toolCalls.push({
          id: block.id,
          type: "function",
          function: { name: block.name, arguments: JSON.stringify(block.arguments || {}) }
        });
      }
      const assistantMessage = { role: "assistant" };
      if (contentParts.length > 0)
        assistantMessage.content = contentParts;
      if (toolCalls.length > 0)
        assistantMessage.toolCalls = toolCalls;
      if (contentParts.length > 0 || toolCalls.length > 0)
        result.push(assistantMessage);
      continue;
    }
    const toolContent = [];
    const textResult = msg.content.filter((part) => part.type === "text").map((part) => part.type === "text" ? sanitizeSurrogates(part.text) : "").join("\n");
    const hasImages = msg.content.some((part) => part.type === "image");
    const toolText = buildToolResultText(textResult, hasImages, supportsImages, msg.isError);
    toolContent.push({ type: "text", text: toolText });
    for (const part of msg.content) {
      if (!supportsImages)
        continue;
      if (part.type !== "image")
        continue;
      toolContent.push({
        type: "image_url",
        imageUrl: `data:${part.mimeType};base64,${part.data}`
      });
    }
    result.push({
      role: "tool",
      toolCallId: msg.toolCallId,
      name: msg.toolName,
      content: toolContent
    });
  }
  return result;
}
function buildToolResultText(text3, hasImages, supportsImages, isError2) {
  const trimmed = text3.trim();
  const errorPrefix = isError2 ? "[tool error] " : "";
  if (trimmed.length > 0) {
    const imageSuffix = hasImages && !supportsImages ? "\n[tool image omitted: model does not support images]" : "";
    return `${errorPrefix}${trimmed}${imageSuffix}`;
  }
  if (hasImages) {
    if (supportsImages) {
      return isError2 ? "[tool error] (see attached image)" : "(see attached image)";
    }
    return isError2 ? "[tool error] (image omitted: model does not support images)" : "(image omitted: model does not support images)";
  }
  return isError2 ? "[tool error] (no tool output)" : "(no tool output)";
}
function mapToolChoice2(choice) {
  if (!choice)
    return void 0;
  if (choice === "auto" || choice === "none" || choice === "any" || choice === "required") {
    return choice;
  }
  return {
    type: "function",
    function: { name: choice.function.name }
  };
}
function mapChatStopReason(reason) {
  if (reason === null)
    return "stop";
  switch (reason) {
    case "stop":
      return "stop";
    case "length":
    case "model_length":
      return "length";
    case "tool_calls":
      return "toolUse";
    case "error":
      return "error";
    default:
      return "stop";
  }
}

// ../pi-mono/packages/ai/dist/providers/openai-completions.js
init_process_shim();
function hasToolHistory(messages) {
  for (const msg of messages) {
    if (msg.role === "toolResult") {
      return true;
    }
    if (msg.role === "assistant") {
      if (msg.content.some((block) => block.type === "toolCall")) {
        return true;
      }
    }
  }
  return false;
}
var streamOpenAICompletions = (model, context, options) => {
  const stream2 = new AssistantMessageEventStream();
  (async () => {
    const output = {
      role: "assistant",
      content: [],
      api: model.api,
      provider: model.provider,
      model: model.id,
      usage: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0,
        totalTokens: 0,
        cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
      },
      stopReason: "stop",
      timestamp: Date.now()
    };
    try {
      const apiKey = options?.apiKey || getEnvApiKey(model.provider) || "";
      const client = createClient5(model, context, apiKey, options?.headers);
      let params = buildParams5(model, context, options);
      const nextParams = await options?.onPayload?.(params, model);
      if (nextParams !== void 0) {
        params = nextParams;
      }
      const openaiStream = await client.chat.completions.create(params, { signal: options?.signal });
      stream2.push({ type: "start", partial: output });
      let currentBlock = null;
      const blocks = output.content;
      const blockIndex = () => blocks.length - 1;
      const finishCurrentBlock = (block) => {
        if (block) {
          if (block.type === "text") {
            stream2.push({
              type: "text_end",
              contentIndex: blockIndex(),
              content: block.text,
              partial: output
            });
          } else if (block.type === "thinking") {
            stream2.push({
              type: "thinking_end",
              contentIndex: blockIndex(),
              content: block.thinking,
              partial: output
            });
          } else if (block.type === "toolCall") {
            block.arguments = parseStreamingJson(block.partialArgs);
            delete block.partialArgs;
            stream2.push({
              type: "toolcall_end",
              contentIndex: blockIndex(),
              toolCall: block,
              partial: output
            });
          }
        }
      };
      for await (const chunk of openaiStream) {
        if (chunk.usage) {
          output.usage = parseChunkUsage(chunk.usage, model);
        }
        const choice = chunk.choices?.[0];
        if (!choice)
          continue;
        if (!chunk.usage && choice.usage) {
          output.usage = parseChunkUsage(choice.usage, model);
        }
        if (choice.finish_reason) {
          output.stopReason = mapStopReason4(choice.finish_reason);
        }
        if (choice.delta) {
          if (choice.delta.content !== null && choice.delta.content !== void 0 && choice.delta.content.length > 0) {
            if (!currentBlock || currentBlock.type !== "text") {
              finishCurrentBlock(currentBlock);
              currentBlock = { type: "text", text: "" };
              output.content.push(currentBlock);
              stream2.push({ type: "text_start", contentIndex: blockIndex(), partial: output });
            }
            if (currentBlock.type === "text") {
              currentBlock.text += choice.delta.content;
              stream2.push({
                type: "text_delta",
                contentIndex: blockIndex(),
                delta: choice.delta.content,
                partial: output
              });
            }
          }
          const reasoningFields = ["reasoning_content", "reasoning", "reasoning_text"];
          let foundReasoningField = null;
          for (const field of reasoningFields) {
            if (choice.delta[field] !== null && choice.delta[field] !== void 0 && choice.delta[field].length > 0) {
              if (!foundReasoningField) {
                foundReasoningField = field;
                break;
              }
            }
          }
          if (foundReasoningField) {
            if (!currentBlock || currentBlock.type !== "thinking") {
              finishCurrentBlock(currentBlock);
              currentBlock = {
                type: "thinking",
                thinking: "",
                thinkingSignature: foundReasoningField
              };
              output.content.push(currentBlock);
              stream2.push({ type: "thinking_start", contentIndex: blockIndex(), partial: output });
            }
            if (currentBlock.type === "thinking") {
              const delta = choice.delta[foundReasoningField];
              currentBlock.thinking += delta;
              stream2.push({
                type: "thinking_delta",
                contentIndex: blockIndex(),
                delta,
                partial: output
              });
            }
          }
          if (choice?.delta?.tool_calls) {
            for (const toolCall of choice.delta.tool_calls) {
              if (!currentBlock || currentBlock.type !== "toolCall" || toolCall.id && currentBlock.id !== toolCall.id) {
                finishCurrentBlock(currentBlock);
                currentBlock = {
                  type: "toolCall",
                  id: toolCall.id || "",
                  name: toolCall.function?.name || "",
                  arguments: {},
                  partialArgs: ""
                };
                output.content.push(currentBlock);
                stream2.push({ type: "toolcall_start", contentIndex: blockIndex(), partial: output });
              }
              if (currentBlock.type === "toolCall") {
                if (toolCall.id)
                  currentBlock.id = toolCall.id;
                if (toolCall.function?.name)
                  currentBlock.name = toolCall.function.name;
                let delta = "";
                if (toolCall.function?.arguments) {
                  delta = toolCall.function.arguments;
                  currentBlock.partialArgs += toolCall.function.arguments;
                  currentBlock.arguments = parseStreamingJson(currentBlock.partialArgs);
                }
                stream2.push({
                  type: "toolcall_delta",
                  contentIndex: blockIndex(),
                  delta,
                  partial: output
                });
              }
            }
          }
          const reasoningDetails = choice.delta.reasoning_details;
          if (reasoningDetails && Array.isArray(reasoningDetails)) {
            for (const detail of reasoningDetails) {
              if (detail.type === "reasoning.encrypted" && detail.id && detail.data) {
                const matchingToolCall = output.content.find((b4) => b4.type === "toolCall" && b4.id === detail.id);
                if (matchingToolCall) {
                  matchingToolCall.thoughtSignature = JSON.stringify(detail);
                }
              }
            }
          }
        }
      }
      finishCurrentBlock(currentBlock);
      if (options?.signal?.aborted) {
        throw new Error("Request was aborted");
      }
      if (output.stopReason === "aborted" || output.stopReason === "error") {
        throw new Error("An unknown error occurred");
      }
      stream2.push({ type: "done", reason: output.stopReason, message: output });
      stream2.end();
    } catch (error) {
      for (const block of output.content)
        delete block.index;
      output.stopReason = options?.signal?.aborted ? "aborted" : "error";
      output.errorMessage = error instanceof Error ? error.message : JSON.stringify(error);
      const rawMetadata = error?.error?.metadata?.raw;
      if (rawMetadata)
        output.errorMessage += `
${rawMetadata}`;
      stream2.push({ type: "error", reason: output.stopReason, error: output });
      stream2.end();
    }
  })();
  return stream2;
};
var streamSimpleOpenAICompletions = (model, context, options) => {
  const apiKey = options?.apiKey || getEnvApiKey(model.provider);
  if (!apiKey) {
    throw new Error(`No API key for provider: ${model.provider}`);
  }
  const base = buildBaseOptions(model, options, apiKey);
  const reasoningEffort = supportsXhigh(model) ? options?.reasoning : clampReasoning(options?.reasoning);
  const toolChoice = options?.toolChoice;
  return streamOpenAICompletions(model, context, {
    ...base,
    reasoningEffort,
    toolChoice
  });
};
function createClient5(model, context, apiKey, optionsHeaders) {
  if (!apiKey) {
    if (!process.env.OPENAI_API_KEY) {
      throw new Error("OpenAI API key is required. Set OPENAI_API_KEY environment variable or pass it as an argument.");
    }
    apiKey = process.env.OPENAI_API_KEY;
  }
  const headers = { ...model.headers };
  if (model.provider === "github-copilot") {
    const hasImages = hasCopilotVisionInput(context.messages);
    const copilotHeaders = buildCopilotDynamicHeaders({
      messages: context.messages,
      hasImages
    });
    Object.assign(headers, copilotHeaders);
  }
  if (optionsHeaders) {
    Object.assign(headers, optionsHeaders);
  }
  return new OpenAI({
    apiKey,
    baseURL: model.baseUrl,
    dangerouslyAllowBrowser: true,
    defaultHeaders: headers
  });
}
function buildParams5(model, context, options) {
  const compat = getCompat(model);
  const messages = convertMessages3(model, context, compat);
  maybeAddOpenRouterAnthropicCacheControl(model, messages);
  const params = {
    model: model.id,
    messages,
    stream: true
  };
  if (compat.supportsUsageInStreaming !== false) {
    params.stream_options = { include_usage: true };
  }
  if (compat.supportsStore) {
    params.store = false;
  }
  if (options?.maxTokens) {
    if (compat.maxTokensField === "max_tokens") {
      params.max_tokens = options.maxTokens;
    } else {
      params.max_completion_tokens = options.maxTokens;
    }
  }
  if (options?.temperature !== void 0) {
    params.temperature = options.temperature;
  }
  if (context.tools) {
    params.tools = convertTools3(context.tools, compat);
  } else if (hasToolHistory(context.messages)) {
    params.tools = [];
  }
  if (options?.toolChoice) {
    params.tool_choice = options.toolChoice;
  }
  if (compat.thinkingFormat === "zai" && model.reasoning) {
    params.enable_thinking = !!options?.reasoningEffort;
  } else if (compat.thinkingFormat === "qwen" && model.reasoning) {
    params.enable_thinking = !!options?.reasoningEffort;
  } else if (compat.thinkingFormat === "qwen-chat-template" && model.reasoning) {
    params.chat_template_kwargs = { enable_thinking: !!options?.reasoningEffort };
  } else if (options?.reasoningEffort && model.reasoning && compat.supportsReasoningEffort) {
    params.reasoning_effort = mapReasoningEffort(options.reasoningEffort, compat.reasoningEffortMap);
  }
  if (model.baseUrl.includes("openrouter.ai") && model.compat?.openRouterRouting) {
    params.provider = model.compat.openRouterRouting;
  }
  if (model.baseUrl.includes("ai-gateway.vercel.sh") && model.compat?.vercelGatewayRouting) {
    const routing = model.compat.vercelGatewayRouting;
    if (routing.only || routing.order) {
      const gatewayOptions = {};
      if (routing.only)
        gatewayOptions.only = routing.only;
      if (routing.order)
        gatewayOptions.order = routing.order;
      params.providerOptions = { gateway: gatewayOptions };
    }
  }
  return params;
}
function mapReasoningEffort(effort, reasoningEffortMap) {
  return reasoningEffortMap[effort] ?? effort;
}
function maybeAddOpenRouterAnthropicCacheControl(model, messages) {
  if (model.provider !== "openrouter" || !model.id.startsWith("anthropic/"))
    return;
  for (let i7 = messages.length - 1; i7 >= 0; i7--) {
    const msg = messages[i7];
    if (msg.role !== "user" && msg.role !== "assistant")
      continue;
    const content = msg.content;
    if (typeof content === "string") {
      msg.content = [
        Object.assign({ type: "text", text: content }, { cache_control: { type: "ephemeral" } })
      ];
      return;
    }
    if (!Array.isArray(content))
      continue;
    for (let j3 = content.length - 1; j3 >= 0; j3--) {
      const part = content[j3];
      if (part?.type === "text") {
        Object.assign(part, { cache_control: { type: "ephemeral" } });
        return;
      }
    }
  }
}
function convertMessages3(model, context, compat) {
  const params = [];
  const normalizeToolCallId2 = (id) => {
    if (id.includes("|")) {
      const [callId] = id.split("|");
      return callId.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 40);
    }
    if (model.provider === "openai")
      return id.length > 40 ? id.slice(0, 40) : id;
    return id;
  };
  const transformedMessages = transformMessages(context.messages, model, (id) => normalizeToolCallId2(id));
  if (context.systemPrompt) {
    const useDeveloperRole = model.reasoning && compat.supportsDeveloperRole;
    const role = useDeveloperRole ? "developer" : "system";
    params.push({ role, content: sanitizeSurrogates(context.systemPrompt) });
  }
  let lastRole = null;
  for (let i7 = 0; i7 < transformedMessages.length; i7++) {
    const msg = transformedMessages[i7];
    if (compat.requiresAssistantAfterToolResult && lastRole === "toolResult" && msg.role === "user") {
      params.push({
        role: "assistant",
        content: "I have processed the tool results."
      });
    }
    if (msg.role === "user") {
      if (typeof msg.content === "string") {
        params.push({
          role: "user",
          content: sanitizeSurrogates(msg.content)
        });
      } else {
        const content = msg.content.map((item) => {
          if (item.type === "text") {
            return {
              type: "text",
              text: sanitizeSurrogates(item.text)
            };
          } else {
            return {
              type: "image_url",
              image_url: {
                url: `data:${item.mimeType};base64,${item.data}`
              }
            };
          }
        });
        const filteredContent = !model.input.includes("image") ? content.filter((c6) => c6.type !== "image_url") : content;
        if (filteredContent.length === 0)
          continue;
        params.push({
          role: "user",
          content: filteredContent
        });
      }
    } else if (msg.role === "assistant") {
      const assistantMsg = {
        role: "assistant",
        content: compat.requiresAssistantAfterToolResult ? "" : null
      };
      const textBlocks = msg.content.filter((b4) => b4.type === "text");
      const nonEmptyTextBlocks = textBlocks.filter((b4) => b4.text && b4.text.trim().length > 0);
      if (nonEmptyTextBlocks.length > 0) {
        assistantMsg.content = nonEmptyTextBlocks.map((b4) => sanitizeSurrogates(b4.text)).join("");
      }
      const thinkingBlocks = msg.content.filter((b4) => b4.type === "thinking");
      const nonEmptyThinkingBlocks = thinkingBlocks.filter((b4) => b4.thinking && b4.thinking.trim().length > 0);
      if (nonEmptyThinkingBlocks.length > 0) {
        if (compat.requiresThinkingAsText) {
          const thinkingText = nonEmptyThinkingBlocks.map((b4) => b4.thinking).join("\n\n");
          const textContent = assistantMsg.content;
          if (textContent) {
            textContent.unshift({ type: "text", text: thinkingText });
          } else {
            assistantMsg.content = [{ type: "text", text: thinkingText }];
          }
        } else {
          const signature = nonEmptyThinkingBlocks[0].thinkingSignature;
          if (signature && signature.length > 0) {
            assistantMsg[signature] = nonEmptyThinkingBlocks.map((b4) => b4.thinking).join("\n");
          }
        }
      }
      const toolCalls = msg.content.filter((b4) => b4.type === "toolCall");
      if (toolCalls.length > 0) {
        assistantMsg.tool_calls = toolCalls.map((tc) => ({
          id: tc.id,
          type: "function",
          function: {
            name: tc.name,
            arguments: JSON.stringify(tc.arguments)
          }
        }));
        const reasoningDetails = toolCalls.filter((tc) => tc.thoughtSignature).map((tc) => {
          try {
            return JSON.parse(tc.thoughtSignature);
          } catch {
            return null;
          }
        }).filter(Boolean);
        if (reasoningDetails.length > 0) {
          assistantMsg.reasoning_details = reasoningDetails;
        }
      }
      const content = assistantMsg.content;
      const hasContent = content !== null && content !== void 0 && (typeof content === "string" ? content.length > 0 : content.length > 0);
      if (!hasContent && !assistantMsg.tool_calls) {
        continue;
      }
      params.push(assistantMsg);
    } else if (msg.role === "toolResult") {
      const imageBlocks = [];
      let j3 = i7;
      for (; j3 < transformedMessages.length && transformedMessages[j3].role === "toolResult"; j3++) {
        const toolMsg = transformedMessages[j3];
        const textResult = toolMsg.content.filter((c6) => c6.type === "text").map((c6) => c6.text).join("\n");
        const hasImages = toolMsg.content.some((c6) => c6.type === "image");
        const hasText = textResult.length > 0;
        const toolResultMsg = {
          role: "tool",
          content: sanitizeSurrogates(hasText ? textResult : "(see attached image)"),
          tool_call_id: toolMsg.toolCallId
        };
        if (compat.requiresToolResultName && toolMsg.toolName) {
          toolResultMsg.name = toolMsg.toolName;
        }
        params.push(toolResultMsg);
        if (hasImages && model.input.includes("image")) {
          for (const block of toolMsg.content) {
            if (block.type === "image") {
              imageBlocks.push({
                type: "image_url",
                image_url: {
                  url: `data:${block.mimeType};base64,${block.data}`
                }
              });
            }
          }
        }
      }
      i7 = j3 - 1;
      if (imageBlocks.length > 0) {
        if (compat.requiresAssistantAfterToolResult) {
          params.push({
            role: "assistant",
            content: "I have processed the tool results."
          });
        }
        params.push({
          role: "user",
          content: [
            {
              type: "text",
              text: "Attached image(s) from tool result:"
            },
            ...imageBlocks
          ]
        });
        lastRole = "user";
      } else {
        lastRole = "toolResult";
      }
      continue;
    }
    lastRole = msg.role;
  }
  return params;
}
function convertTools3(tools, compat) {
  return tools.map((tool) => ({
    type: "function",
    function: {
      name: tool.name,
      description: tool.description,
      parameters: tool.parameters,
      // TypeBox already generates JSON Schema
      // Only include strict if provider supports it. Some reject unknown fields.
      ...compat.supportsStrictMode !== false && { strict: false }
    }
  }));
}
function parseChunkUsage(rawUsage, model) {
  const cachedTokens = rawUsage.prompt_tokens_details?.cached_tokens || 0;
  const reasoningTokens = rawUsage.completion_tokens_details?.reasoning_tokens || 0;
  const input = (rawUsage.prompt_tokens || 0) - cachedTokens;
  const outputTokens = (rawUsage.completion_tokens || 0) + reasoningTokens;
  const usage = {
    input,
    output: outputTokens,
    cacheRead: cachedTokens,
    cacheWrite: 0,
    totalTokens: input + outputTokens + cachedTokens,
    cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
  };
  calculateCost(model, usage);
  return usage;
}
function mapStopReason4(reason) {
  if (reason === null)
    return "stop";
  switch (reason) {
    case "stop":
    case "end":
      return "stop";
    case "length":
      return "length";
    case "function_call":
    case "tool_calls":
      return "toolUse";
    case "content_filter":
      return "error";
    default: {
      const _exhaustive = reason;
      throw new Error(`Unhandled stop reason: ${_exhaustive}`);
    }
  }
}
function detectCompat(model) {
  const provider = model.provider;
  const baseUrl = model.baseUrl;
  const isZai = provider === "zai" || baseUrl.includes("api.z.ai");
  const isNonStandard = provider === "cerebras" || baseUrl.includes("cerebras.ai") || provider === "xai" || baseUrl.includes("api.x.ai") || baseUrl.includes("chutes.ai") || baseUrl.includes("deepseek.com") || isZai || provider === "opencode" || baseUrl.includes("opencode.ai");
  const useMaxTokens = baseUrl.includes("chutes.ai");
  const isGrok = provider === "xai" || baseUrl.includes("api.x.ai");
  const isGroq = provider === "groq" || baseUrl.includes("groq.com");
  const reasoningEffortMap = isGroq && model.id === "qwen/qwen3-32b" ? {
    minimal: "default",
    low: "default",
    medium: "default",
    high: "default",
    xhigh: "default"
  } : {};
  return {
    supportsStore: !isNonStandard,
    supportsDeveloperRole: !isNonStandard,
    supportsReasoningEffort: !isGrok && !isZai,
    reasoningEffortMap,
    supportsUsageInStreaming: true,
    maxTokensField: useMaxTokens ? "max_tokens" : "max_completion_tokens",
    requiresToolResultName: false,
    requiresAssistantAfterToolResult: false,
    requiresThinkingAsText: false,
    thinkingFormat: isZai ? "zai" : "openai",
    openRouterRouting: {},
    vercelGatewayRouting: {},
    supportsStrictMode: true
  };
}
function getCompat(model) {
  const detected = detectCompat(model);
  if (!model.compat)
    return detected;
  return {
    supportsStore: model.compat.supportsStore ?? detected.supportsStore,
    supportsDeveloperRole: model.compat.supportsDeveloperRole ?? detected.supportsDeveloperRole,
    supportsReasoningEffort: model.compat.supportsReasoningEffort ?? detected.supportsReasoningEffort,
    reasoningEffortMap: model.compat.reasoningEffortMap ?? detected.reasoningEffortMap,
    supportsUsageInStreaming: model.compat.supportsUsageInStreaming ?? detected.supportsUsageInStreaming,
    maxTokensField: model.compat.maxTokensField ?? detected.maxTokensField,
    requiresToolResultName: model.compat.requiresToolResultName ?? detected.requiresToolResultName,
    requiresAssistantAfterToolResult: model.compat.requiresAssistantAfterToolResult ?? detected.requiresAssistantAfterToolResult,
    requiresThinkingAsText: model.compat.requiresThinkingAsText ?? detected.requiresThinkingAsText,
    thinkingFormat: model.compat.thinkingFormat ?? detected.thinkingFormat,
    openRouterRouting: model.compat.openRouterRouting ?? {},
    vercelGatewayRouting: model.compat.vercelGatewayRouting ?? detected.vercelGatewayRouting,
    supportsStrictMode: model.compat.supportsStrictMode ?? detected.supportsStrictMode
  };
}

// ../pi-mono/packages/ai/dist/providers/openai-responses.js
init_process_shim();
var OPENAI_TOOL_CALL_PROVIDERS = /* @__PURE__ */ new Set(["openai", "openai-codex", "opencode"]);
function resolveCacheRetention2(cacheRetention) {
  if (cacheRetention) {
    return cacheRetention;
  }
  if (typeof process !== "undefined" && process.env.PI_CACHE_RETENTION === "long") {
    return "long";
  }
  return "short";
}
function getPromptCacheRetention(baseUrl, cacheRetention) {
  if (cacheRetention !== "long") {
    return void 0;
  }
  if (baseUrl.includes("api.openai.com")) {
    return "24h";
  }
  return void 0;
}
var streamOpenAIResponses = (model, context, options) => {
  const stream2 = new AssistantMessageEventStream();
  (async () => {
    const output = {
      role: "assistant",
      content: [],
      api: model.api,
      provider: model.provider,
      model: model.id,
      usage: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0,
        totalTokens: 0,
        cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
      },
      stopReason: "stop",
      timestamp: Date.now()
    };
    try {
      const apiKey = options?.apiKey || getEnvApiKey(model.provider) || "";
      const client = createClient6(model, context, apiKey, options?.headers);
      let params = buildParams6(model, context, options);
      const nextParams = await options?.onPayload?.(params, model);
      if (nextParams !== void 0) {
        params = nextParams;
      }
      const openaiStream = await client.responses.create(params, options?.signal ? { signal: options.signal } : void 0);
      stream2.push({ type: "start", partial: output });
      await processResponsesStream(openaiStream, output, stream2, model, {
        serviceTier: options?.serviceTier,
        applyServiceTierPricing
      });
      if (options?.signal?.aborted) {
        throw new Error("Request was aborted");
      }
      if (output.stopReason === "aborted" || output.stopReason === "error") {
        throw new Error("An unknown error occurred");
      }
      stream2.push({ type: "done", reason: output.stopReason, message: output });
      stream2.end();
    } catch (error) {
      for (const block of output.content)
        delete block.index;
      output.stopReason = options?.signal?.aborted ? "aborted" : "error";
      output.errorMessage = error instanceof Error ? error.message : JSON.stringify(error);
      stream2.push({ type: "error", reason: output.stopReason, error: output });
      stream2.end();
    }
  })();
  return stream2;
};
var streamSimpleOpenAIResponses = (model, context, options) => {
  const apiKey = options?.apiKey || getEnvApiKey(model.provider);
  if (!apiKey) {
    throw new Error(`No API key for provider: ${model.provider}`);
  }
  const base = buildBaseOptions(model, options, apiKey);
  const reasoningEffort = supportsXhigh(model) ? options?.reasoning : clampReasoning(options?.reasoning);
  return streamOpenAIResponses(model, context, {
    ...base,
    reasoningEffort
  });
};
function createClient6(model, context, apiKey, optionsHeaders) {
  if (!apiKey) {
    if (!process.env.OPENAI_API_KEY) {
      throw new Error("OpenAI API key is required. Set OPENAI_API_KEY environment variable or pass it as an argument.");
    }
    apiKey = process.env.OPENAI_API_KEY;
  }
  const headers = { ...model.headers };
  if (model.provider === "github-copilot") {
    const hasImages = hasCopilotVisionInput(context.messages);
    const copilotHeaders = buildCopilotDynamicHeaders({
      messages: context.messages,
      hasImages
    });
    Object.assign(headers, copilotHeaders);
  }
  if (optionsHeaders) {
    Object.assign(headers, optionsHeaders);
  }
  return new OpenAI({
    apiKey,
    baseURL: model.baseUrl,
    dangerouslyAllowBrowser: true,
    defaultHeaders: headers
  });
}
function buildParams6(model, context, options) {
  const messages = convertResponsesMessages(model, context, OPENAI_TOOL_CALL_PROVIDERS);
  const cacheRetention = resolveCacheRetention2(options?.cacheRetention);
  const params = {
    model: model.id,
    input: messages,
    stream: true,
    prompt_cache_key: cacheRetention === "none" ? void 0 : options?.sessionId,
    prompt_cache_retention: getPromptCacheRetention(model.baseUrl, cacheRetention),
    store: false
  };
  if (options?.maxTokens) {
    params.max_output_tokens = options?.maxTokens;
  }
  if (options?.temperature !== void 0) {
    params.temperature = options?.temperature;
  }
  if (options?.serviceTier !== void 0) {
    params.service_tier = options.serviceTier;
  }
  if (context.tools) {
    params.tools = convertResponsesTools(context.tools);
  }
  if (model.reasoning) {
    if (options?.reasoningEffort || options?.reasoningSummary) {
      params.reasoning = {
        effort: options?.reasoningEffort || "medium",
        summary: options?.reasoningSummary || "auto"
      };
      params.include = ["reasoning.encrypted_content"];
    } else {
      if (model.name.startsWith("gpt-5")) {
        messages.push({
          role: "developer",
          content: [
            {
              type: "input_text",
              text: "# Juice: 0 !important"
            }
          ]
        });
      }
    }
  }
  return params;
}
function getServiceTierCostMultiplier(serviceTier) {
  switch (serviceTier) {
    case "flex":
      return 0.5;
    case "priority":
      return 2;
    default:
      return 1;
  }
}
function applyServiceTierPricing(usage, serviceTier) {
  const multiplier = getServiceTierCostMultiplier(serviceTier);
  if (multiplier === 1)
    return;
  usage.cost.input *= multiplier;
  usage.cost.output *= multiplier;
  usage.cost.cacheRead *= multiplier;
  usage.cost.cacheWrite *= multiplier;
  usage.cost.total = usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite;
}

// ../pi-mono/packages/ai/dist/providers/register-builtins.js
init_process_shim();

// ../pi-mono/packages/ai/dist/providers/openai-codex-responses.js
init_process_shim();
var _os = null;
var dynamicImport2 = (specifier) => import(specifier);
var NODE_OS_SPECIFIER2 = "node:os";
if (typeof process !== "undefined" && (process.versions?.node || process.versions?.bun)) {
  dynamicImport2(NODE_OS_SPECIFIER2).then((m4) => {
    _os = m4;
  });
}
var DEFAULT_CODEX_BASE_URL = "https://chatgpt.com/backend-api";
var JWT_CLAIM_PATH = "https://api.openai.com/auth";
var MAX_RETRIES2 = 3;
var BASE_DELAY_MS2 = 1e3;
var CODEX_TOOL_CALL_PROVIDERS = /* @__PURE__ */ new Set(["openai", "openai-codex", "opencode"]);
var CODEX_RESPONSE_STATUSES = /* @__PURE__ */ new Set([
  "completed",
  "incomplete",
  "failed",
  "cancelled",
  "queued",
  "in_progress"
]);
function isRetryableError2(status, errorText) {
  if (status === 429 || status === 500 || status === 502 || status === 503 || status === 504) {
    return true;
  }
  return /rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(errorText);
}
function sleep5(ms, signal) {
  return new Promise((resolve, reject) => {
    if (signal?.aborted) {
      reject(new Error("Request was aborted"));
      return;
    }
    const timeout = setTimeout(resolve, ms);
    signal?.addEventListener("abort", () => {
      clearTimeout(timeout);
      reject(new Error("Request was aborted"));
    });
  });
}
var streamOpenAICodexResponses = (model, context, options) => {
  const stream2 = new AssistantMessageEventStream();
  (async () => {
    const output = {
      role: "assistant",
      content: [],
      api: "openai-codex-responses",
      provider: model.provider,
      model: model.id,
      usage: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0,
        totalTokens: 0,
        cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
      },
      stopReason: "stop",
      timestamp: Date.now()
    };
    try {
      const apiKey = options?.apiKey || getEnvApiKey(model.provider) || "";
      if (!apiKey) {
        throw new Error(`No API key for provider: ${model.provider}`);
      }
      const accountId = extractAccountId(apiKey);
      let body = buildRequestBody(model, context, options);
      const nextBody = await options?.onPayload?.(body, model);
      if (nextBody !== void 0) {
        body = nextBody;
      }
      const websocketRequestId = options?.sessionId || createCodexRequestId();
      const sseHeaders = buildSSEHeaders(model.headers, options?.headers, accountId, apiKey, options?.sessionId);
      const websocketHeaders = buildWebSocketHeaders(model.headers, options?.headers, accountId, apiKey, websocketRequestId);
      const bodyJson = JSON.stringify(body);
      const transport = options?.transport || "sse";
      if (transport !== "sse") {
        let websocketStarted = false;
        try {
          await processWebSocketStream(resolveCodexWebSocketUrl(model.baseUrl), body, websocketHeaders, output, stream2, model, () => {
            websocketStarted = true;
          }, options);
          if (options?.signal?.aborted) {
            throw new Error("Request was aborted");
          }
          stream2.push({
            type: "done",
            reason: output.stopReason,
            message: output
          });
          stream2.end();
          return;
        } catch (error) {
          if (transport === "websocket" || websocketStarted) {
            throw error;
          }
        }
      }
      let response;
      let lastError;
      for (let attempt = 0; attempt <= MAX_RETRIES2; attempt++) {
        if (options?.signal?.aborted) {
          throw new Error("Request was aborted");
        }
        try {
          response = await fetch(resolveCodexUrl(model.baseUrl), {
            method: "POST",
            headers: sseHeaders,
            body: bodyJson,
            signal: options?.signal
          });
          if (response.ok) {
            break;
          }
          const errorText = await response.text();
          if (attempt < MAX_RETRIES2 && isRetryableError2(response.status, errorText)) {
            const delayMs = BASE_DELAY_MS2 * 2 ** attempt;
            await sleep5(delayMs, options?.signal);
            continue;
          }
          const fakeResponse = new Response(errorText, {
            status: response.status,
            statusText: response.statusText
          });
          const info2 = await parseErrorResponse(fakeResponse);
          throw new Error(info2.friendlyMessage || info2.message);
        } catch (error) {
          if (error instanceof Error) {
            if (error.name === "AbortError" || error.message === "Request was aborted") {
              throw new Error("Request was aborted");
            }
          }
          lastError = error instanceof Error ? error : new Error(String(error));
          if (attempt < MAX_RETRIES2 && !lastError.message.includes("usage limit")) {
            const delayMs = BASE_DELAY_MS2 * 2 ** attempt;
            await sleep5(delayMs, options?.signal);
            continue;
          }
          throw lastError;
        }
      }
      if (!response?.ok) {
        throw lastError ?? new Error("Failed after retries");
      }
      if (!response.body) {
        throw new Error("No response body");
      }
      stream2.push({ type: "start", partial: output });
      await processStream(response, output, stream2, model);
      if (options?.signal?.aborted) {
        throw new Error("Request was aborted");
      }
      stream2.push({ type: "done", reason: output.stopReason, message: output });
      stream2.end();
    } catch (error) {
      output.stopReason = options?.signal?.aborted ? "aborted" : "error";
      output.errorMessage = error instanceof Error ? error.message : String(error);
      stream2.push({ type: "error", reason: output.stopReason, error: output });
      stream2.end();
    }
  })();
  return stream2;
};
var streamSimpleOpenAICodexResponses = (model, context, options) => {
  const apiKey = options?.apiKey || getEnvApiKey(model.provider);
  if (!apiKey) {
    throw new Error(`No API key for provider: ${model.provider}`);
  }
  const base = buildBaseOptions(model, options, apiKey);
  const reasoningEffort = supportsXhigh(model) ? options?.reasoning : clampReasoning(options?.reasoning);
  return streamOpenAICodexResponses(model, context, {
    ...base,
    reasoningEffort
  });
};
function buildRequestBody(model, context, options) {
  const messages = convertResponsesMessages(model, context, CODEX_TOOL_CALL_PROVIDERS, {
    includeSystemPrompt: false
  });
  const body = {
    model: model.id,
    store: false,
    stream: true,
    instructions: context.systemPrompt,
    input: messages,
    text: { verbosity: options?.textVerbosity || "medium" },
    include: ["reasoning.encrypted_content"],
    prompt_cache_key: options?.sessionId,
    tool_choice: "auto",
    parallel_tool_calls: true
  };
  if (options?.temperature !== void 0) {
    body.temperature = options.temperature;
  }
  if (context.tools) {
    body.tools = convertResponsesTools(context.tools, { strict: null });
  }
  if (options?.reasoningEffort !== void 0) {
    body.reasoning = {
      effort: clampReasoningEffort(model.id, options.reasoningEffort),
      summary: options.reasoningSummary ?? "auto"
    };
  }
  return body;
}
function clampReasoningEffort(modelId, effort) {
  const id = modelId.includes("/") ? modelId.split("/").pop() : modelId;
  if ((id.startsWith("gpt-5.2") || id.startsWith("gpt-5.3") || id.startsWith("gpt-5.4")) && effort === "minimal")
    return "low";
  if (id === "gpt-5.1" && effort === "xhigh")
    return "high";
  if (id === "gpt-5.1-codex-mini")
    return effort === "high" || effort === "xhigh" ? "high" : "medium";
  return effort;
}
function resolveCodexUrl(baseUrl) {
  const raw = baseUrl && baseUrl.trim().length > 0 ? baseUrl : DEFAULT_CODEX_BASE_URL;
  const normalized = raw.replace(/\/+$/, "");
  if (normalized.endsWith("/codex/responses"))
    return normalized;
  if (normalized.endsWith("/codex"))
    return `${normalized}/responses`;
  return `${normalized}/codex/responses`;
}
function resolveCodexWebSocketUrl(baseUrl) {
  const url = new URL(resolveCodexUrl(baseUrl));
  if (url.protocol === "https:")
    url.protocol = "wss:";
  if (url.protocol === "http:")
    url.protocol = "ws:";
  return url.toString();
}
async function processStream(response, output, stream2, model) {
  await processResponsesStream(mapCodexEvents(parseSSE(response)), output, stream2, model);
}
async function* mapCodexEvents(events) {
  for await (const event of events) {
    const type = typeof event.type === "string" ? event.type : void 0;
    if (!type)
      continue;
    if (type === "error") {
      const code = event.code || "";
      const message = event.message || "";
      throw new Error(`Codex error: ${message || code || JSON.stringify(event)}`);
    }
    if (type === "response.failed") {
      const msg = event.response?.error?.message;
      throw new Error(msg || "Codex response failed");
    }
    if (type === "response.done" || type === "response.completed" || type === "response.incomplete") {
      const response = event.response;
      const normalizedResponse = response ? { ...response, status: normalizeCodexStatus(response.status) } : response;
      yield { ...event, type: "response.completed", response: normalizedResponse };
      return;
    }
    yield event;
  }
}
function normalizeCodexStatus(status) {
  if (typeof status !== "string")
    return void 0;
  return CODEX_RESPONSE_STATUSES.has(status) ? status : void 0;
}
async function* parseSSE(response) {
  if (!response.body)
    return;
  const reader = response.body.getReader();
  const decoder = new TextDecoder();
  let buffer = "";
  try {
    while (true) {
      const { done, value } = await reader.read();
      if (done)
        break;
      buffer += decoder.decode(value, { stream: true });
      let idx = buffer.indexOf("\n\n");
      while (idx !== -1) {
        const chunk = buffer.slice(0, idx);
        buffer = buffer.slice(idx + 2);
        const dataLines = chunk.split("\n").filter((l5) => l5.startsWith("data:")).map((l5) => l5.slice(5).trim());
        if (dataLines.length > 0) {
          const data = dataLines.join("\n").trim();
          if (data && data !== "[DONE]") {
            try {
              yield JSON.parse(data);
            } catch {
            }
          }
        }
        idx = buffer.indexOf("\n\n");
      }
    }
  } finally {
    try {
      await reader.cancel();
    } catch {
    }
    try {
      reader.releaseLock();
    } catch {
    }
  }
}
var OPENAI_BETA_RESPONSES_WEBSOCKETS = "responses_websockets=2026-02-06";
var SESSION_WEBSOCKET_CACHE_TTL_MS = 5 * 60 * 1e3;
var websocketSessionCache = /* @__PURE__ */ new Map();
function getWebSocketConstructor() {
  const ctor = globalThis.WebSocket;
  if (typeof ctor !== "function")
    return null;
  return ctor;
}
function headersToRecord(headers) {
  const out = {};
  for (const [key, value] of headers.entries()) {
    out[key] = value;
  }
  return out;
}
function getWebSocketReadyState(socket) {
  const readyState = socket.readyState;
  return typeof readyState === "number" ? readyState : void 0;
}
function isWebSocketReusable(socket) {
  const readyState = getWebSocketReadyState(socket);
  return readyState === void 0 || readyState === 1;
}
function closeWebSocketSilently(socket, code = 1e3, reason = "done") {
  try {
    socket.close(code, reason);
  } catch {
  }
}
function scheduleSessionWebSocketExpiry(sessionId, entry) {
  if (entry.idleTimer) {
    clearTimeout(entry.idleTimer);
  }
  entry.idleTimer = setTimeout(() => {
    if (entry.busy)
      return;
    closeWebSocketSilently(entry.socket, 1e3, "idle_timeout");
    websocketSessionCache.delete(sessionId);
  }, SESSION_WEBSOCKET_CACHE_TTL_MS);
}
async function connectWebSocket(url, headers, signal) {
  const WebSocketCtor = getWebSocketConstructor();
  if (!WebSocketCtor) {
    throw new Error("WebSocket transport is not available in this runtime");
  }
  const wsHeaders = headersToRecord(headers);
  delete wsHeaders["OpenAI-Beta"];
  return new Promise((resolve, reject) => {
    let settled = false;
    let socket;
    try {
      socket = new WebSocketCtor(url, { headers: wsHeaders });
    } catch (error) {
      reject(error instanceof Error ? error : new Error(String(error)));
      return;
    }
    const onOpen = () => {
      if (settled)
        return;
      settled = true;
      cleanup();
      resolve(socket);
    };
    const onError = (event) => {
      const error = extractWebSocketError(event);
      if (settled)
        return;
      settled = true;
      cleanup();
      reject(error);
    };
    const onClose = (event) => {
      const error = extractWebSocketCloseError(event);
      if (settled)
        return;
      settled = true;
      cleanup();
      reject(error);
    };
    const onAbort = () => {
      if (settled)
        return;
      settled = true;
      cleanup();
      socket.close(1e3, "aborted");
      reject(new Error("Request was aborted"));
    };
    const cleanup = () => {
      socket.removeEventListener("open", onOpen);
      socket.removeEventListener("error", onError);
      socket.removeEventListener("close", onClose);
      signal?.removeEventListener("abort", onAbort);
    };
    socket.addEventListener("open", onOpen);
    socket.addEventListener("error", onError);
    socket.addEventListener("close", onClose);
    signal?.addEventListener("abort", onAbort);
  });
}
async function acquireWebSocket(url, headers, sessionId, signal) {
  if (!sessionId) {
    const socket2 = await connectWebSocket(url, headers, signal);
    return {
      socket: socket2,
      release: ({ keep } = {}) => {
        if (keep === false) {
          closeWebSocketSilently(socket2);
          return;
        }
        closeWebSocketSilently(socket2);
      }
    };
  }
  const cached = websocketSessionCache.get(sessionId);
  if (cached) {
    if (cached.idleTimer) {
      clearTimeout(cached.idleTimer);
      cached.idleTimer = void 0;
    }
    if (!cached.busy && isWebSocketReusable(cached.socket)) {
      cached.busy = true;
      return {
        socket: cached.socket,
        release: ({ keep } = {}) => {
          if (!keep || !isWebSocketReusable(cached.socket)) {
            closeWebSocketSilently(cached.socket);
            websocketSessionCache.delete(sessionId);
            return;
          }
          cached.busy = false;
          scheduleSessionWebSocketExpiry(sessionId, cached);
        }
      };
    }
    if (cached.busy) {
      const socket2 = await connectWebSocket(url, headers, signal);
      return {
        socket: socket2,
        release: () => {
          closeWebSocketSilently(socket2);
        }
      };
    }
    if (!isWebSocketReusable(cached.socket)) {
      closeWebSocketSilently(cached.socket);
      websocketSessionCache.delete(sessionId);
    }
  }
  const socket = await connectWebSocket(url, headers, signal);
  const entry = { socket, busy: true };
  websocketSessionCache.set(sessionId, entry);
  return {
    socket,
    release: ({ keep } = {}) => {
      if (!keep || !isWebSocketReusable(entry.socket)) {
        closeWebSocketSilently(entry.socket);
        if (entry.idleTimer)
          clearTimeout(entry.idleTimer);
        if (websocketSessionCache.get(sessionId) === entry) {
          websocketSessionCache.delete(sessionId);
        }
        return;
      }
      entry.busy = false;
      scheduleSessionWebSocketExpiry(sessionId, entry);
    }
  };
}
function extractWebSocketError(event) {
  if (event && typeof event === "object" && "message" in event) {
    const message = event.message;
    if (typeof message === "string" && message.length > 0) {
      return new Error(message);
    }
  }
  return new Error("WebSocket error");
}
function extractWebSocketCloseError(event) {
  if (event && typeof event === "object") {
    const code = "code" in event ? event.code : void 0;
    const reason = "reason" in event ? event.reason : void 0;
    const codeText = typeof code === "number" ? ` ${code}` : "";
    const reasonText = typeof reason === "string" && reason.length > 0 ? ` ${reason}` : "";
    return new Error(`WebSocket closed${codeText}${reasonText}`.trim());
  }
  return new Error("WebSocket closed");
}
async function decodeWebSocketData(data) {
  if (typeof data === "string")
    return data;
  if (data instanceof ArrayBuffer) {
    return new TextDecoder().decode(new Uint8Array(data));
  }
  if (ArrayBuffer.isView(data)) {
    const view = data;
    return new TextDecoder().decode(new Uint8Array(view.buffer, view.byteOffset, view.byteLength));
  }
  if (data && typeof data === "object" && "arrayBuffer" in data) {
    const blobLike = data;
    const arrayBuffer = await blobLike.arrayBuffer();
    return new TextDecoder().decode(new Uint8Array(arrayBuffer));
  }
  return null;
}
async function* parseWebSocket(socket, signal) {
  const queue = [];
  let pending = null;
  let done = false;
  let failed = null;
  let sawCompletion = false;
  const wake = () => {
    if (!pending)
      return;
    const resolve = pending;
    pending = null;
    resolve();
  };
  const onMessage = (event) => {
    void (async () => {
      if (!event || typeof event !== "object" || !("data" in event))
        return;
      const text3 = await decodeWebSocketData(event.data);
      if (!text3)
        return;
      try {
        const parsed = JSON.parse(text3);
        const type = typeof parsed.type === "string" ? parsed.type : "";
        if (type === "response.completed" || type === "response.done" || type === "response.incomplete") {
          sawCompletion = true;
          done = true;
        }
        queue.push(parsed);
        wake();
      } catch {
      }
    })();
  };
  const onError = (event) => {
    failed = extractWebSocketError(event);
    done = true;
    wake();
  };
  const onClose = (event) => {
    if (sawCompletion) {
      done = true;
      wake();
      return;
    }
    if (!failed) {
      failed = extractWebSocketCloseError(event);
    }
    done = true;
    wake();
  };
  const onAbort = () => {
    failed = new Error("Request was aborted");
    done = true;
    wake();
  };
  socket.addEventListener("message", onMessage);
  socket.addEventListener("error", onError);
  socket.addEventListener("close", onClose);
  signal?.addEventListener("abort", onAbort);
  try {
    while (true) {
      if (signal?.aborted) {
        throw new Error("Request was aborted");
      }
      if (queue.length > 0) {
        yield queue.shift();
        continue;
      }
      if (done)
        break;
      await new Promise((resolve) => {
        pending = resolve;
      });
    }
    if (failed) {
      throw failed;
    }
    if (!sawCompletion) {
      throw new Error("WebSocket stream closed before response.completed");
    }
  } finally {
    socket.removeEventListener("message", onMessage);
    socket.removeEventListener("error", onError);
    socket.removeEventListener("close", onClose);
    signal?.removeEventListener("abort", onAbort);
  }
}
async function processWebSocketStream(url, body, headers, output, stream2, model, onStart, options) {
  const { socket, release } = await acquireWebSocket(url, headers, options?.sessionId, options?.signal);
  let keepConnection = true;
  try {
    socket.send(JSON.stringify({ type: "response.create", ...body }));
    onStart();
    stream2.push({ type: "start", partial: output });
    await processResponsesStream(mapCodexEvents(parseWebSocket(socket, options?.signal)), output, stream2, model);
    if (options?.signal?.aborted) {
      keepConnection = false;
    }
  } catch (error) {
    keepConnection = false;
    throw error;
  } finally {
    release({ keep: keepConnection });
  }
}
async function parseErrorResponse(response) {
  const raw = await response.text();
  let message = raw || response.statusText || "Request failed";
  let friendlyMessage;
  try {
    const parsed = JSON.parse(raw);
    const err = parsed?.error;
    if (err) {
      const code = err.code || err.type || "";
      if (/usage_limit_reached|usage_not_included|rate_limit_exceeded/i.test(code) || response.status === 429) {
        const plan = err.plan_type ? ` (${err.plan_type.toLowerCase()} plan)` : "";
        const mins = err.resets_at ? Math.max(0, Math.round((err.resets_at * 1e3 - Date.now()) / 6e4)) : void 0;
        const when = mins !== void 0 ? ` Try again in ~${mins} min.` : "";
        friendlyMessage = `You have hit your ChatGPT usage limit${plan}.${when}`.trim();
      }
      message = err.message || friendlyMessage || message;
    }
  } catch {
  }
  return { message, friendlyMessage };
}
function extractAccountId(token) {
  try {
    const parts = token.split(".");
    if (parts.length !== 3)
      throw new Error("Invalid token");
    const payload = JSON.parse(atob(parts[1]));
    const accountId = payload?.[JWT_CLAIM_PATH]?.chatgpt_account_id;
    if (!accountId)
      throw new Error("No account ID in token");
    return accountId;
  } catch {
    throw new Error("Failed to extract accountId from token");
  }
}
function createCodexRequestId() {
  if (typeof globalThis.crypto?.randomUUID === "function") {
    return globalThis.crypto.randomUUID();
  }
  return `codex_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
}
function buildBaseCodexHeaders(initHeaders, additionalHeaders, accountId, token) {
  const headers = new Headers(initHeaders);
  for (const [key, value] of Object.entries(additionalHeaders || {})) {
    headers.set(key, value);
  }
  headers.set("Authorization", `Bearer ${token}`);
  headers.set("chatgpt-account-id", accountId);
  headers.set("originator", "pi");
  const userAgent = _os ? `pi (${_os.platform()} ${_os.release()}; ${_os.arch()})` : "pi (browser)";
  headers.set("User-Agent", userAgent);
  return headers;
}
function buildSSEHeaders(initHeaders, additionalHeaders, accountId, token, sessionId) {
  const headers = buildBaseCodexHeaders(initHeaders, additionalHeaders, accountId, token);
  headers.set("OpenAI-Beta", "responses=experimental");
  headers.set("accept", "text/event-stream");
  headers.set("content-type", "application/json");
  if (sessionId) {
    headers.set("session_id", sessionId);
  }
  return headers;
}
function buildWebSocketHeaders(initHeaders, additionalHeaders, accountId, token, requestId) {
  const headers = buildBaseCodexHeaders(initHeaders, additionalHeaders, accountId, token);
  headers.delete("accept");
  headers.delete("content-type");
  headers.delete("OpenAI-Beta");
  headers.delete("openai-beta");
  headers.set("OpenAI-Beta", OPENAI_BETA_RESPONSES_WEBSOCKETS);
  headers.set("x-client-request-id", requestId);
  headers.set("session_id", requestId);
  return headers;
}

// ../pi-mono/packages/ai/dist/providers/register-builtins.js
var dynamicImport3 = (specifier) => import(specifier);
var BEDROCK_PROVIDER_SPECIFIER = "./amazon-bedrock.js";
var bedrockProviderModuleOverride;
async function loadBedrockProviderModule() {
  if (bedrockProviderModuleOverride) {
    return bedrockProviderModuleOverride;
  }
  const module = await dynamicImport3(BEDROCK_PROVIDER_SPECIFIER);
  return module;
}
function forwardStream(target, source) {
  (async () => {
    for await (const event of source) {
      target.push(event);
    }
    target.end();
  })();
}
function createLazyLoadErrorMessage(model, error) {
  return {
    role: "assistant",
    content: [],
    api: "bedrock-converse-stream",
    provider: model.provider,
    model: model.id,
    usage: {
      input: 0,
      output: 0,
      cacheRead: 0,
      cacheWrite: 0,
      totalTokens: 0,
      cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
    },
    stopReason: "error",
    errorMessage: error instanceof Error ? error.message : String(error),
    timestamp: Date.now()
  };
}
function streamBedrockLazy(model, context, options) {
  const outer = new AssistantMessageEventStream();
  loadBedrockProviderModule().then((module) => {
    const inner2 = module.streamBedrock(model, context, options);
    forwardStream(outer, inner2);
  }).catch((error) => {
    const message = createLazyLoadErrorMessage(model, error);
    outer.push({ type: "error", reason: "error", error: message });
    outer.end(message);
  });
  return outer;
}
function streamSimpleBedrockLazy(model, context, options) {
  const outer = new AssistantMessageEventStream();
  loadBedrockProviderModule().then((module) => {
    const inner2 = module.streamSimpleBedrock(model, context, options);
    forwardStream(outer, inner2);
  }).catch((error) => {
    const message = createLazyLoadErrorMessage(model, error);
    outer.push({ type: "error", reason: "error", error: message });
    outer.end(message);
  });
  return outer;
}
function registerBuiltInApiProviders() {
  registerApiProvider({
    api: "anthropic-messages",
    stream: streamAnthropic,
    streamSimple: streamSimpleAnthropic
  });
  registerApiProvider({
    api: "openai-completions",
    stream: streamOpenAICompletions,
    streamSimple: streamSimpleOpenAICompletions
  });
  registerApiProvider({
    api: "mistral-conversations",
    stream: streamMistral,
    streamSimple: streamSimpleMistral
  });
  registerApiProvider({
    api: "openai-responses",
    stream: streamOpenAIResponses,
    streamSimple: streamSimpleOpenAIResponses
  });
  registerApiProvider({
    api: "azure-openai-responses",
    stream: streamAzureOpenAIResponses,
    streamSimple: streamSimpleAzureOpenAIResponses
  });
  registerApiProvider({
    api: "openai-codex-responses",
    stream: streamOpenAICodexResponses,
    streamSimple: streamSimpleOpenAICodexResponses
  });
  registerApiProvider({
    api: "google-generative-ai",
    stream: streamGoogle,
    streamSimple: streamSimpleGoogle
  });
  registerApiProvider({
    api: "google-gemini-cli",
    stream: streamGoogleGeminiCli,
    streamSimple: streamSimpleGoogleGeminiCli
  });
  registerApiProvider({
    api: "google-vertex",
    stream: streamGoogleVertex,
    streamSimple: streamSimpleGoogleVertex
  });
  registerApiProvider({
    api: "bedrock-converse-stream",
    stream: streamBedrockLazy,
    streamSimple: streamSimpleBedrockLazy
  });
}
registerBuiltInApiProviders();

// ../pi-mono/packages/ai/dist/stream.js
init_process_shim();
function resolveApiProvider(api) {
  const provider = getApiProvider(api);
  if (!provider) {
    throw new Error(`No API provider registered for api: ${api}`);
  }
  return provider;
}
function stream(model, context, options) {
  const provider = resolveApiProvider(model.api);
  return provider.stream(model, context, options);
}
async function complete(model, context, options) {
  const s6 = stream(model, context, options);
  return s6.result();
}
function streamSimple(model, context, options) {
  const provider = resolveApiProvider(model.api);
  return provider.streamSimple(model, context, options);
}

// ../pi-mono/packages/ai/dist/types.js
init_process_shim();

// ../pi-mono/packages/ai/dist/utils/overflow.js
init_process_shim();

// ../pi-mono/packages/ai/dist/utils/typebox-helpers.js
init_process_shim();
function StringEnum(values2, options) {
  return Type.Unsafe({
    type: "string",
    enum: values2,
    ...options?.description && { description: options.description },
    ...options?.default && { default: options.default }
  });
}

// ../pi-mono/packages/ai/dist/utils/validation.js
init_process_shim();
var import_ajv = __toESM(require_ajv(), 1);
var import_ajv_formats = __toESM(require_dist2(), 1);
var Ajv = import_ajv.default.default || import_ajv.default;
var addFormats = import_ajv_formats.default.default || import_ajv_formats.default;
var isBrowserExtension = typeof globalThis !== "undefined" && globalThis.chrome?.runtime?.id !== void 0;
var ajv = null;
if (!isBrowserExtension) {
  try {
    ajv = new Ajv({
      allErrors: true,
      strict: false,
      coerceTypes: true
    });
    addFormats(ajv);
  } catch (_e2) {
    console.warn("AJV validation disabled due to CSP restrictions");
  }
}

// ../pi-mono/packages/web-ui/dist/index.js
init_process_shim();

// ../pi-mono/packages/web-ui/dist/ChatPanel.js
init_process_shim();

// ../mini-lit/dist/Badge.js
init_process_shim();
var _Badge = fc(({ variant = "default", className = "", children }) => {
  const variantClasses = {
    default: "border-transparent bg-primary text-primary-foreground hover:bg-primary/80",
    secondary: "border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
    destructive: "border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
    outline: "border-input text-foreground"
  };
  const baseClasses = "inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden";
  return b2` <span class="${baseClasses} ${variantClasses[variant]} ${className}"> ${children} </span> `;
});
function Badge(propsOrChildren, variant = "default", className = "") {
  if (typeof propsOrChildren === "object" && propsOrChildren !== null && "children" in propsOrChildren) {
    return _Badge(propsOrChildren);
  }
  return _Badge({ children: propsOrChildren, variant, className });
}

// node_modules/lit/decorators.js
init_process_shim();

// node_modules/@lit/reactive-element/decorators/custom-element.js
init_process_shim();
var t5 = (t6) => (e9, o9) => {
  void 0 !== o9 ? o9.addInitializer(() => {
    customElements.define(t6, e9);
  }) : customElements.define(t6, e9);
};

// node_modules/@lit/reactive-element/decorators/property.js
init_process_shim();
var o8 = { attribute: true, type: String, converter: u, reflect: false, hasChanged: f };
var r6 = (t6 = o8, e9, r8) => {
  const { kind: n7, metadata: i7 } = r8;
  let s6 = globalThis.litPropertyMetadata.get(i7);
  if (void 0 === s6 && globalThis.litPropertyMetadata.set(i7, s6 = /* @__PURE__ */ new Map()), "setter" === n7 && ((t6 = Object.create(t6)).wrapped = true), s6.set(r8.name, t6), "accessor" === n7) {
    const { name: o9 } = r8;
    return { set(r9) {
      const n8 = e9.get.call(this);
      e9.set.call(this, r9), this.requestUpdate(o9, n8, t6, true, r9);
    }, init(e10) {
      return void 0 !== e10 && this.C(o9, void 0, t6, e10), e10;
    } };
  }
  if ("setter" === n7) {
    const { name: o9 } = r8;
    return function(r9) {
      const n8 = this[o9];
      e9.call(this, r9), this.requestUpdate(o9, n8, t6, true, r9);
    };
  }
  throw Error("Unsupported decorator location: " + n7);
};
function n6(t6) {
  return (e9, o9) => "object" == typeof o9 ? r6(t6, e9, o9) : ((t7, e10, o10) => {
    const r8 = e10.hasOwnProperty(o10);
    return e10.constructor.createProperty(o10, t7), r8 ? Object.getOwnPropertyDescriptor(e10, o10) : void 0;
  })(t6, e9, o9);
}

// node_modules/@lit/reactive-element/decorators/state.js
init_process_shim();
function r7(r8) {
  return n6({ ...r8, state: true, attribute: false });
}

// node_modules/@lit/reactive-element/decorators/event-options.js
init_process_shim();

// node_modules/@lit/reactive-element/decorators/query.js
init_process_shim();

// node_modules/@lit/reactive-element/decorators/base.js
init_process_shim();
var e7 = (e9, t6, c6) => (c6.configurable = true, c6.enumerable = true, Reflect.decorate && "object" != typeof t6 && Object.defineProperty(e9, t6, c6), c6);

// node_modules/@lit/reactive-element/decorators/query.js
function e8(e9, r8) {
  return (n7, s6, i7) => {
    const o9 = (t6) => t6.renderRoot?.querySelector(e9) ?? null;
    if (r8) {
      const { get: e10, set: r9 } = "object" == typeof s6 ? n7 : i7 ?? (() => {
        const t6 = Symbol();
        return { get() {
          return this[t6];
        }, set(e11) {
          this[t6] = e11;
        } };
      })();
      return e7(n7, s6, { get() {
        let t6 = e10.call(this);
        return void 0 === t6 && (t6 = o9(this), (null !== t6 || this.hasUpdated) && r9.call(this, t6)), t6;
      } });
    }
    return e7(n7, s6, { get() {
      return o9(this);
    } });
  };
}

// node_modules/@lit/reactive-element/decorators/query-all.js
init_process_shim();

// node_modules/@lit/reactive-element/decorators/query-async.js
init_process_shim();

// node_modules/@lit/reactive-element/decorators/query-assigned-elements.js
init_process_shim();

// node_modules/@lit/reactive-element/decorators/query-assigned-nodes.js
init_process_shim();

// ../pi-mono/packages/web-ui/dist/components/AgentInterface.js
init_process_shim();

// ../pi-mono/packages/web-ui/dist/dialogs/ModelSelector.js
init_process_shim();

// ../mini-lit/dist/index.js
init_process_shim();

// ../mini-lit/dist/component.js
init_process_shim();

// ../mini-lit/dist/i18n.js
init_process_shim();
var defaultEnglish = {
  "*": "*",
  Copy: "Copy",
  "Copy code": "Copy code",
  "Copied!": "Copied!",
  Download: "Download",
  Close: "Close",
  Preview: "Preview",
  Code: "Code",
  "Loading...": "Loading...",
  "Select an option": "Select an option",
  "Mode 1": "Mode 1",
  "Mode 2": "Mode 2",
  Required: "Required",
  Optional: "Optional",
  "Input Required": "Input Required",
  Cancel: "Cancel",
  Confirm: "Confirm"
};
var defaultGerman = {
  "*": "*",
  Copy: "Kopieren",
  "Copy code": "Code kopieren",
  "Copied!": "Kopiert!",
  Download: "Herunterladen",
  Close: "Schlie\xDFen",
  Preview: "Vorschau",
  Code: "Code",
  "Loading...": "Laden...",
  "Select an option": "Option ausw\xE4hlen",
  "Mode 1": "Modus 1",
  "Mode 2": "Modus 2",
  Required: "Erforderlich",
  Optional: "Optional",
  "Input Required": "Eingabe erforderlich",
  Cancel: "Abbrechen",
  Confirm: "Best\xE4tigen"
};
var userTranslations = null;
var translations = {
  en: defaultEnglish,
  de: defaultGerman
};
function setTranslations(customTranslations) {
  userTranslations = customTranslations;
  translations = customTranslations;
}
function getCurrentLanguage() {
  const stored = localStorage.getItem("language");
  if (stored && translations[stored]) {
    return stored;
  }
  const userLocale = navigator.language || navigator.userLanguage;
  const languageCode = userLocale ? userLocale.split("-")[0] : "en";
  return translations[languageCode] ? languageCode : "en";
}
function i18n(categoryOrKey, key) {
  const languageCode = getCurrentLanguage();
  const implementation = translations[languageCode] || translations.en;
  if (key === void 0) {
    const value = implementation[categoryOrKey];
    if (!value) {
      if (typeof value === "function") {
        return value;
      }
      console.error(`Unknown i18n key: ${categoryOrKey}`);
      return categoryOrKey;
    }
    return value;
  } else {
    const category = implementation[categoryOrKey];
    if (!category || typeof category !== "object") {
      console.error(`Unknown i18n category: ${categoryOrKey}`);
      return key;
    }
    const value = category[key];
    if (!value) {
      console.error(`Unknown i18n key: ${categoryOrKey}.${key}`);
      return key;
    }
    return value;
  }
}

// ../mini-lit/dist/Dialog.js
init_process_shim();
var Dialog = fc(({ isOpen, onClose, children, width = "min(600px, 90vw)", height = "auto", className = "", backdropClassName = "bg-black/50" }) => {
  if (!isOpen)
    return b2``;
  const handleBackdropClick = (e9) => {
    if (e9.target === e9.currentTarget) {
      onClose?.();
    }
  };
  const handleKeyDown = (e9) => {
    if (e9.key === "Escape") {
      onClose?.();
    }
  };
  if (isOpen) {
    document.addEventListener("keydown", handleKeyDown);
    setTimeout(() => {
      if (!isOpen) {
        document.removeEventListener("keydown", handleKeyDown);
      }
    }, 0);
  }
  return b2`
         <!-- Backdrop -->
         <div class="fixed inset-0 ${backdropClassName} z-40" @click=${handleBackdropClick}>
            <!-- Modal -->
            <div
               class="fixed z-50 bg-background rounded-lg shadow-xl flex flex-col border border-border ${className}"
               style="top: 50%; left: 50%; transform: translate(-50%, -50%); width: ${width}; height: ${height};"
               @click=${(e9) => e9.stopPropagation()}
            >
               ${children}

               <!-- Close button - absolutely positioned -->
               <button
                  type="button"
                  @click=${() => onClose?.()}
                  class="absolute top-4 right-4 rounded-sm text-muted-foreground opacity-70 transition-all hover:opacity-100 hover:text-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:ring-offset-background disabled:pointer-events-none cursor-pointer"
                  aria-label="${i18n("Close")}"
               >
                  <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                     <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                  </svg>
               </button>
            </div>
         </div>
      `;
});
var DialogHeader = fc(({ title, description, className = "" }) => {
  return b2`
      <div class="pr-8 ${className}">
         <h2 class="text-lg font-semibold text-foreground${description ? " mb-2" : ""}">${title}</h2>
         ${description ? b2`<p class="text-sm text-muted-foreground">${description}</p>` : ""}
      </div>
   `;
});
var DialogContent = fc(({ children, className = "" }) => {
  return b2` <div class="p-6 flex flex-col gap-4 ${className}">${children}</div> `;
});
var DialogFooter = fc(({ children, className = "" }) => {
  return b2` <div class="flex flex-col-reverse gap-2 sm:flex-row sm:justify-end ${className}">${children}</div> `;
});

// ../mini-lit/dist/DialogBase.js
init_process_shim();
var DialogBase = class extends i4 {
  constructor() {
    super(...arguments);
    this.modalWidth = "min(600px, 90vw)";
    this.modalHeight = "min(600px, 80vh)";
  }
  createRenderRoot() {
    return this;
  }
  open() {
    this.previousFocus = document.activeElement;
    document.body.appendChild(this);
    this.boundHandleKeyDown = (e9) => {
      if (e9.key === "Escape") {
        this.close();
      }
    };
    window.addEventListener("keydown", this.boundHandleKeyDown);
  }
  close() {
    if (this.boundHandleKeyDown) {
      window.removeEventListener("keydown", this.boundHandleKeyDown);
    }
    this.remove();
    if (this.previousFocus?.focus) {
      requestAnimationFrame(() => {
        this.previousFocus?.focus();
      });
    }
  }
  render() {
    return Dialog({
      isOpen: true,
      onClose: () => this.close(),
      width: this.modalWidth,
      height: this.modalHeight,
      backdropClassName: "bg-black/50 backdrop-blur-sm",
      children: this.renderContent()
    });
  }
};

// ../pi-mono/node_modules/lucide/dist/esm/lucide.js
init_process_shim();

// ../pi-mono/node_modules/lucide/dist/esm/icons/brain.js
init_process_shim();
var Brain = [
  ["path", { d: "M12 18V5" }],
  ["path", { d: "M15 13a4.17 4.17 0 0 1-3-4 4.17 4.17 0 0 1-3 4" }],
  ["path", { d: "M17.598 6.5A3 3 0 1 0 12 5a3 3 0 1 0-5.598 1.5" }],
  ["path", { d: "M17.997 5.125a4 4 0 0 1 2.526 5.77" }],
  ["path", { d: "M18 18a4 4 0 0 0 2-7.464" }],
  ["path", { d: "M19.967 17.483A4 4 0 1 1 12 18a4 4 0 1 1-7.967-.517" }],
  ["path", { d: "M6 18a4 4 0 0 1-2-7.464" }],
  ["path", { d: "M6.003 5.125a4 4 0 0 0-2.526 5.77" }]
];

// ../pi-mono/node_modules/lucide/dist/esm/icons/check.js
init_process_shim();
var Check2 = [["path", { d: "M20 6 9 17l-5-5" }]];

// ../pi-mono/node_modules/lucide/dist/esm/icons/chevron-down.js
init_process_shim();
var ChevronDown = [["path", { d: "m6 9 6 6 6-6" }]];

// ../pi-mono/node_modules/lucide/dist/esm/icons/chevron-right.js
init_process_shim();
var ChevronRight = [["path", { d: "m9 18 6-6-6-6" }]];

// ../pi-mono/node_modules/lucide/dist/esm/icons/chevron-up.js
init_process_shim();
var ChevronUp = [["path", { d: "m18 15-6-6-6 6" }]];

// ../pi-mono/node_modules/lucide/dist/esm/icons/chevrons-down.js
init_process_shim();
var ChevronsDown = [
  ["path", { d: "m7 6 5 5 5-5" }],
  ["path", { d: "m7 13 5 5 5-5" }]
];

// ../pi-mono/node_modules/lucide/dist/esm/icons/chevrons-up-down.js
init_process_shim();
var ChevronsUpDown = [
  ["path", { d: "m7 15 5 5 5-5" }],
  ["path", { d: "m7 9 5-5 5 5" }]
];

// ../pi-mono/node_modules/lucide/dist/esm/icons/code.js
init_process_shim();
var Code2 = [
  ["path", { d: "m16 18 6-6-6-6" }],
  ["path", { d: "m8 6-6 6 6 6" }]
];

// ../pi-mono/node_modules/lucide/dist/esm/icons/copy.js
init_process_shim();
var Copy2 = [
  ["rect", { width: "14", height: "14", x: "8", y: "8", rx: "2", ry: "2" }],
  ["path", { d: "M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2" }]
];

// ../pi-mono/node_modules/lucide/dist/esm/icons/download.js
init_process_shim();
var Download2 = [
  ["path", { d: "M12 15V3" }],
  ["path", { d: "M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" }],
  ["path", { d: "m7 10 5 5 5-5" }]
];

// ../pi-mono/node_modules/lucide/dist/esm/icons/file-code-2.js
init_process_shim();
var FileCode2 = [
  ["path", { d: "M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4" }],
  ["path", { d: "M14 2v4a2 2 0 0 0 2 2h4" }],
  ["path", { d: "m5 12-3 3 3 3" }],
  ["path", { d: "m9 18 3-3-3-3" }]
];

// ../pi-mono/node_modules/lucide/dist/esm/icons/file-spreadsheet.js
init_process_shim();
var FileSpreadsheet = [
  ["path", { d: "M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z" }],
  ["path", { d: "M14 2v4a2 2 0 0 0 2 2h4" }],
  ["path", { d: "M8 13h2" }],
  ["path", { d: "M14 13h2" }],
  ["path", { d: "M8 17h2" }],
  ["path", { d: "M14 17h2" }]
];

// ../pi-mono/node_modules/lucide/dist/esm/icons/file-text.js
init_process_shim();
var FileText = [
  ["path", { d: "M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z" }],
  ["path", { d: "M14 2v4a2 2 0 0 0 2 2h4" }],
  ["path", { d: "M10 9H8" }],
  ["path", { d: "M16 13H8" }],
  ["path", { d: "M16 17H8" }]
];

// ../pi-mono/node_modules/lucide/dist/esm/icons/image.js
init_process_shim();
var Image2 = [
  ["rect", { width: "18", height: "18", x: "3", y: "3", rx: "2", ry: "2" }],
  ["circle", { cx: "9", cy: "9", r: "2" }],
  ["path", { d: "m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21" }]
];

// ../pi-mono/node_modules/lucide/dist/esm/icons/loader-circle.js
init_process_shim();
var LoaderCircle = [["path", { d: "M21 12a9 9 0 1 1-6.219-8.56" }]];

// ../pi-mono/node_modules/lucide/dist/esm/icons/loader.js
init_process_shim();
var Loader = [
  ["path", { d: "M12 2v4" }],
  ["path", { d: "m16.2 7.8 2.9-2.9" }],
  ["path", { d: "M18 12h4" }],
  ["path", { d: "m16.2 16.2 2.9 2.9" }],
  ["path", { d: "M12 18v4" }],
  ["path", { d: "m4.9 19.1 2.9-2.9" }],
  ["path", { d: "M2 12h4" }],
  ["path", { d: "m4.9 4.9 2.9 2.9" }]
];

// ../pi-mono/node_modules/lucide/dist/esm/icons/lock.js
init_process_shim();
var Lock = [
  ["rect", { width: "18", height: "11", x: "3", y: "11", rx: "2", ry: "2" }],
  ["path", { d: "M7 11V7a5 5 0 0 1 10 0v4" }]
];

// ../pi-mono/node_modules/lucide/dist/esm/icons/paperclip.js
init_process_shim();
var Paperclip = [
  [
    "path",
    {
      d: "m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551"
    }
  ]
];

// ../pi-mono/node_modules/lucide/dist/esm/icons/refresh-cw.js
init_process_shim();
var RefreshCw = [
  ["path", { d: "M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8" }],
  ["path", { d: "M21 3v5h-5" }],
  ["path", { d: "M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16" }],
  ["path", { d: "M8 16H3v5" }]
];

// ../pi-mono/node_modules/lucide/dist/esm/icons/send.js
init_process_shim();
var Send = [
  [
    "path",
    {
      d: "M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z"
    }
  ],
  ["path", { d: "m21.854 2.147-10.94 10.939" }]
];

// ../pi-mono/node_modules/lucide/dist/esm/icons/sparkles.js
init_process_shim();
var Sparkles = [
  [
    "path",
    {
      d: "M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z"
    }
  ],
  ["path", { d: "M20 2v4" }],
  ["path", { d: "M22 4h-4" }],
  ["circle", { cx: "4", cy: "20", r: "2" }]
];

// ../pi-mono/node_modules/lucide/dist/esm/icons/square-terminal.js
init_process_shim();
var SquareTerminal = [
  ["path", { d: "m7 11 2-2-2-2" }],
  ["path", { d: "M11 13h4" }],
  ["rect", { width: "18", height: "18", x: "3", y: "3", rx: "2", ry: "2" }]
];

// ../pi-mono/node_modules/lucide/dist/esm/icons/square.js
init_process_shim();
var Square = [["rect", { width: "18", height: "18", x: "3", y: "3", rx: "2" }]];

// ../pi-mono/node_modules/lucide/dist/esm/icons/x.js
init_process_shim();
var X = [
  ["path", { d: "M18 6 6 18" }],
  ["path", { d: "m6 6 12 12" }]
];

// ../pi-mono/packages/web-ui/dist/components/Input.js
init_process_shim();

// ../pi-mono/packages/web-ui/dist/utils/i18n.js
init_process_shim();
var translations2 = {
  en: {
    ...defaultEnglish,
    Free: "Free",
    "Input Required": "Input Required",
    Cancel: "Cancel",
    Confirm: "Confirm",
    "Select Model": "Select Model",
    "Search models...": "Search models...",
    Format: "Format",
    Thinking: "Thinking",
    Vision: "Vision",
    You: "You",
    Assistant: "Assistant",
    "Thinking...": "Thinking...",
    "Type your message...": "Type your message...",
    "API Keys Configuration": "API Keys Configuration",
    "Configure API keys for LLM providers. Keys are stored locally in your browser.": "Configure API keys for LLM providers. Keys are stored locally in your browser.",
    Configured: "Configured",
    "Not configured": "Not configured",
    "\u2713 Valid": "\u2713 Valid",
    "\u2717 Invalid": "\u2717 Invalid",
    "Testing...": "Testing...",
    Update: "Update",
    Test: "Test",
    Remove: "Remove",
    Save: "Save",
    "Update API key": "Update API key",
    "Enter API key": "Enter API key",
    "Type a message...": "Type a message...",
    "Failed to fetch file": "Failed to fetch file",
    "Invalid source type": "Invalid source type",
    PDF: "PDF",
    Document: "Document",
    Presentation: "Presentation",
    Spreadsheet: "Spreadsheet",
    Text: "Text",
    "Error loading file": "Error loading file",
    "No text content available": "No text content available",
    "Failed to load PDF": "Failed to load PDF",
    "Failed to load document": "Failed to load document",
    "Failed to load spreadsheet": "Failed to load spreadsheet",
    "Error loading PDF": "Error loading PDF",
    "Error loading document": "Error loading document",
    "Error loading spreadsheet": "Error loading spreadsheet",
    "Preview not available for this file type.": "Preview not available for this file type.",
    "Click the download button above to view it on your computer.": "Click the download button above to view it on your computer.",
    "No content available": "No content available",
    "Failed to display text content": "Failed to display text content",
    "API keys are required to use AI models. Get your keys from the provider's website.": "API keys are required to use AI models. Get your keys from the provider's website.",
    console: "console",
    "Copy output": "Copy output",
    "Copied!": "Copied!",
    "Error:": "Error:",
    "Request aborted": "Request aborted",
    Call: "Call",
    Result: "Result",
    "(no result)": "(no result)",
    "Waiting for tool result\u2026": "Waiting for tool result\u2026",
    "Call was aborted; no result.": "Call was aborted; no result.",
    "No session available": "No session available",
    "No session set": "No session set",
    "Preparing tool parameters...": "Preparing tool parameters...",
    "(no output)": "(no output)",
    Input: "Input",
    Output: "Output",
    "Waiting for expression...": "Waiting for expression...",
    "Writing expression...": "Writing expression...",
    Calculating: "Calculating",
    "Getting current time in": "Getting current time in",
    "Getting current date and time": "Getting current date and time",
    "Waiting for command...": "Waiting for command...",
    "Writing command...": "Writing command...",
    "Running command...": "Running command...",
    "Command failed": "Command failed",
    "Enter Auth Token": "Enter Auth Token",
    "Please enter your auth token.": "Please enter your auth token.",
    "Auth token is required for proxy transport": "Auth token is required for proxy transport",
    // JavaScript REPL strings
    "Execution aborted": "Execution aborted",
    "Code parameter is required": "Code parameter is required",
    "Unknown error": "Unknown error",
    "Code executed successfully (no output)": "Code executed successfully (no output)",
    "Execution failed": "Execution failed",
    "JavaScript REPL": "JavaScript REPL",
    "JavaScript code to execute": "JavaScript code to execute",
    "Writing JavaScript code...": "Writing JavaScript code...",
    "Executing JavaScript": "Executing JavaScript",
    "Preparing JavaScript...": "Preparing JavaScript...",
    "Preparing command...": "Preparing command...",
    "Preparing calculation...": "Preparing calculation...",
    "Preparing tool...": "Preparing tool...",
    "Getting time...": "Getting time...",
    // Artifacts strings
    "Processing artifact...": "Processing artifact...",
    "Preparing artifact...": "Preparing artifact...",
    "Processing artifact": "Processing artifact",
    "Processed artifact": "Processed artifact",
    "Creating artifact": "Creating artifact",
    "Created artifact": "Created artifact",
    "Updating artifact": "Updating artifact",
    "Updated artifact": "Updated artifact",
    "Rewriting artifact": "Rewriting artifact",
    "Rewrote artifact": "Rewrote artifact",
    "Getting artifact": "Getting artifact",
    "Got artifact": "Got artifact",
    "Deleting artifact": "Deleting artifact",
    "Deleted artifact": "Deleted artifact",
    "Getting logs": "Getting logs",
    "Got logs": "Got logs",
    "An error occurred": "An error occurred",
    "Copy logs": "Copy logs",
    "Autoscroll enabled": "Autoscroll enabled",
    "Autoscroll disabled": "Autoscroll disabled",
    Processing: "Processing",
    Create: "Create",
    Rewrite: "Rewrite",
    Get: "Get",
    "Get logs": "Get logs",
    "Show artifacts": "Show artifacts",
    "Close artifacts": "Close artifacts",
    Artifacts: "Artifacts",
    "Copy HTML": "Copy HTML",
    "Download HTML": "Download HTML",
    "Reload HTML": "Reload HTML",
    "Copy SVG": "Copy SVG",
    "Download SVG": "Download SVG",
    "Copy Markdown": "Copy Markdown",
    "Download Markdown": "Download Markdown",
    Download: "Download",
    "No logs for {filename}": "No logs for {filename}",
    "API Keys Settings": "API Keys Settings",
    Settings: "Settings",
    "API Keys": "API Keys",
    Proxy: "Proxy",
    "Use CORS Proxy": "Use CORS Proxy",
    "Proxy URL": "Proxy URL",
    "Format: The proxy must accept requests as <proxy-url>/?url=<target-url>": "Format: The proxy must accept requests as <proxy-url>/?url=<target-url>",
    "Settings are stored locally in your browser": "Settings are stored locally in your browser",
    Clear: "Clear",
    "API Key Required": "API Key Required",
    "Enter your API key for {provider}": "Enter your API key for {provider}",
    "Allows browser-based apps to bypass CORS restrictions when calling LLM providers. Required for Z-AI and Anthropic with OAuth token.": "Allows browser-based apps to bypass CORS restrictions when calling LLM providers. Required for Z-AI and Anthropic with OAuth token.",
    Off: "Off",
    Minimal: "Minimal",
    Low: "Low",
    Medium: "Medium",
    High: "High",
    "Storage Permission Required": "Storage Permission Required",
    "This app needs persistent storage to save your conversations": "This app needs persistent storage to save your conversations",
    "Why is this needed?": "Why is this needed?",
    "Without persistent storage, your browser may delete saved conversations when it needs disk space. Granting this permission ensures your chat history is preserved.": "Without persistent storage, your browser may delete saved conversations when it needs disk space. Granting this permission ensures your chat history is preserved.",
    "What this means:": "What this means:",
    "Your conversations will be saved locally in your browser": "Your conversations will be saved locally in your browser",
    "Data will not be deleted automatically to free up space": "Data will not be deleted automatically to free up space",
    "You can still manually clear data at any time": "You can still manually clear data at any time",
    "No data is sent to external servers": "No data is sent to external servers",
    "Continue Anyway": "Continue Anyway",
    "Requesting...": "Requesting...",
    "Grant Permission": "Grant Permission",
    Sessions: "Sessions",
    "Load a previous conversation": "Load a previous conversation",
    "No sessions yet": "No sessions yet",
    "Delete this session?": "Delete this session?",
    Today: "Today",
    Yesterday: "Yesterday",
    "{days} days ago": "{days} days ago",
    messages: "messages",
    tokens: "tokens",
    Delete: "Delete",
    "Drop files here": "Drop files here",
    "Command failed:": "Command failed:",
    // Providers & Models
    "Providers & Models": "Providers & Models",
    "Cloud Providers": "Cloud Providers",
    "Cloud LLM providers with predefined models. API keys are stored locally in your browser.": "Cloud LLM providers with predefined models. API keys are stored locally in your browser.",
    "Custom Providers": "Custom Providers",
    "User-configured servers with auto-discovered or manually defined models.": "User-configured servers with auto-discovered or manually defined models.",
    "Add Provider": "Add Provider",
    "No custom providers configured. Click 'Add Provider' to get started.": "No custom providers configured. Click 'Add Provider' to get started.",
    "auto-discovered": "auto-discovered",
    Refresh: "Refresh",
    Edit: "Edit",
    "Are you sure you want to delete this provider?": "Are you sure you want to delete this provider?",
    "Edit Provider": "Edit Provider",
    "Provider Name": "Provider Name",
    "e.g., My Ollama Server": "e.g., My Ollama Server",
    "Provider Type": "Provider Type",
    "Base URL": "Base URL",
    "e.g., http://localhost:11434": "e.g., http://localhost:11434",
    "API Key (Optional)": "API Key (Optional)",
    "Leave empty if not required": "Leave empty if not required",
    "Test Connection": "Test Connection",
    Discovered: "Discovered",
    Models: "Models",
    models: "models",
    and: "and",
    more: "more",
    "For manual provider types, add models after saving the provider.": "For manual provider types, add models after saving the provider.",
    "Please fill in all required fields": "Please fill in all required fields",
    "Failed to save provider": "Failed to save provider",
    "OpenAI Completions Compatible": "OpenAI Completions Compatible",
    "OpenAI Responses Compatible": "OpenAI Responses Compatible",
    "Anthropic Messages Compatible": "Anthropic Messages Compatible",
    "Checking...": "Checking...",
    Disconnected: "Disconnected"
  },
  de: {
    ...defaultGerman,
    Free: "Kostenlos",
    "Input Required": "Eingabe erforderlich",
    Cancel: "Abbrechen",
    Confirm: "Best\xE4tigen",
    "Select Model": "Modell ausw\xE4hlen",
    "Search models...": "Modelle suchen...",
    Format: "Formatieren",
    Thinking: "Thinking",
    Vision: "Vision",
    You: "Sie",
    Assistant: "Assistent",
    "Thinking...": "Denkt nach...",
    "Type your message...": "Geben Sie Ihre Nachricht ein...",
    "API Keys Configuration": "API-Schl\xFCssel-Konfiguration",
    "Configure API keys for LLM providers. Keys are stored locally in your browser.": "Konfigurieren Sie API-Schl\xFCssel f\xFCr LLM-Anbieter. Schl\xFCssel werden lokal in Ihrem Browser gespeichert.",
    Configured: "Konfiguriert",
    "Not configured": "Nicht konfiguriert",
    "\u2713 Valid": "\u2713 G\xFCltig",
    "\u2717 Invalid": "\u2717 Ung\xFCltig",
    "Testing...": "Teste...",
    Update: "Aktualisieren",
    Test: "Testen",
    Remove: "Entfernen",
    Save: "Speichern",
    "Update API key": "API-Schl\xFCssel aktualisieren",
    "Enter API key": "API-Schl\xFCssel eingeben",
    "Type a message...": "Nachricht eingeben...",
    "Failed to fetch file": "Datei konnte nicht abgerufen werden",
    "Invalid source type": "Ung\xFCltiger Quellentyp",
    PDF: "PDF",
    Document: "Dokument",
    Presentation: "Pr\xE4sentation",
    Spreadsheet: "Tabelle",
    Text: "Text",
    "Error loading file": "Fehler beim Laden der Datei",
    "No text content available": "Kein Textinhalt verf\xFCgbar",
    "Failed to load PDF": "PDF konnte nicht geladen werden",
    "Failed to load document": "Dokument konnte nicht geladen werden",
    "Failed to load spreadsheet": "Tabelle konnte nicht geladen werden",
    "Error loading PDF": "Fehler beim Laden des PDFs",
    "Error loading document": "Fehler beim Laden des Dokuments",
    "Error loading spreadsheet": "Fehler beim Laden der Tabelle",
    "Preview not available for this file type.": "Vorschau f\xFCr diesen Dateityp nicht verf\xFCgbar.",
    "Click the download button above to view it on your computer.": "Klicken Sie oben auf die Download-Schaltfl\xE4che, um die Datei auf Ihrem Computer anzuzeigen.",
    "No content available": "Kein Inhalt verf\xFCgbar",
    "Failed to display text content": "Textinhalt konnte nicht angezeigt werden",
    "API keys are required to use AI models. Get your keys from the provider's website.": "API-Schl\xFCssel sind erforderlich, um KI-Modelle zu verwenden. Holen Sie sich Ihre Schl\xFCssel von der Website des Anbieters.",
    console: "Konsole",
    "Copy output": "Ausgabe kopieren",
    "Copied!": "Kopiert!",
    "Error:": "Fehler:",
    "Request aborted": "Anfrage abgebrochen",
    Call: "Aufruf",
    Result: "Ergebnis",
    "(no result)": "(kein Ergebnis)",
    "Waiting for tool result\u2026": "Warte auf Tool-Ergebnis\u2026",
    "Call was aborted; no result.": "Aufruf wurde abgebrochen; kein Ergebnis.",
    "No session available": "Keine Sitzung verf\xFCgbar",
    "No session set": "Keine Sitzung gesetzt",
    "Preparing tool parameters...": "Bereite Tool-Parameter vor...",
    "(no output)": "(keine Ausgabe)",
    Input: "Eingabe",
    Output: "Ausgabe",
    "Waiting for expression...": "Warte auf Ausdruck",
    "Writing expression...": "Schreibe Ausdruck...",
    Calculating: "Berechne",
    "Getting current time in": "Hole aktuelle Zeit in",
    "Getting current date and time": "Hole aktuelles Datum und Uhrzeit",
    "Waiting for command...": "Warte auf Befehl...",
    "Writing command...": "Schreibe Befehl...",
    "Running command...": "F\xFChre Befehl aus...",
    "Command failed": "Befehl fehlgeschlagen",
    "Enter Auth Token": "Auth-Token eingeben",
    "Please enter your auth token.": "Bitte geben Sie Ihr Auth-Token ein.",
    "Auth token is required for proxy transport": "Auth-Token ist f\xFCr Proxy-Transport erforderlich",
    // JavaScript REPL strings
    "Execution aborted": "Ausf\xFChrung abgebrochen",
    "Code parameter is required": "Code-Parameter ist erforderlich",
    "Unknown error": "Unbekannter Fehler",
    "Code executed successfully (no output)": "Code erfolgreich ausgef\xFChrt (keine Ausgabe)",
    "Execution failed": "Ausf\xFChrung fehlgeschlagen",
    "JavaScript REPL": "JavaScript REPL",
    "JavaScript code to execute": "Auszuf\xFChrender JavaScript-Code",
    "Writing JavaScript code...": "Schreibe JavaScript-Code...",
    "Executing JavaScript": "F\xFChre JavaScript aus",
    "Preparing JavaScript...": "Bereite JavaScript vor...",
    "Preparing command...": "Bereite Befehl vor...",
    "Preparing calculation...": "Bereite Berechnung vor...",
    "Preparing tool...": "Bereite Tool vor...",
    "Getting time...": "Hole Zeit...",
    // Artifacts strings
    "Processing artifact...": "Verarbeite Artefakt...",
    "Preparing artifact...": "Bereite Artefakt vor...",
    "Processing artifact": "Verarbeite Artefakt",
    "Processed artifact": "Artefakt verarbeitet",
    "Creating artifact": "Erstelle Artefakt",
    "Created artifact": "Artefakt erstellt",
    "Updating artifact": "Aktualisiere Artefakt",
    "Updated artifact": "Artefakt aktualisiert",
    "Rewriting artifact": "\xDCberschreibe Artefakt",
    "Rewrote artifact": "Artefakt \xFCberschrieben",
    "Getting artifact": "Hole Artefakt",
    "Got artifact": "Artefakt geholt",
    "Deleting artifact": "L\xF6sche Artefakt",
    "Deleted artifact": "Artefakt gel\xF6scht",
    "Getting logs": "Hole Logs",
    "Got logs": "Logs geholt",
    "An error occurred": "Ein Fehler ist aufgetreten",
    "Copy logs": "Logs kopieren",
    "Autoscroll enabled": "Automatisches Scrollen aktiviert",
    "Autoscroll disabled": "Automatisches Scrollen deaktiviert",
    Processing: "Verarbeitung",
    Create: "Erstellen",
    Rewrite: "\xDCberschreiben",
    Get: "Abrufen",
    "Get logs": "Logs abrufen",
    "Show artifacts": "Artefakte anzeigen",
    "Close artifacts": "Artefakte schlie\xDFen",
    Artifacts: "Artefakte",
    "Copy HTML": "HTML kopieren",
    "Download HTML": "HTML herunterladen",
    "Reload HTML": "HTML neu laden",
    "Copy SVG": "SVG kopieren",
    "Download SVG": "SVG herunterladen",
    "Copy Markdown": "Markdown kopieren",
    "Download Markdown": "Markdown herunterladen",
    Download: "Herunterladen",
    "No logs for {filename}": "Keine Logs f\xFCr {filename}",
    "API Keys Settings": "API-Schl\xFCssel Einstellungen",
    Settings: "Einstellungen",
    "API Keys": "API-Schl\xFCssel",
    Proxy: "Proxy",
    "Use CORS Proxy": "CORS-Proxy verwenden",
    "Proxy URL": "Proxy-URL",
    "Format: The proxy must accept requests as <proxy-url>/?url=<target-url>": "Format: Der Proxy muss Anfragen als <proxy-url>/?url=<ziel-url> akzeptieren",
    "Settings are stored locally in your browser": "Einstellungen werden lokal in Ihrem Browser gespeichert",
    Clear: "L\xF6schen",
    "API Key Required": "API-Schl\xFCssel erforderlich",
    "Enter your API key for {provider}": "Geben Sie Ihren API-Schl\xFCssel f\xFCr {provider} ein",
    "Allows browser-based apps to bypass CORS restrictions when calling LLM providers. Required for Z-AI and Anthropic with OAuth token.": "Erm\xF6glicht browserbasierten Anwendungen, CORS-Einschr\xE4nkungen beim Aufruf von LLM-Anbietern zu umgehen. Erforderlich f\xFCr Z-AI und Anthropic mit OAuth-Token.",
    Off: "Aus",
    Minimal: "Minimal",
    Low: "Niedrig",
    Medium: "Mittel",
    High: "Hoch",
    "Storage Permission Required": "Speicherberechtigung erforderlich",
    "This app needs persistent storage to save your conversations": "Diese App ben\xF6tigt dauerhaften Speicher, um Ihre Konversationen zu speichern",
    "Why is this needed?": "Warum wird das ben\xF6tigt?",
    "Without persistent storage, your browser may delete saved conversations when it needs disk space. Granting this permission ensures your chat history is preserved.": "Ohne dauerhaften Speicher kann Ihr Browser gespeicherte Konversationen l\xF6schen, wenn Speicherplatz ben\xF6tigt wird. Diese Berechtigung stellt sicher, dass Ihr Chatverlauf erhalten bleibt.",
    "What this means:": "Was das bedeutet:",
    "Your conversations will be saved locally in your browser": "Ihre Konversationen werden lokal in Ihrem Browser gespeichert",
    "Data will not be deleted automatically to free up space": "Daten werden nicht automatisch gel\xF6scht, um Speicherplatz freizugeben",
    "You can still manually clear data at any time": "Sie k\xF6nnen Daten jederzeit manuell l\xF6schen",
    "No data is sent to external servers": "Keine Daten werden an externe Server gesendet",
    "Continue Anyway": "Trotzdem fortfahren",
    "Requesting...": "Anfrage l\xE4uft...",
    "Grant Permission": "Berechtigung erteilen",
    Sessions: "Sitzungen",
    "Load a previous conversation": "Fr\xFChere Konversation laden",
    "No sessions yet": "Noch keine Sitzungen",
    "Delete this session?": "Diese Sitzung l\xF6schen?",
    Today: "Heute",
    Yesterday: "Gestern",
    "{days} days ago": "vor {days} Tagen",
    messages: "Nachrichten",
    tokens: "Tokens",
    Delete: "L\xF6schen",
    "Drop files here": "Dateien hier ablegen",
    "Command failed:": "Befehl fehlgeschlagen:",
    // Providers & Models
    "Providers & Models": "Anbieter & Modelle",
    "Cloud Providers": "Cloud-Anbieter",
    "Cloud LLM providers with predefined models. API keys are stored locally in your browser.": "Cloud-LLM-Anbieter mit vordefinierten Modellen. API-Schl\xFCssel werden lokal in Ihrem Browser gespeichert.",
    "Custom Providers": "Benutzerdefinierte Anbieter",
    "User-configured servers with auto-discovered or manually defined models.": "Benutzerkonfigurierte Server mit automatisch erkannten oder manuell definierten Modellen.",
    "Add Provider": "Anbieter hinzuf\xFCgen",
    "No custom providers configured. Click 'Add Provider' to get started.": "Keine benutzerdefinierten Anbieter konfiguriert. Klicken Sie auf 'Anbieter hinzuf\xFCgen', um zu beginnen.",
    "auto-discovered": "automatisch erkannt",
    Refresh: "Aktualisieren",
    Edit: "Bearbeiten",
    "Are you sure you want to delete this provider?": "Sind Sie sicher, dass Sie diesen Anbieter l\xF6schen m\xF6chten?",
    "Edit Provider": "Anbieter bearbeiten",
    "Provider Name": "Anbietername",
    "e.g., My Ollama Server": "z.B. Mein Ollama Server",
    "Provider Type": "Anbietertyp",
    "Base URL": "Basis-URL",
    "e.g., http://localhost:11434": "z.B. http://localhost:11434",
    "API Key (Optional)": "API-Schl\xFCssel (Optional)",
    "Leave empty if not required": "Leer lassen, falls nicht erforderlich",
    "Test Connection": "Verbindung testen",
    Discovered: "Erkannt",
    Models: "Modelle",
    models: "Modelle",
    and: "und",
    more: "mehr",
    "For manual provider types, add models after saving the provider.": "F\xFCr manuelle Anbietertypen f\xFCgen Sie Modelle nach dem Speichern des Anbieters hinzu.",
    "Please fill in all required fields": "Bitte f\xFCllen Sie alle erforderlichen Felder aus",
    "Failed to save provider": "Fehler beim Speichern des Anbieters",
    "OpenAI Completions Compatible": "OpenAI Completions Kompatibel",
    "OpenAI Responses Compatible": "OpenAI Responses Kompatibel",
    "Anthropic Messages Compatible": "Anthropic Messages Kompatibel",
    "Checking...": "\xDCberpr\xFCfe...",
    Disconnected: "Getrennt"
  }
};
setTranslations(translations2);

// ../pi-mono/packages/web-ui/dist/components/Input.js
var Input = fc(({ type = "text", size = "md", value = "", placeholder = "", label = "", error = "", disabled = false, required = false, name = "", autocomplete = "", min, max, step, inputRef, onInput, onChange, onKeyDown, onKeyUp, className = "" }) => {
  const sizeClasses2 = {
    sm: "h-8 px-3 py-1 text-sm",
    md: "h-9 px-3 py-1 text-sm md:text-sm",
    lg: "h-10 px-4 py-1 text-base"
  };
  const baseClasses = "flex w-full min-w-0 rounded-md border bg-transparent text-foreground shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium";
  const interactionClasses = "placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground";
  const focusClasses = "focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]";
  const darkClasses = "dark:bg-input/30";
  const stateClasses = error ? "border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40" : "border-input";
  const disabledClasses = "disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50";
  const handleInput = (e9) => {
    onInput?.(e9);
  };
  const handleChange = (e9) => {
    onChange?.(e9);
  };
  return b2`
			<div class="flex flex-col gap-1.5 ${className}">
				${label ? b2`
							<label class="text-sm font-medium text-foreground">
								${label} ${required ? b2`<span class="text-destructive">${i18n("*")}</span>` : ""}
							</label>
						` : ""}
				<input
					type="${type}"
					class="${baseClasses} ${sizeClasses2[size]} ${interactionClasses} ${focusClasses} ${darkClasses} ${stateClasses} ${disabledClasses}"
					.value=${value}
					placeholder="${placeholder}"
					?disabled=${disabled}
					?required=${required}
					?aria-invalid=${!!error}
					name="${name}"
					autocomplete="${autocomplete}"
					min="${min ?? ""}"
					max="${max ?? ""}"
					step="${step ?? ""}"
					@input=${handleInput}
					@change=${handleChange}
					@keydown=${onKeyDown}
					@keyup=${onKeyUp}
					${inputRef ? n5(inputRef) : ""}
				/>
				${error ? b2`<span class="text-sm text-destructive">${error}</span>` : ""}
			</div>
		`;
});

// ../pi-mono/packages/web-ui/dist/storage/app-storage.js
init_process_shim();
var AppStorage = class {
  constructor(settings, providerKeys, sessions, customProviders, backend) {
    this.settings = settings;
    this.providerKeys = providerKeys;
    this.sessions = sessions;
    this.customProviders = customProviders;
    this.backend = backend;
  }
  async getQuotaInfo() {
    return this.backend.getQuotaInfo();
  }
  async requestPersistence() {
    return this.backend.requestPersistence();
  }
};
var globalAppStorage = null;
function getAppStorage() {
  if (!globalAppStorage) {
    throw new Error("AppStorage not initialized. Call setAppStorage() first.");
  }
  return globalAppStorage;
}
function setAppStorage(storage2) {
  globalAppStorage = storage2;
}

// ../pi-mono/packages/web-ui/dist/utils/format.js
init_process_shim();
function formatCost(cost) {
  return `$${cost.toFixed(4)}`;
}
function formatModelCost(cost) {
  if (!cost)
    return i18n("Free");
  const input = cost.input || 0;
  const output = cost.output || 0;
  if (input === 0 && output === 0)
    return i18n("Free");
  const formatNum = (num) => {
    if (num >= 100)
      return num.toFixed(0);
    if (num >= 10)
      return num.toFixed(1).replace(/\.0$/, "");
    if (num >= 1)
      return num.toFixed(2).replace(/\.?0+$/, "");
    return num.toFixed(3).replace(/\.?0+$/, "");
  };
  return `$${formatNum(input)}/$${formatNum(output)}`;
}
function formatUsage(usage) {
  if (!usage)
    return "";
  const parts = [];
  if (usage.input)
    parts.push(`\u2191${formatTokenCount(usage.input)}`);
  if (usage.output)
    parts.push(`\u2193${formatTokenCount(usage.output)}`);
  if (usage.cacheRead)
    parts.push(`R${formatTokenCount(usage.cacheRead)}`);
  if (usage.cacheWrite)
    parts.push(`W${formatTokenCount(usage.cacheWrite)}`);
  if (usage.cost?.total)
    parts.push(formatCost(usage.cost.total));
  return parts.join(" ");
}
function formatTokenCount(count) {
  if (count < 1e3)
    return count.toString();
  if (count < 1e4)
    return `${(count / 1e3).toFixed(1)}k`;
  return `${Math.round(count / 1e3)}k`;
}

// ../pi-mono/packages/web-ui/dist/utils/model-discovery.js
init_process_shim();

// ../pi-mono/node_modules/@lmstudio/sdk/dist/index.mjs
init_process_shim();

// ../pi-mono/node_modules/@lmstudio/sdk/node_modules/zod/index.js
init_process_shim();

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

// ../pi-mono/node_modules/@lmstudio/sdk/node_modules/zod/v3/errors.js
init_process_shim();

// ../pi-mono/node_modules/@lmstudio/sdk/node_modules/zod/v3/locales/en.js
init_process_shim();

// ../pi-mono/node_modules/@lmstudio/sdk/node_modules/zod/v3/ZodError.js
init_process_shim();

// ../pi-mono/node_modules/@lmstudio/sdk/node_modules/zod/v3/helpers/util.js
init_process_shim();
var util;
(function(util3) {
  util3.assertEqual = (_3) => {
  };
  function assertIs(_arg) {
  }
  util3.assertIs = assertIs;
  function assertNever3(_x) {
    throw new Error();
  }
  util3.assertNever = assertNever3;
  util3.arrayToEnum = (items) => {
    const obj = {};
    for (const item of items) {
      obj[item] = item;
    }
    return obj;
  };
  util3.getValidEnumValues = (obj) => {
    const validKeys = util3.objectKeys(obj).filter((k2) => typeof obj[obj[k2]] !== "number");
    const filtered = {};
    for (const k2 of validKeys) {
      filtered[k2] = obj[k2];
    }
    return util3.objectValues(filtered);
  };
  util3.objectValues = (obj) => {
    return util3.objectKeys(obj).map(function(e9) {
      return obj[e9];
    });
  };
  util3.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
    const keys2 = [];
    for (const key in object) {
      if (Object.prototype.hasOwnProperty.call(object, key)) {
        keys2.push(key);
      }
    }
    return keys2;
  };
  util3.find = (arr, checker) => {
    for (const item of arr) {
      if (checker(item))
        return item;
    }
    return void 0;
  };
  util3.isInteger = typeof Number.isInteger === "function" ? (val2) => Number.isInteger(val2) : (val2) => typeof val2 === "number" && Number.isFinite(val2) && Math.floor(val2) === val2;
  function joinValues(array, separator = " | ") {
    return array.map((val2) => typeof val2 === "string" ? `'${val2}'` : val2).join(separator);
  }
  util3.joinValues = joinValues;
  util3.jsonStringifyReplacer = (_3, value) => {
    if (typeof value === "bigint") {
      return value.toString();
    }
    return value;
  };
})(util || (util = {}));
var objectUtil;
(function(objectUtil3) {
  objectUtil3.mergeShapes = (first, second) => {
    return {
      ...first,
      ...second
      // second overwrites first
    };
  };
})(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 t6 = typeof data;
  switch (t6) {
    case "undefined":
      return ZodParsedType.undefined;
    case "string":
      return ZodParsedType.string;
    case "number":
      return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
    case "boolean":
      return ZodParsedType.boolean;
    case "function":
      return ZodParsedType.function;
    case "bigint":
      return ZodParsedType.bigint;
    case "symbol":
      return ZodParsedType.symbol;
    case "object":
      if (Array.isArray(data)) {
        return ZodParsedType.array;
      }
      if (data === null) {
        return ZodParsedType.null;
      }
      if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
        return ZodParsedType.promise;
      }
      if (typeof Map !== "undefined" && data instanceof Map) {
        return ZodParsedType.map;
      }
      if (typeof Set !== "undefined" && data instanceof Set) {
        return ZodParsedType.set;
      }
      if (typeof Date !== "undefined" && data instanceof Date) {
        return ZodParsedType.date;
      }
      return ZodParsedType.object;
    default:
      return ZodParsedType.unknown;
  }
};

// ../pi-mono/node_modules/@lmstudio/sdk/node_modules/zod/v3/ZodError.js
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 json2 = JSON.stringify(obj, null, 2);
  return json2.replace(/"([^"]+)":/g, "$1:");
};
var ZodError = class _ZodError extends Error {
  get errors() {
    return this.issues;
  }
  constructor(issues) {
    super();
    this.issues = [];
    this.addIssue = (sub2) => {
      this.issues = [...this.issues, sub2];
    };
    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 i7 = 0;
          while (i7 < issue.path.length) {
            const el = issue.path[i7];
            const terminal = i7 === 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];
            i7++;
          }
        }
      }
    };
    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 sub2 of this.issues) {
      if (sub2.path.length > 0) {
        const firstEl = sub2.path[0];
        fieldErrors[firstEl] = fieldErrors[firstEl] || [];
        fieldErrors[firstEl].push(mapper(sub2));
      } else {
        formErrors.push(mapper(sub2));
      }
    }
    return { formErrors, fieldErrors };
  }
  get formErrors() {
    return this.flatten();
  }
};
ZodError.create = (issues) => {
  const error = new ZodError(issues);
  return error;
};

// ../pi-mono/node_modules/@lmstudio/sdk/node_modules/zod/v3/locales/en.js
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 === "bigint")
        message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
      else if (issue.type === "date")
        message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
      else
        message = "Invalid input";
      break;
    case ZodIssueCode.too_big:
      if (issue.type === "array")
        message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
      else if (issue.type === "string")
        message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
      else if (issue.type === "number")
        message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
      else if (issue.type === "bigint")
        message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
      else if (issue.type === "date")
        message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
      else
        message = "Invalid input";
      break;
    case ZodIssueCode.custom:
      message = `Invalid input`;
      break;
    case ZodIssueCode.invalid_intersection_types:
      message = `Intersection results could not be merged`;
      break;
    case ZodIssueCode.not_multiple_of:
      message = `Number must be a multiple of ${issue.multipleOf}`;
      break;
    case ZodIssueCode.not_finite:
      message = "Number must be finite";
      break;
    default:
      message = _ctx.defaultError;
      util.assertNever(issue);
  }
  return { message };
};
var en_default = errorMap;

// ../pi-mono/node_modules/@lmstudio/sdk/node_modules/zod/v3/errors.js
var overrideErrorMap = en_default;
function setErrorMap(map) {
  overrideErrorMap = map;
}
function getErrorMap() {
  return overrideErrorMap;
}

// ../pi-mono/node_modules/@lmstudio/sdk/node_modules/zod/v3/helpers/parseUtil.js
init_process_shim();
var makeIssue = (params) => {
  const { data, path: path6, errorMaps, issueData } = params;
  const fullPath = [...path6, ...issueData.path || []];
  const fullIssue = {
    ...issueData,
    path: fullPath
  };
  if (issueData.message !== void 0) {
    return {
      ...issueData,
      path: fullPath,
      message: issueData.message
    };
  }
  let errorMessage = "";
  const maps = errorMaps.filter((m4) => !!m4).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,
      // contextual error map is first priority
      ctx.schemaErrorMap,
      // then schema-bound map if available
      overrideMap,
      // then global override map
      overrideMap === en_default ? void 0 : en_default
      // then global default map
    ].filter((x2) => !!x2)
  });
  ctx.common.issues.push(issue);
}
var ParseStatus = class _ParseStatus {
  constructor() {
    this.value = "valid";
  }
  dirty() {
    if (this.value === "valid")
      this.value = "dirty";
  }
  abort() {
    if (this.value !== "aborted")
      this.value = "aborted";
  }
  static mergeArray(status, results) {
    const arrayValue = [];
    for (const s6 of results) {
      if (s6.status === "aborted")
        return INVALID;
      if (s6.status === "dirty")
        status.dirty();
      arrayValue.push(s6.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 = (x2) => x2.status === "aborted";
var isDirty = (x2) => x2.status === "dirty";
var isValid = (x2) => x2.status === "valid";
var isAsync = (x2) => typeof Promise !== "undefined" && x2 instanceof Promise;

// ../pi-mono/node_modules/@lmstudio/sdk/node_modules/zod/v3/types.js
init_process_shim();

// ../pi-mono/node_modules/@lmstudio/sdk/node_modules/zod/v3/helpers/errorUtil.js
init_process_shim();
var errorUtil;
(function(errorUtil3) {
  errorUtil3.errToObj = (message) => typeof message === "string" ? { message } : message || {};
  errorUtil3.toString = (message) => typeof message === "string" ? message : message?.message;
})(errorUtil || (errorUtil = {}));

// ../pi-mono/node_modules/@lmstudio/sdk/node_modules/zod/v3/types.js
var ParseInputLazyPath = class {
  constructor(parent, value, path6, key) {
    this._cachedPath = [];
    this.parent = parent;
    this.data = value;
    this._path = path6;
    this._key = key;
  }
  get path() {
    if (!this._cachedPath.length) {
      if (Array.isArray(this._key)) {
        this._cachedPath.push(...this._path, ...this._key);
      } else {
        this._cachedPath.push(...this._path, this._key);
      }
    }
    return this._cachedPath;
  }
};
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: errorMap3, invalid_type_error, required_error, description } = params;
  if (errorMap3 && (invalid_type_error || required_error)) {
    throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
  }
  if (errorMap3)
    return { errorMap: errorMap3, description };
  const customMap = (iss, ctx) => {
    const { message } = params;
    if (iss.code === "invalid_enum_value") {
      return { message: message ?? ctx.defaultError };
    }
    if (typeof ctx.data === "undefined") {
      return { message: message ?? required_error ?? ctx.defaultError };
    }
    if (iss.code !== "invalid_type")
      return { message: ctx.defaultError };
    return { message: message ?? invalid_type_error ?? ctx.defaultError };
  };
  return { errorMap: customMap, description };
}
var ZodType = class {
  get description() {
    return this._def.description;
  }
  _getType(input) {
    return getParsedType(input.data);
  }
  _getOrReturnCtx(input, ctx) {
    return ctx || {
      common: input.parent.common,
      data: input.data,
      parsedType: getParsedType(input.data),
      schemaErrorMap: this._def.errorMap,
      path: input.path,
      parent: input.parent
    };
  }
  _processInputParams(input) {
    return {
      status: new ParseStatus(),
      ctx: {
        common: input.parent.common,
        data: input.data,
        parsedType: getParsedType(input.data),
        schemaErrorMap: this._def.errorMap,
        path: input.path,
        parent: input.parent
      }
    };
  }
  _parseSync(input) {
    const result = this._parse(input);
    if (isAsync(result)) {
      throw new Error("Synchronous parse encountered promise.");
    }
    return result;
  }
  _parseAsync(input) {
    const result = this._parse(input);
    return Promise.resolve(result);
  }
  parse(data, params) {
    const result = this.safeParse(data, params);
    if (result.success)
      return result.data;
    throw result.error;
  }
  safeParse(data, params) {
    const ctx = {
      common: {
        issues: [],
        async: params?.async ?? false,
        contextualErrorMap: params?.errorMap
      },
      path: params?.path || [],
      schemaErrorMap: this._def.errorMap,
      parent: null,
      data,
      parsedType: getParsedType(data)
    };
    const result = this._parseSync({ data, path: ctx.path, parent: ctx });
    return handleResult(ctx, result);
  }
  "~validate"(data) {
    const ctx = {
      common: {
        issues: [],
        async: !!this["~standard"].async
      },
      path: [],
      schemaErrorMap: this._def.errorMap,
      parent: null,
      data,
      parsedType: getParsedType(data)
    };
    if (!this["~standard"].async) {
      try {
        const result = this._parseSync({ data, path: [], parent: ctx });
        return isValid(result) ? {
          value: result.value
        } : {
          issues: ctx.common.issues
        };
      } catch (err) {
        if (err?.message?.toLowerCase()?.includes("encountered")) {
          this["~standard"].async = true;
        }
        ctx.common = {
          issues: [],
          async: true
        };
      }
    }
    return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
      value: result.value
    } : {
      issues: ctx.common.issues
    });
  }
  async parseAsync(data, params) {
    const result = await this.safeParseAsync(data, params);
    if (result.success)
      return result.data;
    throw result.error;
  }
  async safeParseAsync(data, params) {
    const ctx = {
      common: {
        issues: [],
        contextualErrorMap: params?.errorMap,
        async: true
      },
      path: params?.path || [],
      schemaErrorMap: this._def.errorMap,
      parent: null,
      data,
      parsedType: getParsedType(data)
    };
    const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
    const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
    return handleResult(ctx, result);
  }
  refine(check, message) {
    const getIssueProperties = (val2) => {
      if (typeof message === "string" || typeof message === "undefined") {
        return { message };
      } else if (typeof message === "function") {
        return message(val2);
      } else {
        return message;
      }
    };
    return this._refinement((val2, ctx) => {
      const result = check(val2);
      const setError = () => ctx.addIssue({
        code: ZodIssueCode.custom,
        ...getIssueProperties(val2)
      });
      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((val2, ctx) => {
      if (!check(val2)) {
        ctx.addIssue(typeof refinementData === "function" ? refinementData(val2, 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(void 0).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 secondsRegexSource = `[0-5]\\d`;
  if (args.precision) {
    secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
  } else if (args.precision == null) {
    secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
  }
  const secondsQuantifier = args.precision ? "+" : "?";
  return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
}
function timeRegex(args) {
  return new RegExp(`^${timeRegexSource(args)}$`);
}
function datetimeRegex(args) {
  let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
  const opts = [];
  opts.push(args.local ? `Z?` : `Z`);
  if (args.offset)
    opts.push(`([+-]\\d{2}:?\\d{2})`);
  regex = `${regex}(${opts.join("|")})`;
  return new RegExp(`^${regex}$`);
}
function isValidIP(ip, version5) {
  if ((version5 === "v4" || !version5) && ipv4Regex.test(ip)) {
    return true;
  }
  if ((version5 === "v6" || !version5) && ipv6Regex.test(ip)) {
    return true;
  }
  return false;
}
function isValidJWT(jwt, alg) {
  if (!jwtRegex.test(jwt))
    return false;
  try {
    const [header] = jwt.split(".");
    if (!header)
      return false;
    const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
    const decoded = JSON.parse(atob(base64));
    if (typeof decoded !== "object" || decoded === null)
      return false;
    if ("typ" in decoded && decoded?.typ !== "JWT")
      return false;
    if (!decoded.alg)
      return false;
    if (alg && decoded.alg !== alg)
      return false;
    return true;
  } catch {
    return false;
  }
}
function isValidCidr(ip, version5) {
  if ((version5 === "v4" || !version5) && ipv4CidrRegex.test(ip)) {
    return true;
  }
  if ((version5 === "v6" || !version5) && ipv6CidrRegex.test(ip)) {
    return true;
  }
  return false;
}
var ZodString = class _ZodString extends ZodType {
  _parse(input) {
    if (this._def.coerce) {
      input.data = String(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.string) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.string,
        received: ctx2.parsedType
      });
      return INVALID;
    }
    const status = new ParseStatus();
    let ctx = void 0;
    for (const check of this._def.checks) {
      if (check.kind === "min") {
        if (input.data.length < check.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            minimum: check.value,
            type: "string",
            inclusive: true,
            exact: false,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "max") {
        if (input.data.length > check.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            maximum: check.value,
            type: "string",
            inclusive: true,
            exact: false,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "length") {
        const tooBig = input.data.length > check.value;
        const tooSmall = input.data.length < check.value;
        if (tooBig || tooSmall) {
          ctx = this._getOrReturnCtx(input, ctx);
          if (tooBig) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_big,
              maximum: check.value,
              type: "string",
              inclusive: true,
              exact: true,
              message: check.message
            });
          } else if (tooSmall) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_small,
              minimum: check.value,
              type: "string",
              inclusive: true,
              exact: true,
              message: check.message
            });
          }
          status.dirty();
        }
      } else if (check.kind === "email") {
        if (!emailRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "email",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "emoji") {
        if (!emojiRegex) {
          emojiRegex = new RegExp(_emojiRegex, "u");
        }
        if (!emojiRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "emoji",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "uuid") {
        if (!uuidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "uuid",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "nanoid") {
        if (!nanoidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "nanoid",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "cuid") {
        if (!cuidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "cuid",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "cuid2") {
        if (!cuid2Regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "cuid2",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "ulid") {
        if (!ulidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "ulid",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "url") {
        try {
          new URL(input.data);
        } catch {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "url",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "regex") {
        check.regex.lastIndex = 0;
        const testResult = check.regex.test(input.data);
        if (!testResult) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "regex",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "trim") {
        input.data = input.data.trim();
      } else if (check.kind === "includes") {
        if (!input.data.includes(check.value, check.position)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: { includes: check.value, position: check.position },
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "toLowerCase") {
        input.data = input.data.toLowerCase();
      } else if (check.kind === "toUpperCase") {
        input.data = input.data.toUpperCase();
      } else if (check.kind === "startsWith") {
        if (!input.data.startsWith(check.value)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: { startsWith: check.value },
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "endsWith") {
        if (!input.data.endsWith(check.value)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: { endsWith: check.value },
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "datetime") {
        const regex = datetimeRegex(check);
        if (!regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: "datetime",
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "date") {
        const regex = dateRegex;
        if (!regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: "date",
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "time") {
        const regex = timeRegex(check);
        if (!regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: "time",
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "duration") {
        if (!durationRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "duration",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "ip") {
        if (!isValidIP(input.data, check.version)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "ip",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "jwt") {
        if (!isValidJWT(input.data, check.alg)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "jwt",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "cidr") {
        if (!isValidCidr(input.data, check.version)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "cidr",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "base64") {
        if (!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) {
    if (typeof options === "string") {
      return this._addCheck({
        kind: "datetime",
        precision: null,
        offset: false,
        local: false,
        message: options
      });
    }
    return this._addCheck({
      kind: "datetime",
      precision: typeof options?.precision === "undefined" ? null : options?.precision,
      offset: options?.offset ?? false,
      local: options?.local ?? false,
      ...errorUtil.errToObj(options?.message)
    });
  }
  date(message) {
    return this._addCheck({ kind: "date", message });
  }
  time(options) {
    if (typeof options === "string") {
      return this._addCheck({
        kind: "time",
        precision: null,
        message: options
      });
    }
    return this._addCheck({
      kind: "time",
      precision: typeof options?.precision === "undefined" ? null : options?.precision,
      ...errorUtil.errToObj(options?.message)
    });
  }
  duration(message) {
    return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
  }
  regex(regex, message) {
    return this._addCheck({
      kind: "regex",
      regex,
      ...errorUtil.errToObj(message)
    });
  }
  includes(value, options) {
    return this._addCheck({
      kind: "includes",
      value,
      position: options?.position,
      ...errorUtil.errToObj(options?.message)
    });
  }
  startsWith(value, message) {
    return this._addCheck({
      kind: "startsWith",
      value,
      ...errorUtil.errToObj(message)
    });
  }
  endsWith(value, message) {
    return this._addCheck({
      kind: "endsWith",
      value,
      ...errorUtil.errToObj(message)
    });
  }
  min(minLength, message) {
    return this._addCheck({
      kind: "min",
      value: minLength,
      ...errorUtil.errToObj(message)
    });
  }
  max(maxLength, message) {
    return this._addCheck({
      kind: "max",
      value: maxLength,
      ...errorUtil.errToObj(message)
    });
  }
  length(len, message) {
    return this._addCheck({
      kind: "length",
      value: len,
      ...errorUtil.errToObj(message)
    });
  }
  /**
   * Equivalent to `.min(1)`
   */
  nonempty(message) {
    return this.min(1, errorUtil.errToObj(message));
  }
  trim() {
    return new _ZodString({
      ...this._def,
      checks: [...this._def.checks, { kind: "trim" }]
    });
  }
  toLowerCase() {
    return new _ZodString({
      ...this._def,
      checks: [...this._def.checks, { kind: "toLowerCase" }]
    });
  }
  toUpperCase() {
    return new _ZodString({
      ...this._def,
      checks: [...this._def.checks, { kind: "toUpperCase" }]
    });
  }
  get isDatetime() {
    return !!this._def.checks.find((ch) => ch.kind === "datetime");
  }
  get isDate() {
    return !!this._def.checks.find((ch) => ch.kind === "date");
  }
  get isTime() {
    return !!this._def.checks.find((ch) => ch.kind === "time");
  }
  get isDuration() {
    return !!this._def.checks.find((ch) => ch.kind === "duration");
  }
  get isEmail() {
    return !!this._def.checks.find((ch) => ch.kind === "email");
  }
  get isURL() {
    return !!this._def.checks.find((ch) => ch.kind === "url");
  }
  get isEmoji() {
    return !!this._def.checks.find((ch) => ch.kind === "emoji");
  }
  get isUUID() {
    return !!this._def.checks.find((ch) => ch.kind === "uuid");
  }
  get isNANOID() {
    return !!this._def.checks.find((ch) => ch.kind === "nanoid");
  }
  get isCUID() {
    return !!this._def.checks.find((ch) => ch.kind === "cuid");
  }
  get isCUID2() {
    return !!this._def.checks.find((ch) => ch.kind === "cuid2");
  }
  get isULID() {
    return !!this._def.checks.find((ch) => ch.kind === "ulid");
  }
  get isIP() {
    return !!this._def.checks.find((ch) => ch.kind === "ip");
  }
  get isCIDR() {
    return !!this._def.checks.find((ch) => ch.kind === "cidr");
  }
  get isBase64() {
    return !!this._def.checks.find((ch) => ch.kind === "base64");
  }
  get isBase64url() {
    return !!this._def.checks.find((ch) => ch.kind === "base64url");
  }
  get minLength() {
    let min = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min === null || ch.value > min)
          min = ch.value;
      }
    }
    return min;
  }
  get maxLength() {
    let max = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max === null || ch.value < max)
          max = ch.value;
      }
    }
    return max;
  }
};
ZodString.create = (params) => {
  return new ZodString({
    checks: [],
    typeName: ZodFirstPartyTypeKind.ZodString,
    coerce: params?.coerce ?? false,
    ...processCreateParams(params)
  });
};
function floatSafeRemainder(val2, step) {
  const valDecCount = (val2.toString().split(".")[1] || "").length;
  const stepDecCount = (step.toString().split(".")[1] || "").length;
  const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
  const valInt = Number.parseInt(val2.toFixed(decCount).replace(".", ""));
  const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
  return valInt % stepInt / 10 ** decCount;
}
var ZodNumber = class _ZodNumber extends ZodType {
  constructor() {
    super(...arguments);
    this.min = this.gte;
    this.max = this.lte;
    this.step = this.multipleOf;
  }
  _parse(input) {
    if (this._def.coerce) {
      input.data = Number(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.number) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.number,
        received: ctx2.parsedType
      });
      return INVALID;
    }
    let ctx = void 0;
    const status = new ParseStatus();
    for (const check of this._def.checks) {
      if (check.kind === "int") {
        if (!util.isInteger(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: "integer",
            received: "float",
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "min") {
        const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
        if (tooSmall) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            minimum: check.value,
            type: "number",
            inclusive: check.inclusive,
            exact: false,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "max") {
        const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
        if (tooBig) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            maximum: check.value,
            type: "number",
            inclusive: check.inclusive,
            exact: false,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "multipleOf") {
        if (floatSafeRemainder(input.data, check.value) !== 0) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.not_multiple_of,
            multipleOf: check.value,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "finite") {
        if (!Number.isFinite(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.not_finite,
            message: check.message
          });
          status.dirty();
        }
      } else {
        util.assertNever(check);
      }
    }
    return { status: status.value, value: input.data };
  }
  gte(value, message) {
    return this.setLimit("min", value, true, errorUtil.toString(message));
  }
  gt(value, message) {
    return this.setLimit("min", value, false, errorUtil.toString(message));
  }
  lte(value, message) {
    return this.setLimit("max", value, true, errorUtil.toString(message));
  }
  lt(value, message) {
    return this.setLimit("max", value, false, errorUtil.toString(message));
  }
  setLimit(kind, value, inclusive, message) {
    return new _ZodNumber({
      ...this._def,
      checks: [
        ...this._def.checks,
        {
          kind,
          value,
          inclusive,
          message: errorUtil.toString(message)
        }
      ]
    });
  }
  _addCheck(check) {
    return new _ZodNumber({
      ...this._def,
      checks: [...this._def.checks, check]
    });
  }
  int(message) {
    return this._addCheck({
      kind: "int",
      message: errorUtil.toString(message)
    });
  }
  positive(message) {
    return this._addCheck({
      kind: "min",
      value: 0,
      inclusive: false,
      message: errorUtil.toString(message)
    });
  }
  negative(message) {
    return this._addCheck({
      kind: "max",
      value: 0,
      inclusive: false,
      message: errorUtil.toString(message)
    });
  }
  nonpositive(message) {
    return this._addCheck({
      kind: "max",
      value: 0,
      inclusive: true,
      message: errorUtil.toString(message)
    });
  }
  nonnegative(message) {
    return this._addCheck({
      kind: "min",
      value: 0,
      inclusive: true,
      message: errorUtil.toString(message)
    });
  }
  multipleOf(value, message) {
    return this._addCheck({
      kind: "multipleOf",
      value,
      message: errorUtil.toString(message)
    });
  }
  finite(message) {
    return this._addCheck({
      kind: "finite",
      message: errorUtil.toString(message)
    });
  }
  safe(message) {
    return this._addCheck({
      kind: "min",
      inclusive: true,
      value: Number.MIN_SAFE_INTEGER,
      message: errorUtil.toString(message)
    })._addCheck({
      kind: "max",
      inclusive: true,
      value: Number.MAX_SAFE_INTEGER,
      message: errorUtil.toString(message)
    });
  }
  get minValue() {
    let min = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min === null || ch.value > min)
          min = ch.value;
      }
    }
    return min;
  }
  get maxValue() {
    let max = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max === null || ch.value < max)
          max = ch.value;
      }
    }
    return max;
  }
  get isInt() {
    return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
  }
  get isFinite() {
    let max = null;
    let min = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
        return true;
      } else if (ch.kind === "min") {
        if (min === null || ch.value > min)
          min = ch.value;
      } else if (ch.kind === "max") {
        if (max === null || ch.value < max)
          max = ch.value;
      }
    }
    return Number.isFinite(min) && Number.isFinite(max);
  }
};
ZodNumber.create = (params) => {
  return new ZodNumber({
    checks: [],
    typeName: ZodFirstPartyTypeKind.ZodNumber,
    coerce: params?.coerce || false,
    ...processCreateParams(params)
  });
};
var ZodBigInt = class _ZodBigInt extends ZodType {
  constructor() {
    super(...arguments);
    this.min = this.gte;
    this.max = this.lte;
  }
  _parse(input) {
    if (this._def.coerce) {
      try {
        input.data = BigInt(input.data);
      } catch {
        return this._getInvalidInput(input);
      }
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.bigint) {
      return this._getInvalidInput(input);
    }
    let ctx = void 0;
    const status = new ParseStatus();
    for (const check of this._def.checks) {
      if (check.kind === "min") {
        const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
        if (tooSmall) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            type: "bigint",
            minimum: check.value,
            inclusive: check.inclusive,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "max") {
        const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
        if (tooBig) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            type: "bigint",
            maximum: check.value,
            inclusive: check.inclusive,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "multipleOf") {
        if (input.data % check.value !== BigInt(0)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.not_multiple_of,
            multipleOf: check.value,
            message: check.message
          });
          status.dirty();
        }
      } else {
        util.assertNever(check);
      }
    }
    return { status: status.value, value: input.data };
  }
  _getInvalidInput(input) {
    const ctx = this._getOrReturnCtx(input);
    addIssueToContext(ctx, {
      code: ZodIssueCode.invalid_type,
      expected: ZodParsedType.bigint,
      received: ctx.parsedType
    });
    return INVALID;
  }
  gte(value, message) {
    return this.setLimit("min", value, true, errorUtil.toString(message));
  }
  gt(value, message) {
    return this.setLimit("min", value, false, errorUtil.toString(message));
  }
  lte(value, message) {
    return this.setLimit("max", value, true, errorUtil.toString(message));
  }
  lt(value, message) {
    return this.setLimit("max", value, false, errorUtil.toString(message));
  }
  setLimit(kind, value, inclusive, message) {
    return new _ZodBigInt({
      ...this._def,
      checks: [
        ...this._def.checks,
        {
          kind,
          value,
          inclusive,
          message: errorUtil.toString(message)
        }
      ]
    });
  }
  _addCheck(check) {
    return new _ZodBigInt({
      ...this._def,
      checks: [...this._def.checks, check]
    });
  }
  positive(message) {
    return this._addCheck({
      kind: "min",
      value: BigInt(0),
      inclusive: false,
      message: errorUtil.toString(message)
    });
  }
  negative(message) {
    return this._addCheck({
      kind: "max",
      value: BigInt(0),
      inclusive: false,
      message: errorUtil.toString(message)
    });
  }
  nonpositive(message) {
    return this._addCheck({
      kind: "max",
      value: BigInt(0),
      inclusive: true,
      message: errorUtil.toString(message)
    });
  }
  nonnegative(message) {
    return this._addCheck({
      kind: "min",
      value: BigInt(0),
      inclusive: true,
      message: errorUtil.toString(message)
    });
  }
  multipleOf(value, message) {
    return this._addCheck({
      kind: "multipleOf",
      value,
      message: errorUtil.toString(message)
    });
  }
  get minValue() {
    let min = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min === null || ch.value > min)
          min = ch.value;
      }
    }
    return min;
  }
  get maxValue() {
    let max = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max === null || ch.value < max)
          max = ch.value;
      }
    }
    return max;
  }
};
ZodBigInt.create = (params) => {
  return new ZodBigInt({
    checks: [],
    typeName: ZodFirstPartyTypeKind.ZodBigInt,
    coerce: params?.coerce ?? false,
    ...processCreateParams(params)
  });
};
var ZodBoolean = class extends ZodType {
  _parse(input) {
    if (this._def.coerce) {
      input.data = Boolean(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.boolean) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.boolean,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
};
ZodBoolean.create = (params) => {
  return new ZodBoolean({
    typeName: ZodFirstPartyTypeKind.ZodBoolean,
    coerce: params?.coerce || false,
    ...processCreateParams(params)
  });
};
var ZodDate = class _ZodDate extends ZodType {
  _parse(input) {
    if (this._def.coerce) {
      input.data = new Date(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.date) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.date,
        received: ctx2.parsedType
      });
      return INVALID;
    }
    if (Number.isNaN(input.data.getTime())) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_date
      });
      return INVALID;
    }
    const status = new ParseStatus();
    let ctx = void 0;
    for (const check of this._def.checks) {
      if (check.kind === "min") {
        if (input.data.getTime() < check.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            message: check.message,
            inclusive: true,
            exact: false,
            minimum: check.value,
            type: "date"
          });
          status.dirty();
        }
      } else if (check.kind === "max") {
        if (input.data.getTime() > check.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            message: check.message,
            inclusive: true,
            exact: false,
            maximum: check.value,
            type: "date"
          });
          status.dirty();
        }
      } else {
        util.assertNever(check);
      }
    }
    return {
      status: status.value,
      value: new Date(input.data.getTime())
    };
  }
  _addCheck(check) {
    return new _ZodDate({
      ...this._def,
      checks: [...this._def.checks, check]
    });
  }
  min(minDate, message) {
    return this._addCheck({
      kind: "min",
      value: minDate.getTime(),
      message: errorUtil.toString(message)
    });
  }
  max(maxDate, message) {
    return this._addCheck({
      kind: "max",
      value: maxDate.getTime(),
      message: errorUtil.toString(message)
    });
  }
  get minDate() {
    let min = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min === null || ch.value > min)
          min = ch.value;
      }
    }
    return min != null ? new Date(min) : null;
  }
  get maxDate() {
    let max = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max === null || ch.value < max)
          max = ch.value;
      }
    }
    return max != null ? new Date(max) : null;
  }
};
ZodDate.create = (params) => {
  return new ZodDate({
    checks: [],
    coerce: params?.coerce || false,
    typeName: ZodFirstPartyTypeKind.ZodDate,
    ...processCreateParams(params)
  });
};
var ZodSymbol = class extends ZodType {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.symbol) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.symbol,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
};
ZodSymbol.create = (params) => {
  return new ZodSymbol({
    typeName: ZodFirstPartyTypeKind.ZodSymbol,
    ...processCreateParams(params)
  });
};
var ZodUndefined = class extends ZodType {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.undefined) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.undefined,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
};
ZodUndefined.create = (params) => {
  return new ZodUndefined({
    typeName: ZodFirstPartyTypeKind.ZodUndefined,
    ...processCreateParams(params)
  });
};
var ZodNull = class extends ZodType {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.null) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.null,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
};
ZodNull.create = (params) => {
  return new ZodNull({
    typeName: ZodFirstPartyTypeKind.ZodNull,
    ...processCreateParams(params)
  });
};
var ZodAny = class extends ZodType {
  constructor() {
    super(...arguments);
    this._any = true;
  }
  _parse(input) {
    return OK(input.data);
  }
};
ZodAny.create = (params) => {
  return new ZodAny({
    typeName: ZodFirstPartyTypeKind.ZodAny,
    ...processCreateParams(params)
  });
};
var ZodUnknown = class extends ZodType {
  constructor() {
    super(...arguments);
    this._unknown = true;
  }
  _parse(input) {
    return OK(input.data);
  }
};
ZodUnknown.create = (params) => {
  return new ZodUnknown({
    typeName: ZodFirstPartyTypeKind.ZodUnknown,
    ...processCreateParams(params)
  });
};
var ZodNever = class extends ZodType {
  _parse(input) {
    const ctx = this._getOrReturnCtx(input);
    addIssueToContext(ctx, {
      code: ZodIssueCode.invalid_type,
      expected: ZodParsedType.never,
      received: ctx.parsedType
    });
    return INVALID;
  }
};
ZodNever.create = (params) => {
  return new ZodNever({
    typeName: ZodFirstPartyTypeKind.ZodNever,
    ...processCreateParams(params)
  });
};
var ZodVoid = class extends ZodType {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.undefined) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.void,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
};
ZodVoid.create = (params) => {
  return new ZodVoid({
    typeName: ZodFirstPartyTypeKind.ZodVoid,
    ...processCreateParams(params)
  });
};
var ZodArray = class _ZodArray extends ZodType {
  _parse(input) {
    const { ctx, status } = this._processInputParams(input);
    const def = this._def;
    if (ctx.parsedType !== ZodParsedType.array) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.array,
        received: ctx.parsedType
      });
      return INVALID;
    }
    if (def.exactLength !== null) {
      const tooBig = ctx.data.length > def.exactLength.value;
      const tooSmall = ctx.data.length < def.exactLength.value;
      if (tooBig || tooSmall) {
        addIssueToContext(ctx, {
          code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
          minimum: tooSmall ? def.exactLength.value : void 0,
          maximum: tooBig ? def.exactLength.value : void 0,
          type: "array",
          inclusive: true,
          exact: true,
          message: def.exactLength.message
        });
        status.dirty();
      }
    }
    if (def.minLength !== null) {
      if (ctx.data.length < def.minLength.value) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.too_small,
          minimum: def.minLength.value,
          type: "array",
          inclusive: true,
          exact: false,
          message: def.minLength.message
        });
        status.dirty();
      }
    }
    if (def.maxLength !== null) {
      if (ctx.data.length > def.maxLength.value) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.too_big,
          maximum: def.maxLength.value,
          type: "array",
          inclusive: true,
          exact: false,
          message: def.maxLength.message
        });
        status.dirty();
      }
    }
    if (ctx.common.async) {
      return Promise.all([...ctx.data].map((item, i7) => {
        return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i7));
      })).then((result2) => {
        return ParseStatus.mergeArray(status, result2);
      });
    }
    const result = [...ctx.data].map((item, i7) => {
      return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i7));
    });
    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;
  }
}
var ZodObject = class _ZodObject extends ZodType {
  constructor() {
    super(...arguments);
    this._cached = null;
    this.nonstrict = this.passthrough;
    this.augment = this.extend;
  }
  _getCached() {
    if (this._cached !== null)
      return this._cached;
    const shape = this._def.shape();
    const keys2 = util.objectKeys(shape);
    this._cached = { shape, keys: keys2 };
    return this._cached;
  }
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.object) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.object,
        received: ctx2.parsedType
      });
      return INVALID;
    }
    const { status, ctx } = this._processInputParams(input);
    const { shape, keys: shapeKeys } = this._getCached();
    const extraKeys = [];
    if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
      for (const key in ctx.data) {
        if (!shapeKeys.includes(key)) {
          extraKeys.push(key);
        }
      }
    }
    const pairs = [];
    for (const key of shapeKeys) {
      const keyValidator = shape[key];
      const value = ctx.data[key];
      pairs.push({
        key: { status: "valid", value: key },
        value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
        alwaysSet: key in ctx.data
      });
    }
    if (this._def.catchall instanceof ZodNever) {
      const unknownKeys = this._def.unknownKeys;
      if (unknownKeys === "passthrough") {
        for (const key of extraKeys) {
          pairs.push({
            key: { status: "valid", value: key },
            value: { status: "valid", value: ctx.data[key] }
          });
        }
      } else if (unknownKeys === "strict") {
        if (extraKeys.length > 0) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.unrecognized_keys,
            keys: extraKeys
          });
          status.dirty();
        }
      } else if (unknownKeys === "strip") {
      } else {
        throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
      }
    } else {
      const catchall = this._def.catchall;
      for (const key of extraKeys) {
        const value = ctx.data[key];
        pairs.push({
          key: { status: "valid", value: key },
          value: catchall._parse(
            new ParseInputLazyPath(ctx, value, ctx.path, key)
            //, ctx.child(key), value, getParsedType(value)
          ),
          alwaysSet: key in ctx.data
        });
      }
    }
    if (ctx.common.async) {
      return Promise.resolve().then(async () => {
        const syncPairs = [];
        for (const pair of pairs) {
          const key = await pair.key;
          const value = await pair.value;
          syncPairs.push({
            key,
            value,
            alwaysSet: pair.alwaysSet
          });
        }
        return syncPairs;
      }).then((syncPairs) => {
        return ParseStatus.mergeObjectSync(status, syncPairs);
      });
    } else {
      return ParseStatus.mergeObjectSync(status, pairs);
    }
  }
  get shape() {
    return this._def.shape();
  }
  strict(message) {
    errorUtil.errToObj;
    return new _ZodObject({
      ...this._def,
      unknownKeys: "strict",
      ...message !== void 0 ? {
        errorMap: (issue, ctx) => {
          const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
          if (issue.code === "unrecognized_keys")
            return {
              message: errorUtil.errToObj(message).message ?? defaultError
            };
          return {
            message: defaultError
          };
        }
      } : {}
    });
  }
  strip() {
    return new _ZodObject({
      ...this._def,
      unknownKeys: "strip"
    });
  }
  passthrough() {
    return new _ZodObject({
      ...this._def,
      unknownKeys: "passthrough"
    });
  }
  // const AugmentFactory =
  //   <Def extends ZodObjectDef>(def: Def) =>
  //   <Augmentation extends ZodRawShape>(
  //     augmentation: Augmentation
  //   ): ZodObject<
  //     extendShape<ReturnType<Def["shape"]>, Augmentation>,
  //     Def["unknownKeys"],
  //     Def["catchall"]
  //   > => {
  //     return new ZodObject({
  //       ...def,
  //       shape: () => ({
  //         ...def.shape(),
  //         ...augmentation,
  //       }),
  //     }) as any;
  //   };
  extend(augmentation) {
    return new _ZodObject({
      ...this._def,
      shape: () => ({
        ...this._def.shape(),
        ...augmentation
      })
    });
  }
  /**
   * Prior to zod@1.0.12 there was a bug in the
   * inferred type of merged objects. Please
   * upgrade if you are experiencing issues.
   */
  merge(merging) {
    const merged = new _ZodObject({
      unknownKeys: merging._def.unknownKeys,
      catchall: merging._def.catchall,
      shape: () => ({
        ...this._def.shape(),
        ...merging._def.shape()
      }),
      typeName: ZodFirstPartyTypeKind.ZodObject
    });
    return merged;
  }
  // merge<
  //   Incoming extends AnyZodObject,
  //   Augmentation extends Incoming["shape"],
  //   NewOutput extends {
  //     [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
  //       ? Augmentation[k]["_output"]
  //       : k extends keyof Output
  //       ? Output[k]
  //       : never;
  //   },
  //   NewInput extends {
  //     [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
  //       ? Augmentation[k]["_input"]
  //       : k extends keyof Input
  //       ? Input[k]
  //       : never;
  //   }
  // >(
  //   merging: Incoming
  // ): ZodObject<
  //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
  //   Incoming["_def"]["unknownKeys"],
  //   Incoming["_def"]["catchall"],
  //   NewOutput,
  //   NewInput
  // > {
  //   const merged: any = new ZodObject({
  //     unknownKeys: merging._def.unknownKeys,
  //     catchall: merging._def.catchall,
  //     shape: () =>
  //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
  //     typeName: ZodFirstPartyTypeKind.ZodObject,
  //   }) as any;
  //   return merged;
  // }
  setKey(key, schema) {
    return this.augment({ [key]: schema });
  }
  // merge<Incoming extends AnyZodObject>(
  //   merging: Incoming
  // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
  // ZodObject<
  //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
  //   Incoming["_def"]["unknownKeys"],
  //   Incoming["_def"]["catchall"]
  // > {
  //   // const mergedShape = objectUtil.mergeShapes(
  //   //   this._def.shape(),
  //   //   merging._def.shape()
  //   // );
  //   const merged: any = new ZodObject({
  //     unknownKeys: merging._def.unknownKeys,
  //     catchall: merging._def.catchall,
  //     shape: () =>
  //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
  //     typeName: ZodFirstPartyTypeKind.ZodObject,
  //   }) as any;
  //   return merged;
  // }
  catchall(index) {
    return new _ZodObject({
      ...this._def,
      catchall: index
    });
  }
  pick(mask) {
    const shape = {};
    for (const key of util.objectKeys(mask)) {
      if (mask[key] && this.shape[key]) {
        shape[key] = this.shape[key];
      }
    }
    return new _ZodObject({
      ...this._def,
      shape: () => shape
    });
  }
  omit(mask) {
    const shape = {};
    for (const key of util.objectKeys(this.shape)) {
      if (!mask[key]) {
        shape[key] = this.shape[key];
      }
    }
    return new _ZodObject({
      ...this._def,
      shape: () => shape
    });
  }
  /**
   * @deprecated
   */
  deepPartial() {
    return deepPartialify(this);
  }
  partial(mask) {
    const newShape = {};
    for (const key of util.objectKeys(this.shape)) {
      const fieldSchema = this.shape[key];
      if (mask && !mask[key]) {
        newShape[key] = fieldSchema;
      } else {
        newShape[key] = fieldSchema.optional();
      }
    }
    return new _ZodObject({
      ...this._def,
      shape: () => newShape
    });
  }
  required(mask) {
    const newShape = {};
    for (const key of util.objectKeys(this.shape)) {
      if (mask && !mask[key]) {
        newShape[key] = this.shape[key];
      } else {
        const fieldSchema = this.shape[key];
        let newField = fieldSchema;
        while (newField instanceof ZodOptional) {
          newField = newField._def.innerType;
        }
        newShape[key] = newField;
      }
    }
    return new _ZodObject({
      ...this._def,
      shape: () => newShape
    });
  }
  keyof() {
    return createZodEnum(util.objectKeys(this.shape));
  }
};
ZodObject.create = (shape, params) => {
  return new ZodObject({
    shape: () => shape,
    unknownKeys: "strip",
    catchall: ZodNever.create(),
    typeName: ZodFirstPartyTypeKind.ZodObject,
    ...processCreateParams(params)
  });
};
ZodObject.strictCreate = (shape, params) => {
  return new ZodObject({
    shape: () => shape,
    unknownKeys: "strict",
    catchall: ZodNever.create(),
    typeName: ZodFirstPartyTypeKind.ZodObject,
    ...processCreateParams(params)
  });
};
ZodObject.lazycreate = (shape, params) => {
  return new ZodObject({
    shape,
    unknownKeys: "strip",
    catchall: ZodNever.create(),
    typeName: ZodFirstPartyTypeKind.ZodObject,
    ...processCreateParams(params)
  });
};
var ZodUnion = class extends ZodType {
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    const options = this._def.options;
    function handleResults(results) {
      for (const result of results) {
        if (result.result.status === "valid") {
          return result.result;
        }
      }
      for (const result of results) {
        if (result.result.status === "dirty") {
          ctx.common.issues.push(...result.ctx.common.issues);
          return result.result;
        }
      }
      const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_union,
        unionErrors
      });
      return INVALID;
    }
    if (ctx.common.async) {
      return Promise.all(options.map(async (option) => {
        const childCtx = {
          ...ctx,
          common: {
            ...ctx.common,
            issues: []
          },
          parent: null
        };
        return {
          result: await option._parseAsync({
            data: ctx.data,
            path: ctx.path,
            parent: childCtx
          }),
          ctx: childCtx
        };
      })).then(handleResults);
    } else {
      let dirty = void 0;
      const issues = [];
      for (const option of options) {
        const childCtx = {
          ...ctx,
          common: {
            ...ctx.common,
            issues: []
          },
          parent: null
        };
        const result = option._parseSync({
          data: ctx.data,
          path: ctx.path,
          parent: childCtx
        });
        if (result.status === "valid") {
          return result;
        } else if (result.status === "dirty" && !dirty) {
          dirty = { result, ctx: childCtx };
        }
        if (childCtx.common.issues.length) {
          issues.push(childCtx.common.issues);
        }
      }
      if (dirty) {
        ctx.common.issues.push(...dirty.ctx.common.issues);
        return dirty.result;
      }
      const unionErrors = issues.map((issues2) => new ZodError(issues2));
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_union,
        unionErrors
      });
      return INVALID;
    }
  }
  get options() {
    return this._def.options;
  }
};
ZodUnion.create = (types2, params) => {
  return new ZodUnion({
    options: types2,
    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 [void 0];
  } else if (type instanceof ZodNull) {
    return [null];
  } else if (type instanceof ZodOptional) {
    return [void 0, ...getDiscriminator(type.unwrap())];
  } else if (type instanceof ZodNullable) {
    return [null, ...getDiscriminator(type.unwrap())];
  } else if (type instanceof ZodBranded) {
    return getDiscriminator(type.unwrap());
  } else if (type instanceof ZodReadonly) {
    return getDiscriminator(type.unwrap());
  } else if (type instanceof ZodCatch) {
    return getDiscriminator(type._def.innerType);
  } else {
    return [];
  }
};
var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.object) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.object,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const discriminator = this.discriminator;
    const discriminatorValue = ctx.data[discriminator];
    const option = this.optionsMap.get(discriminatorValue);
    if (!option) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_union_discriminator,
        options: Array.from(this.optionsMap.keys()),
        path: [discriminator]
      });
      return INVALID;
    }
    if (ctx.common.async) {
      return option._parseAsync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      });
    } else {
      return option._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      });
    }
  }
  get discriminator() {
    return this._def.discriminator;
  }
  get options() {
    return this._def.options;
  }
  get optionsMap() {
    return this._def.optionsMap;
  }
  /**
   * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
   * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
   * have a different value for each object in the union.
   * @param discriminator the name of the discriminator property
   * @param types an array of object schemas
   * @param params
   */
  static create(discriminator, options, params) {
    const optionsMap = /* @__PURE__ */ new Map();
    for (const type of options) {
      const discriminatorValues = getDiscriminator(type.shape[discriminator]);
      if (!discriminatorValues.length) {
        throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
      }
      for (const value of discriminatorValues) {
        if (optionsMap.has(value)) {
          throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
        }
        optionsMap.set(value, type);
      }
    }
    return new _ZodDiscriminatedUnion({
      typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
      discriminator,
      options,
      optionsMap,
      ...processCreateParams(params)
    });
  }
};
function mergeValues(a3, b4) {
  const aType = getParsedType(a3);
  const bType = getParsedType(b4);
  if (a3 === b4) {
    return { valid: true, data: a3 };
  } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
    const bKeys = util.objectKeys(b4);
    const sharedKeys = util.objectKeys(a3).filter((key) => bKeys.indexOf(key) !== -1);
    const newObj = { ...a3, ...b4 };
    for (const key of sharedKeys) {
      const sharedValue = mergeValues(a3[key], b4[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 (a3.length !== b4.length) {
      return { valid: false };
    }
    const newArray = [];
    for (let index = 0; index < a3.length; index++) {
      const itemA = a3[index];
      const itemB = b4[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 && +a3 === +b4) {
    return { valid: true, data: a3 };
  } else {
    return { valid: false };
  }
}
var ZodIntersection = class extends ZodType {
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    const handleParsed = (parsedLeft, parsedRight) => {
      if (isAborted(parsedLeft) || isAborted(parsedRight)) {
        return INVALID;
      }
      const merged = mergeValues(parsedLeft.value, parsedRight.value);
      if (!merged.valid) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.invalid_intersection_types
        });
        return INVALID;
      }
      if (isDirty(parsedLeft) || isDirty(parsedRight)) {
        status.dirty();
      }
      return { status: status.value, value: merged.data };
    };
    if (ctx.common.async) {
      return Promise.all([
        this._def.left._parseAsync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        }),
        this._def.right._parseAsync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        })
      ]).then(([left, right]) => handleParsed(left, right));
    } else {
      return handleParsed(this._def.left._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      }), this._def.right._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      }));
    }
  }
};
ZodIntersection.create = (left, right, params) => {
  return new ZodIntersection({
    left,
    right,
    typeName: ZodFirstPartyTypeKind.ZodIntersection,
    ...processCreateParams(params)
  });
};
var ZodTuple = class _ZodTuple extends ZodType {
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.array) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.array,
        received: ctx.parsedType
      });
      return INVALID;
    }
    if (ctx.data.length < this._def.items.length) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.too_small,
        minimum: this._def.items.length,
        inclusive: true,
        exact: false,
        type: "array"
      });
      return INVALID;
    }
    const rest = this._def.rest;
    if (!rest && ctx.data.length > this._def.items.length) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.too_big,
        maximum: this._def.items.length,
        inclusive: true,
        exact: false,
        type: "array"
      });
      status.dirty();
    }
    const items = [...ctx.data].map((item, itemIndex) => {
      const schema = this._def.items[itemIndex] || this._def.rest;
      if (!schema)
        return null;
      return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
    }).filter((x2) => !!x2);
    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)
  });
};
var ZodRecord = class _ZodRecord extends ZodType {
  get keySchema() {
    return this._def.keyType;
  }
  get valueSchema() {
    return this._def.valueType;
  }
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.object) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.object,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const pairs = [];
    const keyType = this._def.keyType;
    const valueType = this._def.valueType;
    for (const key in ctx.data) {
      pairs.push({
        key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
        value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
        alwaysSet: key in ctx.data
      });
    }
    if (ctx.common.async) {
      return ParseStatus.mergeObjectAsync(status, pairs);
    } else {
      return ParseStatus.mergeObjectSync(status, pairs);
    }
  }
  get element() {
    return this._def.valueType;
  }
  static create(first, second, third) {
    if (second instanceof ZodType) {
      return new _ZodRecord({
        keyType: first,
        valueType: second,
        typeName: ZodFirstPartyTypeKind.ZodRecord,
        ...processCreateParams(third)
      });
    }
    return new _ZodRecord({
      keyType: ZodString.create(),
      valueType: first,
      typeName: ZodFirstPartyTypeKind.ZodRecord,
      ...processCreateParams(second)
    });
  }
};
var ZodMap = class extends ZodType {
  get keySchema() {
    return this._def.keyType;
  }
  get valueSchema() {
    return this._def.valueType;
  }
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.map) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.map,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const keyType = this._def.keyType;
    const valueType = this._def.valueType;
    const pairs = [...ctx.data.entries()].map(([key, value], 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 = /* @__PURE__ */ new Map();
      return Promise.resolve().then(async () => {
        for (const pair of pairs) {
          const key = await pair.key;
          const value = await pair.value;
          if (key.status === "aborted" || value.status === "aborted") {
            return INVALID;
          }
          if (key.status === "dirty" || value.status === "dirty") {
            status.dirty();
          }
          finalMap.set(key.value, value.value);
        }
        return { status: status.value, value: finalMap };
      });
    } else {
      const finalMap = /* @__PURE__ */ new Map();
      for (const pair of pairs) {
        const key = pair.key;
        const value = pair.value;
        if (key.status === "aborted" || value.status === "aborted") {
          return INVALID;
        }
        if (key.status === "dirty" || value.status === "dirty") {
          status.dirty();
        }
        finalMap.set(key.value, value.value);
      }
      return { status: status.value, value: finalMap };
    }
  }
};
ZodMap.create = (keyType, valueType, params) => {
  return new ZodMap({
    valueType,
    keyType,
    typeName: ZodFirstPartyTypeKind.ZodMap,
    ...processCreateParams(params)
  });
};
var ZodSet = class _ZodSet extends ZodType {
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.set) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.set,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const def = this._def;
    if (def.minSize !== null) {
      if (ctx.data.size < def.minSize.value) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.too_small,
          minimum: def.minSize.value,
          type: "set",
          inclusive: true,
          exact: false,
          message: def.minSize.message
        });
        status.dirty();
      }
    }
    if (def.maxSize !== null) {
      if (ctx.data.size > def.maxSize.value) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.too_big,
          maximum: def.maxSize.value,
          type: "set",
          inclusive: true,
          exact: false,
          message: def.maxSize.message
        });
        status.dirty();
      }
    }
    const valueType = this._def.valueType;
    function finalizeSet(elements2) {
      const parsedSet = /* @__PURE__ */ new Set();
      for (const element of elements2) {
        if (element.status === "aborted")
          return INVALID;
        if (element.status === "dirty")
          status.dirty();
        parsedSet.add(element.value);
      }
      return { status: status.value, value: parsedSet };
    }
    const elements = [...ctx.data.values()].map((item, i7) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i7)));
    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)
  });
};
var ZodFunction = class _ZodFunction extends ZodType {
  constructor() {
    super(...arguments);
    this.validate = this.implement;
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.function) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.function,
        received: ctx.parsedType
      });
      return INVALID;
    }
    function makeArgsIssue(args, error) {
      return makeIssue({
        data: args,
        path: ctx.path,
        errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x2) => !!x2),
        issueData: {
          code: ZodIssueCode.invalid_arguments,
          argumentsError: error
        }
      });
    }
    function makeReturnsIssue(returns, error) {
      return makeIssue({
        data: returns,
        path: ctx.path,
        errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x2) => !!x2),
        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((e9) => {
          error.addIssue(makeArgsIssue(args, e9));
          throw error;
        });
        const result = await Reflect.apply(fn, this, parsedArgs);
        const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e9) => {
          error.addIssue(makeReturnsIssue(result, e9));
          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)
    });
  }
};
var ZodLazy = class extends ZodType {
  get schema() {
    return this._def.getter();
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    const lazySchema = this._def.getter();
    return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
  }
};
ZodLazy.create = (getter, params) => {
  return new ZodLazy({
    getter,
    typeName: ZodFirstPartyTypeKind.ZodLazy,
    ...processCreateParams(params)
  });
};
var ZodLiteral = class extends ZodType {
  _parse(input) {
    if (input.data !== this._def.value) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        received: ctx.data,
        code: ZodIssueCode.invalid_literal,
        expected: this._def.value
      });
      return INVALID;
    }
    return { status: "valid", value: input.data };
  }
  get value() {
    return this._def.value;
  }
};
ZodLiteral.create = (value, params) => {
  return new ZodLiteral({
    value,
    typeName: ZodFirstPartyTypeKind.ZodLiteral,
    ...processCreateParams(params)
  });
};
function createZodEnum(values2, params) {
  return new ZodEnum({
    values: values2,
    typeName: ZodFirstPartyTypeKind.ZodEnum,
    ...processCreateParams(params)
  });
}
var ZodEnum = class _ZodEnum extends ZodType {
  _parse(input) {
    if (typeof input.data !== "string") {
      const ctx = this._getOrReturnCtx(input);
      const expectedValues = this._def.values;
      addIssueToContext(ctx, {
        expected: util.joinValues(expectedValues),
        received: ctx.parsedType,
        code: ZodIssueCode.invalid_type
      });
      return INVALID;
    }
    if (!this._cache) {
      this._cache = new Set(this._def.values);
    }
    if (!this._cache.has(input.data)) {
      const ctx = this._getOrReturnCtx(input);
      const expectedValues = this._def.values;
      addIssueToContext(ctx, {
        received: ctx.data,
        code: ZodIssueCode.invalid_enum_value,
        options: expectedValues
      });
      return INVALID;
    }
    return OK(input.data);
  }
  get options() {
    return this._def.values;
  }
  get enum() {
    const enumValues = {};
    for (const val2 of this._def.values) {
      enumValues[val2] = val2;
    }
    return enumValues;
  }
  get Values() {
    const enumValues = {};
    for (const val2 of this._def.values) {
      enumValues[val2] = val2;
    }
    return enumValues;
  }
  get Enum() {
    const enumValues = {};
    for (const val2 of this._def.values) {
      enumValues[val2] = val2;
    }
    return enumValues;
  }
  extract(values2, newDef = this._def) {
    return _ZodEnum.create(values2, {
      ...this._def,
      ...newDef
    });
  }
  exclude(values2, newDef = this._def) {
    return _ZodEnum.create(this.options.filter((opt) => !values2.includes(opt)), {
      ...this._def,
      ...newDef
    });
  }
};
ZodEnum.create = createZodEnum;
var ZodNativeEnum = class extends ZodType {
  _parse(input) {
    const nativeEnumValues = util.getValidEnumValues(this._def.values);
    const ctx = this._getOrReturnCtx(input);
    if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
      const expectedValues = util.objectValues(nativeEnumValues);
      addIssueToContext(ctx, {
        expected: util.joinValues(expectedValues),
        received: ctx.parsedType,
        code: ZodIssueCode.invalid_type
      });
      return INVALID;
    }
    if (!this._cache) {
      this._cache = new Set(util.getValidEnumValues(this._def.values));
    }
    if (!this._cache.has(input.data)) {
      const expectedValues = util.objectValues(nativeEnumValues);
      addIssueToContext(ctx, {
        received: ctx.data,
        code: ZodIssueCode.invalid_enum_value,
        options: expectedValues
      });
      return INVALID;
    }
    return OK(input.data);
  }
  get enum() {
    return this._def.values;
  }
};
ZodNativeEnum.create = (values2, params) => {
  return new ZodNativeEnum({
    values: values2,
    typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
    ...processCreateParams(params)
  });
};
var ZodPromise = class extends ZodType {
  unwrap() {
    return this._def.type;
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.promise,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
    return OK(promisified.then((data) => {
      return this._def.type.parseAsync(data, {
        path: ctx.path,
        errorMap: ctx.common.contextualErrorMap
      });
    }));
  }
};
ZodPromise.create = (schema, params) => {
  return new ZodPromise({
    type: schema,
    typeName: ZodFirstPartyTypeKind.ZodPromise,
    ...processCreateParams(params)
  });
};
var ZodEffects = class extends ZodType {
  innerType() {
    return this._def.schema;
  }
  sourceType() {
    return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
  }
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    const effect = this._def.effect || null;
    const checkCtx = {
      addIssue: (arg) => {
        addIssueToContext(ctx, arg);
        if (arg.fatal) {
          status.abort();
        } else {
          status.dirty();
        }
      },
      get path() {
        return ctx.path;
      }
    };
    checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
    if (effect.type === "preprocess") {
      const processed = effect.transform(ctx.data, checkCtx);
      if (ctx.common.async) {
        return Promise.resolve(processed).then(async (processed2) => {
          if (status.value === "aborted")
            return INVALID;
          const result = await this._def.schema._parseAsync({
            data: processed2,
            path: ctx.path,
            parent: ctx
          });
          if (result.status === "aborted")
            return INVALID;
          if (result.status === "dirty")
            return DIRTY(result.value);
          if (status.value === "dirty")
            return DIRTY(result.value);
          return result;
        });
      } else {
        if (status.value === "aborted")
          return INVALID;
        const result = this._def.schema._parseSync({
          data: processed,
          path: ctx.path,
          parent: ctx
        });
        if (result.status === "aborted")
          return INVALID;
        if (result.status === "dirty")
          return DIRTY(result.value);
        if (status.value === "dirty")
          return DIRTY(result.value);
        return result;
      }
    }
    if (effect.type === "refinement") {
      const executeRefinement = (acc) => {
        const result = effect.refinement(acc, checkCtx);
        if (ctx.common.async) {
          return Promise.resolve(result);
        }
        if (result instanceof Promise) {
          throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
        }
        return acc;
      };
      if (ctx.common.async === false) {
        const inner2 = this._def.schema._parseSync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        });
        if (inner2.status === "aborted")
          return INVALID;
        if (inner2.status === "dirty")
          status.dirty();
        executeRefinement(inner2.value);
        return { status: status.value, value: inner2.value };
      } else {
        return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner2) => {
          if (inner2.status === "aborted")
            return INVALID;
          if (inner2.status === "dirty")
            status.dirty();
          return executeRefinement(inner2.value).then(() => {
            return { status: status.value, value: inner2.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 INVALID;
        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 INVALID;
          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)
  });
};
var ZodOptional = class extends ZodType {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType === ZodParsedType.undefined) {
      return OK(void 0);
    }
    return this._def.innerType._parse(input);
  }
  unwrap() {
    return this._def.innerType;
  }
};
ZodOptional.create = (type, params) => {
  return new ZodOptional({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodOptional,
    ...processCreateParams(params)
  });
};
var ZodNullable = class extends ZodType {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType === ZodParsedType.null) {
      return OK(null);
    }
    return this._def.innerType._parse(input);
  }
  unwrap() {
    return this._def.innerType;
  }
};
ZodNullable.create = (type, params) => {
  return new ZodNullable({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodNullable,
    ...processCreateParams(params)
  });
};
var ZodDefault = class extends ZodType {
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    let data = ctx.data;
    if (ctx.parsedType === ZodParsedType.undefined) {
      data = this._def.defaultValue();
    }
    return this._def.innerType._parse({
      data,
      path: ctx.path,
      parent: ctx
    });
  }
  removeDefault() {
    return this._def.innerType;
  }
};
ZodDefault.create = (type, params) => {
  return new ZodDefault({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodDefault,
    defaultValue: typeof params.default === "function" ? params.default : () => params.default,
    ...processCreateParams(params)
  });
};
var ZodCatch = class extends ZodType {
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    const newCtx = {
      ...ctx,
      common: {
        ...ctx.common,
        issues: []
      }
    };
    const result = this._def.innerType._parse({
      data: newCtx.data,
      path: newCtx.path,
      parent: {
        ...newCtx
      }
    });
    if (isAsync(result)) {
      return result.then((result2) => {
        return {
          status: "valid",
          value: result2.status === "valid" ? result2.value : this._def.catchValue({
            get error() {
              return new ZodError(newCtx.common.issues);
            },
            input: newCtx.data
          })
        };
      });
    } else {
      return {
        status: "valid",
        value: result.status === "valid" ? result.value : this._def.catchValue({
          get error() {
            return new ZodError(newCtx.common.issues);
          },
          input: newCtx.data
        })
      };
    }
  }
  removeCatch() {
    return this._def.innerType;
  }
};
ZodCatch.create = (type, params) => {
  return new ZodCatch({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodCatch,
    catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
    ...processCreateParams(params)
  });
};
var ZodNaN = class extends ZodType {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.nan) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.nan,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return { status: "valid", value: input.data };
  }
};
ZodNaN.create = (params) => {
  return new ZodNaN({
    typeName: ZodFirstPartyTypeKind.ZodNaN,
    ...processCreateParams(params)
  });
};
var BRAND = Symbol("zod_brand");
var ZodBranded = class extends ZodType {
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    const data = ctx.data;
    return this._def.type._parse({
      data,
      path: ctx.path,
      parent: ctx
    });
  }
  unwrap() {
    return this._def.type;
  }
};
var ZodPipeline = class _ZodPipeline extends ZodType {
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.common.async) {
      const handleAsync = async () => {
        const inResult = await this._def.in._parseAsync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        });
        if (inResult.status === "aborted")
          return INVALID;
        if (inResult.status === "dirty") {
          status.dirty();
          return DIRTY(inResult.value);
        } else {
          return this._def.out._parseAsync({
            data: inResult.value,
            path: ctx.path,
            parent: ctx
          });
        }
      };
      return handleAsync();
    } else {
      const inResult = this._def.in._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      });
      if (inResult.status === "aborted")
        return INVALID;
      if (inResult.status === "dirty") {
        status.dirty();
        return {
          status: "dirty",
          value: inResult.value
        };
      } else {
        return this._def.out._parseSync({
          data: inResult.value,
          path: ctx.path,
          parent: ctx
        });
      }
    }
  }
  static create(a3, b4) {
    return new _ZodPipeline({
      in: a3,
      out: b4,
      typeName: ZodFirstPartyTypeKind.ZodPipeline
    });
  }
};
var ZodReadonly = class extends ZodType {
  _parse(input) {
    const result = this._def.innerType._parse(input);
    const freeze2 = (data) => {
      if (isValid(data)) {
        data.value = Object.freeze(data.value);
      }
      return data;
    };
    return isAsync(result) ? result.then((data) => freeze2(data)) : freeze2(result);
  }
  unwrap() {
    return this._def.innerType;
  }
};
ZodReadonly.create = (type, params) => {
  return new ZodReadonly({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodReadonly,
    ...processCreateParams(params)
  });
};
function cleanParams(params, data) {
  const p4 = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
  const p22 = typeof p4 === "string" ? { message: p4 } : p4;
  return p22;
}
function custom(check, _params = {}, fatal) {
  if (check)
    return ZodAny.create().superRefine((data, ctx) => {
      const r8 = check(data);
      if (r8 instanceof Promise) {
        return r8.then((r9) => {
          if (!r9) {
            const params = cleanParams(_params, data);
            const _fatal = params.fatal ?? fatal ?? true;
            ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
          }
        });
      }
      if (!r8) {
        const params = cleanParams(_params, data);
        const _fatal = params.fatal ?? fatal ?? true;
        ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
      }
      return;
    });
  return ZodAny.create();
}
var late = {
  object: ZodObject.lazycreate
};
var ZodFirstPartyTypeKind;
(function(ZodFirstPartyTypeKind3) {
  ZodFirstPartyTypeKind3["ZodString"] = "ZodString";
  ZodFirstPartyTypeKind3["ZodNumber"] = "ZodNumber";
  ZodFirstPartyTypeKind3["ZodNaN"] = "ZodNaN";
  ZodFirstPartyTypeKind3["ZodBigInt"] = "ZodBigInt";
  ZodFirstPartyTypeKind3["ZodBoolean"] = "ZodBoolean";
  ZodFirstPartyTypeKind3["ZodDate"] = "ZodDate";
  ZodFirstPartyTypeKind3["ZodSymbol"] = "ZodSymbol";
  ZodFirstPartyTypeKind3["ZodUndefined"] = "ZodUndefined";
  ZodFirstPartyTypeKind3["ZodNull"] = "ZodNull";
  ZodFirstPartyTypeKind3["ZodAny"] = "ZodAny";
  ZodFirstPartyTypeKind3["ZodUnknown"] = "ZodUnknown";
  ZodFirstPartyTypeKind3["ZodNever"] = "ZodNever";
  ZodFirstPartyTypeKind3["ZodVoid"] = "ZodVoid";
  ZodFirstPartyTypeKind3["ZodArray"] = "ZodArray";
  ZodFirstPartyTypeKind3["ZodObject"] = "ZodObject";
  ZodFirstPartyTypeKind3["ZodUnion"] = "ZodUnion";
  ZodFirstPartyTypeKind3["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
  ZodFirstPartyTypeKind3["ZodIntersection"] = "ZodIntersection";
  ZodFirstPartyTypeKind3["ZodTuple"] = "ZodTuple";
  ZodFirstPartyTypeKind3["ZodRecord"] = "ZodRecord";
  ZodFirstPartyTypeKind3["ZodMap"] = "ZodMap";
  ZodFirstPartyTypeKind3["ZodSet"] = "ZodSet";
  ZodFirstPartyTypeKind3["ZodFunction"] = "ZodFunction";
  ZodFirstPartyTypeKind3["ZodLazy"] = "ZodLazy";
  ZodFirstPartyTypeKind3["ZodLiteral"] = "ZodLiteral";
  ZodFirstPartyTypeKind3["ZodEnum"] = "ZodEnum";
  ZodFirstPartyTypeKind3["ZodEffects"] = "ZodEffects";
  ZodFirstPartyTypeKind3["ZodNativeEnum"] = "ZodNativeEnum";
  ZodFirstPartyTypeKind3["ZodOptional"] = "ZodOptional";
  ZodFirstPartyTypeKind3["ZodNullable"] = "ZodNullable";
  ZodFirstPartyTypeKind3["ZodDefault"] = "ZodDefault";
  ZodFirstPartyTypeKind3["ZodCatch"] = "ZodCatch";
  ZodFirstPartyTypeKind3["ZodPromise"] = "ZodPromise";
  ZodFirstPartyTypeKind3["ZodBranded"] = "ZodBranded";
  ZodFirstPartyTypeKind3["ZodPipeline"] = "ZodPipeline";
  ZodFirstPartyTypeKind3["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;

// ../pi-mono/node_modules/@lmstudio/sdk/dist/index.mjs
init_process_shim();
var import_chalk = __toESM(require_source2(), 1);
var import_lms_isomorphic = __toESM(require_browser2(), 1);

// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/index.js
init_process_shim();

// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/Options.js
init_process_shim();
var ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use");
var defaultOptions = {
  name: void 0,
  $refStrategy: "root",
  basePath: ["#"],
  effectStrategy: "input",
  pipeStrategy: "all",
  dateStrategy: "format:date-time",
  mapStrategy: "entries",
  removeAdditionalStrategy: "passthrough",
  allowedAdditionalProperties: true,
  rejectedAdditionalProperties: false,
  definitionPath: "definitions",
  target: "jsonSchema7",
  strictUnions: false,
  definitions: {},
  errorMessages: false,
  markdownDescription: false,
  patternStrategy: "escape",
  applyRegexFlags: false,
  emailStrategy: "format:email",
  base64Strategy: "contentEncoding:base64",
  nameStrategy: "ref",
  openAiAnyTypeName: "OpenAiAnyType"
};
var getDefaultOptions = (options) => typeof options === "string" ? {
  ...defaultOptions,
  name: options
} : {
  ...defaultOptions,
  ...options
};

// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/Refs.js
init_process_shim();
var getRefs = (options) => {
  const _options = getDefaultOptions(options);
  const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;
  return {
    ..._options,
    flags: { hasReferencedOpenAiAnyType: false },
    currentPath,
    propertyPath: void 0,
    seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [
      def._def,
      {
        def: def._def,
        path: [..._options.basePath, _options.definitionPath, name],
        // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
        jsonSchema: void 0
      }
    ]))
  };
};

// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/errorMessages.js
init_process_shim();
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);
}

// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/getRelativePath.js
init_process_shim();
var getRelativePath = (pathA, pathB) => {
  let i7 = 0;
  for (; i7 < pathA.length && i7 < pathB.length; i7++) {
    if (pathA[i7] !== pathB[i7])
      break;
  }
  return [(pathA.length - i7).toString(), ...pathB.slice(i7)].join("/");
};

// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parseDef.js
init_process_shim();

// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/selectParser.js
init_process_shim();

// ../pi-mono/node_modules/zod/v3/index.js
init_process_shim();

// ../pi-mono/node_modules/zod/v3/external.js
init_process_shim();

// ../pi-mono/node_modules/zod/v3/errors.js
init_process_shim();

// ../pi-mono/node_modules/zod/v3/locales/en.js
init_process_shim();

// ../pi-mono/node_modules/zod/v3/ZodError.js
init_process_shim();

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

// ../pi-mono/node_modules/zod/v3/ZodError.js
var ZodIssueCode2 = util2.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 ZodError2 = class _ZodError extends Error {
  get errors() {
    return this.issues;
  }
  constructor(issues) {
    super();
    this.issues = [];
    this.addIssue = (sub2) => {
      this.issues = [...this.issues, sub2];
    };
    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 i7 = 0;
          while (i7 < issue.path.length) {
            const el = issue.path[i7];
            const terminal = i7 === 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];
            i7++;
          }
        }
      }
    };
    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, util2.jsonStringifyReplacer, 2);
  }
  get isEmpty() {
    return this.issues.length === 0;
  }
  flatten(mapper = (issue) => issue.message) {
    const fieldErrors = /* @__PURE__ */ Object.create(null);
    const formErrors = [];
    for (const sub2 of this.issues) {
      if (sub2.path.length > 0) {
        const firstEl = sub2.path[0];
        fieldErrors[firstEl] = fieldErrors[firstEl] || [];
        fieldErrors[firstEl].push(mapper(sub2));
      } else {
        formErrors.push(mapper(sub2));
      }
    }
    return { formErrors, fieldErrors };
  }
  get formErrors() {
    return this.flatten();
  }
};
ZodError2.create = (issues) => {
  const error = new ZodError2(issues);
  return error;
};

// ../pi-mono/node_modules/zod/v3/locales/en.js
var errorMap2 = (issue, _ctx) => {
  let message;
  switch (issue.code) {
    case ZodIssueCode2.invalid_type:
      if (issue.received === ZodParsedType2.undefined) {
        message = "Required";
      } else {
        message = `Expected ${issue.expected}, received ${issue.received}`;
      }
      break;
    case ZodIssueCode2.invalid_literal:
      message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util2.jsonStringifyReplacer)}`;
      break;
    case ZodIssueCode2.unrecognized_keys:
      message = `Unrecognized key(s) in object: ${util2.joinValues(issue.keys, ", ")}`;
      break;
    case ZodIssueCode2.invalid_union:
      message = `Invalid input`;
      break;
    case ZodIssueCode2.invalid_union_discriminator:
      message = `Invalid discriminator value. Expected ${util2.joinValues(issue.options)}`;
      break;
    case ZodIssueCode2.invalid_enum_value:
      message = `Invalid enum value. Expected ${util2.joinValues(issue.options)}, received '${issue.received}'`;
      break;
    case ZodIssueCode2.invalid_arguments:
      message = `Invalid function arguments`;
      break;
    case ZodIssueCode2.invalid_return_type:
      message = `Invalid function return type`;
      break;
    case ZodIssueCode2.invalid_date:
      message = `Invalid date`;
      break;
    case ZodIssueCode2.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 {
          util2.assertNever(issue.validation);
        }
      } else if (issue.validation !== "regex") {
        message = `Invalid ${issue.validation}`;
      } else {
        message = "Invalid";
      }
      break;
    case ZodIssueCode2.too_small:
      if (issue.type === "array")
        message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
      else if (issue.type === "string")
        message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
      else if (issue.type === "number")
        message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
      else if (issue.type === "bigint")
        message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
      else if (issue.type === "date")
        message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
      else
        message = "Invalid input";
      break;
    case ZodIssueCode2.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 ZodIssueCode2.custom:
      message = `Invalid input`;
      break;
    case ZodIssueCode2.invalid_intersection_types:
      message = `Intersection results could not be merged`;
      break;
    case ZodIssueCode2.not_multiple_of:
      message = `Number must be a multiple of ${issue.multipleOf}`;
      break;
    case ZodIssueCode2.not_finite:
      message = "Number must be finite";
      break;
    default:
      message = _ctx.defaultError;
      util2.assertNever(issue);
  }
  return { message };
};
var en_default2 = errorMap2;

// ../pi-mono/node_modules/zod/v3/errors.js
var overrideErrorMap2 = en_default2;
function getErrorMap2() {
  return overrideErrorMap2;
}

// ../pi-mono/node_modules/zod/v3/helpers/parseUtil.js
init_process_shim();
var makeIssue2 = (params) => {
  const { data, path: path6, errorMaps, issueData } = params;
  const fullPath = [...path6, ...issueData.path || []];
  const fullIssue = {
    ...issueData,
    path: fullPath
  };
  if (issueData.message !== void 0) {
    return {
      ...issueData,
      path: fullPath,
      message: issueData.message
    };
  }
  let errorMessage = "";
  const maps = errorMaps.filter((m4) => !!m4).slice().reverse();
  for (const map of maps) {
    errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
  }
  return {
    ...issueData,
    path: fullPath,
    message: errorMessage
  };
};
function addIssueToContext2(ctx, issueData) {
  const overrideMap = getErrorMap2();
  const issue = makeIssue2({
    issueData,
    data: ctx.data,
    path: ctx.path,
    errorMaps: [
      ctx.common.contextualErrorMap,
      // contextual error map is first priority
      ctx.schemaErrorMap,
      // then schema-bound map if available
      overrideMap,
      // then global override map
      overrideMap === en_default2 ? void 0 : en_default2
      // then global default map
    ].filter((x2) => !!x2)
  });
  ctx.common.issues.push(issue);
}
var ParseStatus2 = 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 s6 of results) {
      if (s6.status === "aborted")
        return INVALID2;
      if (s6.status === "dirty")
        status.dirty();
      arrayValue.push(s6.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 INVALID2;
      if (value.status === "aborted")
        return INVALID2;
      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 INVALID2 = Object.freeze({
  status: "aborted"
});
var DIRTY2 = (value) => ({ status: "dirty", value });
var OK2 = (value) => ({ status: "valid", value });
var isAborted2 = (x2) => x2.status === "aborted";
var isDirty2 = (x2) => x2.status === "dirty";
var isValid2 = (x2) => x2.status === "valid";
var isAsync2 = (x2) => typeof Promise !== "undefined" && x2 instanceof Promise;

// ../pi-mono/node_modules/zod/v3/helpers/typeAliases.js
init_process_shim();

// ../pi-mono/node_modules/zod/v3/types.js
init_process_shim();

// ../pi-mono/node_modules/zod/v3/helpers/errorUtil.js
init_process_shim();
var errorUtil2;
(function(errorUtil3) {
  errorUtil3.errToObj = (message) => typeof message === "string" ? { message } : message || {};
  errorUtil3.toString = (message) => typeof message === "string" ? message : message?.message;
})(errorUtil2 || (errorUtil2 = {}));

// ../pi-mono/node_modules/zod/v3/types.js
var ParseInputLazyPath2 = class {
  constructor(parent, value, path6, key) {
    this._cachedPath = [];
    this.parent = parent;
    this.data = value;
    this._path = path6;
    this._key = key;
  }
  get path() {
    if (!this._cachedPath.length) {
      if (Array.isArray(this._key)) {
        this._cachedPath.push(...this._path, ...this._key);
      } else {
        this._cachedPath.push(...this._path, this._key);
      }
    }
    return this._cachedPath;
  }
};
var handleResult2 = (ctx, result) => {
  if (isValid2(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 ZodError2(ctx.common.issues);
        this._error = error;
        return this._error;
      }
    };
  }
};
function processCreateParams2(params) {
  if (!params)
    return {};
  const { errorMap: errorMap3, invalid_type_error, required_error, description } = params;
  if (errorMap3 && (invalid_type_error || required_error)) {
    throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
  }
  if (errorMap3)
    return { errorMap: errorMap3, description };
  const customMap = (iss, ctx) => {
    const { message } = params;
    if (iss.code === "invalid_enum_value") {
      return { message: message ?? ctx.defaultError };
    }
    if (typeof ctx.data === "undefined") {
      return { message: message ?? required_error ?? ctx.defaultError };
    }
    if (iss.code !== "invalid_type")
      return { message: ctx.defaultError };
    return { message: message ?? invalid_type_error ?? ctx.defaultError };
  };
  return { errorMap: customMap, description };
}
var ZodType2 = class {
  get description() {
    return this._def.description;
  }
  _getType(input) {
    return getParsedType2(input.data);
  }
  _getOrReturnCtx(input, ctx) {
    return ctx || {
      common: input.parent.common,
      data: input.data,
      parsedType: getParsedType2(input.data),
      schemaErrorMap: this._def.errorMap,
      path: input.path,
      parent: input.parent
    };
  }
  _processInputParams(input) {
    return {
      status: new ParseStatus2(),
      ctx: {
        common: input.parent.common,
        data: input.data,
        parsedType: getParsedType2(input.data),
        schemaErrorMap: this._def.errorMap,
        path: input.path,
        parent: input.parent
      }
    };
  }
  _parseSync(input) {
    const result = this._parse(input);
    if (isAsync2(result)) {
      throw new Error("Synchronous parse encountered promise.");
    }
    return result;
  }
  _parseAsync(input) {
    const result = this._parse(input);
    return Promise.resolve(result);
  }
  parse(data, params) {
    const result = this.safeParse(data, params);
    if (result.success)
      return result.data;
    throw result.error;
  }
  safeParse(data, params) {
    const ctx = {
      common: {
        issues: [],
        async: params?.async ?? false,
        contextualErrorMap: params?.errorMap
      },
      path: params?.path || [],
      schemaErrorMap: this._def.errorMap,
      parent: null,
      data,
      parsedType: getParsedType2(data)
    };
    const result = this._parseSync({ data, path: ctx.path, parent: ctx });
    return handleResult2(ctx, result);
  }
  "~validate"(data) {
    const ctx = {
      common: {
        issues: [],
        async: !!this["~standard"].async
      },
      path: [],
      schemaErrorMap: this._def.errorMap,
      parent: null,
      data,
      parsedType: getParsedType2(data)
    };
    if (!this["~standard"].async) {
      try {
        const result = this._parseSync({ data, path: [], parent: ctx });
        return isValid2(result) ? {
          value: result.value
        } : {
          issues: ctx.common.issues
        };
      } catch (err) {
        if (err?.message?.toLowerCase()?.includes("encountered")) {
          this["~standard"].async = true;
        }
        ctx.common = {
          issues: [],
          async: true
        };
      }
    }
    return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid2(result) ? {
      value: result.value
    } : {
      issues: ctx.common.issues
    });
  }
  async parseAsync(data, params) {
    const result = await this.safeParseAsync(data, params);
    if (result.success)
      return result.data;
    throw result.error;
  }
  async safeParseAsync(data, params) {
    const ctx = {
      common: {
        issues: [],
        contextualErrorMap: params?.errorMap,
        async: true
      },
      path: params?.path || [],
      schemaErrorMap: this._def.errorMap,
      parent: null,
      data,
      parsedType: getParsedType2(data)
    };
    const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
    const result = await (isAsync2(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
    return handleResult2(ctx, result);
  }
  refine(check, message) {
    const getIssueProperties = (val2) => {
      if (typeof message === "string" || typeof message === "undefined") {
        return { message };
      } else if (typeof message === "function") {
        return message(val2);
      } else {
        return message;
      }
    };
    return this._refinement((val2, ctx) => {
      const result = check(val2);
      const setError = () => ctx.addIssue({
        code: ZodIssueCode2.custom,
        ...getIssueProperties(val2)
      });
      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((val2, ctx) => {
      if (!check(val2)) {
        ctx.addIssue(typeof refinementData === "function" ? refinementData(val2, ctx) : refinementData);
        return false;
      } else {
        return true;
      }
    });
  }
  _refinement(refinement) {
    return new ZodEffects2({
      schema: this,
      typeName: ZodFirstPartyTypeKind2.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 ZodOptional2.create(this, this._def);
  }
  nullable() {
    return ZodNullable2.create(this, this._def);
  }
  nullish() {
    return this.nullable().optional();
  }
  array() {
    return ZodArray2.create(this);
  }
  promise() {
    return ZodPromise2.create(this, this._def);
  }
  or(option) {
    return ZodUnion2.create([this, option], this._def);
  }
  and(incoming) {
    return ZodIntersection2.create(this, incoming, this._def);
  }
  transform(transform) {
    return new ZodEffects2({
      ...processCreateParams2(this._def),
      schema: this,
      typeName: ZodFirstPartyTypeKind2.ZodEffects,
      effect: { type: "transform", transform }
    });
  }
  default(def) {
    const defaultValueFunc = typeof def === "function" ? def : () => def;
    return new ZodDefault2({
      ...processCreateParams2(this._def),
      innerType: this,
      defaultValue: defaultValueFunc,
      typeName: ZodFirstPartyTypeKind2.ZodDefault
    });
  }
  brand() {
    return new ZodBranded2({
      typeName: ZodFirstPartyTypeKind2.ZodBranded,
      type: this,
      ...processCreateParams2(this._def)
    });
  }
  catch(def) {
    const catchValueFunc = typeof def === "function" ? def : () => def;
    return new ZodCatch2({
      ...processCreateParams2(this._def),
      innerType: this,
      catchValue: catchValueFunc,
      typeName: ZodFirstPartyTypeKind2.ZodCatch
    });
  }
  describe(description) {
    const This = this.constructor;
    return new This({
      ...this._def,
      description
    });
  }
  pipe(target) {
    return ZodPipeline2.create(this, target);
  }
  readonly() {
    return ZodReadonly2.create(this);
  }
  isOptional() {
    return this.safeParse(void 0).success;
  }
  isNullable() {
    return this.safeParse(null).success;
  }
};
var cuidRegex2 = /^c[^\s-]{8,}$/i;
var cuid2Regex2 = /^[0-9a-z]+$/;
var ulidRegex2 = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
var uuidRegex2 = /^[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 nanoidRegex2 = /^[a-z0-9_-]{21}$/i;
var jwtRegex2 = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
var durationRegex2 = /^[-+]?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 emailRegex2 = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
var _emojiRegex2 = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
var emojiRegex2;
var ipv4Regex2 = /^(?:(?: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 ipv4CidrRegex2 = /^(?:(?: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 ipv6Regex2 = /^(([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 ipv6CidrRegex2 = /^(([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 base64Regex2 = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
var base64urlRegex2 = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
var dateRegexSource2 = `((\\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 dateRegex2 = new RegExp(`^${dateRegexSource2}$`);
function timeRegexSource2(args) {
  let secondsRegexSource = `[0-5]\\d`;
  if (args.precision) {
    secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
  } else if (args.precision == null) {
    secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
  }
  const secondsQuantifier = args.precision ? "+" : "?";
  return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
}
function timeRegex2(args) {
  return new RegExp(`^${timeRegexSource2(args)}$`);
}
function datetimeRegex2(args) {
  let regex = `${dateRegexSource2}T${timeRegexSource2(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 isValidIP2(ip, version5) {
  if ((version5 === "v4" || !version5) && ipv4Regex2.test(ip)) {
    return true;
  }
  if ((version5 === "v6" || !version5) && ipv6Regex2.test(ip)) {
    return true;
  }
  return false;
}
function isValidJWT2(jwt, alg) {
  if (!jwtRegex2.test(jwt))
    return false;
  try {
    const [header] = jwt.split(".");
    if (!header)
      return false;
    const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
    const decoded = JSON.parse(atob(base64));
    if (typeof decoded !== "object" || decoded === null)
      return false;
    if ("typ" in decoded && decoded?.typ !== "JWT")
      return false;
    if (!decoded.alg)
      return false;
    if (alg && decoded.alg !== alg)
      return false;
    return true;
  } catch {
    return false;
  }
}
function isValidCidr2(ip, version5) {
  if ((version5 === "v4" || !version5) && ipv4CidrRegex2.test(ip)) {
    return true;
  }
  if ((version5 === "v6" || !version5) && ipv6CidrRegex2.test(ip)) {
    return true;
  }
  return false;
}
var ZodString2 = class _ZodString extends ZodType2 {
  _parse(input) {
    if (this._def.coerce) {
      input.data = String(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType2.string) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext2(ctx2, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType2.string,
        received: ctx2.parsedType
      });
      return INVALID2;
    }
    const status = new ParseStatus2();
    let ctx = void 0;
    for (const check of this._def.checks) {
      if (check.kind === "min") {
        if (input.data.length < check.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            code: ZodIssueCode2.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);
          addIssueToContext2(ctx, {
            code: ZodIssueCode2.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) {
            addIssueToContext2(ctx, {
              code: ZodIssueCode2.too_big,
              maximum: check.value,
              type: "string",
              inclusive: true,
              exact: true,
              message: check.message
            });
          } else if (tooSmall) {
            addIssueToContext2(ctx, {
              code: ZodIssueCode2.too_small,
              minimum: check.value,
              type: "string",
              inclusive: true,
              exact: true,
              message: check.message
            });
          }
          status.dirty();
        }
      } else if (check.kind === "email") {
        if (!emailRegex2.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            validation: "email",
            code: ZodIssueCode2.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "emoji") {
        if (!emojiRegex2) {
          emojiRegex2 = new RegExp(_emojiRegex2, "u");
        }
        if (!emojiRegex2.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            validation: "emoji",
            code: ZodIssueCode2.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "uuid") {
        if (!uuidRegex2.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            validation: "uuid",
            code: ZodIssueCode2.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "nanoid") {
        if (!nanoidRegex2.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            validation: "nanoid",
            code: ZodIssueCode2.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "cuid") {
        if (!cuidRegex2.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            validation: "cuid",
            code: ZodIssueCode2.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "cuid2") {
        if (!cuid2Regex2.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            validation: "cuid2",
            code: ZodIssueCode2.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "ulid") {
        if (!ulidRegex2.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            validation: "ulid",
            code: ZodIssueCode2.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "url") {
        try {
          new URL(input.data);
        } catch {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            validation: "url",
            code: ZodIssueCode2.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);
          addIssueToContext2(ctx, {
            validation: "regex",
            code: ZodIssueCode2.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);
          addIssueToContext2(ctx, {
            code: ZodIssueCode2.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);
          addIssueToContext2(ctx, {
            code: ZodIssueCode2.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);
          addIssueToContext2(ctx, {
            code: ZodIssueCode2.invalid_string,
            validation: { endsWith: check.value },
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "datetime") {
        const regex = datetimeRegex2(check);
        if (!regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            code: ZodIssueCode2.invalid_string,
            validation: "datetime",
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "date") {
        const regex = dateRegex2;
        if (!regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            code: ZodIssueCode2.invalid_string,
            validation: "date",
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "time") {
        const regex = timeRegex2(check);
        if (!regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            code: ZodIssueCode2.invalid_string,
            validation: "time",
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "duration") {
        if (!durationRegex2.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            validation: "duration",
            code: ZodIssueCode2.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "ip") {
        if (!isValidIP2(input.data, check.version)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            validation: "ip",
            code: ZodIssueCode2.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "jwt") {
        if (!isValidJWT2(input.data, check.alg)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            validation: "jwt",
            code: ZodIssueCode2.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "cidr") {
        if (!isValidCidr2(input.data, check.version)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            validation: "cidr",
            code: ZodIssueCode2.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "base64") {
        if (!base64Regex2.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            validation: "base64",
            code: ZodIssueCode2.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "base64url") {
        if (!base64urlRegex2.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            validation: "base64url",
            code: ZodIssueCode2.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else {
        util2.assertNever(check);
      }
    }
    return { status: status.value, value: input.data };
  }
  _regex(regex, validation, message) {
    return this.refinement((data) => regex.test(data), {
      validation,
      code: ZodIssueCode2.invalid_string,
      ...errorUtil2.errToObj(message)
    });
  }
  _addCheck(check) {
    return new _ZodString({
      ...this._def,
      checks: [...this._def.checks, check]
    });
  }
  email(message) {
    return this._addCheck({ kind: "email", ...errorUtil2.errToObj(message) });
  }
  url(message) {
    return this._addCheck({ kind: "url", ...errorUtil2.errToObj(message) });
  }
  emoji(message) {
    return this._addCheck({ kind: "emoji", ...errorUtil2.errToObj(message) });
  }
  uuid(message) {
    return this._addCheck({ kind: "uuid", ...errorUtil2.errToObj(message) });
  }
  nanoid(message) {
    return this._addCheck({ kind: "nanoid", ...errorUtil2.errToObj(message) });
  }
  cuid(message) {
    return this._addCheck({ kind: "cuid", ...errorUtil2.errToObj(message) });
  }
  cuid2(message) {
    return this._addCheck({ kind: "cuid2", ...errorUtil2.errToObj(message) });
  }
  ulid(message) {
    return this._addCheck({ kind: "ulid", ...errorUtil2.errToObj(message) });
  }
  base64(message) {
    return this._addCheck({ kind: "base64", ...errorUtil2.errToObj(message) });
  }
  base64url(message) {
    return this._addCheck({
      kind: "base64url",
      ...errorUtil2.errToObj(message)
    });
  }
  jwt(options) {
    return this._addCheck({ kind: "jwt", ...errorUtil2.errToObj(options) });
  }
  ip(options) {
    return this._addCheck({ kind: "ip", ...errorUtil2.errToObj(options) });
  }
  cidr(options) {
    return this._addCheck({ kind: "cidr", ...errorUtil2.errToObj(options) });
  }
  datetime(options) {
    if (typeof options === "string") {
      return this._addCheck({
        kind: "datetime",
        precision: null,
        offset: false,
        local: false,
        message: options
      });
    }
    return this._addCheck({
      kind: "datetime",
      precision: typeof options?.precision === "undefined" ? null : options?.precision,
      offset: options?.offset ?? false,
      local: options?.local ?? false,
      ...errorUtil2.errToObj(options?.message)
    });
  }
  date(message) {
    return this._addCheck({ kind: "date", message });
  }
  time(options) {
    if (typeof options === "string") {
      return this._addCheck({
        kind: "time",
        precision: null,
        message: options
      });
    }
    return this._addCheck({
      kind: "time",
      precision: typeof options?.precision === "undefined" ? null : options?.precision,
      ...errorUtil2.errToObj(options?.message)
    });
  }
  duration(message) {
    return this._addCheck({ kind: "duration", ...errorUtil2.errToObj(message) });
  }
  regex(regex, message) {
    return this._addCheck({
      kind: "regex",
      regex,
      ...errorUtil2.errToObj(message)
    });
  }
  includes(value, options) {
    return this._addCheck({
      kind: "includes",
      value,
      position: options?.position,
      ...errorUtil2.errToObj(options?.message)
    });
  }
  startsWith(value, message) {
    return this._addCheck({
      kind: "startsWith",
      value,
      ...errorUtil2.errToObj(message)
    });
  }
  endsWith(value, message) {
    return this._addCheck({
      kind: "endsWith",
      value,
      ...errorUtil2.errToObj(message)
    });
  }
  min(minLength, message) {
    return this._addCheck({
      kind: "min",
      value: minLength,
      ...errorUtil2.errToObj(message)
    });
  }
  max(maxLength, message) {
    return this._addCheck({
      kind: "max",
      value: maxLength,
      ...errorUtil2.errToObj(message)
    });
  }
  length(len, message) {
    return this._addCheck({
      kind: "length",
      value: len,
      ...errorUtil2.errToObj(message)
    });
  }
  /**
   * Equivalent to `.min(1)`
   */
  nonempty(message) {
    return this.min(1, errorUtil2.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;
  }
};
ZodString2.create = (params) => {
  return new ZodString2({
    checks: [],
    typeName: ZodFirstPartyTypeKind2.ZodString,
    coerce: params?.coerce ?? false,
    ...processCreateParams2(params)
  });
};
function floatSafeRemainder2(val2, step) {
  const valDecCount = (val2.toString().split(".")[1] || "").length;
  const stepDecCount = (step.toString().split(".")[1] || "").length;
  const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
  const valInt = Number.parseInt(val2.toFixed(decCount).replace(".", ""));
  const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
  return valInt % stepInt / 10 ** decCount;
}
var ZodNumber2 = class _ZodNumber extends ZodType2 {
  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 !== ZodParsedType2.number) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext2(ctx2, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType2.number,
        received: ctx2.parsedType
      });
      return INVALID2;
    }
    let ctx = void 0;
    const status = new ParseStatus2();
    for (const check of this._def.checks) {
      if (check.kind === "int") {
        if (!util2.isInteger(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            code: ZodIssueCode2.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);
          addIssueToContext2(ctx, {
            code: ZodIssueCode2.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);
          addIssueToContext2(ctx, {
            code: ZodIssueCode2.too_big,
            maximum: check.value,
            type: "number",
            inclusive: check.inclusive,
            exact: false,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "multipleOf") {
        if (floatSafeRemainder2(input.data, check.value) !== 0) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            code: ZodIssueCode2.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);
          addIssueToContext2(ctx, {
            code: ZodIssueCode2.not_finite,
            message: check.message
          });
          status.dirty();
        }
      } else {
        util2.assertNever(check);
      }
    }
    return { status: status.value, value: input.data };
  }
  gte(value, message) {
    return this.setLimit("min", value, true, errorUtil2.toString(message));
  }
  gt(value, message) {
    return this.setLimit("min", value, false, errorUtil2.toString(message));
  }
  lte(value, message) {
    return this.setLimit("max", value, true, errorUtil2.toString(message));
  }
  lt(value, message) {
    return this.setLimit("max", value, false, errorUtil2.toString(message));
  }
  setLimit(kind, value, inclusive, message) {
    return new _ZodNumber({
      ...this._def,
      checks: [
        ...this._def.checks,
        {
          kind,
          value,
          inclusive,
          message: errorUtil2.toString(message)
        }
      ]
    });
  }
  _addCheck(check) {
    return new _ZodNumber({
      ...this._def,
      checks: [...this._def.checks, check]
    });
  }
  int(message) {
    return this._addCheck({
      kind: "int",
      message: errorUtil2.toString(message)
    });
  }
  positive(message) {
    return this._addCheck({
      kind: "min",
      value: 0,
      inclusive: false,
      message: errorUtil2.toString(message)
    });
  }
  negative(message) {
    return this._addCheck({
      kind: "max",
      value: 0,
      inclusive: false,
      message: errorUtil2.toString(message)
    });
  }
  nonpositive(message) {
    return this._addCheck({
      kind: "max",
      value: 0,
      inclusive: true,
      message: errorUtil2.toString(message)
    });
  }
  nonnegative(message) {
    return this._addCheck({
      kind: "min",
      value: 0,
      inclusive: true,
      message: errorUtil2.toString(message)
    });
  }
  multipleOf(value, message) {
    return this._addCheck({
      kind: "multipleOf",
      value,
      message: errorUtil2.toString(message)
    });
  }
  finite(message) {
    return this._addCheck({
      kind: "finite",
      message: errorUtil2.toString(message)
    });
  }
  safe(message) {
    return this._addCheck({
      kind: "min",
      inclusive: true,
      value: Number.MIN_SAFE_INTEGER,
      message: errorUtil2.toString(message)
    })._addCheck({
      kind: "max",
      inclusive: true,
      value: Number.MAX_SAFE_INTEGER,
      message: errorUtil2.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" && util2.isInteger(ch.value));
  }
  get isFinite() {
    let max = null;
    let min = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
        return true;
      } else if (ch.kind === "min") {
        if (min === null || ch.value > min)
          min = ch.value;
      } else if (ch.kind === "max") {
        if (max === null || ch.value < max)
          max = ch.value;
      }
    }
    return Number.isFinite(min) && Number.isFinite(max);
  }
};
ZodNumber2.create = (params) => {
  return new ZodNumber2({
    checks: [],
    typeName: ZodFirstPartyTypeKind2.ZodNumber,
    coerce: params?.coerce || false,
    ...processCreateParams2(params)
  });
};
var ZodBigInt2 = class _ZodBigInt extends ZodType2 {
  constructor() {
    super(...arguments);
    this.min = this.gte;
    this.max = this.lte;
  }
  _parse(input) {
    if (this._def.coerce) {
      try {
        input.data = BigInt(input.data);
      } catch {
        return this._getInvalidInput(input);
      }
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType2.bigint) {
      return this._getInvalidInput(input);
    }
    let ctx = void 0;
    const status = new ParseStatus2();
    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);
          addIssueToContext2(ctx, {
            code: ZodIssueCode2.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);
          addIssueToContext2(ctx, {
            code: ZodIssueCode2.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);
          addIssueToContext2(ctx, {
            code: ZodIssueCode2.not_multiple_of,
            multipleOf: check.value,
            message: check.message
          });
          status.dirty();
        }
      } else {
        util2.assertNever(check);
      }
    }
    return { status: status.value, value: input.data };
  }
  _getInvalidInput(input) {
    const ctx = this._getOrReturnCtx(input);
    addIssueToContext2(ctx, {
      code: ZodIssueCode2.invalid_type,
      expected: ZodParsedType2.bigint,
      received: ctx.parsedType
    });
    return INVALID2;
  }
  gte(value, message) {
    return this.setLimit("min", value, true, errorUtil2.toString(message));
  }
  gt(value, message) {
    return this.setLimit("min", value, false, errorUtil2.toString(message));
  }
  lte(value, message) {
    return this.setLimit("max", value, true, errorUtil2.toString(message));
  }
  lt(value, message) {
    return this.setLimit("max", value, false, errorUtil2.toString(message));
  }
  setLimit(kind, value, inclusive, message) {
    return new _ZodBigInt({
      ...this._def,
      checks: [
        ...this._def.checks,
        {
          kind,
          value,
          inclusive,
          message: errorUtil2.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: errorUtil2.toString(message)
    });
  }
  negative(message) {
    return this._addCheck({
      kind: "max",
      value: BigInt(0),
      inclusive: false,
      message: errorUtil2.toString(message)
    });
  }
  nonpositive(message) {
    return this._addCheck({
      kind: "max",
      value: BigInt(0),
      inclusive: true,
      message: errorUtil2.toString(message)
    });
  }
  nonnegative(message) {
    return this._addCheck({
      kind: "min",
      value: BigInt(0),
      inclusive: true,
      message: errorUtil2.toString(message)
    });
  }
  multipleOf(value, message) {
    return this._addCheck({
      kind: "multipleOf",
      value,
      message: errorUtil2.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;
  }
};
ZodBigInt2.create = (params) => {
  return new ZodBigInt2({
    checks: [],
    typeName: ZodFirstPartyTypeKind2.ZodBigInt,
    coerce: params?.coerce ?? false,
    ...processCreateParams2(params)
  });
};
var ZodBoolean2 = class extends ZodType2 {
  _parse(input) {
    if (this._def.coerce) {
      input.data = Boolean(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType2.boolean) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext2(ctx, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType2.boolean,
        received: ctx.parsedType
      });
      return INVALID2;
    }
    return OK2(input.data);
  }
};
ZodBoolean2.create = (params) => {
  return new ZodBoolean2({
    typeName: ZodFirstPartyTypeKind2.ZodBoolean,
    coerce: params?.coerce || false,
    ...processCreateParams2(params)
  });
};
var ZodDate2 = class _ZodDate extends ZodType2 {
  _parse(input) {
    if (this._def.coerce) {
      input.data = new Date(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType2.date) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext2(ctx2, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType2.date,
        received: ctx2.parsedType
      });
      return INVALID2;
    }
    if (Number.isNaN(input.data.getTime())) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext2(ctx2, {
        code: ZodIssueCode2.invalid_date
      });
      return INVALID2;
    }
    const status = new ParseStatus2();
    let ctx = void 0;
    for (const check of this._def.checks) {
      if (check.kind === "min") {
        if (input.data.getTime() < check.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            code: ZodIssueCode2.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);
          addIssueToContext2(ctx, {
            code: ZodIssueCode2.too_big,
            message: check.message,
            inclusive: true,
            exact: false,
            maximum: check.value,
            type: "date"
          });
          status.dirty();
        }
      } else {
        util2.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: errorUtil2.toString(message)
    });
  }
  max(maxDate, message) {
    return this._addCheck({
      kind: "max",
      value: maxDate.getTime(),
      message: errorUtil2.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;
  }
};
ZodDate2.create = (params) => {
  return new ZodDate2({
    checks: [],
    coerce: params?.coerce || false,
    typeName: ZodFirstPartyTypeKind2.ZodDate,
    ...processCreateParams2(params)
  });
};
var ZodSymbol2 = class extends ZodType2 {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType2.symbol) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext2(ctx, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType2.symbol,
        received: ctx.parsedType
      });
      return INVALID2;
    }
    return OK2(input.data);
  }
};
ZodSymbol2.create = (params) => {
  return new ZodSymbol2({
    typeName: ZodFirstPartyTypeKind2.ZodSymbol,
    ...processCreateParams2(params)
  });
};
var ZodUndefined2 = class extends ZodType2 {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType2.undefined) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext2(ctx, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType2.undefined,
        received: ctx.parsedType
      });
      return INVALID2;
    }
    return OK2(input.data);
  }
};
ZodUndefined2.create = (params) => {
  return new ZodUndefined2({
    typeName: ZodFirstPartyTypeKind2.ZodUndefined,
    ...processCreateParams2(params)
  });
};
var ZodNull2 = class extends ZodType2 {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType2.null) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext2(ctx, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType2.null,
        received: ctx.parsedType
      });
      return INVALID2;
    }
    return OK2(input.data);
  }
};
ZodNull2.create = (params) => {
  return new ZodNull2({
    typeName: ZodFirstPartyTypeKind2.ZodNull,
    ...processCreateParams2(params)
  });
};
var ZodAny2 = class extends ZodType2 {
  constructor() {
    super(...arguments);
    this._any = true;
  }
  _parse(input) {
    return OK2(input.data);
  }
};
ZodAny2.create = (params) => {
  return new ZodAny2({
    typeName: ZodFirstPartyTypeKind2.ZodAny,
    ...processCreateParams2(params)
  });
};
var ZodUnknown2 = class extends ZodType2 {
  constructor() {
    super(...arguments);
    this._unknown = true;
  }
  _parse(input) {
    return OK2(input.data);
  }
};
ZodUnknown2.create = (params) => {
  return new ZodUnknown2({
    typeName: ZodFirstPartyTypeKind2.ZodUnknown,
    ...processCreateParams2(params)
  });
};
var ZodNever2 = class extends ZodType2 {
  _parse(input) {
    const ctx = this._getOrReturnCtx(input);
    addIssueToContext2(ctx, {
      code: ZodIssueCode2.invalid_type,
      expected: ZodParsedType2.never,
      received: ctx.parsedType
    });
    return INVALID2;
  }
};
ZodNever2.create = (params) => {
  return new ZodNever2({
    typeName: ZodFirstPartyTypeKind2.ZodNever,
    ...processCreateParams2(params)
  });
};
var ZodVoid2 = class extends ZodType2 {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType2.undefined) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext2(ctx, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType2.void,
        received: ctx.parsedType
      });
      return INVALID2;
    }
    return OK2(input.data);
  }
};
ZodVoid2.create = (params) => {
  return new ZodVoid2({
    typeName: ZodFirstPartyTypeKind2.ZodVoid,
    ...processCreateParams2(params)
  });
};
var ZodArray2 = class _ZodArray extends ZodType2 {
  _parse(input) {
    const { ctx, status } = this._processInputParams(input);
    const def = this._def;
    if (ctx.parsedType !== ZodParsedType2.array) {
      addIssueToContext2(ctx, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType2.array,
        received: ctx.parsedType
      });
      return INVALID2;
    }
    if (def.exactLength !== null) {
      const tooBig = ctx.data.length > def.exactLength.value;
      const tooSmall = ctx.data.length < def.exactLength.value;
      if (tooBig || tooSmall) {
        addIssueToContext2(ctx, {
          code: tooBig ? ZodIssueCode2.too_big : ZodIssueCode2.too_small,
          minimum: tooSmall ? def.exactLength.value : void 0,
          maximum: tooBig ? def.exactLength.value : void 0,
          type: "array",
          inclusive: true,
          exact: true,
          message: def.exactLength.message
        });
        status.dirty();
      }
    }
    if (def.minLength !== null) {
      if (ctx.data.length < def.minLength.value) {
        addIssueToContext2(ctx, {
          code: ZodIssueCode2.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) {
        addIssueToContext2(ctx, {
          code: ZodIssueCode2.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, i7) => {
        return def.type._parseAsync(new ParseInputLazyPath2(ctx, item, ctx.path, i7));
      })).then((result2) => {
        return ParseStatus2.mergeArray(status, result2);
      });
    }
    const result = [...ctx.data].map((item, i7) => {
      return def.type._parseSync(new ParseInputLazyPath2(ctx, item, ctx.path, i7));
    });
    return ParseStatus2.mergeArray(status, result);
  }
  get element() {
    return this._def.type;
  }
  min(minLength, message) {
    return new _ZodArray({
      ...this._def,
      minLength: { value: minLength, message: errorUtil2.toString(message) }
    });
  }
  max(maxLength, message) {
    return new _ZodArray({
      ...this._def,
      maxLength: { value: maxLength, message: errorUtil2.toString(message) }
    });
  }
  length(len, message) {
    return new _ZodArray({
      ...this._def,
      exactLength: { value: len, message: errorUtil2.toString(message) }
    });
  }
  nonempty(message) {
    return this.min(1, message);
  }
};
ZodArray2.create = (schema, params) => {
  return new ZodArray2({
    type: schema,
    minLength: null,
    maxLength: null,
    exactLength: null,
    typeName: ZodFirstPartyTypeKind2.ZodArray,
    ...processCreateParams2(params)
  });
};
function deepPartialify2(schema) {
  if (schema instanceof ZodObject2) {
    const newShape = {};
    for (const key in schema.shape) {
      const fieldSchema = schema.shape[key];
      newShape[key] = ZodOptional2.create(deepPartialify2(fieldSchema));
    }
    return new ZodObject2({
      ...schema._def,
      shape: () => newShape
    });
  } else if (schema instanceof ZodArray2) {
    return new ZodArray2({
      ...schema._def,
      type: deepPartialify2(schema.element)
    });
  } else if (schema instanceof ZodOptional2) {
    return ZodOptional2.create(deepPartialify2(schema.unwrap()));
  } else if (schema instanceof ZodNullable2) {
    return ZodNullable2.create(deepPartialify2(schema.unwrap()));
  } else if (schema instanceof ZodTuple2) {
    return ZodTuple2.create(schema.items.map((item) => deepPartialify2(item)));
  } else {
    return schema;
  }
}
var ZodObject2 = class _ZodObject extends ZodType2 {
  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 keys2 = util2.objectKeys(shape);
    this._cached = { shape, keys: keys2 };
    return this._cached;
  }
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType2.object) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext2(ctx2, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType2.object,
        received: ctx2.parsedType
      });
      return INVALID2;
    }
    const { status, ctx } = this._processInputParams(input);
    const { shape, keys: shapeKeys } = this._getCached();
    const extraKeys = [];
    if (!(this._def.catchall instanceof ZodNever2 && 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 ParseInputLazyPath2(ctx, value, ctx.path, key)),
        alwaysSet: key in ctx.data
      });
    }
    if (this._def.catchall instanceof ZodNever2) {
      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) {
          addIssueToContext2(ctx, {
            code: ZodIssueCode2.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 ParseInputLazyPath2(ctx, value, ctx.path, key)
            //, ctx.child(key), value, getParsedType(value)
          ),
          alwaysSet: key in ctx.data
        });
      }
    }
    if (ctx.common.async) {
      return Promise.resolve().then(async () => {
        const syncPairs = [];
        for (const pair of pairs) {
          const key = await pair.key;
          const value = await pair.value;
          syncPairs.push({
            key,
            value,
            alwaysSet: pair.alwaysSet
          });
        }
        return syncPairs;
      }).then((syncPairs) => {
        return ParseStatus2.mergeObjectSync(status, syncPairs);
      });
    } else {
      return ParseStatus2.mergeObjectSync(status, pairs);
    }
  }
  get shape() {
    return this._def.shape();
  }
  strict(message) {
    errorUtil2.errToObj;
    return new _ZodObject({
      ...this._def,
      unknownKeys: "strict",
      ...message !== void 0 ? {
        errorMap: (issue, ctx) => {
          const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
          if (issue.code === "unrecognized_keys")
            return {
              message: errorUtil2.errToObj(message).message ?? defaultError
            };
          return {
            message: defaultError
          };
        }
      } : {}
    });
  }
  strip() {
    return new _ZodObject({
      ...this._def,
      unknownKeys: "strip"
    });
  }
  passthrough() {
    return new _ZodObject({
      ...this._def,
      unknownKeys: "passthrough"
    });
  }
  // const AugmentFactory =
  //   <Def extends ZodObjectDef>(def: Def) =>
  //   <Augmentation extends ZodRawShape>(
  //     augmentation: Augmentation
  //   ): ZodObject<
  //     extendShape<ReturnType<Def["shape"]>, Augmentation>,
  //     Def["unknownKeys"],
  //     Def["catchall"]
  //   > => {
  //     return new ZodObject({
  //       ...def,
  //       shape: () => ({
  //         ...def.shape(),
  //         ...augmentation,
  //       }),
  //     }) as any;
  //   };
  extend(augmentation) {
    return new _ZodObject({
      ...this._def,
      shape: () => ({
        ...this._def.shape(),
        ...augmentation
      })
    });
  }
  /**
   * Prior to zod@1.0.12 there was a bug in the
   * inferred type of merged objects. Please
   * upgrade if you are experiencing issues.
   */
  merge(merging) {
    const merged = new _ZodObject({
      unknownKeys: merging._def.unknownKeys,
      catchall: merging._def.catchall,
      shape: () => ({
        ...this._def.shape(),
        ...merging._def.shape()
      }),
      typeName: ZodFirstPartyTypeKind2.ZodObject
    });
    return merged;
  }
  // merge<
  //   Incoming extends AnyZodObject,
  //   Augmentation extends Incoming["shape"],
  //   NewOutput extends {
  //     [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
  //       ? Augmentation[k]["_output"]
  //       : k extends keyof Output
  //       ? Output[k]
  //       : never;
  //   },
  //   NewInput extends {
  //     [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
  //       ? Augmentation[k]["_input"]
  //       : k extends keyof Input
  //       ? Input[k]
  //       : never;
  //   }
  // >(
  //   merging: Incoming
  // ): ZodObject<
  //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
  //   Incoming["_def"]["unknownKeys"],
  //   Incoming["_def"]["catchall"],
  //   NewOutput,
  //   NewInput
  // > {
  //   const merged: any = new ZodObject({
  //     unknownKeys: merging._def.unknownKeys,
  //     catchall: merging._def.catchall,
  //     shape: () =>
  //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
  //     typeName: ZodFirstPartyTypeKind.ZodObject,
  //   }) as any;
  //   return merged;
  // }
  setKey(key, schema) {
    return this.augment({ [key]: schema });
  }
  // merge<Incoming extends AnyZodObject>(
  //   merging: Incoming
  // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
  // ZodObject<
  //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
  //   Incoming["_def"]["unknownKeys"],
  //   Incoming["_def"]["catchall"]
  // > {
  //   // const mergedShape = objectUtil.mergeShapes(
  //   //   this._def.shape(),
  //   //   merging._def.shape()
  //   // );
  //   const merged: any = new ZodObject({
  //     unknownKeys: merging._def.unknownKeys,
  //     catchall: merging._def.catchall,
  //     shape: () =>
  //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
  //     typeName: ZodFirstPartyTypeKind.ZodObject,
  //   }) as any;
  //   return merged;
  // }
  catchall(index) {
    return new _ZodObject({
      ...this._def,
      catchall: index
    });
  }
  pick(mask) {
    const shape = {};
    for (const key of util2.objectKeys(mask)) {
      if (mask[key] && this.shape[key]) {
        shape[key] = this.shape[key];
      }
    }
    return new _ZodObject({
      ...this._def,
      shape: () => shape
    });
  }
  omit(mask) {
    const shape = {};
    for (const key of util2.objectKeys(this.shape)) {
      if (!mask[key]) {
        shape[key] = this.shape[key];
      }
    }
    return new _ZodObject({
      ...this._def,
      shape: () => shape
    });
  }
  /**
   * @deprecated
   */
  deepPartial() {
    return deepPartialify2(this);
  }
  partial(mask) {
    const newShape = {};
    for (const key of util2.objectKeys(this.shape)) {
      const fieldSchema = this.shape[key];
      if (mask && !mask[key]) {
        newShape[key] = fieldSchema;
      } else {
        newShape[key] = fieldSchema.optional();
      }
    }
    return new _ZodObject({
      ...this._def,
      shape: () => newShape
    });
  }
  required(mask) {
    const newShape = {};
    for (const key of util2.objectKeys(this.shape)) {
      if (mask && !mask[key]) {
        newShape[key] = this.shape[key];
      } else {
        const fieldSchema = this.shape[key];
        let newField = fieldSchema;
        while (newField instanceof ZodOptional2) {
          newField = newField._def.innerType;
        }
        newShape[key] = newField;
      }
    }
    return new _ZodObject({
      ...this._def,
      shape: () => newShape
    });
  }
  keyof() {
    return createZodEnum2(util2.objectKeys(this.shape));
  }
};
ZodObject2.create = (shape, params) => {
  return new ZodObject2({
    shape: () => shape,
    unknownKeys: "strip",
    catchall: ZodNever2.create(),
    typeName: ZodFirstPartyTypeKind2.ZodObject,
    ...processCreateParams2(params)
  });
};
ZodObject2.strictCreate = (shape, params) => {
  return new ZodObject2({
    shape: () => shape,
    unknownKeys: "strict",
    catchall: ZodNever2.create(),
    typeName: ZodFirstPartyTypeKind2.ZodObject,
    ...processCreateParams2(params)
  });
};
ZodObject2.lazycreate = (shape, params) => {
  return new ZodObject2({
    shape,
    unknownKeys: "strip",
    catchall: ZodNever2.create(),
    typeName: ZodFirstPartyTypeKind2.ZodObject,
    ...processCreateParams2(params)
  });
};
var ZodUnion2 = class extends ZodType2 {
  _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 ZodError2(result.ctx.common.issues));
      addIssueToContext2(ctx, {
        code: ZodIssueCode2.invalid_union,
        unionErrors
      });
      return INVALID2;
    }
    if (ctx.common.async) {
      return Promise.all(options.map(async (option) => {
        const childCtx = {
          ...ctx,
          common: {
            ...ctx.common,
            issues: []
          },
          parent: null
        };
        return {
          result: await option._parseAsync({
            data: ctx.data,
            path: ctx.path,
            parent: childCtx
          }),
          ctx: childCtx
        };
      })).then(handleResults);
    } else {
      let dirty = void 0;
      const issues = [];
      for (const option of options) {
        const childCtx = {
          ...ctx,
          common: {
            ...ctx.common,
            issues: []
          },
          parent: null
        };
        const result = option._parseSync({
          data: ctx.data,
          path: ctx.path,
          parent: childCtx
        });
        if (result.status === "valid") {
          return result;
        } else if (result.status === "dirty" && !dirty) {
          dirty = { result, ctx: childCtx };
        }
        if (childCtx.common.issues.length) {
          issues.push(childCtx.common.issues);
        }
      }
      if (dirty) {
        ctx.common.issues.push(...dirty.ctx.common.issues);
        return dirty.result;
      }
      const unionErrors = issues.map((issues2) => new ZodError2(issues2));
      addIssueToContext2(ctx, {
        code: ZodIssueCode2.invalid_union,
        unionErrors
      });
      return INVALID2;
    }
  }
  get options() {
    return this._def.options;
  }
};
ZodUnion2.create = (types2, params) => {
  return new ZodUnion2({
    options: types2,
    typeName: ZodFirstPartyTypeKind2.ZodUnion,
    ...processCreateParams2(params)
  });
};
var getDiscriminator2 = (type) => {
  if (type instanceof ZodLazy2) {
    return getDiscriminator2(type.schema);
  } else if (type instanceof ZodEffects2) {
    return getDiscriminator2(type.innerType());
  } else if (type instanceof ZodLiteral2) {
    return [type.value];
  } else if (type instanceof ZodEnum2) {
    return type.options;
  } else if (type instanceof ZodNativeEnum2) {
    return util2.objectValues(type.enum);
  } else if (type instanceof ZodDefault2) {
    return getDiscriminator2(type._def.innerType);
  } else if (type instanceof ZodUndefined2) {
    return [void 0];
  } else if (type instanceof ZodNull2) {
    return [null];
  } else if (type instanceof ZodOptional2) {
    return [void 0, ...getDiscriminator2(type.unwrap())];
  } else if (type instanceof ZodNullable2) {
    return [null, ...getDiscriminator2(type.unwrap())];
  } else if (type instanceof ZodBranded2) {
    return getDiscriminator2(type.unwrap());
  } else if (type instanceof ZodReadonly2) {
    return getDiscriminator2(type.unwrap());
  } else if (type instanceof ZodCatch2) {
    return getDiscriminator2(type._def.innerType);
  } else {
    return [];
  }
};
var ZodDiscriminatedUnion2 = class _ZodDiscriminatedUnion extends ZodType2 {
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType2.object) {
      addIssueToContext2(ctx, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType2.object,
        received: ctx.parsedType
      });
      return INVALID2;
    }
    const discriminator = this.discriminator;
    const discriminatorValue = ctx.data[discriminator];
    const option = this.optionsMap.get(discriminatorValue);
    if (!option) {
      addIssueToContext2(ctx, {
        code: ZodIssueCode2.invalid_union_discriminator,
        options: Array.from(this.optionsMap.keys()),
        path: [discriminator]
      });
      return INVALID2;
    }
    if (ctx.common.async) {
      return option._parseAsync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      });
    } else {
      return option._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      });
    }
  }
  get discriminator() {
    return this._def.discriminator;
  }
  get options() {
    return this._def.options;
  }
  get optionsMap() {
    return this._def.optionsMap;
  }
  /**
   * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
   * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
   * have a different value for each object in the union.
   * @param discriminator the name of the discriminator property
   * @param types an array of object schemas
   * @param params
   */
  static create(discriminator, options, params) {
    const optionsMap = /* @__PURE__ */ new Map();
    for (const type of options) {
      const discriminatorValues = getDiscriminator2(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: ZodFirstPartyTypeKind2.ZodDiscriminatedUnion,
      discriminator,
      options,
      optionsMap,
      ...processCreateParams2(params)
    });
  }
};
function mergeValues2(a3, b4) {
  const aType = getParsedType2(a3);
  const bType = getParsedType2(b4);
  if (a3 === b4) {
    return { valid: true, data: a3 };
  } else if (aType === ZodParsedType2.object && bType === ZodParsedType2.object) {
    const bKeys = util2.objectKeys(b4);
    const sharedKeys = util2.objectKeys(a3).filter((key) => bKeys.indexOf(key) !== -1);
    const newObj = { ...a3, ...b4 };
    for (const key of sharedKeys) {
      const sharedValue = mergeValues2(a3[key], b4[key]);
      if (!sharedValue.valid) {
        return { valid: false };
      }
      newObj[key] = sharedValue.data;
    }
    return { valid: true, data: newObj };
  } else if (aType === ZodParsedType2.array && bType === ZodParsedType2.array) {
    if (a3.length !== b4.length) {
      return { valid: false };
    }
    const newArray = [];
    for (let index = 0; index < a3.length; index++) {
      const itemA = a3[index];
      const itemB = b4[index];
      const sharedValue = mergeValues2(itemA, itemB);
      if (!sharedValue.valid) {
        return { valid: false };
      }
      newArray.push(sharedValue.data);
    }
    return { valid: true, data: newArray };
  } else if (aType === ZodParsedType2.date && bType === ZodParsedType2.date && +a3 === +b4) {
    return { valid: true, data: a3 };
  } else {
    return { valid: false };
  }
}
var ZodIntersection2 = class extends ZodType2 {
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    const handleParsed = (parsedLeft, parsedRight) => {
      if (isAborted2(parsedLeft) || isAborted2(parsedRight)) {
        return INVALID2;
      }
      const merged = mergeValues2(parsedLeft.value, parsedRight.value);
      if (!merged.valid) {
        addIssueToContext2(ctx, {
          code: ZodIssueCode2.invalid_intersection_types
        });
        return INVALID2;
      }
      if (isDirty2(parsedLeft) || isDirty2(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
      }));
    }
  }
};
ZodIntersection2.create = (left, right, params) => {
  return new ZodIntersection2({
    left,
    right,
    typeName: ZodFirstPartyTypeKind2.ZodIntersection,
    ...processCreateParams2(params)
  });
};
var ZodTuple2 = class _ZodTuple extends ZodType2 {
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType2.array) {
      addIssueToContext2(ctx, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType2.array,
        received: ctx.parsedType
      });
      return INVALID2;
    }
    if (ctx.data.length < this._def.items.length) {
      addIssueToContext2(ctx, {
        code: ZodIssueCode2.too_small,
        minimum: this._def.items.length,
        inclusive: true,
        exact: false,
        type: "array"
      });
      return INVALID2;
    }
    const rest = this._def.rest;
    if (!rest && ctx.data.length > this._def.items.length) {
      addIssueToContext2(ctx, {
        code: ZodIssueCode2.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 ParseInputLazyPath2(ctx, item, ctx.path, itemIndex));
    }).filter((x2) => !!x2);
    if (ctx.common.async) {
      return Promise.all(items).then((results) => {
        return ParseStatus2.mergeArray(status, results);
      });
    } else {
      return ParseStatus2.mergeArray(status, items);
    }
  }
  get items() {
    return this._def.items;
  }
  rest(rest) {
    return new _ZodTuple({
      ...this._def,
      rest
    });
  }
};
ZodTuple2.create = (schemas, params) => {
  if (!Array.isArray(schemas)) {
    throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
  }
  return new ZodTuple2({
    items: schemas,
    typeName: ZodFirstPartyTypeKind2.ZodTuple,
    rest: null,
    ...processCreateParams2(params)
  });
};
var ZodRecord2 = class _ZodRecord extends ZodType2 {
  get keySchema() {
    return this._def.keyType;
  }
  get valueSchema() {
    return this._def.valueType;
  }
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType2.object) {
      addIssueToContext2(ctx, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType2.object,
        received: ctx.parsedType
      });
      return INVALID2;
    }
    const pairs = [];
    const keyType = this._def.keyType;
    const valueType = this._def.valueType;
    for (const key in ctx.data) {
      pairs.push({
        key: keyType._parse(new ParseInputLazyPath2(ctx, key, ctx.path, key)),
        value: valueType._parse(new ParseInputLazyPath2(ctx, ctx.data[key], ctx.path, key)),
        alwaysSet: key in ctx.data
      });
    }
    if (ctx.common.async) {
      return ParseStatus2.mergeObjectAsync(status, pairs);
    } else {
      return ParseStatus2.mergeObjectSync(status, pairs);
    }
  }
  get element() {
    return this._def.valueType;
  }
  static create(first, second, third) {
    if (second instanceof ZodType2) {
      return new _ZodRecord({
        keyType: first,
        valueType: second,
        typeName: ZodFirstPartyTypeKind2.ZodRecord,
        ...processCreateParams2(third)
      });
    }
    return new _ZodRecord({
      keyType: ZodString2.create(),
      valueType: first,
      typeName: ZodFirstPartyTypeKind2.ZodRecord,
      ...processCreateParams2(second)
    });
  }
};
var ZodMap2 = class extends ZodType2 {
  get keySchema() {
    return this._def.keyType;
  }
  get valueSchema() {
    return this._def.valueType;
  }
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType2.map) {
      addIssueToContext2(ctx, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType2.map,
        received: ctx.parsedType
      });
      return INVALID2;
    }
    const keyType = this._def.keyType;
    const valueType = this._def.valueType;
    const pairs = [...ctx.data.entries()].map(([key, value], index) => {
      return {
        key: keyType._parse(new ParseInputLazyPath2(ctx, key, ctx.path, [index, "key"])),
        value: valueType._parse(new ParseInputLazyPath2(ctx, value, ctx.path, [index, "value"]))
      };
    });
    if (ctx.common.async) {
      const finalMap = /* @__PURE__ */ new Map();
      return Promise.resolve().then(async () => {
        for (const pair of pairs) {
          const key = await pair.key;
          const value = await pair.value;
          if (key.status === "aborted" || value.status === "aborted") {
            return INVALID2;
          }
          if (key.status === "dirty" || value.status === "dirty") {
            status.dirty();
          }
          finalMap.set(key.value, value.value);
        }
        return { status: status.value, value: finalMap };
      });
    } else {
      const finalMap = /* @__PURE__ */ new Map();
      for (const pair of pairs) {
        const key = pair.key;
        const value = pair.value;
        if (key.status === "aborted" || value.status === "aborted") {
          return INVALID2;
        }
        if (key.status === "dirty" || value.status === "dirty") {
          status.dirty();
        }
        finalMap.set(key.value, value.value);
      }
      return { status: status.value, value: finalMap };
    }
  }
};
ZodMap2.create = (keyType, valueType, params) => {
  return new ZodMap2({
    valueType,
    keyType,
    typeName: ZodFirstPartyTypeKind2.ZodMap,
    ...processCreateParams2(params)
  });
};
var ZodSet2 = class _ZodSet extends ZodType2 {
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType2.set) {
      addIssueToContext2(ctx, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType2.set,
        received: ctx.parsedType
      });
      return INVALID2;
    }
    const def = this._def;
    if (def.minSize !== null) {
      if (ctx.data.size < def.minSize.value) {
        addIssueToContext2(ctx, {
          code: ZodIssueCode2.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) {
        addIssueToContext2(ctx, {
          code: ZodIssueCode2.too_big,
          maximum: def.maxSize.value,
          type: "set",
          inclusive: true,
          exact: false,
          message: def.maxSize.message
        });
        status.dirty();
      }
    }
    const valueType = this._def.valueType;
    function finalizeSet(elements2) {
      const parsedSet = /* @__PURE__ */ new Set();
      for (const element of elements2) {
        if (element.status === "aborted")
          return INVALID2;
        if (element.status === "dirty")
          status.dirty();
        parsedSet.add(element.value);
      }
      return { status: status.value, value: parsedSet };
    }
    const elements = [...ctx.data.values()].map((item, i7) => valueType._parse(new ParseInputLazyPath2(ctx, item, ctx.path, i7)));
    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: errorUtil2.toString(message) }
    });
  }
  max(maxSize, message) {
    return new _ZodSet({
      ...this._def,
      maxSize: { value: maxSize, message: errorUtil2.toString(message) }
    });
  }
  size(size, message) {
    return this.min(size, message).max(size, message);
  }
  nonempty(message) {
    return this.min(1, message);
  }
};
ZodSet2.create = (valueType, params) => {
  return new ZodSet2({
    valueType,
    minSize: null,
    maxSize: null,
    typeName: ZodFirstPartyTypeKind2.ZodSet,
    ...processCreateParams2(params)
  });
};
var ZodFunction2 = class _ZodFunction extends ZodType2 {
  constructor() {
    super(...arguments);
    this.validate = this.implement;
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType2.function) {
      addIssueToContext2(ctx, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType2.function,
        received: ctx.parsedType
      });
      return INVALID2;
    }
    function makeArgsIssue(args, error) {
      return makeIssue2({
        data: args,
        path: ctx.path,
        errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap2(), en_default2].filter((x2) => !!x2),
        issueData: {
          code: ZodIssueCode2.invalid_arguments,
          argumentsError: error
        }
      });
    }
    function makeReturnsIssue(returns, error) {
      return makeIssue2({
        data: returns,
        path: ctx.path,
        errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap2(), en_default2].filter((x2) => !!x2),
        issueData: {
          code: ZodIssueCode2.invalid_return_type,
          returnTypeError: error
        }
      });
    }
    const params = { errorMap: ctx.common.contextualErrorMap };
    const fn = ctx.data;
    if (this._def.returns instanceof ZodPromise2) {
      const me = this;
      return OK2(async function(...args) {
        const error = new ZodError2([]);
        const parsedArgs = await me._def.args.parseAsync(args, params).catch((e9) => {
          error.addIssue(makeArgsIssue(args, e9));
          throw error;
        });
        const result = await Reflect.apply(fn, this, parsedArgs);
        const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e9) => {
          error.addIssue(makeReturnsIssue(result, e9));
          throw error;
        });
        return parsedReturns;
      });
    } else {
      const me = this;
      return OK2(function(...args) {
        const parsedArgs = me._def.args.safeParse(args, params);
        if (!parsedArgs.success) {
          throw new ZodError2([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 ZodError2([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: ZodTuple2.create(items).rest(ZodUnknown2.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 : ZodTuple2.create([]).rest(ZodUnknown2.create()),
      returns: returns || ZodUnknown2.create(),
      typeName: ZodFirstPartyTypeKind2.ZodFunction,
      ...processCreateParams2(params)
    });
  }
};
var ZodLazy2 = class extends ZodType2 {
  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 });
  }
};
ZodLazy2.create = (getter, params) => {
  return new ZodLazy2({
    getter,
    typeName: ZodFirstPartyTypeKind2.ZodLazy,
    ...processCreateParams2(params)
  });
};
var ZodLiteral2 = class extends ZodType2 {
  _parse(input) {
    if (input.data !== this._def.value) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext2(ctx, {
        received: ctx.data,
        code: ZodIssueCode2.invalid_literal,
        expected: this._def.value
      });
      return INVALID2;
    }
    return { status: "valid", value: input.data };
  }
  get value() {
    return this._def.value;
  }
};
ZodLiteral2.create = (value, params) => {
  return new ZodLiteral2({
    value,
    typeName: ZodFirstPartyTypeKind2.ZodLiteral,
    ...processCreateParams2(params)
  });
};
function createZodEnum2(values2, params) {
  return new ZodEnum2({
    values: values2,
    typeName: ZodFirstPartyTypeKind2.ZodEnum,
    ...processCreateParams2(params)
  });
}
var ZodEnum2 = class _ZodEnum extends ZodType2 {
  _parse(input) {
    if (typeof input.data !== "string") {
      const ctx = this._getOrReturnCtx(input);
      const expectedValues = this._def.values;
      addIssueToContext2(ctx, {
        expected: util2.joinValues(expectedValues),
        received: ctx.parsedType,
        code: ZodIssueCode2.invalid_type
      });
      return INVALID2;
    }
    if (!this._cache) {
      this._cache = new Set(this._def.values);
    }
    if (!this._cache.has(input.data)) {
      const ctx = this._getOrReturnCtx(input);
      const expectedValues = this._def.values;
      addIssueToContext2(ctx, {
        received: ctx.data,
        code: ZodIssueCode2.invalid_enum_value,
        options: expectedValues
      });
      return INVALID2;
    }
    return OK2(input.data);
  }
  get options() {
    return this._def.values;
  }
  get enum() {
    const enumValues = {};
    for (const val2 of this._def.values) {
      enumValues[val2] = val2;
    }
    return enumValues;
  }
  get Values() {
    const enumValues = {};
    for (const val2 of this._def.values) {
      enumValues[val2] = val2;
    }
    return enumValues;
  }
  get Enum() {
    const enumValues = {};
    for (const val2 of this._def.values) {
      enumValues[val2] = val2;
    }
    return enumValues;
  }
  extract(values2, newDef = this._def) {
    return _ZodEnum.create(values2, {
      ...this._def,
      ...newDef
    });
  }
  exclude(values2, newDef = this._def) {
    return _ZodEnum.create(this.options.filter((opt) => !values2.includes(opt)), {
      ...this._def,
      ...newDef
    });
  }
};
ZodEnum2.create = createZodEnum2;
var ZodNativeEnum2 = class extends ZodType2 {
  _parse(input) {
    const nativeEnumValues = util2.getValidEnumValues(this._def.values);
    const ctx = this._getOrReturnCtx(input);
    if (ctx.parsedType !== ZodParsedType2.string && ctx.parsedType !== ZodParsedType2.number) {
      const expectedValues = util2.objectValues(nativeEnumValues);
      addIssueToContext2(ctx, {
        expected: util2.joinValues(expectedValues),
        received: ctx.parsedType,
        code: ZodIssueCode2.invalid_type
      });
      return INVALID2;
    }
    if (!this._cache) {
      this._cache = new Set(util2.getValidEnumValues(this._def.values));
    }
    if (!this._cache.has(input.data)) {
      const expectedValues = util2.objectValues(nativeEnumValues);
      addIssueToContext2(ctx, {
        received: ctx.data,
        code: ZodIssueCode2.invalid_enum_value,
        options: expectedValues
      });
      return INVALID2;
    }
    return OK2(input.data);
  }
  get enum() {
    return this._def.values;
  }
};
ZodNativeEnum2.create = (values2, params) => {
  return new ZodNativeEnum2({
    values: values2,
    typeName: ZodFirstPartyTypeKind2.ZodNativeEnum,
    ...processCreateParams2(params)
  });
};
var ZodPromise2 = class extends ZodType2 {
  unwrap() {
    return this._def.type;
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType2.promise && ctx.common.async === false) {
      addIssueToContext2(ctx, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType2.promise,
        received: ctx.parsedType
      });
      return INVALID2;
    }
    const promisified = ctx.parsedType === ZodParsedType2.promise ? ctx.data : Promise.resolve(ctx.data);
    return OK2(promisified.then((data) => {
      return this._def.type.parseAsync(data, {
        path: ctx.path,
        errorMap: ctx.common.contextualErrorMap
      });
    }));
  }
};
ZodPromise2.create = (schema, params) => {
  return new ZodPromise2({
    type: schema,
    typeName: ZodFirstPartyTypeKind2.ZodPromise,
    ...processCreateParams2(params)
  });
};
var ZodEffects2 = class extends ZodType2 {
  innerType() {
    return this._def.schema;
  }
  sourceType() {
    return this._def.schema._def.typeName === ZodFirstPartyTypeKind2.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) => {
        addIssueToContext2(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 INVALID2;
          const result = await this._def.schema._parseAsync({
            data: processed2,
            path: ctx.path,
            parent: ctx
          });
          if (result.status === "aborted")
            return INVALID2;
          if (result.status === "dirty")
            return DIRTY2(result.value);
          if (status.value === "dirty")
            return DIRTY2(result.value);
          return result;
        });
      } else {
        if (status.value === "aborted")
          return INVALID2;
        const result = this._def.schema._parseSync({
          data: processed,
          path: ctx.path,
          parent: ctx
        });
        if (result.status === "aborted")
          return INVALID2;
        if (result.status === "dirty")
          return DIRTY2(result.value);
        if (status.value === "dirty")
          return DIRTY2(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 inner2 = this._def.schema._parseSync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        });
        if (inner2.status === "aborted")
          return INVALID2;
        if (inner2.status === "dirty")
          status.dirty();
        executeRefinement(inner2.value);
        return { status: status.value, value: inner2.value };
      } else {
        return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner2) => {
          if (inner2.status === "aborted")
            return INVALID2;
          if (inner2.status === "dirty")
            status.dirty();
          return executeRefinement(inner2.value).then(() => {
            return { status: status.value, value: inner2.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 (!isValid2(base))
          return INVALID2;
        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 (!isValid2(base))
            return INVALID2;
          return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
            status: status.value,
            value: result
          }));
        });
      }
    }
    util2.assertNever(effect);
  }
};
ZodEffects2.create = (schema, effect, params) => {
  return new ZodEffects2({
    schema,
    typeName: ZodFirstPartyTypeKind2.ZodEffects,
    effect,
    ...processCreateParams2(params)
  });
};
ZodEffects2.createWithPreprocess = (preprocess, schema, params) => {
  return new ZodEffects2({
    schema,
    effect: { type: "preprocess", transform: preprocess },
    typeName: ZodFirstPartyTypeKind2.ZodEffects,
    ...processCreateParams2(params)
  });
};
var ZodOptional2 = class extends ZodType2 {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType === ZodParsedType2.undefined) {
      return OK2(void 0);
    }
    return this._def.innerType._parse(input);
  }
  unwrap() {
    return this._def.innerType;
  }
};
ZodOptional2.create = (type, params) => {
  return new ZodOptional2({
    innerType: type,
    typeName: ZodFirstPartyTypeKind2.ZodOptional,
    ...processCreateParams2(params)
  });
};
var ZodNullable2 = class extends ZodType2 {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType === ZodParsedType2.null) {
      return OK2(null);
    }
    return this._def.innerType._parse(input);
  }
  unwrap() {
    return this._def.innerType;
  }
};
ZodNullable2.create = (type, params) => {
  return new ZodNullable2({
    innerType: type,
    typeName: ZodFirstPartyTypeKind2.ZodNullable,
    ...processCreateParams2(params)
  });
};
var ZodDefault2 = class extends ZodType2 {
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    let data = ctx.data;
    if (ctx.parsedType === ZodParsedType2.undefined) {
      data = this._def.defaultValue();
    }
    return this._def.innerType._parse({
      data,
      path: ctx.path,
      parent: ctx
    });
  }
  removeDefault() {
    return this._def.innerType;
  }
};
ZodDefault2.create = (type, params) => {
  return new ZodDefault2({
    innerType: type,
    typeName: ZodFirstPartyTypeKind2.ZodDefault,
    defaultValue: typeof params.default === "function" ? params.default : () => params.default,
    ...processCreateParams2(params)
  });
};
var ZodCatch2 = class extends ZodType2 {
  _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 (isAsync2(result)) {
      return result.then((result2) => {
        return {
          status: "valid",
          value: result2.status === "valid" ? result2.value : this._def.catchValue({
            get error() {
              return new ZodError2(newCtx.common.issues);
            },
            input: newCtx.data
          })
        };
      });
    } else {
      return {
        status: "valid",
        value: result.status === "valid" ? result.value : this._def.catchValue({
          get error() {
            return new ZodError2(newCtx.common.issues);
          },
          input: newCtx.data
        })
      };
    }
  }
  removeCatch() {
    return this._def.innerType;
  }
};
ZodCatch2.create = (type, params) => {
  return new ZodCatch2({
    innerType: type,
    typeName: ZodFirstPartyTypeKind2.ZodCatch,
    catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
    ...processCreateParams2(params)
  });
};
var ZodNaN2 = class extends ZodType2 {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType2.nan) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext2(ctx, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType2.nan,
        received: ctx.parsedType
      });
      return INVALID2;
    }
    return { status: "valid", value: input.data };
  }
};
ZodNaN2.create = (params) => {
  return new ZodNaN2({
    typeName: ZodFirstPartyTypeKind2.ZodNaN,
    ...processCreateParams2(params)
  });
};
var BRAND2 = Symbol("zod_brand");
var ZodBranded2 = class extends ZodType2 {
  _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;
  }
};
var ZodPipeline2 = class _ZodPipeline extends ZodType2 {
  _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 INVALID2;
        if (inResult.status === "dirty") {
          status.dirty();
          return DIRTY2(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 INVALID2;
      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(a3, b4) {
    return new _ZodPipeline({
      in: a3,
      out: b4,
      typeName: ZodFirstPartyTypeKind2.ZodPipeline
    });
  }
};
var ZodReadonly2 = class extends ZodType2 {
  _parse(input) {
    const result = this._def.innerType._parse(input);
    const freeze2 = (data) => {
      if (isValid2(data)) {
        data.value = Object.freeze(data.value);
      }
      return data;
    };
    return isAsync2(result) ? result.then((data) => freeze2(data)) : freeze2(result);
  }
  unwrap() {
    return this._def.innerType;
  }
};
ZodReadonly2.create = (type, params) => {
  return new ZodReadonly2({
    innerType: type,
    typeName: ZodFirstPartyTypeKind2.ZodReadonly,
    ...processCreateParams2(params)
  });
};
var late2 = {
  object: ZodObject2.lazycreate
};
var ZodFirstPartyTypeKind2;
(function(ZodFirstPartyTypeKind3) {
  ZodFirstPartyTypeKind3["ZodString"] = "ZodString";
  ZodFirstPartyTypeKind3["ZodNumber"] = "ZodNumber";
  ZodFirstPartyTypeKind3["ZodNaN"] = "ZodNaN";
  ZodFirstPartyTypeKind3["ZodBigInt"] = "ZodBigInt";
  ZodFirstPartyTypeKind3["ZodBoolean"] = "ZodBoolean";
  ZodFirstPartyTypeKind3["ZodDate"] = "ZodDate";
  ZodFirstPartyTypeKind3["ZodSymbol"] = "ZodSymbol";
  ZodFirstPartyTypeKind3["ZodUndefined"] = "ZodUndefined";
  ZodFirstPartyTypeKind3["ZodNull"] = "ZodNull";
  ZodFirstPartyTypeKind3["ZodAny"] = "ZodAny";
  ZodFirstPartyTypeKind3["ZodUnknown"] = "ZodUnknown";
  ZodFirstPartyTypeKind3["ZodNever"] = "ZodNever";
  ZodFirstPartyTypeKind3["ZodVoid"] = "ZodVoid";
  ZodFirstPartyTypeKind3["ZodArray"] = "ZodArray";
  ZodFirstPartyTypeKind3["ZodObject"] = "ZodObject";
  ZodFirstPartyTypeKind3["ZodUnion"] = "ZodUnion";
  ZodFirstPartyTypeKind3["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
  ZodFirstPartyTypeKind3["ZodIntersection"] = "ZodIntersection";
  ZodFirstPartyTypeKind3["ZodTuple"] = "ZodTuple";
  ZodFirstPartyTypeKind3["ZodRecord"] = "ZodRecord";
  ZodFirstPartyTypeKind3["ZodMap"] = "ZodMap";
  ZodFirstPartyTypeKind3["ZodSet"] = "ZodSet";
  ZodFirstPartyTypeKind3["ZodFunction"] = "ZodFunction";
  ZodFirstPartyTypeKind3["ZodLazy"] = "ZodLazy";
  ZodFirstPartyTypeKind3["ZodLiteral"] = "ZodLiteral";
  ZodFirstPartyTypeKind3["ZodEnum"] = "ZodEnum";
  ZodFirstPartyTypeKind3["ZodEffects"] = "ZodEffects";
  ZodFirstPartyTypeKind3["ZodNativeEnum"] = "ZodNativeEnum";
  ZodFirstPartyTypeKind3["ZodOptional"] = "ZodOptional";
  ZodFirstPartyTypeKind3["ZodNullable"] = "ZodNullable";
  ZodFirstPartyTypeKind3["ZodDefault"] = "ZodDefault";
  ZodFirstPartyTypeKind3["ZodCatch"] = "ZodCatch";
  ZodFirstPartyTypeKind3["ZodPromise"] = "ZodPromise";
  ZodFirstPartyTypeKind3["ZodBranded"] = "ZodBranded";
  ZodFirstPartyTypeKind3["ZodPipeline"] = "ZodPipeline";
  ZodFirstPartyTypeKind3["ZodReadonly"] = "ZodReadonly";
})(ZodFirstPartyTypeKind2 || (ZodFirstPartyTypeKind2 = {}));
var stringType2 = ZodString2.create;
var numberType2 = ZodNumber2.create;
var nanType2 = ZodNaN2.create;
var bigIntType2 = ZodBigInt2.create;
var booleanType2 = ZodBoolean2.create;
var dateType2 = ZodDate2.create;
var symbolType2 = ZodSymbol2.create;
var undefinedType2 = ZodUndefined2.create;
var nullType2 = ZodNull2.create;
var anyType2 = ZodAny2.create;
var unknownType2 = ZodUnknown2.create;
var neverType2 = ZodNever2.create;
var voidType2 = ZodVoid2.create;
var arrayType2 = ZodArray2.create;
var objectType2 = ZodObject2.create;
var strictObjectType2 = ZodObject2.strictCreate;
var unionType2 = ZodUnion2.create;
var discriminatedUnionType2 = ZodDiscriminatedUnion2.create;
var intersectionType2 = ZodIntersection2.create;
var tupleType2 = ZodTuple2.create;
var recordType2 = ZodRecord2.create;
var mapType2 = ZodMap2.create;
var setType2 = ZodSet2.create;
var functionType2 = ZodFunction2.create;
var lazyType2 = ZodLazy2.create;
var literalType2 = ZodLiteral2.create;
var enumType2 = ZodEnum2.create;
var nativeEnumType2 = ZodNativeEnum2.create;
var promiseType2 = ZodPromise2.create;
var effectsType2 = ZodEffects2.create;
var optionalType2 = ZodOptional2.create;
var nullableType2 = ZodNullable2.create;
var preprocessType2 = ZodEffects2.createWithPreprocess;
var pipelineType2 = ZodPipeline2.create;

// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/any.js
init_process_shim();
function parseAnyDef(refs) {
  if (refs.target !== "openAi") {
    return {};
  }
  const anyDefinitionPath = [
    ...refs.basePath,
    refs.definitionPath,
    refs.openAiAnyTypeName
  ];
  refs.flags.hasReferencedOpenAiAnyType = true;
  return {
    $ref: refs.$refStrategy === "relative" ? getRelativePath(anyDefinitionPath, refs.currentPath) : anyDefinitionPath.join("/")
  };
}

// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/array.js
init_process_shim();
function parseArrayDef(def, refs) {
  const res = {
    type: "array"
  };
  if (def.type?._def && def.type?._def?.typeName !== ZodFirstPartyTypeKind2.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;
}

// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js
init_process_shim();
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;
}

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

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

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

// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/date.js
init_process_shim();
function parseDateDef(def, refs, overrideDateStrategy) {
  const strategy = overrideDateStrategy ?? refs.dateStrategy;
  if (Array.isArray(strategy)) {
    return {
      anyOf: strategy.map((item, i7) => 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,
          // This is in milliseconds
          check.message,
          refs
        );
        break;
      case "max":
        setResponseValueAndErrors(
          res,
          "maximum",
          check.value,
          // This is in milliseconds
          check.message,
          refs
        );
        break;
    }
  }
  return res;
};

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

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

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

// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js
init_process_shim();
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((x2) => !!x2);
  let unevaluatedProperties = refs.target === "jsonSchema2019-09" ? { unevaluatedProperties: false } : void 0;
  const mergedAllOf = [];
  allOf.forEach((schema) => {
    if (isJsonSchema7AllOfType(schema)) {
      mergedAllOf.push(...schema.allOf);
      if (schema.unevaluatedProperties === void 0) {
        unevaluatedProperties = void 0;
      }
    } else {
      let nestedSchema = schema;
      if ("additionalProperties" in schema && schema.additionalProperties === false) {
        const { additionalProperties, ...rest } = schema;
        nestedSchema = rest;
      } else {
        unevaluatedProperties = void 0;
      }
      mergedAllOf.push(nestedSchema);
    }
  });
  return mergedAllOf.length ? {
    allOf: mergedAllOf,
    ...unevaluatedProperties
  } : void 0;
}

// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/literal.js
init_process_shim();
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
  };
}

// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/map.js
init_process_shim();

// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/record.js
init_process_shim();

// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/string.js
init_process_shim();
var emojiRegex3 = void 0;
var zodPatterns = {
  /**
   * `c` was changed to `[cC]` to replicate /i flag
   */
  cuid: /^[cC][^\s-]{8,}$/,
  cuid2: /^[0-9a-z]+$/,
  ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
  /**
   * `a-z` was added to replicate /i flag
   */
  email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
  /**
   * Constructed a valid Unicode RegExp
   *
   * Lazily instantiate since this type of regex isn't supported
   * in all envs (e.g. React Native).
   *
   * See:
   * https://github.com/colinhacks/zod/issues/2433
   * Fix in Zod:
   * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
   */
  emoji: () => {
    if (emojiRegex3 === void 0) {
      emojiRegex3 = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u");
    }
    return emojiRegex3;
  },
  /**
   * Unused
   */
  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}$/,
  /**
   * Unused
   */
  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])$/,
  /**
   * Unused
   */
  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:
          /* @__PURE__ */ ((_3) => {
          })(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 i7 = 0; i7 < source.length; i7++) {
    if (!ALPHA_NUMERIC.has(source[i7])) {
      result += "\\";
    }
    result += source[i7];
  }
  return result;
}
function addFormat(schema, value, message, refs) {
  if (schema.format || schema.anyOf?.some((x2) => x2.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((x2) => x2.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")
    // `.` matches newlines
  };
  const source = flags.i ? regex.source.toLowerCase() : regex.source;
  let pattern = "";
  let isEscaped = false;
  let inCharGroup = false;
  let inCharRange = false;
  for (let i7 = 0; i7 < source.length; i7++) {
    if (isEscaped) {
      pattern += source[i7];
      isEscaped = false;
      continue;
    }
    if (flags.i) {
      if (inCharGroup) {
        if (source[i7].match(/[a-z]/)) {
          if (inCharRange) {
            pattern += source[i7];
            pattern += `${source[i7 - 2]}-${source[i7]}`.toUpperCase();
            inCharRange = false;
          } else if (source[i7 + 1] === "-" && source[i7 + 2]?.match(/[a-z]/)) {
            pattern += source[i7];
            inCharRange = true;
          } else {
            pattern += `${source[i7]}${source[i7].toUpperCase()}`;
          }
          continue;
        }
      } else if (source[i7].match(/[a-z]/)) {
        pattern += `[${source[i7]}${source[i7].toUpperCase()}]`;
        continue;
      }
    }
    if (flags.m) {
      if (source[i7] === "^") {
        pattern += `(^|(?<=[\r
]))`;
        continue;
      } else if (source[i7] === "$") {
        pattern += `($|(?=[\r
]))`;
        continue;
      }
    }
    if (flags.s && source[i7] === ".") {
      pattern += inCharGroup ? `${source[i7]}\r
` : `[${source[i7]}\r
]`;
      continue;
    }
    pattern += source[i7];
    if (source[i7] === "\\") {
      isEscaped = true;
    } else if (inCharGroup && source[i7] === "]") {
      inCharGroup = false;
    } else if (!inCharGroup && source[i7] === "[") {
      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;
}

// ../pi-mono/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 === ZodFirstPartyTypeKind2.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]
        }) ?? parseAnyDef(refs)
      }), {}),
      additionalProperties: refs.rejectedAdditionalProperties
    };
  }
  const schema = {
    type: "object",
    additionalProperties: parseDef(def.valueType._def, {
      ...refs,
      currentPath: [...refs.currentPath, "additionalProperties"]
    }) ?? refs.allowedAdditionalProperties
  };
  if (refs.target === "openApi3") {
    return schema;
  }
  if (def.keyType?._def.typeName === ZodFirstPartyTypeKind2.ZodString && def.keyType._def.checks?.length) {
    const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
    return {
      ...schema,
      propertyNames: keyType
    };
  } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind2.ZodEnum) {
    return {
      ...schema,
      propertyNames: {
        enum: def.keyType._def.values
      }
    };
  } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind2.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind2.ZodString && def.keyType._def.type._def.checks?.length) {
    const { type, ...keyType } = parseBrandedDef(def.keyType._def, refs);
    return {
      ...schema,
      propertyNames: keyType
    };
  }
  return schema;
}

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

// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js
init_process_shim();
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((values2) => typeof values2)));
  return {
    type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
    enum: actualValues
  };
}

// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/never.js
init_process_shim();
function parseNeverDef(refs) {
  return refs.target === "openAi" ? void 0 : {
    not: parseAnyDef({
      ...refs,
      currentPath: [...refs.currentPath, "not"]
    })
  };
}

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

// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js
init_process_shim();

// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/union.js
init_process_shim();
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((x2) => x2._def.typeName in primitiveMappings && (!x2._def.checks || !x2._def.checks.length))) {
    const types2 = options.reduce((types3, x2) => {
      const type = primitiveMappings[x2._def.typeName];
      return type && !types3.includes(type) ? [...types3, type] : types3;
    }, []);
    return {
      type: types2.length > 1 ? types2 : types2[0]
    };
  } else if (options.every((x2) => x2._def.typeName === "ZodLiteral" && !x2.description)) {
    const types2 = options.reduce((acc, x2) => {
      const type = typeof x2._def.value;
      switch (type) {
        case "string":
        case "number":
        case "boolean":
          return [...acc, type];
        case "bigint":
          return [...acc, "integer"];
        case "object":
          if (x2._def.value === null)
            return [...acc, "null"];
        case "symbol":
        case "undefined":
        case "function":
        default:
          return acc;
      }
    }, []);
    if (types2.length === options.length) {
      const uniqueTypes = types2.filter((x2, i7, a3) => a3.indexOf(x2) === i7);
      return {
        type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
        enum: options.reduce((acc, x2) => {
          return acc.includes(x2._def.value) ? acc : [...acc, x2._def.value];
        }, [])
      };
    }
  } else if (options.every((x2) => x2._def.typeName === "ZodEnum")) {
    return {
      type: "string",
      enum: options.reduce((acc, x2) => [
        ...acc,
        ...x2._def.values.filter((x3) => !acc.includes(x3))
      ], [])
    };
  }
  return asAnyOf(def, refs);
}
var asAnyOf = (def, refs) => {
  const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x2, i7) => parseDef(x2._def, {
    ...refs,
    currentPath: [...refs.currentPath, "anyOf", `${i7}`]
  })).filter((x2) => !!x2 && (!refs.strictUnions || typeof x2 === "object" && Object.keys(x2).length > 0));
  return anyOf.length ? { anyOf } : void 0;
};

// ../pi-mono/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" }] };
}

// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/number.js
init_process_shim();
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;
}

// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/object.js
init_process_shim();
function parseObjectDef(def, refs) {
  const forceOptionalIntoNullable = refs.target === "openAi";
  const result = {
    type: "object",
    properties: {}
  };
  const required = [];
  const shape = def.shape();
  for (const propName in shape) {
    let propDef = shape[propName];
    if (propDef === void 0 || propDef._def === void 0) {
      continue;
    }
    let propOptional = safeIsOptional(propDef);
    if (propOptional && forceOptionalIntoNullable) {
      if (propDef._def.typeName === "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 === void 0) {
      continue;
    }
    result.properties[propName] = parsedDef;
    if (!propOptional) {
      required.push(propName);
    }
  }
  if (required.length) {
    result.required = required;
  }
  const additionalProperties = decideAdditionalProperties(def, refs);
  if (additionalProperties !== void 0) {
    result.additionalProperties = additionalProperties;
  }
  return result;
}
function decideAdditionalProperties(def, refs) {
  if (def.catchall._def.typeName !== "ZodNever") {
    return parseDef(def.catchall._def, {
      ...refs,
      currentPath: [...refs.currentPath, "additionalProperties"]
    });
  }
  switch (def.unknownKeys) {
    case "passthrough":
      return refs.allowedAdditionalProperties;
    case "strict":
      return refs.rejectedAdditionalProperties;
    case "strip":
      return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
  }
}
function safeIsOptional(schema) {
  try {
    return schema.isOptional();
  } catch {
    return true;
  }
}

// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/optional.js
init_process_shim();
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: parseAnyDef(refs)
      },
      innerSchema
    ]
  } : parseAnyDef(refs);
};

// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js
init_process_shim();
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 a3 = parseDef(def.in._def, {
    ...refs,
    currentPath: [...refs.currentPath, "allOf", "0"]
  });
  const b4 = parseDef(def.out._def, {
    ...refs,
    currentPath: [...refs.currentPath, "allOf", a3 ? "1" : "0"]
  });
  return {
    allOf: [a3, b4].filter((x2) => x2 !== void 0)
  };
};

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

// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/set.js
init_process_shim();
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;
}

// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js
init_process_shim();
function parseTupleDef(def, refs) {
  if (def.rest) {
    return {
      type: "array",
      minItems: def.items.length,
      items: def.items.map((x2, i7) => parseDef(x2._def, {
        ...refs,
        currentPath: [...refs.currentPath, "items", `${i7}`]
      })).reduce((acc, x2) => x2 === void 0 ? acc : [...acc, x2], []),
      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((x2, i7) => parseDef(x2._def, {
        ...refs,
        currentPath: [...refs.currentPath, "items", `${i7}`]
      })).reduce((acc, x2) => x2 === void 0 ? acc : [...acc, x2], [])
    };
  }
}

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

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

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

// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/selectParser.js
var selectParser = (def, typeName, refs) => {
  switch (typeName) {
    case ZodFirstPartyTypeKind2.ZodString:
      return parseStringDef(def, refs);
    case ZodFirstPartyTypeKind2.ZodNumber:
      return parseNumberDef(def, refs);
    case ZodFirstPartyTypeKind2.ZodObject:
      return parseObjectDef(def, refs);
    case ZodFirstPartyTypeKind2.ZodBigInt:
      return parseBigintDef(def, refs);
    case ZodFirstPartyTypeKind2.ZodBoolean:
      return parseBooleanDef();
    case ZodFirstPartyTypeKind2.ZodDate:
      return parseDateDef(def, refs);
    case ZodFirstPartyTypeKind2.ZodUndefined:
      return parseUndefinedDef(refs);
    case ZodFirstPartyTypeKind2.ZodNull:
      return parseNullDef(refs);
    case ZodFirstPartyTypeKind2.ZodArray:
      return parseArrayDef(def, refs);
    case ZodFirstPartyTypeKind2.ZodUnion:
    case ZodFirstPartyTypeKind2.ZodDiscriminatedUnion:
      return parseUnionDef(def, refs);
    case ZodFirstPartyTypeKind2.ZodIntersection:
      return parseIntersectionDef(def, refs);
    case ZodFirstPartyTypeKind2.ZodTuple:
      return parseTupleDef(def, refs);
    case ZodFirstPartyTypeKind2.ZodRecord:
      return parseRecordDef(def, refs);
    case ZodFirstPartyTypeKind2.ZodLiteral:
      return parseLiteralDef(def, refs);
    case ZodFirstPartyTypeKind2.ZodEnum:
      return parseEnumDef(def);
    case ZodFirstPartyTypeKind2.ZodNativeEnum:
      return parseNativeEnumDef(def);
    case ZodFirstPartyTypeKind2.ZodNullable:
      return parseNullableDef(def, refs);
    case ZodFirstPartyTypeKind2.ZodOptional:
      return parseOptionalDef(def, refs);
    case ZodFirstPartyTypeKind2.ZodMap:
      return parseMapDef(def, refs);
    case ZodFirstPartyTypeKind2.ZodSet:
      return parseSetDef(def, refs);
    case ZodFirstPartyTypeKind2.ZodLazy:
      return () => def.getter()._def;
    case ZodFirstPartyTypeKind2.ZodPromise:
      return parsePromiseDef(def, refs);
    case ZodFirstPartyTypeKind2.ZodNaN:
    case ZodFirstPartyTypeKind2.ZodNever:
      return parseNeverDef(refs);
    case ZodFirstPartyTypeKind2.ZodEffects:
      return parseEffectsDef(def, refs);
    case ZodFirstPartyTypeKind2.ZodAny:
      return parseAnyDef(refs);
    case ZodFirstPartyTypeKind2.ZodUnknown:
      return parseUnknownDef(refs);
    case ZodFirstPartyTypeKind2.ZodDefault:
      return parseDefaultDef(def, refs);
    case ZodFirstPartyTypeKind2.ZodBranded:
      return parseBrandedDef(def, refs);
    case ZodFirstPartyTypeKind2.ZodReadonly:
      return parseReadonlyDef(def, refs);
    case ZodFirstPartyTypeKind2.ZodCatch:
      return parseCatchDef(def, refs);
    case ZodFirstPartyTypeKind2.ZodPipeline:
      return parsePipelineDef(def, refs);
    case ZodFirstPartyTypeKind2.ZodFunction:
    case ZodFirstPartyTypeKind2.ZodVoid:
    case ZodFirstPartyTypeKind2.ZodSymbol:
      return void 0;
    default:
      return /* @__PURE__ */ ((_3) => void 0)(typeName);
  }
};

// ../pi-mono/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 !== void 0) {
      return seenSchema;
    }
  }
  const newItem = { def, path: refs.currentPath, jsonSchema: void 0 };
  refs.seen.set(def, newItem);
  const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);
  const jsonSchema = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
  if (jsonSchema) {
    addMeta(def, refs, jsonSchema);
  }
  if (refs.postProcess) {
    const postProcessResult = refs.postProcess(jsonSchema, def, refs);
    newItem.jsonSchema = jsonSchema;
    return postProcessResult;
  }
  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 parseAnyDef(refs);
      }
      return refs.$refStrategy === "seen" ? parseAnyDef(refs) : void 0;
    }
  }
};
var addMeta = (def, refs, jsonSchema) => {
  if (def.description) {
    jsonSchema.description = def.description;
    if (refs.markdownDescription) {
      jsonSchema.markdownDescription = def.description;
    }
  }
  return jsonSchema;
};

// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parseTypes.js
init_process_shim();

// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js
init_process_shim();
var zodToJsonSchema = (schema, options) => {
  const refs = getRefs(options);
  let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name2, schema2]) => ({
    ...acc,
    [name2]: parseDef(schema2._def, {
      ...refs,
      currentPath: [...refs.basePath, refs.definitionPath, name2]
    }, true) ?? parseAnyDef(refs)
  }), {}) : void 0;
  const name = typeof options === "string" ? options : options?.nameStrategy === "title" ? void 0 : options?.name;
  const main2 = parseDef(schema._def, name === void 0 ? refs : {
    ...refs,
    currentPath: [...refs.basePath, refs.definitionPath, name]
  }, false) ?? parseAnyDef(refs);
  const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
  if (title !== void 0) {
    main2.title = title;
  }
  if (refs.flags.hasReferencedOpenAiAnyType) {
    if (!definitions) {
      definitions = {};
    }
    if (!definitions[refs.openAiAnyTypeName]) {
      definitions[refs.openAiAnyTypeName] = {
        // Skipping "object" as no properties can be defined and additionalProperties must be "false"
        type: ["string", "number", "integer", "boolean", "array", "null"],
        items: {
          $ref: refs.$refStrategy === "relative" ? "1" : [
            ...refs.basePath,
            refs.definitionPath,
            refs.openAiAnyTypeName
          ].join("/")
        }
      };
    }
  }
  const combined = name === void 0 ? definitions ? {
    ...main2,
    [refs.definitionPath]: definitions
  } : main2 : {
    $ref: [
      ...refs.$refStrategy === "relative" ? [] : refs.basePath,
      refs.definitionPath,
      name
    ].join("/"),
    [refs.definitionPath]: {
      ...definitions,
      [name]: main2
    }
  };
  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;
};

// ../pi-mono/node_modules/@lmstudio/sdk/dist/index.mjs
function isSignalLike(value) {
  return typeof value === "object" && value !== null && typeof value.get === "function" && typeof value.subscribe === "function";
}
var Subscribable = class {
  subscribeWithCleaner(cleaner, listener) {
    const unsubscribe = this.subscribe(listener);
    cleaner.register(unsubscribe);
  }
  subscribeOnce(listener) {
    const unsubscribe = this.subscribe((data) => {
      unsubscribe();
      listener(data);
    });
    return unsubscribe;
  }
  subscribeOnceWithCleaner(cleaner, listener) {
    const unsubscribe = this.subscribeOnce(listener);
    cleaner.register(unsubscribe);
  }
  derive(deriver, outputEqualsPredicate = (a3, b4) => a3 === b4) {
    if (isSignalLike(this)) {
      return LazySignal.deriveFrom([this], deriver);
    }
    const thisWithGetter = this;
    if (thisWithGetter.get !== void 0) {
      const initialValue = thisWithGetter.get();
      if (initialValue === LazySignal.NOT_AVAILABLE) {
        return LazySignal.createWithoutInitialValue((setDownstream) => {
          return thisWithGetter.subscribe((data) => {
            if (isAvailable(data)) {
              setDownstream(deriver(data));
            }
          });
        });
      }
      const thisNarrowed = thisWithGetter;
      return LazySignal.create(deriver(thisNarrowed.get()), (setDownstream) => {
        return thisNarrowed.subscribe((data) => {
          setDownstream(deriver(data));
        });
      }, outputEqualsPredicate);
    }
    return LazySignal.createWithoutInitialValue((setDownstream) => {
      return this.subscribe((data) => {
        if (isAvailable(data)) {
          setDownstream(deriver(data));
        }
      });
    }, outputEqualsPredicate);
  }
};
var Event2 = class _Event extends Subscribable {
  /**
   * Internal state that tracks whether the event has any subscribers.
   */
  constructor() {
    super();
    this.subscribers = /* @__PURE__ */ new Set();
    this.onSubscribed = null;
    this.onUnsubscribed = null;
  }
  emit(data) {
    queueMicrotask(() => {
      for (const subscriber of this.subscribers) {
        subscriber(data);
      }
    });
  }
  static create() {
    const event = new _Event();
    const emitter = (data) => {
      event.emit(data);
    };
    return [event, emitter];
  }
  subscribe(listener) {
    const previousSize = this.subscribers.size;
    this.subscribers.add(listener);
    if (previousSize === 0 && this.subscribers.size === 1) {
      this.onSubscribed?.();
    }
    return () => {
      const previousSize2 = this.subscribers.size;
      this.subscribers.delete(listener);
      if (previousSize2 === 1 && this.subscribers.size === 0) {
        this.onUnsubscribed?.();
      }
    };
  }
  batch({ minIdleTimeMs = 200, maxBatchTimeMs = 1e3 }) {
    const [batchedEvent, emitBatchedEvent] = _Event.create();
    batchedEvent.onSubscribed = () => {
      let batch = [];
      let emitBatchTimeout = null;
      let firstEventTime = 0;
      const emitBatch = () => {
        emitBatchTimeout = null;
        emitBatchedEvent(batch);
        batch = [];
      };
      batchedEvent.onUnsubscribed = this.subscribe((data) => {
        batch.push(data);
        if (emitBatchTimeout === null) {
          firstEventTime = Date.now();
          emitBatchTimeout = setTimeout(emitBatch, Math.min(minIdleTimeMs, maxBatchTimeMs));
        } else {
          clearTimeout(emitBatchTimeout);
          const timeSinceFirstEvent = Date.now() - firstEventTime;
          emitBatchTimeout = setTimeout(emitBatch, Math.min(minIdleTimeMs, Math.max(0, maxBatchTimeMs - timeSinceFirstEvent)));
        }
      });
    };
    return batchedEvent;
  }
};
function makePromise() {
  let resolve;
  let reject;
  const promise = new Promise((_resolve, _reject) => {
    resolve = _resolve;
    reject = _reject;
  });
  return { promise, resolve, reject };
}
var NOTHING = Symbol.for("immer-nothing");
var DRAFTABLE = Symbol.for("immer-draftable");
var DRAFT_STATE = Symbol.for("immer-state");
function die(error, ...args) {
  if (false) {
    const e9 = errors[error];
    const msg = typeof e9 === "function" ? e9.apply(null, args) : e9;
    throw new Error(`[Immer] ${msg}`);
  }
  throw new Error(
    `[Immer] minified error nr: ${error}. Full error at: https://bit.ly/3cXEKWf`
  );
}
var getPrototypeOf = Object.getPrototypeOf;
function isDraft(value) {
  return !!value && !!value[DRAFT_STATE];
}
function isDraftable(value) {
  if (!value)
    return false;
  return isPlainObject$2(value) || Array.isArray(value) || !!value[DRAFTABLE] || !!value.constructor?.[DRAFTABLE] || isMap$1(value) || isSet$1(value);
}
var objectCtorString = Object.prototype.constructor.toString();
function isPlainObject$2(value) {
  if (!value || typeof value !== "object")
    return false;
  const proto = getPrototypeOf(value);
  if (proto === null) {
    return true;
  }
  const Ctor = Object.hasOwnProperty.call(proto, "constructor") && proto.constructor;
  if (Ctor === Object)
    return true;
  return typeof Ctor == "function" && Function.toString.call(Ctor) === objectCtorString;
}
function each(obj, iter) {
  if (getArchtype(obj) === 0) {
    Reflect.ownKeys(obj).forEach((key) => {
      iter(key, obj[key], obj);
    });
  } else {
    obj.forEach((entry, index) => iter(index, entry, obj));
  }
}
function getArchtype(thing) {
  const state = thing[DRAFT_STATE];
  return state ? state.type_ : Array.isArray(thing) ? 1 : isMap$1(thing) ? 2 : isSet$1(thing) ? 3 : 0;
}
function has2(thing, prop) {
  return getArchtype(thing) === 2 ? thing.has(prop) : Object.prototype.hasOwnProperty.call(thing, prop);
}
function get(thing, prop) {
  return getArchtype(thing) === 2 ? thing.get(prop) : thing[prop];
}
function set(thing, propOrOldValue, value) {
  const t6 = getArchtype(thing);
  if (t6 === 2)
    thing.set(propOrOldValue, value);
  else if (t6 === 3) {
    thing.add(value);
  } else
    thing[propOrOldValue] = value;
}
function is(x2, y4) {
  if (x2 === y4) {
    return x2 !== 0 || 1 / x2 === 1 / y4;
  } else {
    return x2 !== x2 && y4 !== y4;
  }
}
function isMap$1(target) {
  return target instanceof Map;
}
function isSet$1(target) {
  return target instanceof Set;
}
function latest(state) {
  return state.copy_ || state.base_;
}
function shallowCopy(base, strict) {
  if (isMap$1(base)) {
    return new Map(base);
  }
  if (isSet$1(base)) {
    return new Set(base);
  }
  if (Array.isArray(base))
    return Array.prototype.slice.call(base);
  const isPlain = isPlainObject$2(base);
  if (strict === true || strict === "class_only" && !isPlain) {
    const descriptors = Object.getOwnPropertyDescriptors(base);
    delete descriptors[DRAFT_STATE];
    let keys2 = Reflect.ownKeys(descriptors);
    for (let i7 = 0; i7 < keys2.length; i7++) {
      const key = keys2[i7];
      const desc = descriptors[key];
      if (desc.writable === false) {
        desc.writable = true;
        desc.configurable = true;
      }
      if (desc.get || desc.set)
        descriptors[key] = {
          configurable: true,
          writable: true,
          // could live with !!desc.set as well here...
          enumerable: desc.enumerable,
          value: base[key]
        };
    }
    return Object.create(getPrototypeOf(base), descriptors);
  } else {
    const proto = getPrototypeOf(base);
    if (proto !== null && isPlain) {
      return { ...base };
    }
    const obj = Object.create(proto);
    return Object.assign(obj, base);
  }
}
function freeze(obj, deep = false) {
  if (isFrozen(obj) || isDraft(obj) || !isDraftable(obj))
    return obj;
  if (getArchtype(obj) > 1) {
    obj.set = obj.add = obj.clear = obj.delete = dontMutateFrozenCollections;
  }
  Object.freeze(obj);
  if (deep)
    Object.values(obj).forEach((value) => freeze(value, true));
  return obj;
}
function dontMutateFrozenCollections() {
  die(2);
}
function isFrozen(obj) {
  return Object.isFrozen(obj);
}
var plugins = {};
function getPlugin(pluginKey) {
  const plugin = plugins[pluginKey];
  if (!plugin) {
    die(0, pluginKey);
  }
  return plugin;
}
function loadPlugin(pluginKey, implementation) {
  if (!plugins[pluginKey])
    plugins[pluginKey] = implementation;
}
var currentScope;
function getCurrentScope() {
  return currentScope;
}
function createScope(parent_, immer_) {
  return {
    drafts_: [],
    parent_,
    immer_,
    // Whenever the modified draft contains a draft from another scope, we
    // need to prevent auto-freezing so the unowned draft can be finalized.
    canAutoFreeze_: true,
    unfinalizedDrafts_: 0
  };
}
function usePatchesInScope(scope, patchListener) {
  if (patchListener) {
    getPlugin("Patches");
    scope.patches_ = [];
    scope.inversePatches_ = [];
    scope.patchListener_ = patchListener;
  }
}
function revokeScope(scope) {
  leaveScope(scope);
  scope.drafts_.forEach(revokeDraft);
  scope.drafts_ = null;
}
function leaveScope(scope) {
  if (scope === currentScope) {
    currentScope = scope.parent_;
  }
}
function enterScope(immer2) {
  return currentScope = createScope(currentScope, immer2);
}
function revokeDraft(draft) {
  const state = draft[DRAFT_STATE];
  if (state.type_ === 0 || state.type_ === 1)
    state.revoke_();
  else
    state.revoked_ = true;
}
function processResult(result, scope) {
  scope.unfinalizedDrafts_ = scope.drafts_.length;
  const baseDraft = scope.drafts_[0];
  const isReplaced = result !== void 0 && result !== baseDraft;
  if (isReplaced) {
    if (baseDraft[DRAFT_STATE].modified_) {
      revokeScope(scope);
      die(4);
    }
    if (isDraftable(result)) {
      result = finalize(scope, result);
      if (!scope.parent_)
        maybeFreeze(scope, result);
    }
    if (scope.patches_) {
      getPlugin("Patches").generateReplacementPatches_(
        baseDraft[DRAFT_STATE].base_,
        result,
        scope.patches_,
        scope.inversePatches_
      );
    }
  } else {
    result = finalize(scope, baseDraft, []);
  }
  revokeScope(scope);
  if (scope.patches_) {
    scope.patchListener_(scope.patches_, scope.inversePatches_);
  }
  return result !== NOTHING ? result : void 0;
}
function finalize(rootScope, value, path6) {
  if (isFrozen(value))
    return value;
  const state = value[DRAFT_STATE];
  if (!state) {
    each(
      value,
      (key, childValue) => finalizeProperty(rootScope, state, value, key, childValue, path6)
    );
    return value;
  }
  if (state.scope_ !== rootScope)
    return value;
  if (!state.modified_) {
    maybeFreeze(rootScope, state.base_, true);
    return state.base_;
  }
  if (!state.finalized_) {
    state.finalized_ = true;
    state.scope_.unfinalizedDrafts_--;
    const result = state.copy_;
    let resultEach = result;
    let isSet2 = false;
    if (state.type_ === 3) {
      resultEach = new Set(result);
      result.clear();
      isSet2 = true;
    }
    each(
      resultEach,
      (key, childValue) => finalizeProperty(rootScope, state, result, key, childValue, path6, isSet2)
    );
    maybeFreeze(rootScope, result, false);
    if (path6 && rootScope.patches_) {
      getPlugin("Patches").generatePatches_(
        state,
        path6,
        rootScope.patches_,
        rootScope.inversePatches_
      );
    }
  }
  return state.copy_;
}
function finalizeProperty(rootScope, parentState, targetObject, prop, childValue, rootPath, targetIsSet) {
  if (false)
    die(5);
  if (isDraft(childValue)) {
    const path6 = rootPath && parentState && parentState.type_ !== 3 && // Set objects are atomic since they have no keys.
    !has2(parentState.assigned_, prop) ? rootPath.concat(prop) : void 0;
    const res = finalize(rootScope, childValue, path6);
    set(targetObject, prop, res);
    if (isDraft(res)) {
      rootScope.canAutoFreeze_ = false;
    } else
      return;
  } else if (targetIsSet) {
    targetObject.add(childValue);
  }
  if (isDraftable(childValue) && !isFrozen(childValue)) {
    if (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {
      return;
    }
    finalize(rootScope, childValue);
    if ((!parentState || !parentState.scope_.parent_) && typeof prop !== "symbol" && Object.prototype.propertyIsEnumerable.call(targetObject, prop))
      maybeFreeze(rootScope, childValue);
  }
}
function maybeFreeze(scope, value, deep = false) {
  if (!scope.parent_ && scope.immer_.autoFreeze_ && scope.canAutoFreeze_) {
    freeze(value, deep);
  }
}
function createProxyProxy(base, parent) {
  const isArray5 = Array.isArray(base);
  const state = {
    type_: isArray5 ? 1 : 0,
    // Track which produce call this is associated with.
    scope_: parent ? parent.scope_ : getCurrentScope(),
    // True for both shallow and deep changes.
    modified_: false,
    // Used during finalization.
    finalized_: false,
    // Track which properties have been assigned (true) or deleted (false).
    assigned_: {},
    // The parent draft state.
    parent_: parent,
    // The base state.
    base_: base,
    // The base proxy.
    draft_: null,
    // set below
    // The base copy with any updated values.
    copy_: null,
    // Called by the `produce` function.
    revoke_: null,
    isManual_: false
  };
  let target = state;
  let traps = objectTraps;
  if (isArray5) {
    target = [state];
    traps = arrayTraps;
  }
  const { revoke, proxy } = Proxy.revocable(target, traps);
  state.draft_ = proxy;
  state.revoke_ = revoke;
  return proxy;
}
var objectTraps = {
  get(state, prop) {
    if (prop === DRAFT_STATE)
      return state;
    const source = latest(state);
    if (!has2(source, prop)) {
      return readPropFromProto(state, source, prop);
    }
    const value = source[prop];
    if (state.finalized_ || !isDraftable(value)) {
      return value;
    }
    if (value === peek(state.base_, prop)) {
      prepareCopy(state);
      return state.copy_[prop] = createProxy(value, state);
    }
    return value;
  },
  has(state, prop) {
    return prop in latest(state);
  },
  ownKeys(state) {
    return Reflect.ownKeys(latest(state));
  },
  set(state, prop, value) {
    const desc = getDescriptorFromProto(latest(state), prop);
    if (desc?.set) {
      desc.set.call(state.draft_, value);
      return true;
    }
    if (!state.modified_) {
      const current2 = peek(latest(state), prop);
      const currentState = current2?.[DRAFT_STATE];
      if (currentState && currentState.base_ === value) {
        state.copy_[prop] = value;
        state.assigned_[prop] = false;
        return true;
      }
      if (is(value, current2) && (value !== void 0 || has2(state.base_, prop)))
        return true;
      prepareCopy(state);
      markChanged(state);
    }
    if (state.copy_[prop] === value && // special case: handle new props with value 'undefined'
    (value !== void 0 || prop in state.copy_) || // special case: NaN
    Number.isNaN(value) && Number.isNaN(state.copy_[prop]))
      return true;
    state.copy_[prop] = value;
    state.assigned_[prop] = true;
    return true;
  },
  deleteProperty(state, prop) {
    if (peek(state.base_, prop) !== void 0 || prop in state.base_) {
      state.assigned_[prop] = false;
      prepareCopy(state);
      markChanged(state);
    } else {
      delete state.assigned_[prop];
    }
    if (state.copy_) {
      delete state.copy_[prop];
    }
    return true;
  },
  // Note: We never coerce `desc.value` into an Immer draft, because we can't make
  // the same guarantee in ES5 mode.
  getOwnPropertyDescriptor(state, prop) {
    const owner = latest(state);
    const desc = Reflect.getOwnPropertyDescriptor(owner, prop);
    if (!desc)
      return desc;
    return {
      writable: true,
      configurable: state.type_ !== 1 || prop !== "length",
      enumerable: desc.enumerable,
      value: owner[prop]
    };
  },
  defineProperty() {
    die(11);
  },
  getPrototypeOf(state) {
    return getPrototypeOf(state.base_);
  },
  setPrototypeOf() {
    die(12);
  }
};
var arrayTraps = {};
each(objectTraps, (key, fn) => {
  arrayTraps[key] = function() {
    arguments[0] = arguments[0][0];
    return fn.apply(this, arguments);
  };
});
arrayTraps.deleteProperty = function(state, prop) {
  if (false)
    die(13);
  return arrayTraps.set.call(this, state, prop, void 0);
};
arrayTraps.set = function(state, prop, value) {
  if (false)
    die(14);
  return objectTraps.set.call(this, state[0], prop, value, state[0]);
};
function peek(draft, prop) {
  const state = draft[DRAFT_STATE];
  const source = state ? latest(state) : draft;
  return source[prop];
}
function readPropFromProto(state, source, prop) {
  const desc = getDescriptorFromProto(source, prop);
  return desc ? `value` in desc ? desc.value : (
    // This is a very special case, if the prop is a getter defined by the
    // prototype, we should invoke it with the draft as context!
    desc.get?.call(state.draft_)
  ) : void 0;
}
function getDescriptorFromProto(source, prop) {
  if (!(prop in source))
    return void 0;
  let proto = getPrototypeOf(source);
  while (proto) {
    const desc = Object.getOwnPropertyDescriptor(proto, prop);
    if (desc)
      return desc;
    proto = getPrototypeOf(proto);
  }
  return void 0;
}
function markChanged(state) {
  if (!state.modified_) {
    state.modified_ = true;
    if (state.parent_) {
      markChanged(state.parent_);
    }
  }
}
function prepareCopy(state) {
  if (!state.copy_) {
    state.copy_ = shallowCopy(
      state.base_,
      state.scope_.immer_.useStrictShallowCopy_
    );
  }
}
var Immer2 = class {
  constructor(config) {
    this.autoFreeze_ = true;
    this.useStrictShallowCopy_ = false;
    this.produce = (base, recipe, patchListener) => {
      if (typeof base === "function" && typeof recipe !== "function") {
        const defaultBase = recipe;
        recipe = base;
        const self2 = this;
        return function curriedProduce(base2 = defaultBase, ...args) {
          return self2.produce(base2, (draft) => recipe.call(this, draft, ...args));
        };
      }
      if (typeof recipe !== "function")
        die(6);
      if (patchListener !== void 0 && typeof patchListener !== "function")
        die(7);
      let result;
      if (isDraftable(base)) {
        const scope = enterScope(this);
        const proxy = createProxy(base, void 0);
        let hasError = true;
        try {
          result = recipe(proxy);
          hasError = false;
        } finally {
          if (hasError)
            revokeScope(scope);
          else
            leaveScope(scope);
        }
        usePatchesInScope(scope, patchListener);
        return processResult(result, scope);
      } else if (!base || typeof base !== "object") {
        result = recipe(base);
        if (result === void 0)
          result = base;
        if (result === NOTHING)
          result = void 0;
        if (this.autoFreeze_)
          freeze(result, true);
        if (patchListener) {
          const p4 = [];
          const ip = [];
          getPlugin("Patches").generateReplacementPatches_(base, result, p4, ip);
          patchListener(p4, ip);
        }
        return result;
      } else
        die(1, base);
    };
    this.produceWithPatches = (base, recipe) => {
      if (typeof base === "function") {
        return (state, ...args) => this.produceWithPatches(state, (draft) => base(draft, ...args));
      }
      let patches, inversePatches;
      const result = this.produce(base, recipe, (p4, ip) => {
        patches = p4;
        inversePatches = ip;
      });
      return [result, patches, inversePatches];
    };
    if (typeof config?.autoFreeze === "boolean")
      this.setAutoFreeze(config.autoFreeze);
    if (typeof config?.useStrictShallowCopy === "boolean")
      this.setUseStrictShallowCopy(config.useStrictShallowCopy);
  }
  createDraft(base) {
    if (!isDraftable(base))
      die(8);
    if (isDraft(base))
      base = current(base);
    const scope = enterScope(this);
    const proxy = createProxy(base, void 0);
    proxy[DRAFT_STATE].isManual_ = true;
    leaveScope(scope);
    return proxy;
  }
  finishDraft(draft, patchListener) {
    const state = draft && draft[DRAFT_STATE];
    if (!state || !state.isManual_)
      die(9);
    const { scope_: scope } = state;
    usePatchesInScope(scope, patchListener);
    return processResult(void 0, scope);
  }
  /**
   * Pass true to automatically freeze all copies created by Immer.
   *
   * By default, auto-freezing is enabled.
   */
  setAutoFreeze(value) {
    this.autoFreeze_ = value;
  }
  /**
   * Pass true to enable strict shallow copy.
   *
   * By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties.
   */
  setUseStrictShallowCopy(value) {
    this.useStrictShallowCopy_ = value;
  }
  applyPatches(base, patches) {
    let i7;
    for (i7 = patches.length - 1; i7 >= 0; i7--) {
      const patch = patches[i7];
      if (patch.path.length === 0 && patch.op === "replace") {
        base = patch.value;
        break;
      }
    }
    if (i7 > -1) {
      patches = patches.slice(i7 + 1);
    }
    const applyPatchesImpl = getPlugin("Patches").applyPatches_;
    if (isDraft(base)) {
      return applyPatchesImpl(base, patches);
    }
    return this.produce(
      base,
      (draft) => applyPatchesImpl(draft, patches)
    );
  }
};
function createProxy(value, parent) {
  const draft = isMap$1(value) ? getPlugin("MapSet").proxyMap_(value, parent) : isSet$1(value) ? getPlugin("MapSet").proxySet_(value, parent) : createProxyProxy(value, parent);
  const scope = parent ? parent.scope_ : getCurrentScope();
  scope.drafts_.push(draft);
  return draft;
}
function current(value) {
  if (!isDraft(value))
    die(10, value);
  return currentImpl(value);
}
function currentImpl(value) {
  if (!isDraftable(value) || isFrozen(value))
    return value;
  const state = value[DRAFT_STATE];
  let copy2;
  if (state) {
    if (!state.modified_)
      return state.base_;
    state.finalized_ = true;
    copy2 = shallowCopy(value, state.scope_.immer_.useStrictShallowCopy_);
  } else {
    copy2 = shallowCopy(value, true);
  }
  each(copy2, (key, childValue) => {
    set(copy2, key, currentImpl(childValue));
  });
  if (state) {
    state.finalized_ = false;
  }
  return copy2;
}
function enableMapSet() {
  class DraftMap extends Map {
    constructor(target, parent) {
      super();
      this[DRAFT_STATE] = {
        type_: 2,
        parent_: parent,
        scope_: parent ? parent.scope_ : getCurrentScope(),
        modified_: false,
        finalized_: false,
        copy_: void 0,
        assigned_: void 0,
        base_: target,
        draft_: this,
        isManual_: false,
        revoked_: false
      };
    }
    get size() {
      return latest(this[DRAFT_STATE]).size;
    }
    has(key) {
      return latest(this[DRAFT_STATE]).has(key);
    }
    set(key, value) {
      const state = this[DRAFT_STATE];
      assertUnrevoked(state);
      if (!latest(state).has(key) || latest(state).get(key) !== value) {
        prepareMapCopy(state);
        markChanged(state);
        state.assigned_.set(key, true);
        state.copy_.set(key, value);
        state.assigned_.set(key, true);
      }
      return this;
    }
    delete(key) {
      if (!this.has(key)) {
        return false;
      }
      const state = this[DRAFT_STATE];
      assertUnrevoked(state);
      prepareMapCopy(state);
      markChanged(state);
      if (state.base_.has(key)) {
        state.assigned_.set(key, false);
      } else {
        state.assigned_.delete(key);
      }
      state.copy_.delete(key);
      return true;
    }
    clear() {
      const state = this[DRAFT_STATE];
      assertUnrevoked(state);
      if (latest(state).size) {
        prepareMapCopy(state);
        markChanged(state);
        state.assigned_ = /* @__PURE__ */ new Map();
        each(state.base_, (key) => {
          state.assigned_.set(key, false);
        });
        state.copy_.clear();
      }
    }
    forEach(cb, thisArg) {
      const state = this[DRAFT_STATE];
      latest(state).forEach((_value, key, _map) => {
        cb.call(thisArg, this.get(key), key, this);
      });
    }
    get(key) {
      const state = this[DRAFT_STATE];
      assertUnrevoked(state);
      const value = latest(state).get(key);
      if (state.finalized_ || !isDraftable(value)) {
        return value;
      }
      if (value !== state.base_.get(key)) {
        return value;
      }
      const draft = createProxy(value, state);
      prepareMapCopy(state);
      state.copy_.set(key, draft);
      return draft;
    }
    keys() {
      return latest(this[DRAFT_STATE]).keys();
    }
    values() {
      const iterator = this.keys();
      return {
        [Symbol.iterator]: () => this.values(),
        next: () => {
          const r8 = iterator.next();
          if (r8.done)
            return r8;
          const value = this.get(r8.value);
          return {
            done: false,
            value
          };
        }
      };
    }
    entries() {
      const iterator = this.keys();
      return {
        [Symbol.iterator]: () => this.entries(),
        next: () => {
          const r8 = iterator.next();
          if (r8.done)
            return r8;
          const value = this.get(r8.value);
          return {
            done: false,
            value: [r8.value, value]
          };
        }
      };
    }
    [Symbol.iterator]() {
      return this.entries();
    }
  }
  function proxyMap_(target, parent) {
    return new DraftMap(target, parent);
  }
  function prepareMapCopy(state) {
    if (!state.copy_) {
      state.assigned_ = /* @__PURE__ */ new Map();
      state.copy_ = new Map(state.base_);
    }
  }
  class DraftSet extends Set {
    constructor(target, parent) {
      super();
      this[DRAFT_STATE] = {
        type_: 3,
        parent_: parent,
        scope_: parent ? parent.scope_ : getCurrentScope(),
        modified_: false,
        finalized_: false,
        copy_: void 0,
        base_: target,
        draft_: this,
        drafts_: /* @__PURE__ */ new Map(),
        revoked_: false,
        isManual_: false
      };
    }
    get size() {
      return latest(this[DRAFT_STATE]).size;
    }
    has(value) {
      const state = this[DRAFT_STATE];
      assertUnrevoked(state);
      if (!state.copy_) {
        return state.base_.has(value);
      }
      if (state.copy_.has(value))
        return true;
      if (state.drafts_.has(value) && state.copy_.has(state.drafts_.get(value)))
        return true;
      return false;
    }
    add(value) {
      const state = this[DRAFT_STATE];
      assertUnrevoked(state);
      if (!this.has(value)) {
        prepareSetCopy(state);
        markChanged(state);
        state.copy_.add(value);
      }
      return this;
    }
    delete(value) {
      if (!this.has(value)) {
        return false;
      }
      const state = this[DRAFT_STATE];
      assertUnrevoked(state);
      prepareSetCopy(state);
      markChanged(state);
      return state.copy_.delete(value) || (state.drafts_.has(value) ? state.copy_.delete(state.drafts_.get(value)) : (
        /* istanbul ignore next */
        false
      ));
    }
    clear() {
      const state = this[DRAFT_STATE];
      assertUnrevoked(state);
      if (latest(state).size) {
        prepareSetCopy(state);
        markChanged(state);
        state.copy_.clear();
      }
    }
    values() {
      const state = this[DRAFT_STATE];
      assertUnrevoked(state);
      prepareSetCopy(state);
      return state.copy_.values();
    }
    entries() {
      const state = this[DRAFT_STATE];
      assertUnrevoked(state);
      prepareSetCopy(state);
      return state.copy_.entries();
    }
    keys() {
      return this.values();
    }
    [Symbol.iterator]() {
      return this.values();
    }
    forEach(cb, thisArg) {
      const iterator = this.values();
      let result = iterator.next();
      while (!result.done) {
        cb.call(thisArg, result.value, result.value, this);
        result = iterator.next();
      }
    }
  }
  function proxySet_(target, parent) {
    return new DraftSet(target, parent);
  }
  function prepareSetCopy(state) {
    if (!state.copy_) {
      state.copy_ = /* @__PURE__ */ new Set();
      state.base_.forEach((value) => {
        if (isDraftable(value)) {
          const draft = createProxy(value, state);
          state.drafts_.set(value, draft);
          state.copy_.add(draft);
        } else {
          state.copy_.add(value);
        }
      });
    }
  }
  function assertUnrevoked(state) {
    if (state.revoked_)
      die(3, JSON.stringify(latest(state)));
  }
  loadPlugin("MapSet", { proxyMap_, proxySet_ });
}
function enablePatches() {
  const errorOffset = 16;
  if (false) {
    errors.push(
      'Sets cannot have "replace" patches.',
      function(op2) {
        return "Unsupported patch operation: " + op2;
      },
      function(path6) {
        return "Cannot apply patch, path doesn't resolve: " + path6;
      },
      "Patching reserved attributes like __proto__, prototype and constructor is not allowed"
    );
  }
  const REPLACE = "replace";
  const ADD = "add";
  const REMOVE = "remove";
  function generatePatches_(state, basePath, patches, inversePatches) {
    switch (state.type_) {
      case 0:
      case 2:
        return generatePatchesFromAssigned(
          state,
          basePath,
          patches,
          inversePatches
        );
      case 1:
        return generateArrayPatches(state, basePath, patches, inversePatches);
      case 3:
        return generateSetPatches(
          state,
          basePath,
          patches,
          inversePatches
        );
    }
  }
  function generateArrayPatches(state, basePath, patches, inversePatches) {
    let { base_, assigned_ } = state;
    let copy_ = state.copy_;
    if (copy_.length < base_.length) {
      [base_, copy_] = [copy_, base_];
      [patches, inversePatches] = [inversePatches, patches];
    }
    for (let i7 = 0; i7 < base_.length; i7++) {
      if (assigned_[i7] && copy_[i7] !== base_[i7]) {
        const path6 = basePath.concat([i7]);
        patches.push({
          op: REPLACE,
          path: path6,
          // Need to maybe clone it, as it can in fact be the original value
          // due to the base/copy inversion at the start of this function
          value: clonePatchValueIfNeeded(copy_[i7])
        });
        inversePatches.push({
          op: REPLACE,
          path: path6,
          value: clonePatchValueIfNeeded(base_[i7])
        });
      }
    }
    for (let i7 = base_.length; i7 < copy_.length; i7++) {
      const path6 = basePath.concat([i7]);
      patches.push({
        op: ADD,
        path: path6,
        // Need to maybe clone it, as it can in fact be the original value
        // due to the base/copy inversion at the start of this function
        value: clonePatchValueIfNeeded(copy_[i7])
      });
    }
    for (let i7 = copy_.length - 1; base_.length <= i7; --i7) {
      const path6 = basePath.concat([i7]);
      inversePatches.push({
        op: REMOVE,
        path: path6
      });
    }
  }
  function generatePatchesFromAssigned(state, basePath, patches, inversePatches) {
    const { base_, copy_ } = state;
    each(state.assigned_, (key, assignedValue) => {
      const origValue = get(base_, key);
      const value = get(copy_, key);
      const op2 = !assignedValue ? REMOVE : has2(base_, key) ? REPLACE : ADD;
      if (origValue === value && op2 === REPLACE)
        return;
      const path6 = basePath.concat(key);
      patches.push(op2 === REMOVE ? { op: op2, path: path6 } : { op: op2, path: path6, value });
      inversePatches.push(
        op2 === ADD ? { op: REMOVE, path: path6 } : op2 === REMOVE ? { op: ADD, path: path6, value: clonePatchValueIfNeeded(origValue) } : { op: REPLACE, path: path6, value: clonePatchValueIfNeeded(origValue) }
      );
    });
  }
  function generateSetPatches(state, basePath, patches, inversePatches) {
    let { base_, copy_ } = state;
    let i7 = 0;
    base_.forEach((value) => {
      if (!copy_.has(value)) {
        const path6 = basePath.concat([i7]);
        patches.push({
          op: REMOVE,
          path: path6,
          value
        });
        inversePatches.unshift({
          op: ADD,
          path: path6,
          value
        });
      }
      i7++;
    });
    i7 = 0;
    copy_.forEach((value) => {
      if (!base_.has(value)) {
        const path6 = basePath.concat([i7]);
        patches.push({
          op: ADD,
          path: path6,
          value
        });
        inversePatches.unshift({
          op: REMOVE,
          path: path6,
          value
        });
      }
      i7++;
    });
  }
  function generateReplacementPatches_(baseValue, replacement, patches, inversePatches) {
    patches.push({
      op: REPLACE,
      path: [],
      value: replacement === NOTHING ? void 0 : replacement
    });
    inversePatches.push({
      op: REPLACE,
      path: [],
      value: baseValue
    });
  }
  function applyPatches_(draft, patches) {
    patches.forEach((patch) => {
      const { path: path6, op: op2 } = patch;
      let base = draft;
      for (let i7 = 0; i7 < path6.length - 1; i7++) {
        const parentType = getArchtype(base);
        let p4 = path6[i7];
        if (typeof p4 !== "string" && typeof p4 !== "number") {
          p4 = "" + p4;
        }
        if ((parentType === 0 || parentType === 1) && (p4 === "__proto__" || p4 === "constructor"))
          die(errorOffset + 3);
        if (typeof base === "function" && p4 === "prototype")
          die(errorOffset + 3);
        base = get(base, p4);
        if (typeof base !== "object")
          die(errorOffset + 2, path6.join("/"));
      }
      const type = getArchtype(base);
      const value = deepClonePatchValue(patch.value);
      const key = path6[path6.length - 1];
      switch (op2) {
        case REPLACE:
          switch (type) {
            case 2:
              return base.set(key, value);
            case 3:
              die(errorOffset);
            default:
              return base[key] = value;
          }
        case ADD:
          switch (type) {
            case 1:
              return key === "-" ? base.push(value) : base.splice(key, 0, value);
            case 2:
              return base.set(key, value);
            case 3:
              return base.add(value);
            default:
              return base[key] = value;
          }
        case REMOVE:
          switch (type) {
            case 1:
              return base.splice(key, 1);
            case 2:
              return base.delete(key);
            case 3:
              return base.delete(patch.value);
            default:
              return delete base[key];
          }
        default:
          die(errorOffset + 1, op2);
      }
    });
    return draft;
  }
  function deepClonePatchValue(obj) {
    if (!isDraftable(obj))
      return obj;
    if (Array.isArray(obj))
      return obj.map(deepClonePatchValue);
    if (isMap$1(obj))
      return new Map(
        Array.from(obj.entries()).map(([k2, v4]) => [k2, deepClonePatchValue(v4)])
      );
    if (isSet$1(obj))
      return new Set(Array.from(obj).map(deepClonePatchValue));
    const cloned = Object.create(getPrototypeOf(obj));
    for (const key in obj)
      cloned[key] = deepClonePatchValue(obj[key]);
    if (has2(obj, DRAFTABLE))
      cloned[DRAFTABLE] = obj[DRAFTABLE];
    return cloned;
  }
  function clonePatchValueIfNeeded(obj) {
    if (isDraft(obj)) {
      return deepClonePatchValue(obj);
    } else
      return obj;
  }
  loadPlugin("Patches", {
    applyPatches_,
    generatePatches_,
    generateReplacementPatches_
  });
}
var immer = new Immer2();
immer.produce;
var produceWithPatches = immer.produceWithPatches.bind(
  immer
);
immer.setAutoFreeze.bind(immer);
immer.setUseStrictShallowCopy.bind(immer);
var applyPatches = immer.applyPatches.bind(immer);
immer.createDraft.bind(immer);
immer.finishDraft.bind(immer);
enableMapSet();
enablePatches();
function cwt(...allTags) {
  return allTags.filter((tags) => tags !== void 0).reduce((acc, tags) => acc.concat(tags), []);
}
function makeRootReplacingPatches(value) {
  return [
    {
      op: "replace",
      path: [],
      value
    }
  ];
}
function makeSetterWithPatches(update, prependTagsFn) {
  const setter = (value, tags) => {
    update(() => [value, makeRootReplacingPatches(value)], cwt(prependTagsFn?.(), tags));
  };
  setter.withProducer = (producer, tags) => {
    update((oldData) => {
      const [newData, patches] = produceWithPatches(oldData, producer);
      if (isAvailable(newData)) {
        return [newData, patches];
      }
      throw new Error("Cannot update value to NOT_AVAILABLE");
    }, cwt(prependTagsFn?.(), tags));
  };
  setter.withUpdater = (updater, tags) => {
    update((oldData) => {
      const newData = updater(oldData);
      return [newData, makeRootReplacingPatches(newData)];
    }, cwt(prependTagsFn?.(), tags));
  };
  setter.withPatchUpdater = (updater, tags) => {
    update(updater, cwt(prependTagsFn?.(), tags));
  };
  setter.withPatches = (patches, tags) => {
    update((oldData) => {
      return [applyPatches(oldData, patches), patches];
    }, cwt(prependTagsFn?.(), tags));
  };
  setter.withValueAndPatches = (newValue, patches, tags) => {
    update(() => [newValue, patches], cwt(prependTagsFn?.(), tags));
  };
  return setter;
}
var equals = (a3, b4) => a3 === b4;
var Signal = class _Signal extends Subscribable {
  /**
   * Creates a signal.
   *
   * @param value - The initial value of the signal.
   * @param equalsPredicate - A function to compare two values. The subscribers will only be called
   * if the value changes according to the `equalsPredicate`. By default, it uses the `===`
   * operator.
   * @returns This method returns a tuple with two elements:
   * - The signal
   * - A function to update the value
   **/
  static create(value, equalsPredicate = equals) {
    const signal = new _Signal(value, equalsPredicate);
    const update = (updater, tags) => {
      signal.update(updater, tags);
    };
    const setter = makeSetterWithPatches(update);
    return [signal, setter];
  }
  static createReadonly(value) {
    return _Signal.create(value)[0];
  }
  constructor(value, equalsPredicate) {
    super();
    this.value = value;
    this.equalsPredicate = equalsPredicate;
    this.subscribers = /* @__PURE__ */ new Set();
    this.queuedUpdaters = [];
    this.isEmitting = false;
  }
  /**
   * Returns the current value of the signal.
   */
  get() {
    return this.value;
  }
  pull() {
    return this.value;
  }
  notifyFull(value, patches, tags) {
    for (const { type, callback } of this.subscribers) {
      if (type === "full") {
        callback(value, patches, tags);
      }
    }
  }
  notifyAll(value, patches, tags) {
    for (const { type, callback } of this.subscribers) {
      if (type === "regular") {
        callback(value);
      } else {
        callback(value, patches, tags);
      }
    }
  }
  notifyAndUpdateIfChanged(value, patches, tags) {
    if (!this.equalsPredicate(this.value, value)) {
      this.value = value;
      this.notifyAll(value, patches, tags);
    } else if (tags.length > 0) {
      this.notifyFull(value, patches, tags);
    }
  }
  isReplaceRoot(patch) {
    return patch.path.length === 0 && patch.op === "replace";
  }
  update(updater, tags) {
    this.queuedUpdaters.push([updater, tags]);
    if (this.isEmitting) {
      return;
    }
    this.isEmitting = true;
    try {
      while (this.queuedUpdaters.length > 0) {
        let value = this.value;
        let patches = [];
        const tags2 = [];
        while (this.queuedUpdaters.length > 0) {
          const [updater2, newTags] = this.queuedUpdaters.shift();
          const [newValue, newPatches] = updater2(value);
          value = newValue;
          const rootReplacerIndex = newPatches.findIndex(this.isReplaceRoot);
          if (rootReplacerIndex !== -1) {
            patches = newPatches.slice(rootReplacerIndex);
          } else {
            patches.push(...newPatches);
          }
          if (newTags !== void 0) {
            tags2.push(...newTags);
          }
        }
        this.notifyAndUpdateIfChanged(value, patches, tags2);
      }
    } finally {
      this.isEmitting = false;
    }
  }
  /**
   * Subscribes to the signal. The callback will be called whenever the value changes. All callbacks
   * are called synchronously upon updating. It will NOT be immediately called with the current
   * value. (Use `get()` to get the current value.) Returns a function to unsubscribe.
   *
   * Edge cases involving manipulating the signal in the callback:
   *
   * - If the callback adds new subscribers, they will also be called within the same update.
   * - If the callback causes removal of subscribers that have not been called yet, they will no
   *   longer be called.
   * - If the callback causes an update of the value, the update will be queued. If multiple updates
   *   are queued, only the last one will be executed.
   *
   * Edge cases involving adding the same callback multiple times.
   *
   *  - Callbacks are tracked with a set. Adding the same subscriber will not cause it to be called
   *    multiple times.
   */
  subscribe(callback) {
    const subscriber = {
      type: "regular",
      callback
    };
    this.subscribers.add(subscriber);
    return () => {
      this.subscribers.delete(subscriber);
    };
  }
  /**
   * Subscribes to the signal with the callback and trigger the callback immediately with the
   * current value.
   */
  subscribeAndNow(callback) {
    const unsubscribe = this.subscribe(callback);
    callback(this.value);
    return unsubscribe;
  }
  subscribeFull(callback) {
    const subscriber = {
      type: "full",
      callback
    };
    this.subscribers.add(subscriber);
    return () => {
      this.subscribers.delete(subscriber);
    };
  }
  /**
   * Wait until the signal satisfies a predicate. If the predicate is already satisfied, it will
   * return immediately. Otherwise, it will wait until the signal satisfies the predicate.
   */
  async until(predicate) {
    const current2 = this.get();
    if (predicate(current2)) {
      return current2;
    }
    const { promise, resolve } = makePromise();
    const unsubscribe = this.subscribe((data) => {
      if (predicate(data)) {
        resolve(data);
        unsubscribe();
      }
    });
    return await promise;
  }
};
function isAvailable(data) {
  return data !== LazySignal.NOT_AVAILABLE;
}
var LazySignal = class _LazySignal extends Subscribable {
  static {
    this.NOT_AVAILABLE = Symbol("notAvailable");
  }
  static create(initialValue, subscribeUpstream, equalsPredicate = (a3, b4) => a3 === b4) {
    return new _LazySignal(initialValue, subscribeUpstream, equalsPredicate);
  }
  static createWithoutInitialValue(subscribeUpstream, equalsPredicate = (a3, b4) => a3 === b4) {
    const fullEqualsPredicate = (a3, b4) => {
      if (a3 === _LazySignal.NOT_AVAILABLE || b4 === _LazySignal.NOT_AVAILABLE) {
        return a3 === b4;
      }
      return equalsPredicate(a3, b4);
    };
    return new _LazySignal(_LazySignal.NOT_AVAILABLE, subscribeUpstream, fullEqualsPredicate);
  }
  static deriveFrom(sourceSignals, deriver, outputEqualsPredicate) {
    let fullEqualsPredicate = void 0;
    if (outputEqualsPredicate !== void 0) {
      fullEqualsPredicate = (a3, b4) => {
        if (a3 === _LazySignal.NOT_AVAILABLE || b4 === _LazySignal.NOT_AVAILABLE) {
          return a3 === b4;
        }
        return outputEqualsPredicate(a3, b4);
      };
    }
    const derive = () => {
      const sourceValues = sourceSignals.map((signal) => signal.get());
      if (sourceValues.some((value) => value === _LazySignal.NOT_AVAILABLE)) {
        return _LazySignal.NOT_AVAILABLE;
      }
      return deriver(...sourceValues);
    };
    return new _LazySignal(derive(), (setDownstream) => {
      const unsubscriber = sourceSignals.map((signal) => signal.subscribe(() => {
        const value = derive();
        if (isAvailable(value)) {
          setDownstream(value);
        }
      }));
      const newValue = derive();
      if (isAvailable(newValue)) {
        setDownstream(newValue);
      }
      return () => {
        unsubscriber.forEach((unsub) => unsub());
      };
    }, fullEqualsPredicate);
  }
  static asyncDeriveFrom(strategy, sourceSignals, deriver, outputEqualsPredicate) {
    let fullEqualsPredicate = void 0;
    if (outputEqualsPredicate !== void 0) {
      fullEqualsPredicate = (a3, b4) => {
        if (a3 === _LazySignal.NOT_AVAILABLE || b4 === _LazySignal.NOT_AVAILABLE) {
          return a3 === b4;
        }
        return outputEqualsPredicate(a3, b4);
      };
    }
    let lastAppliedUpdateId = -1;
    let lastIssuedUpdateId = -1;
    return new _LazySignal(_LazySignal.NOT_AVAILABLE, (setDownstream) => {
      const deriveAndUpdate = () => {
        lastIssuedUpdateId++;
        const updateId = lastIssuedUpdateId;
        const sourceValues = sourceSignals.map((signal) => signal.get());
        if (sourceValues.some((value) => value === _LazySignal.NOT_AVAILABLE)) {
          return;
        }
        deriver(...sourceValues).then((result) => {
          if (!isAvailable(result)) {
            return;
          }
          switch (strategy) {
            case "eager": {
              if (updateId > lastAppliedUpdateId) {
                lastAppliedUpdateId = updateId;
                setDownstream(result);
              }
              break;
            }
            default: {
              const exhaustiveCheck = strategy;
              throw new Error(`Unknown strategy: ${exhaustiveCheck}`);
            }
          }
        });
      };
      const unsubscriber = sourceSignals.map((signal) => signal.subscribe(() => {
        deriveAndUpdate();
      }));
      deriveAndUpdate();
      return () => {
        unsubscriber.forEach((unsub) => unsub());
      };
    }, fullEqualsPredicate);
  }
  constructor(initialValue, subscribeUpstream, equalsPredicate = (a3, b4) => a3 === b4) {
    super();
    this.subscribeUpstream = subscribeUpstream;
    this.dataIsStale = true;
    this.upstreamUnsubscribe = null;
    this.subscribersCount = 0;
    this.isSubscribedToUpstream = false;
    this.updateReceivedSynchronousCallbacks = /* @__PURE__ */ new Set();
    [this.signal, this.setValue] = Signal.create(initialValue, equalsPredicate);
    [this.updateReceivedEvent, this.emitUpdateReceivedEvent] = Event2.create();
  }
  /**
   * Returns whether the value is currently stale.
   *
   * A value is stale whenever the upstream subscription is not active. This can happen in three
   * cases:
   *
   * 1. When no subscriber is attached to this signal, the signal will not subscribe to the
   *    upstream. In this case, the value is always stale.
   * 2. When a subscriber is attached, but the upstream has not yet emitted a single value, the
   *    value is also stale.
   * 3. When the upstream has emitted an error. In this case, the subscription to the upstream is
   *    terminated and the value is stale.
   *
   * If you wish to get the current value and ensure that it is not stale, use the method
   * {@link LazySignal#pull}.
   */
  isStale() {
    return this.dataIsStale;
  }
  subscribeToUpstream() {
    this.isSubscribedToUpstream = true;
    let subscribed = true;
    let becameStale = false;
    const unsubscribeFromUpstream = this.subscribeUpstream(makeSetterWithPatches((updater, tags) => {
      if (!subscribed) {
        return;
      }
      this.setValue.withPatchUpdater(updater, tags);
      this.dataIsStale = becameStale;
      this.emitUpdateReceivedEvent();
      for (const callback of this.updateReceivedSynchronousCallbacks) {
        callback();
      }
    }), (error) => {
      if (!subscribed) {
        return;
      }
      Promise.reject(error);
      this.dataIsStale = true;
      this.isSubscribedToUpstream = false;
      this.upstreamUnsubscribe = null;
      subscribed = false;
    });
    this.upstreamUnsubscribe = () => {
      if (subscribed) {
        subscribed = false;
        becameStale = true;
        unsubscribeFromUpstream();
      }
    };
  }
  unsubscribeFromUpstream() {
    this.isSubscribedToUpstream = false;
    if (this.upstreamUnsubscribe !== null) {
      this.upstreamUnsubscribe();
      this.upstreamUnsubscribe = null;
      this.dataIsStale = true;
    }
  }
  /**
   * Gets the current value of the signal. If the value is not available, it will return
   * {@link LazySignal.NOT_AVAILABLE}. (A value will only be unavailable if the signal is created
   * without an initial value and the upstream has not emitted a value yet.)
   *
   * In addition, the value returned by this method may be stale. Use {@link LazySignal#isStale} to
   * check if the value is stale.
   *
   * If you wish to get the current value and ensure that it is not stale, use the method
   * {@link LazySignal#pull}.
   */
  get() {
    return this.signal.get();
  }
  /**
   * Pulls the current value of the signal. If the value is stale, it will subscribe and wait for
   * the next value from the upstream and return it.
   */
  async pull() {
    const { promise, resolve } = makePromise();
    if (!this.isStale()) {
      resolve(this.get());
    } else {
      const unsubscribe = this.subscribe(() => {
      });
      this.updateReceivedEvent.subscribeOnce(() => {
        resolve(this.get());
      });
      promise.then(unsubscribe);
    }
    return promise;
  }
  /**
   * If the data is not stale, the callback will be called synchronously with the current value.
   *
   * If the data is stale, it will pull the current value and call the callback with the value.
   */
  runOnNextFreshData(callback) {
    if (!this.isStale()) {
      callback(this.get());
    } else {
      let unsubscribe = null;
      const updateCallback = () => {
        this.updateReceivedSynchronousCallbacks.delete(updateCallback);
        callback(this.get());
        unsubscribe?.();
      };
      this.updateReceivedSynchronousCallbacks.add(updateCallback);
      unsubscribe = this.subscribe(() => {
      });
    }
  }
  async ensureAvailable() {
    await this.pull();
    return this;
  }
  subscribe(subscriber) {
    if (!this.isSubscribedToUpstream) {
      this.subscribeToUpstream();
    }
    this.subscribersCount++;
    const unsubscribe = this.signal.subscribe(subscriber);
    let unsubscribeCalled = false;
    return () => {
      if (unsubscribeCalled) {
        return;
      }
      unsubscribe();
      unsubscribeCalled = true;
      this.subscribersCount--;
      if (this.subscribersCount === 0 && this.isSubscribedToUpstream) {
        this.unsubscribeFromUpstream();
      }
    };
  }
  subscribeFull(subscriber) {
    if (!this.isSubscribedToUpstream) {
      this.subscribeToUpstream();
    }
    this.subscribersCount++;
    const unsubscribe = this.signal.subscribeFull(subscriber);
    let unsubscribeCalled = false;
    return () => {
      if (unsubscribeCalled) {
        return;
      }
      unsubscribe();
      unsubscribeCalled = true;
      this.subscribersCount--;
      if (this.subscribersCount === 0 && this.isSubscribedToUpstream) {
        this.unsubscribeFromUpstream();
      }
    };
  }
  /**
   * Subscribes to the signal. Will not cause the signal to subscribe to the upstream.
   */
  passiveSubscribe(subscriber) {
    return this.signal.subscribe(subscriber);
  }
  passiveSubscribeFull(subscriber) {
    return this.signal.subscribeFull(subscriber);
  }
  async until(predicate) {
    const current2 = this.get();
    if (isAvailable(current2) && predicate(current2)) {
      return current2;
    }
    const { promise, resolve } = makePromise();
    const unsubscribe = this.subscribe((data) => {
      if (isAvailable(data) && predicate(data)) {
        resolve(data);
        unsubscribe();
      }
    });
    return await promise;
  }
};
var apiServerPorts = [41343, 52993, 16141, 39414, 22931];
var waitForNextMicroTask = Symbol();
var BufferedEvent = class _BufferedEvent extends Subscribable {
  static create() {
    const event = new _BufferedEvent();
    const emitter = (data) => {
      event.emit(data);
    };
    return [event, emitter];
  }
  constructor() {
    super();
    this.subscriber = null;
    this.queued = [];
    this.isNotifying = false;
  }
  emit(data) {
    if (this.queued.length === 0 && this.queued.at(-1) !== waitForNextMicroTask) {
      this.queued.push(waitForNextMicroTask);
    }
    this.queued.push(data);
    if (!this.isNotifying) {
      this.notifier();
    }
  }
  async notifier() {
    this.isNotifying = true;
    while (this.subscriber !== null && this.queued.length > 0) {
      const data = this.queued.shift();
      if (data === waitForNextMicroTask) {
        await Promise.resolve();
      } else {
        this.subscriber(data);
      }
    }
    this.isNotifying = false;
  }
  subscribe(listener) {
    if (this.subscriber !== null) {
      throw new Error("Cannot have more than one subscriber");
    }
    this.subscriber = listener;
    if (!this.isNotifying && this.queued.length > 0) {
      this.queued = [
        waitForNextMicroTask,
        ...this.queued.filter((data) => data !== waitForNextMicroTask)
      ];
      this.notifier();
    }
    return () => {
      this.subscriber = null;
    };
  }
  /**
   * Convert this buffered event to an event by stop buffering and triggering events on the new
   * returned event.
   */
  flow() {
    const [event, emit] = Event2.create();
    this.subscribe(emit);
    return event;
  }
};
var CancelEvent = class extends Subscribable {
  constructor() {
    super(...arguments);
    this.canceled = false;
    this.listeners = /* @__PURE__ */ new Set();
  }
  subscribe(listener) {
    if (this.canceled) {
      let callbackCanceled = false;
      Promise.resolve().then(() => {
        if (!callbackCanceled) {
          listener();
        }
      });
      return () => {
        callbackCanceled = true;
      };
    }
    this.listeners.add(listener);
    return () => {
      this.listeners.delete(listener);
    };
  }
  cancel() {
    if (this.canceled) {
      throw new Error("Already canceled");
    }
    this.canceled = true;
    for (const listener of this.listeners) {
      listener();
    }
  }
  isCanceled() {
    return this.canceled;
  }
};
var Cleaner = class {
  constructor() {
    this.eagerCleaned = false;
    this.disposed = false;
    this.cleanups = [];
  }
  register(fn) {
    if (this.eagerCleaned) {
      throw new Error("Cannot register a cleanup after eagerClean() was called.");
    }
    if (this.disposed) {
      throw new Error("Cannot register a cleanup after the Cleaner was disposed.");
    }
    this.cleanups.push(fn);
  }
  runCleanersInternal() {
    for (const cleanup of this.cleanups) {
      cleanup();
    }
    this.cleanups.length = 0;
  }
  [Symbol.dispose]() {
    if (this.eagerCleaned) {
      return;
    }
    if (this.disposed) {
      throw new Error("Cannot dispose a Cleaner that was already disposed.");
    }
    this.runCleanersInternal();
  }
  eagerClean() {
    if (this.eagerCleaned) {
      throw new Error("Cannot call eagerClean() twice.");
    }
    if (this.disposed) {
      throw new Error("Cannot call eagerClean() after the Cleaner was disposed.");
    }
    this.eagerCleaned = true;
    this.runCleanersInternal();
  }
};
function getCurrentStack(goAbove = 0) {
  const stack = new Error().stack;
  if (!stack) {
    return "";
  }
  const lines = stack.split("\n");
  return lines.slice(2 + goAbove).join("\n");
}
function changeErrorStackInPlace(error, newStack) {
  if (process_shim_default.env.LMS_KEEP_INTERNAL_STACK) {
    return;
  }
  const stackContent = error.stack ?? "";
  error.stack = (stackContent.substring(0, stackContent.indexOf("\n    at ")).trimEnd() + "\n" + newStack).trimEnd();
}
var IdGiver = class {
  constructor(firstId = 0) {
    this.nextId = firstId;
  }
  next() {
    const id = this.nextId;
    this.nextId++;
    return id;
  }
};
function getDefaultExportFromCjs(x2) {
  return x2 && x2.__esModule && Object.prototype.hasOwnProperty.call(x2, "default") ? x2["default"] : x2;
}
var boxen$1 = { exports: {} };
var stringWidth = { exports: {} };
var ansiRegex;
var hasRequiredAnsiRegex;
function requireAnsiRegex() {
  if (hasRequiredAnsiRegex) return ansiRegex;
  hasRequiredAnsiRegex = 1;
  ansiRegex = ({ onlyFirst = false } = {}) => {
    const pattern = [
      "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
      "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"
    ].join("|");
    return new RegExp(pattern, onlyFirst ? void 0 : "g");
  };
  return ansiRegex;
}
var stripAnsi;
var hasRequiredStripAnsi;
function requireStripAnsi() {
  if (hasRequiredStripAnsi) return stripAnsi;
  hasRequiredStripAnsi = 1;
  const ansiRegex2 = requireAnsiRegex();
  stripAnsi = (string) => typeof string === "string" ? string.replace(ansiRegex2(), "") : string;
  return stripAnsi;
}
var isFullwidthCodePoint = { exports: {} };
var hasRequiredIsFullwidthCodePoint;
function requireIsFullwidthCodePoint() {
  if (hasRequiredIsFullwidthCodePoint) return isFullwidthCodePoint.exports;
  hasRequiredIsFullwidthCodePoint = 1;
  const isFullwidthCodePoint$1 = (codePoint) => {
    if (Number.isNaN(codePoint)) {
      return false;
    }
    if (codePoint >= 4352 && (codePoint <= 4447 || // Hangul Jamo
    codePoint === 9001 || // LEFT-POINTING ANGLE BRACKET
    codePoint === 9002 || // RIGHT-POINTING ANGLE BRACKET
    // CJK Radicals Supplement .. Enclosed CJK Letters and Months
    11904 <= codePoint && codePoint <= 12871 && codePoint !== 12351 || // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A
    12880 <= codePoint && codePoint <= 19903 || // CJK Unified Ideographs .. Yi Radicals
    19968 <= codePoint && codePoint <= 42182 || // Hangul Jamo Extended-A
    43360 <= codePoint && codePoint <= 43388 || // Hangul Syllables
    44032 <= codePoint && codePoint <= 55203 || // CJK Compatibility Ideographs
    63744 <= codePoint && codePoint <= 64255 || // Vertical Forms
    65040 <= codePoint && codePoint <= 65049 || // CJK Compatibility Forms .. Small Form Variants
    65072 <= codePoint && codePoint <= 65131 || // Halfwidth and Fullwidth Forms
    65281 <= codePoint && codePoint <= 65376 || 65504 <= codePoint && codePoint <= 65510 || // Kana Supplement
    110592 <= codePoint && codePoint <= 110593 || // Enclosed Ideographic Supplement
    127488 <= codePoint && codePoint <= 127569 || // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane
    131072 <= codePoint && codePoint <= 262141)) {
      return true;
    }
    return false;
  };
  isFullwidthCodePoint.exports = isFullwidthCodePoint$1;
  isFullwidthCodePoint.exports.default = isFullwidthCodePoint$1;
  return isFullwidthCodePoint.exports;
}
var emojiRegex4;
var hasRequiredEmojiRegex;
function requireEmojiRegex() {
  if (hasRequiredEmojiRegex) return emojiRegex4;
  hasRequiredEmojiRegex = 1;
  emojiRegex4 = function() {
    return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g;
  };
  return emojiRegex4;
}
var hasRequiredStringWidth;
function requireStringWidth() {
  if (hasRequiredStringWidth) return stringWidth.exports;
  hasRequiredStringWidth = 1;
  const stripAnsi2 = requireStripAnsi();
  const isFullwidthCodePoint2 = requireIsFullwidthCodePoint();
  const emojiRegex5 = requireEmojiRegex();
  const stringWidth$1 = (string) => {
    if (typeof string !== "string" || string.length === 0) {
      return 0;
    }
    string = stripAnsi2(string);
    if (string.length === 0) {
      return 0;
    }
    string = string.replace(emojiRegex5(), "  ");
    let width = 0;
    for (let i7 = 0; i7 < string.length; i7++) {
      const code = string.codePointAt(i7);
      if (code <= 31 || code >= 127 && code <= 159) {
        continue;
      }
      if (code >= 768 && code <= 879) {
        continue;
      }
      if (code > 65535) {
        i7++;
      }
      width += isFullwidthCodePoint2(code) ? 2 : 1;
    }
    return width;
  };
  stringWidth.exports = stringWidth$1;
  stringWidth.exports.default = stringWidth$1;
  return stringWidth.exports;
}
var widestLine = { exports: {} };
var hasRequiredWidestLine;
function requireWidestLine() {
  if (hasRequiredWidestLine) return widestLine.exports;
  hasRequiredWidestLine = 1;
  const stringWidth2 = requireStringWidth();
  const widestLine$1 = (input) => {
    let max = 0;
    for (const line of input.split("\n")) {
      max = Math.max(max, stringWidth2(line));
    }
    return max;
  };
  widestLine.exports = widestLine$1;
  widestLine.exports.default = widestLine$1;
  return widestLine.exports;
}
var cliBoxes = { exports: {} };
var single = {
  topLeft: "\u250C",
  topRight: "\u2510",
  bottomRight: "\u2518",
  bottomLeft: "\u2514",
  vertical: "\u2502",
  horizontal: "\u2500"
};
var double = {
  topLeft: "\u2554",
  topRight: "\u2557",
  bottomRight: "\u255D",
  bottomLeft: "\u255A",
  vertical: "\u2551",
  horizontal: "\u2550"
};
var round = {
  topLeft: "\u256D",
  topRight: "\u256E",
  bottomRight: "\u256F",
  bottomLeft: "\u2570",
  vertical: "\u2502",
  horizontal: "\u2500"
};
var bold = {
  topLeft: "\u250F",
  topRight: "\u2513",
  bottomRight: "\u251B",
  bottomLeft: "\u2517",
  vertical: "\u2503",
  horizontal: "\u2501"
};
var singleDouble = {
  topLeft: "\u2553",
  topRight: "\u2556",
  bottomRight: "\u255C",
  bottomLeft: "\u2559",
  vertical: "\u2551",
  horizontal: "\u2500"
};
var doubleSingle = {
  topLeft: "\u2552",
  topRight: "\u2555",
  bottomRight: "\u255B",
  bottomLeft: "\u2558",
  vertical: "\u2502",
  horizontal: "\u2550"
};
var classic = {
  topLeft: "+",
  topRight: "+",
  bottomRight: "+",
  bottomLeft: "+",
  vertical: "|",
  horizontal: "-"
};
var require$$0 = {
  single,
  double,
  round,
  bold,
  singleDouble,
  doubleSingle,
  classic
};
var hasRequiredCliBoxes;
function requireCliBoxes() {
  if (hasRequiredCliBoxes) return cliBoxes.exports;
  hasRequiredCliBoxes = 1;
  const cliBoxes$1 = require$$0;
  cliBoxes.exports = cliBoxes$1;
  cliBoxes.exports.default = cliBoxes$1;
  return cliBoxes.exports;
}
var camelcase = { exports: {} };
var hasRequiredCamelcase;
function requireCamelcase() {
  if (hasRequiredCamelcase) return camelcase.exports;
  hasRequiredCamelcase = 1;
  const UPPERCASE = /[\p{Lu}]/u;
  const LOWERCASE = /[\p{Ll}]/u;
  const LEADING_CAPITAL = /^[\p{Lu}](?![\p{Lu}])/gu;
  const IDENTIFIER = /([\p{Alpha}\p{N}_]|$)/u;
  const SEPARATORS = /[_.\- ]+/;
  const LEADING_SEPARATORS = new RegExp("^" + SEPARATORS.source);
  const SEPARATORS_AND_IDENTIFIER = new RegExp(SEPARATORS.source + IDENTIFIER.source, "gu");
  const NUMBERS_AND_IDENTIFIER = new RegExp("\\d+" + IDENTIFIER.source, "gu");
  const preserveCamelCase = (string, toLowerCase, toUpperCase) => {
    let isLastCharLower = false;
    let isLastCharUpper = false;
    let isLastLastCharUpper = false;
    for (let i7 = 0; i7 < string.length; i7++) {
      const character = string[i7];
      if (isLastCharLower && UPPERCASE.test(character)) {
        string = string.slice(0, i7) + "-" + string.slice(i7);
        isLastCharLower = false;
        isLastLastCharUpper = isLastCharUpper;
        isLastCharUpper = true;
        i7++;
      } else if (isLastCharUpper && isLastLastCharUpper && LOWERCASE.test(character)) {
        string = string.slice(0, i7 - 1) + "-" + string.slice(i7 - 1);
        isLastLastCharUpper = isLastCharUpper;
        isLastCharUpper = false;
        isLastCharLower = true;
      } else {
        isLastCharLower = toLowerCase(character) === character && toUpperCase(character) !== character;
        isLastLastCharUpper = isLastCharUpper;
        isLastCharUpper = toUpperCase(character) === character && toLowerCase(character) !== character;
      }
    }
    return string;
  };
  const preserveConsecutiveUppercase = (input, toLowerCase) => {
    LEADING_CAPITAL.lastIndex = 0;
    return input.replace(LEADING_CAPITAL, (m1) => toLowerCase(m1));
  };
  const postProcess = (input, toUpperCase) => {
    SEPARATORS_AND_IDENTIFIER.lastIndex = 0;
    NUMBERS_AND_IDENTIFIER.lastIndex = 0;
    return input.replace(SEPARATORS_AND_IDENTIFIER, (_3, identifier) => toUpperCase(identifier)).replace(NUMBERS_AND_IDENTIFIER, (m4) => toUpperCase(m4));
  };
  const camelCase = (input, options) => {
    if (!(typeof input === "string" || Array.isArray(input))) {
      throw new TypeError("Expected the input to be `string | string[]`");
    }
    options = {
      pascalCase: false,
      preserveConsecutiveUppercase: false,
      ...options
    };
    if (Array.isArray(input)) {
      input = input.map((x2) => x2.trim()).filter((x2) => x2.length).join("-");
    } else {
      input = input.trim();
    }
    if (input.length === 0) {
      return "";
    }
    const toLowerCase = options.locale === false ? (string) => string.toLowerCase() : (string) => string.toLocaleLowerCase(options.locale);
    const toUpperCase = options.locale === false ? (string) => string.toUpperCase() : (string) => string.toLocaleUpperCase(options.locale);
    if (input.length === 1) {
      return options.pascalCase ? toUpperCase(input) : toLowerCase(input);
    }
    const hasUpperCase = input !== toLowerCase(input);
    if (hasUpperCase) {
      input = preserveCamelCase(input, toLowerCase, toUpperCase);
    }
    input = input.replace(LEADING_SEPARATORS, "");
    if (options.preserveConsecutiveUppercase) {
      input = preserveConsecutiveUppercase(input, toLowerCase);
    } else {
      input = toLowerCase(input);
    }
    if (options.pascalCase) {
      input = toUpperCase(input.charAt(0)) + input.slice(1);
    }
    return postProcess(input, toUpperCase);
  };
  camelcase.exports = camelCase;
  camelcase.exports.default = camelCase;
  return camelcase.exports;
}
var ansiAlign_1;
var hasRequiredAnsiAlign;
function requireAnsiAlign() {
  if (hasRequiredAnsiAlign) return ansiAlign_1;
  hasRequiredAnsiAlign = 1;
  const stringWidth2 = requireStringWidth();
  function ansiAlign(text3, opts) {
    if (!text3) return text3;
    opts = opts || {};
    const align = opts.align || "center";
    if (align === "left") return text3;
    const split = opts.split || "\n";
    const pad2 = opts.pad || " ";
    const widthDiffFn = align !== "right" ? halfDiff : fullDiff;
    let returnString = false;
    if (!Array.isArray(text3)) {
      returnString = true;
      text3 = String(text3).split(split);
    }
    let width;
    let maxWidth = 0;
    text3 = text3.map(function(str2) {
      str2 = String(str2);
      width = stringWidth2(str2);
      maxWidth = Math.max(width, maxWidth);
      return {
        str: str2,
        width
      };
    }).map(function(obj) {
      return new Array(widthDiffFn(maxWidth, obj.width) + 1).join(pad2) + obj.str;
    });
    return returnString ? text3.join(split) : text3;
  }
  ansiAlign.left = function left(text3) {
    return ansiAlign(text3, { align: "left" });
  };
  ansiAlign.center = function center(text3) {
    return ansiAlign(text3, { align: "center" });
  };
  ansiAlign.right = function right(text3) {
    return ansiAlign(text3, { align: "right" });
  };
  ansiAlign_1 = ansiAlign;
  function halfDiff(maxWidth, curWidth) {
    return Math.floor((maxWidth - curWidth) / 2);
  }
  function fullDiff(maxWidth, curWidth) {
    return maxWidth - curWidth;
  }
  return ansiAlign_1;
}
var ansiStyles = { exports: {} };
var colorName;
var hasRequiredColorName;
function requireColorName() {
  if (hasRequiredColorName) return colorName;
  hasRequiredColorName = 1;
  colorName = {
    "aliceblue": [240, 248, 255],
    "antiquewhite": [250, 235, 215],
    "aqua": [0, 255, 255],
    "aquamarine": [127, 255, 212],
    "azure": [240, 255, 255],
    "beige": [245, 245, 220],
    "bisque": [255, 228, 196],
    "black": [0, 0, 0],
    "blanchedalmond": [255, 235, 205],
    "blue": [0, 0, 255],
    "blueviolet": [138, 43, 226],
    "brown": [165, 42, 42],
    "burlywood": [222, 184, 135],
    "cadetblue": [95, 158, 160],
    "chartreuse": [127, 255, 0],
    "chocolate": [210, 105, 30],
    "coral": [255, 127, 80],
    "cornflowerblue": [100, 149, 237],
    "cornsilk": [255, 248, 220],
    "crimson": [220, 20, 60],
    "cyan": [0, 255, 255],
    "darkblue": [0, 0, 139],
    "darkcyan": [0, 139, 139],
    "darkgoldenrod": [184, 134, 11],
    "darkgray": [169, 169, 169],
    "darkgreen": [0, 100, 0],
    "darkgrey": [169, 169, 169],
    "darkkhaki": [189, 183, 107],
    "darkmagenta": [139, 0, 139],
    "darkolivegreen": [85, 107, 47],
    "darkorange": [255, 140, 0],
    "darkorchid": [153, 50, 204],
    "darkred": [139, 0, 0],
    "darksalmon": [233, 150, 122],
    "darkseagreen": [143, 188, 143],
    "darkslateblue": [72, 61, 139],
    "darkslategray": [47, 79, 79],
    "darkslategrey": [47, 79, 79],
    "darkturquoise": [0, 206, 209],
    "darkviolet": [148, 0, 211],
    "deeppink": [255, 20, 147],
    "deepskyblue": [0, 191, 255],
    "dimgray": [105, 105, 105],
    "dimgrey": [105, 105, 105],
    "dodgerblue": [30, 144, 255],
    "firebrick": [178, 34, 34],
    "floralwhite": [255, 250, 240],
    "forestgreen": [34, 139, 34],
    "fuchsia": [255, 0, 255],
    "gainsboro": [220, 220, 220],
    "ghostwhite": [248, 248, 255],
    "gold": [255, 215, 0],
    "goldenrod": [218, 165, 32],
    "gray": [128, 128, 128],
    "green": [0, 128, 0],
    "greenyellow": [173, 255, 47],
    "grey": [128, 128, 128],
    "honeydew": [240, 255, 240],
    "hotpink": [255, 105, 180],
    "indianred": [205, 92, 92],
    "indigo": [75, 0, 130],
    "ivory": [255, 255, 240],
    "khaki": [240, 230, 140],
    "lavender": [230, 230, 250],
    "lavenderblush": [255, 240, 245],
    "lawngreen": [124, 252, 0],
    "lemonchiffon": [255, 250, 205],
    "lightblue": [173, 216, 230],
    "lightcoral": [240, 128, 128],
    "lightcyan": [224, 255, 255],
    "lightgoldenrodyellow": [250, 250, 210],
    "lightgray": [211, 211, 211],
    "lightgreen": [144, 238, 144],
    "lightgrey": [211, 211, 211],
    "lightpink": [255, 182, 193],
    "lightsalmon": [255, 160, 122],
    "lightseagreen": [32, 178, 170],
    "lightskyblue": [135, 206, 250],
    "lightslategray": [119, 136, 153],
    "lightslategrey": [119, 136, 153],
    "lightsteelblue": [176, 196, 222],
    "lightyellow": [255, 255, 224],
    "lime": [0, 255, 0],
    "limegreen": [50, 205, 50],
    "linen": [250, 240, 230],
    "magenta": [255, 0, 255],
    "maroon": [128, 0, 0],
    "mediumaquamarine": [102, 205, 170],
    "mediumblue": [0, 0, 205],
    "mediumorchid": [186, 85, 211],
    "mediumpurple": [147, 112, 219],
    "mediumseagreen": [60, 179, 113],
    "mediumslateblue": [123, 104, 238],
    "mediumspringgreen": [0, 250, 154],
    "mediumturquoise": [72, 209, 204],
    "mediumvioletred": [199, 21, 133],
    "midnightblue": [25, 25, 112],
    "mintcream": [245, 255, 250],
    "mistyrose": [255, 228, 225],
    "moccasin": [255, 228, 181],
    "navajowhite": [255, 222, 173],
    "navy": [0, 0, 128],
    "oldlace": [253, 245, 230],
    "olive": [128, 128, 0],
    "olivedrab": [107, 142, 35],
    "orange": [255, 165, 0],
    "orangered": [255, 69, 0],
    "orchid": [218, 112, 214],
    "palegoldenrod": [238, 232, 170],
    "palegreen": [152, 251, 152],
    "paleturquoise": [175, 238, 238],
    "palevioletred": [219, 112, 147],
    "papayawhip": [255, 239, 213],
    "peachpuff": [255, 218, 185],
    "peru": [205, 133, 63],
    "pink": [255, 192, 203],
    "plum": [221, 160, 221],
    "powderblue": [176, 224, 230],
    "purple": [128, 0, 128],
    "rebeccapurple": [102, 51, 153],
    "red": [255, 0, 0],
    "rosybrown": [188, 143, 143],
    "royalblue": [65, 105, 225],
    "saddlebrown": [139, 69, 19],
    "salmon": [250, 128, 114],
    "sandybrown": [244, 164, 96],
    "seagreen": [46, 139, 87],
    "seashell": [255, 245, 238],
    "sienna": [160, 82, 45],
    "silver": [192, 192, 192],
    "skyblue": [135, 206, 235],
    "slateblue": [106, 90, 205],
    "slategray": [112, 128, 144],
    "slategrey": [112, 128, 144],
    "snow": [255, 250, 250],
    "springgreen": [0, 255, 127],
    "steelblue": [70, 130, 180],
    "tan": [210, 180, 140],
    "teal": [0, 128, 128],
    "thistle": [216, 191, 216],
    "tomato": [255, 99, 71],
    "turquoise": [64, 224, 208],
    "violet": [238, 130, 238],
    "wheat": [245, 222, 179],
    "white": [255, 255, 255],
    "whitesmoke": [245, 245, 245],
    "yellow": [255, 255, 0],
    "yellowgreen": [154, 205, 50]
  };
  return colorName;
}
var conversions;
var hasRequiredConversions;
function requireConversions() {
  if (hasRequiredConversions) return conversions;
  hasRequiredConversions = 1;
  const cssKeywords = requireColorName();
  const reverseKeywords = {};
  for (const key of Object.keys(cssKeywords)) {
    reverseKeywords[cssKeywords[key]] = key;
  }
  const convert = {
    rgb: { channels: 3, labels: "rgb" },
    hsl: { channels: 3, labels: "hsl" },
    hsv: { channels: 3, labels: "hsv" },
    hwb: { channels: 3, labels: "hwb" },
    cmyk: { channels: 4, labels: "cmyk" },
    xyz: { channels: 3, labels: "xyz" },
    lab: { channels: 3, labels: "lab" },
    lch: { channels: 3, labels: "lch" },
    hex: { channels: 1, labels: ["hex"] },
    keyword: { channels: 1, labels: ["keyword"] },
    ansi16: { channels: 1, labels: ["ansi16"] },
    ansi256: { channels: 1, labels: ["ansi256"] },
    hcg: { channels: 3, labels: ["h", "c", "g"] },
    apple: { channels: 3, labels: ["r16", "g16", "b16"] },
    gray: { channels: 1, labels: ["gray"] }
  };
  conversions = convert;
  for (const model of Object.keys(convert)) {
    if (!("channels" in convert[model])) {
      throw new Error("missing channels property: " + model);
    }
    if (!("labels" in convert[model])) {
      throw new Error("missing channel labels property: " + model);
    }
    if (convert[model].labels.length !== convert[model].channels) {
      throw new Error("channel and label counts mismatch: " + model);
    }
    const { channels, labels } = convert[model];
    delete convert[model].channels;
    delete convert[model].labels;
    Object.defineProperty(convert[model], "channels", { value: channels });
    Object.defineProperty(convert[model], "labels", { value: labels });
  }
  convert.rgb.hsl = function(rgb) {
    const r8 = rgb[0] / 255;
    const g3 = rgb[1] / 255;
    const b4 = rgb[2] / 255;
    const min = Math.min(r8, g3, b4);
    const max = Math.max(r8, g3, b4);
    const delta = max - min;
    let h7;
    let s6;
    if (max === min) {
      h7 = 0;
    } else if (r8 === max) {
      h7 = (g3 - b4) / delta;
    } else if (g3 === max) {
      h7 = 2 + (b4 - r8) / delta;
    } else if (b4 === max) {
      h7 = 4 + (r8 - g3) / delta;
    }
    h7 = Math.min(h7 * 60, 360);
    if (h7 < 0) {
      h7 += 360;
    }
    const l5 = (min + max) / 2;
    if (max === min) {
      s6 = 0;
    } else if (l5 <= 0.5) {
      s6 = delta / (max + min);
    } else {
      s6 = delta / (2 - max - min);
    }
    return [h7, s6 * 100, l5 * 100];
  };
  convert.rgb.hsv = function(rgb) {
    let rdif;
    let gdif;
    let bdif;
    let h7;
    let s6;
    const r8 = rgb[0] / 255;
    const g3 = rgb[1] / 255;
    const b4 = rgb[2] / 255;
    const v4 = Math.max(r8, g3, b4);
    const diff = v4 - Math.min(r8, g3, b4);
    const diffc = function(c6) {
      return (v4 - c6) / 6 / diff + 1 / 2;
    };
    if (diff === 0) {
      h7 = 0;
      s6 = 0;
    } else {
      s6 = diff / v4;
      rdif = diffc(r8);
      gdif = diffc(g3);
      bdif = diffc(b4);
      if (r8 === v4) {
        h7 = bdif - gdif;
      } else if (g3 === v4) {
        h7 = 1 / 3 + rdif - bdif;
      } else if (b4 === v4) {
        h7 = 2 / 3 + gdif - rdif;
      }
      if (h7 < 0) {
        h7 += 1;
      } else if (h7 > 1) {
        h7 -= 1;
      }
    }
    return [
      h7 * 360,
      s6 * 100,
      v4 * 100
    ];
  };
  convert.rgb.hwb = function(rgb) {
    const r8 = rgb[0];
    const g3 = rgb[1];
    let b4 = rgb[2];
    const h7 = convert.rgb.hsl(rgb)[0];
    const w3 = 1 / 255 * Math.min(r8, Math.min(g3, b4));
    b4 = 1 - 1 / 255 * Math.max(r8, Math.max(g3, b4));
    return [h7, w3 * 100, b4 * 100];
  };
  convert.rgb.cmyk = function(rgb) {
    const r8 = rgb[0] / 255;
    const g3 = rgb[1] / 255;
    const b4 = rgb[2] / 255;
    const k2 = Math.min(1 - r8, 1 - g3, 1 - b4);
    const c6 = (1 - r8 - k2) / (1 - k2) || 0;
    const m4 = (1 - g3 - k2) / (1 - k2) || 0;
    const y4 = (1 - b4 - k2) / (1 - k2) || 0;
    return [c6 * 100, m4 * 100, y4 * 100, k2 * 100];
  };
  function comparativeDistance(x2, y4) {
    return (x2[0] - y4[0]) ** 2 + (x2[1] - y4[1]) ** 2 + (x2[2] - y4[2]) ** 2;
  }
  convert.rgb.keyword = function(rgb) {
    const reversed = reverseKeywords[rgb];
    if (reversed) {
      return reversed;
    }
    let currentClosestDistance = Infinity;
    let currentClosestKeyword;
    for (const keyword of Object.keys(cssKeywords)) {
      const value = cssKeywords[keyword];
      const distance = comparativeDistance(rgb, value);
      if (distance < currentClosestDistance) {
        currentClosestDistance = distance;
        currentClosestKeyword = keyword;
      }
    }
    return currentClosestKeyword;
  };
  convert.keyword.rgb = function(keyword) {
    return cssKeywords[keyword];
  };
  convert.rgb.xyz = function(rgb) {
    let r8 = rgb[0] / 255;
    let g3 = rgb[1] / 255;
    let b4 = rgb[2] / 255;
    r8 = r8 > 0.04045 ? ((r8 + 0.055) / 1.055) ** 2.4 : r8 / 12.92;
    g3 = g3 > 0.04045 ? ((g3 + 0.055) / 1.055) ** 2.4 : g3 / 12.92;
    b4 = b4 > 0.04045 ? ((b4 + 0.055) / 1.055) ** 2.4 : b4 / 12.92;
    const x2 = r8 * 0.4124 + g3 * 0.3576 + b4 * 0.1805;
    const y4 = r8 * 0.2126 + g3 * 0.7152 + b4 * 0.0722;
    const z3 = r8 * 0.0193 + g3 * 0.1192 + b4 * 0.9505;
    return [x2 * 100, y4 * 100, z3 * 100];
  };
  convert.rgb.lab = function(rgb) {
    const xyz = convert.rgb.xyz(rgb);
    let x2 = xyz[0];
    let y4 = xyz[1];
    let z3 = xyz[2];
    x2 /= 95.047;
    y4 /= 100;
    z3 /= 108.883;
    x2 = x2 > 8856e-6 ? x2 ** (1 / 3) : 7.787 * x2 + 16 / 116;
    y4 = y4 > 8856e-6 ? y4 ** (1 / 3) : 7.787 * y4 + 16 / 116;
    z3 = z3 > 8856e-6 ? z3 ** (1 / 3) : 7.787 * z3 + 16 / 116;
    const l5 = 116 * y4 - 16;
    const a3 = 500 * (x2 - y4);
    const b4 = 200 * (y4 - z3);
    return [l5, a3, b4];
  };
  convert.hsl.rgb = function(hsl) {
    const h7 = hsl[0] / 360;
    const s6 = hsl[1] / 100;
    const l5 = hsl[2] / 100;
    let t22;
    let t32;
    let val2;
    if (s6 === 0) {
      val2 = l5 * 255;
      return [val2, val2, val2];
    }
    if (l5 < 0.5) {
      t22 = l5 * (1 + s6);
    } else {
      t22 = l5 + s6 - l5 * s6;
    }
    const t1 = 2 * l5 - t22;
    const rgb = [0, 0, 0];
    for (let i7 = 0; i7 < 3; i7++) {
      t32 = h7 + 1 / 3 * -(i7 - 1);
      if (t32 < 0) {
        t32++;
      }
      if (t32 > 1) {
        t32--;
      }
      if (6 * t32 < 1) {
        val2 = t1 + (t22 - t1) * 6 * t32;
      } else if (2 * t32 < 1) {
        val2 = t22;
      } else if (3 * t32 < 2) {
        val2 = t1 + (t22 - t1) * (2 / 3 - t32) * 6;
      } else {
        val2 = t1;
      }
      rgb[i7] = val2 * 255;
    }
    return rgb;
  };
  convert.hsl.hsv = function(hsl) {
    const h7 = hsl[0];
    let s6 = hsl[1] / 100;
    let l5 = hsl[2] / 100;
    let smin = s6;
    const lmin = Math.max(l5, 0.01);
    l5 *= 2;
    s6 *= l5 <= 1 ? l5 : 2 - l5;
    smin *= lmin <= 1 ? lmin : 2 - lmin;
    const v4 = (l5 + s6) / 2;
    const sv = l5 === 0 ? 2 * smin / (lmin + smin) : 2 * s6 / (l5 + s6);
    return [h7, sv * 100, v4 * 100];
  };
  convert.hsv.rgb = function(hsv) {
    const h7 = hsv[0] / 60;
    const s6 = hsv[1] / 100;
    let v4 = hsv[2] / 100;
    const hi = Math.floor(h7) % 6;
    const f4 = h7 - Math.floor(h7);
    const p4 = 255 * v4 * (1 - s6);
    const q2 = 255 * v4 * (1 - s6 * f4);
    const t6 = 255 * v4 * (1 - s6 * (1 - f4));
    v4 *= 255;
    switch (hi) {
      case 0:
        return [v4, t6, p4];
      case 1:
        return [q2, v4, p4];
      case 2:
        return [p4, v4, t6];
      case 3:
        return [p4, q2, v4];
      case 4:
        return [t6, p4, v4];
      case 5:
        return [v4, p4, q2];
    }
  };
  convert.hsv.hsl = function(hsv) {
    const h7 = hsv[0];
    const s6 = hsv[1] / 100;
    const v4 = hsv[2] / 100;
    const vmin = Math.max(v4, 0.01);
    let sl;
    let l5;
    l5 = (2 - s6) * v4;
    const lmin = (2 - s6) * vmin;
    sl = s6 * vmin;
    sl /= lmin <= 1 ? lmin : 2 - lmin;
    sl = sl || 0;
    l5 /= 2;
    return [h7, sl * 100, l5 * 100];
  };
  convert.hwb.rgb = function(hwb) {
    const h7 = hwb[0] / 360;
    let wh = hwb[1] / 100;
    let bl = hwb[2] / 100;
    const ratio = wh + bl;
    let f4;
    if (ratio > 1) {
      wh /= ratio;
      bl /= ratio;
    }
    const i7 = Math.floor(6 * h7);
    const v4 = 1 - bl;
    f4 = 6 * h7 - i7;
    if ((i7 & 1) !== 0) {
      f4 = 1 - f4;
    }
    const n7 = wh + f4 * (v4 - wh);
    let r8;
    let g3;
    let b4;
    switch (i7) {
      default:
      case 6:
      case 0:
        r8 = v4;
        g3 = n7;
        b4 = wh;
        break;
      case 1:
        r8 = n7;
        g3 = v4;
        b4 = wh;
        break;
      case 2:
        r8 = wh;
        g3 = v4;
        b4 = n7;
        break;
      case 3:
        r8 = wh;
        g3 = n7;
        b4 = v4;
        break;
      case 4:
        r8 = n7;
        g3 = wh;
        b4 = v4;
        break;
      case 5:
        r8 = v4;
        g3 = wh;
        b4 = n7;
        break;
    }
    return [r8 * 255, g3 * 255, b4 * 255];
  };
  convert.cmyk.rgb = function(cmyk) {
    const c6 = cmyk[0] / 100;
    const m4 = cmyk[1] / 100;
    const y4 = cmyk[2] / 100;
    const k2 = cmyk[3] / 100;
    const r8 = 1 - Math.min(1, c6 * (1 - k2) + k2);
    const g3 = 1 - Math.min(1, m4 * (1 - k2) + k2);
    const b4 = 1 - Math.min(1, y4 * (1 - k2) + k2);
    return [r8 * 255, g3 * 255, b4 * 255];
  };
  convert.xyz.rgb = function(xyz) {
    const x2 = xyz[0] / 100;
    const y4 = xyz[1] / 100;
    const z3 = xyz[2] / 100;
    let r8;
    let g3;
    let b4;
    r8 = x2 * 3.2406 + y4 * -1.5372 + z3 * -0.4986;
    g3 = x2 * -0.9689 + y4 * 1.8758 + z3 * 0.0415;
    b4 = x2 * 0.0557 + y4 * -0.204 + z3 * 1.057;
    r8 = r8 > 31308e-7 ? 1.055 * r8 ** (1 / 2.4) - 0.055 : r8 * 12.92;
    g3 = g3 > 31308e-7 ? 1.055 * g3 ** (1 / 2.4) - 0.055 : g3 * 12.92;
    b4 = b4 > 31308e-7 ? 1.055 * b4 ** (1 / 2.4) - 0.055 : b4 * 12.92;
    r8 = Math.min(Math.max(0, r8), 1);
    g3 = Math.min(Math.max(0, g3), 1);
    b4 = Math.min(Math.max(0, b4), 1);
    return [r8 * 255, g3 * 255, b4 * 255];
  };
  convert.xyz.lab = function(xyz) {
    let x2 = xyz[0];
    let y4 = xyz[1];
    let z3 = xyz[2];
    x2 /= 95.047;
    y4 /= 100;
    z3 /= 108.883;
    x2 = x2 > 8856e-6 ? x2 ** (1 / 3) : 7.787 * x2 + 16 / 116;
    y4 = y4 > 8856e-6 ? y4 ** (1 / 3) : 7.787 * y4 + 16 / 116;
    z3 = z3 > 8856e-6 ? z3 ** (1 / 3) : 7.787 * z3 + 16 / 116;
    const l5 = 116 * y4 - 16;
    const a3 = 500 * (x2 - y4);
    const b4 = 200 * (y4 - z3);
    return [l5, a3, b4];
  };
  convert.lab.xyz = function(lab) {
    const l5 = lab[0];
    const a3 = lab[1];
    const b4 = lab[2];
    let x2;
    let y4;
    let z3;
    y4 = (l5 + 16) / 116;
    x2 = a3 / 500 + y4;
    z3 = y4 - b4 / 200;
    const y22 = y4 ** 3;
    const x22 = x2 ** 3;
    const z22 = z3 ** 3;
    y4 = y22 > 8856e-6 ? y22 : (y4 - 16 / 116) / 7.787;
    x2 = x22 > 8856e-6 ? x22 : (x2 - 16 / 116) / 7.787;
    z3 = z22 > 8856e-6 ? z22 : (z3 - 16 / 116) / 7.787;
    x2 *= 95.047;
    y4 *= 100;
    z3 *= 108.883;
    return [x2, y4, z3];
  };
  convert.lab.lch = function(lab) {
    const l5 = lab[0];
    const a3 = lab[1];
    const b4 = lab[2];
    let h7;
    const hr = Math.atan2(b4, a3);
    h7 = hr * 360 / 2 / Math.PI;
    if (h7 < 0) {
      h7 += 360;
    }
    const c6 = Math.sqrt(a3 * a3 + b4 * b4);
    return [l5, c6, h7];
  };
  convert.lch.lab = function(lch) {
    const l5 = lch[0];
    const c6 = lch[1];
    const h7 = lch[2];
    const hr = h7 / 360 * 2 * Math.PI;
    const a3 = c6 * Math.cos(hr);
    const b4 = c6 * Math.sin(hr);
    return [l5, a3, b4];
  };
  convert.rgb.ansi16 = function(args, saturation = null) {
    const [r8, g3, b4] = args;
    let value = saturation === null ? convert.rgb.hsv(args)[2] : saturation;
    value = Math.round(value / 50);
    if (value === 0) {
      return 30;
    }
    let ansi = 30 + (Math.round(b4 / 255) << 2 | Math.round(g3 / 255) << 1 | Math.round(r8 / 255));
    if (value === 2) {
      ansi += 60;
    }
    return ansi;
  };
  convert.hsv.ansi16 = function(args) {
    return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
  };
  convert.rgb.ansi256 = function(args) {
    const r8 = args[0];
    const g3 = args[1];
    const b4 = args[2];
    if (r8 === g3 && g3 === b4) {
      if (r8 < 8) {
        return 16;
      }
      if (r8 > 248) {
        return 231;
      }
      return Math.round((r8 - 8) / 247 * 24) + 232;
    }
    const ansi = 16 + 36 * Math.round(r8 / 255 * 5) + 6 * Math.round(g3 / 255 * 5) + Math.round(b4 / 255 * 5);
    return ansi;
  };
  convert.ansi16.rgb = function(args) {
    let color = args % 10;
    if (color === 0 || color === 7) {
      if (args > 50) {
        color += 3.5;
      }
      color = color / 10.5 * 255;
      return [color, color, color];
    }
    const mult = (~~(args > 50) + 1) * 0.5;
    const r8 = (color & 1) * mult * 255;
    const g3 = (color >> 1 & 1) * mult * 255;
    const b4 = (color >> 2 & 1) * mult * 255;
    return [r8, g3, b4];
  };
  convert.ansi256.rgb = function(args) {
    if (args >= 232) {
      const c6 = (args - 232) * 10 + 8;
      return [c6, c6, c6];
    }
    args -= 16;
    let rem;
    const r8 = Math.floor(args / 36) / 5 * 255;
    const g3 = Math.floor((rem = args % 36) / 6) / 5 * 255;
    const b4 = rem % 6 / 5 * 255;
    return [r8, g3, b4];
  };
  convert.rgb.hex = function(args) {
    const integer = ((Math.round(args[0]) & 255) << 16) + ((Math.round(args[1]) & 255) << 8) + (Math.round(args[2]) & 255);
    const string = integer.toString(16).toUpperCase();
    return "000000".substring(string.length) + string;
  };
  convert.hex.rgb = function(args) {
    const match2 = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
    if (!match2) {
      return [0, 0, 0];
    }
    let colorString = match2[0];
    if (match2[0].length === 3) {
      colorString = colorString.split("").map((char) => {
        return char + char;
      }).join("");
    }
    const integer = parseInt(colorString, 16);
    const r8 = integer >> 16 & 255;
    const g3 = integer >> 8 & 255;
    const b4 = integer & 255;
    return [r8, g3, b4];
  };
  convert.rgb.hcg = function(rgb) {
    const r8 = rgb[0] / 255;
    const g3 = rgb[1] / 255;
    const b4 = rgb[2] / 255;
    const max = Math.max(Math.max(r8, g3), b4);
    const min = Math.min(Math.min(r8, g3), b4);
    const chroma = max - min;
    let grayscale;
    let hue;
    if (chroma < 1) {
      grayscale = min / (1 - chroma);
    } else {
      grayscale = 0;
    }
    if (chroma <= 0) {
      hue = 0;
    } else if (max === r8) {
      hue = (g3 - b4) / chroma % 6;
    } else if (max === g3) {
      hue = 2 + (b4 - r8) / chroma;
    } else {
      hue = 4 + (r8 - g3) / chroma;
    }
    hue /= 6;
    hue %= 1;
    return [hue * 360, chroma * 100, grayscale * 100];
  };
  convert.hsl.hcg = function(hsl) {
    const s6 = hsl[1] / 100;
    const l5 = hsl[2] / 100;
    const c6 = l5 < 0.5 ? 2 * s6 * l5 : 2 * s6 * (1 - l5);
    let f4 = 0;
    if (c6 < 1) {
      f4 = (l5 - 0.5 * c6) / (1 - c6);
    }
    return [hsl[0], c6 * 100, f4 * 100];
  };
  convert.hsv.hcg = function(hsv) {
    const s6 = hsv[1] / 100;
    const v4 = hsv[2] / 100;
    const c6 = s6 * v4;
    let f4 = 0;
    if (c6 < 1) {
      f4 = (v4 - c6) / (1 - c6);
    }
    return [hsv[0], c6 * 100, f4 * 100];
  };
  convert.hcg.rgb = function(hcg) {
    const h7 = hcg[0] / 360;
    const c6 = hcg[1] / 100;
    const g3 = hcg[2] / 100;
    if (c6 === 0) {
      return [g3 * 255, g3 * 255, g3 * 255];
    }
    const pure = [0, 0, 0];
    const hi = h7 % 1 * 6;
    const v4 = hi % 1;
    const w3 = 1 - v4;
    let mg = 0;
    switch (Math.floor(hi)) {
      case 0:
        pure[0] = 1;
        pure[1] = v4;
        pure[2] = 0;
        break;
      case 1:
        pure[0] = w3;
        pure[1] = 1;
        pure[2] = 0;
        break;
      case 2:
        pure[0] = 0;
        pure[1] = 1;
        pure[2] = v4;
        break;
      case 3:
        pure[0] = 0;
        pure[1] = w3;
        pure[2] = 1;
        break;
      case 4:
        pure[0] = v4;
        pure[1] = 0;
        pure[2] = 1;
        break;
      default:
        pure[0] = 1;
        pure[1] = 0;
        pure[2] = w3;
    }
    mg = (1 - c6) * g3;
    return [
      (c6 * pure[0] + mg) * 255,
      (c6 * pure[1] + mg) * 255,
      (c6 * pure[2] + mg) * 255
    ];
  };
  convert.hcg.hsv = function(hcg) {
    const c6 = hcg[1] / 100;
    const g3 = hcg[2] / 100;
    const v4 = c6 + g3 * (1 - c6);
    let f4 = 0;
    if (v4 > 0) {
      f4 = c6 / v4;
    }
    return [hcg[0], f4 * 100, v4 * 100];
  };
  convert.hcg.hsl = function(hcg) {
    const c6 = hcg[1] / 100;
    const g3 = hcg[2] / 100;
    const l5 = g3 * (1 - c6) + 0.5 * c6;
    let s6 = 0;
    if (l5 > 0 && l5 < 0.5) {
      s6 = c6 / (2 * l5);
    } else if (l5 >= 0.5 && l5 < 1) {
      s6 = c6 / (2 * (1 - l5));
    }
    return [hcg[0], s6 * 100, l5 * 100];
  };
  convert.hcg.hwb = function(hcg) {
    const c6 = hcg[1] / 100;
    const g3 = hcg[2] / 100;
    const v4 = c6 + g3 * (1 - c6);
    return [hcg[0], (v4 - c6) * 100, (1 - v4) * 100];
  };
  convert.hwb.hcg = function(hwb) {
    const w3 = hwb[1] / 100;
    const b4 = hwb[2] / 100;
    const v4 = 1 - b4;
    const c6 = v4 - w3;
    let g3 = 0;
    if (c6 < 1) {
      g3 = (v4 - c6) / (1 - c6);
    }
    return [hwb[0], c6 * 100, g3 * 100];
  };
  convert.apple.rgb = function(apple) {
    return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255];
  };
  convert.rgb.apple = function(rgb) {
    return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535];
  };
  convert.gray.rgb = function(args) {
    return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
  };
  convert.gray.hsl = function(args) {
    return [0, 0, args[0]];
  };
  convert.gray.hsv = convert.gray.hsl;
  convert.gray.hwb = function(gray) {
    return [0, 100, gray[0]];
  };
  convert.gray.cmyk = function(gray) {
    return [0, 0, 0, gray[0]];
  };
  convert.gray.lab = function(gray) {
    return [gray[0], 0, 0];
  };
  convert.gray.hex = function(gray) {
    const val2 = Math.round(gray[0] / 100 * 255) & 255;
    const integer = (val2 << 16) + (val2 << 8) + val2;
    const string = integer.toString(16).toUpperCase();
    return "000000".substring(string.length) + string;
  };
  convert.rgb.gray = function(rgb) {
    const val2 = (rgb[0] + rgb[1] + rgb[2]) / 3;
    return [val2 / 255 * 100];
  };
  return conversions;
}
var route;
var hasRequiredRoute;
function requireRoute() {
  if (hasRequiredRoute) return route;
  hasRequiredRoute = 1;
  const conversions2 = requireConversions();
  function buildGraph() {
    const graph = {};
    const models2 = Object.keys(conversions2);
    for (let len = models2.length, i7 = 0; i7 < len; i7++) {
      graph[models2[i7]] = {
        // http://jsperf.com/1-vs-infinity
        // micro-opt, but this is simple.
        distance: -1,
        parent: null
      };
    }
    return graph;
  }
  function deriveBFS(fromModel) {
    const graph = buildGraph();
    const queue = [fromModel];
    graph[fromModel].distance = 0;
    while (queue.length) {
      const current2 = queue.pop();
      const adjacents = Object.keys(conversions2[current2]);
      for (let len = adjacents.length, i7 = 0; i7 < len; i7++) {
        const adjacent = adjacents[i7];
        const node = graph[adjacent];
        if (node.distance === -1) {
          node.distance = graph[current2].distance + 1;
          node.parent = current2;
          queue.unshift(adjacent);
        }
      }
    }
    return graph;
  }
  function link(from, to) {
    return function(args) {
      return to(from(args));
    };
  }
  function wrapConversion(toModel, graph) {
    const path6 = [graph[toModel].parent, toModel];
    let fn = conversions2[graph[toModel].parent][toModel];
    let cur = graph[toModel].parent;
    while (graph[cur].parent) {
      path6.unshift(graph[cur].parent);
      fn = link(conversions2[graph[cur].parent][cur], fn);
      cur = graph[cur].parent;
    }
    fn.conversion = path6;
    return fn;
  }
  route = function(fromModel) {
    const graph = deriveBFS(fromModel);
    const conversion = {};
    const models2 = Object.keys(graph);
    for (let len = models2.length, i7 = 0; i7 < len; i7++) {
      const toModel = models2[i7];
      const node = graph[toModel];
      if (node.parent === null) {
        continue;
      }
      conversion[toModel] = wrapConversion(toModel, graph);
    }
    return conversion;
  };
  return route;
}
var colorConvert;
var hasRequiredColorConvert;
function requireColorConvert() {
  if (hasRequiredColorConvert) return colorConvert;
  hasRequiredColorConvert = 1;
  const conversions2 = requireConversions();
  const route2 = requireRoute();
  const convert = {};
  const models2 = Object.keys(conversions2);
  function wrapRaw(fn) {
    const wrappedFn = function(...args) {
      const arg0 = args[0];
      if (arg0 === void 0 || arg0 === null) {
        return arg0;
      }
      if (arg0.length > 1) {
        args = arg0;
      }
      return fn(args);
    };
    if ("conversion" in fn) {
      wrappedFn.conversion = fn.conversion;
    }
    return wrappedFn;
  }
  function wrapRounded(fn) {
    const wrappedFn = function(...args) {
      const arg0 = args[0];
      if (arg0 === void 0 || arg0 === null) {
        return arg0;
      }
      if (arg0.length > 1) {
        args = arg0;
      }
      const result = fn(args);
      if (typeof result === "object") {
        for (let len = result.length, i7 = 0; i7 < len; i7++) {
          result[i7] = Math.round(result[i7]);
        }
      }
      return result;
    };
    if ("conversion" in fn) {
      wrappedFn.conversion = fn.conversion;
    }
    return wrappedFn;
  }
  models2.forEach((fromModel) => {
    convert[fromModel] = {};
    Object.defineProperty(convert[fromModel], "channels", { value: conversions2[fromModel].channels });
    Object.defineProperty(convert[fromModel], "labels", { value: conversions2[fromModel].labels });
    const routes = route2(fromModel);
    const routeModels = Object.keys(routes);
    routeModels.forEach((toModel) => {
      const fn = routes[toModel];
      convert[fromModel][toModel] = wrapRounded(fn);
      convert[fromModel][toModel].raw = wrapRaw(fn);
    });
  });
  colorConvert = convert;
  return colorConvert;
}
ansiStyles.exports;
var hasRequiredAnsiStyles;
function requireAnsiStyles() {
  if (hasRequiredAnsiStyles) return ansiStyles.exports;
  hasRequiredAnsiStyles = 1;
  (function(module) {
    const wrapAnsi16 = (fn, offset) => (...args) => {
      const code = fn(...args);
      return `\x1B[${code + offset}m`;
    };
    const wrapAnsi256 = (fn, offset) => (...args) => {
      const code = fn(...args);
      return `\x1B[${38 + offset};5;${code}m`;
    };
    const wrapAnsi16m = (fn, offset) => (...args) => {
      const rgb = fn(...args);
      return `\x1B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
    };
    const ansi2ansi = (n7) => n7;
    const rgb2rgb = (r8, g3, b4) => [r8, g3, b4];
    const setLazyProperty = (object, property, get3) => {
      Object.defineProperty(object, property, {
        get: () => {
          const value = get3();
          Object.defineProperty(object, property, {
            value,
            enumerable: true,
            configurable: true
          });
          return value;
        },
        enumerable: true,
        configurable: true
      });
    };
    let colorConvert2;
    const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => {
      if (colorConvert2 === void 0) {
        colorConvert2 = requireColorConvert();
      }
      const offset = isBackground ? 10 : 0;
      const styles2 = {};
      for (const [sourceSpace, suite] of Object.entries(colorConvert2)) {
        const name = sourceSpace === "ansi16" ? "ansi" : sourceSpace;
        if (sourceSpace === targetSpace) {
          styles2[name] = wrap(identity, offset);
        } else if (typeof suite === "object") {
          styles2[name] = wrap(suite[targetSpace], offset);
        }
      }
      return styles2;
    };
    function assembleStyles() {
      const codes = /* @__PURE__ */ new Map();
      const styles2 = {
        modifier: {
          reset: [0, 0],
          // 21 isn't widely supported and 22 does the same thing
          bold: [1, 22],
          dim: [2, 22],
          italic: [3, 23],
          underline: [4, 24],
          inverse: [7, 27],
          hidden: [8, 28],
          strikethrough: [9, 29]
        },
        color: {
          black: [30, 39],
          red: [31, 39],
          green: [32, 39],
          yellow: [33, 39],
          blue: [34, 39],
          magenta: [35, 39],
          cyan: [36, 39],
          white: [37, 39],
          // Bright color
          blackBright: [90, 39],
          redBright: [91, 39],
          greenBright: [92, 39],
          yellowBright: [93, 39],
          blueBright: [94, 39],
          magentaBright: [95, 39],
          cyanBright: [96, 39],
          whiteBright: [97, 39]
        },
        bgColor: {
          bgBlack: [40, 49],
          bgRed: [41, 49],
          bgGreen: [42, 49],
          bgYellow: [43, 49],
          bgBlue: [44, 49],
          bgMagenta: [45, 49],
          bgCyan: [46, 49],
          bgWhite: [47, 49],
          // Bright color
          bgBlackBright: [100, 49],
          bgRedBright: [101, 49],
          bgGreenBright: [102, 49],
          bgYellowBright: [103, 49],
          bgBlueBright: [104, 49],
          bgMagentaBright: [105, 49],
          bgCyanBright: [106, 49],
          bgWhiteBright: [107, 49]
        }
      };
      styles2.color.gray = styles2.color.blackBright;
      styles2.bgColor.bgGray = styles2.bgColor.bgBlackBright;
      styles2.color.grey = styles2.color.blackBright;
      styles2.bgColor.bgGrey = styles2.bgColor.bgBlackBright;
      for (const [groupName, group] of Object.entries(styles2)) {
        for (const [styleName, style] of Object.entries(group)) {
          styles2[styleName] = {
            open: `\x1B[${style[0]}m`,
            close: `\x1B[${style[1]}m`
          };
          group[styleName] = styles2[styleName];
          codes.set(style[0], style[1]);
        }
        Object.defineProperty(styles2, groupName, {
          value: group,
          enumerable: false
        });
      }
      Object.defineProperty(styles2, "codes", {
        value: codes,
        enumerable: false
      });
      styles2.color.close = "\x1B[39m";
      styles2.bgColor.close = "\x1B[49m";
      setLazyProperty(styles2.color, "ansi", () => makeDynamicStyles(wrapAnsi16, "ansi16", ansi2ansi, false));
      setLazyProperty(styles2.color, "ansi256", () => makeDynamicStyles(wrapAnsi256, "ansi256", ansi2ansi, false));
      setLazyProperty(styles2.color, "ansi16m", () => makeDynamicStyles(wrapAnsi16m, "rgb", rgb2rgb, false));
      setLazyProperty(styles2.bgColor, "ansi", () => makeDynamicStyles(wrapAnsi16, "ansi16", ansi2ansi, true));
      setLazyProperty(styles2.bgColor, "ansi256", () => makeDynamicStyles(wrapAnsi256, "ansi256", ansi2ansi, true));
      setLazyProperty(styles2.bgColor, "ansi16m", () => makeDynamicStyles(wrapAnsi16m, "rgb", rgb2rgb, true));
      return styles2;
    }
    Object.defineProperty(module, "exports", {
      enumerable: true,
      get: assembleStyles
    });
  })(ansiStyles);
  return ansiStyles.exports;
}
var wrapAnsi_1;
var hasRequiredWrapAnsi;
function requireWrapAnsi() {
  if (hasRequiredWrapAnsi) return wrapAnsi_1;
  hasRequiredWrapAnsi = 1;
  const stringWidth2 = requireStringWidth();
  const stripAnsi2 = requireStripAnsi();
  const ansiStyles2 = requireAnsiStyles();
  const ESCAPES = /* @__PURE__ */ new Set([
    "\x1B",
    "\x9B"
  ]);
  const END_CODE = 39;
  const ANSI_ESCAPE_BELL = "\x07";
  const ANSI_CSI = "[";
  const ANSI_OSC = "]";
  const ANSI_SGR_TERMINATOR = "m";
  const ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`;
  const wrapAnsi = (code) => `${ESCAPES.values().next().value}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`;
  const wrapAnsiHyperlink = (uri) => `${ESCAPES.values().next().value}${ANSI_ESCAPE_LINK}${uri}${ANSI_ESCAPE_BELL}`;
  const wordLengths = (string) => string.split(" ").map((character) => stringWidth2(character));
  const wrapWord = (rows, word, columns) => {
    const characters = [...word];
    let isInsideEscape = false;
    let isInsideLinkEscape = false;
    let visible = stringWidth2(stripAnsi2(rows[rows.length - 1]));
    for (const [index, character] of characters.entries()) {
      const characterLength = stringWidth2(character);
      if (visible + characterLength <= columns) {
        rows[rows.length - 1] += character;
      } else {
        rows.push(character);
        visible = 0;
      }
      if (ESCAPES.has(character)) {
        isInsideEscape = true;
        isInsideLinkEscape = characters.slice(index + 1).join("").startsWith(ANSI_ESCAPE_LINK);
      }
      if (isInsideEscape) {
        if (isInsideLinkEscape) {
          if (character === ANSI_ESCAPE_BELL) {
            isInsideEscape = false;
            isInsideLinkEscape = false;
          }
        } else if (character === ANSI_SGR_TERMINATOR) {
          isInsideEscape = false;
        }
        continue;
      }
      visible += characterLength;
      if (visible === columns && index < characters.length - 1) {
        rows.push("");
        visible = 0;
      }
    }
    if (!visible && rows[rows.length - 1].length > 0 && rows.length > 1) {
      rows[rows.length - 2] += rows.pop();
    }
  };
  const stringVisibleTrimSpacesRight = (string) => {
    const words = string.split(" ");
    let last = words.length;
    while (last > 0) {
      if (stringWidth2(words[last - 1]) > 0) {
        break;
      }
      last--;
    }
    if (last === words.length) {
      return string;
    }
    return words.slice(0, last).join(" ") + words.slice(last).join("");
  };
  const exec = (string, columns, options = {}) => {
    if (options.trim !== false && string.trim() === "") {
      return "";
    }
    let returnValue = "";
    let escapeCode;
    let escapeUrl;
    const lengths = wordLengths(string);
    let rows = [""];
    for (const [index, word] of string.split(" ").entries()) {
      if (options.trim !== false) {
        rows[rows.length - 1] = rows[rows.length - 1].trimStart();
      }
      let rowLength = stringWidth2(rows[rows.length - 1]);
      if (index !== 0) {
        if (rowLength >= columns && (options.wordWrap === false || options.trim === false)) {
          rows.push("");
          rowLength = 0;
        }
        if (rowLength > 0 || options.trim === false) {
          rows[rows.length - 1] += " ";
          rowLength++;
        }
      }
      if (options.hard && lengths[index] > columns) {
        const remainingColumns = columns - rowLength;
        const breaksStartingThisLine = 1 + Math.floor((lengths[index] - remainingColumns - 1) / columns);
        const breaksStartingNextLine = Math.floor((lengths[index] - 1) / columns);
        if (breaksStartingNextLine < breaksStartingThisLine) {
          rows.push("");
        }
        wrapWord(rows, word, columns);
        continue;
      }
      if (rowLength + lengths[index] > columns && rowLength > 0 && lengths[index] > 0) {
        if (options.wordWrap === false && rowLength < columns) {
          wrapWord(rows, word, columns);
          continue;
        }
        rows.push("");
      }
      if (rowLength + lengths[index] > columns && options.wordWrap === false) {
        wrapWord(rows, word, columns);
        continue;
      }
      rows[rows.length - 1] += word;
    }
    if (options.trim !== false) {
      rows = rows.map(stringVisibleTrimSpacesRight);
    }
    const pre = [...rows.join("\n")];
    for (const [index, character] of pre.entries()) {
      returnValue += character;
      if (ESCAPES.has(character)) {
        const { groups } = new RegExp(`(?:\\${ANSI_CSI}(?<code>\\d+)m|\\${ANSI_ESCAPE_LINK}(?<uri>.*)${ANSI_ESCAPE_BELL})`).exec(pre.slice(index).join("")) || { groups: {} };
        if (groups.code !== void 0) {
          const code2 = Number.parseFloat(groups.code);
          escapeCode = code2 === END_CODE ? void 0 : code2;
        } else if (groups.uri !== void 0) {
          escapeUrl = groups.uri.length === 0 ? void 0 : groups.uri;
        }
      }
      const code = ansiStyles2.codes.get(Number(escapeCode));
      if (pre[index + 1] === "\n") {
        if (escapeUrl) {
          returnValue += wrapAnsiHyperlink("");
        }
        if (escapeCode && code) {
          returnValue += wrapAnsi(code);
        }
      } else if (character === "\n") {
        if (escapeCode && code) {
          returnValue += wrapAnsi(escapeCode);
        }
        if (escapeUrl) {
          returnValue += wrapAnsiHyperlink(escapeUrl);
        }
      }
    }
    return returnValue;
  };
  wrapAnsi_1 = (string, columns, options) => {
    return String(string).normalize().replace(/\r\n/g, "\n").split("\n").map((line) => exec(line, columns, options)).join("\n");
  };
  return wrapAnsi_1;
}
var hasRequiredBoxen;
function requireBoxen() {
  if (hasRequiredBoxen) return boxen$1.exports;
  hasRequiredBoxen = 1;
  const stringWidth2 = requireStringWidth();
  const chalk$1 = import_chalk.default;
  const widestLine2 = requireWidestLine();
  const cliBoxes2 = requireCliBoxes();
  const camelCase = requireCamelcase();
  const ansiAlign = requireAnsiAlign();
  const wrapAnsi = requireWrapAnsi();
  const NL = "\n";
  const PAD = " ";
  const terminalColumns = () => {
    const { env, stdout, stderr } = process;
    if (stdout && stdout.columns) {
      return stdout.columns;
    }
    if (stderr && stderr.columns) {
      return stderr.columns;
    }
    if (env.COLUMNS) {
      return Number.parseInt(env.COLUMNS, 10);
    }
    return 80;
  };
  const getObject = (detail) => {
    return typeof detail === "number" ? {
      top: detail,
      right: detail * 3,
      bottom: detail,
      left: detail * 3
    } : {
      top: 0,
      right: 0,
      bottom: 0,
      left: 0,
      ...detail
    };
  };
  const getBorderChars = (borderStyle) => {
    const sides = [
      "topLeft",
      "topRight",
      "bottomRight",
      "bottomLeft",
      "vertical",
      "horizontal"
    ];
    let chararacters;
    if (typeof borderStyle === "string") {
      chararacters = cliBoxes2[borderStyle];
      if (!chararacters) {
        throw new TypeError(`Invalid border style: ${borderStyle}`);
      }
    } else {
      for (const side of sides) {
        if (!borderStyle[side] || typeof borderStyle[side] !== "string") {
          throw new TypeError(`Invalid border style: ${side}`);
        }
      }
      chararacters = borderStyle;
    }
    return chararacters;
  };
  const makeTitle = (text3, horizontal, alignement) => {
    let title = "";
    const textWidth = stringWidth2(text3);
    switch (alignement) {
      case "left":
        title = text3 + horizontal.slice(textWidth);
        break;
      case "right":
        title = horizontal.slice(textWidth) + text3;
        break;
      default:
        horizontal = horizontal.slice(textWidth);
        if (horizontal.length % 2 === 1) {
          horizontal = horizontal.slice(Math.floor(horizontal.length / 2));
          title = horizontal.slice(1) + text3 + horizontal;
        } else {
          horizontal = horizontal.slice(horizontal.length / 2);
          title = horizontal + text3 + horizontal;
        }
        break;
    }
    return title;
  };
  const makeContentText = (text3, padding, columns, align) => {
    text3 = ansiAlign(text3, { align });
    let lines = text3.split(NL);
    const textWidth = widestLine2(text3);
    const max = columns - padding.left - padding.right;
    if (textWidth > max) {
      const newLines = [];
      for (const line of lines) {
        const createdLines = wrapAnsi(line, max, { hard: true });
        const alignedLines = ansiAlign(createdLines, { align });
        const alignedLinesArray = alignedLines.split("\n");
        const longestLength = Math.max(...alignedLinesArray.map((s6) => stringWidth2(s6)));
        for (const alignedLine of alignedLinesArray) {
          let paddedLine;
          switch (align) {
            case "center":
              paddedLine = PAD.repeat((max - longestLength) / 2) + alignedLine;
              break;
            case "right":
              paddedLine = PAD.repeat(max - longestLength) + alignedLine;
              break;
            default:
              paddedLine = alignedLine;
              break;
          }
          newLines.push(paddedLine);
        }
      }
      lines = newLines;
    }
    if (align === "center" && textWidth < max) {
      lines = lines.map((line) => PAD.repeat((max - textWidth) / 2) + line);
    } else if (align === "right" && textWidth < max) {
      lines = lines.map((line) => PAD.repeat(max - textWidth) + line);
    }
    const paddingLeft = PAD.repeat(padding.left);
    const paddingRight = PAD.repeat(padding.right);
    lines = lines.map((line) => paddingLeft + line + paddingRight);
    lines = lines.map((line) => {
      if (columns - stringWidth2(line) > 0) {
        switch (align) {
          case "center":
            return line + PAD.repeat(columns - stringWidth2(line));
          case "right":
            return line + PAD.repeat(columns - stringWidth2(line));
          default:
            return line + PAD.repeat(columns - stringWidth2(line));
        }
      }
      return line;
    });
    if (padding.top > 0) {
      lines = new Array(padding.top).fill(PAD.repeat(columns)).concat(lines);
    }
    if (padding.bottom > 0) {
      lines = lines.concat(new Array(padding.bottom).fill(PAD.repeat(columns)));
    }
    return lines.join(NL);
  };
  const isHex = (color) => color.match(/^#(?:[0-f]{3}){1,2}$/i);
  const isColorValid = (color) => typeof color === "string" && (chalk$1[color] || isHex(color));
  const getColorFn = (color) => isHex(color) ? chalk$1.hex(color) : chalk$1[color];
  const getBGColorFn = (color) => isHex(color) ? chalk$1.bgHex(color) : chalk$1[camelCase(["bg", color])];
  boxen$1.exports = (text3, options) => {
    options = {
      padding: 0,
      borderStyle: "single",
      dimBorder: false,
      textAlignment: "left",
      float: "left",
      titleAlignment: "left",
      ...options
    };
    if (options.align) {
      options.textAlignment = options.align;
    }
    const BORDERS_WIDTH = 2;
    if (options.borderColor && !isColorValid(options.borderColor)) {
      throw new Error(`${options.borderColor} is not a valid borderColor`);
    }
    if (options.backgroundColor && !isColorValid(options.backgroundColor)) {
      throw new Error(`${options.backgroundColor} is not a valid backgroundColor`);
    }
    const chars = getBorderChars(options.borderStyle);
    const padding = getObject(options.padding);
    const margin = getObject(options.margin);
    const colorizeBorder = (border) => {
      const newBorder = options.borderColor ? getColorFn(options.borderColor)(border) : border;
      return options.dimBorder ? chalk$1.dim(newBorder) : newBorder;
    };
    const colorizeContent = (content) => options.backgroundColor ? getBGColorFn(options.backgroundColor)(content) : content;
    const columns = terminalColumns() - 1;
    let contentWidth = widestLine2(wrapAnsi(text3, columns - BORDERS_WIDTH, { hard: true, trim: false })) + padding.left + padding.right;
    let title = options.title && options.title.slice(0, columns - 4 - margin.left - margin.right);
    if (title) {
      title = ` ${title} `;
      if (stringWidth2(title) > contentWidth) {
        contentWidth = stringWidth2(title);
      }
    }
    if (margin.left && margin.right && contentWidth + BORDERS_WIDTH + margin.left + margin.right > columns) {
      const spaceForMargins = columns - contentWidth - BORDERS_WIDTH;
      const multiplier = spaceForMargins / (margin.left + margin.right);
      margin.left = Math.max(0, Math.floor(margin.left * multiplier));
      margin.right = Math.max(0, Math.floor(margin.right * multiplier));
    }
    contentWidth = Math.min(contentWidth, columns - BORDERS_WIDTH - margin.left - margin.right);
    text3 = makeContentText(text3, padding, contentWidth, options.textAlignment);
    let marginLeft = PAD.repeat(margin.left);
    if (options.float === "center") {
      const marginWidth = Math.max((columns - contentWidth - BORDERS_WIDTH) / 2, 0);
      marginLeft = PAD.repeat(marginWidth);
    } else if (options.float === "right") {
      const marginWidth = Math.max(columns - contentWidth - margin.right - BORDERS_WIDTH, 0);
      marginLeft = PAD.repeat(marginWidth);
    }
    const horizontal = chars.horizontal.repeat(contentWidth);
    const top = colorizeBorder(NL.repeat(margin.top) + marginLeft + chars.topLeft + (title ? makeTitle(title, horizontal, options.titleAlignment) : horizontal) + chars.topRight);
    const bottom = colorizeBorder(marginLeft + chars.bottomLeft + horizontal + chars.bottomRight + NL.repeat(margin.bottom));
    const side = colorizeBorder(chars.vertical);
    const LINE_SEPARATOR = NL;
    const lines = text3.split(NL);
    const middle = lines.map((line) => {
      return marginLeft + side + colorizeContent(line) + side;
    }).join(LINE_SEPARATOR);
    return top + LINE_SEPARATOR + middle + LINE_SEPARATOR + bottom;
  };
  boxen$1.exports._borderStyles = cliBoxes2;
  return boxen$1.exports;
}
var boxenExports = requireBoxen();
var boxen = /* @__PURE__ */ getDefaultExportFromCjs(boxenExports);
function makeTitledPrettyError(title, content, stack) {
  return makePrettyError(import_chalk.default.redBright(title) + "\n\n" + content, stack);
}
function makePrettyError(content, stack) {
  if (process_shim_default.browser || process_shim_default.env.LMS_NO_FANCY_ERRORS || (0, import_lms_isomorphic.terminalSize)().columns < 80) {
    const error = new Error(content);
    if (stack === void 0) {
      changeErrorStackInPlace(error, "");
    } else {
      changeErrorStackInPlace(error, stack);
    }
    return error;
  } else {
    if (stack !== void 0) {
      content += "\n\n\n " + import_chalk.default.bgWhite.black("  </> STACK TRACE  ") + "\n\n" + import_chalk.default.gray(stack);
    }
    const error = new Error("\n" + boxen(content, { padding: 1, margin: 1, borderColor: "redBright", title: "Error" }));
    Object.defineProperty(error, "lmstudioRawError", { value: content, enumerable: false });
    changeErrorStackInPlace(error, "");
    return error;
  }
}
var compiledTemplatesCache = /* @__PURE__ */ new WeakMap();
function text(strings, ...values2) {
  if (values2.length + 1 !== strings.length) {
    throw new Error("text called with the wrong number of arguments.");
  }
  let compiled = compiledTemplatesCache.get(strings);
  if (compiled === void 0) {
    compiled = compile(strings);
    compiledTemplatesCache.set(strings, compiled);
  }
  for (let i7 = 0; i7 < values2.length; i7++) {
    if (typeof values2[i7] === "object") {
      if (typeof values2[i7].stack === "string") {
        compiled[i7 * 2 + 1] = values2[i7].stack;
      } else {
        try {
          compiled[i7 * 2 + 1] = JSON.stringify(values2[i7]);
        } catch (error) {
          compiled[i7 * 2 + 1] = "[Object failed to stringify]";
        }
      }
    } else {
      compiled[i7 * 2 + 1] = String(values2[i7]);
    }
  }
  return compiled.join("");
}
function removeLeadingNewlines(input) {
  return input.replace(/^\n+/, "");
}
function removeTrailingNewlinesAndWhitespace(input) {
  return input.replace(/[\n ]+$/, "");
}
function removeLeadingWhitespace(input) {
  return input.replace(/^ +/, "");
}
function removeTrailingWhitespace(input) {
  return input.replace(/ +$/, "");
}
function breakIntoLines(strings) {
  const lines = [];
  let currentLine = [];
  for (const string of strings) {
    let prevNewlineIndex = -1;
    let nextNewlineIndex;
    while ((nextNewlineIndex = string.indexOf("\n", prevNewlineIndex + 1)) !== -1) {
      currentLine.push(string.substring(prevNewlineIndex + 1, nextNewlineIndex));
      lines.push(currentLine);
      currentLine = [];
      prevNewlineIndex = nextNewlineIndex;
    }
    currentLine.push(string.substring(prevNewlineIndex + 1));
  }
  lines.push(currentLine);
  return lines;
}
function countStringIndentations(string) {
  let count = 0;
  for (const char of string) {
    if (char === " ") {
      count++;
    } else {
      return count;
    }
  }
  return Infinity;
}
function countLineIndentations(line) {
  const firstPart = line[0];
  const firstPartIndentation = countStringIndentations(firstPart);
  if (firstPartIndentation === Infinity) {
    if (line.length === 1) {
      return Infinity;
    } else {
      return firstPart.length;
    }
  }
  return firstPartIndentation;
}
function findMaxCommonIndentation(lines) {
  let minIndentation = Infinity;
  for (const line of lines) {
    minIndentation = Math.min(minIndentation, countLineIndentations(line));
  }
  return minIndentation;
}
function removeIndentation(line, indentation) {
  if (line.length < indentation) {
    return "";
  }
  return line.slice(indentation);
}
function removeAllIndentation(lines, indentation) {
  for (const line of lines) {
    line[0] = removeIndentation(line[0], indentation);
  }
}
function isEmptyLine(line) {
  if (line.length !== 1) {
    return false;
  }
  for (const char of line[0]) {
    if (char !== " ") {
      return false;
    }
  }
  return true;
}
function mergeLines(lines) {
  const linesAreEmpty = lines.map(isEmptyLine);
  const paragraphs = [];
  let currentParagraph = [];
  for (let i7 = 0; i7 < lines.length; i7++) {
    if (linesAreEmpty[i7]) {
      if (currentParagraph.length !== 0) {
        paragraphs.push(currentParagraph);
        currentParagraph = [];
      }
      continue;
    }
    if (currentParagraph.length !== 0) {
      const last = removeTrailingWhitespace(currentParagraph[currentParagraph.length - 1]);
      const next = removeLeadingWhitespace(lines[i7][0]);
      currentParagraph[currentParagraph.length - 1] = last + " " + next;
      currentParagraph.push(...lines[i7].slice(1));
    } else {
      currentParagraph.push(...lines[i7]);
    }
  }
  if (currentParagraph.length !== 0) {
    paragraphs.push(currentParagraph);
  }
  return paragraphs;
}
function mergeParagraphs(paragraphs) {
  const result = [];
  if (paragraphs.length === 0) {
    return [""];
  }
  result.push(...paragraphs[0]);
  for (let i7 = 1; i7 < paragraphs.length; i7++) {
    result[result.length - 1] += "\n\n" + paragraphs[i7][0];
    result.push(...paragraphs[i7].slice(1));
  }
  return result;
}
function addHolesForVariables(strings) {
  const result = [];
  for (let i7 = 0; i7 < strings.length; i7++) {
    result.push(strings[i7]);
    if (i7 < strings.length - 1) {
      result.push("");
    }
  }
  return result;
}
function compile(readonlyStrings) {
  const strings = [...readonlyStrings];
  strings[0] = removeLeadingNewlines(strings[0]);
  strings[strings.length - 1] = removeTrailingNewlinesAndWhitespace(strings[strings.length - 1]);
  const lines = breakIntoLines(strings);
  const commonIndentation = findMaxCommonIndentation(lines);
  removeAllIndentation(lines, commonIndentation);
  const paragraphs = mergeLines(lines);
  return addHolesForVariables(mergeParagraphs(paragraphs));
}
var MaybeMutable = class {
  constructor(data, mutable) {
    this.data = data;
    this.mutable = mutable;
  }
  /**
   * Gets the underlying data without any access control. Only used internally.
   *
   * @internal
   */
  _internalGetData() {
    return this.data;
  }
  /**
   * If this instance is mutable, return as is.
   *
   * If this instance is immutable, return a mutable copy.
   *
   * Very easy to misuse, thus internal only for now.
   *
   * @internal
   */
  _internalToMutable() {
    if (this.mutable) {
      return this;
    }
    return this.asMutableCopy();
  }
  asMutableCopy() {
    return this.create(this.cloneData(this.data), true);
  }
  asImmutableCopy() {
    if (this.mutable) {
      return this.create(this.cloneData(this.data), false);
    }
    return this;
  }
  guardMutable() {
    if (!this.mutable) {
      throw new Error(text`
        Cannot modify immutable ${this.getClassName()} instance. Use asMutableCopy() to get a
        mutable copy.
      `);
    }
  }
};
function accessMaybeMutableInternals(maybeMutable) {
  return maybeMutable;
}
var OWLSignal = class _OWLSignal extends Subscribable {
  static {
    this.NOT_AVAILABLE = LazySignal.NOT_AVAILABLE;
  }
  applyOptimisticUpdates(data) {
    for (const update of this.queuedUpdates) {
      [data] = update.updater(data);
    }
    return data;
  }
  updateOptimisticValue(tags) {
    const innerValue = this.innerSignal.get();
    if (!isAvailable(innerValue)) {
      return;
    }
    this.setOuterSignal(this.applyOptimisticUpdates(innerValue), tags);
  }
  constructor(initialValue, subscribeUpstream, writeUpstream, equalsPredicate) {
    super();
    this.writeUpstream = writeUpstream;
    this.isWriteLoopRunning = false;
    this.isSubscriptionHandledByWriteLoop = false;
    this.queuedUpdates = [];
    this.currentEnsureAvailablePromise = null;
    [this.writeErrorEvent, this.emitWriteErrorEvent] = Event2.create();
    [this.outerSignal, this.setOuterSignal] = Signal.create(initialValue, equalsPredicate);
    this.innerSignal = LazySignal.create(initialValue, subscribeUpstream, equalsPredicate);
    this.innerSignal.passiveSubscribeFull((_data, _patches, tags) => {
      if (this.isSubscriptionHandledByWriteLoop) {
        return;
      }
      this.updateOptimisticValue(tags);
    });
  }
  static create(initialValue, subscribeUpstream, writeUpstream, equalsPredicate = (a3, b4) => a3 === b4) {
    const signal = new _OWLSignal(initialValue, subscribeUpstream, writeUpstream, equalsPredicate);
    const setSignal = makeSetterWithPatches(signal.update.bind(signal));
    const emitError = (tags, error) => signal.emitWriteErrorEvent({ tags, error });
    return [signal, setSignal, emitError];
  }
  static createWithoutInitialValue(subscribeUpstream, writeUpstream, equalsPredicate = (a3, b4) => a3 === b4) {
    const fullEqualsPredicate = (a3, b4) => {
      if (a3 === _OWLSignal.NOT_AVAILABLE || b4 === _OWLSignal.NOT_AVAILABLE) {
        return a3 === b4;
      }
      return equalsPredicate(a3, b4);
    };
    return _OWLSignal.create(_OWLSignal.NOT_AVAILABLE, subscribeUpstream, writeUpstream, fullEqualsPredicate);
  }
  async update(updater, tags) {
    const { promise, reject, resolve } = makePromise();
    this.queuedUpdates.push({
      updater,
      tags: tags ?? [],
      resolve,
      reject
    });
    this.updateOptimisticValue();
    this.ensureWriteLoop();
    return promise;
  }
  /**
   * Starts the write loop if it is not already running.
   */
  ensureWriteLoop() {
    if (!this.isWriteLoopRunning) {
      this.writeLoop();
    }
  }
  /**
   * The main write loop, it will keep running until there are no more updates to process.
   */
  async writeLoop() {
    const unsubscribe = this.innerSignal.subscribe(() => {
    });
    this.isWriteLoopRunning = true;
    if (this.isStale()) {
      await this.innerSignal.pull();
    }
    while (this.queuedUpdates.length > 0) {
      const numQueuedUpdatesToHandle = this.queuedUpdates.length;
      const updater = (data) => {
        const patches = [];
        for (let i7 = 0; i7 < numQueuedUpdatesToHandle; i7++) {
          const [newData, newPatches] = this.queuedUpdates[i7].updater(data);
          data = newData;
          patches.push(...newPatches);
        }
        return [data, patches];
      };
      const resolve = () => {
        for (let i7 = 0; i7 < numQueuedUpdatesToHandle; i7++) {
          this.queuedUpdates[i7].resolve();
        }
      };
      const reject = (error) => {
        for (let i7 = 0; i7 < numQueuedUpdatesToHandle; i7++) {
          this.queuedUpdates[i7].reject(error);
        }
      };
      const queuedUpdateTags = this.queuedUpdates.flatMap((update) => update.tags);
      const tag = Date.now() + "-" + Math.random();
      await new Promise((nextStep) => {
        this.isSubscriptionHandledByWriteLoop = true;
        const unsubscribeArray = [];
        const settle = () => {
          this.isSubscriptionHandledByWriteLoop = false;
          unsubscribeArray.forEach((unsubscribe2) => unsubscribe2());
          nextStep();
        };
        unsubscribeArray.push(this.innerSignal.subscribeFull((_data, _patches, tags) => {
          if (!this.isSubscriptionHandledByWriteLoop) {
            return;
          }
          if (tags?.includes(tag)) {
            settle();
            resolve();
            this.queuedUpdates.splice(0, numQueuedUpdatesToHandle);
            this.updateOptimisticValue(tags.filter((t6) => t6 !== tag));
          } else {
            this.updateOptimisticValue(tags);
          }
        }));
        unsubscribeArray.push(this.writeErrorEvent.subscribe(({ tags, error }) => {
          if (!this.isSubscriptionHandledByWriteLoop) {
            return;
          }
          if (tags.includes(tag)) {
            settle();
            reject(error);
            this.queuedUpdates.splice(0, numQueuedUpdatesToHandle);
          }
        }));
        const sent = this.writeUpstream(...updater(this.innerSignal.get()), [tag, ...queuedUpdateTags]);
        if (!sent) {
          settle();
          resolve();
          this.queuedUpdates.splice(0, numQueuedUpdatesToHandle);
          this.updateOptimisticValue(queuedUpdateTags.filter((t6) => t6 !== tag));
        }
      });
    }
    this.isWriteLoopRunning = false;
    unsubscribe();
  }
  /**
   * Returns whether the value is currently stale.
   *
   * A value is stale whenever the upstream subscription is not active. This can happen in three
   * cases:
   *
   * 1. When no subscriber is attached to this signal, the signal will not subscribe to the
   *    upstream. In this case, the value is always stale.
   * 2. When a subscriber is attached, but the upstream has not yet emitted a single value, the
   *    value is also stale.
   * 3. When the upstream has emitted an error. In this case, the subscription to the upstream is
   *    terminated and the value is stale.
   *
   * If you wish to get the current value and ensure that it is not stale, use the method
   * {@link OWLSignal#pull}.
   */
  isStale() {
    return this.innerSignal.isStale();
  }
  /**
   * Gets the current value of the signal. If the value is not available, it will return
   * {@link OWLSignal.NOT_AVAILABLE}. (A value will only be unavailable if the signal is created
   * without an initial value and the upstream has not emitted a value yet.)
   *
   * In addition, the value returned by this method may be stale. Use {@link OWLSignal#isStale} to
   * check if the value is stale.
   *
   * If you wish to get the current value and ensure that it is not stale, use the method
   * {@link OWLSignal#pull}.
   */
  get() {
    return this.outerSignal.get();
  }
  /**
   * Gets the current value of the signal pessimistically. If the value is not available, it will
   * return {@link OWLSignal.NOT_AVAILABLE}. (A value will only be unavailable if the signal is
   * created without an initial value and the upstream has not emitted a value yet.)
   */
  getPessimistic() {
    return this.innerSignal.get();
  }
  /**
   * Pulls the current value of the signal. If the value is stale, it will subscribe and wait for
   * the next value from the upstream and return it.
   *
   * You must also provide an `optimistic` flag. If `optimistic` is true, the pending optimistic
   * updates will be applied to the value before returning it.
   */
  async pull({ optimistic = true } = {}) {
    if (optimistic) {
      return this.applyOptimisticUpdates(await this.innerSignal.pull());
    } else {
      return this.innerSignal.pull();
    }
  }
  async ensureAvailable() {
    if (this.currentEnsureAvailablePromise === null) {
      this.currentEnsureAvailablePromise = (async () => {
        await this.innerSignal.pull();
        return this;
      })();
    }
    return this.currentEnsureAvailablePromise;
  }
  subscribe(subscriber) {
    const unsubscribeOuter = this.outerSignal.subscribe(subscriber);
    const unsubscribeInner = this.innerSignal.subscribe(() => {
    });
    return () => {
      unsubscribeOuter();
      unsubscribeInner();
    };
  }
  subscribeFull(subscriber) {
    const unsubscribeOuter = this.outerSignal.subscribeFull(subscriber);
    const unsubscribeInner = this.innerSignal.subscribeFull(() => {
    });
    return () => {
      unsubscribeOuter();
      unsubscribeInner();
    };
  }
};
function parseFileIdentifier(fileIdentifier) {
  if (!fileIdentifier.includes(":")) {
    fileIdentifier = `local:${fileIdentifier}`;
  }
  const colonIndex = fileIdentifier.indexOf(":");
  const namespace = fileIdentifier.slice(0, colonIndex);
  const content = fileIdentifier.slice(colonIndex + 1);
  switch (namespace) {
    case "local": {
      if (content.includes("/") || content.includes("\\") || content.length === 0) {
        throw new Error(`Invalid local file name: ${content}.`);
      }
      return {
        type: "local",
        fileName: content
      };
    }
    case "base64": {
      return {
        type: "base64",
        base64Data: content
      };
    }
    default: {
      throw new Error(`Unknown file identifier namespace: ${namespace}.`);
    }
  }
}
function promisifyAbortSignal(abortSignal) {
  return new Promise((_resolve, reject) => {
    if (abortSignal.aborted) {
      reject(abortSignal.reason);
      return;
    }
    abortSignal.addEventListener("abort", () => {
      reject(abortSignal.reason);
    }, { once: true });
  });
}
function raceWithAbortSignal(promise, abortSignal) {
  return Promise.race([promise, promisifyAbortSignal(abortSignal)]);
}
var allowableEnvVarKeys = ["HSA_OVERRIDE_GFX_VERSION"];
var allowableEnvVarKeysSchema = external_exports.enum(allowableEnvVarKeys);
var allowableEnvVarsSchema = external_exports.record(allowableEnvVarKeysSchema, external_exports.string());
var kebabCaseRegex = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
var kebabCaseSchema = external_exports.string().regex(kebabCaseRegex);
var kebabCaseWithDotsRegex = /^[a-z0-9]+(?:[-.][a-z0-9]+)*$/;
var kebabCaseWithDotsSchema = external_exports.string().regex(kebabCaseWithDotsRegex);
var fileNameRegex = /^[\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~`][\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~` ]*(?<![. ])$/u;
var fileNameSchema = external_exports.string().regex(fileNameRegex, { message: "Invalid file name" });
var relativePathNoLeadingDotSlashRegex = /^[\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~`][\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~` ]*(?<![. ])(?:\/[\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~`][\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~` ]*(?<![. ]))*$/u;
external_exports.string().regex(relativePathNoLeadingDotSlashRegex, {
  message: "Invalid relative path"
});
var huggingFaceModelDownloadSourceSchema = external_exports.object({
  type: external_exports.literal("huggingface"),
  user: fileNameSchema,
  repo: fileNameSchema
});
var modelDownloadSourceSchema = external_exports.discriminatedUnion("type", [huggingFaceModelDownloadSourceSchema]);
var artifactDependencyPurposeSchema = external_exports.enum([
  "baseModel",
  "draftModel",
  "custom"
]);
var artifactDependencyBaseSchema = external_exports.object({
  purpose: artifactDependencyPurposeSchema
});
var artifactModelDependencySchema = external_exports.object({
  type: external_exports.literal("model"),
  ...artifactDependencyBaseSchema.shape,
  modelKeys: external_exports.array(external_exports.string().min(1)),
  sources: external_exports.array(modelDownloadSourceSchema)
});
var artifactArtifactDependencySchema = external_exports.object({
  type: external_exports.literal("artifact"),
  ...artifactDependencyBaseSchema.shape,
  owner: kebabCaseSchema,
  name: kebabCaseWithDotsSchema
});
var artifactDependencySchema = external_exports.discriminatedUnion("type", [
  artifactModelDependencySchema,
  artifactArtifactDependencySchema
]);
var artifactManifestBaseSchema = external_exports.object({
  owner: kebabCaseSchema,
  name: kebabCaseWithDotsSchema.min(1, "Name is required").max(100, "Name too long"),
  revision: external_exports.number().int().optional(),
  dependencies: external_exports.array(artifactDependencySchema).optional(),
  tags: external_exports.array(external_exports.string()).optional()
});
var artifactIdentifierRegex = /^[a-z0-9]+(?:-[a-z0-9]+)*\/[a-z0-9]+(?:[-.][a-z0-9]+)*$/;
var artifactIdentifierSchema = external_exports.string().regex(artifactIdentifierRegex, {
  message: "Invalid artifact identifier format. Expected 'owner/name'."
});
var modelManifestSchema = external_exports.object({
  type: external_exports.literal("model"),
  ...artifactManifestBaseSchema.shape
});
var pluginRunnerTypeSchema = external_exports.enum(["ecmascript", "node", "mcpBridge"]);
var pluginManifestSchema = external_exports.object({
  type: external_exports.literal("plugin"),
  runner: pluginRunnerTypeSchema,
  ...artifactManifestBaseSchema.shape
});
var presetManifestSchema = external_exports.object({
  type: external_exports.literal("preset"),
  ...artifactManifestBaseSchema.shape
});
external_exports.discriminatedUnion("type", [
  pluginManifestSchema,
  presetManifestSchema,
  modelManifestSchema
]);
var artifactTypeSchema = external_exports.enum(["plugin", "preset", "model"]);
var backendNotificationSchema = external_exports.object({
  title: external_exports.string(),
  description: external_exports.string().optional(),
  noAutoDismiss: external_exports.boolean().optional()
});
var fileTypeSchema = external_exports.enum([
  "image",
  "text/plain",
  "application/pdf",
  "application/word",
  "text/other",
  "unknown"
]);
var jsonSerializableSchema = external_exports.any().transform((val2, ctx) => {
  try {
    return JSON.parse(JSON.stringify(val2));
  } catch (e9) {
    ctx.addIssue({
      code: external_exports.ZodIssueCode.custom,
      message: "Not JSON serializable: " + e9.message
    });
    return val2;
  }
});
var chatMessagePartTextDataSchema = external_exports.object({
  type: external_exports.literal("text"),
  text: external_exports.string()
});
var chatMessagePartFileDataSchema = external_exports.object({
  type: external_exports.literal("file"),
  name: external_exports.string(),
  identifier: external_exports.string(),
  sizeBytes: external_exports.number().int(),
  fileType: fileTypeSchema
});
var functionToolCallRequestSchema = external_exports.object({
  id: external_exports.string().optional(),
  type: external_exports.literal("function"),
  arguments: external_exports.record(jsonSerializableSchema).optional(),
  name: external_exports.string()
});
var toolCallRequestSchema = external_exports.discriminatedUnion("type", [
  functionToolCallRequestSchema
]);
var chatMessagePartToolCallRequestDataSchema = external_exports.object({
  type: external_exports.literal("toolCallRequest"),
  toolCallRequest: toolCallRequestSchema
});
external_exports.object({
  content: external_exports.string(),
  toolCallId: external_exports.string().optional()
});
var chatMessagePartToolCallResultDataSchema = external_exports.object({
  type: external_exports.literal("toolCallResult"),
  content: external_exports.string(),
  toolCallId: external_exports.string().optional()
});
external_exports.discriminatedUnion("type", [
  chatMessagePartTextDataSchema,
  chatMessagePartFileDataSchema,
  chatMessagePartToolCallRequestDataSchema,
  chatMessagePartToolCallResultDataSchema
]);
external_exports.enum(["assistant", "user", "system", "tool"]);
var chatMessageDataSchema = external_exports.discriminatedUnion("role", [
  external_exports.object({
    role: external_exports.literal("assistant"),
    content: external_exports.array(external_exports.discriminatedUnion("type", [
      chatMessagePartTextDataSchema,
      chatMessagePartFileDataSchema,
      chatMessagePartToolCallRequestDataSchema
    ]))
  }),
  external_exports.object({
    role: external_exports.literal("user"),
    content: external_exports.array(external_exports.discriminatedUnion("type", [chatMessagePartTextDataSchema, chatMessagePartFileDataSchema]))
  }),
  external_exports.object({
    role: external_exports.literal("system"),
    content: external_exports.array(external_exports.discriminatedUnion("type", [chatMessagePartTextDataSchema, chatMessagePartFileDataSchema]))
  }),
  external_exports.object({
    role: external_exports.literal("tool"),
    content: external_exports.array(chatMessagePartToolCallResultDataSchema)
  })
]);
var chatHistoryDataSchema = external_exports.object({
  messages: external_exports.array(chatMessageDataSchema)
});
var citationSourceSchema = external_exports.object({
  fileName: external_exports.string(),
  absoluteFilePath: external_exports.string().optional(),
  pageNumber: external_exports.union([external_exports.number().int(), external_exports.tuple([external_exports.number().int(), external_exports.number().int()])]).optional(),
  lineNumber: external_exports.union([external_exports.number().int(), external_exports.tuple([external_exports.number().int(), external_exports.number().int()])]).optional()
});
var colorPalette = external_exports.enum([
  "red",
  "green",
  "blue",
  "yellow",
  "orange",
  "purple",
  "default"
]);
var colorPaletteSchema = colorPalette;
var diagnosticsLogEventDataSchema = external_exports.discriminatedUnion("type", [
  external_exports.object({
    type: external_exports.literal("llm.prediction.input"),
    modelPath: external_exports.string(),
    modelIdentifier: external_exports.string(),
    input: external_exports.string()
  })
]);
var diagnosticsLogEventSchema = external_exports.object({
  timestamp: external_exports.number(),
  data: diagnosticsLogEventDataSchema
});
var llmLlamaAccelerationOffloadRatioSchema = external_exports.union([
  external_exports.number().min(0).max(1),
  external_exports.literal("max"),
  external_exports.literal("off")
]);
var llmSplitStrategySchema = external_exports.enum(["evenly", "favorMainGpu"]);
var gpuSettingSchema = external_exports.object({
  ratio: llmLlamaAccelerationOffloadRatioSchema.optional(),
  mainGpu: external_exports.number().int().optional(),
  splitStrategy: llmSplitStrategySchema.optional(),
  disabledGpus: external_exports.array(external_exports.number().int()).optional()
});
var llmLlamaCacheQuantizationTypes = [
  "f32",
  "f16",
  "q8_0",
  "q4_0",
  "q4_1",
  "iq4_nl",
  "q5_0",
  "q5_1"
];
var llmLlamaCacheQuantizationTypeSchema = external_exports.enum(llmLlamaCacheQuantizationTypes);
var llmMlxKvCacheBitsTypeSchema = external_exports.union([
  external_exports.literal(8),
  external_exports.literal(6),
  external_exports.literal(4),
  external_exports.literal(3),
  external_exports.literal(2)
]);
var llmMlxKvCacheGroupSizeTypesSchema = external_exports.union([
  external_exports.literal(32),
  external_exports.literal(64),
  external_exports.literal(128)
]);
var llmMlxKvCacheQuantizationSchema = external_exports.object({
  enabled: external_exports.boolean(),
  bits: llmMlxKvCacheBitsTypeSchema,
  groupSize: llmMlxKvCacheGroupSizeTypesSchema,
  quantizedStart: external_exports.number().int().nonnegative()
});
var llmLoadModelConfigSchema = external_exports.object({
  gpu: gpuSettingSchema.optional(),
  gpuStrictVramCap: external_exports.boolean().optional(),
  offloadKVCacheToGpu: external_exports.boolean().optional(),
  contextLength: external_exports.number().int().min(1).optional(),
  ropeFrequencyBase: external_exports.number().optional(),
  ropeFrequencyScale: external_exports.number().optional(),
  evalBatchSize: external_exports.number().int().min(1).optional(),
  flashAttention: external_exports.boolean().optional(),
  keepModelInMemory: external_exports.boolean().optional(),
  seed: external_exports.number().int().optional(),
  useFp16ForKVCache: external_exports.boolean().optional(),
  tryMmap: external_exports.boolean().optional(),
  numExperts: external_exports.number().int().optional(),
  llamaKCacheQuantizationType: external_exports.enum(llmLlamaCacheQuantizationTypes).or(external_exports.literal(false)).optional(),
  llamaVCacheQuantizationType: external_exports.enum(llmLlamaCacheQuantizationTypes).or(external_exports.literal(false)).optional()
});
var embeddingLoadModelConfigSchema = external_exports.object({
  gpu: gpuSettingSchema.optional(),
  contextLength: external_exports.number().int().min(1).optional(),
  ropeFrequencyBase: external_exports.number().optional(),
  ropeFrequencyScale: external_exports.number().optional(),
  keepModelInMemory: external_exports.boolean().optional(),
  tryMmap: external_exports.boolean().optional()
});
var modelCompatibilityTypeSchema = external_exports.enum([
  "gguf",
  "safetensors",
  "onnx",
  "ggml",
  "mlx_placeholder",
  "torch_safetensors"
]);
var quantizationSchema = external_exports.object({
  name: external_exports.string(),
  bits: external_exports.number().int()
});
var modelInfoBaseSchema = external_exports.object({
  modelKey: external_exports.string(),
  format: modelCompatibilityTypeSchema,
  displayName: external_exports.string(),
  path: external_exports.string(),
  sizeBytes: external_exports.number().int(),
  paramsString: external_exports.string().optional(),
  architecture: external_exports.string().optional(),
  quantization: quantizationSchema.optional()
});
var modelInstanceInfoBaseSchema = modelInfoBaseSchema.extend({
  identifier: external_exports.string(),
  instanceReference: external_exports.string()
});
var embeddingModelAdditionalInfoSchema = external_exports.object({
  maxContextLength: external_exports.number().int()
});
var embeddingModelInstanceAdditionalInfoSchema = external_exports.object({
  contextLength: external_exports.number().int()
});
var embeddingModelInfoSchema = external_exports.object({
  type: external_exports.literal("embedding")
}).extend(modelInfoBaseSchema.shape).extend(embeddingModelAdditionalInfoSchema.shape);
var embeddingModelInstanceInfoSchema = external_exports.object({ type: external_exports.literal("embedding") }).extend(modelInstanceInfoBaseSchema.shape).extend(embeddingModelAdditionalInfoSchema.shape).extend(embeddingModelInstanceAdditionalInfoSchema.shape);
var modelDomainTypeSchema = external_exports.enum([
  "llm",
  "embedding",
  "imageGen",
  "transcription",
  "tts"
]);
var reasonableKeyStringSchema = external_exports.string().min(1).max(1024).refine((value) => value !== "__proto__", {
  message: 'For security reasons, "__proto__" is not allowed'
}).refine((value) => new RegExp("\\p{C}", "u").test(value) === false, {
  message: "Control characters are not allowed"
});
var modelQuerySchema = external_exports.object({
  domain: modelDomainTypeSchema.optional(),
  identifier: reasonableKeyStringSchema.optional(),
  path: reasonableKeyStringSchema.optional(),
  vision: external_exports.boolean().optional()
});
var modelSpecifierSchema = external_exports.discriminatedUnion("type", [
  external_exports.object({
    type: external_exports.literal("query"),
    query: modelQuerySchema
  }),
  external_exports.object({
    type: external_exports.literal("instanceReference"),
    instanceReference: external_exports.string()
  })
]);
var genericErrorDisplayDataSchema = [
  external_exports.object({
    code: external_exports.literal("generic.specificModelUnloaded")
  }),
  external_exports.object({
    code: external_exports.literal("generic.noModelMatchingQuery"),
    query: modelQuerySchema,
    loadedModelsSample: external_exports.array(external_exports.string()),
    totalLoadedModels: external_exports.number().int()
  }),
  external_exports.object({
    code: external_exports.literal("generic.pathNotFound"),
    path: external_exports.string(),
    availablePathsSample: external_exports.array(external_exports.string()),
    totalModels: external_exports.number().int()
  }),
  external_exports.object({
    code: external_exports.literal("generic.identifierNotFound"),
    identifier: external_exports.string(),
    loadedModelsSample: external_exports.array(external_exports.string()),
    totalLoadedModels: external_exports.number().int()
  }),
  external_exports.object({
    code: external_exports.literal("generic.domainMismatch"),
    path: external_exports.string(),
    actualDomain: modelDomainTypeSchema,
    expectedDomain: modelDomainTypeSchema
  }),
  external_exports.object({
    code: external_exports.literal("generic.engineDoesNotSupportFeature"),
    feature: external_exports.string(),
    engineName: external_exports.string(),
    engineType: external_exports.string(),
    installedVersion: external_exports.string(),
    supportedVersion: external_exports.string().nullable()
  }),
  external_exports.object({
    code: external_exports.literal("generic.presetNotFound"),
    specifiedFuzzyPresetIdentifier: external_exports.string(),
    availablePresetsSample: external_exports.array(external_exports.object({
      identifier: external_exports.string(),
      name: external_exports.string()
    })),
    totalAvailablePresets: external_exports.number().int()
  })
];
var llmErrorDisplayDataSchema = [];
var errorDisplayDataSchema = external_exports.discriminatedUnion("code", [
  ...llmErrorDisplayDataSchema,
  ...genericErrorDisplayDataSchema
]);
function failOk(schema) {
  return external_exports.any().transform((val2) => schema.safeParse(val2).success ? val2 : void 0);
}
var serializedLMSExtendedErrorSchema = external_exports.object({
  title: failOk(external_exports.string()).default("Unknown error"),
  cause: failOk(external_exports.string()).optional(),
  suggestion: failOk(external_exports.string()).optional(),
  errorData: failOk(external_exports.record(external_exports.string(), external_exports.unknown())).optional(),
  displayData: failOk(errorDisplayDataSchema).optional(),
  stack: failOk(external_exports.string()).optional(),
  rootTitle: failOk(external_exports.string()).optional()
});
function serializeError(error) {
  if (typeof error === "object") {
    const title = error.title ?? error.lmstudioRawError ?? error.message ?? "Unknown error";
    return serializedLMSExtendedErrorSchema.parse({
      title,
      cause: error.cause,
      suggestion: error.suggestion,
      errorData: error.errorData,
      displayData: error.displayData,
      stack: error.stack,
      rootTitle: title
    });
  } else {
    const title = String(error);
    return {
      title,
      rootTitle: title
    };
  }
}
function attachSerializedErrorData(error, serialized) {
  const untypedError = error;
  untypedError.title = serialized.title;
  if (serialized.cause !== void 0) {
    untypedError.cause = serialized.cause;
  }
  if (serialized.suggestion !== void 0) {
    untypedError.suggestion = serialized.suggestion;
  }
  if (serialized.errorData !== void 0) {
    untypedError.errorData = serialized.errorData;
  }
}
function fromSerializedError(error, message = "Rehydrated error", replacementStack) {
  const result = new Error(error.rootTitle);
  attachSerializedErrorData(result, error);
  if (error.displayData !== void 0) {
    result.displayData = error.displayData;
  }
  if (replacementStack !== void 0) {
    if (error.stack !== void 0) {
      result.stack = `Error: ${message}
${replacementStack}
- Caused By: ${error.stack}`;
    } else {
      result.stack = `Error: ${message}
${replacementStack}`;
    }
  } else {
    if (error.stack !== void 0) {
      result.stack = `Error: ${message}
${result.stack.substring(error.stack.indexOf("\n") + 1)}
- Caused By: ` + error.stack;
    } else {
      result.message += ` - caused by error without stack (${error.title})`;
    }
  }
  return result;
}
var documentParsingLibraryIdentifierSchema = external_exports.object({
  library: external_exports.string(),
  version: external_exports.string()
});
var documentParsingOptsSchema = external_exports.object({
  parserId: documentParsingLibraryIdentifierSchema.optional()
});
external_exports.enum(["local", "base64"]);
external_exports.discriminatedUnion("type", [
  external_exports.object({
    type: external_exports.literal("local"),
    fileName: external_exports.string()
  }),
  external_exports.object({
    type: external_exports.literal("base64"),
    base64Data: external_exports.string()
  })
]);
var gpuSplitStrategies = ["evenly", "priorityOrder", "custom"];
var gpuSplitStrategySchema = external_exports.enum(gpuSplitStrategies);
var defaultGPUSplitConfig = {
  strategy: "evenly",
  disabledGpus: [],
  priority: [],
  customRatio: []
};
var gpuSplitConfigSchema = external_exports.object({
  strategy: gpuSplitStrategySchema,
  disabledGpus: external_exports.array(external_exports.number().int().min(0)),
  priority: external_exports.array(external_exports.number().int().min(0)),
  customRatio: external_exports.array(external_exports.number().min(0))
});
function convertGPUSettingToGPUSplitConfig(gpuSetting) {
  return {
    strategy: gpuSetting?.splitStrategy == "favorMainGpu" ? "priorityOrder" : gpuSetting?.splitStrategy ?? "evenly",
    disabledGpus: gpuSetting?.disabledGpus ?? [],
    priority: gpuSetting?.mainGpu ? [gpuSetting.mainGpu] : [],
    customRatio: []
  };
}
var kvConfigFieldSchema = external_exports.object({
  key: external_exports.string(),
  value: external_exports.any()
});
var kvConfigSchema = external_exports.object({
  fields: external_exports.array(kvConfigFieldSchema)
});
var kvConfigLayerNameSchema = external_exports.enum([
  "currentlyEditing",
  "currentlyLoaded",
  "apiOverride",
  "conversationSpecific",
  "conversationGlobal",
  "preset",
  "serverSession",
  "httpServerRequestOverride",
  "completeModeFormatting",
  "instance",
  "userModelDefault",
  "virtualModel",
  "modelDefault",
  "hardware"
]);
var kvConfigStackLayerSchema = external_exports.object({
  layerName: kvConfigLayerNameSchema,
  config: kvConfigSchema
});
var kvConfigStackSchema = external_exports.object({
  layers: external_exports.array(kvConfigStackLayerSchema)
});
var kvConfigFieldDependencySchema = external_exports.object({
  key: external_exports.string(),
  condition: external_exports.discriminatedUnion("type", [
    external_exports.object({ type: external_exports.literal("equals"), value: external_exports.any() }),
    external_exports.object({ type: external_exports.literal("notEquals"), value: external_exports.any() })
  ])
});
var contentBlockStyleSchema = external_exports.discriminatedUnion("type", [
  external_exports.object({
    type: external_exports.literal("default")
  }),
  external_exports.object({
    type: external_exports.literal("customLabel"),
    label: external_exports.string(),
    color: external_exports.optional(colorPaletteSchema)
  }),
  external_exports.object({
    type: external_exports.literal("thinking"),
    ended: external_exports.boolean().optional(),
    title: external_exports.string().optional()
  })
]);
var llmToolParametersSchema = external_exports.discriminatedUnion("type", [
  external_exports.object({
    type: external_exports.literal("object"),
    properties: external_exports.record(jsonSerializableSchema),
    required: external_exports.array(external_exports.string()).optional(),
    additionalProperties: external_exports.boolean().optional(),
    $defs: external_exports.record(jsonSerializableSchema).optional()
  })
  // add more parameter types here
  // ...
]);
var llmToolSchema = external_exports.discriminatedUnion("type", [
  external_exports.object({
    type: external_exports.literal("function"),
    function: external_exports.object({
      name: external_exports.string(),
      description: external_exports.string().optional(),
      parameters: llmToolParametersSchema.optional()
    })
  })
  // add more tool types here
  // ...
]);
external_exports.array(llmToolSchema);
var llmToolUseSettingSchema = external_exports.discriminatedUnion("type", [
  external_exports.object({
    type: external_exports.literal("none")
  }),
  external_exports.object({
    type: external_exports.literal("toolArray"),
    tools: external_exports.array(llmToolSchema).optional(),
    force: external_exports.boolean().optional()
  })
]);
var llmApplyPromptTemplateOptsSchema = external_exports.object({
  omitBosToken: external_exports.boolean().optional(),
  omitEosToken: external_exports.boolean().optional(),
  toolDefinitions: external_exports.array(llmToolSchema).optional()
});
var llmContextReferenceSchema = external_exports.discriminatedUnion("type", [
  external_exports.object({
    type: external_exports.literal("jsonFile"),
    absPath: external_exports.string()
  }),
  external_exports.object({
    type: external_exports.literal("yamlFile"),
    absPath: external_exports.string()
  })
]);
external_exports.array(external_exports.object({
  role: external_exports.enum(["user", "assistant", "system"]),
  content: external_exports.string()
}));
external_exports.array(external_exports.union([
  external_exports.object({
    system: external_exports.string()
  }),
  external_exports.object({
    user: external_exports.string()
  }),
  external_exports.object({
    assistant: external_exports.string()
  })
]));
var llmAdditionalInfoSchema = external_exports.object({
  vision: external_exports.boolean(),
  trainedForToolUse: external_exports.boolean(),
  maxContextLength: external_exports.number().int()
});
var llmInstanceAdditionalInfoSchema = external_exports.object({
  contextLength: external_exports.number().int()
});
var llmInfoSchema = external_exports.object({
  type: external_exports.literal("llm")
}).extend(modelInfoBaseSchema.shape).extend(llmAdditionalInfoSchema.shape);
var llmInstanceInfoSchema = external_exports.object({
  type: external_exports.literal("llm")
}).extend(modelInstanceInfoBaseSchema.shape).extend(llmAdditionalInfoSchema.shape).extend(llmInstanceAdditionalInfoSchema.shape);
var toolNamingSchema = external_exports.enum(["passThrough", "removeSpecial", "snakeCase", "camelCase"]);
var zodSchemaSchema = external_exports.custom((value) => {
  if (typeof value?.parse !== "function") {
    return false;
  }
  return true;
}, "Expected a zod schema");
var llmManualPromptTemplateSchema = external_exports.object({
  beforeSystem: external_exports.string(),
  afterSystem: external_exports.string(),
  beforeUser: external_exports.string(),
  afterUser: external_exports.string(),
  beforeAssistant: external_exports.string(),
  afterAssistant: external_exports.string()
});
var llmJinjaPromptTemplateSchema = external_exports.object({
  template: external_exports.string()
});
var llmPromptTemplateTypeSchema = external_exports.enum(["manual", "jinja"]);
var llmPromptTemplateSchema = external_exports.object({
  type: llmPromptTemplateTypeSchema,
  manualPromptTemplate: llmManualPromptTemplateSchema.optional(),
  jinjaPromptTemplate: llmJinjaPromptTemplateSchema.optional(),
  stopStrings: external_exports.array(external_exports.string())
});
var llmStructuredPredictionTypeSchema = external_exports.enum(["none", "json", "gbnf"]);
var llmStructuredPredictionSettingSchema = external_exports.object({
  type: llmStructuredPredictionTypeSchema,
  jsonSchema: jsonSerializableSchema.optional(),
  gbnfGrammar: external_exports.string().optional()
});
var llmContextOverflowPolicySchema = external_exports.enum([
  "stopAtLimit",
  "truncateMiddle",
  "rollingWindow"
]);
var llmReasoningParsingSchema = external_exports.object({
  enabled: external_exports.boolean(),
  startString: external_exports.string(),
  endString: external_exports.string()
});
var llmPredictionConfigInputSchema = external_exports.object({
  maxTokens: external_exports.number().int().min(-1).optional().or(external_exports.literal(false)),
  temperature: external_exports.number().min(0).optional(),
  stopStrings: external_exports.array(external_exports.string()).optional(),
  toolCallStopStrings: external_exports.array(external_exports.string()).optional(),
  contextOverflowPolicy: llmContextOverflowPolicySchema.optional(),
  structured: external_exports.union([zodSchemaSchema, llmStructuredPredictionSettingSchema]).optional(),
  rawTools: llmToolUseSettingSchema.optional(),
  toolNaming: toolNamingSchema.optional(),
  topKSampling: external_exports.number().optional(),
  repeatPenalty: external_exports.number().optional().or(external_exports.literal(false)),
  minPSampling: external_exports.number().optional().or(external_exports.literal(false)),
  topPSampling: external_exports.number().optional().or(external_exports.literal(false)),
  cpuThreads: external_exports.number().int().optional(),
  promptTemplate: llmPromptTemplateSchema.optional(),
  draftModel: external_exports.string().optional(),
  speculativeDecodingNumDraftTokensExact: external_exports.number().int().min(1).optional(),
  speculativeDecodingMinDraftLengthToConsider: external_exports.number().int().min(0).optional(),
  speculativeDecodingMinContinueDraftingProbability: external_exports.number().optional(),
  reasoningParsing: llmReasoningParsingSchema.optional(),
  raw: kvConfigSchema.optional()
});
external_exports.object({
  ...llmPredictionConfigInputSchema.shape,
  structured: llmStructuredPredictionSettingSchema.optional()
});
var llmLlamaMirostatSamplingConfigSchema = external_exports.object({
  version: external_exports.union([external_exports.literal(0), external_exports.literal(1), external_exports.literal(2)]),
  learningRate: external_exports.number(),
  targetEntropy: external_exports.number()
});
var llmLlamaSingleLogitBiasModificationSchema = external_exports.union([external_exports.number(), external_exports.literal("-inf")]);
var llmLlamaLogitBiasConfigSchema = external_exports.array(external_exports.tuple([external_exports.number(), llmLlamaSingleLogitBiasModificationSchema]));
var llmPredictionFragmentReasoningTypeSchema = external_exports.enum([
  "none",
  "reasoning",
  "reasoningStartTag",
  "reasoningEndTag"
]);
var llmPredictionFragmentSchema = external_exports.object({
  content: external_exports.string(),
  tokensCount: external_exports.number().int(),
  containsDrafted: external_exports.boolean(),
  reasoningType: llmPredictionFragmentReasoningTypeSchema,
  isStructural: external_exports.boolean()
});
var llmPredictionFragmentInputOptsSchema = external_exports.object({
  tokenCount: external_exports.number().int().optional(),
  containsDrafted: external_exports.boolean().optional(),
  reasoningType: llmPredictionFragmentReasoningTypeSchema.optional(),
  isStructural: external_exports.boolean().optional()
});
var llmPredictionStopReasonSchema = external_exports.enum([
  "userStopped",
  "modelUnloaded",
  "failed",
  "eosFound",
  "stopStringFound",
  "toolCalls",
  "maxPredictedTokensReached",
  "contextLengthReached"
]);
var llmPredictionStatsSchema = external_exports.object({
  stopReason: llmPredictionStopReasonSchema,
  tokensPerSecond: external_exports.number().optional(),
  numGpuLayers: external_exports.number().optional(),
  timeToFirstTokenSec: external_exports.number().optional(),
  totalTimeSec: external_exports.number().optional(),
  promptTokensCount: external_exports.number().int().optional(),
  predictedTokensCount: external_exports.number().int().optional(),
  totalTokensCount: external_exports.number().int().optional(),
  usedDraftModelKey: external_exports.string().optional(),
  totalDraftTokensCount: external_exports.number().int().optional(),
  acceptedDraftTokensCount: external_exports.number().int().optional(),
  rejectedDraftTokensCount: external_exports.number().int().optional(),
  ignoredDraftTokensCount: external_exports.number().int().optional()
});
var llmGenInfoSchema = external_exports.object({
  indexedModelIdentifier: external_exports.string(),
  identifier: external_exports.string(),
  loadModelConfig: kvConfigSchema,
  predictionConfig: kvConfigSchema,
  stats: llmPredictionStatsSchema
});
var blockLocationSchema = external_exports.discriminatedUnion("type", [
  external_exports.object({
    type: external_exports.literal("beforeId"),
    id: external_exports.string()
  }),
  external_exports.object({
    type: external_exports.literal("afterId"),
    id: external_exports.string()
  })
]);
var statusStepStatusSchema = external_exports.enum([
  "waiting",
  "loading",
  "done",
  "error",
  "canceled"
]);
var statusStepStateSchema = external_exports.object({
  status: statusStepStatusSchema,
  text: external_exports.string()
});
var processingUpdateStatusCreateSchema = external_exports.object({
  type: external_exports.literal("status.create"),
  id: external_exports.string(),
  state: statusStepStateSchema,
  location: blockLocationSchema.optional(),
  indentation: external_exports.number().int().optional()
});
var processingUpdateStatusUpdateSchema = external_exports.object({
  type: external_exports.literal("status.update"),
  id: external_exports.string(),
  state: statusStepStateSchema
});
var processingUpdateStatusRemoveSchema = external_exports.object({
  type: external_exports.literal("status.remove"),
  id: external_exports.string()
});
var processingUpdateCitationBlockCreateSchema = external_exports.object({
  type: external_exports.literal("citationBlock.create"),
  id: external_exports.string(),
  citedText: external_exports.string(),
  fileName: external_exports.string(),
  fileIdentifier: external_exports.string(),
  pageNumber: external_exports.union([external_exports.number().int(), external_exports.tuple([external_exports.number().int(), external_exports.number().int()])]).optional(),
  lineNumber: external_exports.union([external_exports.number().int(), external_exports.tuple([external_exports.number().int(), external_exports.number().int()])]).optional()
});
var processingUpdateDebugInfoBlockCreateSchema = external_exports.object({
  type: external_exports.literal("debugInfoBlock.create"),
  id: external_exports.string(),
  debugInfo: external_exports.string()
});
var processingUpdateContentBlockCreateSchema = external_exports.object({
  type: external_exports.literal("contentBlock.create"),
  id: external_exports.string(),
  includeInContext: external_exports.boolean(),
  roleOverride: external_exports.enum(["user", "assistant", "system", "tool"]).optional(),
  style: contentBlockStyleSchema.optional(),
  prefix: external_exports.string().optional(),
  suffix: external_exports.string().optional()
});
var processingUpdateContentBlockAppendTextSchema = external_exports.object({
  type: external_exports.literal("contentBlock.appendText"),
  id: external_exports.string(),
  text: external_exports.string(),
  tokensCount: external_exports.number().int().optional(),
  fromDraftModel: external_exports.boolean().optional(),
  isStructural: external_exports.boolean().optional()
});
var processingUpdateContentBlockAppendToolResultSchema = external_exports.object({
  type: external_exports.literal("contentBlock.appendToolResult"),
  id: external_exports.string(),
  callId: external_exports.number().int(),
  toolCallRequestId: external_exports.string().optional(),
  content: external_exports.string()
});
var processingUpdateContentBlockAppendToolRequestSchema = external_exports.object({
  type: external_exports.literal("contentBlock.appendToolRequest"),
  id: external_exports.string(),
  callId: external_exports.number().int(),
  toolCallRequestId: external_exports.string().optional(),
  name: external_exports.string(),
  parameters: external_exports.record(external_exports.unknown()),
  pluginIdentifier: external_exports.string().optional()
});
var processingUpdateContentBlockReplaceToolRequestSchema = external_exports.object({
  type: external_exports.literal("contentBlock.replaceToolRequest"),
  id: external_exports.string(),
  callId: external_exports.number().int(),
  toolCallRequestId: external_exports.string().optional(),
  name: external_exports.string(),
  parameters: external_exports.record(external_exports.unknown()),
  pluginIdentifier: external_exports.string().optional()
});
var processingUpdateContentBlockReplaceTextSchema = external_exports.object({
  type: external_exports.literal("contentBlock.replaceText"),
  id: external_exports.string(),
  text: external_exports.string()
});
var processingUpdateContentBlockSetPrefixSchema = external_exports.object({
  type: external_exports.literal("contentBlock.setPrefix"),
  id: external_exports.string(),
  prefix: external_exports.string()
});
var processingUpdateContentBlockSetSuffixSchema = external_exports.object({
  type: external_exports.literal("contentBlock.setSuffix"),
  id: external_exports.string(),
  suffix: external_exports.string()
});
var processingUpdateContentBlockAttachGenInfoSchema = external_exports.object({
  type: external_exports.literal("contentBlock.attachGenInfo"),
  id: external_exports.string(),
  genInfo: llmGenInfoSchema
});
var processingUpdateContentBlockSetStyleSchema = external_exports.object({
  type: external_exports.literal("contentBlock.setStyle"),
  id: external_exports.string(),
  style: contentBlockStyleSchema
});
var toolStatusStepStateStatusSchema = external_exports.discriminatedUnion("type", [
  external_exports.object({
    type: external_exports.literal("generatingToolCall"),
    name: external_exports.string().optional(),
    pluginIdentifier: external_exports.string().optional(),
    argumentsString: external_exports.string().optional()
  }),
  external_exports.object({
    type: external_exports.literal("toolCallGenerationFailed"),
    error: external_exports.string(),
    rawContent: external_exports.string().optional()
  }),
  external_exports.object({
    type: external_exports.literal("toolCallQueued")
  }),
  external_exports.object({
    type: external_exports.literal("confirmingToolCall")
  }),
  external_exports.object({
    type: external_exports.literal("toolCallDenied"),
    denyReason: external_exports.string().optional()
  }),
  external_exports.object({
    type: external_exports.literal("callingTool")
  }),
  external_exports.object({
    type: external_exports.literal("toolCallFailed"),
    error: external_exports.string()
  }),
  external_exports.object({
    type: external_exports.literal("toolCallSucceeded"),
    timeMs: external_exports.number().int()
  })
]);
var toolStatusStepStateSchema = external_exports.object({
  status: toolStatusStepStateStatusSchema,
  customStatus: external_exports.string(),
  customWarnings: external_exports.array(external_exports.string())
});
var processingUpdateToolStatusCreateSchema = external_exports.object({
  type: external_exports.literal("toolStatus.create"),
  id: external_exports.string(),
  callId: external_exports.number().int(),
  state: toolStatusStepStateSchema
});
var processingUpdateToolStatusUpdateSchema = external_exports.object({
  type: external_exports.literal("toolStatus.update"),
  id: external_exports.string(),
  state: toolStatusStepStateSchema
});
var processingUpdateToolStatusArgumentFragmentSchema = external_exports.object({
  type: external_exports.literal("toolStatus.argumentFragment"),
  id: external_exports.string(),
  content: external_exports.string()
});
var processingUpdateSetSenderNameSchema = external_exports.object({
  type: external_exports.literal("setSenderName"),
  name: external_exports.string()
});
var processingUpdateSchema = external_exports.discriminatedUnion("type", [
  processingUpdateStatusCreateSchema,
  processingUpdateStatusUpdateSchema,
  processingUpdateStatusRemoveSchema,
  processingUpdateCitationBlockCreateSchema,
  processingUpdateDebugInfoBlockCreateSchema,
  processingUpdateContentBlockCreateSchema,
  processingUpdateContentBlockAppendTextSchema,
  processingUpdateContentBlockAppendToolRequestSchema,
  processingUpdateContentBlockReplaceToolRequestSchema,
  processingUpdateContentBlockAppendToolResultSchema,
  processingUpdateContentBlockReplaceTextSchema,
  processingUpdateContentBlockSetPrefixSchema,
  processingUpdateContentBlockSetSuffixSchema,
  processingUpdateContentBlockAttachGenInfoSchema,
  processingUpdateContentBlockSetStyleSchema,
  processingUpdateToolStatusCreateSchema,
  processingUpdateToolStatusUpdateSchema,
  processingUpdateToolStatusArgumentFragmentSchema,
  processingUpdateSetSenderNameSchema
]);
external_exports.discriminatedUnion("type", [
  processingUpdateStatusCreateSchema,
  processingUpdateStatusUpdateSchema,
  processingUpdateStatusRemoveSchema,
  processingUpdateCitationBlockCreateSchema,
  processingUpdateDebugInfoBlockCreateSchema,
  processingUpdateContentBlockCreateSchema,
  processingUpdateContentBlockAppendTextSchema,
  processingUpdateContentBlockReplaceTextSchema,
  processingUpdateContentBlockAppendToolRequestSchema,
  processingUpdateContentBlockReplaceToolRequestSchema,
  processingUpdateContentBlockAppendToolResultSchema,
  processingUpdateContentBlockAttachGenInfoSchema,
  processingUpdateContentBlockSetStyleSchema,
  processingUpdateToolStatusCreateSchema,
  processingUpdateToolStatusUpdateSchema,
  processingUpdateToolStatusArgumentFragmentSchema,
  processingUpdateSetSenderNameSchema
]);
var processingRequestConfirmToolCallSchema = external_exports.object({
  type: external_exports.literal("confirmToolCall"),
  callId: external_exports.number().int(),
  pluginIdentifier: external_exports.string().optional(),
  name: external_exports.string(),
  parameters: external_exports.record(external_exports.any())
});
var processingRequestTextInputSchema = external_exports.object({
  type: external_exports.literal("textInput"),
  prompt: external_exports.string()
});
var processingRequestSchema = external_exports.discriminatedUnion("type", [
  processingRequestConfirmToolCallSchema,
  processingRequestTextInputSchema
]);
var processingRequestResponseConfirmToolCallSchema = external_exports.object({
  type: external_exports.literal("confirmToolCall"),
  result: external_exports.discriminatedUnion("type", [
    external_exports.object({
      type: external_exports.literal("allow"),
      toolArgsOverride: external_exports.record(external_exports.any()).optional()
    }),
    external_exports.object({
      type: external_exports.literal("deny"),
      denyReason: external_exports.string().optional()
    })
  ])
});
var processingRequestResponseTextInputSchema = external_exports.object({
  type: external_exports.literal("textInput"),
  result: external_exports.string()
});
var processingRequestResponseSchema = external_exports.discriminatedUnion("type", [
  processingRequestResponseConfirmToolCallSchema,
  processingRequestResponseTextInputSchema
]);
external_exports.object({
  modelTag: external_exports.string().optional(),
  ignoreUserConfig: external_exports.boolean().optional()
});
external_exports.discriminatedUnion("type", [
  processingUpdateStatusCreateSchema,
  processingUpdateStatusUpdateSchema,
  processingUpdateStatusRemoveSchema,
  processingUpdateCitationBlockCreateSchema,
  processingUpdateDebugInfoBlockCreateSchema
]);
var tokenSourceIdentifierSchema = external_exports.discriminatedUnion("type", [
  external_exports.object({
    type: external_exports.literal("model"),
    identifier: external_exports.string()
  }),
  external_exports.object({
    type: external_exports.literal("generator"),
    pluginIdentifier: external_exports.string()
  })
]);
var modelInfoSchema = external_exports.discriminatedUnion("type", [
  llmInfoSchema,
  embeddingModelInfoSchema
]);
var modelInstanceInfoSchema = external_exports.discriminatedUnion("type", [
  llmInstanceInfoSchema,
  embeddingModelInstanceInfoSchema
]);
var pluginConfigSpecifierSchema = external_exports.discriminatedUnion("type", [
  external_exports.object({
    type: external_exports.literal("direct"),
    config: kvConfigSchema,
    workingDirectoryPath: external_exports.string().optional()
  }),
  external_exports.object({
    type: external_exports.literal("predictionProcess"),
    pci: external_exports.string(),
    token: external_exports.string()
  })
]);
var remotePluginInfoSchema = external_exports.object({
  identifier: external_exports.string(),
  isDev: external_exports.boolean(),
  isTrusted: external_exports.boolean(),
  hasPromptPreprocessor: external_exports.boolean(),
  hasPredictionLoopHandler: external_exports.boolean(),
  hasToolsProvider: external_exports.boolean(),
  hasGenerator: external_exports.boolean()
});
var artifactDownloadPlanModelInfoSchema = external_exports.object({
  displayName: external_exports.string(),
  sizeBytes: external_exports.number(),
  quantName: external_exports.string().optional(),
  compatibilityType: modelCompatibilityTypeSchema
});
var artifactDownloadPlanNodeStateSchema = external_exports.enum(["pending", "fetching", "satisfied", "completed"]);
var artifactDownloadPlanNodeSchema = external_exports.discriminatedUnion("type", [
  external_exports.object({
    type: external_exports.literal("artifact"),
    owner: kebabCaseSchema,
    name: kebabCaseWithDotsSchema,
    state: artifactDownloadPlanNodeStateSchema,
    artifactType: artifactTypeSchema.optional(),
    sizeBytes: external_exports.number().int().optional(),
    dependencyNodes: external_exports.array(external_exports.number().int())
  }),
  external_exports.object({
    type: external_exports.literal("model"),
    state: artifactDownloadPlanNodeStateSchema,
    resolvedSources: external_exports.number().int().optional(),
    totalSources: external_exports.number().int().optional(),
    alreadyOwned: artifactDownloadPlanModelInfoSchema.optional(),
    selected: artifactDownloadPlanModelInfoSchema.optional()
  })
]);
var artifactDownloadPlanSchema = external_exports.object({
  nodes: external_exports.array(artifactDownloadPlanNodeSchema),
  downloadSizeBytes: external_exports.number().int()
});
var localArtifactFileEntrySchema = external_exports.object({
  relativePath: external_exports.string(),
  sizeBytes: external_exports.number().int()
});
var localArtifactFileListSchema = external_exports.object({
  files: external_exports.array(localArtifactFileEntrySchema),
  usedIgnoreFile: external_exports.string().nullable()
});
var downloadProgressUpdateSchema = external_exports.object({
  downloadedBytes: external_exports.number().int(),
  totalBytes: external_exports.number().int(),
  speedBytesPerSecond: external_exports.number()
});
var modelSearchResultDownloadOptionFitEstimationSchema = external_exports.enum([
  "fullGPUOffload",
  "partialGPUOffload",
  "fitWithoutGPU",
  "willNotFit"
]);
var modelSearchResultDownloadOptionDataSchema = external_exports.object({
  quantization: external_exports.string().optional(),
  name: external_exports.string(),
  sizeBytes: external_exports.number().int(),
  fitEstimation: modelSearchResultDownloadOptionFitEstimationSchema,
  recommended: external_exports.boolean().optional(),
  downloadIdentifier: external_exports.string(),
  indexedModelIdentifier: external_exports.string()
});
var modelSearchResultIdentifierSchema = external_exports.discriminatedUnion("type", [
  external_exports.object({
    type: external_exports.literal("catalog"),
    identifier: external_exports.string()
  }),
  external_exports.object({
    type: external_exports.literal("hf"),
    identifier: external_exports.string()
  })
]);
var modelSearchResultEntryDataSchema = external_exports.object({
  name: external_exports.string(),
  identifier: modelSearchResultIdentifierSchema,
  exact: external_exports.boolean().optional(),
  staffPick: external_exports.boolean().optional()
});
var modelSearchOptsSchema = external_exports.object({
  searchTerm: external_exports.string().optional(),
  limit: external_exports.number().int().positive().max(25).optional(),
  compatibilityTypes: external_exports.array(modelCompatibilityTypeSchema).optional()
});
var internalRetrievalResultEntrySchema = external_exports.object({
  content: external_exports.string(),
  score: external_exports.number(),
  sourceIndex: external_exports.number().int(),
  pageNumber: external_exports.union([external_exports.number().int(), external_exports.tuple([external_exports.number().int(), external_exports.number().int()])]).optional(),
  lineNumber: external_exports.union([external_exports.number().int(), external_exports.tuple([external_exports.number().int(), external_exports.number().int()])]).optional()
});
var internalRetrievalResultSchema = external_exports.object({
  entries: external_exports.array(internalRetrievalResultEntrySchema)
});
external_exports.object({
  content: external_exports.string(),
  score: external_exports.number(),
  citation: citationSourceSchema
});
var retrievalChunkingMethodSchema = external_exports.discriminatedUnion("type", [
  external_exports.object({
    type: external_exports.literal("recursive-v1"),
    chunkSize: external_exports.number().int(),
    chunkOverlap: external_exports.number().int()
  })
]);
var retrievalFileProcessingStepSchema = external_exports.enum(["loading", "chunking", "embedding"]);
var acceleratorTypeSchema = external_exports.enum(["unknown", "integratedGpu", "dedicatedGpu"]);
var acceleratorSchema = external_exports.object({
  name: external_exports.string(),
  deviceId: external_exports.number().int(),
  totalMemoryBytes: external_exports.number().int(),
  type: acceleratorTypeSchema
});
external_exports.object({
  key: external_exports.string(),
  name: external_exports.string(),
  accelerators: external_exports.array(acceleratorSchema)
});
var serializedKVConfigSchematicsFieldSchema = external_exports.object({
  shortKey: external_exports.string(),
  fullKey: external_exports.string(),
  typeKey: external_exports.string(),
  typeParams: jsonSerializableSchema,
  defaultValue: jsonSerializableSchema
});
var serializedKVConfigSchematicsSchema = external_exports.object({
  fields: external_exports.array(serializedKVConfigSchematicsFieldSchema),
  extensionPrefixes: external_exports.array(external_exports.string()).optional()
});
external_exports.object({
  fullKey: external_exports.string(),
  error: jsonSerializableSchema
});
var booleanOrMixedSchema = external_exports.union([
  external_exports.literal(true),
  external_exports.literal(false),
  external_exports.literal("mixed")
]);
var virtualModelDefinitionMetadataOverridesSchema = external_exports.object({
  domain: modelDomainTypeSchema.optional(),
  architectures: external_exports.array(external_exports.string()).optional(),
  compatibilityTypes: external_exports.array(modelCompatibilityTypeSchema).optional(),
  paramsStrings: external_exports.array(external_exports.string()).optional(),
  minMemoryUsageBytes: external_exports.number().optional(),
  contextLengths: external_exports.array(external_exports.number()).optional(),
  trainedForToolUse: booleanOrMixedSchema.optional(),
  vision: booleanOrMixedSchema.optional(),
  reasoning: booleanOrMixedSchema.optional(),
  fim: booleanOrMixedSchema.optional()
});
var virtualModelDefinitionConcreteModelBaseSchema = external_exports.object({
  key: external_exports.string(),
  sources: external_exports.array(modelDownloadSourceSchema)
});
var virtualModelCustomFieldSetJinjaVariableEffectSchema = external_exports.object({
  type: external_exports.literal("setJinjaVariable"),
  variable: external_exports.string()
});
var virtualModelCustomFieldPrependSystemPromptEffectSchema = external_exports.object({
  type: external_exports.literal("prependSystemPrompt"),
  content: external_exports.string()
});
var virtualModelCustomFieldAppendSystemPromptEffectSchema = external_exports.object({
  type: external_exports.literal("appendSystemPrompt"),
  content: external_exports.string()
});
var virtualModelCustomFieldDefinitionBaseSchema = external_exports.object({
  key: external_exports.string(),
  displayName: external_exports.string(),
  description: external_exports.string()
});
var virtualModelBooleanCustomFieldDefinitionSchema = virtualModelCustomFieldDefinitionBaseSchema.extend({
  type: external_exports.literal("boolean"),
  defaultValue: external_exports.boolean(),
  effects: external_exports.array(external_exports.discriminatedUnion("type", [
    virtualModelCustomFieldSetJinjaVariableEffectSchema,
    virtualModelCustomFieldPrependSystemPromptEffectSchema,
    virtualModelCustomFieldAppendSystemPromptEffectSchema
  ]))
});
var virtualModelStringCustomFieldDefinitionSchema = virtualModelCustomFieldDefinitionBaseSchema.extend({
  type: external_exports.literal("string"),
  defaultValue: external_exports.string(),
  effects: external_exports.array(external_exports.discriminatedUnion("type", [virtualModelCustomFieldSetJinjaVariableEffectSchema]))
});
var virtualModelSelectCustomFieldDefinitionSchema = virtualModelCustomFieldDefinitionBaseSchema.extend({
  type: external_exports.literal("select"),
  options: external_exports.array(external_exports.object({
    label: external_exports.string(),
    value: external_exports.string()
  })),
  defaultValue: external_exports.string(),
  effects: external_exports.array(external_exports.discriminatedUnion("type", [virtualModelCustomFieldSetJinjaVariableEffectSchema]))
});
var virtualModelCustomFieldDefinitionSchema = external_exports.discriminatedUnion("type", [
  virtualModelBooleanCustomFieldDefinitionSchema,
  virtualModelStringCustomFieldDefinitionSchema,
  virtualModelSelectCustomFieldDefinitionSchema
]);
var virtualModelConditionEqualsSchema = external_exports.object({
  type: external_exports.literal("equals"),
  key: external_exports.string(),
  value: jsonSerializableSchema
});
var virtualModelConditionSchema = external_exports.discriminatedUnion("type", [
  virtualModelConditionEqualsSchema
]);
var virtualModelSuggestionSchema = external_exports.object({
  message: external_exports.string(),
  conditions: external_exports.array(virtualModelConditionSchema),
  fields: external_exports.array(kvConfigFieldSchema).optional()
});
external_exports.object({
  model: external_exports.string().regex(/^[^/]+\/[^/]+$/),
  base: external_exports.union([external_exports.string(), external_exports.array(virtualModelDefinitionConcreteModelBaseSchema)]),
  tags: external_exports.array(external_exports.string().max(100)).optional(),
  config: external_exports.object({
    load: kvConfigSchema.optional(),
    operation: kvConfigSchema.optional()
  }).optional(),
  metadataOverrides: virtualModelDefinitionMetadataOverridesSchema.optional(),
  customFields: external_exports.array(virtualModelCustomFieldDefinitionSchema).optional(),
  suggestions: external_exports.array(virtualModelSuggestionSchema).optional()
});
var logLevelSchema = external_exports.enum(["debug", "info", "warn", "error"]);
function safeCallCallback(logger2, name, callback, args) {
  if (callback === void 0) {
    return;
  }
  try {
    const maybePromise = callback(...args);
    if (typeof maybePromise === "object" && typeof maybePromise.catch === "function") {
      maybePromise.catch((error) => {
        logger2.error(`Error in the ${name} callback (triggered asynchronously):`, error);
      });
    }
  } catch (error) {
    logger2.error(`Error in the ${name} callback:`, error);
  }
}
function isSimpleLogger(logger2) {
  return logger2?.isSimpleLogger === true;
}
var defaultInfoPrefix = import_chalk.default.greenBright("I");
var defaultWarnPrefix = import_chalk.default.yellowBright("W");
var defaultErrorPrefix = import_chalk.default.redBright("E");
var defaultDebugPrefix = import_chalk.default.blueBright("D");
var SimpleLogger = class _SimpleLogger {
  constructor(prefixText = "", parentLogger = console, { useLogLevelPrefixes, infoPrefix, warnPrefix, errorPrefix, debugPrefix } = {}) {
    this.isSimpleLogger = true;
    this.infoPrefix = [];
    this.warnPrefix = [];
    this.errorPrefix = [];
    this.debugPrefix = [];
    if (isSimpleLogger(parentLogger)) {
      useLogLevelPrefixes = useLogLevelPrefixes ?? parentLogger.opts.useLogLevelPrefixes;
      infoPrefix = infoPrefix === void 0 ? parentLogger.opts.infoPrefix : infoPrefix;
      warnPrefix = warnPrefix === void 0 ? parentLogger.opts.warnPrefix : warnPrefix;
      errorPrefix = errorPrefix === void 0 ? parentLogger.opts.errorPrefix : errorPrefix;
      debugPrefix = debugPrefix === void 0 ? parentLogger.opts.debugPrefix : debugPrefix;
      if (prefixText === "") {
        this.innerPrefix = parentLogger.innerPrefix;
        this.fullPrefix = parentLogger.fullPrefix;
      } else {
        if (parentLogger.fullPrefix === "") {
          this.innerPrefix = prefixText;
        } else {
          this.innerPrefix = `${parentLogger.innerPrefix}][${prefixText}`;
        }
        this.fullPrefix = import_chalk.default.whiteBright(`[${this.innerPrefix}]`);
      }
      this.parentLogger = parentLogger.parentLogger;
    } else {
      useLogLevelPrefixes = useLogLevelPrefixes ?? false;
      infoPrefix = infoPrefix === void 0 ? defaultInfoPrefix : infoPrefix;
      warnPrefix = warnPrefix === void 0 ? defaultWarnPrefix : warnPrefix;
      errorPrefix = errorPrefix === void 0 ? defaultErrorPrefix : errorPrefix;
      debugPrefix = debugPrefix === void 0 ? defaultDebugPrefix : debugPrefix;
      if (prefixText === "") {
        this.innerPrefix = "";
        this.fullPrefix = "";
      } else {
        this.innerPrefix = prefixText;
        this.fullPrefix = import_chalk.default.whiteBright(`[${this.innerPrefix}]`);
      }
      this.parentLogger = parentLogger;
    }
    if (useLogLevelPrefixes) {
      if (infoPrefix !== null) {
        this.infoPrefix.push(infoPrefix);
      }
      if (warnPrefix !== null) {
        this.warnPrefix.push(warnPrefix);
      }
      if (errorPrefix !== null) {
        this.errorPrefix.push(errorPrefix);
      }
      if (debugPrefix !== null) {
        this.debugPrefix.push(debugPrefix);
      }
    }
    if (this.fullPrefix !== "") {
      this.infoPrefix.push(this.fullPrefix);
      this.warnPrefix.push(this.fullPrefix);
      this.errorPrefix.push(this.fullPrefix);
      this.debugPrefix.push(this.fullPrefix);
    }
    this.opts = {
      useLogLevelPrefixes,
      infoPrefix,
      warnPrefix,
      errorPrefix,
      debugPrefix
    };
  }
  subclass(prefixText) {
    return new _SimpleLogger(`${this.innerPrefix}:${prefixText}`, this.parentLogger);
  }
  info(...messages) {
    this.parentLogger.info(...this.infoPrefix, ...messages);
  }
  infoText(strings, ...values2) {
    this.info(text(strings, ...values2));
  }
  infoWithoutPrefix(...messages) {
    this.parentLogger.info(...messages);
  }
  error(...messages) {
    this.parentLogger.error(...this.errorPrefix, ...messages);
  }
  errorText(strings, ...values2) {
    this.error(text(strings, ...values2));
  }
  errorWithoutPrefix(...messages) {
    this.parentLogger.error(...messages);
  }
  warn(...messages) {
    this.parentLogger.warn(...this.warnPrefix, ...messages);
  }
  warnText(strings, ...values2) {
    this.warn(text(strings, ...values2));
  }
  warnWithoutPrefix(...messages) {
    this.parentLogger.warn(...messages);
  }
  debug(...messages) {
    this.parentLogger.debug(...this.debugPrefix, ...messages);
  }
  debugText(strings, ...values2) {
    this.debug(text(strings, ...values2));
  }
  debugWithoutPrefix(...messages) {
    this.parentLogger.debug(...messages);
  }
  throw(message) {
    throw new Error(`${this.fullPrefix} ${message}`);
  }
  logAtLevel(level, ...messages) {
    switch (level) {
      case "debug":
        this.debug(...messages);
        break;
      case "info":
        this.info(...messages);
        break;
      case "warn":
        this.warn(...messages);
        break;
      case "error":
        this.error(...messages);
        break;
    }
  }
  static fromMultiple(loggers, opts) {
    return new _SimpleLogger("", {
      debug: (...messages) => {
        for (const logger2 of loggers) {
          logger2.debug(...messages);
        }
      },
      info: (...messages) => {
        for (const logger2 of loggers) {
          logger2.info(...messages);
        }
      },
      warn: (...messages) => {
        for (const logger2 of loggers) {
          logger2.warn(...messages);
        }
      },
      error: (...messages) => {
        for (const logger2 of loggers) {
          logger2.error(...messages);
        }
      }
    }, {
      ...opts,
      useLogLevelPrefixes: false
    });
  }
};
var _a5;
var finished = Symbol("finished");
var StreamablePromise = class {
  /**
   * Called by the producer when it has finished producing values. If an error is provided, the
   * promise will be rejected with that error. If no error is provided, the promise will be resolved
   * with the final value.
   *
   * This method should be exposed in the static constructor of the subclass.
   *
   * @param error - The error to reject the promise with, if any.
   */
  finished(error) {
    if (this.status !== "pending") {
      throw new Error("`finished` called while not pending");
    }
    if (error === void 0) {
      this.status = "resolved";
      this.nextFragmentPromiseBundle?.resolve(finished);
      this.resolveFinal(this.collect(this.buffer));
    } else {
      this.status = "rejected";
      this.nextFragmentPromiseBundle?.reject(error);
      this.rejectFinal(error);
    }
  }
  /**
   * Called by the producer to push a new fragment into the buffer. This method should be exposed in
   * the static constructor of the subclass.
   *
   * This method should be exposed in the static constructor of the subclass.
   *
   * @param fragment - The fragment to push into the buffer.
   */
  push(fragment) {
    if (this.status !== "pending") {
      throw new Error("`push` called while not pending");
    }
    this.buffer.push(fragment);
    this.nextFragmentPromiseBundle?.resolve(fragment);
    this.nextFragmentPromiseBundle = null;
  }
  constructor() {
    this.status = "pending";
    this.buffer = [];
    this.nextFragmentPromiseBundle = null;
    this.hasIterator = false;
    this[_a5] = "StreamablePromise";
    const { promise, resolve, reject } = makePromise();
    this.promiseFinal = promise;
    this.resolveFinal = resolve;
    this.rejectFinal = reject;
  }
  then(onfulfilled, onrejected) {
    return this.promiseFinal.then(onfulfilled, onrejected);
  }
  catch(onrejected) {
    return this.promiseFinal.catch(onrejected);
  }
  finally(onfinally) {
    return this.promiseFinal.finally(onfinally);
  }
  /**
   * If nextFragmentPromiseBundle exists, it is returned. Otherwise, a new one is created and
   * returned.
   */
  obtainNextFragmentPromiseBundle() {
    if (this.nextFragmentPromiseBundle === null) {
      this.nextFragmentPromiseBundle = makePromise();
    }
    return this.nextFragmentPromiseBundle;
  }
  async *[(_a5 = Symbol.toStringTag, Symbol.asyncIterator)]() {
    if (!this.hasIterator) {
      this.promiseFinal.catch(() => {
      });
      this.hasIterator = true;
    }
    let i7 = 0;
    while (i7 < this.buffer.length || this.status === "pending") {
      if (i7 < this.buffer.length) {
        yield this.buffer[i7];
        i7++;
      } else {
        const nextFragmentPromiseBundle = this.obtainNextFragmentPromiseBundle();
        const nextFragment = await nextFragmentPromiseBundle.promise;
        if (nextFragment === finished) {
          break;
        }
        yield nextFragment;
        i7++;
      }
    }
    await this.promiseFinal;
    await Promise.resolve();
  }
};
var Validator = class _Validator {
  constructor({ attachStack } = {}) {
    this.attachStack = attachStack ?? true;
  }
  /**
   * Pretty-prints a Zod error.
   *
   * @param rootObjectName - The name of the object being validated (used for error messages)
   * @param error - The Zod error to pretty-print
   *
   * @returns The pretty-printed error in a string
   */
  static prettyPrintZod(rootObjectName, error) {
    return error.errors.map((e9) => {
      if (e9.path.length === 0) {
        return `- ${import_chalk.default.redBright(rootObjectName)}: ${e9.message}`;
      }
      const path6 = import_chalk.default.red(`.${e9.path.join(".")}`);
      return `- ${import_chalk.default.redBright(rootObjectName)}${path6}: ${e9.message}`;
    }).join("\n");
  }
  /**
   * Validates a value against a schema and throws an error if it's invalid.
   *
   * @param lead - The start of the error message (used for error messages)
   * @param rootObjectName - The name of the object being validated (used for error messages)
   * @param schema - The schema to validate against
   * @param value - The value to validate
   *
   * @returns The validated value
   * @throws An error if the value is invalid
   */
  validateOrThrow(lead, rootObjectName, schema, value, stack) {
    const result = schema.safeParse(value);
    if (result.success) {
      return result.data;
    } else {
      throw makePrettyError(`${lead}

${_Validator.prettyPrintZod(rootObjectName, result.error)}`, this.attachStack ? stack : void 0);
    }
  }
  /**
   * Validates multiple values against multiple schemas and throws an error if any of them are
   * invalid. All values are validated before any errors are thrown. This is useful when you want to
   * validate multiple values at once and want to see all the errors at once.
   *
   * @param leadProducer - The function to produce the start of the error message (used for error).
   * It is called with a set of indices of the invalid values.
   * @param rootObjectNames - The names of the objects being validated (used for error messages)
   * @param schemas - The schemas to validate against
   * @param values - The values to validate
   *
   * @returns The validated values
   * @throws An error if any of the values are invalid
   */
  validateMultipleOrThrow(leadProducer, rootObjectNames, schemas, values2, stack) {
    const results = schemas.map((schema, index) => schema.safeParse(values2[index]));
    const errors = results.map((result, index) => ({ result, index, rootObjectName: rootObjectNames[index] })).filter(({ result }) => !result.success).map(({ result, rootObjectName, index }) => ({
      error: result.error,
      rootObjectName,
      index
    }));
    if (errors.length === 0) {
      return results.map((result) => result.data);
    } else {
      const erroredValues = new Set(errors.map(({ index }) => index));
      const lead = leadProducer(erroredValues);
      throw makePrettyError(`${lead}

${errors.map(({ error, rootObjectName }) => _Validator.prettyPrintZod(rootObjectName, error)).join("\n")}`, this.attachStack ? stack : void 0);
    }
  }
  /**
   * Validates a value against a schema and throws an error if it's invalid. This is a convenience
   * function for validating one single method parameter.
   *
   * @param className - The name of the class containing the method (used for error messages)
   * @param methodName - The name of the method (used for error messages)
   * @param paramName - The name of the parameter being validated (used for error messages)
   * @param schema - The schema to validate against
   * @param value - The value to validate
   *
   * @returns The validated value
   * @throws An error if the value is invalid
   */
  validateMethodParamOrThrow(className, methodName, paramName, schema, value, stack) {
    const functionCall = import_chalk.default.yellowBright(text`
    ${className}.${methodName}(${import_chalk.default.redBright(paramName)})
  `);
    return this.validateOrThrow(`Invalid parameter(s) for ${functionCall}:`, paramName, schema, value, stack);
  }
  /**
   * Validates multiple values against multiple schemas and throws an error if any of them are
   * invalid. This is a convenience function for validating multiple method parameters.
   *
   * @param className - The name of the class containing the method (used for error messages)
   * @param methodName - The name of the method (used for error messages)
   * @param paramNames - The names of the parameters being validated (used for error messages)
   * @param schemas - The schemas to validate against
   * @param values - The values to validate
   *
   * @returns The validated values
   * @throws An error if any of the values are invalid
   */
  validateMethodParamsOrThrow(className, methodName, paramNames, schemas, values2, stack) {
    return this.validateMultipleOrThrow((erroredValues) => {
      const coloredParamNames = paramNames.map((name, index) => erroredValues.has(index) ? import_chalk.default.redBright(name) : name);
      const functionCall = import_chalk.default.yellowBright(text`
        ${className}.${methodName}(${coloredParamNames.join(", ")})
      `);
      return `Invalid parameter(s) for ${functionCall}:`;
    }, paramNames, schemas, values2, stack);
  }
  /**
   * Validates a value against a schema and throws an error if it's invalid. This is a convenience
   * function for validating one single constructor parameter.
   *
   * @param className - The name of the class (used for error messages)
   * @param paramName - The name of the parameter being validated (used for error messages)
   * @param schema - The schema to validate against
   * @param value - The value to validate
   *
   * @returns The validated value
   * @throws An error if the value is invalid
   */
  validateConstructorParamOrThrow(className, paramName, schema, value, stack) {
    const functionCall = import_chalk.default.yellowBright(text`
    ${className}(${import_chalk.default.redBright(paramName)})
  `);
    return this.validateOrThrow(`Invalid parameter(s) when constructing ${functionCall}`, paramName, schema, value, stack);
  }
  /**
   * Validates multiple values against multiple schemas and throws an error if any of them are
   * invalid. This is a convenience function for validating multiple constructor parameters.
   *
   * @param className - The name of the class (used for error messages)
   * @param paramNames - The names of the parameters being validated (used for error messages)
   *
   * @param schemas - The schemas to validate against
   * @param values - The values to validate
   */
  validateConstructorParamsOrThrow(className, paramNames, schemas, values2, stack) {
    return this.validateMultipleOrThrow((erroredValues) => {
      const coloredParamNames = paramNames.map((name, index) => erroredValues.has(index) ? import_chalk.default.redBright(name) : name);
      const functionCall = import_chalk.default.yellowBright(text`
        ${className}(${coloredParamNames.join(", ")})
      `);
      return `Invalid parameter(s) when constructing ${functionCall}:`;
    }, paramNames, schemas, values2, stack);
  }
};
var sharedValidator = new Validator();
var FileHandle = class {
  /**
   * @deprecated Direct construction is not recommended. Please use the `prepareFile` API instead
   */
  constructor(filesNamespace, identifier, type, sizeBytes, name) {
    this.filesNamespace = filesNamespace;
    this.identifier = identifier;
    this.type = type;
    this.sizeBytes = sizeBytes;
    this.name = name;
    this.parsedIdentifier = parseFileIdentifier(identifier);
  }
  /**
   * Gets the absolute file path of this file.
   */
  async getFilePath() {
    switch (this.parsedIdentifier.type) {
      case "local": {
        return (await this.filesNamespace.getLocalFileAbsolutePath(this.parsedIdentifier.fileName)).path;
      }
      case "base64": {
        throw new Error("Not implemented. Please open an issue on GitHub if you encountered this error.");
      }
      default: {
        const _exhaustiveCheck = this.parsedIdentifier;
        throw new Error(`Unexpected file identifier type: ${JSON.stringify(_exhaustiveCheck)}`);
      }
    }
  }
  isImage() {
    return this.type === "image";
  }
};
var chatMessageInputSchema = external_exports.object({
  role: external_exports.enum(["user", "assistant", "system"]).optional(),
  content: external_exports.string().optional(),
  images: external_exports.array(external_exports.instanceof(FileHandle)).optional()
});
var chatHistoryInputSchema = external_exports.array(chatMessageInputSchema);
function isChatMessageInputAsOpposeToChatMessageData(chatMessageInput) {
  return !Array.isArray(chatMessageInput.content);
}
function isChatMessageInputAsOpposeToChatHistoryData(chatMessageInput) {
  return !("messages" in chatMessageInput);
}
function chatMessageInputToChatMessageData(chatMessageInput) {
  const { role, content, images } = chatMessageInput;
  const parts = [];
  if (images === void 0 || images.length === 0) {
    if (content === void 0) {
      parts.push({
        type: "text",
        text: ""
      });
    }
  } else {
    for (const file of images) {
      parts.push({
        type: "file",
        identifier: file.identifier,
        name: file.name,
        fileType: file.type,
        sizeBytes: file.sizeBytes
      });
    }
  }
  if (content !== void 0) {
    parts.push({
      type: "text",
      text: content
    });
  }
  return {
    role: role ?? "user",
    content: parts
  };
}
var Chat3 = class _Chat extends MaybeMutable {
  getClassName() {
    return "Chat";
  }
  create(data, mutable) {
    return new _Chat(data, mutable);
  }
  cloneData(data) {
    return chatHistoryDataSchema.parse(data);
  }
  /**
   * Don't use this constructor directly.
   *
   * - To create an empty chat history, use `Chat.empty()`.
   * - To create a chat history with existing data, use `Chat.from()`.
   */
  constructor(data, mutable) {
    super(data, mutable);
  }
  /**
   * Creates an empty mutable chat history.
   */
  static empty() {
    return new _Chat({ messages: [] }, true);
  }
  /**
   * Quickly create a mutable chat history with something that can be converted to a chat history.
   *
   * The created chat history will be a mutable copy of the input.
   *
   * @example
   * ```ts
   * const history = Chat.from([
   *   { role: "user", content: "Hello" },
   *   { role: "assistant", content: "Hi!" },
   *   { role: "user", content: "What is your name?" },
   * ]);
   * ```
   */
  static from(initializer) {
    const stack = getCurrentStack(1);
    sharedValidator.validateMethodParamOrThrow("Chat", "from", "initializer", chatHistoryLikeSchema, initializer, stack);
    if (initializer instanceof _Chat) {
      return initializer.asMutableCopy();
    }
    if (typeof initializer === "string") {
      const chatHistory = _Chat.empty();
      chatHistory.append("user", initializer);
      return chatHistory;
    }
    if (Array.isArray(initializer)) {
      return new _Chat({ messages: initializer.map(chatMessageInputToChatMessageData) }, true);
    }
    if (isChatMessageInputAsOpposeToChatHistoryData(initializer)) {
      return new _Chat({ messages: [chatMessageInputToChatMessageData(initializer)] }, true);
    } else {
      return new _Chat(initializer, false).asMutableCopy();
    }
  }
  /**
   * Creates a chat history with raw data. This method is intended for internal use only.
   *
   * If mutable is set to false, you MUST ensure that the data is not mutated.
   *
   * @internal
   */
  static createRaw(data, mutable) {
    return new _Chat(data, mutable);
  }
  /**
   * Gets the raw data of this message. This method is intended for internal use only.
   *
   * If mutable is set to false, you MUST ensure that the data is not mutated.
   *
   * @internal
   */
  getRaw() {
    return this.data;
  }
  append(...args) {
    this.guardMutable();
    if (args.length === 1) {
      const [chatMessageLike] = args;
      const chatMessage = ChatMessage.from(chatMessageLike);
      const messageMutable = accessMaybeMutableInternals(chatMessage)._internalToMutable();
      this.data.messages.push(accessMaybeMutableInternals(messageMutable)._internalGetData());
    } else {
      const [role, content, opts = {}] = args;
      if (role === "user" || role === "system" || role === "assistant") {
        const parts = [
          { type: "text", text: content }
        ];
        if (opts.images !== void 0) {
          for (const image of opts.images) {
            parts.push({
              type: "file",
              name: image.name,
              identifier: image.identifier,
              sizeBytes: image.sizeBytes,
              fileType: image.type
            });
          }
        }
        this.data.messages.push({ role, content: parts });
      } else {
        throw new Error(text`
          Unsupported role for append() API with [role, content] parameters: ${role}.
          Supported roles are 'user', 'system', and 'assistant'.
        `);
      }
    }
  }
  withAppended(...args) {
    const copy2 = this.asMutableCopy();
    copy2.append(...args);
    return copy2;
  }
  /**
   * Get the number of messages in the history.
   */
  getLength() {
    return this.data.messages.length;
  }
  /**
   * Get the number of messages in the history.
   */
  get length() {
    return this.getLength();
  }
  /**
   * Remove the last message from the history. If the history is empty, this method will throw.
   */
  pop() {
    this.guardMutable();
    if (this.data.messages.length === 0) {
      throw new Error("Tried to pop from an empty history.");
    }
    const popped = this.data.messages.pop();
    return ChatMessage.createRaw(popped, true);
  }
  /**
   * Gets all files contained in this history.
   *
   * @param client - LMStudio client
   */
  getAllFiles(client) {
    return this.data.messages.flatMap((message) => message.content.filter((part) => part.type === "file")).map((part) => new FileHandle(client.files, part.identifier, part.fileType, part.sizeBytes, part.name));
  }
  /**
   * Allows iterating over the files in the history.
   */
  *files(client) {
    for (const message of this.data.messages) {
      for (const part of message.content) {
        if (part.type === "file") {
          yield new FileHandle(client.files, part.identifier, part.fileType, part.sizeBytes, part.name);
        }
      }
    }
  }
  /**
   * Returns true if this history contains any files.
   */
  hasFiles() {
    return this.data.messages.some((message) => message.content.some((part) => part.type === "file"));
  }
  /**
   * Gets the message at the given index. If the index is negative, it will be counted from the end.
   *
   * If the index is out of bounds, this method will throw as oppose to returning undefined. This is
   * to help catch bugs early.
   */
  at(index) {
    let actualIndex = index;
    if (index < 0) {
      actualIndex = this.data.messages.length + index;
    }
    if (actualIndex < 0 || actualIndex >= this.data.messages.length) {
      throw new Error(text`
        Tried to access the message at index ${index}, but the history only has
        ${this.data.messages.length} messages.
      `);
    }
    return ChatMessage.createRaw(this.data.messages[actualIndex], this.mutable);
  }
  /**
   * Get all the messages in the history as an array of ChatMessage objects.
   */
  getMessagesArray() {
    return this.data.messages.map((message) => ChatMessage.createRaw(message, this.mutable));
  }
  /**
   * Maps over the messages in the history and returns an array of the results.
   */
  map(mapper) {
    return this.getMessagesArray().map(mapper);
  }
  /**
   * Maps over the messages in the history and returns a flattened array of the results.
   *
   * This is similar to `Array.prototype.flatMap`, but it works with ChatMessage objects.
   */
  flatMap(mapper) {
    return this.getMessagesArray().flatMap(mapper);
  }
  /**
   * Allows iterating over the messages in the history.
   */
  *[Symbol.iterator]() {
    for (const message of this.data.messages) {
      yield ChatMessage.createRaw(message, this.mutable);
    }
  }
  /**
   * Given a predicate, the predicate is called for each file in the history.
   *
   * - If the predicate returns true, the file is removed from the history and is collected into the
   *   returned array.
   * - If the predicate returns false, the file is kept in the history.
   *
   * This method is useful if you are implementing a promptPreprocessor that needs to convert certain
   * types of files.
   *
   * If the predicate needs to be async, use the {@link Chat#consumeFilesAsync} method.
   *
   * @param client - LMStudio client
   * @param predicate - The predicate to call for each file.
   * @returns The files that were consumed.
   */
  consumeFiles(client, predicate) {
    this.guardMutable();
    const consumedFiles = [];
    for (const message of this.data.messages) {
      consumedFiles.push(...ChatMessage.createRaw(message, true).consumeFiles(client, predicate));
    }
    return consumedFiles;
  }
  /**
   * Given an async predicate, the predicate is called for each file in the history.
   *
   * - If the predicate returns true, the file is removed from the history and is collected into the
   *  returned array.
   * - If the predicate returns false, the file is kept in the history.
   *
   * This method is useful if you are implementing a promptPreprocessor that needs to convert certain
   * types of files.
   *
   * If you need a synchronous version, use the {@link Chat#consumeFiles} method.
   *
   * @param client - LMStudio client
   * @param predicate - The predicate to call for each file.
   * @returns The files that were consumed.
   */
  async consumeFilesAsync(client, predicate) {
    this.guardMutable();
    const consumedFiles = [];
    for (const message of this.data.messages) {
      consumedFiles.push(...await ChatMessage.createRaw(message, true).consumeFilesAsync(client, predicate));
    }
    return consumedFiles;
  }
  getSystemPrompt() {
    return this.data.messages.filter((message) => message.role === "system").map((message) => message.content.filter((part) => part.type === "text").map((part) => part.text).join(" ")).join("\n\n");
  }
  replaceSystemPrompt(content) {
    this.guardMutable();
    this.data.messages = this.data.messages.filter((message) => message.role !== "system");
    this.data.messages.unshift({ role: "system", content: [{ type: "text", text: content }] });
  }
  filterInPlace(predicate) {
    this.guardMutable();
    this.data.messages = this.data.messages.filter((message) => predicate(ChatMessage.createRaw(message, true)));
  }
  toString() {
    return "Chat {\n" + this.data.messages.map((message) => {
      const messageString = ChatMessage.createRaw(message, false).toString();
      return messageString.split("\n").map((line) => "  " + line).join("\n");
    }).join("\n") + "\n}";
  }
};
var chatHistoryLikeSchema = external_exports.union([
  external_exports.instanceof(Chat3),
  chatHistoryDataSchema,
  external_exports.string(),
  chatHistoryInputSchema,
  chatMessageInputSchema
]);
var ChatMessage = class _ChatMessage extends MaybeMutable {
  getClassName() {
    return "ChatMessage";
  }
  create(data, mutable) {
    return new _ChatMessage(data, mutable);
  }
  cloneData(data) {
    return chatMessageDataSchema.parse(data);
  }
  constructor(data, mutable) {
    super(data, mutable);
  }
  /**
   * Create a mutable text only message.
   */
  static create(role, content) {
    return new _ChatMessage(chatMessageDataSchema.parse({
      role,
      content: [{ type: "text", text: content }]
    }), true);
  }
  /**
   * Quickly create a mutable message with something that can be converted to a message.
   */
  static from(initializer) {
    const stack = getCurrentStack(1);
    sharedValidator.validateMethodParamOrThrow("ChatMessage", "from", "initializer", chatMessageLikeSchema, initializer, stack);
    if (initializer instanceof _ChatMessage) {
      return initializer.asMutableCopy();
    }
    if (typeof initializer === "string") {
      return new _ChatMessage(chatMessageDataSchema.parse({
        role: "user",
        content: [{ type: "text", text: initializer }]
      }), true);
    }
    if (isChatMessageInputAsOpposeToChatMessageData(initializer)) {
      return new _ChatMessage(chatMessageInputToChatMessageData(initializer), true);
    } else {
      return new _ChatMessage(initializer, true);
    }
  }
  /**
   * Creates a chat history with raw data. This method is intended for internal use only.
   *
   * If mutable is set to false, you MUST ensure that the data is not mutated.
   *
   * @internal
   */
  static createRaw(data, mutable) {
    return new _ChatMessage(data, mutable);
  }
  /**
   * Gets the raw data of this message. This method is intended for internal use only.
   *
   * If mutable is set to false, you MUST ensure that the data is not mutated.
   *
   * @internal
   */
  getRaw() {
    return this.data;
  }
  getRole() {
    return this.data.role;
  }
  setRole(role) {
    this.guardMutable();
    this.data.role = role;
  }
  getFileParts() {
    return this.data.content.filter((part) => part.type === "file");
  }
  /**
   * Gets all text contained in this message.
   */
  getText() {
    return this.data.content.filter((part) => part.type === "text").map((part) => part.text).join(" ");
  }
  /**
   * Get all tool call results within this message.
   */
  getToolCallResults() {
    return this.data.content.filter((part) => part.type === "toolCallResult").map((part) => ({
      content: part.content,
      toolCallId: part.toolCallId
    }));
  }
  /**
   * Gets all file parts contained in this message.
   */
  getToolCallRequests() {
    return this.data.content.filter((part) => part.type === "toolCallRequest").map((part) => part.toolCallRequest);
  }
  /**
   * Gets all files contained in this message.
   *
   * @param client - LMStudio client
   */
  getFiles(client) {
    return this.getFileParts().map((part) => new FileHandle(client.files, part.identifier, part.fileType, part.sizeBytes, part.name));
  }
  /**
   * Allows iterating over the files in the message.
   */
  *files(client) {
    for (const part of this.getFileParts()) {
      yield new FileHandle(client.files, part.identifier, part.fileType, part.sizeBytes, part.name);
    }
  }
  /**
   * Given a predicate, the predicate is called for each file in the message.
   *
   * - If the predicate returns true, the file is removed from the message and is collected into the
   *   returned array.
   * - If the predicate returns false, the file is kept in the message.
   *
   * This method is useful if you are implementing a promptPreprocessor that needs to convert certain
   * types of files.
   *
   * If the predicate needs to be async, use the {@link ChatMessage#consumeFilesAsync} method.
   *
   * @param client - LMStudio client
   * @param predicate - The predicate to call for each file.
   * @returns The files that were consumed.
   */
  consumeFiles(client, predicate) {
    this.guardMutable();
    const consumedFiles = [];
    const partIndexesToRemove = /* @__PURE__ */ new Set();
    for (const [index, part] of this.data.content.entries()) {
      if (part.type !== "file") {
        continue;
      }
      const file = new FileHandle(client.files, part.identifier, part.fileType, part.sizeBytes, part.name);
      if (predicate(file)) {
        consumedFiles.push(file);
        partIndexesToRemove.add(index);
      }
    }
    this.data.content = this.data.content.filter((_3, index) => !partIndexesToRemove.has(index));
    return consumedFiles;
  }
  /**
   * Given an async predicate, the predicate is called for each file in the message.
   *
   * - If the predicate returns true, the file is removed from the message and is collected into the
   *  returned array.
   * - If the predicate returns false, the file is kept in the message.
   *
   * This method is useful if you are implementing a promptPreprocessor that needs to convert certain
   * types of files.
   *
   * If you need a synchronous version, use the {@link ChatMessage#consumeFiles} method.
   *
   * @param client - LMStudio client
   * @param predicate - The predicate to call for each file.
   * @returns The files that were consumed.
   */
  async consumeFilesAsync(client, predicate) {
    this.guardMutable();
    const consumedFiles = [];
    const partIndexesToRemove = /* @__PURE__ */ new Set();
    for (const [index, part] of this.data.content.entries()) {
      if (part.type !== "file") {
        continue;
      }
      const file = new FileHandle(client.files, part.identifier, part.fileType, part.sizeBytes, part.name);
      if (await predicate(file)) {
        consumedFiles.push(file);
        partIndexesToRemove.add(index);
      }
    }
    this.data.content = this.data.content.filter((_3, index) => !partIndexesToRemove.has(index));
    return consumedFiles;
  }
  /**
   * Returns true if this message contains any files.
   */
  hasFiles() {
    return this.data.content.some((part) => part.type === "file");
  }
  /**
   * Append text to the message.
   */
  appendText(text3) {
    this.guardMutable();
    switch (this.data.role) {
      case "assistant":
      case "user":
      case "system":
        this.data.content.push({
          type: "text",
          text: text3
        });
        break;
      case "tool":
        throw new Error(`Cannot append text to a message with role "${this.data.role}"`);
      default: {
        const exhaustiveCheck = this.data;
        throw new Error(`Unhandled role in switch statement: ${exhaustiveCheck.role}`);
      }
    }
  }
  /**
   * Append a file to the message. Takes in a FileHandle. You can obtain a FileHandle from
   * `client.files.prepareImage`.
   */
  appendFile(file) {
    this.guardMutable();
    switch (this.data.role) {
      case "assistant":
      case "user":
      case "system":
        this.data.content.push({
          type: "file",
          name: file.name,
          identifier: file.identifier,
          sizeBytes: file.sizeBytes,
          fileType: file.type
        });
        break;
      case "tool":
        throw new Error(`Cannot append text to a message with role "${this.data.role}"`);
      default: {
        const exhaustiveCheck = this.data;
        throw new Error(`Unhandled role in switch statement: ${exhaustiveCheck.role}`);
      }
    }
  }
  /**
   * Replaces all text in the messages.
   *
   * If the message contains other components (such as files), they will kept. The replaced text
   * will be inserted to the beginning of the message.
   */
  replaceText(text3) {
    this.guardMutable();
    switch (this.data.role) {
      case "assistant":
      case "user":
      case "system":
        this.data.content = [
          { type: "text", text: text3 },
          ...this.data.content.filter((part) => part.type !== "text")
        ];
        break;
      case "tool":
        throw new Error(`Cannot replace text in a message with role "${this.data.role}"`);
      default: {
        const exhaustiveCheck = this.data;
        throw new Error(`Unhandled role in switch statement: ${exhaustiveCheck.role}`);
      }
    }
  }
  isSystemPrompt() {
    return this.data.role === "system";
  }
  isUserMessage() {
    return this.data.role === "user";
  }
  isAssistantMessage() {
    return this.data.role === "assistant";
  }
  toString() {
    const text3 = this.data.content.map((part) => {
      switch (part.type) {
        case "text":
          return part.text;
        case "file":
          return `<file ${part.name}>`;
        case "toolCallRequest":
          return part.toolCallRequest.name + `(${JSON.stringify(part.toolCallRequest.arguments)})`;
        case "toolCallResult":
          return part.content;
        default: {
          const exhaustiveCheck = part;
          throw new Error(`Unknown part type: ${exhaustiveCheck.type}`);
        }
      }
    }).join(" ");
    if (text3.includes("\n")) {
      return this.data.role + ":\n" + text3.split("\n").map((line) => "  " + line).join("\n");
    } else {
      return this.data.role + ": " + text3;
    }
  }
};
var chatMessageLikeSchema = external_exports.union([
  external_exports.instanceof(ChatMessage),
  chatMessageInputSchema,
  external_exports.string(),
  chatMessageDataSchema
]);
var KVFieldValueTypesLibraryBuilder = class {
  constructor(baseSchema) {
    this.baseSchema = baseSchema;
    this.valueTypes = /* @__PURE__ */ new Map();
  }
  /**
   * Define a new field value type.
   */
  valueType(key, param) {
    if (this.valueTypes.has(key)) {
      throw new Error(`ValueType with key ${key} already exists`);
    }
    this.valueTypes.set(key, {
      paramType: external_exports.object({
        ...this.baseSchema,
        ...param.paramType
      }),
      schemaMaker: param.schemaMaker,
      effectiveEquals: param.effectiveEquals,
      stringify: param.stringify
    });
    return this;
  }
  build() {
    return new KVFieldValueTypeLibrary(new Map(this.valueTypes));
  }
};
var KVFieldValueTypeLibrary = class {
  constructor(valueTypes) {
    this.valueTypes = valueTypes;
  }
  /**
   * Gets the schema for a specific field value type with the given key and parameters.
   */
  getSchema(key, param) {
    const valueType = this.valueTypes.get(key);
    if (valueType === void 0) {
      throw new Error(`Cannot find value type ${key}`);
    }
    return valueType.schemaMaker(valueType.paramType.parse(param));
  }
  parseParamTypes(key, param) {
    return this.valueTypes.get(key).paramType.parse(param);
  }
  effectiveEquals(key, typeParam, a3, b4) {
    return this.valueTypes.get(key).effectiveEquals(a3, b4, typeParam);
  }
  stringify(key, typeParam, opts, value) {
    return this.valueTypes.get(key).stringify(value, typeParam, opts);
  }
};
var KVConfigSchematicsBuilder = class _KVConfigSchematicsBuilder {
  constructor(valueTypeLibrary) {
    this.valueTypeLibrary = valueTypeLibrary;
    this.fields = /* @__PURE__ */ new Map();
    this.extensionPrefixes = [];
  }
  /**
   * Adds a field
   */
  field(key, valueTypeKey, valueTypeParams, defaultValue) {
    const schema = this.valueTypeLibrary.getSchema(valueTypeKey, valueTypeParams);
    const defaultValueParseResult = schema.safeParse(defaultValue);
    if (!defaultValueParseResult.success) {
      throw new Error(`Invalid default value for field ${key}: ${defaultValueParseResult.error.message}`);
    }
    defaultValue = defaultValueParseResult.data;
    if (this.fields.has(key)) {
      throw new Error(`Cannot add field with key ${key}. Key already exists in the schematics.`);
    }
    this.fields.set(key, {
      valueTypeKey,
      valueTypeParams,
      schema: this.valueTypeLibrary.getSchema(valueTypeKey, valueTypeParams),
      fullKey: key,
      defaultValue
    });
    return this;
  }
  /**
   * Adds an extension point. For example, if called with .extension("hello.world"), then any keys
   * that match "hello.world.*" will be allowed when going through lenient zod schema. However,
   * any extension fields will still not be accessible via this schematics.
   */
  extension(prefix) {
    this.extensionPrefixes.push(`${prefix}.`);
    return this;
  }
  /**
   * Convenience method for grouping a set of fields under a shared namespace.
   *
   * For example, if we want to create two fields: `some:namespace:a` and `some:namespace:b`.
   * Instead of doing:
   *
   * ```ts
   * builder
   *   .field("some:namespace:a", ...)
   *   .field("some:namespace:b", ...)
   * ```
   *
   * We can do:
   *
   * ```ts
   * builder.scope("some:namespace", builder =>
   *  builder
   *   .field("a", ...)
   *   .field("b", ...)
   * )
   * ```
   *
   * This method does support nesting. Whether to nest or not is up to the user.
   */
  scope(scopeKey, fn) {
    const innerBuilder = fn(new _KVConfigSchematicsBuilder(this.valueTypeLibrary));
    for (const [key, { valueTypeKey, valueTypeParams, schema, defaultValue }] of innerBuilder.fields.entries()) {
      const fullKey = `${scopeKey}.${key}`;
      if (this.fields.has(fullKey)) {
        throw new Error(`Cannot add field with key ${fullKey}. Key already exists in the schematics.`);
      }
      this.fields.set(fullKey, {
        valueTypeKey,
        valueTypeParams,
        schema,
        fullKey,
        defaultValue
      });
    }
    this.extensionPrefixes.push(...innerBuilder.extensionPrefixes.map((prefix) => `${scopeKey}.${prefix}`));
    return this;
  }
  build() {
    return new KVConfigSchematics(this.valueTypeLibrary, this.fields, this.extensionPrefixes);
  }
};
var createParsedKVConfig = Symbol("createParsedKVConfig");
var KVConfigSchematics = class _KVConfigSchematics {
  constructor(valueTypeLibrary, fields, extensionPrefixes) {
    this.valueTypeLibrary = valueTypeLibrary;
    this.fields = fields;
    this.extensionPrefixes = extensionPrefixes;
    this.fullKepMap = void 0;
    this.lenientZodSchema = void 0;
  }
  getFieldsMap() {
    return new Map([...this.fields.values()].map((field) => [field.fullKey, field]));
  }
  obtainField(key) {
    const field = this.fields.get(key);
    if (field === void 0) {
      const fieldKeys = [...this.fields.keys()];
      let availableList = fieldKeys.slice(0, 10).map((key2) => `- ${key2}`).join("\n");
      if (fieldKeys.length > 10) {
        availableList += `
... and ${fieldKeys.length - 10} more`;
      }
      throw new Error(`Cannot access key ${key}. Key does not exist in the schematics. Available keys:

` + availableList);
    }
    return field;
  }
  obtainFieldByFullKey(fullKey) {
    const field = this.getFullKeyMap().get(fullKey);
    if (field === void 0) {
      const fieldKeys = [...this.getFullKeyMap().keys()];
      let availableList = fieldKeys.slice(0, 10).map((key) => `- ${key}`).join("\n");
      if (fieldKeys.length > 10) {
        availableList += `
... and ${fieldKeys.length - 10} more`;
      }
      throw new Error(`Cannot access full key ${fullKey}. Full key does not exist in the schematics. Availablekeys:

` + availableList);
    }
    return field;
  }
  getSchemaForKey(key) {
    const field = this.obtainField(key);
    return field.schema;
  }
  parseField(fieldSchema, value) {
    if (value === void 0) {
      if (fieldSchema.defaultValue === void 0) {
        throw new Error(`Field with key ${fieldSchema.fullKey} is missing and has no default value`);
      }
      return fieldSchema.defaultValue;
    }
    const parseResult = fieldSchema.schema.safeParse(value);
    if (!parseResult.success) {
      throw new Error(`Field with key ${fieldSchema.fullKey} does not satisfy the schema:` + parseResult.error.message);
    }
    return parseResult.data;
  }
  parseFieldWithoutDefault(field, value) {
    if (value === void 0) {
      return void 0;
    }
    const parseResult = field.schema.safeParse(value);
    if (!parseResult.success) {
      throw new Error(`Field with key ${field.fullKey} does not satisfy the schema:` + parseResult.error.message);
    }
    return parseResult.data;
  }
  /**
   * Parse and access a field in the config.
   */
  access(config, key) {
    const field = this.obtainField(key);
    return this.parseField(field, config.fields.find((f4) => f4.key === field.fullKey)?.value);
  }
  accessByFullKey(config, fullKey) {
    const field = this.obtainFieldByFullKey(fullKey);
    return this.parseField(field, config.fields.find((f4) => f4.key === field.fullKey)?.value);
  }
  /**
   * Parse and access a field in the config. Returns undefined if the field is missing.
   */
  accessPartial(config, key) {
    const field = this.obtainField(key);
    return this.parseFieldWithoutDefault(field, config.fields.find((f4) => f4.key === field.fullKey)?.value);
  }
  /**
   * Gets a slice of the config schema with the given key patterns. Support syntax:
   *
   * - `some.namespace.key`: Matches exactly `some.namespace.key`
   * - `some.namespace.*`: Matches anything that starts with `some.namespace.`
   */
  sliced(...patterns) {
    const parsedPatterns = patterns.map((p4) => {
      if (p4.endsWith("*")) {
        return { type: "prefix", value: p4.substring(0, p4.length - 1) };
      }
      return { type: "exact", value: p4 };
    });
    const newFields = /* @__PURE__ */ new Map();
    for (const [key, field] of this.fields.entries()) {
      for (const pattern of parsedPatterns) {
        if (pattern.type === "exact" && key === pattern.value || pattern.type === "prefix" && key.startsWith(pattern.value)) {
          newFields.set(key, field);
        }
      }
    }
    return new _KVConfigSchematics(this.valueTypeLibrary, newFields, this.extensionPrefixes);
  }
  /**
   * Get a subset of the config schema with a specific scope.
   */
  scoped(scopeKey) {
    const newFields = /* @__PURE__ */ new Map();
    for (const [key, field] of this.fields.entries()) {
      if (key.startsWith(`${scopeKey}.`)) {
        newFields.set(key.substring(scopeKey.length + 1), field);
      }
    }
    return new _KVConfigSchematics(this.valueTypeLibrary, newFields, this.extensionPrefixes);
  }
  union(other) {
    const newFields = /* @__PURE__ */ new Map();
    for (const [key, field] of this.fields.entries()) {
      newFields.set(key, field);
    }
    for (const [key, field] of other.fields.entries()) {
      if (newFields.has(key)) {
        throw new Error("Cannot union two KVConfigSchematics. The following key is duplicated: " + key);
      }
      newFields.set(key, field);
    }
    return new _KVConfigSchematics(this.valueTypeLibrary, newFields, [
      ...this.extensionPrefixes,
      ...other.extensionPrefixes
    ]);
  }
  /**
   * Combine baseKey into the fields. Effectively removes the baseKey.
   */
  flattenBaseKey() {
    const newFields = /* @__PURE__ */ new Map();
    for (const field of this.fields.values()) {
      newFields.set(field.fullKey, field);
    }
    return new _KVConfigSchematics(this.valueTypeLibrary, newFields, this.extensionPrefixes);
  }
  parseToMap(config) {
    const rawConfigMap = kvConfigToMap(config);
    const parsedConfigMap = /* @__PURE__ */ new Map();
    for (const [key, field] of this.fields.entries()) {
      const value = rawConfigMap.get(field.fullKey);
      const parsedValue = this.parseField(field, value);
      parsedConfigMap.set(key, parsedValue);
    }
    return parsedConfigMap;
  }
  parseToMapWithFullKey(config) {
    const rawConfigMap = kvConfigToMap(config);
    const parsedConfigMap = /* @__PURE__ */ new Map();
    for (const field of this.fields.values()) {
      const value = rawConfigMap.get(field.fullKey);
      const parsedValue = this.parseField(field, value);
      parsedConfigMap.set(field.fullKey, parsedValue);
    }
    return parsedConfigMap;
  }
  parseToMapPartial(config) {
    const rawConfigMap = kvConfigToMap(config);
    const parsedConfigMap = /* @__PURE__ */ new Map();
    for (const [key, field] of this.fields.entries()) {
      const value = rawConfigMap.get(field.fullKey);
      const parsedValue = this.parseFieldWithoutDefault(field, value);
      if (parsedValue !== void 0) {
        parsedConfigMap.set(key, parsedValue);
      }
    }
    return parsedConfigMap;
  }
  /**
   * Parse the given config to a ParsedKVConfig. **Will throw** if the config does not satisfy the
   * schema.
   */
  parse(config) {
    return ParsedKVConfig[createParsedKVConfig](this.parseToMap(config));
  }
  parsePartial(config) {
    return PartialParsedKVConfig[createParsedKVConfig](this.parseToMapPartial(config));
  }
  /**
   * Builds a full KV config from the given values record. **Will throw** if any of the values are
   * missing or do not satisfy the schema.
   */
  buildFullConfig(valuesRecord) {
    return {
      fields: Array.from(this.fields.entries()).map(([key, field]) => {
        const value = this.parseField(field, valuesRecord[key]);
        return { key: field.fullKey, value };
      })
    };
  }
  /**
   * Builds a partial KV config from the given values record. Will leave holes in the config if the
   * values are missing. **Will throw** if any of the values do not satisfy the schema.
   */
  buildPartialConfig(valuesRecord) {
    return {
      fields: Object.entries(valuesRecord).filter(([_key, value]) => value !== void 0).map(([key, value]) => {
        const field = this.obtainField(key);
        return { key: field.fullKey, value: this.parseField(field, value) };
      })
    };
  }
  createBuildPartialConfigInput() {
    return {};
  }
  configBuilder() {
    return new KVConfigBuilder(this.fields);
  }
  clone() {
    return new _KVConfigSchematics(this.valueTypeLibrary, new Map(this.fields), this.extensionPrefixes);
  }
  withTypeParamOverride(key, paramMapper) {
    const field = this.obtainField(key);
    const clone = this.clone();
    clone.fields.set(key, {
      ...field,
      valueTypeParams: paramMapper(field.valueTypeParams),
      schema: this.valueTypeLibrary.getSchema(field.valueTypeKey, paramMapper(field.valueTypeParams))
    });
    return clone;
  }
  getFullKeyMap() {
    if (this.fullKepMap !== void 0) {
      return this.fullKepMap;
    }
    this.fullKepMap = new Map([...this.fields.values()].map((field) => [field.fullKey, field]));
    return this.fullKepMap;
  }
  makeLenientZodSchema() {
    const fullKeyMap = this.getFullKeyMap();
    return kvConfigSchema.transform((value) => {
      const seenKeys = /* @__PURE__ */ new Set();
      return {
        fields: value.fields.filter((field) => {
          if (this.extensionPrefixes.some((prefix) => field.key.startsWith(prefix))) {
            return true;
          }
          if (seenKeys.has(field.key)) {
            return false;
          }
          const fieldDef = fullKeyMap.get(field.key);
          if (fieldDef === void 0) {
            return false;
          }
          const parsed = fieldDef.schema.safeParse(field.value);
          if (!parsed.success) {
            return false;
          }
          seenKeys.add(field.key);
          return true;
        })
      };
    });
  }
  /**
   * Makes a zod schema that parses a KVConfig which only allows fields with correct keys and types
   * through.
   *
   * Will filter out any fields that are not in the schema.
   */
  getLenientZodSchema() {
    if (this.lenientZodSchema !== void 0) {
      return this.lenientZodSchema;
    }
    this.lenientZodSchema = this.makeLenientZodSchema();
    return this.lenientZodSchema;
  }
  getValueType(key) {
    const field = this.fields.get(key);
    if (field === void 0) {
      return null;
    }
    return field.valueTypeKey;
  }
  getValueTypeParam(key) {
    const field = this.fields.get(key);
    if (field === void 0) {
      return null;
    }
    return field.valueTypeParams;
  }
  getValueTypeParamByFullKey(key) {
    const field = this.getFullKeyMap().get(key);
    if (field === void 0) {
      throw new Error(`Field with key ${key} does not exist in the schematics`);
    }
    return field.valueTypeParams;
  }
  hasFullKey(key) {
    const field = this.getFullKeyMap().get(key);
    return field !== void 0;
  }
  /**
   * Given a KVConfig, filter it to only include fields that are in the schematics.
   */
  filterConfig(config, additionalFilter) {
    const fullKeyMap = this.getFullKeyMap();
    return {
      fields: config.fields.filter((configField) => {
        const field = fullKeyMap.get(configField.key);
        if (field === void 0) {
          return false;
        }
        if (additionalFilter !== void 0) {
          return additionalFilter(field.fullKey, {
            type: field.valueTypeKey,
            param: field.valueTypeParams
          });
        }
        return true;
      })
    };
  }
  /**
   * Given a KVConfigStack, filter it to only include fields that are in the schematics.
   */
  filterStack(stack) {
    return {
      layers: stack.layers.map((layer) => ({
        layerName: layer.layerName,
        config: this.filterConfig(layer.config)
      }))
    };
  }
  twoWayFilterConfig(config, additionalFilter) {
    const includedFields = [];
    const excludedFields = [];
    const fullKeyMap = this.getFullKeyMap();
    for (const configField of config.fields) {
      const field = fullKeyMap.get(configField.key);
      let include = field !== void 0;
      if (field !== void 0 && additionalFilter !== void 0) {
        include = additionalFilter(field.fullKey, {
          type: field.valueTypeKey,
          param: field.valueTypeParams
        });
      }
      if (include) {
        includedFields.push(configField);
      } else {
        excludedFields.push(configField);
      }
    }
    return [{ fields: includedFields }, { fields: excludedFields }];
  }
  /**
   * Given a list of keys, filter it to only include keys that are in the schematics.
   */
  filterFullKeys(keys2) {
    const fullKeyMap = this.getFullKeyMap();
    return keys2.filter((key) => fullKeyMap.has(key));
  }
  /**
   * Compares two KV config. Compare with "effective equals". Only compare fields in the schematics.
   * Does not apply defaults.
   */
  configEffectiveEquals(a3, b4) {
    const aMap = kvConfigToMap(a3);
    const bMap = kvConfigToMap(b4);
    for (const field of this.fields.values()) {
      const aValue = aMap.get(field.fullKey);
      const bValue = bMap.get(field.fullKey);
      if (aValue === void 0) {
        if (bValue === void 0) {
          continue;
        } else {
          return false;
        }
      }
      this.valueTypeLibrary.effectiveEquals(field.valueTypeKey, field.valueTypeParams, aValue, bValue);
    }
    return true;
  }
  /**
   * Compares two KV config field. Compare with "effective equals". Can only compare fields in the
   * schematics.
   */
  fieldEffectiveEquals(key, a3, b4) {
    const field = this.obtainField(key);
    return this.valueTypeLibrary.effectiveEquals(field.valueTypeKey, field.valueTypeParams, field.schema.parse(a3), field.schema.parse(b4));
  }
  fieldEffectiveEqualsWithFullKey(fullKey, a3, b4) {
    const fullKeyMap = this.getFullKeyMap();
    const field = fullKeyMap.get(fullKey);
    if (field === void 0) {
      throw new Error(`Field with key ${fullKey} does not exist in the schematics`);
    }
    return this.valueTypeLibrary.effectiveEquals(field.valueTypeKey, field.valueTypeParams, field.schema.parse(a3), field.schema.parse(b4));
  }
  makeInternalFieldStringifyOpts(opts) {
    return {
      t: opts.t ?? ((_key, fallback) => fallback),
      desiredLength: opts.desiredLength
    };
  }
  stringifyField(key, value, opts = {}) {
    const field = this.obtainField(key);
    return this.valueTypeLibrary.stringify(field.valueTypeKey, field.valueTypeParams, this.makeInternalFieldStringifyOpts(opts), value);
  }
  tryStringifyFieldWithFullKey(key, value, opts) {
    const fullKeyMap = this.getFullKeyMap();
    const field = fullKeyMap.get(key);
    if (field === void 0) {
      return null;
    }
    return this.valueTypeLibrary.stringify(field.valueTypeKey, field.valueTypeParams, this.makeInternalFieldStringifyOpts(opts), value);
  }
  /**
   * Apply config in patch to target. Only apply fields that are in the schematics.
   */
  apply(target, patch) {
    const filteredPatch = this.filterConfig(patch);
    return collapseKVStackRaw([target, filteredPatch]);
  }
  /**
   * Tries to un-apply the patch from the target. Will only un-apply fields that are in the
   * schematics.
   *
   * If the value in the target is not effective equal to the value in the patch, it will not be
   * removed.
   */
  unApply(target, patch) {
    const filteredPatch = this.filterConfig(patch);
    const patchMap = kvConfigToMap(filteredPatch);
    const newMap = new Map(kvConfigToMap(target));
    const fullKeyMap = this.getFullKeyMap();
    for (const [key, value] of patchMap.entries()) {
      const field = fullKeyMap.get(key);
      if (field === void 0) {
        continue;
      }
      const targetValue = newMap.get(key);
      if (targetValue !== void 0) {
        if (!this.valueTypeLibrary.effectiveEquals(field.valueTypeKey, field.valueTypeParams, value, targetValue)) {
          continue;
        }
        newMap.delete(key);
      }
    }
    return mapToKVConfig(newMap);
  }
  /**
   * Given a KVConfig, iterate through all the fields that are in the schematics. Keys will be full
   * keys.
   */
  *iterateFieldsOfConfig(config) {
    const fullKeyMap = this.getFullKeyMap();
    for (const { key, value } of config.fields) {
      const field = fullKeyMap.get(key);
      if (field !== void 0) {
        yield [key, value];
      }
    }
  }
  /**
   * Given a KVConfig, iterate through all the fields that are in the schematics.
   */
  *fullKeys() {
    const fullKeyMap = this.getFullKeyMap();
    for (const key of fullKeyMap.keys()) {
      yield key;
    }
  }
  /**
   * Effectively compare two KV config, and return full keys of fields that are different.
   */
  effectiveCompareConfig(a3, b4, opts = {}) {
    const { fieldFilter } = opts;
    const aMap = kvConfigToMap(a3);
    const bMap = kvConfigToMap(b4);
    const onlyInA = [];
    const onlyInB = [];
    const inBothButDifferent = [];
    for (const field of this.fields.values()) {
      if (fieldFilter !== void 0) {
        if (!fieldFilter(field.fullKey, {
          type: field.valueTypeKey,
          param: field.valueTypeParams
        })) {
          continue;
        }
      }
      const aValue = aMap.get(field.fullKey);
      const bValue = bMap.get(field.fullKey);
      if (aValue === void 0) {
        if (bValue === void 0) {
          continue;
        } else {
          onlyInB.push(field.fullKey);
        }
      } else {
        if (bValue === void 0) {
          onlyInA.push(field.fullKey);
        } else {
          if (!this.valueTypeLibrary.effectiveEquals(field.valueTypeKey, field.valueTypeParams, aValue, bValue)) {
            inBothButDifferent.push(field.fullKey);
          }
        }
      }
    }
    return { onlyInA, onlyInB, inBothButDifferent };
  }
  serialize() {
    return {
      fields: [...this.fields.entries()].map(([key, field]) => ({
        shortKey: key,
        fullKey: field.fullKey,
        typeKey: field.valueTypeKey,
        typeParams: field.valueTypeParams,
        defaultValue: field.defaultValue
      })),
      extensionPrefixes: this.extensionPrefixes
    };
  }
  /**
   * Check if any of the fields in the schematics has a full key that starts with the given prefix.
   */
  hasFieldsWithPrefix(prefix) {
    for (const field of this.fields.values()) {
      if (field.fullKey.startsWith(prefix)) {
        return true;
      }
    }
    return false;
  }
  static deserialize(valueTypeLibrary, serialized) {
    const fields = new Map(serialized.fields.map((field) => {
      const typeParams = valueTypeLibrary.parseParamTypes(field.typeKey, field.typeParams);
      const valueSchema = valueTypeLibrary.getSchema(field.typeKey, typeParams);
      return [
        field.shortKey,
        {
          valueTypeKey: field.typeKey,
          valueTypeParams: typeParams,
          schema: valueSchema,
          fullKey: field.fullKey,
          defaultValue: valueSchema.parse(field.defaultValue)
        }
      ];
    }));
    return new _KVConfigSchematics(valueTypeLibrary, fields, serialized.extensionPrefixes ?? []);
  }
  static tryDeserialize(valueTypeLibrary, serialized) {
    const fields = /* @__PURE__ */ new Map();
    const errors = [];
    for (const field of serialized.fields) {
      try {
        const typeParams = valueTypeLibrary.parseParamTypes(field.typeKey, field.typeParams);
        const valueSchema = valueTypeLibrary.getSchema(field.typeKey, typeParams);
        fields.set(field.shortKey, {
          valueTypeKey: field.typeKey,
          valueTypeParams: typeParams,
          schema: valueSchema,
          fullKey: field.fullKey,
          defaultValue: valueSchema.parse(field.defaultValue)
        });
      } catch (error) {
        errors.push({
          fullKey: field.fullKey,
          error: serializeError(error)
        });
      }
    }
    return {
      schematics: new _KVConfigSchematics(valueTypeLibrary, fields, serialized.extensionPrefixes ?? []),
      errors
    };
  }
};
var KVConfigBuilder = class {
  constructor(fieldDefs) {
    this.fieldDefs = fieldDefs;
    this.fields = /* @__PURE__ */ new Map();
  }
  with(key, value) {
    const field = this.fieldDefs.get(key);
    if (field === void 0) {
      throw new Error(`Field with key ${key} does not exist in the schematics.`);
    }
    this.fields.set(field.fullKey, value);
    return this;
  }
  build() {
    return mapToKVConfig(this.fields);
  }
};
var ParsedKVConfig = class _ParsedKVConfig {
  constructor(configMap) {
    this.configMap = configMap;
  }
  /**
   * @internal
   */
  static [createParsedKVConfig](configMap) {
    return new _ParsedKVConfig(configMap);
  }
  get(key) {
    return this.configMap.get(key);
  }
};
var PartialParsedKVConfig = class _PartialParsedKVConfig {
  constructor(configMap) {
    this.configMap = configMap;
  }
  static [createParsedKVConfig](configMap) {
    return new _PartialParsedKVConfig(configMap);
  }
  get(key) {
    return this.configMap.get(key);
  }
  has(key) {
    return this.configMap.has(key);
  }
};
function kvConfigToMap(config) {
  return new Map(config.fields.map((f4) => [f4.key, f4.value]));
}
function mapToKVConfig(map) {
  return {
    fields: Array.from(map.entries()).map(([key, value]) => ({ key, value }))
  };
}
function collapseKVStackRaw(configs) {
  const map = /* @__PURE__ */ new Map();
  for (const config of configs) {
    for (const { key, value } of config.fields) {
      map.set(key, value);
    }
  }
  return mapToKVConfig(map);
}
var emptyKVConfig = {
  fields: []
};
function singleLayerKVConfigStackOf(name, config) {
  return {
    layers: [
      {
        layerName: name,
        config
      }
    ]
  };
}
function addKVConfigToStack(stack, newLayerName, newLayerConfig) {
  return {
    layers: [
      ...stack.layers,
      {
        layerName: newLayerName,
        config: newLayerConfig
      }
    ]
  };
}
function deepEquals(a3, b4) {
  if (a3 === b4) {
    return true;
  }
  if (typeof a3 !== "object" || typeof b4 !== "object") {
    return false;
  }
  if (a3 === null || b4 === null) {
    return false;
  }
  if (Array.isArray(a3) !== Array.isArray(b4)) {
    return false;
  }
  if (Array.isArray(a3)) {
    if (a3.length !== b4?.length) {
      return false;
    }
    for (let i7 = 0; i7 < a3.length; i7++) {
      if (!deepEquals(a3[i7], b4[i7])) {
        return false;
      }
    }
    return true;
  }
  const aKeys = new Set(Object.keys(a3));
  const bKeys = new Set(Object.keys(b4));
  if (aKeys.size !== bKeys.size) {
    return false;
  }
  for (const key of aKeys) {
    if (!bKeys.has(key)) {
      return false;
    }
    if (!deepEquals(a3[key], b4[key])) {
      return false;
    }
  }
  return true;
}
function quoteString(str2, empty) {
  if (str2 === void 0 || str2 === "") {
    return empty ?? '""';
  }
  return JSON.stringify(str2);
}
function quoteStringWithManualEscape(str2, empty) {
  return quoteString(str2?.replace(/\\n/g, "\n"), empty);
}
var baseKVValueTypesLibraryBuilder = new KVFieldValueTypesLibraryBuilder({
  /**
   * Display name of the field.
   */
  displayName: external_exports.string().optional(),
  /**
   * Hint about the field. Shown when hovering over the field.
   */
  hint: external_exports.string().optional(),
  /**
   * A field can be marked as model centric when it loses its meaning when there is no model to
   * reference.
   *
   * An example would be prompt template. There is no point to configure prompt template when there
   * isn't a specific model.
   *
   * @experimental This field is experimental and may change in the future.
   */
  modelCentric: external_exports.boolean().optional(),
  /**
   * A field can be marked as non-configurable when it is only used as a means to carry information.
   * As a result, it will not be shown in the UI.
   *
   * An example would be context length for MLX, as you cannot change it.
   *
   * @experimental This field is experimental and may change in the future.
   */
  nonConfigurable: external_exports.boolean().optional(),
  /**
   * A field can be marked as engineDoesNotSupport when when the engine running the model does not
   * support the field.
   *
   * @experimental This field is experimental and may change in the future.
   */
  engineDoesNotSupport: external_exports.boolean().optional(),
  /**
   * A field can be marked as machine dependent when its value is highly dependent on the machine
   * that is being used. When exporting the config, one may decide to not include machine dependent
   * fields by default.
   *
   * An example would be GPU offload settings.
   *
   * @experimental This field is experimental and may change in the future.
   */
  machineDependent: external_exports.boolean().optional(),
  warning: external_exports.string().optional(),
  subtitle: external_exports.string().optional(),
  isExperimental: external_exports.boolean().optional(),
  dependencies: external_exports.array(kvConfigFieldDependencySchema).optional()
}).valueType("numeric", {
  paramType: {
    min: external_exports.number().optional(),
    max: external_exports.number().optional(),
    step: external_exports.number().optional(),
    int: external_exports.boolean().optional(),
    precision: external_exports.number().int().nonnegative().optional(),
    slider: external_exports.object({
      min: external_exports.number(),
      max: external_exports.number(),
      step: external_exports.number()
    }).optional(),
    shortHand: external_exports.string().optional()
  },
  schemaMaker: ({ min, max, int, precision }) => {
    let schema = external_exports.number();
    if (min !== void 0) {
      schema = schema.min(min);
    }
    if (max !== void 0) {
      schema = schema.max(max);
    }
    if (int) {
      if (precision !== void 0) {
        throw new Error("Cannot specify both int and precision.");
      }
      schema = schema.int();
    }
    return schema;
  },
  effectiveEquals: (a3, b4) => {
    return a3 === b4;
  },
  stringify: (value, { int, precision }) => {
    if (int) {
      return String(Math.round(value));
    }
    return value.toFixed(precision ?? 2);
  }
}).valueType("string", {
  paramType: {
    minLength: external_exports.number().optional(),
    maxLength: external_exports.number().optional(),
    isParagraph: external_exports.boolean().optional(),
    isProtected: external_exports.boolean().optional(),
    /**
     * If true, the string should match to a single token.
     */
    isToken: external_exports.boolean().optional(),
    placeholder: external_exports.string().optional()
  },
  schemaMaker: ({ minLength, maxLength }) => {
    let schema = external_exports.string();
    if (minLength !== void 0) {
      schema = schema.min(minLength);
    }
    if (maxLength !== void 0) {
      schema = schema.max(maxLength);
    }
    return schema;
  },
  effectiveEquals: (a3, b4) => {
    return a3 === b4;
  },
  stringify: (value, { isParagraph, isProtected }, { t: t6, desiredLength }) => {
    if (isProtected) {
      return "********";
    }
    if (isParagraph) {
      if (value === "") {
        return t6("config:customInputs.string.emptyParagraph", "<Empty>");
      } else {
        if (desiredLength === void 0 || value.length <= desiredLength) {
          return value;
        } else {
          return value.slice(0, Math.floor(desiredLength / 2)) + " ... " + value.slice(-Math.ceil(desiredLength / 2));
        }
      }
    } else {
      const quoted = quoteString(value);
      if (desiredLength === void 0 || quoted.length <= desiredLength) {
        return quoted;
      } else {
        return quoted.slice(0, Math.floor(desiredLength / 2)) + "..." + quoted.slice(-Math.ceil(desiredLength / 2));
      }
    }
  }
}).valueType("select", {
  paramType: {
    options: external_exports.array(external_exports.object({ value: external_exports.string().nonempty(), displayName: external_exports.string() }).or(external_exports.string())).refine((options) => {
      const values2 = /* @__PURE__ */ new Set();
      for (const option of options) {
        const value = typeof option === "string" ? option : option.value;
        if (values2.has(value)) {
          return false;
        }
        values2.add(value);
      }
      return true;
    }, {
      message: "Duplicate values in options."
    })
  },
  schemaMaker: ({ options }) => {
    const allowedValues = new Set(options.map((option) => typeof option === "string" ? option : option.value));
    return external_exports.string().refine((value) => allowedValues.has(value));
  },
  effectiveEquals: (a3, b4) => {
    return a3 === b4;
  },
  stringify: (value) => {
    return value;
  }
}).valueType("boolean", {
  paramType: {},
  schemaMaker: () => {
    return external_exports.boolean();
  },
  effectiveEquals: (a3, b4) => {
    return a3 === b4;
  },
  stringify: (value) => {
    return value ? "ON" : "OFF";
  }
}).valueType("stringArray", {
  paramType: {
    maxNumItems: external_exports.number().optional(),
    /**
     * Whether to allow empty strings in the array. Default is false.
     */
    allowEmptyStrings: external_exports.boolean().optional()
  },
  schemaMaker: ({ maxNumItems, allowEmptyStrings }) => {
    let stringSchema = external_exports.string();
    if (!allowEmptyStrings) {
      stringSchema = stringSchema.min(1);
    }
    let schema = external_exports.array(stringSchema);
    if (maxNumItems !== void 0) {
      schema = schema.max(maxNumItems);
    }
    return schema;
  },
  effectiveEquals: (a3, b4) => {
    return a3.length === b4.length && a3.every((v4, i7) => v4 === b4[i7]);
  },
  stringify: (value, _typeParam, { t: t6, desiredLength }) => {
    const quoted = value.map((v4) => quoteString(v4));
    if (quoted.length === 0) {
      return t6("config:customInputs.stringArray.empty", "<Empty>");
    }
    if (quoted.length <= 2 || desiredLength === void 0) {
      return quoted.join(", ");
    }
    let currentLength = quoted[0].length + quoted[1].length + 6;
    for (let i7 = 1; i7 < quoted.length - 1; i7++) {
      currentLength += quoted[i7].length + 2;
      if (currentLength >= desiredLength) {
        return quoted.slice(0, i7).join(", ") + ", ..." + quoted[quoted.length - 1];
      }
    }
    return quoted.join(", ");
  }
});
baseKVValueTypesLibraryBuilder.build();
var kvValueTypesLibrary = baseKVValueTypesLibraryBuilder.valueType("checkboxNumeric", {
  paramType: {
    min: external_exports.number().optional(),
    max: external_exports.number().optional(),
    step: external_exports.number().optional(),
    int: external_exports.boolean().optional(),
    uncheckedHint: external_exports.string().optional(),
    precision: external_exports.number().int().nonnegative().optional(),
    slider: external_exports.object({
      min: external_exports.number(),
      max: external_exports.number(),
      step: external_exports.number()
    }).optional()
  },
  schemaMaker: ({ min, max, int, precision }) => {
    let numberSchema = external_exports.number();
    if (min !== void 0) {
      numberSchema = numberSchema.min(min);
    }
    if (max !== void 0) {
      numberSchema = numberSchema.max(max);
    }
    if (int) {
      if (precision !== void 0) {
        throw new Error("Cannot specify both int and precision.");
      }
      numberSchema = numberSchema.int();
    }
    return external_exports.object({
      checked: external_exports.boolean(),
      value: numberSchema
    });
  },
  effectiveEquals: (a3, b4) => {
    if (a3.checked !== b4.checked) {
      return false;
    }
    if (!a3.checked) {
      return true;
    }
    return a3.value === b4.value;
  },
  stringify: (value, { int, precision }, { t: t6 }) => {
    if (!value.checked) {
      return t6("config:customInputs.checkboxNumeric.off", "OFF");
    }
    if (int) {
      return String(Math.round(value.value));
    }
    return value.value.toFixed(precision ?? 2);
  }
}).valueType("numericArray", {
  paramType: {
    min: external_exports.number().optional(),
    max: external_exports.number().optional(),
    int: external_exports.boolean().optional()
  },
  schemaMaker: ({ min, max, int }) => {
    let numberSchema = external_exports.number();
    if (min !== void 0) {
      numberSchema = numberSchema.min(min);
    }
    if (max !== void 0) {
      numberSchema = numberSchema.max(max);
    }
    if (int) {
      numberSchema = numberSchema.int();
    }
    return external_exports.array(numberSchema);
  },
  effectiveEquals: (a3, b4) => {
    return a3.length === b4.length && a3.every((v4, i7) => v4 === b4[i7]);
  },
  stringify: (value, { int }) => {
    return value.map((v4) => int ? String(Math.round(v4)) : String(v4)).join(", ");
  }
}).valueType("contextOverflowPolicy", {
  paramType: {},
  schemaMaker: () => {
    return llmContextOverflowPolicySchema;
  },
  effectiveEquals: (a3, b4) => {
    return a3 === b4;
  },
  stringify: (value, _typeParam, { t: t6 }) => {
    switch (value) {
      case "stopAtLimit":
        return t6("config:customInputs.contextOverflowPolicy.stopAtLimit", "Stop At Limit");
      case "truncateMiddle":
        return t6("config:customInputs.contextOverflowPolicy.truncateMiddle", "Truncate Middle");
      case "rollingWindow":
        return t6("config:customInputs.contextOverflowPolicy.rollingWindow", "Rolling Window");
    }
  }
}).valueType("context", {
  paramType: {},
  schemaMaker: () => {
    return external_exports.array(llmContextReferenceSchema);
  },
  effectiveEquals: (a3, b4) => {
    return deepEquals(a3, b4);
  },
  stringify: (value) => {
    return JSON.stringify(value, null, 2);
  }
}).valueType("contextLength", {
  paramType: {
    max: external_exports.number().optional()
  },
  schemaMaker: () => {
    return external_exports.number().int().positive();
  },
  effectiveEquals: (a3, b4) => {
    return a3 === b4;
  },
  stringify: (value, { max }) => {
    if (max === void 0) {
      return String(value);
    }
    return `${value}/${max}`;
  }
}).valueType("modelIdentifier", {
  paramType: {
    domain: external_exports.array(modelDomainTypeSchema).optional()
  },
  schemaMaker: () => {
    return external_exports.string();
  },
  effectiveEquals: (a3, b4) => {
    return a3 === b4;
  },
  stringify: (value) => {
    return value;
  }
}).valueType("llmPromptTemplate", {
  paramType: {},
  schemaMaker: () => {
    return llmPromptTemplateSchema;
  },
  effectiveEquals: (a3, b4) => {
    if (a3.type !== b4.type) {
      return false;
    }
    if (a3.stopStrings.length !== b4.stopStrings.length) {
      return false;
    }
    if (!a3.stopStrings.every((v4, i7) => v4 === b4.stopStrings[i7])) {
      return false;
    }
    switch (a3.type) {
      case "jinja":
        return a3.jinjaPromptTemplate?.template === b4.jinjaPromptTemplate?.template;
      case "manual":
        return a3.manualPromptTemplate?.beforeSystem === b4.manualPromptTemplate?.beforeSystem && a3.manualPromptTemplate?.afterSystem === b4.manualPromptTemplate?.afterSystem && a3.manualPromptTemplate?.beforeUser === b4.manualPromptTemplate?.beforeUser && a3.manualPromptTemplate?.afterUser === b4.manualPromptTemplate?.afterUser && a3.manualPromptTemplate?.beforeAssistant === b4.manualPromptTemplate?.beforeAssistant && a3.manualPromptTemplate?.afterAssistant === b4.manualPromptTemplate?.afterAssistant;
      default: {
        const exhaustiveCheck = a3.type;
        throw new Error("Unknown template type: " + exhaustiveCheck);
      }
    }
  },
  stringify: (value, _typeParam, { t: t6, desiredLength }) => {
    switch (value.type) {
      case "jinja": {
        const lead = `${t6("config:customInputs.llmPromptTemplate.type", "Type")}: ${t6("config:customInputs.llmPromptTemplate.types.jinja/label", "Jinja")}
${t6("config:customInputs.llmPromptTemplate.jinja.template/label", "Template")}: `;
        if (desiredLength === void 0) {
          return lead + value.jinjaPromptTemplate?.template;
        }
        const currentLength = lead.length;
        const remainingLength = Math.min(100, desiredLength - currentLength);
        const template = value.jinjaPromptTemplate?.template ?? "";
        if (template.length <= remainingLength) {
          return lead + template;
        }
        return lead + template.slice(0, Math.floor(remainingLength / 2)) + "..." + template.slice(-Math.ceil(remainingLength / 2));
      }
      case "manual": {
        return `${t6("config:customInputs.llmPromptTemplate.type", "Type")}: ${t6("config:customInputs.llmPromptTemplate.types.manual/label", "Manual")}
${t6("config:customInputs.llmPromptTemplate.manual.subfield.beforeSystem/label", "Before System")}: ${quoteStringWithManualEscape(value.manualPromptTemplate?.beforeSystem)}
${t6("config:customInputs.llmPromptTemplate.manual.subfield.afterSystem/label", "After System")}: ${quoteStringWithManualEscape(value.manualPromptTemplate?.afterSystem)}
${t6("config:customInputs.llmPromptTemplate.manual.subfield.beforeUser/label", "Before User")}: ${quoteStringWithManualEscape(value.manualPromptTemplate?.beforeUser)}
${t6("config:customInputs.llmPromptTemplate.manual.subfield.afterUser/label", "After User")}: ${quoteStringWithManualEscape(value.manualPromptTemplate?.afterUser)}
${t6("config:customInputs.llmPromptTemplate.manual.subfield.beforeAssistant/label", "Before Assistant")}: ${quoteStringWithManualEscape(value.manualPromptTemplate?.beforeAssistant)}
${t6("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label", "After Assistant")}: ${quoteStringWithManualEscape(value.manualPromptTemplate?.afterAssistant)}`;
      }
      default: {
        const exhaustiveCheck = value.type;
        throw new Error("Unknown template type: " + exhaustiveCheck);
      }
    }
  }
}).valueType("llmReasoningParsing", {
  paramType: {},
  schemaMaker: () => {
    return llmReasoningParsingSchema;
  },
  effectiveEquals: (a3, b4) => {
    return a3.startString === b4.startString && a3.endString === b4.endString;
  },
  stringify: (value) => {
    return JSON.stringify(value, null, 2);
  }
}).valueType("llamaStructuredOutput", {
  paramType: {},
  schemaMaker: () => {
    return llmStructuredPredictionSettingSchema;
  },
  effectiveEquals: (a3, b4) => {
    if (a3.type === "json" && b4.type === "json") {
      return deepEquals(a3, b4);
    } else if (a3.type === "none" && b4.type === "none") {
      return true;
    } else {
      return false;
    }
  },
  stringify: (value) => {
    return JSON.stringify(value, null, 2);
  }
}).valueType("speculativeDecodingDraftModel", {
  paramType: {},
  schemaMaker: () => {
    return external_exports.string();
  },
  effectiveEquals: (a3, b4) => {
    return a3 === b4;
  },
  stringify: (value, _typeParam, { t: t6 }) => {
    if (value === "") {
      return t6("config:customInputs.speculativeDecodingDraftModel.off", "OFF");
    }
    return value;
  }
}).valueType("toolUse", {
  paramType: {},
  schemaMaker: () => {
    return llmToolUseSettingSchema;
  },
  effectiveEquals: (a3, b4) => {
    return deepEquals(a3, b4);
  },
  stringify: (value) => {
    return JSON.stringify(value, null, 2);
  }
}).valueType("toolNaming", {
  paramType: {},
  schemaMaker: () => {
    return toolNamingSchema;
  },
  effectiveEquals: (a3, b4) => {
    return a3 === b4;
  },
  stringify: (value) => {
    return value;
  }
}).valueType("llamaAccelerationOffloadRatio", {
  paramType: {
    numLayers: external_exports.number().optional()
  },
  schemaMaker: () => {
    return llmLlamaAccelerationOffloadRatioSchema;
  },
  effectiveEquals: (a3, b4) => {
    const ratioA = a3 === "max" ? 1 : a3 === "off" ? 0 : a3;
    const ratioB = b4 === "max" ? 1 : b4 === "off" ? 0 : b4;
    return ratioA === ratioB;
  },
  stringify: (value, { numLayers }, { t: t6 }) => {
    if (value === "max" || value === 1) {
      const label = t6("config:customInputs.llamaAccelerationOffloadRatio.max", "MAX");
      if (numLayers !== 0) {
        return `${label} (${numLayers})`;
      }
      return label;
    }
    if (value === "off" || value === 0) {
      return t6("config:customInputs.llamaAccelerationOffloadRatio.off", "OFF");
    }
    if (numLayers !== void 0) {
      return String(Math.round(numLayers * value));
    }
    return (value * 100).toFixed(0) + "%";
  }
}).valueType("llamaMirostatSampling", {
  paramType: {},
  schemaMaker: () => {
    return llmLlamaMirostatSamplingConfigSchema;
  },
  effectiveEquals: (a3, b4) => {
    return deepEquals(a3, b4);
  },
  stringify: (value) => {
    return JSON.stringify(value, null, 2);
  }
}).valueType("llamaLogitBias", {
  paramType: {},
  schemaMaker: () => {
    return llmLlamaLogitBiasConfigSchema;
  },
  effectiveEquals: (a3, b4) => {
    return deepEquals(a3, b4);
  },
  stringify: (value) => {
    return JSON.stringify(value, null, 2);
  }
}).valueType("llamaCacheQuantizationType", {
  paramType: {},
  schemaMaker: () => {
    return external_exports.object({
      checked: external_exports.boolean(),
      value: llmLlamaCacheQuantizationTypeSchema
    });
  },
  effectiveEquals: (a3, b4) => {
    if (a3.checked !== b4.checked) {
      return false;
    }
    if (!a3.checked) {
      return true;
    }
    return a3.value === b4.value;
  },
  stringify: (value, _typeParam, { t: t6 }) => {
    if (!value.checked) {
      return t6("config:customInputs.llamaCacheQuantizationType.off", "OFF");
    }
    return value.value;
  }
}).valueType("mlxKvCacheQuantizationType", {
  paramType: {},
  schemaMaker: () => {
    return llmMlxKvCacheQuantizationSchema;
  },
  effectiveEquals: (a3, b4) => {
    if (a3.enabled !== b4.enabled) {
      return false;
    }
    if (!a3.enabled) {
      return true;
    }
    return a3.bits === b4.bits && a3.groupSize === b4.groupSize && a3.quantizedStart === b4.quantizedStart;
  },
  stringify: (value) => {
    return JSON.stringify(value, null, 2);
  }
}).valueType("retrievalChunkingMethod", {
  paramType: {},
  schemaMaker: () => {
    return retrievalChunkingMethodSchema;
  },
  effectiveEquals: (a3, b4) => {
    return deepEquals(a3, b4);
  },
  stringify: (value) => {
    return JSON.stringify(value, null, 2);
  }
}).valueType("envVars", {
  paramType: {},
  schemaMaker: () => {
    return allowableEnvVarsSchema;
  },
  effectiveEquals: (a3, b4) => {
    return deepEquals(a3, b4);
  },
  stringify: (value) => {
    return JSON.stringify(value, null, 2);
  }
}).valueType("gpuSplitConfig", {
  paramType: {},
  schemaMaker: () => {
    return gpuSplitConfigSchema;
  },
  effectiveEquals: (a3, b4) => {
    return deepEquals(a3, b4);
  },
  stringify: (value) => {
    return JSON.stringify(value, null, 2);
  }
}).build();
var globalConfigSchematics = new KVConfigSchematicsBuilder(kvValueTypesLibrary).extension("ext.virtualModel.customField").field("envVars", "envVars", {}, {}).scope("llm.prediction", (builder) => builder.field("temperature", "numeric", {
  min: 0,
  step: 0.01,
  slider: { min: 0, max: 1, step: 0.01 },
  precision: 2,
  shortHand: "temp"
}, 0.8).field("contextOverflowPolicy", "contextOverflowPolicy", {}, "truncateMiddle").field("maxPredictedTokens", "checkboxNumeric", { min: 1, int: true }, { checked: false, value: 1e3 }).field("stopStrings", "stringArray", {}, []).field("toolCallStopStrings", "stringArray", {}, []).field("structured", "llamaStructuredOutput", {}, { type: "none" }).scope("speculativeDecoding", (builder2) => builder2.field("draftModel", "speculativeDecodingDraftModel", {
  modelCentric: true
}, "").field("minDraftLengthToConsider", "numeric", {
  modelCentric: true,
  min: 0,
  int: true,
  slider: { min: 0, max: 10, step: 1 }
}, 0).field("numReuseTokens", "numeric", { modelCentric: true, min: 1, int: true }, 256).field("minContinueDraftingProbability", "numeric", {
  modelCentric: true,
  min: 0,
  max: 1,
  step: 0.01,
  precision: 2,
  slider: { min: 0, max: 1, step: 0.01 }
}, 0.75).field("maxTokensToDraft", "numeric", { modelCentric: true, min: 1, int: true, slider: { min: 10, max: 30, step: 1 } }, 16).field("numDraftTokensExact", "numeric", {
  modelCentric: true,
  min: 1,
  int: true,
  slider: { min: 1, max: 10, step: 1 }
}, 2)).field("tools", "toolUse", {}, { type: "none" }).field("toolNaming", "toolNaming", {}, "removeSpecial").field("promptTemplate", "llmPromptTemplate", { modelCentric: true }, {
  type: "manual",
  manualPromptTemplate: {
    beforeSystem: "Instruct: ",
    afterSystem: "\n",
    beforeAssistant: "AI: ",
    afterAssistant: "\n",
    beforeUser: "Human: ",
    afterUser: "\n"
  },
  stopStrings: []
}).field("systemPrompt", "string", { isParagraph: true }, "").field("seed", "checkboxNumeric", { int: true, min: -1, uncheckedHint: "config:seedUncheckedHint" }, { checked: false, value: -1 }).field("contextPrefill", "context", {}, []).field("topKSampling", "numeric", { min: -1, max: 500, int: true }, 40).field("repeatPenalty", "checkboxNumeric", { min: -1, step: 0.01 }, { checked: true, value: 1.1 }).field("minPSampling", "checkboxNumeric", { min: 0, max: 1, step: 0.01, precision: 2, slider: { min: 0, max: 1, step: 0.01 } }, { checked: true, value: 0.05 }).field("topPSampling", "checkboxNumeric", { min: 0, max: 1, step: 0.01, precision: 2, slider: { min: 0, max: 1, step: 0.01 } }, { checked: true, value: 0.95 }).field("logProbs", "checkboxNumeric", { min: 0, max: 100, int: true }, { checked: false, value: 0 }).scope("reasoning", (builder2) => builder2.field("parsing", "llmReasoningParsing", {}, {
  enabled: true,
  startString: "<think>",
  endString: "</think>"
})).scope("llama", (builder2) => builder2.field("cpuThreads", "numeric", { min: 1, int: true }, 4).field("frequencyPenalty", "checkboxNumeric", { precision: 2 }, { checked: false, value: 0 }).field("xtcProbability", "checkboxNumeric", { min: 0, max: 1, step: 0.01, precision: 2, slider: { min: 0, max: 1, step: 0.01 } }, { checked: false, value: 0.5 }).field("xtcThreshold", "checkboxNumeric", { min: 0, max: 1, step: 0.01, precision: 2, slider: { min: 0, max: 0.5, step: 0.01 } }, { checked: false, value: 0.1 }).field("presencePenalty", "checkboxNumeric", { precision: 2 }, { checked: false, value: 0 }).field("mirostatSampling", "llamaMirostatSampling", {}, {
  // Disabled by default
  version: 0,
  learningRate: 0.1,
  targetEntropy: 5
}).field("tailFreeSampling", "checkboxNumeric", { min: 0, max: 1, step: 0.01, precision: 2, slider: { min: 0, max: 1, step: 0.01 } }, { checked: false, value: 0.95 }).field("locallyTypicalSampling", "checkboxNumeric", { min: 0, max: 1, step: 0.01, precision: 2, slider: { min: 0, max: 1, step: 0.01 } }, { checked: false, value: 0.9 }).field("logitBias", "llamaLogitBias", {}, []))).scope("llm.load", (builder) => builder.field("contextLength", "contextLength", {
  machineDependent: true
}, 2048).field("numExperts", "numeric", { min: 0, int: true }, 0).field("seed", "checkboxNumeric", { int: true, min: -1, uncheckedHint: "config:seedUncheckedHint" }, { checked: false, value: -1 }).field("offloadKVCacheToGpu", "boolean", {}, true).field("numCpuExpertLayersRatio", "llamaAccelerationOffloadRatio", { machineDependent: true, isExperimental: true }, "off").scope("llama", (builder2) => builder2.scope("acceleration", (builder3) => builder3.field("offloadRatio", "llamaAccelerationOffloadRatio", { machineDependent: true }, "max")).field("cpuThreadPoolSize", "numeric", { min: 1, machineDependent: true }, 4).field("evalBatchSize", "numeric", { min: 1, int: true }, 512).field("flashAttention", "boolean", { isExperimental: true, warning: "config:flashAttentionWarning" }, false).field("ropeFrequencyBase", "checkboxNumeric", { min: 0, uncheckedHint: "config:ropeFrequencyBaseUncheckedHint" }, { checked: false, value: 0 }).field("ropeFrequencyScale", "checkboxNumeric", { min: 0, uncheckedHint: "config:ropeFrequencyScaleUncheckedHint" }, { checked: false, value: 0 }).field("keepModelInMemory", "boolean", {}, true).field("useFp16ForKVCache", "boolean", {}, true).field("tryMmap", "boolean", {}, true).field("kCacheQuantizationType", "llamaCacheQuantizationType", { isExperimental: true }, { checked: false, value: "f16" }).field("vCacheQuantizationType", "llamaCacheQuantizationType", { isExperimental: true, warning: "config:llamaKvCacheQuantizationWarning" }, { checked: false, value: "f16" })).scope("mlx", (builder2) => builder2.field("kvCacheQuantization", "mlxKvCacheQuantizationType", { isExperimental: true }, { enabled: false, bits: 8, groupSize: 64, quantizedStart: 5e3 }))).scope("load", (builder) => builder.field("gpuSplitConfig", "gpuSplitConfig", {}, defaultGPUSplitConfig).field("gpuStrictVramCap", "boolean", {}, false)).scope("embedding.load", (builder) => builder.field("contextLength", "contextLength", { machineDependent: true }, 2048).field("seed", "checkboxNumeric", { int: true, min: -1, uncheckedHint: "config:seedUncheckedHint" }, { checked: false, value: -1 }).scope("llama", (builder2) => builder2.scope("acceleration", (builder3) => builder3.field("offloadRatio", "llamaAccelerationOffloadRatio", { machineDependent: true }, "max")).field("evalBatchSize", "numeric", { min: 1, int: true }, 512).field("ropeFrequencyBase", "checkboxNumeric", { min: 0, uncheckedHint: "config:ropeFrequencyBaseUncheckedHint" }, { checked: false, value: 0 }).field("ropeFrequencyScale", "checkboxNumeric", { min: 0, uncheckedHint: "config:ropeFrequencyScaleUncheckedHint" }, { checked: false, value: 0 }).field("keepModelInMemory", "boolean", {}, true).field("tryMmap", "boolean", {}, true))).scope("retrieval", (builder) => builder.field("databaseFile", "string", { machineDependent: true }, "").field("chunkingMethod", "retrievalChunkingMethod", {}, {
  type: "recursive-v1",
  chunkSize: 512,
  chunkOverlap: 100
}).field("limit", "numeric", { min: 1, int: true }, 5).field("embeddingModel", "modelIdentifier", { domain: ["embedding"] }, "")).build();
var llmPredictionConfigSchematics = globalConfigSchematics.scoped("llm.prediction");
var llmSharedPredictionConfigSchematics = llmPredictionConfigSchematics.sliced("temperature", "maxPredictedTokens", "promptTemplate", "systemPrompt", "seed", "contextPrefill", "tools", "toolNaming", "reasoning.*");
llmSharedPredictionConfigSchematics.union(llmPredictionConfigSchematics.sliced("llama.*", "contextOverflowPolicy", "stopStrings", "toolCallStopStrings", "structured", "topKSampling", "repeatPenalty", "minPSampling", "topPSampling", "logProbs", "speculativeDecoding.draftModel", "speculativeDecoding.minContinueDraftingProbability", "speculativeDecoding.minDraftLengthToConsider", "speculativeDecoding.maxTokensToDraft", "speculativeDecoding.numReuseTokens"));
llmSharedPredictionConfigSchematics.union(llmPredictionConfigSchematics.sliced("mlx.*", "contextOverflowPolicy", "stopStrings", "toolCallStopStrings", "structured", "repeatPenalty", "minPSampling", "topPSampling", "topKSampling", "speculativeDecoding.draftModel", "speculativeDecoding.numDraftTokensExact"));
llmSharedPredictionConfigSchematics.union(llmPredictionConfigSchematics.sliced("transformers.*"));
llmSharedPredictionConfigSchematics.union(llmPredictionConfigSchematics.sliced("onnx.*", "repeatPenalty", "topPSampling", "topKSampling"));
var llmLoadSchematics = globalConfigSchematics.scoped("llm.load").union(globalConfigSchematics.sliced("envVars"));
var llmSharedLoadConfigSchematics = llmLoadSchematics.sliced("contextLength", "seed", "envVars");
var llamaLoadConfigSchematics = globalConfigSchematics.sliced("llama.load.*", "load.*");
var llmLlamaLoadConfigSchematics = llmSharedLoadConfigSchematics.union(llmLoadSchematics.sliced("llama.*", "load.*", "offloadKVCacheToGpu")).union(llamaLoadConfigSchematics);
llmSharedLoadConfigSchematics.union(llmLoadSchematics.sliced("mlx.*"));
llmSharedLoadConfigSchematics.union(llmLoadSchematics.sliced("transformers.*"));
llmSharedLoadConfigSchematics.union(llmLoadSchematics.sliced("onnx.*"));
var llmLlamaMoeAdditionalLoadConfigSchematics = llmLoadSchematics.sliced("numExperts", "numCpuExpertLayersRatio");
var llmLlamaMoeLoadConfigSchematics = llmLlamaLoadConfigSchematics.union(llmLlamaMoeAdditionalLoadConfigSchematics);
var embeddingLoadSchematics = globalConfigSchematics.scoped("embedding.load").union(globalConfigSchematics.sliced("load.*"));
var embeddingSharedLoadConfigSchematics = embeddingLoadSchematics.sliced("contextLength", "seed");
var retrievalSchematics = globalConfigSchematics.scoped("retrieval");
var embeddingLlamaLoadConfigSchematics = embeddingSharedLoadConfigSchematics.union(embeddingLoadSchematics.sliced("llama.*")).union(llamaLoadConfigSchematics);
new KVConfigSchematicsBuilder(kvValueTypesLibrary).build();
function maybeFalseNumberToCheckboxNumeric(maybeFalseNumber, valueWhenUnchecked) {
  if (maybeFalseNumber === void 0) {
    return void 0;
  }
  if (maybeFalseNumber === false) {
    return { checked: false, value: valueWhenUnchecked };
  }
  return { checked: true, value: maybeFalseNumber };
}
function llmPredictionConfigToKVConfig(config) {
  const top = llmPredictionConfigSchematics.buildPartialConfig({
    "temperature": config.temperature,
    "contextOverflowPolicy": config.contextOverflowPolicy,
    "maxPredictedTokens": maybeFalseNumberToCheckboxNumeric(config.maxTokens, 1),
    "stopStrings": config.stopStrings,
    "toolCallStopStrings": config.toolCallStopStrings,
    "structured": config.structured,
    "tools": config.rawTools,
    "toolNaming": config.toolNaming,
    "topKSampling": config.topKSampling,
    "repeatPenalty": maybeFalseNumberToCheckboxNumeric(config.repeatPenalty, 1.1),
    "minPSampling": maybeFalseNumberToCheckboxNumeric(config.minPSampling, 0.05),
    "topPSampling": maybeFalseNumberToCheckboxNumeric(config.topPSampling, 0.95),
    "llama.xtcProbability": maybeFalseNumberToCheckboxNumeric(config.xtcProbability, 0),
    "llama.xtcThreshold": maybeFalseNumberToCheckboxNumeric(config.xtcThreshold, 0),
    "logProbs": maybeFalseNumberToCheckboxNumeric(config.logProbs, 0),
    "llama.cpuThreads": config.cpuThreads,
    "promptTemplate": config.promptTemplate,
    "speculativeDecoding.draftModel": config.draftModel,
    "speculativeDecoding.numDraftTokensExact": config.speculativeDecodingNumDraftTokensExact,
    "speculativeDecoding.minDraftLengthToConsider": config.speculativeDecodingMinDraftLengthToConsider,
    "speculativeDecoding.minContinueDraftingProbability": config.speculativeDecodingMinContinueDraftingProbability,
    "reasoning.parsing": config.reasoningParsing
  });
  if (config.raw !== void 0) {
    return collapseKVStackRaw([config.raw, top]);
  }
  return top;
}
var lib = {};
var helpers = {};
var hasRequiredHelpers;
function requireHelpers() {
  if (hasRequiredHelpers) return helpers;
  hasRequiredHelpers = 1;
  var ValidationError = helpers.ValidationError = function ValidationError2(message, instance, schema, path6, name, argument) {
    if (Array.isArray(path6)) {
      this.path = path6;
      this.property = path6.reduce(function(sum, item) {
        return sum + makeSuffix(item);
      }, "instance");
    } else if (path6 !== void 0) {
      this.property = path6;
    }
    if (message) {
      this.message = message;
    }
    if (schema) {
      var id = schema.$id || schema.id;
      this.schema = id || schema;
    }
    if (instance !== void 0) {
      this.instance = instance;
    }
    this.name = name;
    this.argument = argument;
    this.stack = this.toString();
  };
  ValidationError.prototype.toString = function toString() {
    return this.property + " " + this.message;
  };
  var ValidatorResult = helpers.ValidatorResult = function ValidatorResult2(instance, schema, options, ctx) {
    this.instance = instance;
    this.schema = schema;
    this.options = options;
    this.path = ctx.path;
    this.propertyPath = ctx.propertyPath;
    this.errors = [];
    this.throwError = options && options.throwError;
    this.throwFirst = options && options.throwFirst;
    this.throwAll = options && options.throwAll;
    this.disableFormat = options && options.disableFormat === true;
  };
  ValidatorResult.prototype.addError = function addError(detail) {
    var err;
    if (typeof detail == "string") {
      err = new ValidationError(detail, this.instance, this.schema, this.path);
    } else {
      if (!detail) throw new Error("Missing error detail");
      if (!detail.message) throw new Error("Missing error message");
      if (!detail.name) throw new Error("Missing validator type");
      err = new ValidationError(detail.message, this.instance, this.schema, this.path, detail.name, detail.argument);
    }
    this.errors.push(err);
    if (this.throwFirst) {
      throw new ValidatorResultError(this);
    } else if (this.throwError) {
      throw err;
    }
    return err;
  };
  ValidatorResult.prototype.importErrors = function importErrors(res) {
    if (typeof res == "string" || res && res.validatorType) {
      this.addError(res);
    } else if (res && res.errors) {
      this.errors = this.errors.concat(res.errors);
    }
  };
  function stringizer(v4, i7) {
    return i7 + ": " + v4.toString() + "\n";
  }
  ValidatorResult.prototype.toString = function toString(res) {
    return this.errors.map(stringizer).join("");
  };
  Object.defineProperty(ValidatorResult.prototype, "valid", { get: function() {
    return !this.errors.length;
  } });
  helpers.ValidatorResultError = ValidatorResultError;
  function ValidatorResultError(result) {
    if (typeof Error.captureStackTrace === "function") {
      Error.captureStackTrace(this, ValidatorResultError);
    }
    this.instance = result.instance;
    this.schema = result.schema;
    this.options = result.options;
    this.errors = result.errors;
  }
  ValidatorResultError.prototype = new Error();
  ValidatorResultError.prototype.constructor = ValidatorResultError;
  ValidatorResultError.prototype.name = "Validation Error";
  var SchemaError = helpers.SchemaError = function SchemaError2(msg, schema) {
    this.message = msg;
    this.schema = schema;
    Error.call(this, msg);
    if (typeof Error.captureStackTrace === "function") {
      Error.captureStackTrace(this, SchemaError2);
    }
  };
  SchemaError.prototype = Object.create(
    Error.prototype,
    {
      constructor: { value: SchemaError, enumerable: false },
      name: { value: "SchemaError", enumerable: false }
    }
  );
  var SchemaContext = helpers.SchemaContext = function SchemaContext2(schema, options, path6, base, schemas) {
    this.schema = schema;
    this.options = options;
    if (Array.isArray(path6)) {
      this.path = path6;
      this.propertyPath = path6.reduce(function(sum, item) {
        return sum + makeSuffix(item);
      }, "instance");
    } else {
      this.propertyPath = path6;
    }
    this.base = base;
    this.schemas = schemas;
  };
  SchemaContext.prototype.resolve = function resolve(target) {
    return (() => resolveUrl(this.base, target))();
  };
  SchemaContext.prototype.makeChild = function makeChild(schema, propertyName) {
    var path6 = propertyName === void 0 ? this.path : this.path.concat([propertyName]);
    var id = schema.$id || schema.id;
    let base = (() => resolveUrl(this.base, id || ""))();
    var ctx = new SchemaContext(schema, this.options, path6, base, Object.create(this.schemas));
    if (id && !ctx.schemas[base]) {
      ctx.schemas[base] = schema;
    }
    return ctx;
  };
  var FORMAT_REGEXPS = helpers.FORMAT_REGEXPS = {
    // 7.3.1. Dates, Times, and Duration
    "date-time": /^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-(3[01]|0[1-9]|[12][0-9])[tT ](2[0-4]|[01][0-9]):([0-5][0-9]):(60|[0-5][0-9])(\.\d+)?([zZ]|[+-]([0-5][0-9]):(60|[0-5][0-9]))$/,
    "date": /^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-(3[01]|0[1-9]|[12][0-9])$/,
    "time": /^(2[0-4]|[01][0-9]):([0-5][0-9]):(60|[0-5][0-9])$/,
    "duration": /P(T\d+(H(\d+M(\d+S)?)?|M(\d+S)?|S)|\d+(D|M(\d+D)?|Y(\d+M(\d+D)?)?)(T\d+(H(\d+M(\d+S)?)?|M(\d+S)?|S))?|\d+W)/i,
    // 7.3.2. Email Addresses
    // TODO: fix the email production
    "email": /^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/,
    "idn-email": /^("(?:[!#-\[\]-\u{10FFFF}]|\\[\t -\u{10FFFF}])*"|[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}](?:\.?[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}])*)@([!#-'*+\-/-9=?A-Z\^-\u{10FFFF}](?:\.?[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}])*|\[[!-Z\^-\u{10FFFF}]*\])$/u,
    // 7.3.3. Hostnames
    // 7.3.4. IP Addresses
    "ip-address": /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,
    // FIXME whitespace is invalid
    "ipv6": /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/,
    // 7.3.5. Resource Identifiers
    // TODO: A more accurate regular expression for "uri" goes:
    // [A-Za-z][+\-.0-9A-Za-z]*:((/(/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?)?)?#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|(/(/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~])|/?%[0-9A-Fa-f]{2}|[!$&-.0-;=?-Z_a-z~])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*(#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*)?|/(/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+(:\d*)?|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?:\d*|\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)?)?
    "uri": /^[a-zA-Z][a-zA-Z0-9+.-]*:[^\s]*$/,
    "uri-reference": /^(((([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|([A-Za-z][+\-.0-9A-Za-z]*:?)?)|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|(\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?)?))#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|(([A-Za-z][+\-.0-9A-Za-z]*)?%[0-9A-Fa-f]{2}|[!$&-.0-9;=@_~]|[A-Za-z][+\-.0-9A-Za-z]*[!$&-*,;=@_~])(%[0-9A-Fa-f]{2}|[!$&-.0-9;=@-Z_a-z~])*((([/?](%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*)?#|[/?])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*)?|([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+(:\d*)?|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?:\d*|\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)?|[A-Za-z][+\-.0-9A-Za-z]*:?)?$/,
    "iri": /^[a-zA-Z][a-zA-Z0-9+.-]*:[^\s]*$/,
    "iri-reference": /^(((([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~-\u{10FFFF}]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|([A-Za-z][+\-.0-9A-Za-z]*:?)?)|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~-\u{10FFFF}])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|(\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?)?))#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|(([A-Za-z][+\-.0-9A-Za-z]*)?%[0-9A-Fa-f]{2}|[!$&-.0-9;=@_~-\u{10FFFF}]|[A-Za-z][+\-.0-9A-Za-z]*[!$&-*,;=@_~-\u{10FFFF}])(%[0-9A-Fa-f]{2}|[!$&-.0-9;=@-Z_a-z~-\u{10FFFF}])*((([/?](%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*)?#|[/?])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*)?|([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~-\u{10FFFF}]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~-\u{10FFFF}])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+(:\d*)?|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?:\d*|\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)?|[A-Za-z][+\-.0-9A-Za-z]*:?)?$/u,
    "uuid": /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i,
    // 7.3.6. uri-template
    "uri-template": /(%[0-9a-f]{2}|[!#$&(-;=?@\[\]_a-z~]|\{[!#&+,./;=?@|]?(%[0-9a-f]{2}|[0-9_a-z])(\.?(%[0-9a-f]{2}|[0-9_a-z]))*(:[1-9]\d{0,3}|\*)?(,(%[0-9a-f]{2}|[0-9_a-z])(\.?(%[0-9a-f]{2}|[0-9_a-z]))*(:[1-9]\d{0,3}|\*)?)*\})*/iu,
    // 7.3.7. JSON Pointers
    "json-pointer": /^(\/([\x00-\x2e0-@\[-}\x7f]|~[01])*)*$/iu,
    "relative-json-pointer": /^\d+(#|(\/([\x00-\x2e0-@\[-}\x7f]|~[01])*)*)$/iu,
    // hostname regex from: http://stackoverflow.com/a/1420225/5628
    "hostname": /^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?)*\.?$/,
    "host-name": /^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?)*\.?$/,
    "utc-millisec": function(input) {
      return typeof input === "string" && parseFloat(input) === parseInt(input, 10) && !isNaN(input);
    },
    // 7.3.8. regex
    "regex": function(input) {
      var result = true;
      try {
        new RegExp(input);
      } catch (e9) {
        result = false;
      }
      return result;
    },
    // Other definitions
    // "style" was removed from JSON Schema in draft-4 and is deprecated
    "style": /[\r\n\t ]*[^\r\n\t ][^:]*:[\r\n\t ]*[^\r\n\t ;]*[\r\n\t ]*;?/,
    // "color" was removed from JSON Schema in draft-4 and is deprecated
    "color": /^(#?([0-9A-Fa-f]{3}){1,2}\b|aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow|(rgb\(\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*\))|(rgb\(\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*\)))$/,
    "phone": /^\+(?:[0-9] ?){6,14}[0-9]$/,
    "alpha": /^[a-zA-Z]+$/,
    "alphanumeric": /^[a-zA-Z0-9]+$/
  };
  FORMAT_REGEXPS.regexp = FORMAT_REGEXPS.regex;
  FORMAT_REGEXPS.pattern = FORMAT_REGEXPS.regex;
  FORMAT_REGEXPS.ipv4 = FORMAT_REGEXPS["ip-address"];
  helpers.isFormat = function isFormat(input, format, validator2) {
    if (typeof input === "string" && FORMAT_REGEXPS[format] !== void 0) {
      if (FORMAT_REGEXPS[format] instanceof RegExp) {
        return FORMAT_REGEXPS[format].test(input);
      }
      if (typeof FORMAT_REGEXPS[format] === "function") {
        return FORMAT_REGEXPS[format](input);
      }
    } else if (validator2 && validator2.customFormats && typeof validator2.customFormats[format] === "function") {
      return validator2.customFormats[format](input);
    }
    return true;
  };
  var makeSuffix = helpers.makeSuffix = function makeSuffix2(key) {
    key = key.toString();
    if (!key.match(/[.\s\[\]]/) && !key.match(/^[\d]/)) {
      return "." + key;
    }
    if (key.match(/^\d+$/)) {
      return "[" + key + "]";
    }
    return "[" + JSON.stringify(key) + "]";
  };
  helpers.deepCompareStrict = function deepCompareStrict(a3, b4) {
    if (typeof a3 !== typeof b4) {
      return false;
    }
    if (Array.isArray(a3)) {
      if (!Array.isArray(b4)) {
        return false;
      }
      if (a3.length !== b4.length) {
        return false;
      }
      return a3.every(function(v4, i7) {
        return deepCompareStrict(a3[i7], b4[i7]);
      });
    }
    if (typeof a3 === "object") {
      if (!a3 || !b4) {
        return a3 === b4;
      }
      var aKeys = Object.keys(a3);
      var bKeys = Object.keys(b4);
      if (aKeys.length !== bKeys.length) {
        return false;
      }
      return aKeys.every(function(v4) {
        return deepCompareStrict(a3[v4], b4[v4]);
      });
    }
    return a3 === b4;
  };
  function deepMerger(target, dst, e9, i7) {
    if (typeof e9 === "object") {
      dst[i7] = deepMerge(target[i7], e9);
    } else {
      if (target.indexOf(e9) === -1) {
        dst.push(e9);
      }
    }
  }
  function copyist(src, dst, key) {
    dst[key] = src[key];
  }
  function copyistWithDeepMerge(target, src, dst, key) {
    if (typeof src[key] !== "object" || !src[key]) {
      dst[key] = src[key];
    } else {
      if (!target[key]) {
        dst[key] = src[key];
      } else {
        dst[key] = deepMerge(target[key], src[key]);
      }
    }
  }
  function deepMerge(target, src) {
    var array = Array.isArray(src);
    var dst = array && [] || {};
    if (array) {
      target = target || [];
      dst = dst.concat(target);
      src.forEach(deepMerger.bind(null, target, dst));
    } else {
      if (target && typeof target === "object") {
        Object.keys(target).forEach(copyist.bind(null, target, dst));
      }
      Object.keys(src).forEach(copyistWithDeepMerge.bind(null, target, src, dst));
    }
    return dst;
  }
  helpers.deepMerge = deepMerge;
  helpers.objectGetPath = function objectGetPath(o9, s6) {
    var parts = s6.split("/").slice(1);
    var k2;
    while (typeof (k2 = parts.shift()) == "string") {
      var n7 = decodeURIComponent(k2.replace(/~0/, "~").replace(/~1/g, "/"));
      if (!(n7 in o9)) return;
      o9 = o9[n7];
    }
    return o9;
  };
  function pathEncoder(v4) {
    return "/" + encodeURIComponent(v4).replace(/~/g, "%7E");
  }
  helpers.encodePath = function encodePointer(a3) {
    return a3.map(pathEncoder).join("");
  };
  helpers.getDecimalPlaces = function getDecimalPlaces(number) {
    var decimalPlaces = 0;
    if (isNaN(number)) return decimalPlaces;
    if (typeof number !== "number") {
      number = Number(number);
    }
    var parts = number.toString().split("e");
    if (parts.length === 2) {
      if (parts[1][0] !== "-") {
        return decimalPlaces;
      } else {
        decimalPlaces = Number(parts[1].slice(1));
      }
    }
    var decimalParts = parts[0].split(".");
    if (decimalParts.length === 2) {
      decimalPlaces += decimalParts[1].length;
    }
    return decimalPlaces;
  };
  helpers.isSchema = function isSchema(val2) {
    return typeof val2 === "object" && val2 || typeof val2 === "boolean";
  };
  var resolveUrl = helpers.resolveUrl = function resolveUrl2(from, to) {
    const resolvedUrl = new URL(to, new URL(from, "resolve://"));
    if (resolvedUrl.protocol === "resolve:") {
      const { pathname, search, hash } = resolvedUrl;
      return pathname + search + hash;
    }
    return resolvedUrl.toString();
  };
  return helpers;
}
var attribute_1;
var hasRequiredAttribute;
function requireAttribute() {
  if (hasRequiredAttribute) return attribute_1;
  hasRequiredAttribute = 1;
  var helpers2 = requireHelpers();
  var ValidatorResult = helpers2.ValidatorResult;
  var SchemaError = helpers2.SchemaError;
  var attribute = {};
  attribute.ignoreProperties = {
    // informative properties
    "id": true,
    "default": true,
    "description": true,
    "title": true,
    // arguments to other properties
    "additionalItems": true,
    "then": true,
    "else": true,
    // special-handled properties
    "$schema": true,
    "$ref": true,
    "extends": true
  };
  var validators = attribute.validators = {};
  validators.type = function validateType(instance, schema, options, ctx) {
    if (instance === void 0) {
      return null;
    }
    var result = new ValidatorResult(instance, schema, options, ctx);
    var types2 = Array.isArray(schema.type) ? schema.type : [schema.type];
    if (!types2.some(this.testType.bind(this, instance, schema, options, ctx))) {
      var list = types2.map(function(v4) {
        if (!v4) return;
        var id = v4.$id || v4.id;
        return id ? "<" + id + ">" : v4 + "";
      });
      result.addError({
        name: "type",
        argument: list,
        message: "is not of a type(s) " + list
      });
    }
    return result;
  };
  function testSchemaNoThrow(instance, options, ctx, callback, schema) {
    var throwError = options.throwError;
    var throwAll = options.throwAll;
    options.throwError = false;
    options.throwAll = false;
    var res = this.validateSchema(instance, schema, options, ctx);
    options.throwError = throwError;
    options.throwAll = throwAll;
    if (!res.valid && callback instanceof Function) {
      callback(res);
    }
    return res.valid;
  }
  validators.anyOf = function validateAnyOf(instance, schema, options, ctx) {
    if (instance === void 0) {
      return null;
    }
    var result = new ValidatorResult(instance, schema, options, ctx);
    var inner2 = new ValidatorResult(instance, schema, options, ctx);
    if (!Array.isArray(schema.anyOf)) {
      throw new SchemaError("anyOf must be an array");
    }
    if (!schema.anyOf.some(
      testSchemaNoThrow.bind(
        this,
        instance,
        options,
        ctx,
        function(res) {
          inner2.importErrors(res);
        }
      )
    )) {
      var list = schema.anyOf.map(function(v4, i7) {
        var id = v4.$id || v4.id;
        if (id) return "<" + id + ">";
        return v4.title && JSON.stringify(v4.title) || v4["$ref"] && "<" + v4["$ref"] + ">" || "[subschema " + i7 + "]";
      });
      if (options.nestedErrors) {
        result.importErrors(inner2);
      }
      result.addError({
        name: "anyOf",
        argument: list,
        message: "is not any of " + list.join(",")
      });
    }
    return result;
  };
  validators.allOf = function validateAllOf(instance, schema, options, ctx) {
    if (instance === void 0) {
      return null;
    }
    if (!Array.isArray(schema.allOf)) {
      throw new SchemaError("allOf must be an array");
    }
    var result = new ValidatorResult(instance, schema, options, ctx);
    var self2 = this;
    schema.allOf.forEach(function(v4, i7) {
      var valid = self2.validateSchema(instance, v4, options, ctx);
      if (!valid.valid) {
        var id = v4.$id || v4.id;
        var msg = id || v4.title && JSON.stringify(v4.title) || v4["$ref"] && "<" + v4["$ref"] + ">" || "[subschema " + i7 + "]";
        result.addError({
          name: "allOf",
          argument: { id: msg, length: valid.errors.length, valid },
          message: "does not match allOf schema " + msg + " with " + valid.errors.length + " error[s]:"
        });
        result.importErrors(valid);
      }
    });
    return result;
  };
  validators.oneOf = function validateOneOf(instance, schema, options, ctx) {
    if (instance === void 0) {
      return null;
    }
    if (!Array.isArray(schema.oneOf)) {
      throw new SchemaError("oneOf must be an array");
    }
    var result = new ValidatorResult(instance, schema, options, ctx);
    var inner2 = new ValidatorResult(instance, schema, options, ctx);
    var count = schema.oneOf.filter(
      testSchemaNoThrow.bind(
        this,
        instance,
        options,
        ctx,
        function(res) {
          inner2.importErrors(res);
        }
      )
    ).length;
    var list = schema.oneOf.map(function(v4, i7) {
      var id = v4.$id || v4.id;
      return id || v4.title && JSON.stringify(v4.title) || v4["$ref"] && "<" + v4["$ref"] + ">" || "[subschema " + i7 + "]";
    });
    if (count !== 1) {
      if (options.nestedErrors) {
        result.importErrors(inner2);
      }
      result.addError({
        name: "oneOf",
        argument: list,
        message: "is not exactly one from " + list.join(",")
      });
    }
    return result;
  };
  validators.if = function validateIf(instance, schema, options, ctx) {
    if (instance === void 0) return null;
    if (!helpers2.isSchema(schema.if)) throw new Error('Expected "if" keyword to be a schema');
    var ifValid = testSchemaNoThrow.call(this, instance, options, ctx, null, schema.if);
    var result = new ValidatorResult(instance, schema, options, ctx);
    var res;
    if (ifValid) {
      if (schema.then === void 0) return;
      if (!helpers2.isSchema(schema.then)) throw new Error('Expected "then" keyword to be a schema');
      res = this.validateSchema(instance, schema.then, options, ctx.makeChild(schema.then));
      result.importErrors(res);
    } else {
      if (schema.else === void 0) return;
      if (!helpers2.isSchema(schema.else)) throw new Error('Expected "else" keyword to be a schema');
      res = this.validateSchema(instance, schema.else, options, ctx.makeChild(schema.else));
      result.importErrors(res);
    }
    return result;
  };
  function getEnumerableProperty(object, key) {
    if (Object.hasOwnProperty.call(object, key)) return object[key];
    if (!(key in object)) return;
    while (object = Object.getPrototypeOf(object)) {
      if (Object.propertyIsEnumerable.call(object, key)) return object[key];
    }
  }
  validators.propertyNames = function validatePropertyNames(instance, schema, options, ctx) {
    if (!this.types.object(instance)) return;
    var result = new ValidatorResult(instance, schema, options, ctx);
    var subschema = schema.propertyNames !== void 0 ? schema.propertyNames : {};
    if (!helpers2.isSchema(subschema)) throw new SchemaError('Expected "propertyNames" to be a schema (object or boolean)');
    for (var property in instance) {
      if (getEnumerableProperty(instance, property) !== void 0) {
        var res = this.validateSchema(property, subschema, options, ctx.makeChild(subschema));
        result.importErrors(res);
      }
    }
    return result;
  };
  validators.properties = function validateProperties(instance, schema, options, ctx) {
    if (!this.types.object(instance)) return;
    var result = new ValidatorResult(instance, schema, options, ctx);
    var properties = schema.properties || {};
    for (var property in properties) {
      var subschema = properties[property];
      if (subschema === void 0) {
        continue;
      } else if (subschema === null) {
        throw new SchemaError('Unexpected null, expected schema in "properties"');
      }
      if (typeof options.preValidateProperty == "function") {
        options.preValidateProperty(instance, property, subschema, options, ctx);
      }
      var prop = getEnumerableProperty(instance, property);
      var res = this.validateSchema(prop, subschema, options, ctx.makeChild(subschema, property));
      if (res.instance !== result.instance[property]) result.instance[property] = res.instance;
      result.importErrors(res);
    }
    return result;
  };
  function testAdditionalProperty(instance, schema, options, ctx, property, result) {
    if (!this.types.object(instance)) return;
    if (schema.properties && schema.properties[property] !== void 0) {
      return;
    }
    if (schema.additionalProperties === false) {
      result.addError({
        name: "additionalProperties",
        argument: property,
        message: "is not allowed to have the additional property " + JSON.stringify(property)
      });
    } else {
      var additionalProperties = schema.additionalProperties || {};
      if (typeof options.preValidateProperty == "function") {
        options.preValidateProperty(instance, property, additionalProperties, options, ctx);
      }
      var res = this.validateSchema(instance[property], additionalProperties, options, ctx.makeChild(additionalProperties, property));
      if (res.instance !== result.instance[property]) result.instance[property] = res.instance;
      result.importErrors(res);
    }
  }
  validators.patternProperties = function validatePatternProperties(instance, schema, options, ctx) {
    if (!this.types.object(instance)) return;
    var result = new ValidatorResult(instance, schema, options, ctx);
    var patternProperties = schema.patternProperties || {};
    for (var property in instance) {
      var test = true;
      for (var pattern in patternProperties) {
        var subschema = patternProperties[pattern];
        if (subschema === void 0) {
          continue;
        } else if (subschema === null) {
          throw new SchemaError('Unexpected null, expected schema in "patternProperties"');
        }
        try {
          var regexp = new RegExp(pattern, "u");
        } catch (_e2) {
          regexp = new RegExp(pattern);
        }
        if (!regexp.test(property)) {
          continue;
        }
        test = false;
        if (typeof options.preValidateProperty == "function") {
          options.preValidateProperty(instance, property, subschema, options, ctx);
        }
        var res = this.validateSchema(instance[property], subschema, options, ctx.makeChild(subschema, property));
        if (res.instance !== result.instance[property]) result.instance[property] = res.instance;
        result.importErrors(res);
      }
      if (test) {
        testAdditionalProperty.call(this, instance, schema, options, ctx, property, result);
      }
    }
    return result;
  };
  validators.additionalProperties = function validateAdditionalProperties(instance, schema, options, ctx) {
    if (!this.types.object(instance)) return;
    if (schema.patternProperties) {
      return null;
    }
    var result = new ValidatorResult(instance, schema, options, ctx);
    for (var property in instance) {
      testAdditionalProperty.call(this, instance, schema, options, ctx, property, result);
    }
    return result;
  };
  validators.minProperties = function validateMinProperties(instance, schema, options, ctx) {
    if (!this.types.object(instance)) return;
    var result = new ValidatorResult(instance, schema, options, ctx);
    var keys2 = Object.keys(instance);
    if (!(keys2.length >= schema.minProperties)) {
      result.addError({
        name: "minProperties",
        argument: schema.minProperties,
        message: "does not meet minimum property length of " + schema.minProperties
      });
    }
    return result;
  };
  validators.maxProperties = function validateMaxProperties(instance, schema, options, ctx) {
    if (!this.types.object(instance)) return;
    var result = new ValidatorResult(instance, schema, options, ctx);
    var keys2 = Object.keys(instance);
    if (!(keys2.length <= schema.maxProperties)) {
      result.addError({
        name: "maxProperties",
        argument: schema.maxProperties,
        message: "does not meet maximum property length of " + schema.maxProperties
      });
    }
    return result;
  };
  validators.items = function validateItems(instance, schema, options, ctx) {
    var self2 = this;
    if (!this.types.array(instance)) return;
    if (schema.items === void 0) return;
    var result = new ValidatorResult(instance, schema, options, ctx);
    instance.every(function(value, i7) {
      if (Array.isArray(schema.items)) {
        var items = schema.items[i7] === void 0 ? schema.additionalItems : schema.items[i7];
      } else {
        var items = schema.items;
      }
      if (items === void 0) {
        return true;
      }
      if (items === false) {
        result.addError({
          name: "items",
          message: "additionalItems not permitted"
        });
        return false;
      }
      var res = self2.validateSchema(value, items, options, ctx.makeChild(items, i7));
      if (res.instance !== result.instance[i7]) result.instance[i7] = res.instance;
      result.importErrors(res);
      return true;
    });
    return result;
  };
  validators.contains = function validateContains(instance, schema, options, ctx) {
    var self2 = this;
    if (!this.types.array(instance)) return;
    if (schema.contains === void 0) return;
    if (!helpers2.isSchema(schema.contains)) throw new Error('Expected "contains" keyword to be a schema');
    var result = new ValidatorResult(instance, schema, options, ctx);
    var count = instance.some(function(value, i7) {
      var res = self2.validateSchema(value, schema.contains, options, ctx.makeChild(schema.contains, i7));
      return res.errors.length === 0;
    });
    if (count === false) {
      result.addError({
        name: "contains",
        argument: schema.contains,
        message: "must contain an item matching given schema"
      });
    }
    return result;
  };
  validators.minimum = function validateMinimum(instance, schema, options, ctx) {
    if (!this.types.number(instance)) return;
    var result = new ValidatorResult(instance, schema, options, ctx);
    if (schema.exclusiveMinimum && schema.exclusiveMinimum === true) {
      if (!(instance > schema.minimum)) {
        result.addError({
          name: "minimum",
          argument: schema.minimum,
          message: "must be greater than " + schema.minimum
        });
      }
    } else {
      if (!(instance >= schema.minimum)) {
        result.addError({
          name: "minimum",
          argument: schema.minimum,
          message: "must be greater than or equal to " + schema.minimum
        });
      }
    }
    return result;
  };
  validators.maximum = function validateMaximum(instance, schema, options, ctx) {
    if (!this.types.number(instance)) return;
    var result = new ValidatorResult(instance, schema, options, ctx);
    if (schema.exclusiveMaximum && schema.exclusiveMaximum === true) {
      if (!(instance < schema.maximum)) {
        result.addError({
          name: "maximum",
          argument: schema.maximum,
          message: "must be less than " + schema.maximum
        });
      }
    } else {
      if (!(instance <= schema.maximum)) {
        result.addError({
          name: "maximum",
          argument: schema.maximum,
          message: "must be less than or equal to " + schema.maximum
        });
      }
    }
    return result;
  };
  validators.exclusiveMinimum = function validateExclusiveMinimum(instance, schema, options, ctx) {
    if (typeof schema.exclusiveMinimum === "boolean") return;
    if (!this.types.number(instance)) return;
    var result = new ValidatorResult(instance, schema, options, ctx);
    var valid = instance > schema.exclusiveMinimum;
    if (!valid) {
      result.addError({
        name: "exclusiveMinimum",
        argument: schema.exclusiveMinimum,
        message: "must be strictly greater than " + schema.exclusiveMinimum
      });
    }
    return result;
  };
  validators.exclusiveMaximum = function validateExclusiveMaximum(instance, schema, options, ctx) {
    if (typeof schema.exclusiveMaximum === "boolean") return;
    if (!this.types.number(instance)) return;
    var result = new ValidatorResult(instance, schema, options, ctx);
    var valid = instance < schema.exclusiveMaximum;
    if (!valid) {
      result.addError({
        name: "exclusiveMaximum",
        argument: schema.exclusiveMaximum,
        message: "must be strictly less than " + schema.exclusiveMaximum
      });
    }
    return result;
  };
  var validateMultipleOfOrDivisbleBy = function validateMultipleOfOrDivisbleBy2(instance, schema, options, ctx, validationType, errorMessage) {
    if (!this.types.number(instance)) return;
    var validationArgument = schema[validationType];
    if (validationArgument == 0) {
      throw new SchemaError(validationType + " cannot be zero");
    }
    var result = new ValidatorResult(instance, schema, options, ctx);
    var instanceDecimals = helpers2.getDecimalPlaces(instance);
    var divisorDecimals = helpers2.getDecimalPlaces(validationArgument);
    var maxDecimals = Math.max(instanceDecimals, divisorDecimals);
    var multiplier = Math.pow(10, maxDecimals);
    if (Math.round(instance * multiplier) % Math.round(validationArgument * multiplier) !== 0) {
      result.addError({
        name: validationType,
        argument: validationArgument,
        message: errorMessage + JSON.stringify(validationArgument)
      });
    }
    return result;
  };
  validators.multipleOf = function validateMultipleOf(instance, schema, options, ctx) {
    return validateMultipleOfOrDivisbleBy.call(this, instance, schema, options, ctx, "multipleOf", "is not a multiple of (divisible by) ");
  };
  validators.divisibleBy = function validateDivisibleBy(instance, schema, options, ctx) {
    return validateMultipleOfOrDivisbleBy.call(this, instance, schema, options, ctx, "divisibleBy", "is not divisible by (multiple of) ");
  };
  validators.required = function validateRequired(instance, schema, options, ctx) {
    var result = new ValidatorResult(instance, schema, options, ctx);
    if (instance === void 0 && schema.required === true) {
      result.addError({
        name: "required",
        message: "is required"
      });
    } else if (this.types.object(instance) && Array.isArray(schema.required)) {
      schema.required.forEach(function(n7) {
        if (getEnumerableProperty(instance, n7) === void 0) {
          result.addError({
            name: "required",
            argument: n7,
            message: "requires property " + JSON.stringify(n7)
          });
        }
      });
    }
    return result;
  };
  validators.pattern = function validatePattern(instance, schema, options, ctx) {
    if (!this.types.string(instance)) return;
    var result = new ValidatorResult(instance, schema, options, ctx);
    var pattern = schema.pattern;
    try {
      var regexp = new RegExp(pattern, "u");
    } catch (_e2) {
      regexp = new RegExp(pattern);
    }
    if (!instance.match(regexp)) {
      result.addError({
        name: "pattern",
        argument: schema.pattern,
        message: "does not match pattern " + JSON.stringify(schema.pattern.toString())
      });
    }
    return result;
  };
  validators.format = function validateFormat(instance, schema, options, ctx) {
    if (instance === void 0) return;
    var result = new ValidatorResult(instance, schema, options, ctx);
    if (!result.disableFormat && !helpers2.isFormat(instance, schema.format, this)) {
      result.addError({
        name: "format",
        argument: schema.format,
        message: "does not conform to the " + JSON.stringify(schema.format) + " format"
      });
    }
    return result;
  };
  validators.minLength = function validateMinLength(instance, schema, options, ctx) {
    if (!this.types.string(instance)) return;
    var result = new ValidatorResult(instance, schema, options, ctx);
    var hsp = instance.match(/[\uDC00-\uDFFF]/g);
    var length = instance.length - (hsp ? hsp.length : 0);
    if (!(length >= schema.minLength)) {
      result.addError({
        name: "minLength",
        argument: schema.minLength,
        message: "does not meet minimum length of " + schema.minLength
      });
    }
    return result;
  };
  validators.maxLength = function validateMaxLength(instance, schema, options, ctx) {
    if (!this.types.string(instance)) return;
    var result = new ValidatorResult(instance, schema, options, ctx);
    var hsp = instance.match(/[\uDC00-\uDFFF]/g);
    var length = instance.length - (hsp ? hsp.length : 0);
    if (!(length <= schema.maxLength)) {
      result.addError({
        name: "maxLength",
        argument: schema.maxLength,
        message: "does not meet maximum length of " + schema.maxLength
      });
    }
    return result;
  };
  validators.minItems = function validateMinItems(instance, schema, options, ctx) {
    if (!this.types.array(instance)) return;
    var result = new ValidatorResult(instance, schema, options, ctx);
    if (!(instance.length >= schema.minItems)) {
      result.addError({
        name: "minItems",
        argument: schema.minItems,
        message: "does not meet minimum length of " + schema.minItems
      });
    }
    return result;
  };
  validators.maxItems = function validateMaxItems(instance, schema, options, ctx) {
    if (!this.types.array(instance)) return;
    var result = new ValidatorResult(instance, schema, options, ctx);
    if (!(instance.length <= schema.maxItems)) {
      result.addError({
        name: "maxItems",
        argument: schema.maxItems,
        message: "does not meet maximum length of " + schema.maxItems
      });
    }
    return result;
  };
  function testArrays(v4, i7, a3) {
    var j3, len = a3.length;
    for (j3 = i7 + 1, len; j3 < len; j3++) {
      if (helpers2.deepCompareStrict(v4, a3[j3])) {
        return false;
      }
    }
    return true;
  }
  validators.uniqueItems = function validateUniqueItems(instance, schema, options, ctx) {
    if (schema.uniqueItems !== true) return;
    if (!this.types.array(instance)) return;
    var result = new ValidatorResult(instance, schema, options, ctx);
    if (!instance.every(testArrays)) {
      result.addError({
        name: "uniqueItems",
        message: "contains duplicate item"
      });
    }
    return result;
  };
  validators.dependencies = function validateDependencies(instance, schema, options, ctx) {
    if (!this.types.object(instance)) return;
    var result = new ValidatorResult(instance, schema, options, ctx);
    for (var property in schema.dependencies) {
      if (instance[property] === void 0) {
        continue;
      }
      var dep = schema.dependencies[property];
      var childContext = ctx.makeChild(dep, property);
      if (typeof dep == "string") {
        dep = [dep];
      }
      if (Array.isArray(dep)) {
        dep.forEach(function(prop) {
          if (instance[prop] === void 0) {
            result.addError({
              // FIXME there's two different "dependencies" errors here with slightly different outputs
              // Can we make these the same? Or should we create different error types?
              name: "dependencies",
              argument: childContext.propertyPath,
              message: "property " + prop + " not found, required by " + childContext.propertyPath
            });
          }
        });
      } else {
        var res = this.validateSchema(instance, dep, options, childContext);
        if (result.instance !== res.instance) result.instance = res.instance;
        if (res && res.errors.length) {
          result.addError({
            name: "dependencies",
            argument: childContext.propertyPath,
            message: "does not meet dependency required by " + childContext.propertyPath
          });
          result.importErrors(res);
        }
      }
    }
    return result;
  };
  validators["enum"] = function validateEnum(instance, schema, options, ctx) {
    if (instance === void 0) {
      return null;
    }
    if (!Array.isArray(schema["enum"])) {
      throw new SchemaError("enum expects an array", schema);
    }
    var result = new ValidatorResult(instance, schema, options, ctx);
    if (!schema["enum"].some(helpers2.deepCompareStrict.bind(null, instance))) {
      result.addError({
        name: "enum",
        argument: schema["enum"],
        message: "is not one of enum values: " + schema["enum"].map(String).join(",")
      });
    }
    return result;
  };
  validators["const"] = function validateEnum(instance, schema, options, ctx) {
    if (instance === void 0) {
      return null;
    }
    var result = new ValidatorResult(instance, schema, options, ctx);
    if (!helpers2.deepCompareStrict(schema["const"], instance)) {
      result.addError({
        name: "const",
        argument: schema["const"],
        message: "does not exactly match expected constant: " + schema["const"]
      });
    }
    return result;
  };
  validators.not = validators.disallow = function validateNot(instance, schema, options, ctx) {
    var self2 = this;
    if (instance === void 0) return null;
    var result = new ValidatorResult(instance, schema, options, ctx);
    var notTypes = schema.not || schema.disallow;
    if (!notTypes) return null;
    if (!Array.isArray(notTypes)) notTypes = [notTypes];
    notTypes.forEach(function(type) {
      if (self2.testType(instance, schema, options, ctx, type)) {
        var id = type && (type.$id || type.id);
        var schemaId = id || type;
        result.addError({
          name: "not",
          argument: schemaId,
          message: "is of prohibited type " + schemaId
        });
      }
    });
    return result;
  };
  attribute_1 = attribute;
  return attribute_1;
}
var scan = {};
var hasRequiredScan;
function requireScan() {
  if (hasRequiredScan) return scan;
  hasRequiredScan = 1;
  var helpers2 = requireHelpers();
  scan.SchemaScanResult = SchemaScanResult;
  function SchemaScanResult(found, ref) {
    this.id = found;
    this.ref = ref;
  }
  scan.scan = function scan2(base, schema) {
    function scanSchema(baseuri, schema2) {
      if (!schema2 || typeof schema2 != "object") return;
      if (schema2.$ref) {
        let resolvedUri = helpers2.resolveUrl(baseuri, schema2.$ref);
        ref[resolvedUri] = ref[resolvedUri] ? ref[resolvedUri] + 1 : 0;
        return;
      }
      var id = schema2.$id || schema2.id;
      let resolvedBase = helpers2.resolveUrl(baseuri, id);
      var ourBase = id ? resolvedBase : baseuri;
      if (ourBase) {
        if (ourBase.indexOf("#") < 0) ourBase += "#";
        if (found[ourBase]) {
          if (!helpers2.deepCompareStrict(found[ourBase], schema2)) {
            throw new Error("Schema <" + ourBase + "> already exists with different definition");
          }
          return found[ourBase];
        }
        found[ourBase] = schema2;
        if (ourBase[ourBase.length - 1] == "#") {
          found[ourBase.substring(0, ourBase.length - 1)] = schema2;
        }
      }
      scanArray(ourBase + "/items", Array.isArray(schema2.items) ? schema2.items : [schema2.items]);
      scanArray(ourBase + "/extends", Array.isArray(schema2.extends) ? schema2.extends : [schema2.extends]);
      scanSchema(ourBase + "/additionalItems", schema2.additionalItems);
      scanObject(ourBase + "/properties", schema2.properties);
      scanSchema(ourBase + "/additionalProperties", schema2.additionalProperties);
      scanObject(ourBase + "/definitions", schema2.definitions);
      scanObject(ourBase + "/patternProperties", schema2.patternProperties);
      scanObject(ourBase + "/dependencies", schema2.dependencies);
      scanArray(ourBase + "/disallow", schema2.disallow);
      scanArray(ourBase + "/allOf", schema2.allOf);
      scanArray(ourBase + "/anyOf", schema2.anyOf);
      scanArray(ourBase + "/oneOf", schema2.oneOf);
      scanSchema(ourBase + "/not", schema2.not);
    }
    function scanArray(baseuri, schemas) {
      if (!Array.isArray(schemas)) return;
      for (var i7 = 0; i7 < schemas.length; i7++) {
        scanSchema(baseuri + "/" + i7, schemas[i7]);
      }
    }
    function scanObject(baseuri, schemas) {
      if (!schemas || typeof schemas != "object") return;
      for (var p4 in schemas) {
        scanSchema(baseuri + "/" + p4, schemas[p4]);
      }
    }
    var found = {};
    var ref = {};
    scanSchema(base, schema);
    return new SchemaScanResult(found, ref);
  };
  return scan;
}
var validator;
var hasRequiredValidator;
function requireValidator() {
  if (hasRequiredValidator) return validator;
  hasRequiredValidator = 1;
  var attribute = requireAttribute();
  var helpers2 = requireHelpers();
  var scanSchema = requireScan().scan;
  var ValidatorResult = helpers2.ValidatorResult;
  var ValidatorResultError = helpers2.ValidatorResultError;
  var SchemaError = helpers2.SchemaError;
  var SchemaContext = helpers2.SchemaContext;
  var anonymousBase = "/";
  var Validator2 = function Validator3() {
    this.customFormats = Object.create(Validator3.prototype.customFormats);
    this.schemas = {};
    this.unresolvedRefs = [];
    this.types = Object.create(types2);
    this.attributes = Object.create(attribute.validators);
  };
  Validator2.prototype.customFormats = {};
  Validator2.prototype.schemas = null;
  Validator2.prototype.types = null;
  Validator2.prototype.attributes = null;
  Validator2.prototype.unresolvedRefs = null;
  Validator2.prototype.addSchema = function addSchema(schema, base) {
    var self2 = this;
    if (!schema) {
      return null;
    }
    var scan2 = scanSchema(base || anonymousBase, schema);
    var ourUri = base || schema.$id || schema.id;
    for (var uri in scan2.id) {
      this.schemas[uri] = scan2.id[uri];
    }
    for (var uri in scan2.ref) {
      this.unresolvedRefs.push(uri);
    }
    this.unresolvedRefs = this.unresolvedRefs.filter(function(uri2) {
      return typeof self2.schemas[uri2] === "undefined";
    });
    return this.schemas[ourUri];
  };
  Validator2.prototype.addSubSchemaArray = function addSubSchemaArray(baseuri, schemas) {
    if (!Array.isArray(schemas)) return;
    for (var i7 = 0; i7 < schemas.length; i7++) {
      this.addSubSchema(baseuri, schemas[i7]);
    }
  };
  Validator2.prototype.addSubSchemaObject = function addSubSchemaArray(baseuri, schemas) {
    if (!schemas || typeof schemas != "object") return;
    for (var p4 in schemas) {
      this.addSubSchema(baseuri, schemas[p4]);
    }
  };
  Validator2.prototype.setSchemas = function setSchemas(schemas) {
    this.schemas = schemas;
  };
  Validator2.prototype.getSchema = function getSchema(urn) {
    return this.schemas[urn];
  };
  Validator2.prototype.validate = function validate(instance, schema, options, ctx) {
    if (typeof schema !== "boolean" && typeof schema !== "object" || schema === null) {
      throw new SchemaError("Expected `schema` to be an object or boolean");
    }
    if (!options) {
      options = {};
    }
    var id = schema.$id || schema.id;
    let base = helpers2.resolveUrl(options.base, id || "");
    if (!ctx) {
      ctx = new SchemaContext(schema, options, [], base, Object.create(this.schemas));
      if (!ctx.schemas[base]) {
        ctx.schemas[base] = schema;
      }
      var found = scanSchema(base, schema);
      for (var n7 in found.id) {
        var sch = found.id[n7];
        ctx.schemas[n7] = sch;
      }
    }
    if (options.required && instance === void 0) {
      var result = new ValidatorResult(instance, schema, options, ctx);
      result.addError("is required, but is undefined");
      return result;
    }
    var result = this.validateSchema(instance, schema, options, ctx);
    if (!result) {
      throw new Error("Result undefined");
    } else if (options.throwAll && result.errors.length) {
      throw new ValidatorResultError(result);
    }
    return result;
  };
  function shouldResolve(schema) {
    var ref = typeof schema === "string" ? schema : schema.$ref;
    if (typeof ref == "string") return ref;
    return false;
  }
  Validator2.prototype.validateSchema = function validateSchema(instance, schema, options, ctx) {
    var result = new ValidatorResult(instance, schema, options, ctx);
    if (typeof schema === "boolean") {
      if (schema === true) {
        schema = {};
      } else if (schema === false) {
        schema = { type: [] };
      }
    } else if (!schema) {
      throw new Error("schema is undefined");
    }
    if (schema["extends"]) {
      if (Array.isArray(schema["extends"])) {
        var schemaobj = { schema, ctx };
        schema["extends"].forEach(this.schemaTraverser.bind(this, schemaobj));
        schema = schemaobj.schema;
        schemaobj.schema = null;
        schemaobj.ctx = null;
        schemaobj = null;
      } else {
        schema = helpers2.deepMerge(schema, this.superResolve(schema["extends"], ctx));
      }
    }
    var switchSchema = shouldResolve(schema);
    if (switchSchema) {
      var resolved = this.resolve(schema, switchSchema, ctx);
      var subctx = new SchemaContext(resolved.subschema, options, ctx.path, resolved.switchSchema, ctx.schemas);
      return this.validateSchema(instance, resolved.subschema, options, subctx);
    }
    var skipAttributes = options && options.skipAttributes || [];
    for (var key in schema) {
      if (!attribute.ignoreProperties[key] && skipAttributes.indexOf(key) < 0) {
        var validatorErr = null;
        var validator2 = this.attributes[key];
        if (validator2) {
          validatorErr = validator2.call(this, instance, schema, options, ctx);
        } else if (options.allowUnknownAttributes === false) {
          throw new SchemaError("Unsupported attribute: " + key, schema);
        }
        if (validatorErr) {
          result.importErrors(validatorErr);
        }
      }
    }
    if (typeof options.rewrite == "function") {
      var value = options.rewrite.call(this, instance, schema, options, ctx);
      result.instance = value;
    }
    return result;
  };
  Validator2.prototype.schemaTraverser = function schemaTraverser(schemaobj, s6) {
    schemaobj.schema = helpers2.deepMerge(schemaobj.schema, this.superResolve(s6, schemaobj.ctx));
  };
  Validator2.prototype.superResolve = function superResolve(schema, ctx) {
    var ref = shouldResolve(schema);
    if (ref) {
      return this.resolve(schema, ref, ctx).subschema;
    }
    return schema;
  };
  Validator2.prototype.resolve = function resolve(schema, switchSchema, ctx) {
    switchSchema = ctx.resolve(switchSchema);
    if (ctx.schemas[switchSchema]) {
      return { subschema: ctx.schemas[switchSchema], switchSchema };
    }
    let parsed = new URL(switchSchema, "thismessage::/");
    let fragment = parsed.hash;
    var document2 = fragment && fragment.length && switchSchema.substr(0, switchSchema.length - fragment.length);
    if (!document2 || !ctx.schemas[document2]) {
      throw new SchemaError("no such schema <" + switchSchema + ">", schema);
    }
    var subschema = helpers2.objectGetPath(ctx.schemas[document2], fragment.substr(1));
    if (subschema === void 0) {
      throw new SchemaError("no such schema " + fragment + " located in <" + document2 + ">", schema);
    }
    return { subschema, switchSchema };
  };
  Validator2.prototype.testType = function validateType(instance, schema, options, ctx, type) {
    if (type === void 0) {
      return;
    } else if (type === null) {
      throw new SchemaError('Unexpected null in "type" keyword');
    }
    if (typeof this.types[type] == "function") {
      return this.types[type].call(this, instance);
    }
    if (type && typeof type == "object") {
      var res = this.validateSchema(instance, type, options, ctx);
      return res === void 0 || !(res && res.errors.length);
    }
    return true;
  };
  var types2 = Validator2.prototype.types = {};
  types2.string = function testString(instance) {
    return typeof instance == "string";
  };
  types2.number = function testNumber(instance) {
    return typeof instance == "number" && isFinite(instance);
  };
  types2.integer = function testInteger(instance) {
    return typeof instance == "number" && instance % 1 === 0;
  };
  types2.boolean = function testBoolean(instance) {
    return typeof instance == "boolean";
  };
  types2.array = function testArray(instance) {
    return Array.isArray(instance);
  };
  types2["null"] = function testNull(instance) {
    return instance === null;
  };
  types2.date = function testDate(instance) {
    return instance instanceof Date;
  };
  types2.any = function testAny(instance) {
    return true;
  };
  types2.object = function testObject(instance) {
    return instance && typeof instance === "object" && !Array.isArray(instance) && !(instance instanceof Date);
  };
  validator = Validator2;
  return validator;
}
var hasRequiredLib;
function requireLib() {
  if (hasRequiredLib) return lib;
  hasRequiredLib = 1;
  var Validator2 = lib.Validator = requireValidator();
  lib.ValidatorResult = requireHelpers().ValidatorResult;
  lib.ValidatorResultError = requireHelpers().ValidatorResultError;
  lib.ValidationError = requireHelpers().ValidationError;
  lib.SchemaError = requireHelpers().SchemaError;
  lib.SchemaScanResult = requireScan().SchemaScanResult;
  lib.scan = requireScan().scan;
  lib.validate = function(instance, schema, options) {
    var v4 = new Validator2();
    return v4.validate(instance, schema, options);
  };
  return lib;
}
var libExports = requireLib();
var toolBaseSchema = external_exports.object({
  name: external_exports.string(),
  description: external_exports.string()
});
var SimpleToolCallContext = class {
  constructor(logger2, signal, callId) {
    this.logger = logger2;
    this.signal = signal;
    this.callId = callId;
  }
  status(text3) {
    this.logger.info(text3);
  }
  warn(text3) {
    this.logger.warn(text3);
  }
};
var functionToolSchema = toolBaseSchema.extend({
  type: external_exports.literal("function"),
  parametersSchema: zodSchemaSchema,
  checkParameters: external_exports.function(),
  implementation: external_exports.function()
});
var rawFunctionToolSchema = toolBaseSchema.extend({
  type: external_exports.literal("rawFunction"),
  parametersSchema: zodSchemaSchema,
  checkParameters: external_exports.function(),
  implementation: external_exports.function()
});
var unimplementedRawFunctionToolSchema = toolBaseSchema.extend({
  type: external_exports.literal("unimplementedRawFunction"),
  parametersJsonSchema: zodSchemaSchema,
  checkParameters: external_exports.function(),
  implementation: external_exports.function()
});
var remoteToolSchema = toolBaseSchema.extend({
  type: external_exports.literal("remoteTool"),
  pluginIdentifier: external_exports.string(),
  parametersJsonSchema: zodSchemaSchema,
  checkParameters: external_exports.function(),
  implementation: external_exports.function()
});
external_exports.discriminatedUnion("type", [
  functionToolSchema,
  rawFunctionToolSchema,
  unimplementedRawFunctionToolSchema,
  remoteToolSchema
]);
function jsonSchemaValidationErrorToAIReadableText(root, validationErrors) {
  return validationErrors.map((validatioNError) => {
    const fullPath = [root, ...validatioNError.path].join(".");
    return `${fullPath} ${validatioNError.message}`;
  }).join("\n");
}
var UnimplementedToolError = class extends Error {
  constructor(toolName) {
    super(`Tool "${toolName}" is not implemented.`);
  }
};
function internalCreateRemoteTool({ name, description, pluginIdentifier, parametersJsonSchema, implementation }) {
  return {
    name,
    description,
    type: "remoteTool",
    pluginIdentifier,
    parametersJsonSchema,
    checkParameters: (params) => {
      const jsonSchemaValidator = new libExports.Validator();
      const validationResult = jsonSchemaValidator.validate(params, parametersJsonSchema);
      if (validationResult.errors.length > 0) {
        throw new Error(text`
          Failed to parse arguments for tool "${name}":
          ${jsonSchemaValidationErrorToAIReadableText("params", validationResult.errors)}
        `);
      }
    },
    implementation
  };
}
function functionToolToLLMTool(tool) {
  return {
    type: "function",
    function: {
      name: tool.name,
      description: tool.description,
      parameters: zodToJsonSchema(tool.parametersSchema)
    }
  };
}
function rawFunctionToolToLLMTool(tool) {
  return {
    type: "function",
    function: {
      name: tool.name,
      description: tool.description,
      parameters: tool.parametersJsonSchema
    }
  };
}
function remoteToolToLLMTool(tool) {
  return {
    type: "function",
    function: {
      name: tool.name,
      description: tool.description,
      parameters: tool.parametersJsonSchema
    }
  };
}
function toolToLLMTool(tool) {
  const type = tool.type;
  switch (type) {
    case "function":
      return functionToolToLLMTool(tool);
    case "rawFunction":
    case "unimplementedRawFunction":
      return rawFunctionToolToLLMTool(tool);
    case "remoteTool":
      return remoteToolToLLMTool(tool);
    default: {
      const exhaustiveCheck = type;
      throw new Error(`Unhandled type: ${exhaustiveCheck}`);
    }
  }
}
var ToolCallRequestError = class extends Error {
  constructor(message, rawContent) {
    super(message);
    this.rawContent = rawContent;
  }
};
var BackendInterface = class {
  constructor() {
    this.unhandledEndpoints = /* @__PURE__ */ new Set();
    this.existingEndpointNames = /* @__PURE__ */ new Set();
    this.rpcEndpoints = /* @__PURE__ */ new Map();
    this.channelEndpoints = /* @__PURE__ */ new Map();
    this.signalEndpoints = /* @__PURE__ */ new Map();
    this.writableSignalEndpoints = /* @__PURE__ */ new Map();
  }
  withContextType() {
    return this;
  }
  assertEndpointNameNotExists(endpointName) {
    if (this.existingEndpointNames.has(endpointName)) {
      throw new Error(`Endpoint with name ${endpointName} already exists`);
    }
  }
  /**
   * Register an Rpc endpoint.
   */
  addRpcEndpoint(endpointName, { parameter, returns, serialization = "raw" }) {
    this.assertEndpointNameNotExists(endpointName);
    this.existingEndpointNames.add(endpointName);
    this.rpcEndpoints.set(endpointName, {
      name: endpointName,
      parameter,
      returns,
      serialization,
      handler: null
    });
    return this;
  }
  addChannelEndpoint(endpointName, { creationParameter, toServerPacket, toClientPacket, serialization = "raw" }) {
    this.assertEndpointNameNotExists(endpointName);
    this.existingEndpointNames.add(endpointName);
    this.channelEndpoints.set(endpointName, {
      name: endpointName,
      creationParameter,
      toServerPacket,
      toClientPacket,
      serialization,
      handler: null
    });
    return this;
  }
  addSignalEndpoint(endpointName, { creationParameter, signalData, serialization = "raw" }) {
    this.assertEndpointNameNotExists(endpointName);
    this.existingEndpointNames.add(endpointName);
    this.signalEndpoints.set(endpointName, {
      name: endpointName,
      creationParameter,
      signalData,
      serialization,
      handler: null
    });
    return this;
  }
  addWritableSignalEndpoint(endpointName, { creationParameter, signalData, serialization = "raw" }) {
    this.assertEndpointNameNotExists(endpointName);
    this.existingEndpointNames.add(endpointName);
    this.writableSignalEndpoints.set(endpointName, {
      name: endpointName,
      creationParameter,
      signalData,
      serialization,
      handler: null
    });
    return this;
  }
  /**
   * Adds a handler for an Rpc endpoint.
   *
   * @param endpointName - The name of the endpoint.
   * @param handler - The handler function. Will be called when the endpoint is invoked. When
   * called, the first parameter is the context, and the second parameter is the "parameter" for the
   * RPC call. Can return a value or a promise that resolves to the result.
   */
  handleRpcEndpoint(endpointName, handler) {
    const endpoint = this.rpcEndpoints.get(endpointName);
    if (endpoint === void 0) {
      throw new Error(`No Rpc endpoint with name ${endpointName}`);
    }
    if (endpoint.handler !== null) {
      throw new Error(`Rpc endpoint with name ${endpointName} already has a handler`);
    }
    endpoint.handler = handler;
    this.unhandledEndpoints.delete(endpointName);
  }
  /**
   * Adds a handler for a channel endpoint.
   *
   * @param endpointName - The name of the endpoint.
   * @param handler - The handler function. Will be called when the client creates a channel for
   * this endpoint. When called, the first parameter is the context, the second parameter is the
   * "creationParameter" for the channel, and the third parameter is a channel object that can be
   * used to send and receive messages from the client.
   *
   * Must return a promise. Once that promise is settled, the channel will be closed.
   */
  handleChannelEndpoint(endpointName, handler) {
    const endpoint = this.channelEndpoints.get(endpointName);
    if (endpoint === void 0) {
      throw new Error(`No channel endpoint with name ${endpointName}`);
    }
    if (endpoint.handler !== null) {
      throw new Error(`Channel endpoint with name ${endpointName} already has a handler`);
    }
    endpoint.handler = handler;
    this.unhandledEndpoints.delete(endpointName);
  }
  /**
   * Adds a handler for a signal endpoint.
   *
   * @param endpointName - The name of the endpoint.
   * @param handler - The handler function. Will be called when the client creates a signal, and at
   * least one subscriber is attached to that signal. When called, the first parameter is the
   * context, and the second parameter is the "creationParameter" for the signal. This method should
   * return a SignalLike, or a promise that resolves to a SignalLike.
   *
   * Note: There is no 1-to-1 correlation between the signal on the client side and the number of
   * times this handler is called. Every time the number of client subscribers changes from 0 to 1,
   * this handler will be called. Every time the number of client subscribers changes from 1 to 0,
   * the signal returned from this handler will be unsubscribed.
   *
   * Caution: Do NOT create new subscriptions that don't self-terminate in this handler, as it will
   * cause memory leaks. That is, either:
   *
   * - Return a signal that already exists
   * - Create and return a LazySignal
   */
  handleSignalEndpoint(endpointName, handler) {
    const endpoint = this.signalEndpoints.get(endpointName);
    if (endpoint === void 0) {
      throw new Error(`No signal endpoint with name ${endpointName}`);
    }
    if (endpoint.handler !== null) {
      throw new Error(`Signal endpoint with name ${endpointName} already has a handler`);
    }
    endpoint.handler = handler;
    this.unhandledEndpoints.delete(endpointName);
  }
  /**
   * Adds a handler for a writable signal endpoint.
   *
   * @param endpointName - The name of the endpoint.
   * @param handler - The handler function. Will be called when the client creates a writable
   * signal, and at least one subscriber is attached to that signal. When called, the first
   * parameter is the context, and the second parameter is the "creationParameter" for the signal.
   * This method should return a tuple of the signal and an update function. The update function
   * should be called with the new data, patches, and tags to update the signal.
   *
   * Note: There is no 1-to-1 correlation between the signal on the client side and the number of
   * times this handler is called. Every time the number of client subscribers changes from 0 to 1,
   * this handler will be called. Every time the number of client subscribers changes from 1 to 0
   * the signal returned from this handler will be unsubscribed.
   *
   * Caution: Do NOT create new subscriptions that don't self-terminate in this handler, as it will
   * cause memory leaks. That is, either:
   *
   * - Return a signal that already exists
   * - Create and return a LazySignal
   */
  handleWritableSignalEndpoint(endpointName, handler) {
    const endpoint = this.writableSignalEndpoints.get(endpointName);
    if (endpoint === void 0) {
      throw new Error(`No writable signal endpoint with name ${endpointName}`);
    }
    if (endpoint.handler !== null) {
      throw new Error(`Writable signal endpoint with name ${endpointName} already has a handler`);
    }
    endpoint.handler = handler;
    this.unhandledEndpoints.delete(endpointName);
  }
  assertAllEndpointsHandled() {
    if (this.unhandledEndpoints.size > 0) {
      throw new Error(`The following endpoints were not handled: ${Array.from(this.unhandledEndpoints).join(", ")}`);
    }
  }
  getRpcEndpoint(endpointName) {
    return this.rpcEndpoints.get(endpointName);
  }
  getAllRpcEndpoints() {
    return [...this.rpcEndpoints.values()];
  }
  getChannelEndpoint(endpointName) {
    return this.channelEndpoints.get(endpointName);
  }
  getAllChannelEndpoints() {
    return [...this.channelEndpoints.values()];
  }
  getSignalEndpoint(endpointName) {
    return this.signalEndpoints.get(endpointName);
  }
  getAllSignalEndpoints() {
    return [...this.signalEndpoints.values()];
  }
  getWritableSignalEndpoint(endpointName) {
    return this.writableSignalEndpoints.get(endpointName);
  }
  getAllWritableSignalEndpoints() {
    return [...this.writableSignalEndpoints.values()];
  }
};
var ConnectionStatus;
(function(ConnectionStatus2) {
  ConnectionStatus2["Connected"] = "CONNECTED";
  ConnectionStatus2["Errored"] = "ERRORED";
  ConnectionStatus2["Closed"] = "CLOSED";
})(ConnectionStatus || (ConnectionStatus = {}));
var logger = new SimpleLogger("Channel");
var Channel = class _Channel {
  constructor(innerSend) {
    this.innerSend = innerSend;
    this.nextAckId = 0;
    this.waitingForAck = /* @__PURE__ */ new Map();
    this.receivedACK = (ackId) => {
      if (this.connectionStatus.get() !== ConnectionStatus.Connected) {
        logger.warn("Received ACK while in status", this.connectionStatus.get());
        return;
      }
      const waiting = this.waitingForAck.get(ackId);
      if (waiting === void 0) {
        logger.warn("Received ACK for a message that is no longer waiting for ACK, ackId =", ackId);
        return;
      }
      waiting.resolve();
      this.waitingForAck.delete(ackId);
    };
    this.receivedMessage = (packet) => {
      if (this.connectionStatus.get() !== ConnectionStatus.Connected) {
        logger.warn("Received message while in status", this.connectionStatus.get());
        return;
      }
      this.emitOnMessage(packet);
    };
    this.errored = (error) => {
      if (this.connectionStatus.get() !== ConnectionStatus.Connected) {
        logger.warn("Received error while in status", this.connectionStatus.get());
        return;
      }
      this.rejectAllWaitingForAck(error);
      this.setConnectionStatus(ConnectionStatus.Errored);
      this.emitOnError(error);
    };
    this.closed = () => {
      this.rejectAllWaitingForAck(new Error("Channel closed"));
      this.setConnectionStatus(ConnectionStatus.Closed);
      this.emitOnClose();
    };
    [this.onMessage, this.emitOnMessage] = BufferedEvent.create();
    [this.onError, this.emitOnError] = BufferedEvent.create();
    [this.onClose, this.emitOnClose] = BufferedEvent.create();
    [this.connectionStatus, this.setConnectionStatus] = Signal.create(ConnectionStatus.Connected);
  }
  rejectAllWaitingForAck(error) {
    const rejects = Array.from(this.waitingForAck.values()).map(({ reject }) => reject);
    this.waitingForAck.clear();
    for (const reject of rejects) {
      reject(error);
    }
  }
  static create(innerSend) {
    const channel = new _Channel(innerSend);
    return {
      channel,
      receivedAck: channel.receivedACK,
      receivedMessage: channel.receivedMessage,
      errored: channel.errored,
      closed: channel.closed
    };
  }
  send(packet) {
    this.innerSend(packet);
  }
  sendAndWaitForACK(packet) {
    const { promise, resolve, reject } = makePromise();
    const ackId = this.nextAckId;
    this.nextAckId++;
    this.waitingForAck.set(ackId, { resolve, reject });
    this.innerSend(packet, ackId);
    return promise;
  }
};
var DoubleIndexedKV = (
  /** @class */
  (function() {
    function DoubleIndexedKV2() {
      this.keyToValue = /* @__PURE__ */ new Map();
      this.valueToKey = /* @__PURE__ */ new Map();
    }
    DoubleIndexedKV2.prototype.set = function(key, value) {
      this.keyToValue.set(key, value);
      this.valueToKey.set(value, key);
    };
    DoubleIndexedKV2.prototype.getByKey = function(key) {
      return this.keyToValue.get(key);
    };
    DoubleIndexedKV2.prototype.getByValue = function(value) {
      return this.valueToKey.get(value);
    };
    DoubleIndexedKV2.prototype.clear = function() {
      this.keyToValue.clear();
      this.valueToKey.clear();
    };
    return DoubleIndexedKV2;
  })()
);
var Registry = (
  /** @class */
  (function() {
    function Registry2(generateIdentifier) {
      this.generateIdentifier = generateIdentifier;
      this.kv = new DoubleIndexedKV();
    }
    Registry2.prototype.register = function(value, identifier) {
      if (this.kv.getByValue(value)) {
        return;
      }
      if (!identifier) {
        identifier = this.generateIdentifier(value);
      }
      this.kv.set(identifier, value);
    };
    Registry2.prototype.clear = function() {
      this.kv.clear();
    };
    Registry2.prototype.getIdentifier = function(value) {
      return this.kv.getByValue(value);
    };
    Registry2.prototype.getValue = function(identifier) {
      return this.kv.getByKey(identifier);
    };
    return Registry2;
  })()
);
var __extends = globalThis && globalThis.__extends || /* @__PURE__ */ (function() {
  var extendStatics = function(d4, b4) {
    extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d5, b5) {
      d5.__proto__ = b5;
    } || function(d5, b5) {
      for (var p4 in b5) if (Object.prototype.hasOwnProperty.call(b5, p4)) d5[p4] = b5[p4];
    };
    return extendStatics(d4, b4);
  };
  return function(d4, b4) {
    if (typeof b4 !== "function" && b4 !== null)
      throw new TypeError("Class extends value " + String(b4) + " is not a constructor or null");
    extendStatics(d4, b4);
    function __() {
      this.constructor = d4;
    }
    d4.prototype = b4 === null ? Object.create(b4) : (__.prototype = b4.prototype, new __());
  };
})();
var ClassRegistry = (
  /** @class */
  (function(_super) {
    __extends(ClassRegistry2, _super);
    function ClassRegistry2() {
      var _this = _super.call(this, function(c6) {
        return c6.name;
      }) || this;
      _this.classToAllowedProps = /* @__PURE__ */ new Map();
      return _this;
    }
    ClassRegistry2.prototype.register = function(value, options) {
      if (typeof options === "object") {
        if (options.allowProps) {
          this.classToAllowedProps.set(value, options.allowProps);
        }
        _super.prototype.register.call(this, value, options.identifier);
      } else {
        _super.prototype.register.call(this, value, options);
      }
    };
    ClassRegistry2.prototype.getAllowedProps = function(value) {
      return this.classToAllowedProps.get(value);
    };
    return ClassRegistry2;
  })(Registry)
);
var __read$3 = globalThis && globalThis.__read || function(o9, n7) {
  var m4 = typeof Symbol === "function" && o9[Symbol.iterator];
  if (!m4) return o9;
  var i7 = m4.call(o9), r8, ar = [], e9;
  try {
    while ((n7 === void 0 || n7-- > 0) && !(r8 = i7.next()).done) ar.push(r8.value);
  } catch (error) {
    e9 = { error };
  } finally {
    try {
      if (r8 && !r8.done && (m4 = i7["return"])) m4.call(i7);
    } finally {
      if (e9) throw e9.error;
    }
  }
  return ar;
};
function valuesOfObj(record) {
  if ("values" in Object) {
    return Object.values(record);
  }
  var values2 = [];
  for (var key in record) {
    if (record.hasOwnProperty(key)) {
      values2.push(record[key]);
    }
  }
  return values2;
}
function find(record, predicate) {
  var values2 = valuesOfObj(record);
  if ("find" in values2) {
    return values2.find(predicate);
  }
  var valuesNotNever = values2;
  for (var i7 = 0; i7 < valuesNotNever.length; i7++) {
    var value = valuesNotNever[i7];
    if (predicate(value)) {
      return value;
    }
  }
  return void 0;
}
function forEach(record, run) {
  Object.entries(record).forEach(function(_a7) {
    var _b = __read$3(_a7, 2), key = _b[0], value = _b[1];
    return run(value, key);
  });
}
function includes(arr, value) {
  return arr.indexOf(value) !== -1;
}
function findArr(record, predicate) {
  for (var i7 = 0; i7 < record.length; i7++) {
    var value = record[i7];
    if (predicate(value)) {
      return value;
    }
  }
  return void 0;
}
var CustomTransformerRegistry = (
  /** @class */
  (function() {
    function CustomTransformerRegistry2() {
      this.transfomers = {};
    }
    CustomTransformerRegistry2.prototype.register = function(transformer) {
      this.transfomers[transformer.name] = transformer;
    };
    CustomTransformerRegistry2.prototype.findApplicable = function(v4) {
      return find(this.transfomers, function(transformer) {
        return transformer.isApplicable(v4);
      });
    };
    CustomTransformerRegistry2.prototype.findByName = function(name) {
      return this.transfomers[name];
    };
    return CustomTransformerRegistry2;
  })()
);
var getType$1 = function(payload) {
  return Object.prototype.toString.call(payload).slice(8, -1);
};
var isUndefined = function(payload) {
  return typeof payload === "undefined";
};
var isNull = function(payload) {
  return payload === null;
};
var isPlainObject$1 = function(payload) {
  if (typeof payload !== "object" || payload === null)
    return false;
  if (payload === Object.prototype)
    return false;
  if (Object.getPrototypeOf(payload) === null)
    return true;
  return Object.getPrototypeOf(payload) === Object.prototype;
};
var isEmptyObject = function(payload) {
  return isPlainObject$1(payload) && Object.keys(payload).length === 0;
};
var isArray$1 = function(payload) {
  return Array.isArray(payload);
};
var isString = function(payload) {
  return typeof payload === "string";
};
var isNumber = function(payload) {
  return typeof payload === "number" && !isNaN(payload);
};
var isBoolean = function(payload) {
  return typeof payload === "boolean";
};
var isRegExp = function(payload) {
  return payload instanceof RegExp;
};
var isMap = function(payload) {
  return payload instanceof Map;
};
var isSet = function(payload) {
  return payload instanceof Set;
};
var isSymbol = function(payload) {
  return getType$1(payload) === "Symbol";
};
var isDate = function(payload) {
  return payload instanceof Date && !isNaN(payload.valueOf());
};
var isError = function(payload) {
  return payload instanceof Error;
};
var isNaNValue = function(payload) {
  return typeof payload === "number" && isNaN(payload);
};
var isPrimitive = function(payload) {
  return isBoolean(payload) || isNull(payload) || isUndefined(payload) || isNumber(payload) || isString(payload) || isSymbol(payload);
};
var isBigint = function(payload) {
  return typeof payload === "bigint";
};
var isInfinite = function(payload) {
  return payload === Infinity || payload === -Infinity;
};
var isTypedArray = function(payload) {
  return ArrayBuffer.isView(payload) && !(payload instanceof DataView);
};
var isURL = function(payload) {
  return payload instanceof URL;
};
var escapeKey = function(key) {
  return key.replace(/\./g, "\\.");
};
var stringifyPath = function(path6) {
  return path6.map(String).map(escapeKey).join(".");
};
var parsePath = function(string) {
  var result = [];
  var segment = "";
  for (var i7 = 0; i7 < string.length; i7++) {
    var char = string.charAt(i7);
    var isEscapedDot = char === "\\" && string.charAt(i7 + 1) === ".";
    if (isEscapedDot) {
      segment += ".";
      i7++;
      continue;
    }
    var isEndOfSegment = char === ".";
    if (isEndOfSegment) {
      result.push(segment);
      segment = "";
      continue;
    }
    segment += char;
  }
  var lastSegment = segment;
  result.push(lastSegment);
  return result;
};
var __assign$1 = globalThis && globalThis.__assign || function() {
  __assign$1 = Object.assign || function(t6) {
    for (var s6, i7 = 1, n7 = arguments.length; i7 < n7; i7++) {
      s6 = arguments[i7];
      for (var p4 in s6) if (Object.prototype.hasOwnProperty.call(s6, p4))
        t6[p4] = s6[p4];
    }
    return t6;
  };
  return __assign$1.apply(this, arguments);
};
var __read$2 = globalThis && globalThis.__read || function(o9, n7) {
  var m4 = typeof Symbol === "function" && o9[Symbol.iterator];
  if (!m4) return o9;
  var i7 = m4.call(o9), r8, ar = [], e9;
  try {
    while ((n7 === void 0 || n7-- > 0) && !(r8 = i7.next()).done) ar.push(r8.value);
  } catch (error) {
    e9 = { error };
  } finally {
    try {
      if (r8 && !r8.done && (m4 = i7["return"])) m4.call(i7);
    } finally {
      if (e9) throw e9.error;
    }
  }
  return ar;
};
var __spreadArray$2 = globalThis && globalThis.__spreadArray || function(to, from) {
  for (var i7 = 0, il = from.length, j3 = to.length; i7 < il; i7++, j3++)
    to[j3] = from[i7];
  return to;
};
function simpleTransformation(isApplicable, annotation, transform, untransform) {
  return {
    isApplicable,
    annotation,
    transform,
    untransform
  };
}
var simpleRules = [
  simpleTransformation(isUndefined, "undefined", function() {
    return null;
  }, function() {
    return void 0;
  }),
  simpleTransformation(isBigint, "bigint", function(v4) {
    return v4.toString();
  }, function(v4) {
    if (typeof BigInt !== "undefined") {
      return BigInt(v4);
    }
    console.error("Please add a BigInt polyfill.");
    return v4;
  }),
  simpleTransformation(isDate, "Date", function(v4) {
    return v4.toISOString();
  }, function(v4) {
    return new Date(v4);
  }),
  simpleTransformation(isError, "Error", function(v4, superJson) {
    var baseError = {
      name: v4.name,
      message: v4.message
    };
    superJson.allowedErrorProps.forEach(function(prop) {
      baseError[prop] = v4[prop];
    });
    return baseError;
  }, function(v4, superJson) {
    var e9 = new Error(v4.message);
    e9.name = v4.name;
    e9.stack = v4.stack;
    superJson.allowedErrorProps.forEach(function(prop) {
      e9[prop] = v4[prop];
    });
    return e9;
  }),
  simpleTransformation(isRegExp, "regexp", function(v4) {
    return "" + v4;
  }, function(regex) {
    var body = regex.slice(1, regex.lastIndexOf("/"));
    var flags = regex.slice(regex.lastIndexOf("/") + 1);
    return new RegExp(body, flags);
  }),
  simpleTransformation(
    isSet,
    "set",
    // (sets only exist in es6+)
    // eslint-disable-next-line es5/no-es6-methods
    function(v4) {
      return __spreadArray$2([], __read$2(v4.values()));
    },
    function(v4) {
      return new Set(v4);
    }
  ),
  simpleTransformation(isMap, "map", function(v4) {
    return __spreadArray$2([], __read$2(v4.entries()));
  }, function(v4) {
    return new Map(v4);
  }),
  simpleTransformation(function(v4) {
    return isNaNValue(v4) || isInfinite(v4);
  }, "number", function(v4) {
    if (isNaNValue(v4)) {
      return "NaN";
    }
    if (v4 > 0) {
      return "Infinity";
    } else {
      return "-Infinity";
    }
  }, Number),
  simpleTransformation(function(v4) {
    return v4 === 0 && 1 / v4 === -Infinity;
  }, "number", function() {
    return "-0";
  }, Number),
  simpleTransformation(isURL, "URL", function(v4) {
    return v4.toString();
  }, function(v4) {
    return new URL(v4);
  })
];
function compositeTransformation(isApplicable, annotation, transform, untransform) {
  return {
    isApplicable,
    annotation,
    transform,
    untransform
  };
}
var symbolRule = compositeTransformation(function(s6, superJson) {
  if (isSymbol(s6)) {
    var isRegistered = !!superJson.symbolRegistry.getIdentifier(s6);
    return isRegistered;
  }
  return false;
}, function(s6, superJson) {
  var identifier = superJson.symbolRegistry.getIdentifier(s6);
  return ["symbol", identifier];
}, function(v4) {
  return v4.description;
}, function(_3, a3, superJson) {
  var value = superJson.symbolRegistry.getValue(a3[1]);
  if (!value) {
    throw new Error("Trying to deserialize unknown symbol");
  }
  return value;
});
var constructorToName = [
  Int8Array,
  Uint8Array,
  Int16Array,
  Uint16Array,
  Int32Array,
  Uint32Array,
  Float32Array,
  Float64Array,
  Uint8ClampedArray
].reduce(function(obj, ctor) {
  obj[ctor.name] = ctor;
  return obj;
}, {});
var typedArrayRule = compositeTransformation(isTypedArray, function(v4) {
  return ["typed-array", v4.constructor.name];
}, function(v4) {
  return __spreadArray$2([], __read$2(v4));
}, function(v4, a3) {
  var ctor = constructorToName[a3[1]];
  if (!ctor) {
    throw new Error("Trying to deserialize unknown typed array");
  }
  return new ctor(v4);
});
function isInstanceOfRegisteredClass(potentialClass, superJson) {
  if (potentialClass === null || potentialClass === void 0 ? void 0 : potentialClass.constructor) {
    var isRegistered = !!superJson.classRegistry.getIdentifier(potentialClass.constructor);
    return isRegistered;
  }
  return false;
}
var classRule = compositeTransformation(isInstanceOfRegisteredClass, function(clazz, superJson) {
  var identifier = superJson.classRegistry.getIdentifier(clazz.constructor);
  return ["class", identifier];
}, function(clazz, superJson) {
  var allowedProps = superJson.classRegistry.getAllowedProps(clazz.constructor);
  if (!allowedProps) {
    return __assign$1({}, clazz);
  }
  var result = {};
  allowedProps.forEach(function(prop) {
    result[prop] = clazz[prop];
  });
  return result;
}, function(v4, a3, superJson) {
  var clazz = superJson.classRegistry.getValue(a3[1]);
  if (!clazz) {
    throw new Error("Trying to deserialize unknown class - check https://github.com/blitz-js/superjson/issues/116#issuecomment-773996564");
  }
  return Object.assign(Object.create(clazz.prototype), v4);
});
var customRule = compositeTransformation(function(value, superJson) {
  return !!superJson.customTransformerRegistry.findApplicable(value);
}, function(value, superJson) {
  var transformer = superJson.customTransformerRegistry.findApplicable(value);
  return ["custom", transformer.name];
}, function(value, superJson) {
  var transformer = superJson.customTransformerRegistry.findApplicable(value);
  return transformer.serialize(value);
}, function(v4, a3, superJson) {
  var transformer = superJson.customTransformerRegistry.findByName(a3[1]);
  if (!transformer) {
    throw new Error("Trying to deserialize unknown custom value");
  }
  return transformer.deserialize(v4);
});
var compositeRules = [classRule, symbolRule, customRule, typedArrayRule];
var transformValue = function(value, superJson) {
  var applicableCompositeRule = findArr(compositeRules, function(rule) {
    return rule.isApplicable(value, superJson);
  });
  if (applicableCompositeRule) {
    return {
      value: applicableCompositeRule.transform(value, superJson),
      type: applicableCompositeRule.annotation(value, superJson)
    };
  }
  var applicableSimpleRule = findArr(simpleRules, function(rule) {
    return rule.isApplicable(value, superJson);
  });
  if (applicableSimpleRule) {
    return {
      value: applicableSimpleRule.transform(value, superJson),
      type: applicableSimpleRule.annotation
    };
  }
  return void 0;
};
var simpleRulesByAnnotation = {};
simpleRules.forEach(function(rule) {
  simpleRulesByAnnotation[rule.annotation] = rule;
});
var untransformValue = function(json2, type, superJson) {
  if (isArray$1(type)) {
    switch (type[0]) {
      case "symbol":
        return symbolRule.untransform(json2, type, superJson);
      case "class":
        return classRule.untransform(json2, type, superJson);
      case "custom":
        return customRule.untransform(json2, type, superJson);
      case "typed-array":
        return typedArrayRule.untransform(json2, type, superJson);
      default:
        throw new Error("Unknown transformation: " + type);
    }
  } else {
    var transformation = simpleRulesByAnnotation[type];
    if (!transformation) {
      throw new Error("Unknown transformation: " + type);
    }
    return transformation.untransform(json2, superJson);
  }
};
var getNthKey = function(value, n7) {
  var keys2 = value.keys();
  while (n7 > 0) {
    keys2.next();
    n7--;
  }
  return keys2.next().value;
};
function validatePath(path6) {
  if (includes(path6, "__proto__")) {
    throw new Error("__proto__ is not allowed as a property");
  }
  if (includes(path6, "prototype")) {
    throw new Error("prototype is not allowed as a property");
  }
  if (includes(path6, "constructor")) {
    throw new Error("constructor is not allowed as a property");
  }
}
var getDeep = function(object, path6) {
  validatePath(path6);
  for (var i7 = 0; i7 < path6.length; i7++) {
    var key = path6[i7];
    if (isSet(object)) {
      object = getNthKey(object, +key);
    } else if (isMap(object)) {
      var row = +key;
      var type = +path6[++i7] === 0 ? "key" : "value";
      var keyOfRow = getNthKey(object, row);
      switch (type) {
        case "key":
          object = keyOfRow;
          break;
        case "value":
          object = object.get(keyOfRow);
          break;
      }
    } else {
      object = object[key];
    }
  }
  return object;
};
var setDeep = function(object, path6, mapper) {
  validatePath(path6);
  if (path6.length === 0) {
    return mapper(object);
  }
  var parent = object;
  for (var i7 = 0; i7 < path6.length - 1; i7++) {
    var key = path6[i7];
    if (isArray$1(parent)) {
      var index = +key;
      parent = parent[index];
    } else if (isPlainObject$1(parent)) {
      parent = parent[key];
    } else if (isSet(parent)) {
      var row = +key;
      parent = getNthKey(parent, row);
    } else if (isMap(parent)) {
      var isEnd = i7 === path6.length - 2;
      if (isEnd) {
        break;
      }
      var row = +key;
      var type = +path6[++i7] === 0 ? "key" : "value";
      var keyOfRow = getNthKey(parent, row);
      switch (type) {
        case "key":
          parent = keyOfRow;
          break;
        case "value":
          parent = parent.get(keyOfRow);
          break;
      }
    }
  }
  var lastKey = path6[path6.length - 1];
  if (isArray$1(parent)) {
    parent[+lastKey] = mapper(parent[+lastKey]);
  } else if (isPlainObject$1(parent)) {
    parent[lastKey] = mapper(parent[lastKey]);
  }
  if (isSet(parent)) {
    var oldValue = getNthKey(parent, +lastKey);
    var newValue = mapper(oldValue);
    if (oldValue !== newValue) {
      parent["delete"](oldValue);
      parent.add(newValue);
    }
  }
  if (isMap(parent)) {
    var row = +path6[path6.length - 2];
    var keyToRow = getNthKey(parent, row);
    var type = +lastKey === 0 ? "key" : "value";
    switch (type) {
      case "key": {
        var newKey = mapper(keyToRow);
        parent.set(newKey, parent.get(keyToRow));
        if (newKey !== keyToRow) {
          parent["delete"](keyToRow);
        }
        break;
      }
      case "value": {
        parent.set(keyToRow, mapper(parent.get(keyToRow)));
        break;
      }
    }
  }
  return object;
};
var __read$1 = globalThis && globalThis.__read || function(o9, n7) {
  var m4 = typeof Symbol === "function" && o9[Symbol.iterator];
  if (!m4) return o9;
  var i7 = m4.call(o9), r8, ar = [], e9;
  try {
    while ((n7 === void 0 || n7-- > 0) && !(r8 = i7.next()).done) ar.push(r8.value);
  } catch (error) {
    e9 = { error };
  } finally {
    try {
      if (r8 && !r8.done && (m4 = i7["return"])) m4.call(i7);
    } finally {
      if (e9) throw e9.error;
    }
  }
  return ar;
};
var __spreadArray$1 = globalThis && globalThis.__spreadArray || function(to, from) {
  for (var i7 = 0, il = from.length, j3 = to.length; i7 < il; i7++, j3++)
    to[j3] = from[i7];
  return to;
};
function traverse(tree, walker2, origin) {
  if (origin === void 0) {
    origin = [];
  }
  if (!tree) {
    return;
  }
  if (!isArray$1(tree)) {
    forEach(tree, function(subtree, key) {
      return traverse(subtree, walker2, __spreadArray$1(__spreadArray$1([], __read$1(origin)), __read$1(parsePath(key))));
    });
    return;
  }
  var _a7 = __read$1(tree, 2), nodeValue = _a7[0], children = _a7[1];
  if (children) {
    forEach(children, function(child, key) {
      traverse(child, walker2, __spreadArray$1(__spreadArray$1([], __read$1(origin)), __read$1(parsePath(key))));
    });
  }
  walker2(nodeValue, origin);
}
function applyValueAnnotations(plain, annotations, superJson) {
  traverse(annotations, function(type, path6) {
    plain = setDeep(plain, path6, function(v4) {
      return untransformValue(v4, type, superJson);
    });
  });
  return plain;
}
function applyReferentialEqualityAnnotations(plain, annotations) {
  function apply(identicalPaths, path6) {
    var object = getDeep(plain, parsePath(path6));
    identicalPaths.map(parsePath).forEach(function(identicalObjectPath) {
      plain = setDeep(plain, identicalObjectPath, function() {
        return object;
      });
    });
  }
  if (isArray$1(annotations)) {
    var _a7 = __read$1(annotations, 2), root = _a7[0], other = _a7[1];
    root.forEach(function(identicalPath) {
      plain = setDeep(plain, parsePath(identicalPath), function() {
        return plain;
      });
    });
    if (other) {
      forEach(other, apply);
    }
  } else {
    forEach(annotations, apply);
  }
  return plain;
}
var isDeep = function(object, superJson) {
  return isPlainObject$1(object) || isArray$1(object) || isMap(object) || isSet(object) || isInstanceOfRegisteredClass(object, superJson);
};
function addIdentity(object, path6, identities) {
  var existingSet = identities.get(object);
  if (existingSet) {
    existingSet.push(path6);
  } else {
    identities.set(object, [path6]);
  }
}
function generateReferentialEqualityAnnotations(identitites, dedupe) {
  var result = {};
  var rootEqualityPaths = void 0;
  identitites.forEach(function(paths) {
    if (paths.length <= 1) {
      return;
    }
    if (!dedupe) {
      paths = paths.map(function(path6) {
        return path6.map(String);
      }).sort(function(a3, b4) {
        return a3.length - b4.length;
      });
    }
    var _a7 = __read$1(paths), representativePath = _a7[0], identicalPaths = _a7.slice(1);
    if (representativePath.length === 0) {
      rootEqualityPaths = identicalPaths.map(stringifyPath);
    } else {
      result[stringifyPath(representativePath)] = identicalPaths.map(stringifyPath);
    }
  });
  if (rootEqualityPaths) {
    if (isEmptyObject(result)) {
      return [rootEqualityPaths];
    } else {
      return [rootEqualityPaths, result];
    }
  } else {
    return isEmptyObject(result) ? void 0 : result;
  }
}
var walker = function(object, identities, superJson, dedupe, path6, objectsInThisPath, seenObjects) {
  var _a7;
  if (path6 === void 0) {
    path6 = [];
  }
  if (objectsInThisPath === void 0) {
    objectsInThisPath = [];
  }
  if (seenObjects === void 0) {
    seenObjects = /* @__PURE__ */ new Map();
  }
  var primitive = isPrimitive(object);
  if (!primitive) {
    addIdentity(object, path6, identities);
    var seen = seenObjects.get(object);
    if (seen) {
      return dedupe ? {
        transformedValue: null
      } : seen;
    }
  }
  if (!isDeep(object, superJson)) {
    var transformed_1 = transformValue(object, superJson);
    var result_1 = transformed_1 ? {
      transformedValue: transformed_1.value,
      annotations: [transformed_1.type]
    } : {
      transformedValue: object
    };
    if (!primitive) {
      seenObjects.set(object, result_1);
    }
    return result_1;
  }
  if (includes(objectsInThisPath, object)) {
    return {
      transformedValue: null
    };
  }
  var transformationResult = transformValue(object, superJson);
  var transformed = (_a7 = transformationResult === null || transformationResult === void 0 ? void 0 : transformationResult.value) !== null && _a7 !== void 0 ? _a7 : object;
  var transformedValue = isArray$1(transformed) ? [] : {};
  var innerAnnotations = {};
  forEach(transformed, function(value, index) {
    var recursiveResult = walker(value, identities, superJson, dedupe, __spreadArray$1(__spreadArray$1([], __read$1(path6)), [index]), __spreadArray$1(__spreadArray$1([], __read$1(objectsInThisPath)), [object]), seenObjects);
    transformedValue[index] = recursiveResult.transformedValue;
    if (isArray$1(recursiveResult.annotations)) {
      innerAnnotations[index] = recursiveResult.annotations;
    } else if (isPlainObject$1(recursiveResult.annotations)) {
      forEach(recursiveResult.annotations, function(tree, key) {
        innerAnnotations[escapeKey(index) + "." + key] = tree;
      });
    }
  });
  var result = isEmptyObject(innerAnnotations) ? {
    transformedValue,
    annotations: !!transformationResult ? [transformationResult.type] : void 0
  } : {
    transformedValue,
    annotations: !!transformationResult ? [transformationResult.type, innerAnnotations] : innerAnnotations
  };
  if (!primitive) {
    seenObjects.set(object, result);
  }
  return result;
};
function getType(payload) {
  return Object.prototype.toString.call(payload).slice(8, -1);
}
function isArray4(payload) {
  return getType(payload) === "Array";
}
function isPlainObject(payload) {
  if (getType(payload) !== "Object")
    return false;
  const prototype = Object.getPrototypeOf(payload);
  return !!prototype && prototype.constructor === Object && prototype === Object.prototype;
}
function assignProp(carry2, key, newVal, originalObject, includeNonenumerable) {
  const propType = {}.propertyIsEnumerable.call(originalObject, key) ? "enumerable" : "nonenumerable";
  if (propType === "enumerable")
    carry2[key] = newVal;
  if (includeNonenumerable && propType === "nonenumerable") {
    Object.defineProperty(carry2, key, {
      value: newVal,
      enumerable: false,
      writable: true,
      configurable: true
    });
  }
}
function copy(target, options = {}) {
  if (isArray4(target)) {
    return target.map((item) => copy(item, options));
  }
  if (!isPlainObject(target)) {
    return target;
  }
  const props = Object.getOwnPropertyNames(target);
  const symbols2 = Object.getOwnPropertySymbols(target);
  return [...props, ...symbols2].reduce((carry2, key) => {
    if (isArray4(options.props) && !options.props.includes(key)) {
      return carry2;
    }
    const val2 = target[key];
    const newVal = copy(val2, options);
    assignProp(carry2, key, newVal, target, options.nonenumerable);
    return carry2;
  }, {});
}
var __assign = globalThis && globalThis.__assign || function() {
  __assign = Object.assign || function(t6) {
    for (var s6, i7 = 1, n7 = arguments.length; i7 < n7; i7++) {
      s6 = arguments[i7];
      for (var p4 in s6) if (Object.prototype.hasOwnProperty.call(s6, p4))
        t6[p4] = s6[p4];
    }
    return t6;
  };
  return __assign.apply(this, arguments);
};
var __read = globalThis && globalThis.__read || function(o9, n7) {
  var m4 = typeof Symbol === "function" && o9[Symbol.iterator];
  if (!m4) return o9;
  var i7 = m4.call(o9), r8, ar = [], e9;
  try {
    while ((n7 === void 0 || n7-- > 0) && !(r8 = i7.next()).done) ar.push(r8.value);
  } catch (error) {
    e9 = { error };
  } finally {
    try {
      if (r8 && !r8.done && (m4 = i7["return"])) m4.call(i7);
    } finally {
      if (e9) throw e9.error;
    }
  }
  return ar;
};
var __spreadArray = globalThis && globalThis.__spreadArray || function(to, from) {
  for (var i7 = 0, il = from.length, j3 = to.length; i7 < il; i7++, j3++)
    to[j3] = from[i7];
  return to;
};
var SuperJSON = (
  /** @class */
  (function() {
    function SuperJSON2(_a7) {
      var _b = _a7 === void 0 ? {} : _a7, _c = _b.dedupe, dedupe = _c === void 0 ? false : _c;
      this.classRegistry = new ClassRegistry();
      this.symbolRegistry = new Registry(function(s6) {
        var _a8;
        return (_a8 = s6.description) !== null && _a8 !== void 0 ? _a8 : "";
      });
      this.customTransformerRegistry = new CustomTransformerRegistry();
      this.allowedErrorProps = [];
      this.dedupe = dedupe;
    }
    SuperJSON2.prototype.serialize = function(object) {
      var identities = /* @__PURE__ */ new Map();
      var output = walker(object, identities, this, this.dedupe);
      var res = {
        json: output.transformedValue
      };
      if (output.annotations) {
        res.meta = __assign(__assign({}, res.meta), { values: output.annotations });
      }
      var equalityAnnotations = generateReferentialEqualityAnnotations(identities, this.dedupe);
      if (equalityAnnotations) {
        res.meta = __assign(__assign({}, res.meta), { referentialEqualities: equalityAnnotations });
      }
      return res;
    };
    SuperJSON2.prototype.deserialize = function(payload) {
      var json2 = payload.json, meta = payload.meta;
      var result = copy(json2);
      if (meta === null || meta === void 0 ? void 0 : meta.values) {
        result = applyValueAnnotations(result, meta.values, this);
      }
      if (meta === null || meta === void 0 ? void 0 : meta.referentialEqualities) {
        result = applyReferentialEqualityAnnotations(result, meta.referentialEqualities);
      }
      return result;
    };
    SuperJSON2.prototype.stringify = function(object) {
      return JSON.stringify(this.serialize(object));
    };
    SuperJSON2.prototype.parse = function(string) {
      return this.deserialize(JSON.parse(string));
    };
    SuperJSON2.prototype.registerClass = function(v4, options) {
      this.classRegistry.register(v4, options);
    };
    SuperJSON2.prototype.registerSymbol = function(v4, identifier) {
      this.symbolRegistry.register(v4, identifier);
    };
    SuperJSON2.prototype.registerCustom = function(transformer, name) {
      this.customTransformerRegistry.register(__assign({ name }, transformer));
    };
    SuperJSON2.prototype.allowErrorProps = function() {
      var _a7;
      var props = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        props[_i] = arguments[_i];
      }
      (_a7 = this.allowedErrorProps).push.apply(_a7, __spreadArray([], __read(props)));
    };
    SuperJSON2.defaultInstance = new SuperJSON2();
    SuperJSON2.serialize = SuperJSON2.defaultInstance.serialize.bind(SuperJSON2.defaultInstance);
    SuperJSON2.deserialize = SuperJSON2.defaultInstance.deserialize.bind(SuperJSON2.defaultInstance);
    SuperJSON2.stringify = SuperJSON2.defaultInstance.stringify.bind(SuperJSON2.defaultInstance);
    SuperJSON2.parse = SuperJSON2.defaultInstance.parse.bind(SuperJSON2.defaultInstance);
    SuperJSON2.registerClass = SuperJSON2.defaultInstance.registerClass.bind(SuperJSON2.defaultInstance);
    SuperJSON2.registerSymbol = SuperJSON2.defaultInstance.registerSymbol.bind(SuperJSON2.defaultInstance);
    SuperJSON2.registerCustom = SuperJSON2.defaultInstance.registerCustom.bind(SuperJSON2.defaultInstance);
    SuperJSON2.allowErrorProps = SuperJSON2.defaultInstance.allowErrorProps.bind(SuperJSON2.defaultInstance);
    return SuperJSON2;
  })()
);
var serialize$1 = SuperJSON.serialize;
var deserialize$1 = SuperJSON.deserialize;
function serialize(type, value) {
  switch (type) {
    case "raw":
      return value;
    case "superjson":
      return serialize$1(value);
  }
}
function deserialize(type, value) {
  switch (type) {
    case "raw":
      return value;
    case "superjson":
      return deserialize$1(value);
  }
}
var serializedOpaqueSchema = external_exports.any();
var clientToServerMessageSchema = external_exports.discriminatedUnion("type", [
  // Communication
  external_exports.object({
    type: external_exports.literal("communicationWarning"),
    warning: external_exports.string()
  }),
  external_exports.object({
    type: external_exports.literal("keepAlive")
  }),
  // Channel
  external_exports.object({
    type: external_exports.literal("channelCreate"),
    endpoint: external_exports.string(),
    channelId: external_exports.number().int(),
    creationParameter: serializedOpaqueSchema
  }),
  external_exports.object({
    type: external_exports.literal("channelSend"),
    channelId: external_exports.number().int(),
    message: serializedOpaqueSchema,
    ackId: external_exports.number().int().optional()
  }),
  external_exports.object({
    type: external_exports.literal("channelAck"),
    channelId: external_exports.number().int(),
    ackId: external_exports.number().int()
  }),
  // RPC
  external_exports.object({
    type: external_exports.literal("rpcCall"),
    endpoint: external_exports.string(),
    callId: external_exports.number().int(),
    parameter: serializedOpaqueSchema
  }),
  // Readonly signal
  external_exports.object({
    type: external_exports.literal("signalSubscribe"),
    creationParameter: serializedOpaqueSchema,
    endpoint: external_exports.string(),
    subscribeId: external_exports.number().int()
  }),
  external_exports.object({
    type: external_exports.literal("signalUnsubscribe"),
    subscribeId: external_exports.number().int()
  }),
  // Writable signal
  external_exports.object({
    type: external_exports.literal("writableSignalSubscribe"),
    creationParameter: serializedOpaqueSchema,
    endpoint: external_exports.string(),
    subscribeId: external_exports.number().int()
  }),
  external_exports.object({
    type: external_exports.literal("writableSignalUnsubscribe"),
    subscribeId: external_exports.number().int()
  }),
  external_exports.object({
    type: external_exports.literal("writableSignalUpdate"),
    subscribeId: external_exports.number().int(),
    patches: external_exports.array(serializedOpaqueSchema),
    tags: external_exports.array(external_exports.string())
  })
]);
var serverToClientMessageSchema = external_exports.discriminatedUnion("type", [
  // Communication
  external_exports.object({
    type: external_exports.literal("communicationWarning"),
    warning: external_exports.string()
  }),
  external_exports.object({
    type: external_exports.literal("keepAliveAck")
  }),
  // Channel
  external_exports.object({
    type: external_exports.literal("channelSend"),
    channelId: external_exports.number().int(),
    message: serializedOpaqueSchema,
    ackId: external_exports.number().int().optional()
  }),
  external_exports.object({
    type: external_exports.literal("channelAck"),
    channelId: external_exports.number().int(),
    ackId: external_exports.number().int()
  }),
  external_exports.object({
    type: external_exports.literal("channelClose"),
    channelId: external_exports.number().int()
  }),
  external_exports.object({
    type: external_exports.literal("channelError"),
    channelId: external_exports.number().int(),
    error: serializedLMSExtendedErrorSchema
  }),
  // RPC
  external_exports.object({
    type: external_exports.literal("rpcResult"),
    callId: external_exports.number().int(),
    result: serializedOpaqueSchema
  }),
  external_exports.object({
    type: external_exports.literal("rpcError"),
    callId: external_exports.number().int(),
    error: serializedLMSExtendedErrorSchema
  }),
  // Readonly signal
  external_exports.object({
    type: external_exports.literal("signalUpdate"),
    subscribeId: external_exports.number().int(),
    patches: external_exports.array(serializedOpaqueSchema),
    tags: external_exports.array(external_exports.string())
  }),
  external_exports.object({
    type: external_exports.literal("signalError"),
    subscribeId: external_exports.number().int(),
    error: serializedLMSExtendedErrorSchema
  }),
  // Writable signal
  external_exports.object({
    type: external_exports.literal("writableSignalUpdate"),
    subscribeId: external_exports.number().int(),
    patches: external_exports.array(serializedOpaqueSchema),
    tags: external_exports.array(external_exports.string())
  }),
  external_exports.object({
    type: external_exports.literal("writableSignalError"),
    subscribeId: external_exports.number().int(),
    error: serializedLMSExtendedErrorSchema
  })
]);
var Transport = class {
  constructor() {
    this.disposed = false;
  }
  async [Symbol.asyncDispose]() {
    if (this.disposed) {
      throw new Error("Cannot dispose twice");
    }
    this.disposed = true;
  }
};
var ClientTransport = class extends Transport {
  parseIncomingMessage(message) {
    return serverToClientMessageSchema.parse(message);
  }
  send(message) {
    const result = clientToServerMessageSchema.parse(message);
    this.sendViaTransport(result);
  }
  /**
   * Called by the client port when the number of open communications changes from 0 to 1. This
   * usually indicates the `socket.ref()` should be called to prevent the process from exiting.
   */
  onHavingOneOrMoreOpenCommunication() {
  }
  // The following snippet is intentionally not a tsdoc (only 1 star as oppose to 2). There is
  // likely a bug in TypeScript that when we change it to tsdoc, on darwin and linux, it causes the
  // generated .d.ts file to be invalid. We have considered reporting this to TypeScript, but it is
  // way too difficult to narrow down, thus we just hope this is the only case that this error
  // occurs.
  /*
   * Called by the client port when the number of open communications changes from 1 or more to 0.
   * This usually indicates the `socket.unref()` should be called to allow the process to exit.
   */
  onHavingNoOpenCommunication() {
  }
};
var wsAuthenticationResultSchema = external_exports.discriminatedUnion("success", [
  external_exports.object({
    success: external_exports.literal(true)
  }),
  external_exports.object({
    success: external_exports.literal(false),
    error: external_exports.string()
  })
]);
var WsClientTransportStatus;
(function(WsClientTransportStatus2) {
  WsClientTransportStatus2["Disconnected"] = "DISCONNECTED";
  WsClientTransportStatus2["Connecting"] = "CONNECTING";
  WsClientTransportStatus2["Connected"] = "CONNECTED";
})(WsClientTransportStatus || (WsClientTransportStatus = {}));
var WsClientTransport = class _WsClientTransport extends ClientTransport {
  constructor(url, receivedMessage, errored, { abortSignal, parentLogger } = {}) {
    super();
    this.url = url;
    this.receivedMessage = receivedMessage;
    this.errored = errored;
    this.ws = null;
    this.queuedMessages = [];
    this.status = WsClientTransportStatus.Disconnected;
    this.resolvedUrl = null;
    this.shouldRef = false;
    this.resolveDisposed = null;
    this.abortSignal = abortSignal;
    this.logger = new SimpleLogger("WsClientTransport", parentLogger);
  }
  static createWsClientTransportFactory(url, { abortSignal } = {}) {
    return (receivedMessage, errored, parentLogger) => new _WsClientTransport(url, receivedMessage, errored, {
      abortSignal,
      parentLogger
    });
  }
  connect() {
    if (this.status !== WsClientTransportStatus.Disconnected) {
      this.logger.warn("connect() called while not disconnected");
      return;
    }
    if (this.disposed) {
      throw new Error(text`
        Cannot establish WebSocket connection because the transport has been disposed.
      `);
    }
    if (this.abortSignal !== void 0 && this.abortSignal.aborted) {
      throw new Error(this.abortSignal.reason);
    }
    this.status = WsClientTransportStatus.Connecting;
    Promise.resolve(this.url).then((url) => {
      this.resolvedUrl = url;
      this.ws = new import_lms_isomorphic.WebSocket(url);
      this.ws.addEventListener("open", this.onWsOpen.bind(this));
      this.ws.addEventListener("error", (event) => this.onWsError(event.error));
      this.ws.addEventListener("close", () => {
        this.onWsError(new Error("WebSocket connection closed"));
      });
      const abortSignal = this.abortSignal;
      if (abortSignal !== void 0) {
        if (abortSignal.aborted) {
          this.onWsError(abortSignal.reason);
        } else {
          const abortListener = () => {
            this.onWsError(abortSignal.reason);
          };
          abortSignal.addEventListener("abort", abortListener, { once: true });
          this.ws.addEventListener("close", () => {
            abortSignal.removeEventListener("abort", abortListener);
          });
        }
      }
    });
  }
  onWsOpen() {
    this.ws.addEventListener("message", this.onWsMessage.bind(this));
    this.status = WsClientTransportStatus.Connected;
    this.queuedMessages.forEach((message) => this.sendViaTransport(message));
    this.queuedMessages = [];
    this.updateShouldRef(this.shouldRef);
  }
  onWsMessage(event) {
    if (this.status !== WsClientTransportStatus.Connected) {
      this.logger.warn("Received message while not connected. Message ignored:", event.data);
      return;
    }
    let message;
    try {
      message = JSON.parse(String(event.data));
    } catch (error) {
      this.logger.warn("Received invalid JSON message from server:", event.data);
      return;
    }
    let parsed;
    try {
      parsed = this.parseIncomingMessage(message);
    } catch (error) {
      this.logger.warn("Received invalid message from server:", message);
      return;
    }
    this.receivedMessage(parsed);
  }
  onWsError(error) {
    if (this.status === WsClientTransportStatus.Disconnected) {
      return;
    }
    this.logger.warn("WebSocket error:", error);
    if (error.code === "ECONNREFUSED") {
      this.logger.warnText`
        WebSocket connection refused. This can happen if the server is not running or the client
        is trying to connect to the wrong path. The server path that this client is
        attempting to connect to is:
        ${this.resolvedUrl ?? "Unknown"}.

        Please make sure the following:

          1. LM Studio is running

          2. The API server in LM Studio has started

          3. The client is attempting to connect to the correct path
      `;
    }
    try {
      this.ws?.close();
    } catch (error2) {
    }
    this.status = WsClientTransportStatus.Disconnected;
    this.errored(error);
  }
  onWsTimeout() {
    if (this.status === WsClientTransportStatus.Disconnected) {
      return;
    }
    this.logger.warn("Websocket timed out");
    try {
      this.ws?.close();
    } catch (error) {
    }
    this.status = WsClientTransportStatus.Disconnected;
    this.errored(new Error("WebSocket timed out"));
  }
  onHavingNoOpenCommunication() {
    this.updateShouldRef(false);
    if (this.disposed && this.resolveDisposed !== null) {
      this.resolveDisposed();
      this.resolveDisposed = null;
    }
  }
  onHavingOneOrMoreOpenCommunication() {
    this.updateShouldRef(true);
  }
  updateShouldRef(shouldRef) {
    this.shouldRef = shouldRef;
    if (this.ws === null) {
      return;
    }
    if (!this.ws._socket) {
      return;
    }
    if (shouldRef) {
      this.ws._socket.ref();
    } else {
      this.ws._socket.unref();
    }
  }
  sendViaTransport(message) {
    if (this.status === WsClientTransportStatus.Connected) {
      this.ws.send(JSON.stringify(message));
    } else {
      this.queuedMessages.push(message);
      if (this.status === WsClientTransportStatus.Disconnected) {
        this.connect();
      }
    }
  }
  async [Symbol.asyncDispose]() {
    await super[Symbol.asyncDispose]();
    if (this.shouldRef) {
      const { promise: disposedPromise, resolve: resolveDisposed } = makePromise();
      this.resolveDisposed = resolveDisposed;
      await disposedPromise;
    }
    if (this.ws !== null) {
      try {
        this.ws.close();
      } catch (error) {
      }
      this.ws = null;
    }
    this.errored(new Error("WebSocket client transport disposed"));
    this.status = WsClientTransportStatus.Disconnected;
  }
};
var AuthenticatedWsClientTransport = class _AuthenticatedWsClientTransport extends WsClientTransport {
  constructor(url, clientIdentifier, clientPasskey, receivedMessage, errored, { parentLogger, abortSignal } = {}) {
    super(url, receivedMessage, errored, { parentLogger, abortSignal });
    this.clientIdentifier = clientIdentifier;
    this.clientPasskey = clientPasskey;
    this.logger = this.logger.subclass("AuthenticatedWsClientTransport");
  }
  static createAuthenticatedWsClientTransportFactory({ url, clientIdentifier, clientPasskey, abortSignal }) {
    return (receivedMessage, errored, parentLogger) => new _AuthenticatedWsClientTransport(url, clientIdentifier, clientPasskey, receivedMessage, errored, { parentLogger, abortSignal });
  }
  onWsOpen() {
    this.ws.send(JSON.stringify({
      authVersion: 1,
      clientIdentifier: this.clientIdentifier,
      clientPasskey: this.clientPasskey
    }));
    this.ws.addEventListener("message", (event) => {
      try {
        const data = JSON.parse(event.data.toString("utf-8"));
        const result = wsAuthenticationResultSchema.parse(data);
        if (result.success) {
          super.onWsOpen();
        } else {
          this.onWsError(new Error("Failed to authenticate: " + result.error));
        }
      } catch (error) {
        this.onWsError(new Error("Failed to parse authentication result: " + error?.message));
      }
    }, {
      once: true
    });
  }
};
function defaultErrorDeserializer(serialized, directCause, stack) {
  return fromSerializedError(serialized, directCause, stack);
}
var ClientPort = class {
  constructor(backendInterface, factory, { parentLogger, errorDeserializer, verboseErrorMessage } = {}) {
    this.backendInterface = backendInterface;
    this.openChannels = /* @__PURE__ */ new Map();
    this.ongoingRpcs = /* @__PURE__ */ new Map();
    this.openSignalSubscriptions = /* @__PURE__ */ new Map();
    this.openWritableSignalSubscriptions = /* @__PURE__ */ new Map();
    this.openCommunicationsCount = 0;
    this.nextChannelId = 0;
    this.nextSubscribeId = 0;
    this.nextWritableSubscribeId = 0;
    this.producedCommunicationWarningsCount = 0;
    this.receivedMessage = (message) => {
      switch (message.type) {
        case "channelSend": {
          this.receivedChannelSend(message);
          break;
        }
        case "channelAck": {
          this.receivedChannelAck(message);
          break;
        }
        case "channelClose": {
          this.receivedChannelClose(message);
          break;
        }
        case "channelError": {
          this.receivedChannelError(message);
          break;
        }
        case "rpcResult": {
          this.receivedRpcResult(message);
          break;
        }
        case "rpcError": {
          this.receivedRpcError(message);
          break;
        }
        case "signalUpdate": {
          this.receivedSignalUpdate(message);
          break;
        }
        case "signalError": {
          this.receivedSignalError(message);
          break;
        }
        case "writableSignalUpdate": {
          this.receivedWritableSignalUpdate(message);
          break;
        }
        case "writableSignalError": {
          this.receivedWritableSignalError(message);
          break;
        }
        case "communicationWarning": {
          this.receivedCommunicationWarning(message);
          break;
        }
        case "keepAliveAck": {
          this.receivedKeepAliveAck(message);
          break;
        }
      }
    };
    this.errored = (error) => {
      for (const openChannel of this.openChannels.values()) {
        openChannel.errored(error);
      }
      this.openChannels.clear();
      for (const ongoingRpc of this.ongoingRpcs.values()) {
        ongoingRpc.reject(error);
      }
      this.ongoingRpcs.clear();
      for (const openSignalSubscription of this.openSignalSubscriptions.values()) {
        openSignalSubscription.errored(error);
      }
      this.openSignalSubscriptions.clear();
      for (const openWritableSignalSubscription of this.openWritableSignalSubscriptions.values()) {
        openWritableSignalSubscription.errored(error);
      }
      this.openWritableSignalSubscriptions.clear();
      this.updateOpenCommunicationsCount();
    };
    this.logger = new SimpleLogger("ClientPort", parentLogger);
    this.errorDeserializer = errorDeserializer ?? defaultErrorDeserializer;
    this.verboseErrorMessage = verboseErrorMessage ?? true;
    this.transport = factory(this.receivedMessage, this.errored, this.logger);
  }
  communicationWarning(warning) {
    if (this.producedCommunicationWarningsCount >= 5) {
      return;
    }
    this.logger.warnText`
      Produced communication warning: ${warning}
      
      This is usually caused by communication protocol incompatibility. Please make sure you are
      using the up-to-date versions of the SDK and LM Studio.
    `;
    this.transport.send({
      type: "communicationWarning",
      warning
    });
    this.producedCommunicationWarningsCount++;
    if (this.producedCommunicationWarningsCount >= 5) {
      this.logger.errorText`
        5 communication warnings have been produced. Further warnings will not be printed.
      `;
    }
  }
  updateOpenCommunicationsCount() {
    const previousCount = this.openCommunicationsCount;
    this.openCommunicationsCount = this.openChannels.size + this.ongoingRpcs.size + this.openSignalSubscriptions.size + this.openWritableSignalSubscriptions.size;
    if (this.openCommunicationsCount === 0 && previousCount > 0) {
      this.transport.onHavingNoOpenCommunication();
    } else if (this.openCommunicationsCount === 1 && previousCount === 0) {
      this.transport.onHavingOneOrMoreOpenCommunication();
    }
  }
  receivedChannelSend(message) {
    const openChannel = this.openChannels.get(message.channelId);
    if (openChannel === void 0) {
      this.communicationWarning(`Received channelSend for unknown channel, channelId = ${message.channelId}`);
      return;
    }
    const deserializedMessage = deserialize(openChannel.endpoint.serialization, message.message);
    const parsed = openChannel.endpoint.toClientPacket.safeParse(deserializedMessage);
    if (!parsed.success) {
      this.communicationWarning(text`
        Received invalid message for channel: endpointName = ${openChannel.endpoint.name}, message =
        ${deserializedMessage}. Zod error:

        ${Validator.prettyPrintZod("message", parsed.error)}
      `);
      return;
    }
    openChannel.receivedMessage(parsed.data);
  }
  receivedChannelAck(message) {
    const openChannel = this.openChannels.get(message.channelId);
    if (openChannel === void 0) {
      this.communicationWarning(`Received channelAck for unknown channel, channelId = ${message.channelId}`);
      return;
    }
    openChannel.receivedAck(message.ackId);
  }
  receivedChannelClose(message) {
    const openChannel = this.openChannels.get(message.channelId);
    if (openChannel === void 0) {
      this.communicationWarning(`Received channelClose for unknown channel, channelId = ${message.channelId}`);
      return;
    }
    this.openChannels.delete(message.channelId);
    openChannel.closed();
    this.updateOpenCommunicationsCount();
  }
  receivedChannelError(message) {
    const openChannel = this.openChannels.get(message.channelId);
    if (openChannel === void 0) {
      this.communicationWarning(`Received channelError for unknown channel, channelId = ${message.channelId}`);
      return;
    }
    this.openChannels.delete(message.channelId);
    const error = this.errorDeserializer(message.error, "Channel Error", this.verboseErrorMessage ? openChannel.stack : void 0);
    openChannel.errored(error);
    this.updateOpenCommunicationsCount();
  }
  receivedRpcResult(message) {
    const ongoingRpc = this.ongoingRpcs.get(message.callId);
    if (ongoingRpc === void 0) {
      this.communicationWarning(`Received rpcResult for unknown rpc, callId = ${message.callId}`);
      return;
    }
    const deserializedResult = deserialize(ongoingRpc.endpoint.serialization, message.result);
    const parsed = ongoingRpc.endpoint.returns.safeParse(deserializedResult);
    if (!parsed.success) {
      this.communicationWarning(text`
        Received invalid result for rpc, endpointName = ${ongoingRpc.endpoint.name}, result =
        ${deserializedResult}. Zod error:

        ${Validator.prettyPrintZod("result", parsed.error)}
      `);
      return;
    }
    ongoingRpc.resolve(parsed.data);
    this.ongoingRpcs.delete(message.callId);
    this.updateOpenCommunicationsCount();
  }
  receivedRpcError(message) {
    const ongoingRpc = this.ongoingRpcs.get(message.callId);
    if (ongoingRpc === void 0) {
      this.communicationWarning(`Received rpcError for unknown rpc, callId = ${message.callId}`);
      return;
    }
    const error = this.errorDeserializer(message.error, "RPC Error", this.verboseErrorMessage ? ongoingRpc.stack : void 0);
    ongoingRpc.reject(error);
    this.ongoingRpcs.delete(message.callId);
    this.updateOpenCommunicationsCount();
  }
  receivedSignalUpdate(message) {
    const openSignalSubscription = this.openSignalSubscriptions.get(message.subscribeId);
    if (openSignalSubscription === void 0) {
      return;
    }
    const patches = message.patches.map((patch) => deserialize(openSignalSubscription.endpoint.serialization, patch));
    const beforeValue = openSignalSubscription.getValue();
    let afterValue;
    try {
      afterValue = applyPatches(beforeValue, patches);
    } catch (error) {
      this.communicationWarning(text`
        Failed to apply patches to signal on signalUpdate. subscribeId = ${message.subscribeId}.

        beforeValue = ${JSON.stringify(beforeValue, null, 2)},

        patches = ${JSON.stringify(patches, null, 2)}.

        Error: ${String(error)}
      `);
      return;
    }
    const parseResult = openSignalSubscription.endpoint.signalData.safeParse(afterValue);
    if (!parseResult.success) {
      this.communicationWarning(text`
        Received invalid signal patch data, subscribeId = ${message.subscribeId}

        patches = ${patches},

        beforeValue = ${beforeValue},

        afterValue = ${afterValue}.

        Zod error:

        ${Validator.prettyPrintZod("value", parseResult.error)}
      `);
      return;
    }
    openSignalSubscription.receivedPatches(afterValue, patches, message.tags);
  }
  receivedSignalError(message) {
    const openSignalSubscription = this.openSignalSubscriptions.get(message.subscribeId);
    if (openSignalSubscription === void 0) {
      this.communicationWarning(`Received signalError for unknown signal, subscribeId = ${message.subscribeId}`);
      return;
    }
    const error = this.errorDeserializer(message.error, "Signal Error", this.verboseErrorMessage ? openSignalSubscription.stack : void 0);
    openSignalSubscription.errored(error);
    this.openSignalSubscriptions.delete(message.subscribeId);
    this.updateOpenCommunicationsCount();
  }
  receivedWritableSignalUpdate(message) {
    const openSignalSubscription = this.openWritableSignalSubscriptions.get(message.subscribeId);
    if (openSignalSubscription === void 0) {
      return;
    }
    const patches = message.patches.map((patch) => deserialize(openSignalSubscription.endpoint.serialization, patch));
    const beforeValue = openSignalSubscription.getValue();
    let afterValue;
    try {
      afterValue = applyPatches(openSignalSubscription.getValue(), patches);
    } catch (error) {
      this.communicationWarning(text`
        Failed to apply patches to writable signal on writableSignalUpdate. subscribeId =
        ${message.subscribeId}.

        beforeValue = ${JSON.stringify(beforeValue, null, 2)},

        patches = ${JSON.stringify(patches, null, 2)}.

        Error: ${String(error)}
      `);
    }
    const parseResult = openSignalSubscription.endpoint.signalData.safeParse(afterValue);
    if (!parseResult.success) {
      this.communicationWarning(text`
        Received invalid writable signal patch data, subscribeId = ${message.subscribeId}

        patches = ${patches},

        beforeValue = ${beforeValue},

        afterValue = ${afterValue}.

        Zod error:

        ${Validator.prettyPrintZod("value", parseResult.error)}
      `);
      return;
    }
    openSignalSubscription.firstUpdateReceived = true;
    openSignalSubscription.receivedPatches(afterValue, patches, message.tags);
  }
  receivedWritableSignalError(message) {
    const openSignalSubscription = this.openWritableSignalSubscriptions.get(message.subscribeId);
    if (openSignalSubscription === void 0) {
      this.communicationWarning(`Received writableSignalError for unknown signal, subscribeId = ${message.subscribeId}`);
      return;
    }
    const error = this.errorDeserializer(message.error, "Writable Signal Error", this.verboseErrorMessage ? openSignalSubscription.stack : void 0);
    openSignalSubscription.errored(error);
    this.openWritableSignalSubscriptions.delete(message.subscribeId);
    this.updateOpenCommunicationsCount();
  }
  receivedCommunicationWarning(message) {
    this.logger.warnText`
      Received communication warning from the server: ${message.warning}
      
      This is usually caused by communication protocol incompatibility. Please make sure you are
      using the up-to-date versions of the SDK and LM Studio.

      Note: This warning was received from the server and is printed on the client for convenience.
    `;
  }
  receivedKeepAliveAck(_message) {
  }
  async callRpc(endpointName, param, { stack } = {}) {
    const endpoint = this.backendInterface.getRpcEndpoint(endpointName);
    if (endpoint === void 0) {
      throw new Error(`No Rpc endpoint with name ${endpointName}`);
    }
    const parameter = endpoint.parameter.parse(param);
    const serializedParameter = serialize(endpoint.serialization, parameter);
    const callId = this.nextChannelId;
    this.nextChannelId++;
    const { promise, resolve, reject } = makePromise();
    stack = stack ?? getCurrentStack(1);
    this.ongoingRpcs.set(callId, {
      endpoint,
      stack,
      resolve,
      reject
    });
    this.transport.send({
      type: "rpcCall",
      endpoint: endpointName,
      callId,
      parameter: serializedParameter
    });
    this.updateOpenCommunicationsCount();
    return await promise;
  }
  createChannel(endpointName, param, onMessage, { stack } = {}) {
    const channelEndpoint = this.backendInterface.getChannelEndpoint(endpointName);
    if (channelEndpoint === void 0) {
      throw new Error(`No channel endpoint with name ${endpointName}`);
    }
    const creationParameter = channelEndpoint.creationParameter.parse(param);
    const serializedCreationParameter = serialize(channelEndpoint.serialization, creationParameter);
    const channelId = this.nextChannelId;
    this.nextChannelId++;
    this.transport.send({
      type: "channelCreate",
      endpoint: endpointName,
      channelId,
      creationParameter: serializedCreationParameter
    });
    stack = stack ?? getCurrentStack(1);
    const openChannel = {
      endpoint: channelEndpoint,
      stack,
      ...Channel.create((packet) => {
        const parsed = channelEndpoint.toServerPacket.parse(packet);
        const serializedMessage = serialize(channelEndpoint.serialization, parsed);
        this.transport.send({
          type: "channelSend",
          channelId,
          message: serializedMessage
        });
      })
    };
    if (onMessage !== void 0) {
      openChannel.channel.onMessage.subscribe(onMessage);
    }
    this.openChannels.set(channelId, openChannel);
    this.updateOpenCommunicationsCount();
    return openChannel.channel;
  }
  /**
   * Creates a readonly lazy signal will subscribe to the signal endpoint with the given name.
   */
  createSignal(endpointName, param, { stack } = {}) {
    const signalEndpoint = this.backendInterface.getSignalEndpoint(endpointName);
    if (signalEndpoint === void 0) {
      throw new Error(`No signal endpoint with name ${endpointName}`);
    }
    const creationParameter = signalEndpoint.creationParameter.parse(param);
    const serializedCreationParameter = serialize(signalEndpoint.serialization, creationParameter);
    stack = stack ?? getCurrentStack(1);
    const signal = LazySignal.createWithoutInitialValue((setDownstream, errorListener) => {
      const subscribeId = this.nextSubscribeId;
      this.nextSubscribeId++;
      this.transport.send({
        type: "signalSubscribe",
        endpoint: endpointName,
        subscribeId,
        creationParameter: serializedCreationParameter
      });
      this.openSignalSubscriptions.set(subscribeId, {
        endpoint: signalEndpoint,
        getValue: () => signal.get(),
        receivedPatches: setDownstream.withValueAndPatches,
        errored: errorListener,
        stack
      });
      this.updateOpenCommunicationsCount();
      return () => {
        this.transport.send({
          type: "signalUnsubscribe",
          subscribeId
        });
        this.openSignalSubscriptions.delete(subscribeId);
      };
    });
    return signal;
  }
  createWritableSignal(endpointName, param, { stack } = {}) {
    const signalEndpoint = this.backendInterface.getWritableSignalEndpoint(endpointName);
    if (signalEndpoint === void 0) {
      throw new Error(`No writable signal endpoint with name ${endpointName}`);
    }
    const creationParameter = signalEndpoint.creationParameter.parse(param);
    const serializedCreationParameter = serialize(signalEndpoint.serialization, creationParameter);
    stack = stack ?? getCurrentStack(1);
    let currentSubscribeId = null;
    const writeUpstream = (_data, patches, tags) => {
      if (currentSubscribeId === null) {
        console.warn("writeUpstream called when not subscribed");
        return false;
      }
      const subscription = this.openWritableSignalSubscriptions.get(currentSubscribeId);
      if (!subscription?.firstUpdateReceived) {
        console.warn("writeUpstream called before the first update is received");
        return false;
      }
      this.transport.send({
        type: "writableSignalUpdate",
        subscribeId: currentSubscribeId,
        patches: patches.map((patch) => serialize(signalEndpoint.serialization, patch)),
        tags
      });
      return true;
    };
    const [signal, setter] = OWLSignal.createWithoutInitialValue((setDownstream, errorListener) => {
      const subscribeId = this.nextWritableSubscribeId;
      currentSubscribeId = subscribeId;
      this.nextWritableSubscribeId++;
      this.transport.send({
        type: "writableSignalSubscribe",
        endpoint: endpointName,
        subscribeId,
        creationParameter: serializedCreationParameter
      });
      this.openWritableSignalSubscriptions.set(subscribeId, {
        endpoint: signalEndpoint,
        getValue: () => signal.getPessimistic(),
        receivedPatches: setDownstream.withValueAndPatches,
        firstUpdateReceived: false,
        errored: errorListener,
        stack
      });
      this.updateOpenCommunicationsCount();
      return () => {
        currentSubscribeId = null;
        this.transport.send({
          type: "writableSignalUnsubscribe",
          subscribeId
        });
        this.openWritableSignalSubscriptions.delete(subscribeId);
      };
    }, writeUpstream);
    return [signal, setter];
  }
  async [Symbol.asyncDispose]() {
    await this.transport[Symbol.asyncDispose]();
  }
};
var GenericClientTransport = class _GenericClientTransport extends ClientTransport {
  constructor(onMessage, onClose, sendMessage, receivedMessage, errored, parentLogger) {
    super();
    this.sendMessage = sendMessage;
    this.receivedMessage = receivedMessage;
    this.errored = errored;
    this.closed = false;
    this.logger = new SimpleLogger("GenericClientTransport", parentLogger);
    onMessage.subscribe((message) => {
      let parsed;
      try {
        parsed = this.parseIncomingMessage(message);
      } catch (error) {
        this.logger.warn("Received invalid message from server:", message);
        return;
      }
      this.receivedMessage(parsed);
    });
    onClose.subscribeOnce(() => {
      if (this.closed) {
        return;
      }
      this.closed = true;
      this.errored(new Error("Server closed the connection"));
    });
  }
  static createFactory(onMessage, onClose, sendMessage) {
    return (receivedMessage, errored, parentLogger) => new _GenericClientTransport(onMessage, onClose, sendMessage, receivedMessage, errored, parentLogger);
  }
  sendViaTransport(message) {
    this.sendMessage(message);
  }
};
function getHostedEnv() {
  let anyWindow;
  try {
    anyWindow = window;
  } catch (error) {
    anyWindow = void 0;
  }
  if (anyWindow !== void 0 && anyWindow.lmsHostedEnv !== void 0) {
    return anyWindow.lmsHostedEnv;
  }
  return null;
}
function createBaseModelBackendInterface(specificModelInstanceInfoSchemaInput, specificModelInfoSchemaInput) {
  const specificModelInstanceInfoSchema = specificModelInstanceInfoSchemaInput;
  const specificModelInfoSchema = specificModelInfoSchemaInput;
  return new BackendInterface().addChannelEndpoint("loadModel", {
    creationParameter: external_exports.object({
      modelKey: external_exports.string(),
      identifier: external_exports.string().optional(),
      /**
       * If provided, when the model is not used for this amount of time, it will be unloaded.
       */
      ttlMs: external_exports.number().int().min(1).optional(),
      loadConfigStack: kvConfigStackSchema
    }),
    toClientPacket: external_exports.discriminatedUnion("type", [
      external_exports.object({
        type: external_exports.literal("resolved"),
        info: specificModelInfoSchema,
        ambiguous: external_exports.array(external_exports.string()).optional()
      }),
      external_exports.object({
        type: external_exports.literal("progress"),
        progress: external_exports.number()
      }),
      external_exports.object({
        type: external_exports.literal("success"),
        info: specificModelInstanceInfoSchema
      })
    ]),
    toServerPacket: external_exports.discriminatedUnion("type", [
      external_exports.object({
        type: external_exports.literal("cancel")
      })
    ])
  }).addRpcEndpoint("unloadModel", {
    parameter: external_exports.object({
      identifier: external_exports.string()
    }),
    returns: external_exports.void()
  }).addRpcEndpoint("listLoaded", {
    parameter: external_exports.undefined(),
    returns: external_exports.array(specificModelInstanceInfoSchema)
  }).addRpcEndpoint("getModelInfo", {
    parameter: external_exports.object({
      specifier: modelSpecifierSchema,
      throwIfNotFound: external_exports.boolean()
    }),
    returns: specificModelInstanceInfoSchema.optional()
  }).addRpcEndpoint("getLoadConfig", {
    parameter: external_exports.object({
      specifier: modelSpecifierSchema
    }),
    returns: kvConfigSchema
  }).addChannelEndpoint("getOrLoad", {
    creationParameter: external_exports.object({
      identifier: external_exports.string(),
      /**
       * If provided and a new instance is loaded as a result of this call, it will be unloaded
       * after idling for this amount of time.
       */
      loadTtlMs: external_exports.number().int().min(1).optional(),
      loadConfigStack: kvConfigStackSchema
    }),
    toClientPacket: external_exports.discriminatedUnion("type", [
      external_exports.object({
        type: external_exports.literal("alreadyLoaded"),
        info: specificModelInstanceInfoSchema
      }),
      external_exports.object({
        type: external_exports.literal("startLoading"),
        identifier: external_exports.string(),
        info: specificModelInfoSchema
      }),
      external_exports.object({
        // We are unloading other JIT model
        type: external_exports.literal("unloadingOtherJITModel"),
        info: modelInstanceInfoSchema
      }),
      external_exports.object({
        type: external_exports.literal("loadProgress"),
        progress: external_exports.number()
      }),
      external_exports.object({
        type: external_exports.literal("loadSuccess"),
        info: specificModelInstanceInfoSchema
      })
    ]),
    toServerPacket: external_exports.discriminatedUnion("type", [
      external_exports.object({
        type: external_exports.literal("cancel")
      })
    ])
  });
}
function createDiagnosticsBackendInterface() {
  return new BackendInterface().addChannelEndpoint("streamLogs", {
    creationParameter: external_exports.void(),
    toServerPacket: external_exports.discriminatedUnion("type", [
      external_exports.object({
        type: external_exports.literal("stop")
      })
    ]),
    toClientPacket: external_exports.discriminatedUnion("type", [
      external_exports.object({
        type: external_exports.literal("log"),
        log: diagnosticsLogEventSchema
      })
    ])
  });
}
function createEmbeddingBackendInterface() {
  const baseModelBackendInterface = createBaseModelBackendInterface(embeddingModelInstanceInfoSchema, embeddingModelInfoSchema);
  return baseModelBackendInterface.addRpcEndpoint("embedString", {
    parameter: external_exports.object({
      modelSpecifier: modelSpecifierSchema,
      inputString: external_exports.string()
    }),
    returns: external_exports.object({
      embedding: external_exports.array(external_exports.number())
    })
  }).addRpcEndpoint("tokenize", {
    parameter: external_exports.object({
      specifier: modelSpecifierSchema,
      inputString: external_exports.string()
    }),
    returns: external_exports.object({
      tokens: external_exports.array(external_exports.number())
    })
  }).addRpcEndpoint("countTokens", {
    parameter: external_exports.object({
      specifier: modelSpecifierSchema,
      inputString: external_exports.string()
    }),
    returns: external_exports.object({
      tokenCount: external_exports.number().int()
    })
  });
}
function createFilesBackendInterface() {
  return new BackendInterface().addRpcEndpoint("getLocalFileAbsolutePath", {
    parameter: external_exports.object({
      fileName: external_exports.string()
    }),
    returns: external_exports.object({
      path: external_exports.string()
    })
  }).addRpcEndpoint("uploadFileBase64", {
    parameter: external_exports.object({
      name: external_exports.string(),
      contentBase64: external_exports.string()
    }),
    returns: external_exports.object({
      identifier: external_exports.string(),
      fileType: fileTypeSchema,
      sizeBytes: external_exports.number().int()
    })
  }).addChannelEndpoint("retrieve", {
    creationParameter: external_exports.object({
      query: external_exports.string(),
      fileIdentifiers: external_exports.array(external_exports.string()),
      config: kvConfigSchema
    }),
    toServerPacket: external_exports.discriminatedUnion("type", [
      external_exports.object({
        type: external_exports.literal("stop")
      })
    ]),
    toClientPacket: external_exports.discriminatedUnion("type", [
      external_exports.object({
        type: external_exports.literal("onFileProcessList"),
        indices: external_exports.array(external_exports.number().int())
      }),
      external_exports.object({
        type: external_exports.literal("onFileProcessingStart"),
        index: external_exports.number().int()
      }),
      external_exports.object({
        type: external_exports.literal("onFileProcessingEnd"),
        index: external_exports.number().int()
      }),
      external_exports.object({
        type: external_exports.literal("onFileProcessingStepStart"),
        index: external_exports.number().int(),
        step: retrievalFileProcessingStepSchema
      }),
      external_exports.object({
        type: external_exports.literal("onFileProcessingStepProgress"),
        index: external_exports.number().int(),
        step: retrievalFileProcessingStepSchema,
        progress: external_exports.number()
      }),
      external_exports.object({
        type: external_exports.literal("onFileProcessingStepEnd"),
        index: external_exports.number().int(),
        step: retrievalFileProcessingStepSchema
      }),
      external_exports.object({
        type: external_exports.literal("onSearchingStart")
      }),
      external_exports.object({
        type: external_exports.literal("onSearchingEnd")
      }),
      external_exports.object({
        type: external_exports.literal("result"),
        result: internalRetrievalResultSchema
      })
    ])
  }).addChannelEndpoint("parseDocument", {
    creationParameter: external_exports.object({
      fileIdentifier: external_exports.string(),
      parseOpts: documentParsingOptsSchema
    }),
    toClientPacket: external_exports.discriminatedUnion("type", [
      external_exports.object({
        type: external_exports.literal("parserLoaded"),
        parser: documentParsingLibraryIdentifierSchema
      }),
      external_exports.object({
        type: external_exports.literal("progress"),
        progress: external_exports.number()
      }),
      external_exports.object({
        type: external_exports.literal("result"),
        content: external_exports.string(),
        parser: documentParsingLibraryIdentifierSchema
      })
    ]),
    toServerPacket: external_exports.discriminatedUnion("type", [
      external_exports.object({
        type: external_exports.literal("cancel")
      })
    ])
  }).addRpcEndpoint("getDocumentParsingLibrary", {
    parameter: external_exports.object({
      fileIdentifier: external_exports.string()
    }),
    returns: external_exports.object({
      library: external_exports.string(),
      version: external_exports.string()
    })
  });
}
function createLlmBackendInterface() {
  const baseModelBackendInterface = createBaseModelBackendInterface(llmInstanceInfoSchema, llmInfoSchema);
  return baseModelBackendInterface.addChannelEndpoint("predict", {
    creationParameter: external_exports.object({
      modelSpecifier: modelSpecifierSchema,
      history: chatHistoryDataSchema,
      predictionConfigStack: kvConfigStackSchema,
      /**
       * Which preset to use. Supports limited fuzzy matching.
       */
      fuzzyPresetIdentifier: external_exports.string().optional(),
      ignoreServerSessionConfig: external_exports.boolean().optional()
    }),
    toClientPacket: external_exports.discriminatedUnion("type", [
      external_exports.object({
        type: external_exports.literal("fragment"),
        fragment: llmPredictionFragmentSchema,
        logprobs: external_exports.array(external_exports.array(external_exports.object({ text: external_exports.string(), logprob: external_exports.number() }))).optional()
      }),
      external_exports.object({
        type: external_exports.literal("promptProcessingProgress"),
        progress: external_exports.number()
      }),
      external_exports.object({
        type: external_exports.literal("toolCallGenerationStart"),
        /**
         * The LLM specific call id of the tool call.
         */
        toolCallId: external_exports.string().optional()
      }),
      external_exports.object({
        type: external_exports.literal("toolCallGenerationNameReceived"),
        name: external_exports.string()
      }),
      external_exports.object({
        type: external_exports.literal("toolCallGenerationArgumentFragmentGenerated"),
        content: external_exports.string()
      }),
      external_exports.object({
        type: external_exports.literal("toolCallGenerationEnd"),
        toolCallRequest: toolCallRequestSchema,
        /**
         * The raw output that represents this tool call. It is recommended to present this to
         * the user as is, if desired.
         *
         * @remarks It is not guaranteed to be valid JSON as the model does not necessarily use
         * JSON to represent tool calls.
         */
        rawContent: external_exports.string().optional()
      }),
      external_exports.object({
        type: external_exports.literal("toolCallGenerationFailed"),
        error: serializedLMSExtendedErrorSchema,
        /**
         * The raw output that was generated by the model before the tool call. The exact nature
         * of this fields depends on the error. It sometimes include the entire tool calls
         * section, or sometimes just the single tool call that failed.
         *
         * It is recommended to present this to the user as is, if desired.
         */
        rawContent: external_exports.string().optional()
      }),
      external_exports.object({
        type: external_exports.literal("success"),
        stats: llmPredictionStatsSchema,
        modelInfo: llmInstanceInfoSchema,
        loadModelConfig: kvConfigSchema,
        predictionConfig: kvConfigSchema
      })
    ]),
    toServerPacket: external_exports.discriminatedUnion("type", [
      external_exports.object({
        type: external_exports.literal("cancel")
      })
    ])
  }).addRpcEndpoint("applyPromptTemplate", {
    parameter: external_exports.object({
      specifier: modelSpecifierSchema,
      history: chatHistoryDataSchema,
      predictionConfigStack: kvConfigStackSchema,
      opts: llmApplyPromptTemplateOptsSchema
    }),
    returns: external_exports.object({
      formatted: external_exports.string()
    })
  }).addRpcEndpoint("tokenize", {
    parameter: external_exports.object({
      specifier: modelSpecifierSchema,
      inputString: external_exports.string()
    }),
    returns: external_exports.object({
      tokens: external_exports.array(external_exports.number())
    })
  }).addRpcEndpoint("countTokens", {
    parameter: external_exports.object({
      specifier: modelSpecifierSchema,
      inputString: external_exports.string()
    }),
    returns: external_exports.object({
      tokenCount: external_exports.number().int()
    })
  }).addRpcEndpoint("preloadDraftModel", {
    parameter: external_exports.object({
      specifier: modelSpecifierSchema,
      draftModelKey: external_exports.string()
    }),
    returns: external_exports.void()
  });
}
function createPluginsBackendInterface() {
  return new BackendInterface().addChannelEndpoint("startToolUseSession", {
    creationParameter: external_exports.object({
      pluginIdentifier: external_exports.string(),
      pluginConfigSpecifier: pluginConfigSpecifierSchema
    }),
    toClientPacket: external_exports.discriminatedUnion("type", [
      /**
       * The session has been started successfully. The client can now use the session. Note,
       * there are no sessionError message because if a session fails to start, the channel
       * will error instead.
       */
      external_exports.object({
        type: external_exports.literal("sessionReady"),
        toolDefinitions: external_exports.array(llmToolSchema)
      }),
      /**
       * A tool call has been completed.
       */
      external_exports.object({
        type: external_exports.literal("toolCallComplete"),
        callId: external_exports.number(),
        result: jsonSerializableSchema
      }),
      /**
       * A tool call has failed.
       */
      external_exports.object({
        type: external_exports.literal("toolCallError"),
        callId: external_exports.number(),
        error: serializedLMSExtendedErrorSchema
      }),
      /**
       * Status update for a tool call.
       */
      external_exports.object({
        type: external_exports.literal("toolCallStatus"),
        callId: external_exports.number(),
        statusText: external_exports.string()
      }),
      /**
       * Warning message for a tool call.
       */
      external_exports.object({
        type: external_exports.literal("toolCallWarn"),
        callId: external_exports.number(),
        warnText: external_exports.string()
      })
    ]),
    toServerPacket: external_exports.discriminatedUnion("type", [
      /**
       * Request to start a tool call. This call can be aborted using the `abortToolCall`
       * packet. When the tool call is completed, either the `toolCallResult` or `toolCallError`
       * packet will be sent.
       */
      external_exports.object({
        type: external_exports.literal("callTool"),
        callId: external_exports.number(),
        name: external_exports.string(),
        arguments: jsonSerializableSchema
      }),
      /**
       * Request to abort a tool call. Upon calling this, no toolCallComplete or toolCallError
       * packets will be sent for the call. We assume abort is done immediately.
       */
      external_exports.object({
        type: external_exports.literal("abortToolCall"),
        callId: external_exports.number()
      }),
      /**
       * Client requests to discard the session. Upon calling this, the channel will be closed.
       */
      external_exports.object({
        type: external_exports.literal("discardSession")
      })
    ])
  }).addChannelEndpoint("generateWithGenerator", {
    creationParameter: external_exports.object({
      pluginIdentifier: external_exports.string(),
      pluginConfigSpecifier: pluginConfigSpecifierSchema,
      tools: external_exports.array(llmToolSchema),
      history: chatHistoryDataSchema
    }),
    toClientPacket: external_exports.discriminatedUnion("type", [
      external_exports.object({
        type: external_exports.literal("fragment"),
        fragment: llmPredictionFragmentSchema
      }),
      external_exports.object({
        type: external_exports.literal("promptProcessingProgress"),
        progress: external_exports.number()
      }),
      external_exports.object({
        type: external_exports.literal("toolCallGenerationStart"),
        /**
         * The LLM specific call id of the tool call.
         */
        toolCallId: external_exports.string().optional()
      }),
      external_exports.object({
        type: external_exports.literal("toolCallGenerationNameReceived"),
        name: external_exports.string()
      }),
      external_exports.object({
        type: external_exports.literal("toolCallGenerationArgumentFragmentGenerated"),
        content: external_exports.string()
      }),
      external_exports.object({
        type: external_exports.literal("toolCallGenerationEnd"),
        toolCallRequest: toolCallRequestSchema
      }),
      external_exports.object({
        type: external_exports.literal("toolCallGenerationFailed")
      }),
      external_exports.object({
        type: external_exports.literal("success")
      })
    ]),
    toServerPacket: external_exports.discriminatedUnion("type", [
      external_exports.object({
        type: external_exports.literal("cancel")
      })
    ])
  }).addChannelEndpoint("registerDevelopmentPlugin", {
    creationParameter: external_exports.object({
      manifest: pluginManifestSchema
    }),
    toClientPacket: external_exports.discriminatedUnion("type", [
      external_exports.object({
        type: external_exports.literal("ready"),
        clientIdentifier: external_exports.string(),
        clientPasskey: external_exports.string()
      })
    ]),
    toServerPacket: external_exports.discriminatedUnion("type", [
      external_exports.object({
        type: external_exports.literal("end")
      })
    ])
  }).addRpcEndpoint("reindexPlugins", {
    parameter: external_exports.void(),
    returns: external_exports.void()
  }).addChannelEndpoint("setPromptPreprocessor", {
    creationParameter: external_exports.void(),
    toClientPacket: external_exports.discriminatedUnion("type", [
      external_exports.object({
        type: external_exports.literal("preprocess"),
        taskId: external_exports.string(),
        input: chatMessageDataSchema,
        config: kvConfigSchema,
        pluginConfig: kvConfigSchema,
        globalPluginConfig: kvConfigSchema,
        workingDirectoryPath: external_exports.string().nullable(),
        /**
         * An array of all the plugins that are enabled for this prediction.
         */
        enabledPluginInfos: external_exports.array(remotePluginInfoSchema),
        /** Processing Context Identifier */
        pci: external_exports.string(),
        token: external_exports.string()
      }),
      external_exports.object({
        type: external_exports.literal("abort"),
        taskId: external_exports.string()
      })
    ]),
    toServerPacket: external_exports.discriminatedUnion("type", [
      external_exports.object({
        type: external_exports.literal("complete"),
        taskId: external_exports.string(),
        processed: chatMessageDataSchema
      }),
      external_exports.object({
        type: external_exports.literal("aborted"),
        taskId: external_exports.string()
      }),
      external_exports.object({
        type: external_exports.literal("error"),
        taskId: external_exports.string(),
        error: serializedLMSExtendedErrorSchema
      })
    ])
  }).addChannelEndpoint("setPredictionLoopHandler", {
    creationParameter: external_exports.void(),
    toClientPacket: external_exports.discriminatedUnion("type", [
      external_exports.object({
        type: external_exports.literal("handlePredictionLoop"),
        taskId: external_exports.string(),
        config: kvConfigSchema,
        pluginConfig: kvConfigSchema,
        globalPluginConfig: kvConfigSchema,
        workingDirectoryPath: external_exports.string().nullable(),
        /**
         * An array of all the plugins that are enabled for this prediction.
         */
        enabledPluginInfos: external_exports.array(remotePluginInfoSchema),
        /** Processing Context Identifier */
        pci: external_exports.string(),
        token: external_exports.string()
      }),
      external_exports.object({
        type: external_exports.literal("abort"),
        taskId: external_exports.string()
      })
    ]),
    toServerPacket: external_exports.discriminatedUnion("type", [
      external_exports.object({
        type: external_exports.literal("complete"),
        taskId: external_exports.string()
      }),
      external_exports.object({
        type: external_exports.literal("aborted"),
        taskId: external_exports.string()
      }),
      external_exports.object({
        type: external_exports.literal("error"),
        taskId: external_exports.string(),
        error: serializedLMSExtendedErrorSchema
      })
    ])
  }).addChannelEndpoint("setToolsProvider", {
    creationParameter: external_exports.void(),
    toClientPacket: external_exports.discriminatedUnion("type", [
      /**
       * Starts a "tool providing session". Once this is received, the plugin should call the
       * tools provider and pass the tools to the server using the `sessionInitialized` packet.
       *
       * If the initialization failed, the plugin should send the `sessionInitializationFailed`
       * packet.
       */
      external_exports.object({
        type: external_exports.literal("initSession"),
        pluginConfig: kvConfigSchema,
        globalPluginConfig: kvConfigSchema,
        workingDirectoryPath: external_exports.string().nullable(),
        sessionId: external_exports.string()
      }),
      external_exports.object({
        type: external_exports.literal("discardSession"),
        sessionId: external_exports.string()
      }),
      /**
       * Call a tool within a session. The plugin should call the tool and return the result
       * using the `toolCallComplete` packet.
       *
       * If the tool call fails in an unrecoverable way the plugin can send the `toolCallError`
       * packet.
       */
      external_exports.object({
        type: external_exports.literal("callTool"),
        sessionId: external_exports.string(),
        callId: external_exports.string(),
        toolName: external_exports.string(),
        parameters: jsonSerializableSchema
      }),
      /**
       * Abort a tool call. The plugin should abort the tool call and confirm the abort using
       * the `toolCallAborted` packet.
       */
      external_exports.object({
        type: external_exports.literal("abortToolCall"),
        sessionId: external_exports.string(),
        callId: external_exports.string()
      })
    ]),
    toServerPacket: external_exports.discriminatedUnion("type", [
      /**
       * The plugin has provided a list of tools in a new session.
       */
      external_exports.object({
        type: external_exports.literal("sessionInitialized"),
        sessionId: external_exports.string(),
        toolDefinitions: external_exports.array(llmToolSchema)
      }),
      external_exports.object({
        type: external_exports.literal("sessionInitializationFailed"),
        sessionId: external_exports.string(),
        error: serializedLMSExtendedErrorSchema
      }),
      external_exports.object({
        type: external_exports.literal("toolCallComplete"),
        sessionId: external_exports.string(),
        callId: external_exports.string(),
        result: jsonSerializableSchema
      }),
      external_exports.object({
        type: external_exports.literal("toolCallError"),
        sessionId: external_exports.string(),
        callId: external_exports.string(),
        error: serializedLMSExtendedErrorSchema
      }),
      external_exports.object({
        type: external_exports.literal("toolCallStatus"),
        sessionId: external_exports.string(),
        callId: external_exports.string(),
        statusText: external_exports.string()
      }),
      external_exports.object({
        type: external_exports.literal("toolCallWarn"),
        sessionId: external_exports.string(),
        callId: external_exports.string(),
        warnText: external_exports.string()
      })
    ])
  }).addChannelEndpoint("setGenerator", {
    creationParameter: external_exports.void(),
    toClientPacket: external_exports.discriminatedUnion("type", [
      external_exports.object({
        type: external_exports.literal("generate"),
        taskId: external_exports.string(),
        input: chatHistoryDataSchema,
        pluginConfig: kvConfigSchema,
        globalPluginConfig: kvConfigSchema,
        toolDefinitions: external_exports.array(llmToolSchema),
        workingDirectoryPath: external_exports.string().nullable()
      }),
      external_exports.object({
        type: external_exports.literal("abort"),
        taskId: external_exports.string()
      })
    ]),
    toServerPacket: external_exports.discriminatedUnion("type", [
      external_exports.object({
        type: external_exports.literal("complete"),
        taskId: external_exports.string()
      }),
      external_exports.object({
        type: external_exports.literal("aborted"),
        taskId: external_exports.string()
      }),
      external_exports.object({
        type: external_exports.literal("error"),
        taskId: external_exports.string(),
        error: serializedLMSExtendedErrorSchema
      }),
      external_exports.object({
        type: external_exports.literal("fragmentGenerated"),
        taskId: external_exports.string(),
        content: external_exports.string(),
        opts: llmPredictionFragmentInputOptsSchema
      }),
      external_exports.object({
        type: external_exports.literal("toolCallGenerationStarted"),
        taskId: external_exports.string(),
        toolCallId: external_exports.string().optional()
      }),
      external_exports.object({
        type: external_exports.literal("toolCallGenerationNameReceived"),
        taskId: external_exports.string(),
        toolName: external_exports.string()
      }),
      external_exports.object({
        type: external_exports.literal("toolCallGenerationArgumentFragmentGenerated"),
        taskId: external_exports.string(),
        content: external_exports.string()
      }),
      external_exports.object({
        type: external_exports.literal("toolCallGenerationEnded"),
        taskId: external_exports.string(),
        toolCallRequest: toolCallRequestSchema
      }),
      external_exports.object({
        type: external_exports.literal("toolCallGenerationFailed"),
        taskId: external_exports.string(),
        error: serializedLMSExtendedErrorSchema
      })
    ])
  }).addRpcEndpoint("processingHandleUpdate", {
    parameter: external_exports.object({
      /** Processing Context Identifier */
      pci: external_exports.string(),
      token: external_exports.string(),
      update: processingUpdateSchema
    }),
    returns: external_exports.void()
  }).addRpcEndpoint("processingHandleRequest", {
    parameter: external_exports.object({
      /** Processing Context Identifier */
      pci: external_exports.string(),
      token: external_exports.string(),
      request: processingRequestSchema
    }),
    returns: external_exports.object({
      response: processingRequestResponseSchema
    })
  }).addRpcEndpoint("processingPullHistory", {
    parameter: external_exports.object({
      /** Processing Context Identifier */
      pci: external_exports.string(),
      token: external_exports.string(),
      includeCurrent: external_exports.boolean()
    }),
    returns: chatHistoryDataSchema
  }).addRpcEndpoint("processingGetOrLoadTokenSource", {
    parameter: external_exports.object({
      /** Processing Context Identifier */
      pci: external_exports.string(),
      token: external_exports.string()
    }),
    returns: external_exports.object({
      tokenSourceIdentifier: tokenSourceIdentifierSchema
    })
  }).addRpcEndpoint("processingHasStatus", {
    parameter: external_exports.object({
      /** Processing Context Identifier */
      pci: external_exports.string(),
      token: external_exports.string()
    }),
    returns: external_exports.boolean()
  }).addRpcEndpoint("processingNeedsNaming", {
    parameter: external_exports.object({
      /** Processing Context Identifier */
      pci: external_exports.string(),
      token: external_exports.string()
    }),
    returns: external_exports.boolean()
  }).addRpcEndpoint("processingSuggestName", {
    parameter: external_exports.object({
      /** Processing Context Identifier */
      pci: external_exports.string(),
      token: external_exports.string(),
      name: external_exports.string()
    }),
    returns: external_exports.void()
  }).addRpcEndpoint("processingSetSenderName", {
    parameter: external_exports.object({
      /** Processing Context Identifier */
      pci: external_exports.string(),
      token: external_exports.string(),
      name: external_exports.string()
    }),
    returns: external_exports.void()
  }).addRpcEndpoint("setConfigSchematics", {
    parameter: external_exports.object({
      schematics: serializedKVConfigSchematicsSchema
    }),
    returns: external_exports.void()
  }).addRpcEndpoint("setGlobalConfigSchematics", {
    parameter: external_exports.object({
      schematics: serializedKVConfigSchematicsSchema
    }),
    returns: external_exports.void()
  }).addRpcEndpoint("pluginInitCompleted", {
    parameter: external_exports.void(),
    returns: external_exports.void()
  });
}
function createRepositoryBackendInterface() {
  return new BackendInterface().addRpcEndpoint("searchModels", {
    parameter: external_exports.object({
      opts: modelSearchOptsSchema
    }),
    returns: external_exports.object({
      results: external_exports.array(modelSearchResultEntryDataSchema)
    })
  }).addRpcEndpoint("getModelDownloadOptions", {
    parameter: external_exports.object({
      modelSearchResultIdentifier: modelSearchResultIdentifierSchema
    }),
    returns: external_exports.object({
      results: external_exports.array(modelSearchResultDownloadOptionDataSchema)
    })
  }).addChannelEndpoint("downloadModel", {
    creationParameter: external_exports.object({
      downloadIdentifier: external_exports.string()
    }),
    toClientPacket: external_exports.discriminatedUnion("type", [
      external_exports.object({
        type: external_exports.literal("downloadProgress"),
        update: downloadProgressUpdateSchema
      }),
      external_exports.object({
        type: external_exports.literal("startFinalizing")
      }),
      external_exports.object({
        type: external_exports.literal("success"),
        defaultIdentifier: external_exports.string()
      })
    ]),
    toServerPacket: external_exports.discriminatedUnion("type", [
      external_exports.object({
        type: external_exports.literal("cancel")
      })
    ])
  }).addChannelEndpoint("downloadArtifact", {
    creationParameter: external_exports.object({
      artifactOwner: kebabCaseSchema,
      artifactName: kebabCaseWithDotsSchema,
      revisionNumber: external_exports.number().int().nullable(),
      path: external_exports.string()
    }),
    toClientPacket: external_exports.discriminatedUnion("type", [
      external_exports.object({
        type: external_exports.literal("downloadProgress"),
        update: downloadProgressUpdateSchema
      }),
      external_exports.object({
        type: external_exports.literal("startFinalizing")
      }),
      external_exports.object({
        type: external_exports.literal("success")
      })
    ]),
    toServerPacket: external_exports.discriminatedUnion("type", [
      external_exports.object({
        type: external_exports.literal("cancel")
      })
    ])
  }).addRpcEndpoint("installPluginDependencies", {
    parameter: external_exports.object({
      pluginFolder: external_exports.string()
    }),
    returns: external_exports.void()
  }).addRpcEndpoint("getLocalArtifactFiles", {
    parameter: external_exports.object({
      path: external_exports.string()
    }),
    returns: external_exports.object({
      fileList: localArtifactFileListSchema
    })
  }).addChannelEndpoint("pushArtifact", {
    creationParameter: external_exports.object({
      path: external_exports.string(),
      description: external_exports.string().max(1e3).optional(),
      /**
       * Request to make the artifact private. Only effective if the artifact did not exist
       * before. Will not change the visibility of an existing artifact.
       */
      makePrivate: external_exports.boolean().optional(),
      /**
       * If true, will write the revision number of the artifact after the push back to the
       * artifact manifest.json.
       */
      writeRevision: external_exports.boolean().optional(),
      overrides: jsonSerializableSchema.optional()
    }),
    toServerPacket: external_exports.void(),
    toClientPacket: external_exports.discriminatedUnion("type", [
      external_exports.object({
        type: external_exports.literal("message"),
        message: external_exports.string()
      })
    ])
  }).addChannelEndpoint("ensureAuthenticated", {
    creationParameter: external_exports.void(),
    toServerPacket: external_exports.void(),
    toClientPacket: external_exports.discriminatedUnion("type", [
      external_exports.object({
        type: external_exports.literal("authenticationUrl"),
        url: external_exports.string()
      }),
      external_exports.object({
        type: external_exports.literal("authenticated")
      })
    ])
  }).addRpcEndpoint("loginWithPreAuthenticatedKeys", {
    parameter: external_exports.object({
      keyId: external_exports.string(),
      publicKey: external_exports.string(),
      privateKey: external_exports.string()
    }),
    returns: external_exports.object({
      userName: external_exports.string()
    })
  }).addChannelEndpoint("createArtifactDownloadPlan", {
    creationParameter: external_exports.object({
      owner: kebabCaseSchema,
      name: kebabCaseWithDotsSchema
    }),
    toServerPacket: external_exports.discriminatedUnion("type", [
      /**
       * If called before committing the plan, the plan is aborted. If called after committing
       * the plan, the download is canceled.
       */
      external_exports.object({
        type: external_exports.literal("cancel")
      }),
      /**
       * Can only be called after plan ready. Once called, starts the plan.
       */
      external_exports.object({
        type: external_exports.literal("commit")
      })
    ]),
    toClientPacket: external_exports.discriminatedUnion("type", [
      external_exports.object({
        type: external_exports.literal("planUpdated"),
        plan: artifactDownloadPlanSchema
      }),
      external_exports.object({
        type: external_exports.literal("planReady"),
        plan: artifactDownloadPlanSchema
      }),
      external_exports.object({
        type: external_exports.literal("downloadProgress"),
        update: downloadProgressUpdateSchema
      }),
      external_exports.object({
        type: external_exports.literal("startFinalizing")
      }),
      external_exports.object({
        type: external_exports.literal("success")
      })
    ])
  });
}
function createSystemBackendInterface() {
  return new BackendInterface().addRpcEndpoint("listDownloadedModels", {
    parameter: external_exports.void(),
    returns: external_exports.array(modelInfoSchema)
  }).addChannelEndpoint("alive", {
    creationParameter: external_exports.void(),
    toServerPacket: external_exports.void(),
    toClientPacket: external_exports.void()
  }).addRpcEndpoint("notify", {
    parameter: backendNotificationSchema,
    returns: external_exports.void()
  }).addRpcEndpoint("version", {
    parameter: external_exports.void(),
    returns: external_exports.object({
      /**
       * `major.minor.patch`
       */
      version: external_exports.string(),
      /**
       * LM Studio build number
       */
      build: external_exports.number()
    })
  }).addRpcEndpoint("setExperimentFlag", {
    parameter: external_exports.object({
      code: external_exports.string(),
      value: external_exports.boolean()
    }),
    returns: external_exports.void()
  }).addRpcEndpoint("getExperimentFlags", {
    parameter: external_exports.void(),
    returns: external_exports.array(external_exports.string())
  }).addRpcEndpoint("startHttpServer", {
    parameter: external_exports.object({
      port: external_exports.number().int().min(1).max(65535).optional(),
      cors: external_exports.boolean().optional()
    }),
    returns: external_exports.void()
  }).addRpcEndpoint("stopHttpServer", {
    parameter: external_exports.void(),
    returns: external_exports.void()
  });
}
function createAuthenticatedIpcTransportFactory(apiNamespace, hostedEnv, clientIdentifier, clientPasskey) {
  const [onMessage, emitOnMessage] = BufferedEvent.create();
  const [onClose, emitOnClose] = BufferedEvent.create();
  const sendToServer = hostedEnv.getApiIpcTunnel(apiNamespace, {
    authVersion: 1,
    clientIdentifier,
    clientPasskey
  }, emitOnMessage, emitOnClose);
  return GenericClientTransport.createFactory(onMessage, onClose, sendToServer);
}
function createAuthenticatedWsTransportFactory(apiNamespace, wsAddress, clientIdentifier, clientPasskey) {
  return AuthenticatedWsClientTransport.createAuthenticatedWsClientTransportFactory({
    url: Promise.resolve(wsAddress).then((wsAddress2) => `${wsAddress2}/${apiNamespace}`),
    clientIdentifier,
    clientPasskey
  });
}
function createAuthenticatedClientPort(backendInterface, wsAddress, apiNamespace, clientIdentifier, clientPasskey, logger2, { errorDeserializer, verboseErrorMessage } = {}) {
  const hostedEnv = getHostedEnv();
  if (hostedEnv !== null) {
    if (wsAddress !== void 0) {
      logger2.debug("Ignoring wsAddress parameter when constructing the client because the client is running in a hosted environment. This is not an error.");
    }
    return new ClientPort(backendInterface, createAuthenticatedIpcTransportFactory(apiNamespace, hostedEnv, clientIdentifier, clientPasskey), { parentLogger: logger2, errorDeserializer, verboseErrorMessage });
  } else {
    return new ClientPort(backendInterface, createAuthenticatedWsTransportFactory(apiNamespace, wsAddress, clientIdentifier, clientPasskey), { parentLogger: logger2, errorDeserializer, verboseErrorMessage });
  }
}
var DiagnosticsNamespace = class {
  /** @internal */
  constructor(diagnosticsPort, validator2, parentLogger) {
    this.diagnosticsPort = diagnosticsPort;
    this.validator = validator2;
    this.logger = new SimpleLogger("Diagnostics", parentLogger);
  }
  /**
   * Register a callback to receive log events. Return a function to stop receiving log events.
   *
   * This method is in alpha. Do not use this method in production yet.
   * @alpha
   */
  unstable_streamLogs(listener) {
    const stack = getCurrentStack(1);
    this.validator.validateMethodParamOrThrow("client.diagnostics", "unstable_streamLogs", "listener", external_exports.function(), listener, stack);
    const channel = this.diagnosticsPort.createChannel("streamLogs", void 0, void 0, {
      stack
    });
    const unsubscribe = channel.onMessage.subscribe((message) => {
      if (message.type === "log") {
        listener(message.log);
      }
    });
    return () => {
      unsubscribe();
      channel.send({
        type: "stop"
      });
    };
  }
};
function makeLoadModelOptsSchema(loadModelConfigSchema) {
  return external_exports.object({
    identifier: external_exports.string().optional(),
    config: loadModelConfigSchema.optional(),
    signal: external_exports.instanceof(AbortSignal).optional(),
    ttl: external_exports.number().optional(),
    verbose: external_exports.union([external_exports.boolean(), logLevelSchema]).optional(),
    onProgress: external_exports.function().optional()
  });
}
var ModelNamespace = class {
  /** @internal */
  getLoadModelOptsSchema() {
    if (this.loadModelOptsSchema === null) {
      this.loadModelOptsSchema = makeLoadModelOptsSchema(this.loadModelConfigSchema);
    }
    return this.loadModelOptsSchema;
  }
  /** @internal */
  constructor(client, port, logger2, validator2) {
    this.client = client;
    this.port = port;
    this.logger = logger2;
    this.validator = validator2;
    this.loadModelOptsSchema = null;
  }
  /**
   * Load a model for inferencing. The first parameter is the model key. The second parameter is an
   * optional object with additional options.
   *
   * To find out what models are available, you can use the `lms ls` command, or programmatically
   * use the `client.system.listDownloadedModels` method.
   *
   * Here are some examples:
   *
   * Loading Llama 3.2:
   *
   * ```typescript
   * const model = await client.llm.load("llama-3.2-3b-instruct");
   * ```
   *
   * Once loaded, see {@link LLMDynamicHandle} or {@link EmbeddingDynamicHandle} for how to use the
   * model for inferencing or other things you can do with the model.
   *
   * @param modelKey - The path of the model to load.
   * @param opts - Options for loading the model.
   * @returns A promise that resolves to the model that can be used for inferencing
   */
  async load(modelKey, opts = {}) {
    const stack = getCurrentStack(1);
    [modelKey, opts] = this.validator.validateMethodParamsOrThrow(`client.${this.namespace}`, "load", ["modelKey", "opts"], [reasonableKeyStringSchema, this.getLoadModelOptsSchema()], [modelKey, opts], stack);
    const { identifier, signal, verbose = "info", config, onProgress } = opts;
    let lastVerboseCallTime = 0;
    const { promise, resolve, reject } = makePromise();
    const verboseLevel = typeof verbose === "boolean" ? "info" : verbose;
    const startTime = Date.now();
    if (verbose) {
      this.logger.logAtLevel(verboseLevel, text`
          Verbose logging is enabled. To hide progress logs, set the "verbose" option to false in
          client.llm.load.
        `);
    }
    let fullPath = modelKey;
    const channel = this.port.createChannel("loadModel", {
      modelKey,
      identifier,
      ttlMs: opts.ttl === void 0 ? void 0 : opts.ttl * 1e3,
      loadConfigStack: singleLayerKVConfigStackOf("apiOverride", this.loadConfigToKVConfig(config ?? this.defaultLoadConfig))
    }, (message) => {
      switch (message.type) {
        case "resolved": {
          fullPath = message.info.modelKey;
          if (message.ambiguous !== void 0) {
            this.logger.warn(text`
                Multiple models found for key ${modelKey}:

                ${message.ambiguous.map((x2) => ` - ${x2}`).join("\n")}

                Using the first one.
              `);
          }
          if (verbose) {
            this.logger.logAtLevel(verboseLevel, text`
                  Start loading model ${fullPath}...
                `);
          }
          break;
        }
        case "success": {
          if (verbose) {
            this.logger.logAtLevel(verboseLevel, text`
                  Successfully loaded model ${fullPath} in ${Date.now() - startTime}ms
                `);
          }
          resolve(this.createDomainSpecificModel(this.port, message.info, this.validator, this.logger));
          break;
        }
        case "progress": {
          const { progress } = message;
          if (onProgress !== void 0) {
            safeCallCallback(this.logger, "onProgress", onProgress, [progress]);
          } else if (verbose) {
            const now = Date.now();
            if (now - lastVerboseCallTime > 500 || progress === 1) {
              const progressText = (progress * 100).toFixed(1);
              this.logger.logAtLevel(verboseLevel, `Loading the model, progress: ${progressText}%`);
              lastVerboseCallTime = now;
            }
          }
        }
      }
    }, { stack });
    channel.onError.subscribeOnce(reject);
    if (signal !== void 0) {
      if (signal.aborted) {
        channel.send({ type: "cancel" });
        reject(signal.reason);
      } else {
        signal.addEventListener("abort", () => {
          channel.send({ type: "cancel" });
          reject(signal.reason);
        }, { once: true });
      }
    }
    return await promise;
  }
  /**
   * Unload a model. Once a model is unloaded, it can no longer be used. If you wish to use the
   * model afterwards, you will need to load it with {@link LLMNamespace#loadModel} again.
   *
   * @param identifier - The identifier of the model to unload.
   */
  unload(identifier) {
    const stack = getCurrentStack(1);
    this.validator.validateMethodParamOrThrow(`client.${this.namespace}`, "unload", "identifier", reasonableKeyStringSchema, identifier, stack);
    return this.port.callRpc("unloadModel", { identifier }, { stack });
  }
  /**
   * List all the currently loaded models.
   */
  async listLoaded() {
    const stack = getCurrentStack(1);
    const infos = await this.port.callRpc("listLoaded", void 0, { stack });
    return infos.map((info2) => this.createDomainSpecificModel(this.port, info2, this.validator, this.logger));
  }
  /**
   * Get any loaded model of this domain.
   */
  async getAny(stack) {
    const info2 = await this.port.callRpc("getModelInfo", { specifier: { type: "query", query: {} }, throwIfNotFound: true }, { stack });
    if (info2 === void 0) {
      throw new Error("Backend should have thrown.");
    }
    return this.createDomainSpecificModel(this.port, info2, this.validator, new SimpleLogger("LLM", this.logger));
  }
  createDynamicHandle(param) {
    const stack = getCurrentStack(1);
    this.validator.validateMethodParamOrThrow(`client.${this.namespace}`, "createDynamicHandle", "param", external_exports.union([reasonableKeyStringSchema, modelQuerySchema]), param, stack);
    let query;
    if (typeof param === "string") {
      query = {
        identifier: param
      };
    } else {
      query = param;
    }
    if (query.path?.includes("\\")) {
      throw makePrettyError(text`
          Model path should not contain backslashes, even if you are on Windows. Use forward
          slashes instead.
        `, stack);
    }
    return this.createDomainDynamicHandle(this.port, {
      type: "query",
      query
    }, this.validator, new SimpleLogger("DynamicHandle", this.logger));
  }
  /**
   * Create a dynamic handle from the internal instance reference.
   *
   * @alpha
   */
  createDynamicHandleFromInstanceReference(instanceReference) {
    const stack = getCurrentStack(1);
    this.validator.validateMethodParamOrThrow(`client.${this.namespace}`, "createDynamicHandleFromInstanceReference", "instanceReference", external_exports.string(), instanceReference, stack);
    return this.createDomainDynamicHandle(this.port, {
      type: "instanceReference",
      instanceReference
    }, this.validator, new SimpleLogger("DynamicHandle", this.logger));
  }
  async model(modelKey, opts = {}) {
    const stack = getCurrentStack(1);
    if (modelKey === void 0) {
      return await this.getAny(stack);
    }
    [modelKey, opts] = this.validator.validateMethodParamsOrThrow(`client.${this.namespace}`, "model", ["modelKey", "opts"], [reasonableKeyStringSchema, this.getLoadModelOptsSchema()], [modelKey, opts], stack);
    const { identifier, signal, verbose = "info", config, onProgress } = opts;
    if (identifier !== void 0) {
      throw new Error("The identifier option is not allowed when using `.model`.");
    }
    let lastVerboseCallTime = 0;
    const { promise, resolve, reject } = makePromise();
    const verboseLevel = typeof verbose === "boolean" ? "info" : verbose;
    const startTime = Date.now();
    const channel = this.port.createChannel("getOrLoad", {
      identifier: modelKey,
      loadTtlMs: opts.ttl === void 0 ? void 0 : opts.ttl * 1e3,
      loadConfigStack: singleLayerKVConfigStackOf("apiOverride", this.loadConfigToKVConfig(config ?? this.defaultLoadConfig))
    }, (message) => {
      switch (message.type) {
        case "alreadyLoaded": {
          return resolve(this.createDomainSpecificModel(this.port, message.info, this.validator, this.logger));
        }
        case "unloadingOtherJITModel": {
          if (verbose) {
            this.logger.logAtLevel(verboseLevel, text`
                  Unloading other JIT model ${message.info.modelKey}. (You can disable this behavior
                  by going to LM Studio -> Settings -> Developer -> Turn OFF JIT models auto-evict)
                `);
          }
          break;
        }
        case "startLoading": {
          if (verbose) {
            this.logger.logAtLevel(verboseLevel, text`
                  Verbose logging is enabled. To hide progress logs, set the "verbose" option to
                  false in .model().
                `);
            this.logger.logAtLevel(verboseLevel, text`
                  Model ${modelKey} is not loaded. Start loading...
                `);
          }
          break;
        }
        case "loadProgress": {
          const { progress } = message;
          if (onProgress !== void 0) {
            safeCallCallback(this.logger, "onProgress", onProgress, [progress]);
          } else if (verbose) {
            const now = Date.now();
            if (now - lastVerboseCallTime > 500 || progress === 1) {
              const progressText = (progress * 100).toFixed(1);
              this.logger.logAtLevel(verboseLevel, `Loading the model, progress: ${progressText}%`);
              lastVerboseCallTime = now;
            }
          }
          break;
        }
        case "loadSuccess": {
          if (verbose) {
            this.logger.logAtLevel(verboseLevel, text`
                  Successfully loaded model ${message.info.modelKey} in ${Date.now() - startTime}ms
                `);
          }
          resolve(this.createDomainSpecificModel(this.port, message.info, this.validator, this.logger));
        }
      }
    }, { stack });
    channel.onError.subscribeOnce(reject);
    signal?.addEventListener("abort", () => {
      channel.send({ type: "cancel" });
      reject(signal.reason);
    });
    return await promise;
  }
};
function numberToCheckboxNumeric(value, uncheckedValue, valueWhenUnchecked) {
  if (value === void 0) {
    return void 0;
  }
  if (value === uncheckedValue) {
    return { checked: false, value: valueWhenUnchecked };
  }
  return { checked: true, value };
}
var DynamicHandle = class {
  /**
   * Don't construct this on your own. Use {@link LLMNamespace#get} or {@link LLMNamespace#load}
   * instead.
   *
   * @internal
   */
  constructor(port, specifier) {
    this.port = port;
    this.specifier = specifier;
  }
  /**
   * Gets the information of the model that is currently associated with this `DynamicHandle`. If no
   * model is currently associated, this will return `undefined`.
   *
   * Note: As models are loaded/unloaded, the model associated with this `LLMModel` may change at
   * any moment.
   */
  async getModelInfo() {
    const info2 = await this.port.callRpc("getModelInfo", { specifier: this.specifier, throwIfNotFound: false }, { stack: getCurrentStack(1) });
    if (info2 === void 0) {
      return void 0;
    }
    return info2;
  }
  async getLoadConfig(stack) {
    const loadConfig = await this.port.callRpc("getLoadConfig", { specifier: this.specifier }, { stack });
    return loadConfig;
  }
};
var EmbeddingDynamicHandle = class extends DynamicHandle {
  /**
   * Don't construct this on your own. Use {@link EmbeddingNamespace#get} or
   * {@link EmbeddingNamespace#load}
   * instead.
   *
   * @internal
   */
  constructor(port, specifier, validator2, logger2 = new SimpleLogger(`EmbeddingModel`)) {
    super(port, specifier);
    this.validator = validator2;
    this.logger = logger2;
  }
  async embed(inputString) {
    const stack = getCurrentStack(1);
    inputString = this.validator.validateMethodParamOrThrow("client.embedding", "embed", "inputString", external_exports.string().or(external_exports.array(external_exports.string())), inputString, stack);
    if (Array.isArray(inputString)) {
      return await Promise.all(inputString.map((s6) => this.port.callRpc("embedString", { inputString: s6, modelSpecifier: this.specifier }, { stack })));
    } else {
      return await this.port.callRpc("embedString", { inputString, modelSpecifier: this.specifier }, { stack });
    }
  }
  async getContextLength() {
    const stack = getCurrentStack(1);
    const loadConfig = await this.getLoadConfig(stack);
    return embeddingSharedLoadConfigSchematics.access(loadConfig, "contextLength");
  }
  async getEvalBatchSize() {
    const stack = getCurrentStack(1);
    const loadConfig = await this.getLoadConfig(stack);
    return globalConfigSchematics.access(loadConfig, "embedding.load.llama.evalBatchSize");
  }
  async tokenize(inputString) {
    const stack = getCurrentStack(1);
    inputString = this.validator.validateMethodParamOrThrow("model", "tokenize", "inputString", external_exports.string().or(external_exports.array(external_exports.string())), inputString, stack);
    if (Array.isArray(inputString)) {
      return (await Promise.all(inputString.map((s6) => this.port.callRpc("tokenize", { specifier: this.specifier, inputString: s6 }, { stack })))).map((r8) => r8.tokens);
    } else {
      return (await this.port.callRpc("tokenize", {
        specifier: this.specifier,
        inputString
      }, { stack })).tokens;
    }
  }
  async countTokens(inputString) {
    const stack = getCurrentStack(1);
    inputString = this.validator.validateMethodParamOrThrow("model", "countTokens", "inputString", external_exports.string(), inputString, stack);
    return (await this.port.callRpc("countTokens", {
      specifier: this.specifier,
      inputString
    }, { stack })).tokenCount;
  }
};
var EmbeddingModel = class extends EmbeddingDynamicHandle {
  /** @internal */
  constructor(embeddingPort, info2, validator2, logger2 = new SimpleLogger(`EmbeddingModel`)) {
    const specifier = {
      type: "instanceReference",
      instanceReference: info2.instanceReference
    };
    super(embeddingPort, specifier, validator2, logger2);
    this.identifier = info2.identifier;
    this.path = info2.path;
    this.modelKey = info2.modelKey;
    this.format = info2.format;
    this.displayName = info2.displayName;
    this.sizeBytes = info2.sizeBytes;
  }
  async unload() {
    const stack = getCurrentStack(1);
    await this.port.callRpc("unloadModel", { identifier: this.identifier }, { stack });
  }
  async getModelInfo() {
    const info2 = await super.getModelInfo();
    if (info2 === void 0) {
      const stack = getCurrentStack(1);
      throw makePrettyError("This model has already been unloaded", stack);
    }
    return info2;
  }
};
var EmbeddingNamespace = class extends ModelNamespace {
  constructor() {
    super(...arguments);
    this.namespace = "embedding";
    this.defaultLoadConfig = {};
    this.loadModelConfigSchema = embeddingLoadModelConfigSchema;
  }
  /** @internal */
  loadConfigToKVConfig(config) {
    return embeddingLlamaLoadConfigSchematics.buildPartialConfig({
      "llama.acceleration.offloadRatio": config.gpu?.ratio,
      "load.gpuSplitConfig": convertGPUSettingToGPUSplitConfig(config.gpu),
      "contextLength": config.contextLength,
      "llama.ropeFrequencyBase": numberToCheckboxNumeric(config.ropeFrequencyBase, 0, 0),
      "llama.ropeFrequencyScale": numberToCheckboxNumeric(config.ropeFrequencyScale, 0, 0),
      "llama.keepModelInMemory": config.keepModelInMemory,
      "llama.tryMmap": config.tryMmap
    });
  }
  /** @internal */
  createDomainSpecificModel(port, info2, validator2, logger2) {
    return new EmbeddingModel(port, info2, validator2, logger2);
  }
  /** @internal */
  createDomainDynamicHandle(port, specifier, validator2, logger2) {
    return new EmbeddingDynamicHandle(port, specifier, validator2, logger2);
  }
};
var parseDocumentOptsSchema = documentParsingOptsSchema.extend({
  onProgress: external_exports.function().optional(),
  signal: external_exports.instanceof(AbortSignal).optional()
});
var retrievalCallbacksSchema = external_exports.object({
  onFileProcessList: external_exports.function().optional(),
  onFileProcessingStart: external_exports.function().optional(),
  onFileProcessingEnd: external_exports.function().optional(),
  onFileProcessingStepStart: external_exports.function().optional(),
  onFileProcessingStepProgress: external_exports.function().optional(),
  onFileProcessingStepEnd: external_exports.function().optional(),
  onSearchingStart: external_exports.function().optional(),
  onSearchingEnd: external_exports.function().optional(),
  verbose: external_exports.union([external_exports.boolean(), external_exports.string()]).optional()
});
var retrievalOptsSchema = external_exports.object({
  chunkingMethod: retrievalChunkingMethodSchema.optional(),
  limit: external_exports.number().int().optional(),
  embeddingModel: external_exports.instanceof(EmbeddingDynamicHandle).optional(),
  databasePath: external_exports.string().optional(),
  signal: external_exports.instanceof(AbortSignal).optional(),
  ...retrievalCallbacksSchema.shape
});
function getProcessingStepName(processingStep) {
  switch (processingStep) {
    case "loading":
      return "Loading";
    case "chunking":
      return "Chunking";
    case "embedding":
      return "Embedding";
    default: {
      const exhaustiveCheck = processingStep;
      throw new Error(`Unexpected processing step: ${exhaustiveCheck}`);
    }
  }
}
var FilesNamespace = class {
  /** @internal */
  constructor(filesPort, validator2, parentLogger) {
    this.filesPort = filesPort;
    this.validator = validator2;
    this.logger = new SimpleLogger("File", parentLogger);
  }
  /**
   * Gets the absolute path to a local file.
   *
   * @internal
   */
  async getLocalFileAbsolutePath(fileName, stack) {
    return await this.filesPort.callRpc("getLocalFileAbsolutePath", { fileName }, { stack });
  }
  /**
   * Creates a file handle from a chat message part file data. Used internally.
   *
   * @internal
   */
  createFileHandleFromChatMessagePartFileData(data) {
    return new FileHandle(this, data.identifier, data.fileType, data.sizeBytes, data.name);
  }
  /**
   * Adds a temporary image to LM Studio, and returns a FileHandle that can be used to reference
   * this image. This image will be deleted when the client disconnects.
   *
   * This method can only be used in environments that have file system access (such as Node.js).
   */
  async prepareImage(path6) {
    const result = await (0, import_lms_isomorphic.readFileAsBase64)(path6);
    if (result.success === false) {
      throw new Error(text`
        Your current JavaScript environment does not support reading files. If you can read the file
        using other methods, please use "prepareImageBase64".
      `);
    }
    const fileName = path6.split(/[\\/]/).at(-1);
    const { identifier, fileType, sizeBytes } = await this.filesPort.callRpc("uploadFileBase64", {
      name: fileName,
      contentBase64: result.base64
    });
    return new FileHandle(this, identifier, fileType, sizeBytes, fileName);
  }
  /**
   * Adds a temporary image to LM Studio. The content of the file is specified using base64. If you
   * are using Node.js and have a file laying around, consider using `prepareImage` instead.
   */
  async prepareImageBase64(fileName, contentBase64) {
    const { identifier, fileType, sizeBytes } = await this.filesPort.callRpc("uploadFileBase64", {
      name: fileName,
      contentBase64
    });
    return new FileHandle(this, identifier, fileType, sizeBytes, fileName);
  }
  /**
   * Adds a temporary file to LM Studio, and returns a FileHandle that can be used to reference this
   * file. This file will be deleted when the client disconnects.
   *
   * This method can only be used in environments that have file system access (such as Node.js).
   *
   * @deprecated [DEP-RETRIEVAL] Retrieval API is still in active development. Stay tuned for
   * updates.
   */
  async prepareFile(path6) {
    const result = await (0, import_lms_isomorphic.readFileAsBase64)(path6);
    if (result.success === false) {
      throw new Error(text`
        Your current JavaScript environment does not support reading files. If you can read the file
        using other methods, please use "prepareFileBase64".
      `);
    }
    const fileName = path6.split(/[\\/]/).at(-1);
    const { identifier, fileType, sizeBytes } = await this.filesPort.callRpc("uploadFileBase64", {
      name: fileName,
      contentBase64: result.base64
    });
    return new FileHandle(this, identifier, fileType, sizeBytes, fileName);
  }
  /**
   * Adds a temporary file to LM Studio. The content of the file is specified using base64. If you
   * are using Node.js and have a file laying around, consider using `prepareFile` instead.
   *
   * @deprecated [DEP-RETRIEVAL] Retrieval API is still in active development. Stay tuned for
   * updates.   */
  async prepareFileBase64(fileName, contentBase64) {
    const { identifier, fileType, sizeBytes } = await this.filesPort.callRpc("uploadFileBase64", {
      name: fileName,
      contentBase64
    });
    return new FileHandle(this, identifier, fileType, sizeBytes, fileName);
  }
  /**
   * @deprecated [DEP-RETRIEVAL] Retrieval API is still in active development. Stay tuned for
   * updates.   */
  async retrieve(query, files, opts = {}) {
    const logger2 = this.logger;
    const stack = getCurrentStack(1);
    this.validator.validateMethodParamsOrThrow("client.retrieval", "retrieve", ["query", "filePaths", "opts"], [external_exports.string(), external_exports.array(external_exports.instanceof(FileHandle)), retrievalOptsSchema], [query, files, opts], stack);
    const { verbose = "info" } = opts;
    const verboseLevel = typeof verbose === "boolean" ? "info" : verbose;
    const shouldLog = verbose && opts.onFileProcessList === void 0 && opts.onFileProcessingStart === void 0 && opts.onFileProcessingEnd === void 0 && opts.onFileProcessingStepStart === void 0 && opts.onFileProcessingStepProgress === void 0 && opts.onFileProcessingStepEnd === void 0 && opts.onSearchingStart === void 0 && opts.onSearchingEnd === void 0;
    if (opts.embeddingModel === void 0) {
      throw new Error("Embedding model currently is required.");
    }
    const resolveFileIndex = (index) => {
      const file = files[index];
      if (file === void 0) {
        throw new Error(`File not found: ${index}`);
      }
      return file;
    };
    const resolveFileIndices = (indices) => {
      return indices.map(resolveFileIndex);
    };
    const kvConfig = retrievalSchematics.buildPartialConfig({
      chunkingMethod: opts.chunkingMethod,
      databaseFile: opts.databasePath,
      embeddingModel: (await opts.embeddingModel.getModelInfo())?.identifier,
      limit: opts.limit
    });
    let filesToProcess;
    const filesProcessingStartTimes = [];
    let searchingStartTime = 0;
    let lastVerboseCallTime = 0;
    let lastVerboseLine = "";
    return await new Promise((resolve, reject) => {
      const channel = this.filesPort.createChannel("retrieve", { query, fileIdentifiers: files.map((file) => file.identifier), config: kvConfig }, (message) => {
        switch (message.type) {
          case "onFileProcessList":
            filesToProcess = resolveFileIndices(message.indices);
            safeCallCallback(logger2, "onFileProcessList", opts.onFileProcessList, [
              filesToProcess
            ]);
            if (shouldLog) {
              logger2.logAtLevel(verboseLevel, text`
                    Found ${filesToProcess.length} files need processing:
                    ${filesToProcess.map((file) => file.name).join(", ")}
                  `);
            }
            break;
          case "onFileProcessingStart": {
            if (filesToProcess === null) {
              throw new Error("onFileProcessList must be called before onFileProcessingStart");
            }
            const file = resolveFileIndex(message.index);
            safeCallCallback(logger2, "onFileProcessingStart", opts.onFileProcessingStart, [
              file,
              filesToProcess.indexOf(file),
              filesToProcess
            ]);
            if (shouldLog) {
              filesProcessingStartTimes[message.index] = Date.now();
              logger2.logAtLevel(verboseLevel, text`
                    Start processing file: ${file.name}
                    (${message.index + 1}/${filesToProcess.length})
                  `);
            }
            break;
          }
          case "onFileProcessingEnd": {
            if (filesToProcess === null) {
              throw new Error("onFileProcessList must be called before onFileProcessingEnd");
            }
            const file = resolveFileIndex(message.index);
            safeCallCallback(logger2, "onFileProcessingEnd", opts.onFileProcessingEnd, [
              file,
              filesToProcess.indexOf(file),
              filesToProcess
            ]);
            if (shouldLog) {
              logger2.logAtLevel(verboseLevel, text`
                    File processed: ${file.name}.
                    Time took: ${Date.now() - filesProcessingStartTimes[message.index]}ms
                  `);
            }
            break;
          }
          case "onFileProcessingStepStart":
            safeCallCallback(logger2, "onFileProcessingStepStart", opts.onFileProcessingStepStart, [resolveFileIndex(message.index), message.step]);
            break;
          case "onFileProcessingStepProgress": {
            safeCallCallback(logger2, "onFileProcessingStepProgress", opts.onFileProcessingStepProgress, [resolveFileIndex(message.index), message.step, message.progress]);
            const now = Date.now();
            if (shouldLog && (now - lastVerboseCallTime > 500 || message.progress === 1)) {
              lastVerboseCallTime = now;
              const line = text`
                  > ${getProcessingStepName(message.step)}: ${Math.round(message.progress * 100)}%
                `;
              if (lastVerboseLine !== line) {
                lastVerboseLine = line;
                logger2.logAtLevel(verboseLevel, line);
              }
            }
            break;
          }
          case "onFileProcessingStepEnd":
            safeCallCallback(logger2, "onFileProcessingStepEnd", opts.onFileProcessingStepEnd, [
              resolveFileIndex(message.index),
              message.step
            ]);
            break;
          case "onSearchingStart":
            safeCallCallback(logger2, "onSearchingStart", opts.onSearchingStart, []);
            if (shouldLog) {
              searchingStartTime = Date.now();
              logger2.logAtLevel(verboseLevel, "Start searching in the vector database...");
            }
            break;
          case "onSearchingEnd":
            safeCallCallback(logger2, "onSearchingEnd", opts.onSearchingEnd, []);
            if (shouldLog) {
              logger2.logAtLevel(verboseLevel, text`
                    Finished searching in the vector database.
                    Time took: ${Date.now() - searchingStartTime}ms
                  `);
            }
            break;
          case "result": {
            resolve({
              entries: message.result.entries.map((entry) => ({
                content: entry.content,
                score: entry.score,
                source: files[entry.sourceIndex]
              }))
            });
            break;
          }
        }
      });
      if (opts.signal !== void 0) {
        if (opts.signal.aborted) {
          reject(opts.signal.reason);
          channel.send({ type: "stop" });
        } else {
          opts.signal?.addEventListener("abort", () => {
            reject(opts.signal.reason);
            channel.send({ type: "stop" });
          });
        }
      }
      channel.onError.subscribeOnce(reject);
    });
  }
  /**
   * Parse a document
   *
   * @deprecated [DEP-DOC-PARSE] Document parsing API is still in active development. Stay tuned for
   * updates.
   */
  async parseDocument(fileHandle, opts = {}) {
    const stack = getCurrentStack(1);
    this.validator.validateMethodParamsOrThrow("client.files", "parseDocument", ["fileHandle", "opts"], [external_exports.instanceof(FileHandle), parseDocumentOptsSchema], [fileHandle, opts], stack);
    const { onParserLoaded, onProgress, signal, ...config } = opts;
    const { promise, resolve, reject } = makePromise();
    opts.signal?.throwIfAborted();
    let finished2 = false;
    const channel = this.filesPort.createChannel("parseDocument", { fileIdentifier: fileHandle.identifier, parseOpts: config }, (message) => {
      const messageType = message.type;
      switch (messageType) {
        case "progress": {
          safeCallCallback(this.logger, "onProgress", onProgress, [message.progress]);
          break;
        }
        case "parserLoaded": {
          safeCallCallback(this.logger, "onParserLoaded", onParserLoaded, [message.parser]);
          break;
        }
        case "result": {
          resolve({
            content: message.content,
            parser: message.parser
          });
          finished2 = true;
          break;
        }
      }
    }, { stack });
    signal?.addEventListener("abort", () => {
      if (finished2) {
        return;
      }
      reject(signal.reason);
      channel.send({ type: "cancel" });
    });
    channel.onError.subscribeOnce(reject);
    channel.onClose.subscribeOnce(() => {
      if (!finished2) {
        reject(new Error("Channel closed before receiving a result."));
      }
    });
    return await promise;
  }
  /**
   * Get the parsing method for a document.
   *
   * @deprecated [DEP-DOC-PARSE] Document parsing API is still in active development. Stay tuned for
   * updates.
   */
  async getDocumentParsingLibrary(fileHandle) {
    const stack = getCurrentStack(1);
    return await this.filesPort.callRpc("getDocumentParsingLibrary", { fileIdentifier: fileHandle.identifier }, { stack });
  }
};
function deserializeOtherError(serialized, stack) {
  let content = import_chalk.default.redBright(` ${serialized.title} `);
  if (serialized.suggestion !== void 0) {
    content += "\n\n\n " + import_chalk.default.bgWhite.black("  (!) SUGGESTION  ") + "\n\n" + import_chalk.default.white(serialized.suggestion);
  }
  if (serialized.cause !== void 0) {
    content += "\n\n\n " + import_chalk.default.bgWhite.black("  (X) CAUSE  ") + "\n\n" + import_chalk.default.gray(serialized.cause);
  }
  return makePrettyError(content, stack);
}
var errorDeserializersMap = /* @__PURE__ */ new Map();
function registerErrorDeserializer(code, deserializer) {
  errorDeserializersMap.set(code, deserializer);
}
function formatAvailableLLMs(availablePathsSample, totalModels) {
  if (availablePathsSample.length === 0) {
    return import_chalk.default.gray("    You don't have any LLMs downloaded.");
  }
  let text3 = availablePathsSample.map((path6) => import_chalk.default.cyanBright(" \u2022 " + path6)).join("\n");
  if (availablePathsSample.length < totalModels) {
    text3 += import_chalk.default.gray(`
     ... (and ${totalModels - availablePathsSample.length} more)`);
  }
  return text3;
}
registerErrorDeserializer("generic.pathNotFound", ({ availablePathsSample, path: path6, totalModels }, stack) => {
  return makeTitledPrettyError(`Cannot find a model with path "${import_chalk.default.yellowBright(path6)}"`, text`
        Here are your available models:

        ${formatAvailableLLMs(availablePathsSample, totalModels)}

        Run

            ${import_chalk.default.yellowBright("lms ls")}

        to see a full list of loadable models
      `, stack);
});
function formatLoadedModels(loadedModelsSample, totalLoadedModels) {
  if (loadedModelsSample.length === 0) {
    return import_chalk.default.gray("    You don't have any models loaded.");
  }
  let text3 = loadedModelsSample.map((path6) => import_chalk.default.cyanBright(" \u2022 " + path6)).join("\n");
  if (loadedModelsSample.length < totalLoadedModels) {
    text3 += import_chalk.default.gray(`
     ... (and ${totalLoadedModels - loadedModelsSample.length} more)`);
  }
  return text3;
}
registerErrorDeserializer("generic.identifierNotFound", ({ loadedModelsSample, identifier, totalLoadedModels }, stack) => {
  return makeTitledPrettyError(`Cannot find a model with identifier "${import_chalk.default.yellowBright(identifier)}"`, text`
        Here are your loaded models:

        ${formatLoadedModels(loadedModelsSample, totalLoadedModels)}

        Run

            ${import_chalk.default.yellowBright("lms ps")}

        to see a full list of loaded models
      `, stack);
});
registerErrorDeserializer("generic.specificModelUnloaded", (_3, stack) => {
  return makePrettyError(import_chalk.default.bgRed.white(text`
      This model has already been unloaded.
    `), stack);
});
function getModelDomainTypeDisplayNameSingular(domain) {
  switch (domain) {
    case "llm":
      return "an LLM";
    case "embedding":
      return "an embedding model";
    case "imageGen":
      return "an image generation model";
    case "transcription":
      return "a transcription model";
    case "tts":
      return "a text-to-speech model";
    default: {
      const exhaustiveCheck = domain;
      console.error(`Unexpected domain type: ${exhaustiveCheck}`);
      return "Unknown Model Domain";
    }
  }
}
function formatQuery(query) {
  const requirements = [];
  if (query.domain !== void 0) {
    requirements.push(text`
      The model must be ${import_chalk.default.yellowBright(getModelDomainTypeDisplayNameSingular(query.domain))}
    `);
  }
  if (query.identifier !== void 0) {
    requirements.push(`The identifier must be exactly "${import_chalk.default.yellowBright(query.identifier)}"`);
  }
  if (query.path !== void 0) {
    requirements.push(`The path must match "${import_chalk.default.yellowBright(query.path)}"`);
  }
  if (requirements.length === 0) {
    return import_chalk.default.gray(" \u2022 Any Model");
  }
  return requirements.map((req) => import_chalk.default.white(" \u2022 " + req)).join("\n");
}
registerErrorDeserializer("generic.noModelMatchingQuery", ({ loadedModelsSample, totalLoadedModels, query }, stack) => {
  return makePrettyError(text`
        ${import_chalk.default.bgRed.white(" No loaded model satisfies all requirements specified in the query. ")}

        Loaded Models:

        ${formatLoadedModels(loadedModelsSample, totalLoadedModels)}

        Your query:

        ${formatQuery(query)}

        Run

            ${import_chalk.default.yellowBright("lms ps")}

        to see a full list of loaded models with details
      `, stack);
});
registerErrorDeserializer("generic.domainMismatch", ({ actualDomain, expectedDomain, path: path6 }, stack) => {
  return makePrettyError(text`
        ${import_chalk.default.bgRed.white(" Model has wrong domain. ")}

        Expecting ${import_chalk.default.greenBright(path6)} to be ${import_chalk.default.yellowBright(getModelDomainTypeDisplayNameSingular(expectedDomain))}, but it is actually ${import_chalk.default.yellowBright(getModelDomainTypeDisplayNameSingular(actualDomain))}.
      `, stack);
});
function formatAvailablePresets(presets, totalAvailablePresets) {
  if (presets.length === 0) {
    return import_chalk.default.gray("    You don't have any presets available.");
  }
  let text3 = presets.map(({ identifier, name }) => import_chalk.default.cyanBright(` \u2022 ${name} (${import_chalk.default.cyan(identifier)})`)).join("\n");
  if (presets.length < totalAvailablePresets) {
    text3 += import_chalk.default.gray(`
     ... (and ${totalAvailablePresets - presets.length} more)`);
  }
  return text3;
}
registerErrorDeserializer("generic.presetNotFound", ({ specifiedFuzzyPresetIdentifier, availablePresetsSample, totalAvailablePresets }) => {
  return makeTitledPrettyError(`Cannot find a preset with identifier "${import_chalk.default.yellowBright(specifiedFuzzyPresetIdentifier)}"`, text`
        Here are your available presets:

        ${formatAvailablePresets(availablePresetsSample, totalAvailablePresets)}

        Note: To specify a preset in the SDK, you need to use its identifier (in parentheses). You
        can get a preset's identifier by right-clicking on it and then select "Copy Preset
        Identifier".
      `);
});
function friendlyErrorDeserializer(serialized, _directCause, stack) {
  if (serialized.displayData === void 0) {
    return deserializeOtherError(serialized, stack);
  }
  let error;
  const specificDeserializer = errorDeserializersMap.get(serialized.displayData.code);
  if (specificDeserializer !== void 0) {
    error = specificDeserializer(serialized.displayData, stack);
    attachSerializedErrorData(error, serialized);
    return error;
  } else {
    return deserializeOtherError(serialized, stack);
  }
}
function cacheQuantizationTypeToCheckbox({ value, falseDefault }) {
  return value === void 0 ? void 0 : value === false ? { checked: false, value: falseDefault } : { checked: true, value };
}
var ActResult = class {
  constructor(rounds, totalExecutionTimeSeconds) {
    this.rounds = rounds;
    this.totalExecutionTimeSeconds = totalExecutionTimeSeconds;
  }
};
var callIdGiver = new IdGiver(Math.floor(Math.random() * (Number.MAX_SAFE_INTEGER / 2 / 1e4)) * 1e4);
var NoQueueQueue = class {
  needsQueueing() {
    return false;
  }
  async runInQueue(fn, signal) {
    if (signal?.aborted) {
      throw new Error("Operation aborted");
    }
    return fn();
  }
};
var FIFOQueue = class {
  constructor() {
    this.queue = [];
    this.executing = false;
    this.poisoned = false;
    this.poisonError = null;
  }
  needsQueueing() {
    return this.executing || this.queue.length > 0;
  }
  async runInQueue(fn, signal) {
    if (signal?.aborted) {
      throw new Error("Operation aborted");
    }
    if (this.poisoned) {
      throw this.poisonError ?? new Error("Queue has been poisoned by a previous error");
    }
    if (!this.needsQueueing()) {
      this.executing = true;
      try {
        if (signal?.aborted) {
          throw new Error("Operation aborted");
        }
        return await fn();
      } catch (error) {
        this.poisoned = true;
        this.poisonError = error;
        this.clearQueue(error);
        throw error;
      } finally {
        this.executing = false;
        this.processQueue();
      }
    }
    return new Promise((resolve, reject) => {
      if (signal) {
        if (signal.aborted) {
          return reject(new Error("Operation aborted"));
        }
        signal.addEventListener("abort", () => {
          const index = this.queue.findIndex((item) => item.resolve === resolve && item.reject === reject);
          if (index !== -1) {
            this.queue.splice(index, 1);
            reject(new Error("Operation aborted"));
          }
        }, { once: true });
      }
      this.queue.push({
        fn: async () => {
          try {
            if (signal?.aborted) {
              throw new Error("Operation aborted");
            }
            const result = await fn();
            resolve(result);
            return result;
          } catch (error) {
            reject(error);
            throw error;
          }
        },
        resolve,
        reject,
        signal
      });
    });
  }
  async processQueue() {
    if (this.executing || this.queue.length === 0 || this.poisoned) {
      return;
    }
    const nextItem = this.queue.shift();
    if (!nextItem)
      return;
    if (nextItem.signal?.aborted) {
      nextItem.reject(new Error("Operation aborted"));
      this.processQueue();
      return;
    }
    this.executing = true;
    try {
      await nextItem.fn();
    } catch (error) {
      this.poisoned = true;
      this.poisonError = error;
      this.clearQueue(error);
    } finally {
      this.executing = false;
      if (!this.poisoned) {
        this.processQueue();
      }
    }
  }
  clearQueue(error) {
    for (const item of this.queue) {
      item.reject(error);
    }
    this.queue = [];
  }
};
var GuardToolCallController = class {
  /**
   * Don't construct this object yourself.
   */
  constructor(toolCallRequest, tool, resultContainer) {
    this.toolCallRequest = toolCallRequest;
    this.tool = tool;
    this.resultContainer = resultContainer;
    this.allow = () => {
      this.assertNoResultYet("allow", getCurrentStack(1));
      this.resultContainer[0] = { type: "allow" };
    };
    this.allowAndOverrideParameters = (newParameters) => {
      this.assertNoResultYet("allowAndOverrideParameters", getCurrentStack(1));
      this.resultContainer[0] = { type: "allowAndOverrideParameters", parameters: newParameters };
    };
    this.deny = (reason) => {
      this.assertNoResultYet("deny", getCurrentStack(1));
      this.resultContainer[0] = { type: "deny", reason };
    };
  }
  assertNoResultYet(calledMethodName, stack) {
    if (this.resultContainer[0] === null) {
      return;
    }
    throw makeTitledPrettyError(`Cannot call ${calledMethodName} after a result has been set`, text`
        This tool call guard has already set a result previously (${this.resultContainer[0].type}). 
        You cannot set a result more than once.
      `, stack);
  }
};
var llmActBaseOptsSchema = external_exports.object({
  onFirstToken: external_exports.function().optional(),
  onPredictionFragment: external_exports.function().optional(),
  onMessage: external_exports.function().optional(),
  onRoundStart: external_exports.function().optional(),
  onRoundEnd: external_exports.function().optional(),
  onPredictionCompleted: external_exports.function().optional(),
  onPromptProcessingProgress: external_exports.function().optional(),
  onToolCallRequestStart: external_exports.function().optional(),
  onToolCallRequestNameReceived: external_exports.function().optional(),
  onToolCallRequestArgumentFragmentGenerated: external_exports.function().optional(),
  onToolCallRequestEnd: external_exports.function().optional(),
  onToolCallRequestFinalized: external_exports.function().optional(),
  onToolCallRequestFailure: external_exports.function().optional(),
  onToolCallRequestDequeued: external_exports.function().optional(),
  guardToolCall: external_exports.function().optional(),
  handleInvalidToolRequest: external_exports.function().optional(),
  maxPredictionRounds: external_exports.number().int().min(1).optional(),
  signal: external_exports.instanceof(AbortSignal).optional(),
  allowParallelToolExecution: external_exports.boolean().optional()
});
var defaultHandleInvalidToolRequest = (error, request) => {
  if (request) {
    return error.message;
  }
  throw error;
};
async function internalAct(chat, tools, baseOpts, stack, logger2, startTime, predictImpl, makePredictionResult) {
  const abortController = new AbortController();
  const mutableChat = Chat3.from(chat);
  let currentCallId = -1;
  let hasCalledUnimplementedTool = false;
  if (baseOpts.signal !== void 0) {
    if (baseOpts.signal.aborted) {
      abortController.abort(baseOpts.signal.reason);
    } else {
      baseOpts.signal.addEventListener("abort", () => {
        abortController.abort(baseOpts.signal?.reason);
      }, { once: true });
    }
  }
  let shouldContinue = false;
  let predictionsPerformed = 0;
  const toolsMap = /* @__PURE__ */ new Map();
  for (const tool of tools) {
    if (toolsMap.has(tool.name)) {
      logger2.warnText`
        Duplicate tool (${tool.name}) found in the tools array. The last tool with the same name
        will be used.
      `;
    }
    toolsMap.set(tool.name, tool);
  }
  do {
    let allowTools = true;
    if (
      // If there is a defined number of max predictions,
      baseOpts.maxPredictionRounds !== void 0 && // ... and this is the last chance to perform predictions, don't allow the model to use
      // tools.
      predictionsPerformed + 1 >= baseOpts.maxPredictionRounds
    ) {
      allowTools = false;
    }
    let finished2 = false;
    let firstTokenTriggered = false;
    const contentArray = [];
    const reasoningContentArray = [];
    const nonReasoningContentArray = [];
    const toolCallRequests = [];
    let nextToolCallIndex = 0;
    const toolCallResults = [];
    const toolCallPromises = [];
    const { promise: predictionPromise, resolve: predictionResolve, reject: predictionReject } = makePromise();
    const { promise: finalPromise, resolve: finalResolve, reject: finalReject } = makePromise();
    const internalHandleInvalidToolCallRequest = async (error, request, toolCallIndex) => {
      let result;
      try {
        result = await (baseOpts.handleInvalidToolRequest ?? defaultHandleInvalidToolRequest)(error, request);
      } catch (error2) {
        if (abortController.signal.aborted) {
          throw abortController.signal.reason;
        }
        abortController.abort();
        throw error2;
      }
      if (result === void 0) {
        return;
      }
      let resultString;
      try {
        resultString = JSON.stringify(result);
      } catch (error2) {
        abortController.abort();
        throw makePrettyError("handleInvalidToolRequest returned a value that cannot be converted to JSON.", stack);
      }
      if (request === void 0) {
        logger2.warnText`
          The "handleInvalidToolRequest" callback has returned a result, but the tool request has
          completely failed to parse, thus LM Studio cannot provide the result to the tool call.
          Please avoid returning a result when the second parameter of the callback is undefined.
          See the documentation for "handleInvalidToolRequest" for more information.
        `;
      } else {
        toolCallResults.push({
          index: toolCallIndex,
          data: {
            type: "toolCallResult",
            toolCallId: request.id,
            content: resultString
          }
        });
        nextToolCallIndex++;
      }
    };
    abortController.signal.throwIfAborted();
    safeCallCallback(logger2, "onRoundStart", baseOpts.onRoundStart, [predictionsPerformed]);
    let isGeneratingToolCall = false;
    const roundAbortController = new AbortController();
    const queue = baseOpts.allowParallelToolExecution ? new NoQueueQueue() : new FIFOQueue();
    let receivedEagerToolNameReporting = false;
    let receivedToolArgumentsStreaming = false;
    predictImpl({
      allowTools,
      history: accessMaybeMutableInternals(mutableChat)._internalGetData(),
      signal: roundAbortController.signal,
      handleFragment: (fragment) => {
        if (!firstTokenTriggered) {
          firstTokenTriggered = true;
          safeCallCallback(logger2, "onFirstToken", baseOpts.onFirstToken, [predictionsPerformed]);
        }
        safeCallCallback(logger2, "onFragment", baseOpts.onPredictionFragment, [
          { roundIndex: predictionsPerformed, ...fragment }
        ]);
        contentArray.push(fragment.content);
        if (!fragment.isStructural) {
          if (fragment.reasoningType === "reasoning") {
            reasoningContentArray.push(fragment.content);
          } else {
            nonReasoningContentArray.push(fragment.content);
          }
        }
      },
      handlePromptProcessingProgress: (progress) => {
        safeCallCallback(logger2, "onPromptProcessingProgress", baseOpts.onPromptProcessingProgress, [predictionsPerformed, progress]);
      },
      handleToolCallGenerationStart: (toolCallId) => {
        currentCallId = callIdGiver.next();
        receivedEagerToolNameReporting = false;
        receivedToolArgumentsStreaming = false;
        isGeneratingToolCall = true;
        safeCallCallback(logger2, "onToolCallRequestStart", baseOpts.onToolCallRequestStart, [
          predictionsPerformed,
          currentCallId,
          { toolCallId }
        ]);
      },
      handleToolCallGenerationNameReceived: (name) => {
        receivedEagerToolNameReporting = true;
        safeCallCallback(logger2, "onToolCallRequestNameReceived", baseOpts.onToolCallRequestNameReceived, [predictionsPerformed, currentCallId, name]);
      },
      handleToolCallGenerationArgumentFragmentGenerated: (content) => {
        receivedToolArgumentsStreaming = true;
        safeCallCallback(logger2, "onToolCallRequestArgumentFragmentGenerated", baseOpts.onToolCallRequestArgumentFragmentGenerated, [predictionsPerformed, currentCallId, content]);
      },
      handleToolCallGenerationEnd: (request, rawContent) => {
        const callId = currentCallId;
        isGeneratingToolCall = false;
        const toolCallIndex = nextToolCallIndex;
        nextToolCallIndex++;
        if (!receivedEagerToolNameReporting) {
          safeCallCallback(logger2, "onToolCallRequestNameReceived", baseOpts.onToolCallRequestNameReceived, [predictionsPerformed, callId, request.name]);
        }
        if (!receivedToolArgumentsStreaming) {
          safeCallCallback(logger2, "onToolCallRequestArgumentFragmentGenerated", baseOpts.onToolCallRequestArgumentFragmentGenerated, [predictionsPerformed, callId, JSON.stringify(request.arguments ?? {}, null, 2)]);
        }
        const pushedRequest = { ...request };
        toolCallRequests.push(pushedRequest);
        const tool = toolsMap.get(request.name);
        if (tool === void 0) {
          const toolCallRequestError = new ToolCallRequestError(`Cannot find tool with name ${request.name}.`, rawContent);
          toolCallPromises.push(internalHandleInvalidToolCallRequest(toolCallRequestError, request, toolCallIndex).catch(finalReject));
          safeCallCallback(logger2, "onToolCallRequestFailure", baseOpts.onToolCallRequestFailure, [
            predictionsPerformed,
            callId,
            toolCallRequestError
          ]);
          return;
        }
        try {
          tool.checkParameters(pushedRequest.arguments);
        } catch (error) {
          const toolCallRequestError = new ToolCallRequestError(error.message, rawContent);
          toolCallPromises.push(internalHandleInvalidToolCallRequest(toolCallRequestError, request, toolCallIndex).catch(finalReject));
          safeCallCallback(logger2, "onToolCallRequestFailure", baseOpts.onToolCallRequestFailure, [
            predictionsPerformed,
            callId,
            toolCallRequestError
          ]);
          return;
        }
        const toolCallContext = new SimpleToolCallContext(new SimpleLogger(`Tool(${request.name})`, logger2), abortController.signal, callId);
        const isQueued = queue.needsQueueing();
        safeCallCallback(logger2, "onToolCallRequestEnd", baseOpts.onToolCallRequestEnd, [
          predictionsPerformed,
          callId,
          {
            isQueued,
            toolCallRequest: request,
            rawContent
          }
        ]);
        toolCallPromises.push(queue.runInQueue(async () => {
          if (isQueued) {
            safeCallCallback(logger2, "onToolCallRequestDequeued", baseOpts.onToolCallRequestDequeued, [predictionsPerformed, callId]);
          }
          if (baseOpts.guardToolCall !== void 0) {
            const resultContainer = [null];
            await baseOpts.guardToolCall(predictionsPerformed, callId, new GuardToolCallController(request, tool, resultContainer));
            if (resultContainer[0] === null) {
              throw makeTitledPrettyError("Tool call guard did not allow or deny the tool call.", text`
                      The \`guardToolCall\` handler must call one of the methods on the controller
                      to allow or deny the tool call.
                    `, stack);
            }
            const guardResult = resultContainer[0];
            const guardResultType = guardResult.type;
            switch (guardResultType) {
              case "allow": {
                break;
              }
              case "allowAndOverrideParameters": {
                pushedRequest.arguments = guardResult.parameters;
                break;
              }
              case "deny": {
                toolCallResults.push({
                  index: toolCallIndex,
                  data: {
                    type: "toolCallResult",
                    toolCallId: request.id,
                    content: JSON.stringify({
                      error: guardResult.reason
                    })
                  }
                });
                return;
              }
            }
          }
          safeCallCallback(logger2, "onToolCallRequestFinalized", baseOpts.onToolCallRequestFinalized, [
            predictionsPerformed,
            callId,
            {
              toolCallRequest: request,
              rawContent
            }
          ]);
          let result;
          try {
            result = await tool.implementation(pushedRequest.arguments ?? {}, toolCallContext);
          } catch (error) {
            if (!(error instanceof UnimplementedToolError)) {
              throw error;
            }
            hasCalledUnimplementedTool = true;
          }
          let resultString;
          if (result === void 0) {
            resultString = "undefined";
          } else {
            try {
              resultString = JSON.stringify(result);
            } catch (error) {
              throw makePrettyError(`Return value of tool ${tool.name} cannot be converted to JSON.`, stack);
            }
          }
          toolCallResults.push({
            index: toolCallIndex,
            data: {
              type: "toolCallResult",
              toolCallId: request.id,
              content: resultString
            }
          });
        }, abortController.signal).catch(finalReject));
      },
      handleToolCallGenerationFailed: (error, rawContent) => {
        isGeneratingToolCall = false;
        const toolCallRequestError = new ToolCallRequestError(error.message, rawContent);
        toolCallPromises.push(internalHandleInvalidToolCallRequest(
          toolCallRequestError,
          // We don't have a request in this because the model has failed miserably.
          void 0,
          // Tool call index. Doesn't matter because if there is no request, there cannot be
          // a replacement.
          0
        ).catch(finalReject));
        safeCallCallback(logger2, "onToolCallRequestFailure", baseOpts.onToolCallRequestFailure, [
          predictionsPerformed,
          currentCallId,
          toolCallRequestError
        ]);
      },
      handlePredictionEnd: (endPacket) => {
        const predictionResult = makePredictionResult({
          endPacket,
          content: contentArray.join(""),
          reasoningContent: reasoningContentArray.join(""),
          nonReasoningContent: nonReasoningContentArray.join(""),
          predictionsPerformed
        });
        safeCallCallback(logger2, "onPredictionCompleted", baseOpts.onPredictionCompleted, [
          predictionResult
        ]);
        predictionResolve();
      },
      handleError: (error) => {
        if (isGeneratingToolCall) {
          const toolCallRequestError = new ToolCallRequestError(`Generation failed: ${error.message}`, void 0);
          isGeneratingToolCall = false;
          safeCallCallback(logger2, "onToolCallRequestFailure", baseOpts.onToolCallRequestFailure, [
            predictionsPerformed,
            currentCallId,
            toolCallRequestError
          ]);
        }
        finished2 = true;
        predictionReject(error);
      }
    });
    const abortListener = () => {
      if (finished2) {
        return;
      }
      finished2 = true;
      roundAbortController.abort(abortController.signal.reason);
    };
    abortController.signal.addEventListener("abort", abortListener);
    predictionPromise.then(() => {
      const assistantMessage = ChatMessage.from({
        role: "assistant",
        content: [
          {
            type: "text",
            text: contentArray.join("")
          },
          ...toolCallRequests.map((toolCallRequest) => ({
            type: "toolCallRequest",
            toolCallRequest
          }))
        ]
      });
      mutableChat.append(assistantMessage.asMutableCopy());
      safeCallCallback(logger2, "onMessage", baseOpts.onMessage, [assistantMessage]);
    }).then(() => Promise.all(toolCallPromises)).then(() => finalResolve(), finalReject);
    await finalPromise;
    shouldContinue = false;
    if (toolCallResults.length > 0) {
      toolCallResults.sort((a3, b4) => a3.index - b4.index);
      const toolMessage = ChatMessage.from({
        role: "tool",
        content: toolCallResults.map((r8) => r8.data)
      });
      mutableChat.append(toolMessage.asMutableCopy());
      safeCallCallback(logger2, "onMessage", baseOpts.onMessage, [toolMessage]);
      shouldContinue = true;
    }
    safeCallCallback(logger2, "onRoundEnd", baseOpts.onRoundEnd, [predictionsPerformed]);
    predictionsPerformed++;
    if (baseOpts.maxPredictionRounds !== void 0 && predictionsPerformed >= baseOpts.maxPredictionRounds) {
      shouldContinue = false;
    }
    shouldContinue &&= !hasCalledUnimplementedTool;
  } while (shouldContinue);
  return new ActResult(predictionsPerformed, (performance.now() - startTime) / 1e3);
}
var PredictionResult = class {
  constructor(content, reasoningContent, nonReasoningContent, stats, modelInfo, roundIndex, loadConfig, predictionConfig) {
    this.content = content;
    this.reasoningContent = reasoningContent;
    this.nonReasoningContent = nonReasoningContent;
    this.stats = stats;
    this.modelInfo = modelInfo;
    this.roundIndex = roundIndex;
    this.loadConfig = loadConfig;
    this.predictionConfig = predictionConfig;
  }
};
var StructuredPredictionResult = class extends PredictionResult {
  constructor(content, reasoningContent, nonReasoningContent, stats, modelInfo, roundIndex, loadConfig, predictionConfig, parsed) {
    super(content, reasoningContent, nonReasoningContent, stats, modelInfo, roundIndex, loadConfig, predictionConfig);
    this.parsed = parsed;
  }
};
var OngoingPrediction = class _OngoingPrediction extends StreamablePromise {
  async collect(fragments) {
    const content = fragments.map(({ content: content2 }) => content2).join("");
    const reasoningContent = fragments.filter(({ isStructural }) => !isStructural).filter(({ reasoningType }) => reasoningType === "reasoning").map(({ content: content2 }) => content2).join("");
    const nonReasoningContent = fragments.filter(({ isStructural }) => !isStructural).filter(({ reasoningType }) => reasoningType === "none").map(({ content: content2 }) => content2).join("");
    if (this.stats === null) {
      throw new Error("Stats should not be null");
    }
    if (this.modelInfo === null) {
      throw new Error("Model info should not be null");
    }
    if (this.loadModelConfig === null) {
      throw new Error("Load model config should not be null");
    }
    if (this.predictionConfig === null) {
      throw new Error("Prediction config should not be null");
    }
    if (this.parser === null) {
      return new PredictionResult(
        content,
        reasoningContent,
        nonReasoningContent,
        this.stats,
        this.modelInfo,
        // Currently, OngoingPrediction is only used with single round predictions. Thus always
        // use roundIndex 0.
        /* roundIndex */
        0,
        this.loadModelConfig,
        this.predictionConfig
      );
    } else {
      return new StructuredPredictionResult(
        content,
        reasoningContent,
        nonReasoningContent,
        this.stats,
        this.modelInfo,
        // Currently, OngoingPrediction is only used with single round predictions. Thus always
        // use roundIndex 0.
        /* predictionIndex */
        0,
        this.loadModelConfig,
        this.predictionConfig,
        this.parser(content)
      );
    }
  }
  constructor(onCancel, parser) {
    super();
    this.onCancel = onCancel;
    this.parser = parser;
    this.stats = null;
    this.modelInfo = null;
    this.loadModelConfig = null;
    this.predictionConfig = null;
  }
  /** @internal */
  static create(onCancel, parser) {
    const ongoingPrediction = new _OngoingPrediction(onCancel, parser);
    const finished2 = (stats, modelInfo, loadModelConfig, predictionConfig) => {
      ongoingPrediction.stats = stats;
      ongoingPrediction.modelInfo = modelInfo;
      ongoingPrediction.loadModelConfig = loadModelConfig;
      ongoingPrediction.predictionConfig = predictionConfig;
      ongoingPrediction.finished();
    };
    const failed = (error) => ongoingPrediction.finished(error);
    const push = (fragment) => ongoingPrediction.push(fragment);
    return { ongoingPrediction, finished: finished2, failed, push };
  }
  /**
   * Get the final prediction results. If you have been streaming the results, awaiting on this
   * method will take no extra effort, as the results are already available in the internal buffer.
   *
   * Example:
   *
   * ```typescript
   * const prediction = model.complete("When will The Winds of Winter be released?");
   * for await (const { content } of prediction) {
   *   process.stdout.write(content);
   * }
   * const result = await prediction.result();
   * console.log(result.stats);
   * ```
   *
   * Technically, awaiting on this method is the same as awaiting on the instance itself:
   *
   * ```typescript
   * await prediction.result();
   *
   * // Is the same as:
   *
   * await prediction;
   * ```
   */
  async result() {
    return await this;
  }
  /**
   * Cancels the prediction. This will stop the prediction with stop reason `userStopped`. See
   * {@link LLMPredictionStopReason} for other reasons that a prediction might stop.
   */
  async cancel() {
    this.onCancel();
  }
};
var llmPredictionOptsSchema = llmPredictionConfigInputSchema.extend({
  onPromptProcessingProgress: external_exports.function().optional(),
  onFirstToken: external_exports.function().optional(),
  onPredictionFragment: external_exports.function().optional(),
  onToolCallRequestStart: external_exports.function().optional(),
  onToolCallRequestNameReceived: external_exports.function().optional(),
  onToolCallRequestArgumentFragmentGenerated: external_exports.function().optional(),
  onToolCallRequestEnd: external_exports.function().optional(),
  onToolCallRequestFailure: external_exports.function().optional(),
  signal: external_exports.instanceof(AbortSignal).optional(),
  preset: external_exports.string().optional()
});
function splitPredictionOpts(opts) {
  const { onPromptProcessingProgress, onFirstToken, onPredictionFragment, onToolCallRequestStart, onToolCallRequestNameReceived, onToolCallRequestArgumentFragmentGenerated, onToolCallRequestEnd, onToolCallRequestFailure, signal, preset, ...config } = opts;
  return [
    config,
    {
      onPromptProcessingProgress,
      onFirstToken,
      onPredictionFragment,
      onToolCallRequestStart,
      onToolCallRequestNameReceived,
      onToolCallRequestArgumentFragmentGenerated,
      onToolCallRequestEnd,
      onToolCallRequestFailure,
      signal,
      preset
    }
  ];
}
var llmRespondOptsSchema = llmPredictionOptsSchema.extend({
  onMessage: external_exports.function().optional(),
  onToolCallRequestStart: external_exports.function().optional(),
  onToolCallRequestNameReceived: external_exports.function().optional(),
  onToolCallRequestArgumentFragmentGenerated: external_exports.function().optional(),
  onToolCallRequestEnd: external_exports.function().optional(),
  onToolCallRequestFailure: external_exports.function().optional()
});
function splitRespondOpts(opts) {
  const { onMessage, ...remaining } = opts;
  const [config, llmPredictionOpts] = splitPredictionOpts(remaining);
  return [
    config,
    llmPredictionOpts,
    {
      onMessage
    }
  ];
}
var llmActionOptsSchema = llmPredictionConfigInputSchema.extend(llmActBaseOptsSchema.shape).extend({
  preset: external_exports.string().optional()
});
function splitActOpts(opts) {
  const { onFirstToken, onPredictionFragment, onMessage, onRoundStart, onRoundEnd, onPredictionCompleted, onPromptProcessingProgress, onToolCallRequestStart, onToolCallRequestNameReceived, onToolCallRequestArgumentFragmentGenerated, onToolCallRequestEnd, onToolCallRequestFinalized, onToolCallRequestFailure, onToolCallRequestDequeued, guardToolCall, handleInvalidToolRequest, maxPredictionRounds, signal, preset, allowParallelToolExecution, ...config } = opts;
  return [
    config,
    {
      onFirstToken,
      onPredictionFragment,
      onMessage,
      onRoundStart,
      onRoundEnd,
      onPredictionCompleted,
      onPromptProcessingProgress,
      onToolCallRequestStart,
      onToolCallRequestNameReceived,
      onToolCallRequestArgumentFragmentGenerated,
      onToolCallRequestEnd,
      onToolCallRequestFinalized,
      onToolCallRequestFailure,
      onToolCallRequestDequeued,
      guardToolCall,
      handleInvalidToolRequest,
      maxPredictionRounds,
      signal,
      preset,
      allowParallelToolExecution
    }
  ];
}
var noFormattingTemplate = text`
  {% for message in messages %}{{ message['content'] }}{% endfor %}
`;
var LLMDynamicHandle = class extends DynamicHandle {
  /**
   * Don't construct this on your own. Use {@link LLMNamespace#model} or
   * {@link LLMNamespace#createDynamicHandle} instead.
   *
   * @internal
   */
  constructor(port, specifier, validator2, logger2 = new SimpleLogger(`LLMModel`)) {
    super(port, specifier);
    this.validator = validator2;
    this.logger = logger2;
    this.internalKVConfigStack = { layers: [] };
    this.internalIgnoreServerSessionConfig = void 0;
  }
  /** @internal */
  internalPredict(history, predictionConfigStack, cancelEvent, extraOpts, onFragment, onFinished, onError) {
    let finished2 = false;
    let firstTokenTriggered = false;
    let currentCallId = null;
    let receivedEagerToolNameReporting = false;
    let receivedToolArgumentsStreaming = false;
    const channel = this.port.createChannel("predict", {
      modelSpecifier: this.specifier,
      history,
      predictionConfigStack,
      fuzzyPresetIdentifier: extraOpts.preset,
      ignoreServerSessionConfig: this.internalIgnoreServerSessionConfig
    }, (message) => {
      switch (message.type) {
        case "fragment": {
          if (!firstTokenTriggered) {
            firstTokenTriggered = true;
            safeCallCallback(this.logger, "onFirstToken", extraOpts.onFirstToken, []);
          }
          safeCallCallback(this.logger, "onFragment", extraOpts.onPredictionFragment, [
            message.fragment
          ]);
          onFragment(message.fragment);
          break;
        }
        case "promptProcessingProgress": {
          safeCallCallback(this.logger, "onPromptProcessingProgress", extraOpts.onPromptProcessingProgress, [message.progress]);
          break;
        }
        case "toolCallGenerationStart": {
          if (currentCallId === null) {
            currentCallId = 0;
          } else {
            currentCallId++;
          }
          receivedEagerToolNameReporting = false;
          receivedToolArgumentsStreaming = false;
          safeCallCallback(this.logger, "onToolCallGenerationStart", extraOpts.onToolCallRequestStart, [currentCallId, { toolCallId: message.toolCallId }]);
          break;
        }
        case "toolCallGenerationNameReceived": {
          receivedEagerToolNameReporting = true;
          safeCallCallback(this.logger, "onToolCallGenerationNameReceived", extraOpts.onToolCallRequestNameReceived, [currentCallId ?? -1, message.name]);
          break;
        }
        case "toolCallGenerationArgumentFragmentGenerated": {
          receivedToolArgumentsStreaming = true;
          safeCallCallback(this.logger, "onToolCallGenerationArgumentFragmentGenerated", extraOpts.onToolCallRequestArgumentFragmentGenerated, [currentCallId ?? -1, message.content]);
          break;
        }
        case "toolCallGenerationEnd": {
          if (!receivedEagerToolNameReporting) {
            safeCallCallback(this.logger, "onToolCallGenerationNameReceived", extraOpts.onToolCallRequestNameReceived, [currentCallId ?? -1, message.toolCallRequest.name]);
          }
          if (!receivedToolArgumentsStreaming) {
            safeCallCallback(this.logger, "onToolCallGenerationArgumentFragmentGenerated", extraOpts.onToolCallRequestArgumentFragmentGenerated, [
              currentCallId ?? -1,
              JSON.stringify(message.toolCallRequest.arguments ?? {}, null, 2)
            ]);
          }
          safeCallCallback(this.logger, "onToolCallGenerationEnd", extraOpts.onToolCallRequestEnd, [
            currentCallId ?? -1,
            { toolCallRequest: message.toolCallRequest, rawContent: message.rawContent }
          ]);
          break;
        }
        case "toolCallGenerationFailed": {
          const toolCallRequestError = new ToolCallRequestError(fromSerializedError(message.error).message, message.rawContent);
          safeCallCallback(this.logger, "onToolCallGenerationFailed", extraOpts.onToolCallRequestFailure, [currentCallId ?? -1, toolCallRequestError]);
          break;
        }
        case "success": {
          finished2 = true;
          onFinished(message.stats, message.modelInfo, message.loadModelConfig, message.predictionConfig);
          break;
        }
      }
    }, { stack: getCurrentStack(2) });
    cancelEvent.subscribeOnce(() => {
      if (finished2) {
        return;
      }
      channel.send({ type: "cancel" });
    });
    channel.onError.subscribeOnce(onError);
  }
  predictionConfigInputToKVConfig(config) {
    let structuredField = void 0;
    if (typeof config.structured?.parse === "function") {
      structuredField = {
        type: "json",
        jsonSchema: zodToJsonSchema(config.structured)
      };
    } else {
      structuredField = config.structured;
    }
    const convertedConfig = {
      ...config,
      structured: structuredField
    };
    return llmPredictionConfigToKVConfig(convertedConfig);
  }
  createZodParser(zodSchema) {
    return (content) => {
      try {
        return zodSchema.parse(JSON.parse(content));
      } catch (e9) {
        throw new Error("Failed to parse structured output: " + JSON.stringify(content), {
          cause: e9
        });
      }
    };
  }
  /**
   * Use the loaded model to predict text.
   *
   * This method returns an {@link OngoingPrediction} object. An ongoing prediction can be used as a
   * promise (if you only care about the final result) or as an async iterable (if you want to
   * stream the results as they are being generated).
   *
   * Example usage as a promise (Resolves to a {@link PredictionResult}):
   *
   * ```typescript
   * const result = await model.complete("When will The Winds of Winter be released?");
   * console.log(result.content);
   * ```
   *
   * Or
   *
   * ```typescript
   * model.complete("When will The Winds of Winter be released?")
   *  .then(result =\> console.log(result.content))
   *  .catch(error =\> console.error(error));
   * ```
   *
   * Example usage as an async iterable (streaming):
   *
   * ```typescript
   * for await (const { content } of model.complete("When will The Winds of Winter be released?")) {
   *   process.stdout.write(content);
   * }
   * ```
   *
   * If you wish to stream the result, but also getting the final prediction results (for example,
   * you wish to get the prediction stats), you can use the following pattern:
   *
   * ```typescript
   * const prediction = model.complete("When will The Winds of Winter be released?");
   * for await (const { content } of prediction) {
   *   process.stdout.write(content);
   * }
   * const result = await prediction.result();
   * console.log(result.stats);
   * ```
   *
   * @param prompt - The prompt to use for prediction.
   * @param opts - Options for the prediction.
   */
  complete(prompt, opts = {}) {
    const stack = getCurrentStack(1);
    [prompt, opts] = this.validator.validateMethodParamsOrThrow("model", "complete", ["prompt", "opts"], [external_exports.string(), llmPredictionOptsSchema], [prompt, opts], stack);
    const [config, extraOpts] = splitPredictionOpts(opts);
    const [cancelEvent, emitCancelEvent] = BufferedEvent.create();
    if (extraOpts.signal !== void 0) {
      if (extraOpts.signal.aborted) {
        emitCancelEvent();
      } else {
        extraOpts.signal.addEventListener("abort", () => {
          emitCancelEvent();
        }, { once: true });
      }
    }
    const zodSchemaParseResult = zodSchemaSchema.safeParse(config.structured);
    const { ongoingPrediction, finished: finished2, failed, push } = OngoingPrediction.create(emitCancelEvent, !zodSchemaParseResult.success ? null : this.createZodParser(zodSchemaParseResult.data));
    this.internalPredict(this.resolveCompletionContext(prompt), {
      layers: [
        ...this.internalKVConfigStack.layers,
        {
          layerName: "apiOverride",
          config: this.predictionConfigInputToKVConfig({
            // If the user did not specify `stopStrings`, we default to an empty array. This is to
            // prevent the model from using the value set in the preset.
            stopStrings: [],
            ...config
          })
        },
        {
          layerName: "completeModeFormatting",
          config: llmSharedPredictionConfigSchematics.buildPartialConfig({
            promptTemplate: {
              type: "jinja",
              jinjaPromptTemplate: {
                template: noFormattingTemplate
              },
              stopStrings: []
            }
          })
        }
      ]
    }, cancelEvent, extraOpts, (fragment) => push(fragment), (stats, modelInfo, loadModelConfig, predictionConfig) => finished2(stats, modelInfo, loadModelConfig, predictionConfig), (error) => failed(error));
    return ongoingPrediction;
  }
  resolveCompletionContext(contextInput) {
    return {
      messages: [
        {
          role: "user",
          content: [{ type: "text", text: contextInput }]
        }
      ]
    };
  }
  /**
   * Use the loaded model to generate a response based on the given history.
   *
   * This method returns an {@link OngoingPrediction} object. An ongoing prediction can be used as a
   * promise (if you only care about the final result) or as an async iterable (if you want to
   * stream the results as they are being generated).
   *
   * Example usage as a promise (Resolves to a {@link PredictionResult}):
   *
   * ```typescript
   * const history = [{ role: 'user', content: "When will The Winds of Winter be released?" }];
   * const result = await model.respond(history);
   * console.log(result.content);
   * ```
   *
   * Or
   *
   * ```typescript
   * const history = [{ role: 'user', content: "When will The Winds of Winter be released?" }];
   * model.respond(history)
   *  .then(result => console.log(result.content))
   *  .catch(error => console.error(error));
   * ```
   *
   * Example usage as an async iterable (streaming):
   *
   * ```typescript
   * const history = [{ role: 'user', content: "When will The Winds of Winter be released?" }];
   * for await (const { content } of model.respond(history)) {
   *   process.stdout.write(content);
   * }
   * ```
   *
   * If you wish to stream the result, but also getting the final prediction results (for example,
   * you wish to get the prediction stats), you can use the following pattern:
   *
   * ```typescript
   * const history = [{ role: 'user', content: "When will The Winds of Winter be released?" }];
   * const prediction = model.respond(history);
   * for await (const { content } of prediction) {
   *   process.stdout.write(content);
   * }
   * const result = await prediction;
   * console.log(result.stats);
   * ```
   *
   * @param chat - The LLMChatHistory array to use for generating a response.
   * @param opts - Options for the prediction.
   */
  respond(chat, opts = {}) {
    const stack = getCurrentStack(1);
    [chat, opts] = this.validator.validateMethodParamsOrThrow("model", "respond", ["chat", "opts"], [chatHistoryLikeSchema, llmRespondOptsSchema], [chat, opts], stack);
    const [cancelEvent, emitCancelEvent] = BufferedEvent.create();
    const [config, predictionOpts, respondOpts] = splitRespondOpts(opts);
    if (predictionOpts.signal !== void 0) {
      if (predictionOpts.signal.aborted) {
        emitCancelEvent();
      } else {
        predictionOpts.signal.addEventListener("abort", () => {
          emitCancelEvent();
        }, { once: true });
      }
    }
    const zodSchemaParseResult = zodSchemaSchema.safeParse(config.structured);
    const { ongoingPrediction, finished: finished2, failed, push } = OngoingPrediction.create(emitCancelEvent, !zodSchemaParseResult.success ? null : this.createZodParser(zodSchemaParseResult.data));
    this.internalPredict(accessMaybeMutableInternals(Chat3.from(chat))._internalGetData(), addKVConfigToStack(this.internalKVConfigStack, "apiOverride", this.predictionConfigInputToKVConfig(config)), cancelEvent, predictionOpts, (fragment) => push(fragment), (stats, modelInfo, loadModelConfig, predictionConfig) => finished2(stats, modelInfo, loadModelConfig, predictionConfig), (error) => failed(error));
    ongoingPrediction.then((result) => {
      safeCallCallback(this.logger, "onMessage", respondOpts.onMessage, [
        ChatMessage.create("assistant", result.content)
      ]);
    }, () => {
    });
    return ongoingPrediction;
  }
  /**
   * @param chat - The LLMChatHistory array to act from as the base
   * @param tool - An array of tools that the model can use during the operation. You can create
   * tools by using the `tool` function.
   * @param opts - Additional options
   *
   * Example:
   *
   * ```
   * import { LMStudioClient, tool } from "@lmstudio/sdk";
   * import { z } from "zod";
   *
   * const client = new LMStudioClient();
   * const model = await client.llm.model();
   *
   * const additionTool = tool({
   *   name: "add",
   *   description: "Add two numbers",
   *   parameters: {
   *     a: z.number(),
   *     b: z.number(),
   *   },
   *   implementation: ({ a, b }) => a + b,
   * });
   *
   * await model.act("What is 1234 + 4321?", [additionTool], {
   *   onMessage: message => console.log(message.toString()),
   * });
   * ```
   */
  async act(chat, tools, opts = {}) {
    const startTime = performance.now();
    const stack = getCurrentStack(1);
    [chat, opts] = this.validator.validateMethodParamsOrThrow("model", "act", ["chat", "opts"], [chatHistoryLikeSchema, llmActionOptsSchema], [chat, opts], stack);
    const [config, { preset, ...baseOpts }] = splitActOpts(opts);
    if (config.structured !== void 0 && config.structured.type !== "none" && tools.length > 0) {
      throw makePrettyError("Structured output is currently not supported in .act() when there are tools.", stack);
    }
    if (config.structured !== void 0 && config.structured.parse !== void 0) {
      throw makePrettyError("zod schema is not supported in .act().", stack);
    }
    if (config.rawTools !== void 0) {
      throw makePrettyError("`rawTools` is not supported in act. Use `tools` instead", stack);
    }
    let rawTools;
    if (tools.length === 0) {
      rawTools = { type: "none" };
    } else {
      rawTools = {
        type: "toolArray",
        tools: tools.map(toolToLLMTool)
      };
    }
    const configWithTools = addKVConfigToStack(this.internalKVConfigStack, "apiOverride", this.predictionConfigInputToKVConfig({
      ...config,
      rawTools
    }));
    const configWithoutTools = addKVConfigToStack(this.internalKVConfigStack, "apiOverride", this.predictionConfigInputToKVConfig({
      ...config,
      rawTools: { type: "none" }
    }));
    return await internalAct(
      chat,
      tools,
      baseOpts,
      stack,
      this.logger,
      startTime,
      // Implementation of the prediction function. This performs the prediction by creating a
      // predict channel and redirect the messages to the appropriate handlers.
      async ({ allowTools, history, signal, handleFragment, handlePromptProcessingProgress, handleToolCallGenerationStart, handleToolCallGenerationNameReceived, handleToolCallGenerationArgumentFragmentGenerated, handleToolCallGenerationEnd, handleToolCallGenerationFailed, handlePredictionEnd, handleError }) => {
        const channel = this.port.createChannel("predict", {
          modelSpecifier: this.specifier,
          history,
          predictionConfigStack: allowTools ? configWithTools : configWithoutTools,
          fuzzyPresetIdentifier: preset,
          ignoreServerSessionConfig: this.internalIgnoreServerSessionConfig
        }, (message) => {
          const messageType = message.type;
          switch (messageType) {
            case "fragment": {
              handleFragment(message.fragment);
              break;
            }
            case "promptProcessingProgress": {
              handlePromptProcessingProgress(message.progress);
              break;
            }
            case "toolCallGenerationStart": {
              handleToolCallGenerationStart(message.toolCallId);
              break;
            }
            case "toolCallGenerationNameReceived": {
              handleToolCallGenerationNameReceived(message.name);
              break;
            }
            case "toolCallGenerationArgumentFragmentGenerated": {
              handleToolCallGenerationArgumentFragmentGenerated(message.content);
              break;
            }
            case "toolCallGenerationEnd": {
              handleToolCallGenerationEnd(message.toolCallRequest, message.rawContent);
              break;
            }
            case "toolCallGenerationFailed": {
              handleToolCallGenerationFailed(fromSerializedError(message.error), message.rawContent);
              break;
            }
            case "success": {
              handlePredictionEnd({
                stats: message.stats,
                modelInfo: message.modelInfo,
                loadModelConfig: message.loadModelConfig,
                predictionConfig: message.predictionConfig
              });
              break;
            }
          }
        }, { stack });
        if (signal.aborted) {
          channel.send({ type: "cancel" });
        } else {
          signal.addEventListener("abort", () => {
            channel.send({ type: "cancel" });
          }, { once: true });
        }
        channel.onError.subscribeOnce(handleError);
      },
      ({ endPacket, content, nonReasoningContent, reasoningContent, predictionsPerformed }) => {
        return new PredictionResult(content, reasoningContent, nonReasoningContent, endPacket.stats, endPacket.modelInfo, predictionsPerformed, endPacket.loadModelConfig, endPacket.predictionConfig);
      }
    );
  }
  async getContextLength() {
    const stack = getCurrentStack(1);
    const loadConfig = await this.getLoadConfig(stack);
    return llmSharedLoadConfigSchematics.access(loadConfig, "contextLength");
  }
  async applyPromptTemplate(history, opts = {}) {
    const stack = getCurrentStack(1);
    [history, opts] = this.validator.validateMethodParamsOrThrow("model", "applyPromptTemplate", ["history", "opts"], [chatHistoryLikeSchema, llmApplyPromptTemplateOptsSchema], [history, opts], stack);
    return (await this.port.callRpc("applyPromptTemplate", {
      specifier: this.specifier,
      history: accessMaybeMutableInternals(Chat3.from(history))._internalGetData(),
      predictionConfigStack: this.internalKVConfigStack,
      opts
    }, {
      stack
    })).formatted;
  }
  async tokenize(inputString) {
    const stack = getCurrentStack(1);
    inputString = this.validator.validateMethodParamOrThrow("model", "tokenize", "inputString", external_exports.string().or(external_exports.array(external_exports.string())), inputString, stack);
    if (Array.isArray(inputString)) {
      return (await Promise.all(inputString.map((s6) => this.port.callRpc("tokenize", { specifier: this.specifier, inputString: s6 }, { stack })))).map((r8) => r8.tokens);
    } else {
      return (await this.port.callRpc("tokenize", {
        specifier: this.specifier,
        inputString
      }, { stack })).tokens;
    }
  }
  async countTokens(inputString) {
    const stack = getCurrentStack(1);
    inputString = this.validator.validateMethodParamOrThrow("model", "countTokens", "inputString", external_exports.string(), inputString, stack);
    return (await this.port.callRpc("countTokens", {
      specifier: this.specifier,
      inputString
    }, { stack })).tokenCount;
  }
  /**
   * Starts to eagerly preload a draft model. This is useful when you want a draft model to be ready
   * for speculative decoding.
   *
   * Preloading is done on a best-effort basis and may not always succeed. It is not guaranteed that
   * the draft model is actually loaded when this method returns. Thus, this method should only be
   * used as an optimization. The actual draft model used only depends on the parameter set when
   * performing the prediction.
   */
  async unstable_preloadDraftModel(draftModelKey) {
    const stack = getCurrentStack(1);
    draftModelKey = this.validator.validateMethodParamOrThrow("model", "unstable_preloadDraftModel", "draftModelKey", external_exports.string(), draftModelKey, stack);
    await this.port.callRpc("preloadDraftModel", { specifier: this.specifier, draftModelKey }, { stack });
  }
};
var LLM = class extends LLMDynamicHandle {
  /** @internal */
  constructor(llmPort, info2, validator2, logger2 = new SimpleLogger(`LLM`)) {
    const specifier = {
      type: "instanceReference",
      instanceReference: info2.instanceReference
    };
    super(llmPort, specifier, validator2, logger2);
    this.identifier = info2.identifier;
    this.path = info2.path;
    this.modelKey = info2.modelKey;
    this.format = info2.format;
    this.displayName = info2.displayName;
    this.sizeBytes = info2.sizeBytes;
    this.vision = info2.vision;
    this.trainedForToolUse = info2.trainedForToolUse;
  }
  async unload() {
    const stack = getCurrentStack(1);
    await this.port.callRpc("unloadModel", { identifier: this.identifier }, { stack });
  }
  async getModelInfo() {
    const info2 = await super.getModelInfo();
    if (info2 === void 0) {
      const stack = getCurrentStack(1);
      throw makePrettyError("This model has already been unloaded", stack);
    }
    return info2;
  }
};
var LLMNamespace = class extends ModelNamespace {
  constructor() {
    super(...arguments);
    this.namespace = "llm";
    this.defaultLoadConfig = {};
    this.loadModelConfigSchema = llmLoadModelConfigSchema;
  }
  /** @internal */
  loadConfigToKVConfig(config) {
    return llmLlamaMoeLoadConfigSchematics.buildPartialConfig({
      "contextLength": config.contextLength,
      "llama.evalBatchSize": config.evalBatchSize,
      "llama.acceleration.offloadRatio": config.gpu?.ratio,
      "numCpuExpertLayersRatio": config.gpu?.numCpuExpertLayersRatio,
      "load.gpuSplitConfig": convertGPUSettingToGPUSplitConfig(config.gpu),
      "llama.flashAttention": config.flashAttention,
      "llama.ropeFrequencyBase": numberToCheckboxNumeric(config.ropeFrequencyBase, 0, 0),
      "llama.ropeFrequencyScale": numberToCheckboxNumeric(config.ropeFrequencyScale, 0, 0),
      "llama.keepModelInMemory": config.keepModelInMemory,
      "seed": numberToCheckboxNumeric(config.seed, -1, 0),
      "llama.useFp16ForKVCache": config.useFp16ForKVCache,
      "llama.tryMmap": config.tryMmap,
      "numExperts": config.numExperts,
      "llama.kCacheQuantizationType": cacheQuantizationTypeToCheckbox({
        value: config.llamaKCacheQuantizationType,
        falseDefault: "f16"
      }),
      "llama.vCacheQuantizationType": cacheQuantizationTypeToCheckbox({
        value: config.llamaVCacheQuantizationType,
        falseDefault: "f16"
      })
    });
  }
  /** @internal */
  createDomainSpecificModel(port, info2, validator2, logger2) {
    return new LLM(port, info2, validator2, logger2);
  }
  /** @internal */
  createDomainDynamicHandle(port, specifier, validator2, logger2) {
    return new LLMDynamicHandle(port, specifier, validator2, logger2);
  }
};
var GeneratorPredictionResult = class {
  constructor(content, reasoningContent, nonReasoningContent, pluginIdentifier) {
    this.content = content;
    this.reasoningContent = reasoningContent;
    this.nonReasoningContent = nonReasoningContent;
    this.pluginIdentifier = pluginIdentifier;
  }
};
var OngoingGeneratorPrediction = class _OngoingGeneratorPrediction extends StreamablePromise {
  async collect(fragments) {
    const content = fragments.map(({ content: content2 }) => content2).join("");
    const reasoningContent = fragments.filter(({ isStructural }) => !isStructural).filter(({ reasoningType }) => reasoningType === "reasoning").map(({ content: content2 }) => content2).join("");
    const nonReasoningContent = fragments.filter(({ isStructural }) => !isStructural).filter(({ reasoningType }) => reasoningType === "none").map(({ content: content2 }) => content2).join("");
    return new GeneratorPredictionResult(content, reasoningContent, nonReasoningContent, this.pluginIdentifier);
  }
  constructor(pluginIdentifier, onCancel) {
    super();
    this.pluginIdentifier = pluginIdentifier;
    this.onCancel = onCancel;
  }
  /** @internal */
  static create(pluginIdentifier, onCancel) {
    const ongoingPrediction = new _OngoingGeneratorPrediction(pluginIdentifier, onCancel);
    const finished2 = () => ongoingPrediction.finished();
    const failed = (error) => ongoingPrediction.finished(error);
    const push = (fragment) => ongoingPrediction.push(fragment);
    return { ongoingPrediction, finished: finished2, failed, push };
  }
  /**
   * Get the final prediction results. If you have been streaming the results, awaiting on this
   * method will take no extra effort, as the results are already available in the internal buffer.
   *
   * Example:
   *
   * ```typescript
   * const prediction = generator.complete("When will The Winds of Winter be released?");
   * for await (const { content } of prediction) {
   *   process.stdout.write(content);
   * }
   * const result = await prediction.result();
   * console.log(result.stats);
   * ```
   *
   * Technically, awaiting on this method is the same as awaiting on the instance itself:
   *
   * ```typescript
   * await prediction.result();
   *
   * // Is the same as:
   *
   * await prediction;
   * ```
   */
  async result() {
    return await this;
  }
  /**
   * Cancels the prediction.
   */
  async cancel() {
    this.onCancel();
  }
};
var llmGeneratorPredictionOptsSchema = external_exports.object({
  onFirstToken: external_exports.function().optional(),
  onPredictionFragment: external_exports.function().optional(),
  onMessage: external_exports.function().optional(),
  signal: external_exports.instanceof(AbortSignal).optional(),
  pluginConfig: kvConfigSchema.optional(),
  workingDirectory: external_exports.string().optional()
});
var llmGeneratorActOptsSchema = llmActBaseOptsSchema.extend({
  pluginConfig: kvConfigSchema.optional(),
  workingDirectory: external_exports.string().optional()
});
var LLMGeneratorHandle = class {
  /**
   * Don't use this method directly, use {@link LLMNamespace#createGeneratorHandle} instead.
   *
   * @internal
   */
  constructor(port, pluginIdentifier, validator2, associatedPredictionProcess, logger2 = new SimpleLogger(`LLMGeneratorHandle`)) {
    this.port = port;
    this.pluginIdentifier = pluginIdentifier;
    this.validator = validator2;
    this.associatedPredictionProcess = associatedPredictionProcess;
    this.logger = logger2;
    this.identifier = this.pluginIdentifier;
  }
  getPluginConfigSpecifier(userSuppliedPluginConfig, userSuppliedWorkingDirectory, stack) {
    if (this.associatedPredictionProcess === null) {
      return {
        type: "direct",
        config: userSuppliedPluginConfig ?? emptyKVConfig,
        workingDirectoryPath: userSuppliedWorkingDirectory ?? void 0
      };
    }
    if (userSuppliedPluginConfig !== void 0) {
      throw makeTitledPrettyError("Cannot use plugin config with prediction process", text`
          You cannot provide a plugin config to the generator handle when it is associated with a
          prediction process. The plugin config that was configured for the prediction process will
          be used instead.

          If you want to use a different plugin config, you will need to create a separate
          GeneratorHandle instead.
        `, stack);
    }
    if (userSuppliedWorkingDirectory !== void 0) {
      throw makeTitledPrettyError("Cannot use working directory with prediction process", text`
          You cannot provide a working directory to the generator handle when it is associated with
          a prediction process. The working directory that was configured for the prediction process
          will be used instead.

          If you want to use a different working directory, you will need to create a separate
          GeneratorHandle instead.
        `, stack);
    }
    return {
      type: "predictionProcess",
      pci: this.associatedPredictionProcess.pci,
      token: this.associatedPredictionProcess.token
    };
  }
  /**
   * Use the generator to produce a response based on the given history.
   */
  respond(chat, opts = {}) {
    const stack = getCurrentStack(1);
    [chat, opts] = this.validator.validateMethodParamsOrThrow("LLMGeneratorHandle", "respond", ["chat", "opts"], [chatHistoryLikeSchema, llmGeneratorPredictionOptsSchema], [chat, opts], stack);
    const { onFirstToken, onPredictionFragment, onMessage, signal, pluginConfig, workingDirectory } = opts;
    let resolved = false;
    let firstTokenTriggered = false;
    const cancelEvent = new CancelEvent();
    if (signal !== void 0) {
      if (signal.aborted) {
        cancelEvent.cancel();
      } else {
        signal.addEventListener("abort", () => cancelEvent.cancel(), { once: true });
      }
    }
    const { ongoingPrediction, finished: finished2, failed, push } = OngoingGeneratorPrediction.create(this.pluginIdentifier, () => {
      cancelEvent.cancel();
    });
    const channel = this.port.createChannel("generateWithGenerator", {
      pluginIdentifier: this.pluginIdentifier,
      pluginConfigSpecifier: this.getPluginConfigSpecifier(pluginConfig, workingDirectory, stack),
      tools: [],
      history: accessMaybeMutableInternals(Chat3.from(chat))._internalGetData()
    }, (message) => {
      const messageType = message.type;
      switch (messageType) {
        case "fragment": {
          if (!firstTokenTriggered) {
            firstTokenTriggered = true;
            safeCallCallback(this.logger, "onFirstToken", onFirstToken, []);
          }
          safeCallCallback(this.logger, "onPredictionFragment", onPredictionFragment, [
            message.fragment
          ]);
          push(message.fragment);
          break;
        }
        case "success": {
          resolved = true;
          finished2();
          break;
        }
      }
    }, { stack });
    channel.onError.subscribeOnce((error) => {
      if (resolved) {
        return;
      }
      resolved = true;
      failed(error);
    });
    cancelEvent.subscribeOnce(() => {
      if (resolved) {
        return;
      }
      channel.send({ type: "cancel" });
    });
    ongoingPrediction.then((result) => {
      safeCallCallback(this.logger, "onMessage", onMessage, [
        ChatMessage.create("assistant", result.content)
      ]);
    }, () => {
    });
    return ongoingPrediction;
  }
  async act(chat, tools, opts = {}) {
    const startTime = performance.now();
    const stack = getCurrentStack(1);
    [chat, opts] = this.validator.validateMethodParamsOrThrow("LLMGeneratorHandle", "act", ["chat", "opts"], [chatHistoryLikeSchema, llmGeneratorActOptsSchema], [chat, opts], stack);
    const { pluginConfig, workingDirectory, ...baseOpts } = opts;
    const toolDefinitions = tools.map(toolToLLMTool);
    return await internalAct(
      chat,
      tools,
      baseOpts,
      stack,
      this.logger,
      startTime,
      // Implementation of the prediction function. This performs the prediction by creating a
      // predict channel and redirect the messages to the appropriate handlers.
      async ({ allowTools, history, signal, handleFragment, handlePromptProcessingProgress, handleToolCallGenerationStart, handleToolCallGenerationNameReceived, handleToolCallGenerationArgumentFragmentGenerated, handleToolCallGenerationEnd, handleToolCallGenerationFailed, handlePredictionEnd, handleError }) => {
        const channel = this.port.createChannel("generateWithGenerator", {
          pluginIdentifier: this.pluginIdentifier,
          pluginConfigSpecifier: this.getPluginConfigSpecifier(pluginConfig, workingDirectory, stack),
          tools: allowTools ? toolDefinitions : [],
          history
        }, (message) => {
          const messageType = message.type;
          switch (messageType) {
            case "fragment": {
              handleFragment(message.fragment);
              break;
            }
            case "promptProcessingProgress": {
              handlePromptProcessingProgress(message.progress);
              break;
            }
            case "toolCallGenerationStart": {
              handleToolCallGenerationStart(message.toolCallId);
              break;
            }
            case "toolCallGenerationNameReceived": {
              handleToolCallGenerationNameReceived(message.name);
              break;
            }
            case "toolCallGenerationArgumentFragmentGenerated": {
              handleToolCallGenerationArgumentFragmentGenerated(message.content);
              break;
            }
            case "toolCallGenerationEnd": {
              handleToolCallGenerationEnd(message.toolCallRequest, void 0);
              break;
            }
            case "toolCallGenerationFailed": {
              handleToolCallGenerationFailed(
                new Error("Tool call generation failed"),
                // Placeholder error for now
                void 0
              );
              break;
            }
            case "success": {
              handlePredictionEnd(void 0);
              break;
            }
          }
        }, { stack });
        if (signal.aborted) {
          channel.send({ type: "cancel" });
        } else {
          signal.addEventListener("abort", () => {
            channel.send({ type: "cancel" });
          }, { once: true });
        }
        channel.onError.subscribeOnce(handleError);
      },
      ({ content, nonReasoningContent, reasoningContent }) => new GeneratorPredictionResult(content, reasoningContent, nonReasoningContent, this.pluginIdentifier)
    );
  }
};
var generatorSchema = external_exports.function();
var BaseController = class {
  constructor(client, abortSignal, pluginConfig, globalPluginConfig, workingDirectoryPath) {
    this.client = client;
    this.abortSignal = abortSignal;
    this.pluginConfig = pluginConfig;
    this.globalPluginConfig = globalPluginConfig;
    this.workingDirectoryPath = workingDirectoryPath;
  }
  /**
   * Gets the working directory for the current prediction. If your plugin produces files, you
   * should aim to put them in this directory.
   */
  getWorkingDirectory() {
    if (this.workingDirectoryPath === null) {
      throw new Error("This prediction process is not attached to a working directory.");
    }
    return this.workingDirectoryPath;
  }
  /**
   * Get the per-chat config for the plugin. Takes in the configSchematics. You can get the
   * values of fields like so:
   *
   * ```ts
   * const config = ctl.getPluginConfig(configSchematics);
   * const value = config.get("fieldKey");
   * ```
   *
   * @remarks
   *
   * If you need to name the type of the returned value, use:
   *
   * `InferParsedConfig<typeof configSchematics>`.
   *
   * Example:
   *
   * ```ts
   * function myFunction(config: InferParsedConfig<typeof configSchematics>) {
   *   // ...
   * }
   *
   * myFunction(ctl.getPluginConfig(configSchematics));
   * ```
   */
  getPluginConfig(configSchematics) {
    return configSchematics.parse(this.pluginConfig);
  }
  /**
   * Get the application-wide config for the plugin. Takes in the globalConfigSchematics. You can
   * get the values of fields like so:
   *
   * ```ts
   * const config = ctl.getGlobalPluginConfig(globalConfigSchematics);
   * const value = config.get("fieldKey");
   * ```
   *
   * @remarks
   *
   * If you need to name the type of the returned value, use:
   *
   * `InferParsedConfig<typeof globalConfigSchematics>`.
   *
   * Example:
   *
   * ```ts
   * function myFunction(config: InferParsedConfig<typeof globalConfigSchematics>) {
   *   // ...
   * }
   *
   * myFunction(ctl.getGlobalPluginConfig(globalConfigSchematics));
   * ```
   */
  getGlobalPluginConfig(globalConfigSchematics2) {
    return globalConfigSchematics2.parse(this.globalPluginConfig);
  }
  /**
   * Provides a callback that will be called when the prediction is aborted. If the prediction is
   * already aborted, the callback will be called immediately.
   *
   * You can also use {@link BaseController.abortSignal} if you are using an async function that
   * supports abort signals.
   *
   * See https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal for more information about
   * abort signals.
   */
  onAborted(callback) {
    if (this.abortSignal.aborted) {
      callback();
    } else {
      this.abortSignal.addEventListener("abort", callback, { once: true });
    }
  }
};
var GeneratorController = class extends BaseController {
  /**
   * @internal Do not construct this class yourself.
   */
  constructor(client, pluginConfig, globalPluginConfig, workingDirectoryPath, abortSignal, toolDefinitions, connector, validator2) {
    super(client, abortSignal, pluginConfig, globalPluginConfig, workingDirectoryPath);
    this.toolDefinitions = toolDefinitions;
    this.connector = connector;
    this.validator = validator2;
  }
  /**
   * Get the definitions of the tools available for this generation.
   */
  getToolDefinitions() {
    return this.toolDefinitions;
  }
  /**
   * Use this function to report a text fragment has been generated.
   *
   * @param content - The content that has been generated.
   * @param opts - Additional info about the generated content, such as how many tokens it contains.
   *   See {@link LLMPredictionFragmentInputOpts} for more info. All the fields are optional.
   */
  fragmentGenerated(content, opts = {}) {
    const stack = getCurrentStack(1);
    [content, opts] = this.validator.validateMethodParamsOrThrow("GeneratorController", "fragmentGenerated", ["content", "opts"], [external_exports.string(), llmPredictionFragmentInputOptsSchema], [content, opts], stack);
    this.connector.fragmentGenerated(content, opts);
  }
  /**
   * Use this function to report that a tool call generation has started. Each
   * `toolCallGenerationStarted` must be paired up with a `toolCallGenerationEnded` call for
   * successfully generated tool calls, or a `toolCallGenerationFailed` call for
   * failed tool calls.
   */
  toolCallGenerationStarted({ toolCallId } = {}) {
    this.connector.toolCallGenerationStarted(toolCallId);
  }
  /**
   * Use this function to report that the name of the tool call has been generated. This function
   * should only be called once for each `toolCallGenerationStarted`.
   *
   * @param toolName - The name of the tool that has been generated.
   */
  toolCallGenerationNameReceived(toolName) {
    const stack = getCurrentStack(1);
    toolName = this.validator.validateMethodParamOrThrow("GeneratorController", "toolCallGenerationNameReceived", "toolName", external_exports.string(), toolName, stack);
    this.connector.toolCallGenerationNameReceived(toolName);
  }
  /**
   * Use this function to report that a new argument fragment has been generated for the tool call.
   * This function can be called multiple times for each `toolCallGenerationStarted`.
   *
   * @param content - The new fragment that has been generated for the tool call.
   */
  toolCallGenerationArgumentFragmentGenerated(content) {
    const stack = getCurrentStack(1);
    content = this.validator.validateMethodParamOrThrow("GeneratorController", "toolCallGenerationArgumentFragmentGenerated", "content", external_exports.string(), content, stack);
    this.connector.toolCallGenerationArgumentFragmentGenerated(content);
  }
  /**
   * Use this function to report that a tool call generation has successfully ended. This function
   * should only be called after a `toolCallGenerationStarted` call.
   */
  toolCallGenerationEnded(toolCallRequest) {
    const stack = getCurrentStack(1);
    toolCallRequest = this.validator.validateMethodParamOrThrow("GeneratorController", "toolCallGenerationEnded", "toolCallRequest", toolCallRequestSchema, toolCallRequest, stack);
    this.connector.toolCallGenerationEnded(toolCallRequest);
  }
  /**
   * Use this function to report that a tool call generation has failed. This function should only
   * be called after a `toolCallGenerationStarted` call.
   *
   * @param error - The error that occurred during the tool call generation.
   */
  toolCallGenerationFailed(error) {
    const stack = getCurrentStack(1);
    error = this.validator.validateMethodParamOrThrow("GeneratorController", "toolCallGenerationFailed", "error", external_exports.instanceof(Error), error, stack);
    this.connector.toolCallGenerationFailed(error);
  }
};
var __addDisposableResource$1 = globalThis && globalThis.__addDisposableResource || function(env, value, async) {
  if (value !== null && value !== void 0) {
    if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
    var dispose, inner2;
    if (async) {
      if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
      dispose = value[Symbol.asyncDispose];
    }
    if (dispose === void 0) {
      if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
      dispose = value[Symbol.dispose];
      if (async) inner2 = dispose;
    }
    if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
    if (inner2) dispose = function() {
      try {
        inner2.call(this);
      } catch (e9) {
        return Promise.reject(e9);
      }
    };
    env.stack.push({ value, dispose, async });
  } else if (async) {
    env.stack.push({ async: true });
  }
  return value;
};
var __disposeResources$1 = globalThis && globalThis.__disposeResources || /* @__PURE__ */ (function(SuppressedError2) {
  return function(env) {
    function fail(e9) {
      env.error = env.hasError ? new SuppressedError2(e9, env.error, "An error was suppressed during disposal.") : e9;
      env.hasError = true;
    }
    var r8, s6 = 0;
    function next() {
      while (r8 = env.stack.pop()) {
        try {
          if (!r8.async && s6 === 1) return s6 = 0, env.stack.push(r8), Promise.resolve().then(next);
          if (r8.dispose) {
            var result = r8.dispose.call(r8.value);
            if (r8.async) return s6 |= 2, Promise.resolve(result).then(next, function(e9) {
              fail(e9);
              return next();
            });
          } else s6 |= 1;
        } catch (e9) {
          fail(e9);
        }
      }
      if (s6 === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
      if (env.hasError) throw env.error;
    }
    return next();
  };
})(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
  var e9 = new Error(message);
  return e9.name = "SuppressedError", e9.error = error, e9.suppressed = suppressed, e9;
});
function stringifyAny(message) {
  switch (typeof message) {
    case "string":
      return message;
    case "number":
      return message.toString();
    case "boolean":
      return message ? "true" : "false";
    case "undefined":
      return "undefined";
    case "object":
      if (message === null) {
        return "null";
      }
      if (message instanceof Error) {
        return message.stack;
      }
      return JSON.stringify(message, null, 2);
    case "bigint":
      return message.toString();
    case "symbol":
      return message.toString();
    case "function":
      return message.toString();
    default:
      return "unknown";
  }
}
function concatenateDebugMessages(...messages) {
  return messages.map(stringifyAny).join(" ");
}
function createId() {
  return `${Date.now()}-${Math.random()}`;
}
var ProcessingConnector = class {
  constructor(pluginsPort, abortSignal, processingContextIdentifier, token, logger2) {
    this.pluginsPort = pluginsPort;
    this.abortSignal = abortSignal;
    this.processingContextIdentifier = processingContextIdentifier;
    this.token = token;
    this.logger = logger2;
  }
  handleUpdate(update) {
    this.pluginsPort.callRpc("processingHandleUpdate", {
      pci: this.processingContextIdentifier,
      token: this.token,
      update
    }).catch((error) => {
      this.logger.error("Failed to send update", error);
    });
  }
  async handleRequest(request) {
    const { response } = await this.pluginsPort.callRpc("processingHandleRequest", {
      pci: this.processingContextIdentifier,
      token: this.token,
      request
    });
    return response;
  }
  async pullHistory(includeCurrent) {
    const chatHistoryData = await this.pluginsPort.callRpc("processingPullHistory", {
      pci: this.processingContextIdentifier,
      token: this.token,
      includeCurrent
    });
    return Chat3.createRaw(
      chatHistoryData,
      /* mutable */
      false
    ).asMutableCopy();
  }
  async getOrLoadTokenSource() {
    const result = await this.pluginsPort.callRpc("processingGetOrLoadTokenSource", {
      pci: this.processingContextIdentifier,
      token: this.token
    });
    return result.tokenSourceIdentifier;
  }
  async hasStatus() {
    return await this.pluginsPort.callRpc("processingHasStatus", {
      pci: this.processingContextIdentifier,
      token: this.token
    });
  }
  async needsNaming() {
    return await this.pluginsPort.callRpc("processingNeedsNaming", {
      pci: this.processingContextIdentifier,
      token: this.token
    });
  }
  async suggestName(name) {
    await this.pluginsPort.callRpc("processingSuggestName", {
      pci: this.processingContextIdentifier,
      token: this.token,
      name
    });
  }
};
var ProcessingController = class extends BaseController {
  /** @internal */
  constructor(client, pluginConfig, globalPluginConfig, workingDirectoryPath, enabledPluginInfos, connector, config, shouldIncludeCurrentInHistory) {
    super(client, connector.abortSignal, pluginConfig, globalPluginConfig, workingDirectoryPath);
    this.enabledPluginInfos = enabledPluginInfos;
    this.connector = connector;
    this.config = config;
    this.shouldIncludeCurrentInHistory = shouldIncludeCurrentInHistory;
    this.processingControllerHandle = {
      abortSignal: connector.abortSignal,
      sendUpdate: (update) => {
        connector.handleUpdate(update);
      },
      sendRequest: async (request) => {
        const type = request.type;
        const response = await connector.handleRequest(request);
        if (response.type !== type) {
          throw new Error(`Expected response type ${type}, but got ${response.type}. This is a bug.`);
        }
        return response;
      }
    };
  }
  sendUpdate(update) {
    this.processingControllerHandle.sendUpdate(update);
  }
  /**
   * Gets a mutable copy of the current history. The returned history is a copy, so mutating it will
   * not affect the actual history. It is mutable for convenience reasons.
   *
   * - If you are a promptPreprocessor, this will not include the user message you are currently
   *   preprocessing.
   * - If you are a prediction loop handler, this will include the user message, and can be fed into
   *   the {@link LLMDynamicHandle#respond} method directly.
   */
  async pullHistory() {
    return await this.connector.pullHistory(this.shouldIncludeCurrentInHistory);
  }
  createStatus(initialState) {
    const id = createId();
    this.sendUpdate({
      type: "status.create",
      id,
      state: initialState
    });
    const statusController = new PredictionProcessStatusController(this.processingControllerHandle, initialState, id);
    return statusController;
  }
  addCitations(arg) {
    if (Array.isArray(arg)) {
      for (const entry of arg) {
        this.createCitationBlock(entry.content, {
          fileName: entry.source.name,
          fileIdentifier: entry.source.identifier
        });
      }
    } else {
      for (const entry of arg.entries) {
        this.createCitationBlock(entry.content, {
          fileName: entry.source.name,
          fileIdentifier: entry.source.identifier
        });
      }
    }
  }
  createCitationBlock(citedText, source) {
    const id = createId();
    this.sendUpdate({
      type: "citationBlock.create",
      id,
      citedText,
      ...source
    });
    const citationBlockController = new PredictionProcessCitationBlockController(this.processingControllerHandle, id);
    return citationBlockController;
  }
  /**
   * @internal
   */
  createDebugInfoBlock(debugInfo) {
    const id = createId();
    this.sendUpdate({
      type: "debugInfoBlock.create",
      id,
      debugInfo
    });
    const debugInfoBlockController = new PredictionProcessDebugInfoBlockController(this.processingControllerHandle, id);
    return debugInfoBlockController;
  }
  createContentBlock({ roleOverride, includeInContext = true, style, prefix, suffix } = {}) {
    const id = createId();
    this.sendUpdate({
      type: "contentBlock.create",
      id,
      roleOverride,
      includeInContext,
      style,
      prefix,
      suffix
    });
    const contentBlockController = new PredictionProcessContentBlockController(this.processingControllerHandle, id, roleOverride ?? "assistant");
    return contentBlockController;
  }
  debug(...messages) {
    this.createDebugInfoBlock(concatenateDebugMessages(...messages));
  }
  /**
   * Gets the token source associated with this prediction process (i.e. what the user has selected
   * on the top navigation bar).
   *
   * The token source can either be a model or a generator plugin. In both cases, the returned
   * object will contain a ".act" and a ".respond" method, which can be used to generate text.
   *
   * The token source is already pre-configured to use user's prediction config - you don't need to
   * pass through any additional configuration.
   */
  async tokenSource() {
    const tokenSourceIdentifier = await this.connector.getOrLoadTokenSource();
    const tokenSourceIdentifierType = tokenSourceIdentifier.type;
    switch (tokenSourceIdentifierType) {
      case "model": {
        const model = await this.client.llm.model(tokenSourceIdentifier.identifier);
        model.internalIgnoreServerSessionConfig = true;
        model.internalKVConfigStack = {
          layers: [
            {
              layerName: "conversationSpecific",
              config: this.config
            }
          ]
        };
        return model;
      }
      case "generator": {
        const generator = this.client.plugins.createGeneratorHandleAssociatedWithPredictionProcess(tokenSourceIdentifier.pluginIdentifier, this.connector.processingContextIdentifier, this.connector.token);
        return generator;
      }
    }
  }
  /**
   * Sets the sender name for this message. The sender name shown above the message in the chat.
   */
  async setSenderName(name) {
    this.sendUpdate({
      type: "setSenderName",
      name
    });
  }
  /**
   * Throws an error if the prediction process has been aborted. Sprinkle this throughout your code
   * to ensure that the prediction process is aborted as soon as possible.
   */
  guardAbort() {
    this.abortSignal.throwIfAborted();
  }
  /**
   * Whether this prediction process has had any status.
   */
  async hasStatus() {
    return await this.connector.hasStatus();
  }
  /**
   * Returns whether this conversation needs a name.
   */
  async needsNaming() {
    return await this.connector.needsNaming();
  }
  /**
   * Suggests a name for this conversation.
   */
  async suggestName(name) {
    await this.connector.suggestName(name);
  }
  async requestConfirmToolCall({ callId, pluginIdentifier, name, parameters }) {
    const { result } = await raceWithAbortSignal(this.processingControllerHandle.sendRequest({
      type: "confirmToolCall",
      callId,
      pluginIdentifier,
      name,
      parameters
    }), this.abortSignal);
    const resultType = result.type;
    switch (resultType) {
      case "allow": {
        return {
          type: "allow",
          toolArgsOverride: result.toolArgsOverride
        };
      }
      case "deny": {
        return {
          type: "deny",
          denyReason: result.denyReason
        };
      }
      default: {
        const exhaustiveCheck = resultType;
        throw new Error(`Unexpected result type ${exhaustiveCheck}. This is a bug. Please report it.`);
      }
    }
  }
  createToolStatus(callId, initialStatus) {
    const id = createId();
    this.sendUpdate({
      type: "toolStatus.create",
      id,
      callId,
      state: {
        status: initialStatus,
        customStatus: "",
        customWarnings: []
      }
    });
    const toolStatusController = new PredictionProcessToolStatusController(this.processingControllerHandle, id, initialStatus);
    return toolStatusController;
  }
  /**
   * Starts a tool use session with tools available in the prediction process. Note, this method
   * should be used with "Explicit Resource Management". That is, you should use it like so:
   *
   * ```typescript
   * using toolUseSession = await ctl.startToolUseSession();
   * // ^ Notice the `using` keyword here.
   * ```
   *
   * If you do not `using`, you should call `toolUseSession[Symbol.dispose]()` after you are done.
   *
   * If you don't, lmstudio-js will close the session upon the end of the prediction step
   * automatically. However, it is not recommended.
   *
   * @public
   * @deprecated WIP
   */
  async startToolUseSession() {
    const identifiersOfPluginsWithTools = this.enabledPluginInfos.filter(({ hasToolsProvider }) => hasToolsProvider).map(({ identifier }) => identifier);
    return await this.client.plugins.startToolUseSessionUsingPredictionProcess(
      // We start a tool use session with all the plugins that have tools available
      identifiersOfPluginsWithTools,
      this.connector.processingContextIdentifier,
      this.connector.token
    );
  }
};
var PredictionProcessStatusController = class _PredictionProcessStatusController {
  /** @internal */
  constructor(handle, initialState, id, indentation = 0) {
    this.handle = handle;
    this.id = id;
    this.indentation = indentation;
    this.lastSubStatus = this;
    this.lastState = initialState;
  }
  setText(text3) {
    this.lastState.text = text3;
    this.handle.sendUpdate({
      type: "status.update",
      id: this.id,
      state: this.lastState
    });
  }
  setState(state) {
    this.lastState = state;
    this.handle.sendUpdate({
      type: "status.update",
      id: this.id,
      state
    });
  }
  remove() {
    this.handle.sendUpdate({
      type: "status.remove",
      id: this.id
    });
  }
  getNestedLastSubStatusBlockId() {
    let current2 = this.lastSubStatus;
    while (current2 !== current2.lastSubStatus) {
      current2 = current2.lastSubStatus;
    }
    return current2.id;
  }
  addSubStatus(initialState) {
    const id = createId();
    this.handle.sendUpdate({
      type: "status.create",
      id,
      state: initialState,
      location: {
        type: "afterId",
        id: this.getNestedLastSubStatusBlockId()
      },
      indentation: this.indentation + 1
    });
    const controller = new _PredictionProcessStatusController(this.handle, initialState, id, this.indentation + 1);
    this.lastSubStatus = controller;
    return controller;
  }
};
var PredictionProcessCitationBlockController = class {
  /** @internal */
  constructor(handle, id) {
    this.handle = handle;
    this.id = id;
  }
};
var PredictionProcessDebugInfoBlockController = class {
  /** @internal */
  constructor(handle, id) {
    this.handle = handle;
    this.id = id;
  }
};
var PredictionProcessContentBlockController = class {
  /** @internal */
  constructor(handle, id, role) {
    this.handle = handle;
    this.id = id;
    this.role = role;
  }
  appendText(text3, { tokensCount, fromDraftModel, isStructural } = {}) {
    if (this.role === "tool") {
      throw new Error("Text cannot be appended to tool blocks.");
    }
    this.handle.sendUpdate({
      type: "contentBlock.appendText",
      id: this.id,
      text: text3,
      tokensCount,
      fromDraftModel,
      isStructural
    });
  }
  appendToolRequest({ callId, toolCallRequestId, name, parameters, pluginIdentifier }) {
    if (this.role !== "assistant") {
      throw new Error(`Tool requests can only be appended to assistant blocks. This is a ${this.role} block.`);
    }
    this.handle.sendUpdate({
      type: "contentBlock.appendToolRequest",
      id: this.id,
      callId,
      toolCallRequestId,
      name,
      parameters,
      pluginIdentifier
    });
  }
  replaceToolRequest({ callId, toolCallRequestId, name, parameters, pluginIdentifier }) {
    if (this.role !== "assistant") {
      throw new Error(`Tool requests can only be replaced in assistant blocks. This is a ${this.role} block.`);
    }
    this.handle.sendUpdate({
      type: "contentBlock.replaceToolRequest",
      id: this.id,
      callId,
      toolCallRequestId,
      name,
      parameters,
      pluginIdentifier
    });
  }
  appendToolResult({ callId, toolCallRequestId, content }) {
    if (this.role !== "tool") {
      throw new Error(`Tool results can only be appended to tool blocks. This is a ${this.role} block.`);
    }
    this.handle.sendUpdate({
      type: "contentBlock.appendToolResult",
      id: this.id,
      callId,
      toolCallRequestId,
      content
    });
  }
  replaceText(text3) {
    if (this.role === "tool") {
      throw new Error("Text cannot be set in tool blocks.");
    }
    this.handle.sendUpdate({
      type: "contentBlock.replaceText",
      id: this.id,
      text: text3
    });
  }
  setStyle(style) {
    this.handle.sendUpdate({
      type: "contentBlock.setStyle",
      id: this.id,
      style
    });
  }
  setPrefix(prefix) {
    this.handle.sendUpdate({
      type: "contentBlock.setPrefix",
      id: this.id,
      prefix
    });
  }
  setSuffix(suffix) {
    this.handle.sendUpdate({
      type: "contentBlock.setSuffix",
      id: this.id,
      suffix
    });
  }
  attachGenInfo(genInfo) {
    this.handle.sendUpdate({
      type: "contentBlock.attachGenInfo",
      id: this.id,
      genInfo
    });
  }
  async pipeFrom(prediction) {
    const env_1 = { stack: [], error: void 0, hasError: false };
    try {
      const cleaner = __addDisposableResource$1(env_1, new Cleaner(), false);
      const abortListener = () => {
        prediction.cancel();
      };
      this.handle.abortSignal.addEventListener("abort", abortListener);
      cleaner.register(() => {
        this.handle.abortSignal.removeEventListener("abort", abortListener);
      });
      for await (const { content } of prediction) {
        this.appendText(content);
      }
      const result = await prediction;
      this.attachGenInfo({
        indexedModelIdentifier: result.modelInfo.path,
        identifier: result.modelInfo.identifier,
        loadModelConfig: result.loadConfig,
        predictionConfig: result.predictionConfig,
        stats: result.stats
      });
      this.handle.abortSignal.throwIfAborted();
      return result;
    } catch (e_1) {
      env_1.error = e_1;
      env_1.hasError = true;
    } finally {
      __disposeResources$1(env_1);
    }
  }
};
var PredictionProcessToolStatusController = class {
  /** @internal */
  constructor(handle, id, initialStatus) {
    this.handle = handle;
    this.id = id;
    this.customStatus = "";
    this.customWarnings = [];
    this.status = initialStatus;
  }
  updateState() {
    this.handle.sendUpdate({
      type: "toolStatus.update",
      id: this.id,
      state: {
        status: this.status,
        customStatus: this.customStatus,
        customWarnings: this.customWarnings
      }
    });
  }
  setCustomStatusText(status) {
    this.customStatus = status;
    this.updateState();
  }
  addWarning(warning) {
    this.customWarnings.push(warning);
    this.updateState();
  }
  setStatus(status) {
    this.status = status;
    this.updateState();
  }
  appendArgumentFragment(content) {
    this.handle.sendUpdate({
      type: "toolStatus.argumentFragment",
      id: this.id,
      content
    });
  }
};
var ToolsProviderController = class extends BaseController {
  /**
   * @internal Do not construct this class yourself.
   */
  constructor(client, signal, pluginConfig, globalPluginConfig, workingDirectoryPath) {
    super(client, signal, pluginConfig, globalPluginConfig, workingDirectoryPath);
  }
};
var GeneratorConnectorImpl = class {
  constructor(channel, taskId) {
    this.channel = channel;
    this.taskId = taskId;
  }
  fragmentGenerated(content, opts) {
    this.channel.send({
      type: "fragmentGenerated",
      taskId: this.taskId,
      content,
      opts
    });
  }
  toolCallGenerationStarted(toolCallId) {
    this.channel.send({
      type: "toolCallGenerationStarted",
      taskId: this.taskId,
      toolCallId
    });
  }
  toolCallGenerationNameReceived(toolName) {
    this.channel.send({
      type: "toolCallGenerationNameReceived",
      taskId: this.taskId,
      toolName
    });
  }
  toolCallGenerationArgumentFragmentGenerated(content) {
    this.channel.send({
      type: "toolCallGenerationArgumentFragmentGenerated",
      taskId: this.taskId,
      content
    });
  }
  toolCallGenerationEnded(toolCallRequest) {
    this.channel.send({
      type: "toolCallGenerationEnded",
      taskId: this.taskId,
      toolCallRequest
    });
  }
  toolCallGenerationFailed(error) {
    this.channel.send({
      type: "toolCallGenerationFailed",
      taskId: this.taskId,
      error: serializeError(error)
    });
  }
};
var PluginSelfRegistrationHost = class {
  constructor(port, client, rootLogger, validator2) {
    this.port = port;
    this.client = client;
    this.rootLogger = rootLogger;
    this.validator = validator2;
  }
  /**
   * Sets the promptPreprocessor to be used by the plugin represented by this client.
   *
   * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the
   * future without warning.
   */
  setPromptPreprocessor(promptPreprocessor) {
    const stack = getCurrentStack(1);
    this.validator.validateMethodParamOrThrow("plugins", "registerPromptPreprocessor", "promptPreprocessor", external_exports.function(), promptPreprocessor, stack);
    const logger2 = new SimpleLogger(`PromptPreprocessor`, this.rootLogger);
    logger2.info("Register with LM Studio");
    const tasks = /* @__PURE__ */ new Map();
    const channel = this.port.createChannel("setPromptPreprocessor", void 0, (message) => {
      switch (message.type) {
        case "preprocess": {
          const taskLogger = new SimpleLogger(`Request (${message.taskId.substring(0, 6)})`, logger2);
          taskLogger.info(`New preprocess request received.`);
          const abortController = new AbortController();
          const connector = new ProcessingConnector(this.port, abortController.signal, message.pci, message.token, taskLogger);
          const input = ChatMessage.createRaw(
            message.input,
            /* mutable */
            false
          );
          const controller = new ProcessingController(
            this.client,
            message.pluginConfig,
            message.globalPluginConfig,
            message.workingDirectoryPath,
            message.enabledPluginInfos,
            connector,
            message.config,
            /* shouldIncludeInputInHistory */
            false
          );
          tasks.set(message.taskId, {
            cancel: () => {
              abortController.abort();
            },
            taskLogger
          });
          promptPreprocessor(controller, input.asMutableCopy()).then((result) => {
            taskLogger.info(`Preprocess request completed.`);
            const parsedReturned = external_exports.union([external_exports.string(), external_exports.custom((v4) => v4 instanceof ChatMessage)]).safeParse(result);
            if (!parsedReturned.success) {
              throw new Error("PromptPreprocessor returned an invalid value:" + Validator.prettyPrintZod("result", parsedReturned.error));
            }
            const returned = parsedReturned.data;
            let processed;
            if (typeof returned === "string") {
              const messageCopy = input.asMutableCopy();
              messageCopy.replaceText(returned);
              processed = messageCopy.getRaw();
            } else {
              processed = returned.getRaw();
            }
            channel.send({
              type: "complete",
              taskId: message.taskId,
              processed
            });
          }).catch((error) => {
            if (error.name === "AbortError") {
              logger2.info(`Request successfully aborted.`);
              channel.send({
                type: "aborted",
                taskId: message.taskId
              });
              return;
            }
            logger2.warn(`Preprocessing failed.`, error);
            channel.send({
              type: "error",
              taskId: message.taskId,
              error: serializeError(error)
            });
          }).finally(() => {
            tasks.delete(message.taskId);
          });
          break;
        }
        case "abort": {
          const task = tasks.get(message.taskId);
          if (task !== void 0) {
            task.taskLogger.info(`Received abort request.`);
            task.cancel();
            tasks.delete(message.taskId);
          }
          break;
        }
      }
    }, { stack });
  }
  /**
   * Sets the prediction loop handler to be used by the plugin represented by this client.
   *
   * @deprecated [DEP-PLUGIN-PREDICTION-LOOP-HANDLER] Prediction loop handler support is still in
   * development. Stay tuned for updates.
   */
  setPredictionLoopHandler(predictionLoopHandler) {
    const stack = getCurrentStack(1);
    this.validator.validateMethodParamOrThrow("plugins", "setPredictionLoopHandler", "predictionLoopHandler", external_exports.function(), predictionLoopHandler, stack);
    const logger2 = new SimpleLogger(`   PredictionLoopHandler`, this.rootLogger);
    logger2.info("Register with LM Studio");
    const tasks = /* @__PURE__ */ new Map();
    const channel = this.port.createChannel("setPredictionLoopHandler", void 0, (message) => {
      switch (message.type) {
        case "handlePredictionLoop": {
          const taskLogger = new SimpleLogger(`Request (${message.taskId.substring(0, 6)})`, logger2);
          taskLogger.info(`New prediction loop handling request received.`);
          const abortController = new AbortController();
          const connector = new ProcessingConnector(this.port, abortController.signal, message.pci, message.token, taskLogger);
          const controller = new ProcessingController(
            this.client,
            message.pluginConfig,
            message.globalPluginConfig,
            message.workingDirectoryPath,
            message.enabledPluginInfos,
            connector,
            message.config,
            /* shouldIncludeInputInHistory */
            true
          );
          tasks.set(message.taskId, {
            cancel: () => {
              abortController.abort();
            },
            taskLogger
          });
          predictionLoopHandler(controller).then(() => {
            channel.send({
              type: "complete",
              taskId: message.taskId
            });
          }).catch((error) => {
            if (error.name === "AbortError") {
              logger2.info(`Request successfully aborted.`);
              channel.send({
                type: "aborted",
                taskId: message.taskId
              });
              return;
            }
            logger2.warn(`Generation failed.`, error);
            channel.send({
              type: "error",
              taskId: message.taskId,
              error: serializeError(error)
            });
          }).finally(() => {
            tasks.delete(message.taskId);
          });
          break;
        }
        case "abort": {
          const task = tasks.get(message.taskId);
          if (task !== void 0) {
            task.taskLogger.info(`Received abort request.`);
            task.cancel();
            tasks.delete(message.taskId);
          }
          break;
        }
      }
    }, { stack });
  }
  /**
   * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the
   * future without warning.
   */
  async setConfigSchematics(configSchematics) {
    const stack = getCurrentStack(1);
    this.validator.validateMethodParamOrThrow("plugins", "setConfigSchematics", "configSchematics", external_exports.instanceof(KVConfigSchematics), configSchematics, stack);
    await this.port.callRpc("setConfigSchematics", {
      schematics: configSchematics.serialize()
    }, { stack });
  }
  /**
   * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the
   * future without warning.
   */
  async setGlobalConfigSchematics(globalConfigSchematics2) {
    const stack = getCurrentStack(1);
    this.validator.validateMethodParamOrThrow("plugins", "setGlobalConfigSchematics", "globalConfigSchematics", external_exports.instanceof(KVConfigSchematics), globalConfigSchematics2, stack);
    await this.port.callRpc("setGlobalConfigSchematics", {
      schematics: globalConfigSchematics2.serialize()
    }, { stack });
  }
  /**
   * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the
   * future without warning.
   */
  setToolsProvider(toolsProvider) {
    const stack = getCurrentStack(1);
    this.validator.validateMethodParamOrThrow("plugins", "setToolsProvider", "toolsProvider", external_exports.function(), toolsProvider, stack);
    const logger2 = new SimpleLogger(`Tools Prvdr.`, this.rootLogger);
    logger2.info("Register with LM Studio");
    const openSessions = /* @__PURE__ */ new Map();
    const channel = this.port.createChannel("setToolsProvider", void 0, (message) => {
      const messageType = message.type;
      switch (messageType) {
        case "initSession": {
          const sessionId = message.sessionId;
          const sessionAbortController = new AbortController();
          const openSession = {
            tools: null,
            ongoingToolCalls: /* @__PURE__ */ new Map(),
            discarded: false,
            abortController: sessionAbortController
          };
          openSessions.set(sessionId, openSession);
          const controller = new ToolsProviderController(this.client, sessionAbortController.signal, message.pluginConfig, message.globalPluginConfig, message.workingDirectoryPath);
          toolsProvider(controller).then((tools) => {
            const llmTools = tools.map(toolToLLMTool);
            if (openSession.discarded) {
              return;
            }
            channel.send({
              type: "sessionInitialized",
              sessionId,
              toolDefinitions: llmTools
            });
            openSession.tools = new Map(tools.map((tool) => [tool.name, tool]));
          }, (error) => {
            if (openSession.discarded) {
              return;
            }
            channel.send({
              type: "sessionInitializationFailed",
              sessionId,
              error: serializeError(error)
            });
            openSession.discarded = true;
            openSessions.delete(sessionId);
          });
          break;
        }
        case "discardSession": {
          const sessionId = message.sessionId;
          const openSession = openSessions.get(sessionId);
          if (openSession === void 0) {
            return;
          }
          openSession.discarded = true;
          openSession.abortController.abort();
          openSessions.delete(sessionId);
          break;
        }
        case "callTool": {
          const sessionId = message.sessionId;
          const openSession = openSessions.get(sessionId);
          if (openSession === void 0) {
            return;
          }
          if (openSession.tools === null) {
            throw new Error("Tool called before initialization completed. This is unexpected.");
          }
          const tool = openSession.tools.get(message.toolName);
          if (tool === void 0) {
            throw new Error(`Tool ${message.toolName} not found.`);
          }
          const callId = message.callId;
          const ongoingToolCall = {
            settled: false,
            abortController: new AbortController()
          };
          openSession.ongoingToolCalls.set(callId, ongoingToolCall);
          new SimpleLogger(`Tool (${message.toolName})`, this.rootLogger);
          const toolCallContext = {
            status(text3) {
              channel.send({
                type: "toolCallStatus",
                sessionId,
                callId,
                statusText: text3
              });
            },
            warn(text3) {
              channel.send({
                type: "toolCallWarn",
                sessionId,
                callId,
                warnText: text3
              });
            },
            signal: ongoingToolCall.abortController.signal,
            // Call ID is used to match up life cycle events of the same tool call. In this case,
            // each call does not have different parts, thus call ID is useless. We can just use 0.
            // If the user wants a "unique" ID, they can just have variable that goes up by one
            // each time the function is called.
            callId: 0
          };
          (async () => {
            return await tool.implementation(message.parameters, toolCallContext);
          })().then((result) => {
            if (openSession.discarded) {
              return;
            }
            if (ongoingToolCall.settled) {
              return;
            }
            if (ongoingToolCall.abortController.signal.aborted) {
              return;
            }
            if (result === void 0) {
              result = "undefined";
              channel.send({
                type: "toolCallWarn",
                sessionId,
                callId,
                warnText: text`
                    Tool call returned undefined. This is not expected as the model always expects
                    a result. If you don't want to return anything, you can just return a string
                    reporting that the tool call was successful. For example: "operation
                    successful." In this case, we will give the model string "${result}".
                  `
              });
            }
            try {
              JSON.stringify(result);
            } catch (error) {
              result = text`
                  Error: Tool call completed but returned a value that cannot be serialized to JSON
                `;
              channel.send({
                type: "toolCallWarn",
                sessionId,
                callId,
                warnText: text`
                    Tool call succeeded, but returned a value that is not JSON serializable. In
                    order to provide the result to the model, return values of tools must be JSON
                    serializable. In this case, we will give the model string "${result}".
                  `
              });
            }
            channel.send({
              type: "toolCallComplete",
              sessionId,
              callId,
              result
            });
            ongoingToolCall.settled = true;
            openSession.ongoingToolCalls.delete(callId);
          }, (error) => {
            if (openSession.discarded) {
              return;
            }
            if (ongoingToolCall.settled) {
              return;
            }
            if (ongoingToolCall.abortController.signal.aborted) {
              return;
            }
            channel.send({
              type: "toolCallError",
              sessionId,
              callId,
              error: serializeError(error)
            });
            ongoingToolCall.settled = true;
            openSession.ongoingToolCalls.delete(callId);
          });
          break;
        }
        case "abortToolCall": {
          const sessionId = message.sessionId;
          const callId = message.callId;
          const openSession = openSessions.get(sessionId);
          if (openSession === void 0) {
            return;
          }
          const ongoingToolCall = openSession.ongoingToolCalls.get(callId);
          if (ongoingToolCall === void 0) {
            return;
          }
          ongoingToolCall.settled = true;
          ongoingToolCall.abortController.abort();
          openSession.ongoingToolCalls.delete(callId);
          break;
        }
        default: {
          const exhaustiveCheck = messageType;
          throw new Error(`Unexpected message type: ${exhaustiveCheck}`);
        }
      }
    });
  }
  /**
   * Sets the generator to be used by the plugin represented by this client.
   *
   * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the
   * future without warning.
   */
  setGenerator(generator) {
    const stack = getCurrentStack(1);
    this.validator.validateMethodParamOrThrow("plugins", "setGenerator", "generator", generatorSchema, generator, stack);
    const logger2 = new SimpleLogger(`Generator`, this.rootLogger);
    logger2.info("Register with LM Studio");
    const tasks = /* @__PURE__ */ new Map();
    const channel = this.port.createChannel("setGenerator", void 0, (message) => {
      const messageType = message.type;
      switch (messageType) {
        case "generate": {
          const taskLogger = new SimpleLogger(`Request (${message.taskId.substring(0, 6)})`, logger2);
          taskLogger.info(`New generate request received.`);
          const abortController = new AbortController();
          const connector = new GeneratorConnectorImpl(channel, message.taskId);
          const controller = new GeneratorController(this.client, message.pluginConfig, message.globalPluginConfig, message.workingDirectoryPath, abortController.signal, message.toolDefinitions, connector, this.validator);
          tasks.set(message.taskId, {
            cancel: () => {
              abortController.abort();
            },
            taskLogger
          });
          const history = Chat3.createRaw(message.input, false);
          generator(controller, history).then((result) => {
            if (result !== void 0) {
              taskLogger.warnText`
                    The generator has returned a value. This it not expected. You should report
                    generated content using method on the controller. The returned value will be
                    ignored.
                  `;
            }
            channel.send({
              type: "complete",
              taskId: message.taskId
            });
          }, (error) => {
            if (error.name === "AbortError") {
              taskLogger.info(`Request successfully aborted.`);
              channel.send({
                type: "aborted",
                taskId: message.taskId
              });
            } else {
              channel.send({
                type: "error",
                taskId: message.taskId,
                error: serializeError(error)
              });
              taskLogger.warn(`Generation failed.`, error);
            }
          }).finally(() => {
            tasks.delete(message.taskId);
          });
          break;
        }
        case "abort": {
          const task = tasks.get(message.taskId);
          if (task !== void 0) {
            task.taskLogger.info(`Received abort request.`);
            task.cancel();
            tasks.delete(message.taskId);
          }
          break;
        }
        default: {
          const exhaustiveCheck = messageType;
          throw new Error(`Unexpected message type: ${exhaustiveCheck}`);
        }
      }
    });
  }
  /**
   * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the
   * future without warning.
   */
  async initCompleted() {
    const stack = getCurrentStack(1);
    await this.port.callRpc("pluginInitCompleted", void 0, { stack });
  }
};
var __addDisposableResource = globalThis && globalThis.__addDisposableResource || function(env, value, async) {
  if (value !== null && value !== void 0) {
    if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
    var dispose, inner2;
    if (async) {
      if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
      dispose = value[Symbol.asyncDispose];
    }
    if (dispose === void 0) {
      if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
      dispose = value[Symbol.dispose];
      if (async) inner2 = dispose;
    }
    if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
    if (inner2) dispose = function() {
      try {
        inner2.call(this);
      } catch (e9) {
        return Promise.reject(e9);
      }
    };
    env.stack.push({ value, dispose, async });
  } else if (async) {
    env.stack.push({ async: true });
  }
  return value;
};
var __disposeResources = globalThis && globalThis.__disposeResources || /* @__PURE__ */ (function(SuppressedError2) {
  return function(env) {
    function fail(e9) {
      env.error = env.hasError ? new SuppressedError2(e9, env.error, "An error was suppressed during disposal.") : e9;
      env.hasError = true;
    }
    var r8, s6 = 0;
    function next() {
      while (r8 = env.stack.pop()) {
        try {
          if (!r8.async && s6 === 1) return s6 = 0, env.stack.push(r8), Promise.resolve().then(next);
          if (r8.dispose) {
            var result = r8.dispose.call(r8.value);
            if (r8.async) return s6 |= 2, Promise.resolve(result).then(next, function(e9) {
              fail(e9);
              return next();
            });
          } else s6 |= 1;
        } catch (e9) {
          fail(e9);
        }
      }
      if (s6 === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
      if (env.hasError) throw env.error;
    }
    return next();
  };
})(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
  var e9 = new Error(message);
  return e9.name = "SuppressedError", e9.error = error, e9.suppressed = suppressed, e9;
});
var SingleRemoteToolUseSession = class _SingleRemoteToolUseSession {
  static async create(pluginsPort, pluginIdentifier, pluginConfigSpecifier, logger2, stack) {
    const session = new _SingleRemoteToolUseSession(pluginsPort, pluginIdentifier, pluginConfigSpecifier, logger2);
    await session.init(stack);
    return session;
  }
  constructor(pluginsPort, pluginIdentifier, pluginConfigSpecifier, logger2) {
    this.pluginsPort = pluginsPort;
    this.pluginIdentifier = pluginIdentifier;
    this.pluginConfigSpecifier = pluginConfigSpecifier;
    this.logger = logger2;
    this.status = "initializing";
    this.poison = null;
    this.ongoingToolCalls = /* @__PURE__ */ new Map();
    this.callIdGiver = new IdGiver(0);
  }
  async init(stack) {
    const { promise: initPromise, resolve: resolveInit, reject: rejectInit } = makePromise();
    const channel = this.pluginsPort.createChannel("startToolUseSession", {
      pluginIdentifier: this.pluginIdentifier,
      pluginConfigSpecifier: this.pluginConfigSpecifier
    }, (message) => {
      const messageType = message.type;
      switch (messageType) {
        // Upon receiving session ready, mark self as ready and resolve the promise.
        case "sessionReady": {
          if (this.status !== "initializing") {
            this.logger.error("Received sessionReady message while not initializing");
            return;
          }
          this.status = "ready";
          resolveInit();
          this.tools = message.toolDefinitions.map((toolDefinition) => this.makeTool(toolDefinition));
          break;
        }
        case "toolCallComplete": {
          const ongoingCall = this.ongoingToolCalls.get(message.callId);
          if (ongoingCall === void 0) {
            return;
          }
          ongoingCall.resolve(message.result);
          break;
        }
        case "toolCallError": {
          const ongoingCall = this.ongoingToolCalls.get(message.callId);
          if (ongoingCall === void 0) {
            return;
          }
          ongoingCall.reject(fromSerializedError(message.error));
          break;
        }
        case "toolCallStatus": {
          const ongoingCall = this.ongoingToolCalls.get(message.callId);
          if (ongoingCall === void 0) {
            return;
          }
          ongoingCall.reportStatus(message.statusText);
          break;
        }
        case "toolCallWarn": {
          const ongoingCall = this.ongoingToolCalls.get(message.callId);
          if (ongoingCall === void 0) {
            return;
          }
          ongoingCall.reportWarning(message.warnText);
          break;
        }
        default: {
          const exhaustiveCheck = messageType;
          this.logger.warn(`Received unexpected message type in tool use session: ${exhaustiveCheck}`);
        }
      }
    }, { stack });
    channel.onError.subscribeOnce((error) => {
      if (this.status === "initializing") {
        rejectInit(error);
      } else {
        this.logger.error("Tool use session error.", error);
        this.poison = error;
      }
      for (const ongoingCall of this.ongoingToolCalls.values()) {
        ongoingCall.reject(error);
      }
      this.status = "disposed";
    });
    channel.onClose.subscribeOnce(() => {
      let error;
      if (this.status === "initializing") {
        error = new Error("Tool use session channel closed unexpectedly during initialization.");
        rejectInit(error);
      } else {
        error = new Error("Tool use session has already ended.");
        this.poison = error;
      }
      for (const ongoingCall of this.ongoingToolCalls.values()) {
        ongoingCall.reject(error);
      }
      this.status = "disposed";
    });
    this.channel = channel;
    await initPromise;
  }
  [Symbol.dispose]() {
    if (this.status !== "disposed") {
      this.channel.send({ type: "discardSession" });
      this.status = "disposed";
      const error = new Error("Session disposed by client.");
      for (const ongoingCall of this.ongoingToolCalls.values()) {
        ongoingCall.reject(error);
      }
      this.poison = error;
    }
  }
  makeTool(toolDefinition) {
    return internalCreateRemoteTool({
      name: toolDefinition.function.name,
      description: toolDefinition.function.description ?? "",
      pluginIdentifier: this.pluginIdentifier,
      parametersJsonSchema: toolDefinition.function.parameters ?? {},
      implementation: async (args, ctx) => {
        const env_1 = { stack: [], error: void 0, hasError: false };
        try {
          if (this.poison !== null) {
            throw this.poison;
          }
          if (ctx.signal.aborted) {
            throw ctx.signal.reason;
          }
          const callId = this.callIdGiver.next();
          const { promise, resolve, reject } = makePromise();
          const cleaner = __addDisposableResource(env_1, new Cleaner(), false);
          this.ongoingToolCalls.set(callId, {
            callId,
            resolve,
            reject,
            reportStatus: (status) => ctx.status(status),
            reportWarning: (warning) => ctx.warn(warning)
          });
          cleaner.register(() => {
            this.ongoingToolCalls.delete(callId);
          });
          this.channel.send({
            type: "callTool",
            callId,
            name: toolDefinition.function.name,
            arguments: args
          });
          ctx.signal.addEventListener("abort", () => {
            if (this.status === "disposed") {
              return;
            }
            this.channel.send({
              type: "abortToolCall",
              callId
            });
            reject(ctx.signal.reason);
          }, { once: true });
          return await promise;
        } catch (e_1) {
          env_1.error = e_1;
          env_1.hasError = true;
        } finally {
          __disposeResources(env_1);
        }
      }
    });
  }
};
var MultiRemoteToolUseSession = class _MultiRemoteToolUseSession {
  static async createUsingPredictionProcess(pluginsPort, pluginIdentifiers, predictionContextIdentifier, token, logger2, stack) {
    const results = await Promise.allSettled(pluginIdentifiers.map((pluginIdentifier) => SingleRemoteToolUseSession.create(pluginsPort, pluginIdentifier, {
      type: "predictionProcess",
      pci: predictionContextIdentifier,
      token
    }, logger2, stack)));
    const failed = results.filter((result) => result.status === "rejected");
    if (failed.length > 0) {
      for (const result of results) {
        if (result.status === "fulfilled") {
          try {
            result.value[Symbol.dispose]();
          } catch (error) {
            logger2.error("Failed to dispose a session after initialization failure.", error);
          }
        }
      }
      throw new AggregateError(failed.map((result) => result.reason), "Failed to initialize some tool use sessions.");
    }
    return new _MultiRemoteToolUseSession(results.map((result) => result.value), logger2);
  }
  constructor(sessions, logger2) {
    this.sessions = sessions;
    this.logger = logger2;
    this.tools = [];
    this.tools = sessions.flatMap((session) => session.tools);
  }
  [Symbol.dispose]() {
    for (const session of this.sessions) {
      try {
        session[Symbol.dispose]();
      } catch (error) {
        this.logger.error("Failed to dispose a session.", error);
      }
    }
  }
};
var pluginToolsOptsSchema = external_exports.object({
  pluginConfig: kvConfigSchema.optional(),
  workingDirectory: external_exports.string().optional()
});
var registerDevelopmentPluginOptsSchema = external_exports.object({
  manifest: pluginManifestSchema
});
var PluginsNamespace = class {
  /** @internal */
  constructor(port, client, validator2, parentLogger, rootLogger) {
    this.port = port;
    this.client = client;
    this.validator = validator2;
    this.rootLogger = rootLogger;
    this.logger = new SimpleLogger("Plugins", parentLogger);
  }
  /**
   * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the
   * future without warning.
   */
  async registerDevelopmentPlugin(opts) {
    const stack = getCurrentStack(1);
    this.validator.validateMethodParamOrThrow("plugins", "registerDevelopmentPlugin", "opts", registerDevelopmentPluginOptsSchema, opts, stack);
    const { promise, resolve } = makePromise();
    const channel = this.port.createChannel("registerDevelopmentPlugin", opts, (message) => {
      if (message.type === "ready") {
        resolve({
          clientIdentifier: message.clientIdentifier,
          clientPasskey: message.clientPasskey
        });
      }
    }, { stack });
    let unregisterCalled = false;
    const unregister = async () => {
      if (unregisterCalled) {
        return;
      }
      unregisterCalled = true;
      channel.send({ type: "end" });
      const { promise: promise2, resolve: resolve2 } = makePromise();
      channel.onClose.subscribeOnce(resolve2);
      await promise2;
    };
    const base = await promise;
    return {
      ...base,
      unregister
    };
  }
  /**
   * Requests LM Studio to reindex all the plugins.
   *
   * CAVEAT: Currently, we do not wait for the reindex to complete before returning. In the future,
   * we will change this behavior and only return after the reindex is completed.
   *
   * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the
   * future without warning.
   */
  async reindexPlugins() {
    const stack = getCurrentStack(1);
    await this.port.callRpc("reindexPlugins", void 0, { stack });
  }
  /**
   * If this client is currently running as a plugin, get the self registration host which can be
   * used to register hooks.
   *
   * @deprecated This method is used by plugins internally to register hooks. Do not use directly.
   */
  getSelfRegistrationHost() {
    return new PluginSelfRegistrationHost(this.port, this.client, this.rootLogger, this.validator);
  }
  /**
   * Starts a tool use session use any config specifier.
   */
  async internalStartToolUseSession(pluginIdentifier, pluginConfigSpecifier, _stack) {
    return await SingleRemoteToolUseSession.create(this.port, pluginIdentifier, pluginConfigSpecifier, this.logger);
  }
  /**
   * Start a tool use session with a plugin. Note, this method must be used with "Explicit Resource
   * Management". That is, you should use it like so:
   *
   * ```typescript
   * using pluginTools = await client.plugins.pluginTools("owner/name", { ... });
   * // ^ Notice the `using` keyword here.
   * ```
   *
   * If you do not use `using`, you must call `pluginTools[Symbol.dispose]()` after you are done.
   * Otherwise, there will be a memory leak and the plugins you requested tools from will be loaded
   * indefinitely.
   *
   * @experimental [EXP-USE-USE-PLUGIN-TOOLS] Using tools from other applications is still in
   * development. This may change in the future without warning.
   */
  async pluginTools(pluginIdentifier, opts = {}) {
    const stack = getCurrentStack(1);
    [pluginIdentifier, opts] = this.validator.validateMethodParamsOrThrow("plugins", "pluginTools", ["pluginIdentifier", "opts"], [artifactIdentifierSchema, pluginToolsOptsSchema], [pluginIdentifier, opts], stack);
    return await this.internalStartToolUseSession(pluginIdentifier, {
      type: "direct",
      config: opts.pluginConfig ?? emptyKVConfig,
      workingDirectoryPath: opts.workingDirectory
    });
  }
  /**
   * Start a tool use session associated with a prediction process.
   *
   * This method is used internally by processing controllers and will be stripped by the internal
   * tag.
   *
   * @internal
   */
  async startToolUseSessionUsingPredictionProcess(pluginIdentifiers, predictionContextIdentifier, token, stack) {
    return await MultiRemoteToolUseSession.createUsingPredictionProcess(this.port, pluginIdentifiers, predictionContextIdentifier, token, this.logger, stack);
  }
  /**
   * @experimental [EXP-GEN-PREDICT] Using generator plugins programmatically is still in
   * development. This may change in the future without warning.
   */
  createGeneratorHandle(pluginIdentifier) {
    return new LLMGeneratorHandle(this.port, pluginIdentifier, this.validator, null, this.logger);
  }
  /**
   * Creates a generator handle that is already associated with a prediction process.
   *
   * This method is used internally by the processing controllers to create generator handles. It is
   * marked as internal and will be stripped.
   *
   * @internal
   */
  createGeneratorHandleAssociatedWithPredictionProcess(pluginIdentifier, predictionContextIdentifier, token) {
    return new LLMGeneratorHandle(this.port, pluginIdentifier, this.validator, { pci: predictionContextIdentifier, token }, this.logger);
  }
};
var artifactDownloadPlannerDownloadOptsSchema = external_exports.object({
  onStartFinalizing: external_exports.function().optional(),
  onProgress: external_exports.function().optional(),
  signal: external_exports.instanceof(AbortSignal).optional()
});
var ArtifactDownloadPlanner = class {
  /**
   * @internal Do not construct this class yourself.
   */
  constructor(owner, name, onPlanUpdated, channel, validator2, onDisposed) {
    this.owner = owner;
    this.name = name;
    this.onPlanUpdated = onPlanUpdated;
    this.channel = channel;
    this.validator = validator2;
    this.onDisposed = onDisposed;
    this.readyDeferredPromise = makePromise();
    this.isReadyBoolean = false;
    this.currentDownload = null;
    this.errorReceivedBeforeDownloadStart = null;
    this.logger = new SimpleLogger(`ArtifactDownloadPlanner(${owner}/${name})`);
    this.readyDeferredPromise.promise.catch(() => {
    });
    this.planValue = {
      nodes: [
        {
          type: "artifact",
          owner,
          name,
          state: "pending",
          dependencyNodes: []
        }
      ],
      downloadSizeBytes: 0
    };
    this.channel.onMessage.subscribe((message) => {
      const messageType = message.type;
      switch (messageType) {
        case "planReady": {
          this.isReadyBoolean = true;
          this.readyDeferredPromise.resolve();
          this.planValue = message.plan;
          break;
        }
        case "planUpdated": {
          this.planValue = message.plan;
          safeCallCallback(this.logger, "onPlanUpdated", this.onPlanUpdated, [message.plan]);
          break;
        }
        case "success": {
          if (this.currentDownload === null) {
            throw new Error("Unexpected: received success message without a download.");
          }
          this.currentDownload.downloadFinished();
          break;
        }
        case "downloadProgress": {
          if (this.currentDownload === null) {
            throw new Error("Unexpected: received progress message without a download.");
          }
          this.currentDownload.progressUpdate(message.update);
          break;
        }
        case "startFinalizing": {
          if (this.currentDownload === null) {
            throw new Error("Unexpected: received startFinalizing message without a download.");
          }
          this.currentDownload.startFinalizing();
          break;
        }
      }
    });
    this.channel.onError.subscribeOnce((error) => {
      if (this.currentDownload === null) {
        this.errorReceivedBeforeDownloadStart = error;
        this.readyDeferredPromise.reject(error);
      } else {
        this.currentDownload.downloadFailed(error);
      }
    });
  }
  [Symbol.dispose]() {
    this.channel.send({ type: "cancel" });
    this.onDisposed();
  }
  isReady() {
    return this.isReadyBoolean;
  }
  async untilReady() {
    return await this.readyDeferredPromise.promise;
  }
  getPlan() {
    return this.planValue;
  }
  /**
   * Download this artifact. `download` can only be called once.
   */
  async download(opts) {
    const stack = getCurrentStack(1);
    opts = this.validator.validateMethodParamOrThrow("ArtifactDownloadPlanner", "download", "opts", artifactDownloadPlannerDownloadOptsSchema, opts, stack);
    const { onProgress, onStartFinalizing, signal = new AbortController().signal } = opts;
    if (this.currentDownload !== null) {
      throw new Error("You can only call `download` once for each planner.");
    }
    if (this.errorReceivedBeforeDownloadStart !== null) {
      const error = this.errorReceivedBeforeDownloadStart;
      this.errorReceivedBeforeDownloadStart = null;
      throw error;
    }
    const { promise, resolve, reject } = makePromise();
    this.currentDownload = {
      downloadFinished: () => {
        resolve();
      },
      startFinalizing: () => {
        safeCallCallback(this.logger, "onStartFinalizing", onStartFinalizing, []);
      },
      progressUpdate: (update) => {
        safeCallCallback(this.logger, "onProgress", onProgress, [update]);
      },
      downloadFailed: (error) => {
        reject(error);
      }
    };
    this.channel.send({ type: "commit" });
    if (signal.aborted) {
      this.channel.send({ type: "cancel" });
    } else {
      signal.addEventListener("abort", () => {
        this.channel.send({ type: "cancel" });
      });
    }
    return await promise.catch((error) => {
      if (signal.aborted) {
        throw signal.reason;
      } else {
        throw error;
      }
    });
  }
};
var downloadOptsSchema = external_exports.object({
  onProgress: external_exports.function().optional(),
  onStartFinalizing: external_exports.function().optional(),
  signal: external_exports.instanceof(AbortSignal).optional()
});
var ModelSearchResultDownloadOption = class {
  /** @internal */
  constructor(repositoryPort, validator2, logger2, data) {
    this.repositoryPort = repositoryPort;
    this.validator = validator2;
    this.logger = logger2;
    this.data = data;
    this.quantization = data.quantization;
    this.name = data.name;
    this.sizeBytes = data.sizeBytes;
    this.fitEstimation = this.data.fitEstimation;
    this.indexedModelIdentifier = this.data.indexedModelIdentifier;
  }
  isRecommended() {
    return this.data.recommended ?? false;
  }
  /**
   * Download the model. Returns the model key which can be used to load the model.
   */
  async download(opts = {}) {
    const stack = getCurrentStack(1);
    this.validator.validateMethodParamOrThrow("ModelSearchResultDownloadOption", "download", "opts", downloadOptsSchema, opts, stack);
    const { promise, resolve, reject } = makePromise();
    const channel = this.repositoryPort.createChannel("downloadModel", {
      downloadIdentifier: this.data.downloadIdentifier
    }, (message) => {
      switch (message.type) {
        case "downloadProgress": {
          safeCallCallback(this.logger, "onProgress", opts.onProgress, [message.update]);
          break;
        }
        case "startFinalizing": {
          safeCallCallback(this.logger, "onStartFinalizing", opts.onStartFinalizing, []);
          break;
        }
        case "success": {
          resolve(message.defaultIdentifier);
          break;
        }
        default: {
          const exhaustiveCheck = message;
          throw new Error(`Unexpected message type: ${exhaustiveCheck}`);
        }
      }
    }, { stack });
    channel.onError.subscribeOnce((error) => {
      if (opts.signal?.aborted) {
        reject(opts.signal.reason);
      } else {
        reject(error);
      }
    });
    channel.onClose.subscribeOnce(() => {
      if (opts.signal?.aborted) {
        reject(opts.signal.reason);
      } else {
        reject(new Error("Channel closed unexpectedly."));
      }
    });
    const abortListener = () => {
      channel.send({ type: "cancel" });
    };
    opts.signal?.addEventListener("abort", abortListener);
    promise.finally(() => {
      opts.signal?.removeEventListener("abort", abortListener);
    });
    return await promise;
  }
};
var ModelSearchResultEntry = class {
  /**
   * @internal
   */
  constructor(repositoryPort, validator2, logger2, data) {
    this.repositoryPort = repositoryPort;
    this.validator = validator2;
    this.logger = logger2;
    this.data = data;
    this.name = data.name;
  }
  isExactMatch() {
    return this.data.exact ?? false;
  }
  isStaffPick() {
    return this.data.staffPick ?? false;
  }
  async getDownloadOptions() {
    const { results } = await this.repositoryPort.callRpc("getModelDownloadOptions", {
      modelSearchResultIdentifier: this.data.identifier
    });
    return results.map((data) => new ModelSearchResultDownloadOption(this.repositoryPort, this.validator, this.logger, data));
  }
};
var downloadArtifactOptsSchema = external_exports.object({
  owner: external_exports.string(),
  name: external_exports.string(),
  revisionNumber: external_exports.number(),
  path: external_exports.string(),
  onProgress: external_exports.function().optional(),
  onStartFinalizing: external_exports.function().optional(),
  signal: external_exports.instanceof(AbortSignal).optional()
});
var pushArtifactOptsSchema = external_exports.object({
  path: external_exports.string(),
  description: external_exports.string().optional(),
  makePrivate: external_exports.boolean().optional(),
  writeRevision: external_exports.boolean().optional(),
  overrides: jsonSerializableSchema.optional(),
  onMessage: external_exports.function().optional()
});
var ensureAuthenticatedOptsSchema = external_exports.object({
  onAuthenticationUrl: external_exports.function()
});
var loginWithPreAuthenticatedKeysOptsSchema = external_exports.object({
  keyId: external_exports.string(),
  publicKey: external_exports.string(),
  privateKey: external_exports.string()
});
external_exports.object({
  userName: external_exports.string()
});
var createArtifactDownloadPlannerOptsSchema = external_exports.object({
  owner: external_exports.string(),
  name: external_exports.string(),
  onPlanUpdated: external_exports.function().optional()
});
var RepositoryNamespace = class {
  /** @internal */
  constructor(repositoryPort, validator2, parentLogger) {
    this.repositoryPort = repositoryPort;
    this.validator = validator2;
    this.downloadPlanFinalizationRegistry = new FinalizationRegistry(({ owner, name }) => {
      this.logger.warn(`
      A download plan for artifact ${owner}/${name} has been garbage collected without being
      disposed. Please make sure you are creating the download plan with the "using" keyword.

      This is a memory leak and needs to be fixed.
    `);
    });
    this.logger = new SimpleLogger("Repository", parentLogger);
  }
  async searchModels(opts) {
    const stack = getCurrentStack(1);
    opts = this.validator.validateMethodParamOrThrow("repository", "search", "opts", modelSearchOptsSchema, opts, stack);
    const { results } = await this.repositoryPort.callRpc("searchModels", { opts }, { stack });
    return results.map((data) => new ModelSearchResultEntry(this.repositoryPort, this.validator, this.logger, data));
  }
  /**
   * @deprecated [DEP-HUB-API-ACCESS] LM Studio Hub API access is still in active development. Stay
   * tuned for updates.
   */
  async installPluginDependencies(pluginFolder) {
    const stack = getCurrentStack(1);
    this.validator.validateMethodParamOrThrow("repository", "installPluginDependencies", "pluginFolder", external_exports.string(), pluginFolder, stack);
    await this.repositoryPort.callRpc("installPluginDependencies", { pluginFolder }, { stack });
  }
  /**
   * @deprecated [DEP-HUB-API-ACCESS] LM Studio Hub API access is still in active development. Stay
   * tuned for updates.
   */
  async downloadArtifact(opts) {
    const stack = getCurrentStack(1);
    this.validator.validateMethodParamOrThrow("client.repository", "downloadArtifact", "opts", downloadArtifactOptsSchema, opts, stack);
    const { owner, name, revisionNumber, path: path6, onProgress, onStartFinalizing, signal } = opts;
    const { promise, resolve, reject } = makePromise();
    const channel = this.repositoryPort.createChannel("downloadArtifact", { artifactOwner: owner, artifactName: name, revisionNumber, path: path6 }, (message) => {
      switch (message.type) {
        case "downloadProgress": {
          safeCallCallback(this.logger, "onProgress", onProgress, [message.update]);
          break;
        }
        case "startFinalizing": {
          safeCallCallback(this.logger, "onStartFinalizing", onStartFinalizing, []);
          break;
        }
        case "success": {
          resolve();
          break;
        }
        default: {
          const exhaustiveCheck = message;
          throw new Error(`Unexpected message type: ${exhaustiveCheck}`);
        }
      }
    }, { stack });
    channel.onError.subscribeOnce(reject);
    channel.onClose.subscribeOnce(() => {
      if (signal?.aborted) {
        reject(signal.reason);
      } else {
        reject(new Error("Channel closed unexpectedly."));
      }
    });
    const abortListener = () => {
      channel.send({ type: "cancel" });
    };
    signal?.addEventListener("abort", abortListener);
    promise.finally(() => {
      signal?.removeEventListener("abort", abortListener);
    });
    return await promise;
  }
  /**
   * @deprecated [DEP-HUB-API-ACCESS] LM Studio Hub API access is still in active development. Stay
   * tuned for updates.
   */
  async pushArtifact(opts) {
    const stack = getCurrentStack(1);
    const { path: path6, description, makePrivate, writeRevision, overrides, onMessage } = this.validator.validateMethodParamOrThrow("repository", "pushArtifact", "opts", pushArtifactOptsSchema, opts, stack);
    const channel = this.repositoryPort.createChannel("pushArtifact", { path: path6, description, makePrivate, writeRevision, overrides }, (message) => {
      const type = message.type;
      switch (type) {
        case "message": {
          safeCallCallback(this.logger, "onMessage", onMessage, [message.message]);
          break;
        }
        default: {
          const exhaustiveCheck = type;
          throw new Error(`Unexpected message type: ${exhaustiveCheck}`);
        }
      }
    }, { stack });
    const { promise, resolve, reject } = makePromise();
    channel.onError.subscribeOnce(reject);
    channel.onClose.subscribeOnce(resolve);
    await promise;
  }
  /**
   * @deprecated [DEP-HUB-API-ACCESS] LM Studio Hub API access is still in active development. Stay
   * tuned for updates.
   */
  async getLocalArtifactFileList(path6) {
    const stack = getCurrentStack(1);
    this.validator.validateMethodParamOrThrow("repository", "getLocalArtifactFileList", "path", external_exports.string(), path6, stack);
    const { fileList } = await this.repositoryPort.callRpc("getLocalArtifactFiles", { path: path6 }, { stack });
    return fileList;
  }
  /**
   * @deprecated [DEP-HUB-API-ACCESS] LM Studio Hub API access is still in active development. Stay
   * tuned for updates.
   */
  async ensureAuthenticated(opts) {
    const stack = getCurrentStack(1);
    this.validator.validateMethodParamOrThrow("repository", "ensureAuthenticated", "opts", ensureAuthenticatedOptsSchema, opts, stack);
    const { promise, resolve, reject } = makePromise();
    const channel = this.repositoryPort.createChannel("ensureAuthenticated", void 0, (message) => {
      const type = message.type;
      switch (type) {
        case "authenticationUrl": {
          safeCallCallback(this.logger, "onAuthenticationUrl", opts.onAuthenticationUrl, [
            message.url
          ]);
          break;
        }
        case "authenticated": {
          resolve();
          break;
        }
        default: {
          const exhaustiveCheck = type;
          throw new Error(`Unexpected message type: ${exhaustiveCheck}`);
        }
      }
    });
    channel.onError.subscribeOnce(reject);
    await promise;
  }
  async loginWithPreAuthenticatedKeys(opts) {
    const stack = getCurrentStack(1);
    this.validator.validateMethodParamOrThrow("repository", "loginWithPreAuthenticatedKeys", "opts", loginWithPreAuthenticatedKeysOptsSchema, opts, stack);
    const { keyId, publicKey, privateKey } = opts;
    const { userName } = await this.repositoryPort.callRpc("loginWithPreAuthenticatedKeys", { keyId, publicKey, privateKey }, { stack });
    return { userName };
  }
  /**
   * @deprecated [DEP-HUB-API-ACCESS] LM Studio Hub API access is still in active development. Stay
   * tuned for updates.
   */
  createArtifactDownloadPlanner(opts) {
    const { owner, name, onPlanUpdated } = this.validator.validateMethodParamOrThrow("repository", "createArtifactDownloadPlanner", "opts", createArtifactDownloadPlannerOptsSchema, opts);
    const stack = getCurrentStack(1);
    const channel = this.repositoryPort.createChannel(
      "createArtifactDownloadPlan",
      { owner, name },
      void 0,
      // Don't listen to the messages yet.
      { stack }
    );
    const planner = new ArtifactDownloadPlanner(owner, name, onPlanUpdated, channel, this.validator, () => {
      this.downloadPlanFinalizationRegistry.unregister(planner);
    });
    this.downloadPlanFinalizationRegistry.register(planner, { owner, name }, planner);
    return planner;
  }
};
var startHttpServerOptsSchema = external_exports.object({
  port: external_exports.number().int().min(1).max(65535).describe("Port to run the API server on. Must be between 1 and 65535."),
  cors: external_exports.boolean().describe("Enable CORS on the API server. Allows any website to access the server.")
});
var SystemNamespace = class {
  /** @internal */
  constructor(systemPort, validator2, parentLogger) {
    this.systemPort = systemPort;
    this.validator = validator2;
    this.logger = new SimpleLogger("System", parentLogger);
  }
  async listDownloadedModels(domain) {
    const stack = getCurrentStack(1);
    domain = this.validator.validateMethodParamOrThrow("client.system", "listDownloadedModels", "domain", external_exports.union([external_exports.literal("llm"), external_exports.literal("embedding"), external_exports.undefined()]), domain, stack);
    const models2 = await this.systemPort.callRpc("listDownloadedModels", void 0, {
      stack: getCurrentStack(1)
    });
    if (domain === void 0) {
      return models2;
    }
    return models2.filter((model) => model.type === domain);
  }
  async whenDisconnected() {
    const stack = getCurrentStack(1);
    const channel = this.systemPort.createChannel("alive", void 0, void 0, { stack });
    const { promise, resolve } = makePromise();
    channel.onError.subscribeOnce(resolve);
    channel.onClose.subscribeOnce(resolve);
    await promise;
  }
  async notify(notification) {
    const stack = getCurrentStack(1);
    notification = this.validator.validateMethodParamOrThrow("client.system", "notify", "notification", backendNotificationSchema, notification, stack);
    await this.systemPort.callRpc("notify", notification, { stack });
  }
  async getLMStudioVersion() {
    const stack = getCurrentStack(1);
    return await this.systemPort.callRpc("version", void 0, { stack });
  }
  /**
   * Sets an experiment flags for LM Studio. This is an unstable API and may change without notice.
   *
   * @experimental
   */
  async unstable_setExperimentFlag(flag, value) {
    const stack = getCurrentStack(1);
    [flag, value] = this.validator.validateMethodParamsOrThrow("client.system", "setExperimentFlag", ["flag", "value"], [external_exports.string(), external_exports.boolean()], [flag, value], stack);
    await this.systemPort.callRpc("setExperimentFlag", { code: flag, value }, { stack });
  }
  /**
   * Gets all experiment flags for LM Studio. This is an unstable API and may change without notice.
   *
   * @experimental
   */
  async unstable_getExperimentFlags() {
    const stack = getCurrentStack(1);
    return await this.systemPort.callRpc("getExperimentFlags", void 0, { stack });
  }
  /**
   * Starts the API server on the specified port.
   *
   * @experimental
   */
  async startHttpServer(opts) {
    const stack = getCurrentStack(1);
    opts = this.validator.validateMethodParamOrThrow("client.system", "startHttpServer", "args", startHttpServerOptsSchema, opts);
    return await this.systemPort.callRpc("startHttpServer", { port: opts.port, cors: opts.cors }, {
      stack
    });
  }
  /**
   * Stops the API server if it is running.
   *
   * @experimental
   */
  async stopHttpServer() {
    const stack = getCurrentStack(1);
    return await this.systemPort.callRpc("stopHttpServer", void 0, { stack });
  }
};
var constructorOptsSchema = external_exports.object({
  logger: external_exports.any().optional(),
  baseUrl: external_exports.string().optional(),
  verboseErrorMessages: external_exports.boolean().optional(),
  clientIdentifier: external_exports.string().optional(),
  clientPasskey: external_exports.string().optional(),
  // Internal testing options
  disableConnection: external_exports.boolean().optional(),
  llmPort: external_exports.any().optional(),
  embeddingPort: external_exports.any().optional(),
  systemPort: external_exports.any().optional(),
  diagnosticsPort: external_exports.any().optional(),
  retrievalPort: external_exports.any().optional(),
  filesPort: external_exports.any().optional(),
  repositoryPort: external_exports.any().optional(),
  pluginsPort: external_exports.any().optional()
}).strict();
var LMStudioClient = class {
  /** @internal */
  validateBaseUrlOrThrow(baseUrl) {
    let url;
    try {
      url = new URL(baseUrl);
    } catch (e9) {
      this.logger.throw(text`
        Failed to construct LMStudioClient. The baseUrl passed in is invalid. Received: ${baseUrl}
      `);
    }
    if (!["ws:", "wss:"].includes(url.protocol)) {
      this.logger.throw(text`
        Failed to construct LMStudioClient. The baseUrl passed in must have protocol "ws" or "wss". 
        Received: ${baseUrl}
      `);
    }
    if (url.search !== "") {
      this.logger.throw(text`
        Failed to construct LMStudioClient. The baseUrl passed contains search parameters
        ("${url.search}").
      `);
    }
    if (url.hash !== "") {
      this.logger.throw(text`
        Failed to construct LMStudioClient. The baseUrl passed contains a hash ("${url.hash}").
      `);
    }
    if (url.username !== "" || url.password !== "") {
      this.logger.throw(text`
        Failed to construct LMStudioClient. The baseUrl passed contains a username or password. We
        do not support these in the baseUrl. Received: ${baseUrl}
      `);
    }
    if (baseUrl.endsWith("/")) {
      this.logger.throw(text`
        Failed to construct LMStudioClient. The baseUrl passed in must not end with a "/". If you
        are reverse-proxying, you should remove the trailing slash from the baseUrl. Received:
        ${baseUrl}
      `);
    }
  }
  async isLocalhostWithGivenPortLMStudioServer(port) {
    const response = await fetch(`http://127.0.0.1:${port}/lmstudio-greeting`);
    if (response.status !== 200) {
      throw new Error("Status is not 200.");
    }
    const json2 = await response.json();
    if (json2?.lmstudio !== true) {
      throw new Error("Not an LM Studio server.");
    }
    return port;
  }
  /**
   * Guess the base URL of the LM Studio server by visiting localhost on various default ports.
   */
  async guessBaseUrl(stack) {
    if (getHostedEnv() !== null) {
      return Promise.resolve("Using hosted env");
    }
    if (process_shim_default.browser) {
      try {
        this.isLocalhostWithGivenPortLMStudioServer(1234);
        return "ws://127.0.0.1:1234";
      } catch (error) {
        text`
          ${import_chalk.default.redBright("Failed to connect to LM Studio.")}

          Is LM Studio running? If not, please start it by running:

              ${import_chalk.default.yellow("lms server start --cors")}

          If you are attempting to connect to LM Studio on a separate machine, please provide the
          baseUrl option when creating the LMStudioClient:

              ${import_chalk.default.blueBright(text`
                const client = new LMStudioClient({ baseUrl: 'ws://<host_name>:<port>' });
              `)}

          ${import_chalk.default.white("(i) For more information, refer to the LM Studio documentation:")}

              ${import_chalk.default.gray("https://lmstudio.ai/docs/local-server")}
        `;
      }
    }
    return Promise.any(apiServerPorts.map(this.isLocalhostWithGivenPortLMStudioServer)).then((port) => `ws://127.0.0.1:${port}`, () => {
      throw makePrettyError(text`
            ${import_chalk.default.redBright("Failed to connect to LM Studio.")}

            Please make sure LM Studio is running on your machine.
            
            If you are attempting to connect to LM Studio on a separate machine, please provide the
            baseUrl option when creating the LMStudioClient:

                ${import_chalk.default.blueBright(text`
                  const client = new LMStudioClient({ baseUrl: 'ws://<host_name>:<port>' });
                `)}

            ${import_chalk.default.white("(i) For more information, refer to the LM Studio documentation:")}

                ${import_chalk.default.gray("https://lmstudio.ai/docs/local-server")}
          `, stack);
    });
  }
  createPort(namespace, name, backendInterface) {
    return createAuthenticatedClientPort(backendInterface, this.resolvingBaseUrl, namespace, this.clientIdentifier, this.clientPasskey, new SimpleLogger(name, this.logger), {
      errorDeserializer: friendlyErrorDeserializer,
      verboseErrorMessage: this.verboseErrorMessages
    });
  }
  constructor(opts = {}) {
    const { logger: logger2, baseUrl, verboseErrorMessages, clientIdentifier, clientPasskey, disableConnection, llmPort, embeddingPort, systemPort, diagnosticsPort, retrievalPort, filesPort, repositoryPort, pluginsPort } = new Validator().validateConstructorParamOrThrow("LMStudioClient", "opts", constructorOptsSchema, opts);
    if (globalThis.__LMS_PLUGIN_CONTEXT && opts.baseUrl === void 0) {
      throw new Error(text`
          You cannot create a local LMStudioClient in a plugin context. To use LM Studio APIs, use
          the "client" property attached to the Controllers.

          For example, instead of:

          ${"const client = new LMStudioClient(); // <-- Error\nexport async function generate(ctl: GeneratorController) {\n  const model = await client.llm.model(...);\n}"}

          Do this:
            
          ${"export async function generate(ctl: GeneratorController) {\n  const model = await ctl.client.llm.model(...);\n}"}

          If you need to connect to a remote LM Studio, you should pass in the \`baseUrl\` option to
          the LMStudioClient constructor:

          ${"const client = new LMStudioClient({ baseUrl: 'ws://<host_name>:<port>' });"}
        `);
    }
    this.logger = new SimpleLogger("LMStudioClient", logger2);
    this.clientIdentifier = clientIdentifier ?? (0, import_lms_isomorphic.generateRandomBase64)(18);
    this.clientPasskey = clientPasskey ?? (0, import_lms_isomorphic.generateRandomBase64)(18);
    const stack = getCurrentStack(1);
    if (disableConnection) {
      this.resolvingBaseUrl = new Promise(() => void 0);
    } else {
      if (baseUrl === void 0) {
        this.resolvingBaseUrl = this.guessBaseUrl(verboseErrorMessages ? stack : void 0);
      } else {
        this.validateBaseUrlOrThrow(baseUrl);
        this.resolvingBaseUrl = baseUrl;
      }
    }
    this.verboseErrorMessages = verboseErrorMessages ?? true;
    this.llmPort = llmPort ?? this.createPort("llm", "LLM", createLlmBackendInterface());
    this.embeddingPort = embeddingPort ?? this.createPort("embedding", "Embedding", createEmbeddingBackendInterface());
    this.systemPort = systemPort ?? this.createPort("system", "System", createSystemBackendInterface());
    this.diagnosticsPort = diagnosticsPort ?? this.createPort("diagnostics", "Diagnostics", createDiagnosticsBackendInterface());
    this.filesPort = filesPort ?? this.createPort("files", "Files", createFilesBackendInterface());
    this.repositoryPort = repositoryPort ?? this.createPort("repository", "Repository", createRepositoryBackendInterface());
    this.pluginsPort = pluginsPort ?? this.createPort("plugins", "Plugins", createPluginsBackendInterface());
    const validator2 = new Validator();
    this.llm = new LLMNamespace(this, this.llmPort, new SimpleLogger("LLM", this.logger), validator2);
    this.embedding = new EmbeddingNamespace(this, this.embeddingPort, new SimpleLogger("Embedding", this.logger), validator2);
    this.system = new SystemNamespace(this.systemPort, validator2, this.logger);
    this.diagnostics = new DiagnosticsNamespace(this.diagnosticsPort, validator2, this.logger);
    this.files = new FilesNamespace(this.filesPort, validator2, this.logger);
    this.repository = new RepositoryNamespace(this.repositoryPort, validator2, this.logger);
    this.plugins = new PluginsNamespace(this.pluginsPort, this, validator2, this.logger, logger2);
  }
  async [Symbol.asyncDispose]() {
    await Promise.all([
      this.llmPort[Symbol.asyncDispose](),
      this.embeddingPort[Symbol.asyncDispose](),
      this.systemPort[Symbol.asyncDispose](),
      this.diagnosticsPort[Symbol.asyncDispose](),
      this.filesPort[Symbol.asyncDispose](),
      this.repositoryPort[Symbol.asyncDispose](),
      this.pluginsPort[Symbol.asyncDispose]()
    ]);
  }
};

// ../pi-mono/node_modules/ollama/dist/browser.mjs
init_process_shim();

// ../pi-mono/node_modules/whatwg-fetch/fetch.js
init_process_shim();
var g2 = typeof globalThis !== "undefined" && globalThis || typeof self !== "undefined" && self || // eslint-disable-next-line no-undef
typeof globalThis !== "undefined" && globalThis || {};
var support = {
  searchParams: "URLSearchParams" in g2,
  iterable: "Symbol" in g2 && "iterator" in Symbol,
  blob: "FileReader" in g2 && "Blob" in g2 && (function() {
    try {
      new Blob();
      return true;
    } catch (e9) {
      return false;
    }
  })(),
  formData: "FormData" in g2,
  arrayBuffer: "ArrayBuffer" in g2
};
function isDataView(obj) {
  return obj && DataView.prototype.isPrototypeOf(obj);
}
if (support.arrayBuffer) {
  viewClasses = [
    "[object Int8Array]",
    "[object Uint8Array]",
    "[object Uint8ClampedArray]",
    "[object Int16Array]",
    "[object Uint16Array]",
    "[object Int32Array]",
    "[object Uint32Array]",
    "[object Float32Array]",
    "[object Float64Array]"
  ];
  isArrayBufferView = ArrayBuffer.isView || function(obj) {
    return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1;
  };
}
var viewClasses;
var isArrayBufferView;
function normalizeName(name) {
  if (typeof name !== "string") {
    name = String(name);
  }
  if (/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(name) || name === "") {
    throw new TypeError('Invalid character in header field name: "' + name + '"');
  }
  return name.toLowerCase();
}
function normalizeValue(value) {
  if (typeof value !== "string") {
    value = String(value);
  }
  return value;
}
function iteratorFor(items) {
  var iterator = {
    next: function() {
      var value = items.shift();
      return { done: value === void 0, value };
    }
  };
  if (support.iterable) {
    iterator[Symbol.iterator] = function() {
      return iterator;
    };
  }
  return iterator;
}
function Headers2(headers) {
  this.map = {};
  if (headers instanceof Headers2) {
    headers.forEach(function(value, name) {
      this.append(name, value);
    }, this);
  } else if (Array.isArray(headers)) {
    headers.forEach(function(header) {
      if (header.length != 2) {
        throw new TypeError("Headers constructor: expected name/value pair to be length 2, found" + header.length);
      }
      this.append(header[0], header[1]);
    }, this);
  } else if (headers) {
    Object.getOwnPropertyNames(headers).forEach(function(name) {
      this.append(name, headers[name]);
    }, this);
  }
}
Headers2.prototype.append = function(name, value) {
  name = normalizeName(name);
  value = normalizeValue(value);
  var oldValue = this.map[name];
  this.map[name] = oldValue ? oldValue + ", " + value : value;
};
Headers2.prototype["delete"] = function(name) {
  delete this.map[normalizeName(name)];
};
Headers2.prototype.get = function(name) {
  name = normalizeName(name);
  return this.has(name) ? this.map[name] : null;
};
Headers2.prototype.has = function(name) {
  return this.map.hasOwnProperty(normalizeName(name));
};
Headers2.prototype.set = function(name, value) {
  this.map[normalizeName(name)] = normalizeValue(value);
};
Headers2.prototype.forEach = function(callback, thisArg) {
  for (var name in this.map) {
    if (this.map.hasOwnProperty(name)) {
      callback.call(thisArg, this.map[name], name, this);
    }
  }
};
Headers2.prototype.keys = function() {
  var items = [];
  this.forEach(function(value, name) {
    items.push(name);
  });
  return iteratorFor(items);
};
Headers2.prototype.values = function() {
  var items = [];
  this.forEach(function(value) {
    items.push(value);
  });
  return iteratorFor(items);
};
Headers2.prototype.entries = function() {
  var items = [];
  this.forEach(function(value, name) {
    items.push([name, value]);
  });
  return iteratorFor(items);
};
if (support.iterable) {
  Headers2.prototype[Symbol.iterator] = Headers2.prototype.entries;
}
function consumed(body) {
  if (body._noBody) return;
  if (body.bodyUsed) {
    return Promise.reject(new TypeError("Already read"));
  }
  body.bodyUsed = true;
}
function fileReaderReady(reader) {
  return new Promise(function(resolve, reject) {
    reader.onload = function() {
      resolve(reader.result);
    };
    reader.onerror = function() {
      reject(reader.error);
    };
  });
}
function readBlobAsArrayBuffer(blob) {
  var reader = new FileReader();
  var promise = fileReaderReady(reader);
  reader.readAsArrayBuffer(blob);
  return promise;
}
function readBlobAsText(blob) {
  var reader = new FileReader();
  var promise = fileReaderReady(reader);
  var match2 = /charset=([A-Za-z0-9_-]+)/.exec(blob.type);
  var encoding = match2 ? match2[1] : "utf-8";
  reader.readAsText(blob, encoding);
  return promise;
}
function readArrayBufferAsText(buf) {
  var view = new Uint8Array(buf);
  var chars = new Array(view.length);
  for (var i7 = 0; i7 < view.length; i7++) {
    chars[i7] = String.fromCharCode(view[i7]);
  }
  return chars.join("");
}
function bufferClone(buf) {
  if (buf.slice) {
    return buf.slice(0);
  } else {
    var view = new Uint8Array(buf.byteLength);
    view.set(new Uint8Array(buf));
    return view.buffer;
  }
}
function Body() {
  this.bodyUsed = false;
  this._initBody = function(body) {
    this.bodyUsed = this.bodyUsed;
    this._bodyInit = body;
    if (!body) {
      this._noBody = true;
      this._bodyText = "";
    } else if (typeof body === "string") {
      this._bodyText = body;
    } else if (support.blob && Blob.prototype.isPrototypeOf(body)) {
      this._bodyBlob = body;
    } else if (support.formData && FormData.prototype.isPrototypeOf(body)) {
      this._bodyFormData = body;
    } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
      this._bodyText = body.toString();
    } else if (support.arrayBuffer && support.blob && isDataView(body)) {
      this._bodyArrayBuffer = bufferClone(body.buffer);
      this._bodyInit = new Blob([this._bodyArrayBuffer]);
    } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) {
      this._bodyArrayBuffer = bufferClone(body);
    } else {
      this._bodyText = body = Object.prototype.toString.call(body);
    }
    if (!this.headers.get("content-type")) {
      if (typeof body === "string") {
        this.headers.set("content-type", "text/plain;charset=UTF-8");
      } else if (this._bodyBlob && this._bodyBlob.type) {
        this.headers.set("content-type", this._bodyBlob.type);
      } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
        this.headers.set("content-type", "application/x-www-form-urlencoded;charset=UTF-8");
      }
    }
  };
  if (support.blob) {
    this.blob = function() {
      var rejected = consumed(this);
      if (rejected) {
        return rejected;
      }
      if (this._bodyBlob) {
        return Promise.resolve(this._bodyBlob);
      } else if (this._bodyArrayBuffer) {
        return Promise.resolve(new Blob([this._bodyArrayBuffer]));
      } else if (this._bodyFormData) {
        throw new Error("could not read FormData body as blob");
      } else {
        return Promise.resolve(new Blob([this._bodyText]));
      }
    };
  }
  this.arrayBuffer = function() {
    if (this._bodyArrayBuffer) {
      var isConsumed = consumed(this);
      if (isConsumed) {
        return isConsumed;
      } else if (ArrayBuffer.isView(this._bodyArrayBuffer)) {
        return Promise.resolve(
          this._bodyArrayBuffer.buffer.slice(
            this._bodyArrayBuffer.byteOffset,
            this._bodyArrayBuffer.byteOffset + this._bodyArrayBuffer.byteLength
          )
        );
      } else {
        return Promise.resolve(this._bodyArrayBuffer);
      }
    } else if (support.blob) {
      return this.blob().then(readBlobAsArrayBuffer);
    } else {
      throw new Error("could not read as ArrayBuffer");
    }
  };
  this.text = function() {
    var rejected = consumed(this);
    if (rejected) {
      return rejected;
    }
    if (this._bodyBlob) {
      return readBlobAsText(this._bodyBlob);
    } else if (this._bodyArrayBuffer) {
      return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer));
    } else if (this._bodyFormData) {
      throw new Error("could not read FormData body as text");
    } else {
      return Promise.resolve(this._bodyText);
    }
  };
  if (support.formData) {
    this.formData = function() {
      return this.text().then(decode);
    };
  }
  this.json = function() {
    return this.text().then(JSON.parse);
  };
  return this;
}
var methods = ["CONNECT", "DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT", "TRACE"];
function normalizeMethod(method) {
  var upcased = method.toUpperCase();
  return methods.indexOf(upcased) > -1 ? upcased : method;
}
function Request2(input, options) {
  if (!(this instanceof Request2)) {
    throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');
  }
  options = options || {};
  var body = options.body;
  if (input instanceof Request2) {
    if (input.bodyUsed) {
      throw new TypeError("Already read");
    }
    this.url = input.url;
    this.credentials = input.credentials;
    if (!options.headers) {
      this.headers = new Headers2(input.headers);
    }
    this.method = input.method;
    this.mode = input.mode;
    this.signal = input.signal;
    if (!body && input._bodyInit != null) {
      body = input._bodyInit;
      input.bodyUsed = true;
    }
  } else {
    this.url = String(input);
  }
  this.credentials = options.credentials || this.credentials || "same-origin";
  if (options.headers || !this.headers) {
    this.headers = new Headers2(options.headers);
  }
  this.method = normalizeMethod(options.method || this.method || "GET");
  this.mode = options.mode || this.mode || null;
  this.signal = options.signal || this.signal || (function() {
    if ("AbortController" in g2) {
      var ctrl = new AbortController();
      return ctrl.signal;
    }
  })();
  this.referrer = null;
  if ((this.method === "GET" || this.method === "HEAD") && body) {
    throw new TypeError("Body not allowed for GET or HEAD requests");
  }
  this._initBody(body);
  if (this.method === "GET" || this.method === "HEAD") {
    if (options.cache === "no-store" || options.cache === "no-cache") {
      var reParamSearch = /([?&])_=[^&]*/;
      if (reParamSearch.test(this.url)) {
        this.url = this.url.replace(reParamSearch, "$1_=" + (/* @__PURE__ */ new Date()).getTime());
      } else {
        var reQueryString = /\?/;
        this.url += (reQueryString.test(this.url) ? "&" : "?") + "_=" + (/* @__PURE__ */ new Date()).getTime();
      }
    }
  }
}
Request2.prototype.clone = function() {
  return new Request2(this, { body: this._bodyInit });
};
function decode(body) {
  var form = new FormData();
  body.trim().split("&").forEach(function(bytes) {
    if (bytes) {
      var split = bytes.split("=");
      var name = split.shift().replace(/\+/g, " ");
      var value = split.join("=").replace(/\+/g, " ");
      form.append(decodeURIComponent(name), decodeURIComponent(value));
    }
  });
  return form;
}
function parseHeaders(rawHeaders) {
  var headers = new Headers2();
  var preProcessedHeaders = rawHeaders.replace(/\r?\n[\t ]+/g, " ");
  preProcessedHeaders.split("\r").map(function(header) {
    return header.indexOf("\n") === 0 ? header.substr(1, header.length) : header;
  }).forEach(function(line) {
    var parts = line.split(":");
    var key = parts.shift().trim();
    if (key) {
      var value = parts.join(":").trim();
      try {
        headers.append(key, value);
      } catch (error) {
        console.warn("Response " + error.message);
      }
    }
  });
  return headers;
}
Body.call(Request2.prototype);
function Response2(bodyInit, options) {
  if (!(this instanceof Response2)) {
    throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');
  }
  if (!options) {
    options = {};
  }
  this.type = "default";
  this.status = options.status === void 0 ? 200 : options.status;
  if (this.status < 200 || this.status > 599) {
    throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");
  }
  this.ok = this.status >= 200 && this.status < 300;
  this.statusText = options.statusText === void 0 ? "" : "" + options.statusText;
  this.headers = new Headers2(options.headers);
  this.url = options.url || "";
  this._initBody(bodyInit);
}
Body.call(Response2.prototype);
Response2.prototype.clone = function() {
  return new Response2(this._bodyInit, {
    status: this.status,
    statusText: this.statusText,
    headers: new Headers2(this.headers),
    url: this.url
  });
};
Response2.error = function() {
  var response = new Response2(null, { status: 200, statusText: "" });
  response.ok = false;
  response.status = 0;
  response.type = "error";
  return response;
};
var redirectStatuses = [301, 302, 303, 307, 308];
Response2.redirect = function(url, status) {
  if (redirectStatuses.indexOf(status) === -1) {
    throw new RangeError("Invalid status code");
  }
  return new Response2(null, { status, headers: { location: url } });
};
var DOMException = g2.DOMException;
try {
  new DOMException();
} catch (err) {
  DOMException = function(message, name) {
    this.message = message;
    this.name = name;
    var error = Error(message);
    this.stack = error.stack;
  };
  DOMException.prototype = Object.create(Error.prototype);
  DOMException.prototype.constructor = DOMException;
}
function fetch2(input, init) {
  return new Promise(function(resolve, reject) {
    var request = new Request2(input, init);
    if (request.signal && request.signal.aborted) {
      return reject(new DOMException("Aborted", "AbortError"));
    }
    var xhr = new XMLHttpRequest();
    function abortXhr() {
      xhr.abort();
    }
    xhr.onload = function() {
      var options = {
        statusText: xhr.statusText,
        headers: parseHeaders(xhr.getAllResponseHeaders() || "")
      };
      if (request.url.indexOf("file://") === 0 && (xhr.status < 200 || xhr.status > 599)) {
        options.status = 200;
      } else {
        options.status = xhr.status;
      }
      options.url = "responseURL" in xhr ? xhr.responseURL : options.headers.get("X-Request-URL");
      var body = "response" in xhr ? xhr.response : xhr.responseText;
      setTimeout(function() {
        resolve(new Response2(body, options));
      }, 0);
    };
    xhr.onerror = function() {
      setTimeout(function() {
        reject(new TypeError("Network request failed"));
      }, 0);
    };
    xhr.ontimeout = function() {
      setTimeout(function() {
        reject(new TypeError("Network request timed out"));
      }, 0);
    };
    xhr.onabort = function() {
      setTimeout(function() {
        reject(new DOMException("Aborted", "AbortError"));
      }, 0);
    };
    function fixUrl(url) {
      try {
        return url === "" && g2.location.href ? g2.location.href : url;
      } catch (e9) {
        return url;
      }
    }
    xhr.open(request.method, fixUrl(request.url), true);
    if (request.credentials === "include") {
      xhr.withCredentials = true;
    } else if (request.credentials === "omit") {
      xhr.withCredentials = false;
    }
    if ("responseType" in xhr) {
      if (support.blob) {
        xhr.responseType = "blob";
      } else if (support.arrayBuffer) {
        xhr.responseType = "arraybuffer";
      }
    }
    if (init && typeof init.headers === "object" && !(init.headers instanceof Headers2 || g2.Headers && init.headers instanceof g2.Headers)) {
      var names = [];
      Object.getOwnPropertyNames(init.headers).forEach(function(name) {
        names.push(normalizeName(name));
        xhr.setRequestHeader(name, normalizeValue(init.headers[name]));
      });
      request.headers.forEach(function(value, name) {
        if (names.indexOf(name) === -1) {
          xhr.setRequestHeader(name, value);
        }
      });
    } else {
      request.headers.forEach(function(value, name) {
        xhr.setRequestHeader(name, value);
      });
    }
    if (request.signal) {
      request.signal.addEventListener("abort", abortXhr);
      xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
          request.signal.removeEventListener("abort", abortXhr);
        }
      };
    }
    xhr.send(typeof request._bodyInit === "undefined" ? null : request._bodyInit);
  });
}
fetch2.polyfill = true;
if (!g2.fetch) {
  g2.fetch = fetch2;
  g2.Headers = Headers2;
  g2.Request = Request2;
  g2.Response = Response2;
}

// ../pi-mono/node_modules/ollama/dist/browser.mjs
var defaultPort = "11434";
var defaultHost = `http://127.0.0.1:${defaultPort}`;
var version = "0.6.3";
var __defProp$1 = Object.defineProperty;
var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField$1 = (obj, key, value) => {
  __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
  return value;
};
var ResponseError = class _ResponseError extends Error {
  constructor(error, status_code) {
    super(error);
    this.error = error;
    this.status_code = status_code;
    this.name = "ResponseError";
    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, _ResponseError);
    }
  }
};
var AbortableAsyncIterator = class {
  constructor(abortController, itr, doneCallback) {
    __publicField$1(this, "abortController");
    __publicField$1(this, "itr");
    __publicField$1(this, "doneCallback");
    this.abortController = abortController;
    this.itr = itr;
    this.doneCallback = doneCallback;
  }
  abort() {
    this.abortController.abort();
  }
  async *[Symbol.asyncIterator]() {
    for await (const message of this.itr) {
      if ("error" in message) {
        throw new Error(message.error);
      }
      yield message;
      if (message.done || message.status === "success") {
        this.doneCallback();
        return;
      }
    }
    throw new Error("Did not receive done or success response in stream.");
  }
};
var checkOk = async (response) => {
  if (response.ok) {
    return;
  }
  let message = `Error ${response.status}: ${response.statusText}`;
  let errorData = null;
  if (response.headers.get("content-type")?.includes("application/json")) {
    try {
      errorData = await response.json();
      message = errorData.error || message;
    } catch (error) {
      console.log("Failed to parse error response as JSON");
    }
  } else {
    try {
      console.log("Getting text from response");
      const textResponse = await response.text();
      message = textResponse || message;
    } catch (error) {
      console.log("Failed to get text from error response");
    }
  }
  throw new ResponseError(message, response.status);
};
function getPlatform() {
  if (typeof window !== "undefined" && window.navigator) {
    const nav = navigator;
    if ("userAgentData" in nav && nav.userAgentData?.platform) {
      return `${nav.userAgentData.platform.toLowerCase()} Browser/${navigator.userAgent};`;
    }
    if (navigator.platform) {
      return `${navigator.platform.toLowerCase()} Browser/${navigator.userAgent};`;
    }
    return `unknown Browser/${navigator.userAgent};`;
  } else if (typeof process !== "undefined") {
    return `${process.arch} ${process.platform} Node.js/${process.version}`;
  }
  return "";
}
function normalizeHeaders(headers) {
  if (headers instanceof Headers) {
    const obj = {};
    headers.forEach((value, key) => {
      obj[key] = value;
    });
    return obj;
  } else if (Array.isArray(headers)) {
    return Object.fromEntries(headers);
  } else {
    return headers || {};
  }
}
var readEnvVar = (obj, key) => {
  return obj[key];
};
var fetchWithHeaders = async (fetch3, url, options = {}) => {
  const defaultHeaders = {
    "Content-Type": "application/json",
    Accept: "application/json",
    "User-Agent": `ollama-js/${version} (${getPlatform()})`
  };
  options.headers = normalizeHeaders(options.headers);
  try {
    const parsed = new URL(url);
    if (parsed.protocol === "https:" && parsed.hostname === "ollama.com") {
      const apiKey = typeof process === "object" && process !== null && typeof process.env === "object" && process.env !== null ? readEnvVar(process.env, "OLLAMA_API_KEY") : void 0;
      const authorization = options.headers["authorization"] || options.headers["Authorization"];
      if (!authorization && apiKey) {
        options.headers["Authorization"] = `Bearer ${apiKey}`;
      }
    }
  } catch (error) {
    console.error("error parsing url", error);
  }
  const customHeaders = Object.fromEntries(
    Object.entries(options.headers).filter(
      ([key]) => !Object.keys(defaultHeaders).some(
        (defaultKey) => defaultKey.toLowerCase() === key.toLowerCase()
      )
    )
  );
  options.headers = {
    ...defaultHeaders,
    ...customHeaders
  };
  return fetch3(url, options);
};
var get2 = async (fetch3, host, options) => {
  const response = await fetchWithHeaders(fetch3, host, {
    headers: options?.headers
  });
  await checkOk(response);
  return response;
};
var post = async (fetch3, host, data, options) => {
  const isRecord = (input) => {
    return input !== null && typeof input === "object" && !Array.isArray(input);
  };
  const formattedData = isRecord(data) ? JSON.stringify(data) : data;
  const response = await fetchWithHeaders(fetch3, host, {
    method: "POST",
    body: formattedData,
    signal: options?.signal,
    headers: options?.headers
  });
  await checkOk(response);
  return response;
};
var del = async (fetch3, host, data, options) => {
  const response = await fetchWithHeaders(fetch3, host, {
    method: "DELETE",
    body: JSON.stringify(data),
    headers: options?.headers
  });
  await checkOk(response);
  return response;
};
var parseJSON2 = async function* (itr) {
  const decoder = new TextDecoder("utf-8");
  let buffer = "";
  const reader = itr.getReader();
  while (true) {
    const { done, value: chunk } = await reader.read();
    if (done) {
      break;
    }
    buffer += decoder.decode(chunk, { stream: true });
    const parts = buffer.split("\n");
    buffer = parts.pop() ?? "";
    for (const part of parts) {
      try {
        yield JSON.parse(part);
      } catch (error) {
        console.warn("invalid json: ", part);
      }
    }
  }
  buffer += decoder.decode();
  for (const part of buffer.split("\n").filter((p4) => p4 !== "")) {
    try {
      yield JSON.parse(part);
    } catch (error) {
      console.warn("invalid json: ", part);
    }
  }
};
var formatHost = (host) => {
  if (!host) {
    return defaultHost;
  }
  let isExplicitProtocol = host.includes("://");
  if (host.startsWith(":")) {
    host = `http://127.0.0.1${host}`;
    isExplicitProtocol = true;
  }
  if (!isExplicitProtocol) {
    host = `http://${host}`;
  }
  const url = new URL(host);
  let port = url.port;
  if (!port) {
    if (!isExplicitProtocol) {
      port = defaultPort;
    } else {
      port = url.protocol === "https:" ? "443" : "80";
    }
  }
  let auth = "";
  if (url.username) {
    auth = url.username;
    if (url.password) {
      auth += `:${url.password}`;
    }
    auth += "@";
  }
  let formattedHost = `${url.protocol}//${auth}${url.hostname}:${port}${url.pathname}`;
  if (formattedHost.endsWith("/")) {
    formattedHost = formattedHost.slice(0, -1);
  }
  return formattedHost;
};
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);
  return value;
};
var Ollama$1 = class Ollama {
  constructor(config) {
    __publicField(this, "config");
    __publicField(this, "fetch");
    __publicField(this, "ongoingStreamedRequests", []);
    this.config = {
      host: "",
      headers: config?.headers
    };
    if (!config?.proxy) {
      this.config.host = formatHost(config?.host ?? defaultHost);
    }
    this.fetch = config?.fetch ?? fetch;
  }
  // Abort any ongoing streamed requests to Ollama
  abort() {
    for (const request of this.ongoingStreamedRequests) {
      request.abort();
    }
    this.ongoingStreamedRequests.length = 0;
  }
  /**
   * Processes a request to the Ollama server. If the request is streamable, it will return a
   * AbortableAsyncIterator that yields the response messages. Otherwise, it will return the response
   * object.
   * @param endpoint {string} - The endpoint to send the request to.
   * @param request {object} - The request object to send to the endpoint.
   * @protected {T | AbortableAsyncIterator<T>} - The response object or a AbortableAsyncIterator that yields
   * response messages.
   * @throws {Error} - If the response body is missing or if the response is an error.
   * @returns {Promise<T | AbortableAsyncIterator<T>>} - The response object or a AbortableAsyncIterator that yields the streamed response.
   */
  async processStreamableRequest(endpoint, request) {
    request.stream = request.stream ?? false;
    const host = `${this.config.host}/api/${endpoint}`;
    if (request.stream) {
      const abortController = new AbortController();
      const response2 = await post(this.fetch, host, request, {
        signal: abortController.signal,
        headers: this.config.headers
      });
      if (!response2.body) {
        throw new Error("Missing body");
      }
      const itr = parseJSON2(response2.body);
      const abortableAsyncIterator = new AbortableAsyncIterator(
        abortController,
        itr,
        () => {
          const i7 = this.ongoingStreamedRequests.indexOf(abortableAsyncIterator);
          if (i7 > -1) {
            this.ongoingStreamedRequests.splice(i7, 1);
          }
        }
      );
      this.ongoingStreamedRequests.push(abortableAsyncIterator);
      return abortableAsyncIterator;
    }
    const response = await post(this.fetch, host, request, {
      headers: this.config.headers
    });
    return await response.json();
  }
  /**
   * Encodes an image to base64 if it is a Uint8Array.
   * @param image {Uint8Array | string} - The image to encode.
   * @returns {Promise<string>} - The base64 encoded image.
   */
  async encodeImage(image) {
    if (typeof image !== "string") {
      const uint8Array = new Uint8Array(image);
      let byteString = "";
      const len = uint8Array.byteLength;
      for (let i7 = 0; i7 < len; i7++) {
        byteString += String.fromCharCode(uint8Array[i7]);
      }
      return btoa(byteString);
    }
    return image;
  }
  /**
   * Generates a response from a text prompt.
   * @param request {GenerateRequest} - The request object.
   * @returns {Promise<GenerateResponse | AbortableAsyncIterator<GenerateResponse>>} - The response object or
   * an AbortableAsyncIterator that yields response messages.
   */
  async generate(request) {
    if (request.images) {
      request.images = await Promise.all(request.images.map(this.encodeImage.bind(this)));
    }
    return this.processStreamableRequest("generate", request);
  }
  /**
   * Chats with the model. The request object can contain messages with images that are either
   * Uint8Arrays or base64 encoded strings. The images will be base64 encoded before sending the
   * request.
   * @param request {ChatRequest} - The request object.
   * @returns {Promise<ChatResponse | AbortableAsyncIterator<ChatResponse>>} - The response object or an
   * AbortableAsyncIterator that yields response messages.
   */
  async chat(request) {
    if (request.messages) {
      for (const message of request.messages) {
        if (message.images) {
          message.images = await Promise.all(
            message.images.map(this.encodeImage.bind(this))
          );
        }
      }
    }
    return this.processStreamableRequest("chat", request);
  }
  /**
   * Creates a new model from a stream of data.
   * @param request {CreateRequest} - The request object.
   * @returns {Promise<ProgressResponse | AbortableAsyncIterator<ProgressResponse>>} - The response object or a stream of progress responses.
   */
  async create(request) {
    return this.processStreamableRequest("create", {
      ...request
    });
  }
  /**
   * Pulls a model from the Ollama registry. The request object can contain a stream flag to indicate if the
   * response should be streamed.
   * @param request {PullRequest} - The request object.
   * @returns {Promise<ProgressResponse | AbortableAsyncIterator<ProgressResponse>>} - The response object or
   * an AbortableAsyncIterator that yields response messages.
   */
  async pull(request) {
    return this.processStreamableRequest("pull", {
      name: request.model,
      stream: request.stream,
      insecure: request.insecure
    });
  }
  /**
   * Pushes a model to the Ollama registry. The request object can contain a stream flag to indicate if the
   * response should be streamed.
   * @param request {PushRequest} - The request object.
   * @returns {Promise<ProgressResponse | AbortableAsyncIterator<ProgressResponse>>} - The response object or
   * an AbortableAsyncIterator that yields response messages.
   */
  async push(request) {
    return this.processStreamableRequest("push", {
      name: request.model,
      stream: request.stream,
      insecure: request.insecure
    });
  }
  /**
   * Deletes a model from the server. The request object should contain the name of the model to
   * delete.
   * @param request {DeleteRequest} - The request object.
   * @returns {Promise<StatusResponse>} - The response object.
   */
  async delete(request) {
    await del(
      this.fetch,
      `${this.config.host}/api/delete`,
      { name: request.model },
      { headers: this.config.headers }
    );
    return { status: "success" };
  }
  /**
   * Copies a model from one name to another. The request object should contain the name of the
   * model to copy and the new name.
   * @param request {CopyRequest} - The request object.
   * @returns {Promise<StatusResponse>} - The response object.
   */
  async copy(request) {
    await post(this.fetch, `${this.config.host}/api/copy`, { ...request }, {
      headers: this.config.headers
    });
    return { status: "success" };
  }
  /**
   * Lists the models on the server.
   * @returns {Promise<ListResponse>} - The response object.
   * @throws {Error} - If the response body is missing.
   */
  async list() {
    const response = await get2(this.fetch, `${this.config.host}/api/tags`, {
      headers: this.config.headers
    });
    return await response.json();
  }
  /**
   * Shows the metadata of a model. The request object should contain the name of the model.
   * @param request {ShowRequest} - The request object.
   * @returns {Promise<ShowResponse>} - The response object.
   */
  async show(request) {
    const response = await post(this.fetch, `${this.config.host}/api/show`, {
      ...request
    }, {
      headers: this.config.headers
    });
    return await response.json();
  }
  /**
   * Embeds text input into vectors.
   * @param request {EmbedRequest} - The request object.
   * @returns {Promise<EmbedResponse>} - The response object.
   */
  async embed(request) {
    const response = await post(this.fetch, `${this.config.host}/api/embed`, {
      ...request
    }, {
      headers: this.config.headers
    });
    return await response.json();
  }
  /**
   * Embeds a text prompt into a vector.
   * @param request {EmbeddingsRequest} - The request object.
   * @returns {Promise<EmbeddingsResponse>} - The response object.
   */
  async embeddings(request) {
    const response = await post(this.fetch, `${this.config.host}/api/embeddings`, {
      ...request
    }, {
      headers: this.config.headers
    });
    return await response.json();
  }
  /**
   * Lists the running models on the server
   * @returns {Promise<ListResponse>} - The response object.
   * @throws {Error} - If the response body is missing.
   */
  async ps() {
    const response = await get2(this.fetch, `${this.config.host}/api/ps`, {
      headers: this.config.headers
    });
    return await response.json();
  }
  /**
   * Returns the Ollama server version.
   * @returns {Promise<VersionResponse>} - The server version object.
   */
  async version() {
    const response = await get2(this.fetch, `${this.config.host}/api/version`, {
      headers: this.config.headers
    });
    return await response.json();
  }
  /**
   * Performs web search using the Ollama web search API
   * @param request {WebSearchRequest} - The search request containing query and options
   * @returns {Promise<WebSearchResponse>} - The search results
   * @throws {Error} - If the request is invalid or the server returns an error
   */
  async webSearch(request) {
    if (!request.query || request.query.length === 0) {
      throw new Error("Query is required");
    }
    const response = await post(this.fetch, `https://ollama.com/api/web_search`, { ...request }, {
      headers: this.config.headers
    });
    return await response.json();
  }
  /**
   * Fetches a single page using the Ollama web fetch API
   * @param request {WebFetchRequest} - The fetch request containing a URL
   * @returns {Promise<WebFetchResponse>} - The fetch result
   * @throws {Error} - If the request is invalid or the server returns an error
   */
  async webFetch(request) {
    if (!request.url || request.url.length === 0) {
      throw new Error("URL is required");
    }
    const response = await post(this.fetch, `https://ollama.com/api/web_fetch`, { ...request }, { headers: this.config.headers });
    return await response.json();
  }
};
var browser = new Ollama$1();

// ../pi-mono/packages/web-ui/dist/utils/model-discovery.js
async function discoverOllamaModels(baseUrl, _apiKey) {
  try {
    const ollama = new Ollama$1({ host: baseUrl });
    const { models: models2 } = await ollama.list();
    const ollamaModelPromises = models2.map(async (model) => {
      try {
        const details = await ollama.show({
          model: model.name
        });
        const capabilities = details.capabilities || [];
        if (!capabilities.includes("tools")) {
          console.debug(`Skipping model ${model.name}: does not support tools`);
          return null;
        }
        const modelInfo = details.model_info || {};
        const architecture = modelInfo["general.architecture"] || "";
        const contextKey = `${architecture}.context_length`;
        const contextWindow = parseInt(modelInfo[contextKey] || "8192", 10);
        const maxTokens = contextWindow * 10;
        const ollamaModel = {
          id: model.name,
          name: model.name,
          api: "openai-completions",
          provider: "",
          // Will be set by caller
          baseUrl: `${baseUrl}/v1`,
          reasoning: capabilities.includes("thinking"),
          input: ["text"],
          cost: {
            input: 0,
            output: 0,
            cacheRead: 0,
            cacheWrite: 0
          },
          contextWindow,
          maxTokens
        };
        return ollamaModel;
      } catch (err) {
        console.error(`Failed to fetch details for model ${model.name}:`, err);
        return null;
      }
    });
    const results = await Promise.all(ollamaModelPromises);
    return results.filter((m4) => m4 !== null);
  } catch (err) {
    console.error("Failed to discover Ollama models:", err);
    throw new Error(`Ollama discovery failed: ${err instanceof Error ? err.message : String(err)}`);
  }
}
async function discoverLlamaCppModels(baseUrl, apiKey) {
  try {
    const headers = {
      "Content-Type": "application/json"
    };
    if (apiKey) {
      headers.Authorization = `Bearer ${apiKey}`;
    }
    const response = await fetch(`${baseUrl}/v1/models`, {
      method: "GET",
      headers
    });
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }
    const data = await response.json();
    if (!data.data || !Array.isArray(data.data)) {
      throw new Error("Invalid response format from llama.cpp server");
    }
    return data.data.map((model) => {
      const contextWindow = model.context_length || 8192;
      const maxTokens = model.max_tokens || 4096;
      const llamaModel = {
        id: model.id,
        name: model.id,
        api: "openai-completions",
        provider: "",
        // Will be set by caller
        baseUrl: `${baseUrl}/v1`,
        reasoning: false,
        input: ["text"],
        cost: {
          input: 0,
          output: 0,
          cacheRead: 0,
          cacheWrite: 0
        },
        contextWindow,
        maxTokens
      };
      return llamaModel;
    });
  } catch (err) {
    console.error("Failed to discover llama.cpp models:", err);
    throw new Error(`llama.cpp discovery failed: ${err instanceof Error ? err.message : String(err)}`);
  }
}
async function discoverVLLMModels(baseUrl, apiKey) {
  try {
    const headers = {
      "Content-Type": "application/json"
    };
    if (apiKey) {
      headers.Authorization = `Bearer ${apiKey}`;
    }
    const response = await fetch(`${baseUrl}/v1/models`, {
      method: "GET",
      headers
    });
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }
    const data = await response.json();
    if (!data.data || !Array.isArray(data.data)) {
      throw new Error("Invalid response format from vLLM server");
    }
    return data.data.map((model) => {
      const contextWindow = model.max_model_len || 8192;
      const maxTokens = Math.min(contextWindow, 4096);
      const vllmModel = {
        id: model.id,
        name: model.id,
        api: "openai-completions",
        provider: "",
        // Will be set by caller
        baseUrl: `${baseUrl}/v1`,
        reasoning: false,
        input: ["text"],
        cost: {
          input: 0,
          output: 0,
          cacheRead: 0,
          cacheWrite: 0
        },
        contextWindow,
        maxTokens
      };
      return vllmModel;
    });
  } catch (err) {
    console.error("Failed to discover vLLM models:", err);
    throw new Error(`vLLM discovery failed: ${err instanceof Error ? err.message : String(err)}`);
  }
}
async function discoverLMStudioModels(baseUrl, _apiKey) {
  try {
    const url = new URL(baseUrl);
    const port = url.port ? parseInt(url.port, 10) : 1234;
    const client = new LMStudioClient({ baseUrl: `ws://${url.hostname}:${port}` });
    const models2 = await client.system.listDownloadedModels();
    return models2.filter((model) => model.type === "llm").map((model) => {
      const contextWindow = model.maxContextLength;
      const maxTokens = contextWindow;
      const lmStudioModel = {
        id: model.path,
        name: model.displayName || model.path,
        api: "openai-completions",
        provider: "",
        // Will be set by caller
        baseUrl: `${baseUrl}/v1`,
        reasoning: model.trainedForToolUse || false,
        input: model.vision ? ["text", "image"] : ["text"],
        cost: {
          input: 0,
          output: 0,
          cacheRead: 0,
          cacheWrite: 0
        },
        contextWindow,
        maxTokens
      };
      return lmStudioModel;
    });
  } catch (err) {
    console.error("Failed to discover LM Studio models:", err);
    throw new Error(`LM Studio discovery failed: ${err instanceof Error ? err.message : String(err)}`);
  }
}
async function discoverModels(type, baseUrl, apiKey) {
  switch (type) {
    case "ollama":
      return discoverOllamaModels(baseUrl, apiKey);
    case "llama.cpp":
      return discoverLlamaCppModels(baseUrl, apiKey);
    case "vllm":
      return discoverVLLMModels(baseUrl, apiKey);
    case "lmstudio":
      return discoverLMStudioModels(baseUrl, apiKey);
  }
}

// ../pi-mono/packages/web-ui/dist/dialogs/ModelSelector.js
var __decorate = function(decorators, target, key, desc) {
  var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc);
  else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8;
  return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8;
};
var ModelSelector_1;
function subsequenceScore(query, text3) {
  let qi = 0;
  let ti = 0;
  let gaps = 0;
  let lastMatchIndex = -1;
  while (qi < query.length && ti < text3.length) {
    if (query[qi] === text3[ti]) {
      if (lastMatchIndex >= 0) {
        gaps += ti - lastMatchIndex - 1;
      }
      lastMatchIndex = ti;
      qi++;
    }
    ti++;
  }
  if (qi < query.length)
    return 0;
  return query.length / (query.length + gaps);
}
var ModelSelector = ModelSelector_1 = class ModelSelector2 extends DialogBase {
  constructor() {
    super(...arguments);
    this.currentModel = null;
    this.searchQuery = "";
    this.filterThinking = false;
    this.filterVision = false;
    this.customProvidersLoading = false;
    this.selectedIndex = 0;
    this.navigationMode = "mouse";
    this.customProviderModels = [];
    this.scrollContainerRef = e5();
    this.searchInputRef = e5();
    this.lastMousePosition = { x: 0, y: 0 };
    this.modalWidth = "min(400px, 90vw)";
  }
  static async open(currentModel, onSelect, allowedProviders) {
    const selector = new ModelSelector_1();
    selector.currentModel = currentModel;
    selector.onSelectCallback = onSelect;
    if (allowedProviders) {
      selector.allowedProviders = new Set(allowedProviders);
    }
    selector.open();
    selector.loadCustomProviders();
  }
  async firstUpdated(changedProperties) {
    super.firstUpdated(changedProperties);
    await this.updateComplete;
    this.searchInputRef.value?.focus();
    this.addEventListener("mousemove", (e9) => {
      if (e9.clientX !== this.lastMousePosition.x || e9.clientY !== this.lastMousePosition.y) {
        this.lastMousePosition = { x: e9.clientX, y: e9.clientY };
        if (this.navigationMode === "keyboard") {
          this.navigationMode = "mouse";
          const target = e9.target;
          const modelItem = target.closest("[data-model-item]");
          if (modelItem) {
            const allItems = this.scrollContainerRef.value?.querySelectorAll("[data-model-item]");
            if (allItems) {
              const index = Array.from(allItems).indexOf(modelItem);
              if (index !== -1) {
                this.selectedIndex = index;
              }
            }
          }
        }
      }
    });
    this.addEventListener("keydown", (e9) => {
      const filteredModels = this.getFilteredModels();
      if (e9.key === "ArrowDown") {
        e9.preventDefault();
        this.navigationMode = "keyboard";
        this.selectedIndex = Math.min(this.selectedIndex + 1, filteredModels.length - 1);
        this.scrollToSelected();
      } else if (e9.key === "ArrowUp") {
        e9.preventDefault();
        this.navigationMode = "keyboard";
        this.selectedIndex = Math.max(this.selectedIndex - 1, 0);
        this.scrollToSelected();
      } else if (e9.key === "Enter") {
        e9.preventDefault();
        if (filteredModels[this.selectedIndex]) {
          this.handleSelect(filteredModels[this.selectedIndex].model);
        }
      }
    });
  }
  async loadCustomProviders() {
    this.customProvidersLoading = true;
    const allCustomModels = [];
    try {
      const storage2 = getAppStorage();
      const customProviders = await storage2.customProviders.getAll();
      for (const provider of customProviders) {
        const isAutoDiscovery = provider.type === "ollama" || provider.type === "llama.cpp" || provider.type === "vllm" || provider.type === "lmstudio";
        if (isAutoDiscovery) {
          try {
            const models2 = await discoverModels(provider.type, provider.baseUrl, provider.apiKey);
            const modelsWithProvider = models2.map((model) => ({
              ...model,
              provider: provider.name
            }));
            allCustomModels.push(...modelsWithProvider);
          } catch (error) {
            console.debug(`Failed to load models from ${provider.name}:`, error);
          }
        } else if (provider.models) {
          allCustomModels.push(...provider.models);
        }
      }
    } catch (error) {
      console.error("Failed to load custom providers:", error);
    } finally {
      this.customProviderModels = allCustomModels;
      this.customProvidersLoading = false;
      this.requestUpdate();
    }
  }
  formatTokens(tokens) {
    if (tokens >= 1e6)
      return `${(tokens / 1e6).toFixed(0)}M`;
    if (tokens >= 1e3)
      return `${(tokens / 1e3).toFixed(0)}`;
    return String(tokens);
  }
  handleSelect(model) {
    if (model) {
      this.onSelectCallback?.(model);
      this.close();
    }
  }
  getFilteredModels() {
    const allModels = [];
    const knownProviders = getProviders();
    for (const provider of knownProviders) {
      const models2 = getModels(provider);
      for (const model of models2) {
        allModels.push({ provider, id: model.id, model });
      }
    }
    for (const model of this.customProviderModels) {
      allModels.push({ provider: model.provider, id: model.id, model });
    }
    if (this.allowedProviders) {
      const allowed = this.allowedProviders;
      allModels.splice(0, allModels.length, ...allModels.filter(({ provider }) => allowed.has(provider)));
    }
    let filteredModels = allModels;
    if (this.searchQuery) {
      const query = this.searchQuery.toLowerCase().replace(/\s+/g, "");
      if (query) {
        const scored = [];
        for (const entry of filteredModels) {
          const searchText = `${entry.provider} ${entry.id} ${entry.model.name}`.toLowerCase();
          const score = subsequenceScore(query, searchText);
          if (score > 0) {
            scored.push({ item: entry, score });
          }
        }
        scored.sort((a3, b4) => b4.score - a3.score);
        filteredModels = scored.map((s6) => s6.item);
      }
    }
    if (this.filterThinking) {
      filteredModels = filteredModels.filter(({ model }) => model.reasoning);
    }
    if (this.filterVision) {
      filteredModels = filteredModels.filter(({ model }) => model.input.includes("image"));
    }
    if (!this.searchQuery) {
      filteredModels.sort((a3, b4) => {
        const aIsCurrent = modelsAreEqual(this.currentModel, a3.model);
        const bIsCurrent = modelsAreEqual(this.currentModel, b4.model);
        if (aIsCurrent && !bIsCurrent)
          return -1;
        if (!aIsCurrent && bIsCurrent)
          return 1;
        return a3.provider.localeCompare(b4.provider);
      });
    }
    return filteredModels;
  }
  scrollToSelected() {
    requestAnimationFrame(() => {
      const scrollContainer = this.scrollContainerRef.value;
      const selectedElement = scrollContainer?.querySelectorAll("[data-model-item]")[this.selectedIndex];
      if (selectedElement) {
        selectedElement.scrollIntoView({ block: "nearest", behavior: "smooth" });
      }
    });
  }
  renderContent() {
    const filteredModels = this.getFilteredModels();
    return b2`
			<!-- Header and Search -->
			<div class="p-6 pb-4 flex flex-col gap-4 border-b border-border flex-shrink-0">
				${DialogHeader({ title: i18n("Select Model") })}
				${Input({
      placeholder: i18n("Search models..."),
      value: this.searchQuery,
      inputRef: this.searchInputRef,
      onInput: (e9) => {
        this.searchQuery = e9.target.value;
        this.selectedIndex = 0;
        if (this.scrollContainerRef.value) {
          this.scrollContainerRef.value.scrollTop = 0;
        }
      }
    })}
				<div class="flex gap-2">
					${Button({
      variant: this.filterThinking ? "default" : "secondary",
      size: "sm",
      onClick: () => {
        this.filterThinking = !this.filterThinking;
        this.selectedIndex = 0;
        if (this.scrollContainerRef.value) {
          this.scrollContainerRef.value.scrollTop = 0;
        }
      },
      className: "rounded-full",
      children: b2`<span class="inline-flex items-center gap-1">${icon(Brain, "sm")} ${i18n("Thinking")}</span>`
    })}
					${Button({
      variant: this.filterVision ? "default" : "secondary",
      size: "sm",
      onClick: () => {
        this.filterVision = !this.filterVision;
        this.selectedIndex = 0;
        if (this.scrollContainerRef.value) {
          this.scrollContainerRef.value.scrollTop = 0;
        }
      },
      className: "rounded-full",
      children: b2`<span class="inline-flex items-center gap-1">${icon(Image2, "sm")} ${i18n("Vision")}</span>`
    })}
				</div>
			</div>

			<!-- Scrollable model list -->
			<div class="flex-1 overflow-y-auto" ${n5(this.scrollContainerRef)}>
				${filteredModels.map(({ provider, id, model }, index) => {
      const isCurrent = modelsAreEqual(this.currentModel, model);
      const isSelected = index === this.selectedIndex;
      return b2`
						<div
							data-model-item
							class="px-4 py-3 ${this.navigationMode === "mouse" ? "hover:bg-muted" : ""} cursor-pointer border-b border-border ${isSelected ? "bg-accent" : ""}"
							@click=${() => this.handleSelect(model)}
							@mouseenter=${() => {
        if (this.navigationMode === "mouse") {
          this.selectedIndex = index;
        }
      }}
						>
							<div class="flex items-center justify-between gap-2 mb-1">
								<div class="flex items-center gap-2 flex-1 min-w-0">
									<span class="text-sm font-medium text-foreground truncate">${id}</span>
									${isCurrent ? b2`<span class="text-green-500">✓</span>` : ""}
								</div>
								${Badge(provider, "outline")}
							</div>
							<div class="flex items-center justify-between text-xs text-muted-foreground">
								<div class="flex items-center gap-2">
									<span class="${model.reasoning ? "" : "opacity-30"}">${icon(Brain, "sm")}</span>
									<span class="${model.input.includes("image") ? "" : "opacity-30"}">${icon(Image2, "sm")}</span>
									<span>${this.formatTokens(model.contextWindow)}K/${this.formatTokens(model.maxTokens)}K</span>
								</div>
								<span>${formatModelCost(model.cost)}</span>
							</div>
						</div>
					`;
    })}
			</div>
		`;
  }
};
__decorate([
  r7()
], ModelSelector.prototype, "currentModel", void 0);
__decorate([
  r7()
], ModelSelector.prototype, "searchQuery", void 0);
__decorate([
  r7()
], ModelSelector.prototype, "filterThinking", void 0);
__decorate([
  r7()
], ModelSelector.prototype, "filterVision", void 0);
__decorate([
  r7()
], ModelSelector.prototype, "customProvidersLoading", void 0);
__decorate([
  r7()
], ModelSelector.prototype, "selectedIndex", void 0);
__decorate([
  r7()
], ModelSelector.prototype, "navigationMode", void 0);
__decorate([
  r7()
], ModelSelector.prototype, "customProviderModels", void 0);
ModelSelector = ModelSelector_1 = __decorate([
  t5("agent-model-selector")
], ModelSelector);

// ../pi-mono/packages/web-ui/dist/components/MessageEditor.js
init_process_shim();

// ../mini-lit/dist/Select.js
init_process_shim();
var activeSelect = null;
function Select(props) {
  const { value, placeholder = i18n("Select an option"), options, onChange, disabled = false, className = "", width = "180px", size = "md", variant = "default", fitContent = false } = props;
  const triggerRef = e5();
  const state = {
    isOpen: false,
    focusedIndex: -1
  };
  const sizeClasses2 = {
    sm: "h-8 px-2 text-xs",
    md: "h-9 px-3 text-sm",
    lg: "h-10 px-4 text-base"
  };
  const variantClasses = {
    default: "text-foreground border-input bg-transparent hover:bg-accent/50 shadow-xs",
    ghost: "text-foreground border-transparent bg-transparent hover:bg-accent hover:text-accent-foreground",
    outline: "text-foreground border-input bg-transparent hover:bg-accent hover:text-accent-foreground"
  };
  const flatOptions = [];
  const isGrouped = options.length > 0 && "options" in options[0];
  if (isGrouped) {
    options.forEach((group) => {
      flatOptions.push(...group.options.filter((opt) => !opt.disabled));
    });
  } else {
    flatOptions.push(...options.filter((opt) => !opt.disabled));
  }
  const selectedOption = flatOptions.find((opt) => opt.value === value);
  let portalContainer = null;
  const ensurePortalContainer = () => {
    if (!portalContainer) {
      portalContainer = document.createElement("div");
      portalContainer.className = "select-portal-container";
      portalContainer.style.cssText = "position: fixed; z-index: 50; pointer-events: none;";
      document.body.appendChild(portalContainer);
    }
    return portalContainer;
  };
  const updatePosition = () => {
    if (!triggerRef.value || !portalContainer)
      return;
    const rect = triggerRef.value.getBoundingClientRect();
    state.triggerRect = rect;
    const spaceBelow = window.innerHeight - rect.bottom;
    const spaceAbove = rect.top;
    const dropdownHeight = 300;
    const showAbove = spaceBelow < dropdownHeight && spaceAbove > spaceBelow;
    portalContainer.style.cssText = `
			position: fixed;
			left: ${rect.left}px;
			${showAbove ? `bottom: ${window.innerHeight - rect.top}px` : `top: ${rect.bottom}px`};
			min-width: ${rect.width}px;
			width: max-content;
			z-index: 50;
			pointer-events: ${state.isOpen ? "auto" : "none"};
		`;
  };
  const open2 = () => {
    if (disabled || state.isOpen)
      return;
    if (activeSelect && activeSelect !== api) {
      activeSelect.close();
    }
    state.isOpen = true;
    state.focusedIndex = selectedOption ? flatOptions.indexOf(selectedOption) : 0;
    ensurePortalContainer();
    updatePosition();
    renderPortal();
    setTimeout(() => {
      document.addEventListener("click", handleOutsideClick);
      document.addEventListener("keydown", handleKeyDown);
      window.addEventListener("scroll", updatePosition, true);
      window.addEventListener("resize", updatePosition);
    }, 0);
    activeSelect = api;
    if (triggerRef.value) {
      triggerRef.value.setAttribute("aria-expanded", "true");
    }
  };
  const close2 = () => {
    if (!state.isOpen)
      return;
    state.isOpen = false;
    state.focusedIndex = -1;
    document.removeEventListener("click", handleOutsideClick);
    document.removeEventListener("keydown", handleKeyDown);
    window.removeEventListener("scroll", updatePosition, true);
    window.removeEventListener("resize", updatePosition);
    if (portalContainer) {
      D(b2``, portalContainer);
    }
    if (activeSelect === api) {
      activeSelect = null;
    }
    if (triggerRef.value) {
      triggerRef.value.setAttribute("aria-expanded", "false");
      triggerRef.value.focus();
    }
  };
  const handleOutsideClick = (e9) => {
    const target = e9.target;
    if (triggerRef.value?.contains(target) || portalContainer?.contains(target)) {
      return;
    }
    close2();
  };
  const handleKeyDown = (e9) => {
    if (!state.isOpen)
      return;
    switch (e9.key) {
      case "Escape":
        e9.preventDefault();
        close2();
        break;
      case "ArrowDown":
        e9.preventDefault();
        state.focusedIndex = Math.min(state.focusedIndex + 1, flatOptions.length - 1);
        renderPortal();
        break;
      case "ArrowUp":
        e9.preventDefault();
        state.focusedIndex = Math.max(state.focusedIndex - 1, 0);
        renderPortal();
        break;
      case "Enter":
      case " ":
        e9.preventDefault();
        if (state.focusedIndex >= 0 && state.focusedIndex < flatOptions.length) {
          selectOption(flatOptions[state.focusedIndex].value);
        }
        break;
      case "Home":
        e9.preventDefault();
        state.focusedIndex = 0;
        renderPortal();
        break;
      case "End":
        e9.preventDefault();
        state.focusedIndex = flatOptions.length - 1;
        renderPortal();
        break;
    }
  };
  const selectOption = (optionValue) => {
    onChange(optionValue);
    close2();
  };
  const renderPortal = () => {
    if (!portalContainer || !state.isOpen)
      return;
    const dropdownContent = b2`
         <div
            class="border border-border bg-popover text-popover-foreground shadow-md rounded-md overflow-hidden animate-in fade-in-0 zoom-in-95"
            role="listbox"
            style="max-height: 300px; overflow-y: auto;"
         >
            <div class="p-1">
               ${isGrouped ? options.map((group, _groupIndex) => b2`
                          <div role="group">
                             ${group.label ? b2`
                                     <div class="text-muted-foreground px-2 py-1.5 text-xs font-medium">
                                        ${group.label}
                                     </div>
                                  ` : ""}
                             ${group.options.map((option, _optionIndex) => {
      const globalIndex = flatOptions.indexOf(option);
      const isFocused = globalIndex === state.focusedIndex;
      const isSelected = option.value === value;
      return b2`
                                   <div
                                      role="option"
                                      aria-selected=${isSelected}
                                      data-disabled=${option.disabled || false}
                                      tabindex="-1"
                                      class="relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-none select-none transition-colors
												${isFocused ? "bg-accent text-accent-foreground" : ""}
												${option.disabled ? "pointer-events-none opacity-50" : "hover:bg-accent hover:text-accent-foreground"}
												${isSelected ? "font-medium" : ""}"
                                      @click=${option.disabled ? null : () => selectOption(option.value)}
                                      @mouseenter=${() => {
        if (!option.disabled) {
          state.focusedIndex = globalIndex;
          renderPortal();
        }
      }}
                                   >
                                      <span class="absolute right-2 flex h-3.5 w-3.5 items-center justify-center">
                                         ${isSelected ? b2`
                                                 <svg
                                                    class="h-4 w-4"
                                                    xmlns="http://www.w3.org/2000/svg"
                                                    viewBox="0 0 24 24"
                                                    fill="none"
                                                    stroke="currentColor"
                                                    stroke-width="2"
                                                    stroke-linecap="round"
                                                    stroke-linejoin="round"
                                                 >
                                                    <polyline points="20 6 9 17 4 12"></polyline>
                                                 </svg>
                                              ` : ""}
                                      </span>
                                      ${option.icon ? b2`<span class="flex-shrink-0">${option.icon}</span>` : ""}
                                      <span>${option.label}</span>
                                   </div>
                                `;
    })}
                          </div>
                       `) : options.map((option, index) => {
      const isFocused = index === state.focusedIndex;
      const isSelected = option.value === value;
      return b2`
                          <div
                             role="option"
                             aria-selected=${isSelected}
                             data-disabled=${option.disabled || false}
                             tabindex="-1"
                             class="relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-none select-none transition-colors
										${isFocused ? "bg-accent text-accent-foreground" : ""}
										${option.disabled ? "pointer-events-none opacity-50" : "hover:bg-accent hover:text-accent-foreground"}
										${isSelected ? "font-medium" : ""}"
                             @click=${option.disabled ? null : () => selectOption(option.value)}
                             @mouseenter=${() => {
        if (!option.disabled) {
          state.focusedIndex = index;
          renderPortal();
        }
      }}
                          >
                             <span class="absolute right-2 flex h-3.5 w-3.5 items-center justify-center">
                                ${isSelected ? b2`
                                        <svg
                                           class="h-4 w-4"
                                           xmlns="http://www.w3.org/2000/svg"
                                           viewBox="0 0 24 24"
                                           fill="none"
                                           stroke="currentColor"
                                           stroke-width="2"
                                           stroke-linecap="round"
                                           stroke-linejoin="round"
                                        >
                                           <polyline points="20 6 9 17 4 12"></polyline>
                                        </svg>
                                     ` : ""}
                             </span>
                             ${option.icon ? b2`<span class="flex-shrink-0">${option.icon}</span>` : ""}
                             <span>${option.label}</span>
                          </div>
                       `;
    })}
            </div>
         </div>
      `;
    D(dropdownContent, portalContainer);
  };
  const api = { close: close2 };
  const handleTriggerClick = (e9) => {
    e9.preventDefault();
    e9.stopPropagation();
    if (state.isOpen) {
      close2();
    } else {
      open2();
    }
  };
  const buttonWidth = fitContent ? "auto" : width;
  const minWidth = fitContent ? width || "auto" : void 0;
  return b2`
      <button
         ${n5(triggerRef)}
         type="button"
         role="combobox"
         aria-expanded=${state.isOpen}
         aria-haspopup="listbox"
         aria-autocomplete="none"
         ?disabled=${disabled}
         @click=${handleTriggerClick}
         class="flex items-center justify-between gap-2 rounded-md border whitespace-nowrap transition-[color,box-shadow] outline-none
				focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background
				disabled:cursor-not-allowed disabled:opacity-50
				data-[placeholder]:text-muted-foreground
				${sizeClasses2[size]} ${variantClasses[variant]} ${className}"
         style="width: ${buttonWidth}; ${minWidth ? `min-width: ${minWidth};` : ""}"
      >
         <span class="flex items-center gap-2 truncate">
            ${selectedOption?.icon ? b2`<span class="flex-shrink-0">${selectedOption.icon}</span>` : ""}
            ${selectedOption ? selectedOption.label : placeholder}
         </span>
         <svg
            xmlns="http://www.w3.org/2000/svg"
            width="24"
            height="24"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
            class="h-4 w-4 opacity-50 flex-shrink-0"
         >
            <path d="m6 9 6 6 6-6"></path>
         </svg>
      </button>
   `;
}

// ../pi-mono/packages/web-ui/dist/utils/attachment-utils.js
init_process_shim();

// ../pi-mono/node_modules/docx-preview/dist/docx-preview.mjs
init_process_shim();
var import_jszip = __toESM(require_jszip_min(), 1);
var RelationshipTypes;
(function(RelationshipTypes2) {
  RelationshipTypes2["OfficeDocument"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument";
  RelationshipTypes2["FontTable"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable";
  RelationshipTypes2["Image"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image";
  RelationshipTypes2["Numbering"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering";
  RelationshipTypes2["Styles"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles";
  RelationshipTypes2["StylesWithEffects"] = "http://schemas.microsoft.com/office/2007/relationships/stylesWithEffects";
  RelationshipTypes2["Theme"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme";
  RelationshipTypes2["Settings"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings";
  RelationshipTypes2["WebSettings"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/webSettings";
  RelationshipTypes2["Hyperlink"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink";
  RelationshipTypes2["Footnotes"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes";
  RelationshipTypes2["Endnotes"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/endnotes";
  RelationshipTypes2["Footer"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer";
  RelationshipTypes2["Header"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/header";
  RelationshipTypes2["ExtendedProperties"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties";
  RelationshipTypes2["CoreProperties"] = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties";
  RelationshipTypes2["CustomProperties"] = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/custom-properties";
  RelationshipTypes2["Comments"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments";
  RelationshipTypes2["CommentsExtended"] = "http://schemas.microsoft.com/office/2011/relationships/commentsExtended";
  RelationshipTypes2["AltChunk"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/aFChunk";
})(RelationshipTypes || (RelationshipTypes = {}));
function parseRelationships(root, xml2) {
  return xml2.elements(root).map((e9) => ({
    id: xml2.attr(e9, "Id"),
    type: xml2.attr(e9, "Type"),
    target: xml2.attr(e9, "Target"),
    targetMode: xml2.attr(e9, "TargetMode")
  }));
}
function escapeClassName(className) {
  return className?.replace(/[ .]+/g, "-").replace(/[&]+/g, "and").toLowerCase();
}
function encloseFontFamily(fontFamily) {
  return /^[^"'].*\s.*[^"']$/.test(fontFamily) ? `'${fontFamily}'` : fontFamily;
}
function splitPath(path6) {
  let si = path6.lastIndexOf("/") + 1;
  let folder = si == 0 ? "" : path6.substring(0, si);
  let fileName = si == 0 ? path6 : path6.substring(si);
  return [folder, fileName];
}
function resolvePath(path6, base) {
  try {
    const prefix = "http://docx/";
    const url = new URL(path6, prefix + base).toString();
    return url.substring(prefix.length);
  } catch {
    return `${base}${path6}`;
  }
}
function keyBy(array, by) {
  return array.reduce((a3, x2) => {
    a3[by(x2)] = x2;
    return a3;
  }, {});
}
function blobToBase64(blob) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onloadend = () => resolve(reader.result);
    reader.onerror = () => reject();
    reader.readAsDataURL(blob);
  });
}
function isObject(item) {
  return item && typeof item === "object" && !Array.isArray(item);
}
function isString2(item) {
  return typeof item === "string" || item instanceof String;
}
function mergeDeep(target, ...sources) {
  if (!sources.length)
    return target;
  const source = sources.shift();
  if (isObject(target) && isObject(source)) {
    for (const key in source) {
      if (isObject(source[key])) {
        const val2 = target[key] ?? (target[key] = {});
        mergeDeep(val2, source[key]);
      } else {
        target[key] = source[key];
      }
    }
  }
  return mergeDeep(target, ...sources);
}
function asArray(val2) {
  return Array.isArray(val2) ? val2 : [val2];
}
function clamp(val2, min, max) {
  return min > val2 ? min : max < val2 ? max : val2;
}
var ns$1 = {
  wordml: "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
};
var LengthUsage = {
  Dxa: { mul: 0.05, unit: "pt" },
  Emu: { mul: 1 / 12700, unit: "pt" },
  FontSize: { mul: 0.5, unit: "pt" },
  Border: { mul: 0.125, unit: "pt", min: 0.25, max: 12 },
  Point: { mul: 1, unit: "pt" },
  Percent: { mul: 0.02, unit: "%" }
};
function convertLength(val2, usage = LengthUsage.Dxa) {
  if (val2 == null || /.+(p[xt]|[%])$/.test(val2)) {
    return val2;
  }
  var num = parseInt(val2) * usage.mul;
  if (usage.min && usage.max)
    num = clamp(num, usage.min, usage.max);
  return `${num.toFixed(2)}${usage.unit}`;
}
function convertBoolean(v4, defaultValue = false) {
  switch (v4) {
    case "1":
      return true;
    case "0":
      return false;
    case "on":
      return true;
    case "off":
      return false;
    case "true":
      return true;
    case "false":
      return false;
    default:
      return defaultValue;
  }
}
function parseCommonProperty(elem, props, xml2) {
  if (elem.namespaceURI != ns$1.wordml)
    return false;
  switch (elem.localName) {
    case "color":
      props.color = xml2.attr(elem, "val");
      break;
    case "sz":
      props.fontSize = xml2.lengthAttr(elem, "val", LengthUsage.FontSize);
      break;
    default:
      return false;
  }
  return true;
}
function parseXmlString(xmlString, trimXmlDeclaration = false) {
  if (trimXmlDeclaration)
    xmlString = xmlString.replace(/<[?].*[?]>/, "");
  xmlString = removeUTF8BOM(xmlString);
  const result = new DOMParser().parseFromString(xmlString, "application/xml");
  const errorText = hasXmlParserError(result);
  if (errorText)
    throw new Error(errorText);
  return result;
}
function hasXmlParserError(doc) {
  return doc.getElementsByTagName("parsererror")[0]?.textContent;
}
function removeUTF8BOM(data) {
  return data.charCodeAt(0) === 65279 ? data.substring(1) : data;
}
function serializeXmlString(elem) {
  return new XMLSerializer().serializeToString(elem);
}
var XmlParser = class {
  elements(elem, localName = null) {
    const result = [];
    for (let i7 = 0, l5 = elem.childNodes.length; i7 < l5; i7++) {
      let c6 = elem.childNodes.item(i7);
      if (c6.nodeType == Node.ELEMENT_NODE && (localName == null || c6.localName == localName))
        result.push(c6);
    }
    return result;
  }
  element(elem, localName) {
    for (let i7 = 0, l5 = elem.childNodes.length; i7 < l5; i7++) {
      let c6 = elem.childNodes.item(i7);
      if (c6.nodeType == 1 && c6.localName == localName)
        return c6;
    }
    return null;
  }
  elementAttr(elem, localName, attrLocalName) {
    var el = this.element(elem, localName);
    return el ? this.attr(el, attrLocalName) : void 0;
  }
  attrs(elem) {
    return Array.from(elem.attributes);
  }
  attr(elem, localName) {
    for (let i7 = 0, l5 = elem.attributes.length; i7 < l5; i7++) {
      let a3 = elem.attributes.item(i7);
      if (a3.localName == localName)
        return a3.value;
    }
    return null;
  }
  intAttr(node, attrName, defaultValue = null) {
    var val2 = this.attr(node, attrName);
    return val2 ? parseInt(val2) : defaultValue;
  }
  hexAttr(node, attrName, defaultValue = null) {
    var val2 = this.attr(node, attrName);
    return val2 ? parseInt(val2, 16) : defaultValue;
  }
  floatAttr(node, attrName, defaultValue = null) {
    var val2 = this.attr(node, attrName);
    return val2 ? parseFloat(val2) : defaultValue;
  }
  boolAttr(node, attrName, defaultValue = null) {
    return convertBoolean(this.attr(node, attrName), defaultValue);
  }
  lengthAttr(node, attrName, usage = LengthUsage.Dxa) {
    return convertLength(this.attr(node, attrName), usage);
  }
};
var globalXmlParser = new XmlParser();
var Part = class {
  constructor(_package, path6) {
    this._package = _package;
    this.path = path6;
  }
  async load() {
    this.rels = await this._package.loadRelationships(this.path);
    const xmlText = await this._package.load(this.path);
    const xmlDoc = this._package.parseXmlDocument(xmlText);
    if (this._package.options.keepOrigin) {
      this._xmlDocument = xmlDoc;
    }
    this.parseXml(xmlDoc.firstElementChild);
  }
  save() {
    this._package.update(this.path, serializeXmlString(this._xmlDocument));
  }
  parseXml(root) {
  }
};
var embedFontTypeMap = {
  embedRegular: "regular",
  embedBold: "bold",
  embedItalic: "italic",
  embedBoldItalic: "boldItalic"
};
function parseFonts(root, xml2) {
  return xml2.elements(root).map((el) => parseFont(el, xml2));
}
function parseFont(elem, xml2) {
  let result = {
    name: xml2.attr(elem, "name"),
    embedFontRefs: []
  };
  for (let el of xml2.elements(elem)) {
    switch (el.localName) {
      case "family":
        result.family = xml2.attr(el, "val");
        break;
      case "altName":
        result.altName = xml2.attr(el, "val");
        break;
      case "embedRegular":
      case "embedBold":
      case "embedItalic":
      case "embedBoldItalic":
        result.embedFontRefs.push(parseEmbedFontRef(el, xml2));
        break;
    }
  }
  return result;
}
function parseEmbedFontRef(elem, xml2) {
  return {
    id: xml2.attr(elem, "id"),
    key: xml2.attr(elem, "fontKey"),
    type: embedFontTypeMap[elem.localName]
  };
}
var FontTablePart = class extends Part {
  parseXml(root) {
    this.fonts = parseFonts(root, this._package.xmlParser);
  }
};
var OpenXmlPackage = class _OpenXmlPackage {
  constructor(_zip, options) {
    this._zip = _zip;
    this.options = options;
    this.xmlParser = new XmlParser();
  }
  get(path6) {
    const p4 = normalizePath(path6);
    return this._zip.files[p4] ?? this._zip.files[p4.replace(/\//g, "\\")];
  }
  update(path6, content) {
    this._zip.file(path6, content);
  }
  static async load(input, options) {
    const zip = await import_jszip.default.loadAsync(input);
    return new _OpenXmlPackage(zip, options);
  }
  save(type = "blob") {
    return this._zip.generateAsync({ type });
  }
  load(path6, type = "string") {
    return this.get(path6)?.async(type) ?? Promise.resolve(null);
  }
  async loadRelationships(path6 = null) {
    let relsPath = `_rels/.rels`;
    if (path6 != null) {
      const [f4, fn] = splitPath(path6);
      relsPath = `${f4}_rels/${fn}.rels`;
    }
    const txt = await this.load(relsPath);
    return txt ? parseRelationships(this.parseXmlDocument(txt).firstElementChild, this.xmlParser) : null;
  }
  parseXmlDocument(txt) {
    return parseXmlString(txt, this.options.trimXmlDeclaration);
  }
};
function normalizePath(path6) {
  return path6.startsWith("/") ? path6.substr(1) : path6;
}
var DocumentPart = class extends Part {
  constructor(pkg, path6, parser) {
    super(pkg, path6);
    this._documentParser = parser;
  }
  parseXml(root) {
    this.body = this._documentParser.parseDocumentFile(root);
  }
};
function parseBorder(elem, xml2) {
  return {
    type: xml2.attr(elem, "val"),
    color: xml2.attr(elem, "color"),
    size: xml2.lengthAttr(elem, "sz", LengthUsage.Border),
    offset: xml2.lengthAttr(elem, "space", LengthUsage.Point),
    frame: xml2.boolAttr(elem, "frame"),
    shadow: xml2.boolAttr(elem, "shadow")
  };
}
function parseBorders(elem, xml2) {
  var result = {};
  for (let e9 of xml2.elements(elem)) {
    switch (e9.localName) {
      case "left":
        result.left = parseBorder(e9, xml2);
        break;
      case "top":
        result.top = parseBorder(e9, xml2);
        break;
      case "right":
        result.right = parseBorder(e9, xml2);
        break;
      case "bottom":
        result.bottom = parseBorder(e9, xml2);
        break;
    }
  }
  return result;
}
var SectionType;
(function(SectionType2) {
  SectionType2["Continuous"] = "continuous";
  SectionType2["NextPage"] = "nextPage";
  SectionType2["NextColumn"] = "nextColumn";
  SectionType2["EvenPage"] = "evenPage";
  SectionType2["OddPage"] = "oddPage";
})(SectionType || (SectionType = {}));
function parseSectionProperties(elem, xml2 = globalXmlParser) {
  var section = {};
  for (let e9 of xml2.elements(elem)) {
    switch (e9.localName) {
      case "pgSz":
        section.pageSize = {
          width: xml2.lengthAttr(e9, "w"),
          height: xml2.lengthAttr(e9, "h"),
          orientation: xml2.attr(e9, "orient")
        };
        break;
      case "type":
        section.type = xml2.attr(e9, "val");
        break;
      case "pgMar":
        section.pageMargins = {
          left: xml2.lengthAttr(e9, "left"),
          right: xml2.lengthAttr(e9, "right"),
          top: xml2.lengthAttr(e9, "top"),
          bottom: xml2.lengthAttr(e9, "bottom"),
          header: xml2.lengthAttr(e9, "header"),
          footer: xml2.lengthAttr(e9, "footer"),
          gutter: xml2.lengthAttr(e9, "gutter")
        };
        break;
      case "cols":
        section.columns = parseColumns(e9, xml2);
        break;
      case "headerReference":
        (section.headerRefs ?? (section.headerRefs = [])).push(parseFooterHeaderReference(e9, xml2));
        break;
      case "footerReference":
        (section.footerRefs ?? (section.footerRefs = [])).push(parseFooterHeaderReference(e9, xml2));
        break;
      case "titlePg":
        section.titlePage = xml2.boolAttr(e9, "val", true);
        break;
      case "pgBorders":
        section.pageBorders = parseBorders(e9, xml2);
        break;
      case "pgNumType":
        section.pageNumber = parsePageNumber(e9, xml2);
        break;
    }
  }
  return section;
}
function parseColumns(elem, xml2) {
  return {
    numberOfColumns: xml2.intAttr(elem, "num"),
    space: xml2.lengthAttr(elem, "space"),
    separator: xml2.boolAttr(elem, "sep"),
    equalWidth: xml2.boolAttr(elem, "equalWidth", true),
    columns: xml2.elements(elem, "col").map((e9) => ({
      width: xml2.lengthAttr(e9, "w"),
      space: xml2.lengthAttr(e9, "space")
    }))
  };
}
function parsePageNumber(elem, xml2) {
  return {
    chapSep: xml2.attr(elem, "chapSep"),
    chapStyle: xml2.attr(elem, "chapStyle"),
    format: xml2.attr(elem, "fmt"),
    start: xml2.intAttr(elem, "start")
  };
}
function parseFooterHeaderReference(elem, xml2) {
  return {
    id: xml2.attr(elem, "id"),
    type: xml2.attr(elem, "type")
  };
}
function parseLineSpacing(elem, xml2) {
  return {
    before: xml2.lengthAttr(elem, "before"),
    after: xml2.lengthAttr(elem, "after"),
    line: xml2.intAttr(elem, "line"),
    lineRule: xml2.attr(elem, "lineRule")
  };
}
function parseRunProperties(elem, xml2) {
  let result = {};
  for (let el of xml2.elements(elem)) {
    parseRunProperty(el, result, xml2);
  }
  return result;
}
function parseRunProperty(elem, props, xml2) {
  if (parseCommonProperty(elem, props, xml2))
    return true;
  return false;
}
function parseParagraphProperties(elem, xml2) {
  let result = {};
  for (let el of xml2.elements(elem)) {
    parseParagraphProperty(el, result, xml2);
  }
  return result;
}
function parseParagraphProperty(elem, props, xml2) {
  if (elem.namespaceURI != ns$1.wordml)
    return false;
  if (parseCommonProperty(elem, props, xml2))
    return true;
  switch (elem.localName) {
    case "tabs":
      props.tabs = parseTabs(elem, xml2);
      break;
    case "sectPr":
      props.sectionProps = parseSectionProperties(elem, xml2);
      break;
    case "numPr":
      props.numbering = parseNumbering$1(elem, xml2);
      break;
    case "spacing":
      props.lineSpacing = parseLineSpacing(elem, xml2);
      return false;
    case "textAlignment":
      props.textAlignment = xml2.attr(elem, "val");
      return false;
    case "keepLines":
      props.keepLines = xml2.boolAttr(elem, "val", true);
      break;
    case "keepNext":
      props.keepNext = xml2.boolAttr(elem, "val", true);
      break;
    case "pageBreakBefore":
      props.pageBreakBefore = xml2.boolAttr(elem, "val", true);
      break;
    case "outlineLvl":
      props.outlineLevel = xml2.intAttr(elem, "val");
      break;
    case "pStyle":
      props.styleName = xml2.attr(elem, "val");
      break;
    case "rPr":
      props.runProps = parseRunProperties(elem, xml2);
      break;
    default:
      return false;
  }
  return true;
}
function parseTabs(elem, xml2) {
  return xml2.elements(elem, "tab").map((e9) => ({
    position: xml2.lengthAttr(e9, "pos"),
    leader: xml2.attr(e9, "leader"),
    style: xml2.attr(e9, "val")
  }));
}
function parseNumbering$1(elem, xml2) {
  var result = {};
  for (let e9 of xml2.elements(elem)) {
    switch (e9.localName) {
      case "numId":
        result.id = xml2.attr(e9, "val");
        break;
      case "ilvl":
        result.level = xml2.intAttr(e9, "val");
        break;
    }
  }
  return result;
}
function parseNumberingPart(elem, xml2) {
  let result = {
    numberings: [],
    abstractNumberings: [],
    bulletPictures: []
  };
  for (let e9 of xml2.elements(elem)) {
    switch (e9.localName) {
      case "num":
        result.numberings.push(parseNumbering(e9, xml2));
        break;
      case "abstractNum":
        result.abstractNumberings.push(parseAbstractNumbering(e9, xml2));
        break;
      case "numPicBullet":
        result.bulletPictures.push(parseNumberingBulletPicture(e9, xml2));
        break;
    }
  }
  return result;
}
function parseNumbering(elem, xml2) {
  let result = {
    id: xml2.attr(elem, "numId"),
    overrides: []
  };
  for (let e9 of xml2.elements(elem)) {
    switch (e9.localName) {
      case "abstractNumId":
        result.abstractId = xml2.attr(e9, "val");
        break;
      case "lvlOverride":
        result.overrides.push(parseNumberingLevelOverrride(e9, xml2));
        break;
    }
  }
  return result;
}
function parseAbstractNumbering(elem, xml2) {
  let result = {
    id: xml2.attr(elem, "abstractNumId"),
    levels: []
  };
  for (let e9 of xml2.elements(elem)) {
    switch (e9.localName) {
      case "name":
        result.name = xml2.attr(e9, "val");
        break;
      case "multiLevelType":
        result.multiLevelType = xml2.attr(e9, "val");
        break;
      case "numStyleLink":
        result.numberingStyleLink = xml2.attr(e9, "val");
        break;
      case "styleLink":
        result.styleLink = xml2.attr(e9, "val");
        break;
      case "lvl":
        result.levels.push(parseNumberingLevel(e9, xml2));
        break;
    }
  }
  return result;
}
function parseNumberingLevel(elem, xml2) {
  let result = {
    level: xml2.intAttr(elem, "ilvl")
  };
  for (let e9 of xml2.elements(elem)) {
    switch (e9.localName) {
      case "start":
        result.start = xml2.attr(e9, "val");
        break;
      case "lvlRestart":
        result.restart = xml2.intAttr(e9, "val");
        break;
      case "numFmt":
        result.format = xml2.attr(e9, "val");
        break;
      case "lvlText":
        result.text = xml2.attr(e9, "val");
        break;
      case "lvlJc":
        result.justification = xml2.attr(e9, "val");
        break;
      case "lvlPicBulletId":
        result.bulletPictureId = xml2.attr(e9, "val");
        break;
      case "pStyle":
        result.paragraphStyle = xml2.attr(e9, "val");
        break;
      case "pPr":
        result.paragraphProps = parseParagraphProperties(e9, xml2);
        break;
      case "rPr":
        result.runProps = parseRunProperties(e9, xml2);
        break;
    }
  }
  return result;
}
function parseNumberingLevelOverrride(elem, xml2) {
  let result = {
    level: xml2.intAttr(elem, "ilvl")
  };
  for (let e9 of xml2.elements(elem)) {
    switch (e9.localName) {
      case "startOverride":
        result.start = xml2.intAttr(e9, "val");
        break;
      case "lvl":
        result.numberingLevel = parseNumberingLevel(e9, xml2);
        break;
    }
  }
  return result;
}
function parseNumberingBulletPicture(elem, xml2) {
  var pict = xml2.element(elem, "pict");
  var shape = pict && xml2.element(pict, "shape");
  var imagedata = shape && xml2.element(shape, "imagedata");
  return imagedata ? {
    id: xml2.attr(elem, "numPicBulletId"),
    referenceId: xml2.attr(imagedata, "id"),
    style: xml2.attr(shape, "style")
  } : null;
}
var NumberingPart = class extends Part {
  constructor(pkg, path6, parser) {
    super(pkg, path6);
    this._documentParser = parser;
  }
  parseXml(root) {
    Object.assign(this, parseNumberingPart(root, this._package.xmlParser));
    this.domNumberings = this._documentParser.parseNumberingFile(root);
  }
};
var StylesPart = class extends Part {
  constructor(pkg, path6, parser) {
    super(pkg, path6);
    this._documentParser = parser;
  }
  parseXml(root) {
    this.styles = this._documentParser.parseStylesFile(root);
  }
};
var DomType;
(function(DomType2) {
  DomType2["Document"] = "document";
  DomType2["Paragraph"] = "paragraph";
  DomType2["Run"] = "run";
  DomType2["Break"] = "break";
  DomType2["NoBreakHyphen"] = "noBreakHyphen";
  DomType2["Table"] = "table";
  DomType2["Row"] = "row";
  DomType2["Cell"] = "cell";
  DomType2["Hyperlink"] = "hyperlink";
  DomType2["SmartTag"] = "smartTag";
  DomType2["Drawing"] = "drawing";
  DomType2["Image"] = "image";
  DomType2["Text"] = "text";
  DomType2["Tab"] = "tab";
  DomType2["Symbol"] = "symbol";
  DomType2["BookmarkStart"] = "bookmarkStart";
  DomType2["BookmarkEnd"] = "bookmarkEnd";
  DomType2["Footer"] = "footer";
  DomType2["Header"] = "header";
  DomType2["FootnoteReference"] = "footnoteReference";
  DomType2["EndnoteReference"] = "endnoteReference";
  DomType2["Footnote"] = "footnote";
  DomType2["Endnote"] = "endnote";
  DomType2["SimpleField"] = "simpleField";
  DomType2["ComplexField"] = "complexField";
  DomType2["Instruction"] = "instruction";
  DomType2["VmlPicture"] = "vmlPicture";
  DomType2["MmlMath"] = "mmlMath";
  DomType2["MmlMathParagraph"] = "mmlMathParagraph";
  DomType2["MmlFraction"] = "mmlFraction";
  DomType2["MmlFunction"] = "mmlFunction";
  DomType2["MmlFunctionName"] = "mmlFunctionName";
  DomType2["MmlNumerator"] = "mmlNumerator";
  DomType2["MmlDenominator"] = "mmlDenominator";
  DomType2["MmlRadical"] = "mmlRadical";
  DomType2["MmlBase"] = "mmlBase";
  DomType2["MmlDegree"] = "mmlDegree";
  DomType2["MmlSuperscript"] = "mmlSuperscript";
  DomType2["MmlSubscript"] = "mmlSubscript";
  DomType2["MmlPreSubSuper"] = "mmlPreSubSuper";
  DomType2["MmlSubArgument"] = "mmlSubArgument";
  DomType2["MmlSuperArgument"] = "mmlSuperArgument";
  DomType2["MmlNary"] = "mmlNary";
  DomType2["MmlDelimiter"] = "mmlDelimiter";
  DomType2["MmlRun"] = "mmlRun";
  DomType2["MmlEquationArray"] = "mmlEquationArray";
  DomType2["MmlLimit"] = "mmlLimit";
  DomType2["MmlLimitLower"] = "mmlLimitLower";
  DomType2["MmlMatrix"] = "mmlMatrix";
  DomType2["MmlMatrixRow"] = "mmlMatrixRow";
  DomType2["MmlBox"] = "mmlBox";
  DomType2["MmlBar"] = "mmlBar";
  DomType2["MmlGroupChar"] = "mmlGroupChar";
  DomType2["VmlElement"] = "vmlElement";
  DomType2["Inserted"] = "inserted";
  DomType2["Deleted"] = "deleted";
  DomType2["DeletedText"] = "deletedText";
  DomType2["Comment"] = "comment";
  DomType2["CommentReference"] = "commentReference";
  DomType2["CommentRangeStart"] = "commentRangeStart";
  DomType2["CommentRangeEnd"] = "commentRangeEnd";
  DomType2["AltChunk"] = "altChunk";
})(DomType || (DomType = {}));
var OpenXmlElementBase = class {
  constructor() {
    this.children = [];
    this.cssStyle = {};
  }
};
var WmlHeader = class extends OpenXmlElementBase {
  constructor() {
    super(...arguments);
    this.type = DomType.Header;
  }
};
var WmlFooter = class extends OpenXmlElementBase {
  constructor() {
    super(...arguments);
    this.type = DomType.Footer;
  }
};
var BaseHeaderFooterPart = class extends Part {
  constructor(pkg, path6, parser) {
    super(pkg, path6);
    this._documentParser = parser;
  }
  parseXml(root) {
    this.rootElement = this.createRootElement();
    this.rootElement.children = this._documentParser.parseBodyElements(root);
  }
};
var HeaderPart = class extends BaseHeaderFooterPart {
  createRootElement() {
    return new WmlHeader();
  }
};
var FooterPart = class extends BaseHeaderFooterPart {
  createRootElement() {
    return new WmlFooter();
  }
};
function parseExtendedProps(root, xmlParser) {
  const result = {};
  for (let el of xmlParser.elements(root)) {
    switch (el.localName) {
      case "Template":
        result.template = el.textContent;
        break;
      case "Pages":
        result.pages = safeParseToInt(el.textContent);
        break;
      case "Words":
        result.words = safeParseToInt(el.textContent);
        break;
      case "Characters":
        result.characters = safeParseToInt(el.textContent);
        break;
      case "Application":
        result.application = el.textContent;
        break;
      case "Lines":
        result.lines = safeParseToInt(el.textContent);
        break;
      case "Paragraphs":
        result.paragraphs = safeParseToInt(el.textContent);
        break;
      case "Company":
        result.company = el.textContent;
        break;
      case "AppVersion":
        result.appVersion = el.textContent;
        break;
    }
  }
  return result;
}
function safeParseToInt(value) {
  if (typeof value === "undefined")
    return;
  return parseInt(value);
}
var ExtendedPropsPart = class extends Part {
  parseXml(root) {
    this.props = parseExtendedProps(root, this._package.xmlParser);
  }
};
function parseCoreProps(root, xmlParser) {
  const result = {};
  for (let el of xmlParser.elements(root)) {
    switch (el.localName) {
      case "title":
        result.title = el.textContent;
        break;
      case "description":
        result.description = el.textContent;
        break;
      case "subject":
        result.subject = el.textContent;
        break;
      case "creator":
        result.creator = el.textContent;
        break;
      case "keywords":
        result.keywords = el.textContent;
        break;
      case "language":
        result.language = el.textContent;
        break;
      case "lastModifiedBy":
        result.lastModifiedBy = el.textContent;
        break;
      case "revision":
        el.textContent && (result.revision = parseInt(el.textContent));
        break;
    }
  }
  return result;
}
var CorePropsPart = class extends Part {
  parseXml(root) {
    this.props = parseCoreProps(root, this._package.xmlParser);
  }
};
var DmlTheme = class {
};
function parseTheme(elem, xml2) {
  var result = new DmlTheme();
  var themeElements = xml2.element(elem, "themeElements");
  for (let el of xml2.elements(themeElements)) {
    switch (el.localName) {
      case "clrScheme":
        result.colorScheme = parseColorScheme(el, xml2);
        break;
      case "fontScheme":
        result.fontScheme = parseFontScheme(el, xml2);
        break;
    }
  }
  return result;
}
function parseColorScheme(elem, xml2) {
  var result = {
    name: xml2.attr(elem, "name"),
    colors: {}
  };
  for (let el of xml2.elements(elem)) {
    var srgbClr = xml2.element(el, "srgbClr");
    var sysClr = xml2.element(el, "sysClr");
    if (srgbClr) {
      result.colors[el.localName] = xml2.attr(srgbClr, "val");
    } else if (sysClr) {
      result.colors[el.localName] = xml2.attr(sysClr, "lastClr");
    }
  }
  return result;
}
function parseFontScheme(elem, xml2) {
  var result = {
    name: xml2.attr(elem, "name")
  };
  for (let el of xml2.elements(elem)) {
    switch (el.localName) {
      case "majorFont":
        result.majorFont = parseFontInfo(el, xml2);
        break;
      case "minorFont":
        result.minorFont = parseFontInfo(el, xml2);
        break;
    }
  }
  return result;
}
function parseFontInfo(elem, xml2) {
  return {
    latinTypeface: xml2.elementAttr(elem, "latin", "typeface"),
    eaTypeface: xml2.elementAttr(elem, "ea", "typeface"),
    csTypeface: xml2.elementAttr(elem, "cs", "typeface")
  };
}
var ThemePart = class extends Part {
  constructor(pkg, path6) {
    super(pkg, path6);
  }
  parseXml(root) {
    this.theme = parseTheme(root, this._package.xmlParser);
  }
};
var WmlBaseNote = class {
};
var WmlFootnote = class extends WmlBaseNote {
  constructor() {
    super(...arguments);
    this.type = DomType.Footnote;
  }
};
var WmlEndnote = class extends WmlBaseNote {
  constructor() {
    super(...arguments);
    this.type = DomType.Endnote;
  }
};
var BaseNotePart = class extends Part {
  constructor(pkg, path6, parser) {
    super(pkg, path6);
    this._documentParser = parser;
  }
};
var FootnotesPart = class extends BaseNotePart {
  constructor(pkg, path6, parser) {
    super(pkg, path6, parser);
  }
  parseXml(root) {
    this.notes = this._documentParser.parseNotes(root, "footnote", WmlFootnote);
  }
};
var EndnotesPart = class extends BaseNotePart {
  constructor(pkg, path6, parser) {
    super(pkg, path6, parser);
  }
  parseXml(root) {
    this.notes = this._documentParser.parseNotes(root, "endnote", WmlEndnote);
  }
};
function parseSettings(elem, xml2) {
  var result = {};
  for (let el of xml2.elements(elem)) {
    switch (el.localName) {
      case "defaultTabStop":
        result.defaultTabStop = xml2.lengthAttr(el, "val");
        break;
      case "footnotePr":
        result.footnoteProps = parseNoteProperties(el, xml2);
        break;
      case "endnotePr":
        result.endnoteProps = parseNoteProperties(el, xml2);
        break;
      case "autoHyphenation":
        result.autoHyphenation = xml2.boolAttr(el, "val");
        break;
    }
  }
  return result;
}
function parseNoteProperties(elem, xml2) {
  var result = {
    defaultNoteIds: []
  };
  for (let el of xml2.elements(elem)) {
    switch (el.localName) {
      case "numFmt":
        result.nummeringFormat = xml2.attr(el, "val");
        break;
      case "footnote":
      case "endnote":
        result.defaultNoteIds.push(xml2.attr(el, "id"));
        break;
    }
  }
  return result;
}
var SettingsPart = class extends Part {
  constructor(pkg, path6) {
    super(pkg, path6);
  }
  parseXml(root) {
    this.settings = parseSettings(root, this._package.xmlParser);
  }
};
function parseCustomProps(root, xml2) {
  return xml2.elements(root, "property").map((e9) => {
    const firstChild = e9.firstChild;
    return {
      formatId: xml2.attr(e9, "fmtid"),
      name: xml2.attr(e9, "name"),
      type: firstChild.nodeName,
      value: firstChild.textContent
    };
  });
}
var CustomPropsPart = class extends Part {
  parseXml(root) {
    this.props = parseCustomProps(root, this._package.xmlParser);
  }
};
var CommentsPart = class extends Part {
  constructor(pkg, path6, parser) {
    super(pkg, path6);
    this._documentParser = parser;
  }
  parseXml(root) {
    this.comments = this._documentParser.parseComments(root);
    this.commentMap = keyBy(this.comments, (x2) => x2.id);
  }
};
var CommentsExtendedPart = class extends Part {
  constructor(pkg, path6) {
    super(pkg, path6);
    this.comments = [];
  }
  parseXml(root) {
    const xml2 = this._package.xmlParser;
    for (let el of xml2.elements(root, "commentEx")) {
      this.comments.push({
        paraId: xml2.attr(el, "paraId"),
        paraIdParent: xml2.attr(el, "paraIdParent"),
        done: xml2.boolAttr(el, "done")
      });
    }
    this.commentMap = keyBy(this.comments, (x2) => x2.paraId);
  }
};
var topLevelRels = [
  { type: RelationshipTypes.OfficeDocument, target: "word/document.xml" },
  { type: RelationshipTypes.ExtendedProperties, target: "docProps/app.xml" },
  { type: RelationshipTypes.CoreProperties, target: "docProps/core.xml" },
  { type: RelationshipTypes.CustomProperties, target: "docProps/custom.xml" }
];
var WordDocument = class _WordDocument {
  constructor() {
    this.parts = [];
    this.partsMap = {};
  }
  static async load(blob, parser, options) {
    var d4 = new _WordDocument();
    d4._options = options;
    d4._parser = parser;
    d4._package = await OpenXmlPackage.load(blob, options);
    d4.rels = await d4._package.loadRelationships();
    await Promise.all(topLevelRels.map((rel2) => {
      const r8 = d4.rels.find((x2) => x2.type === rel2.type) ?? rel2;
      return d4.loadRelationshipPart(r8.target, r8.type);
    }));
    return d4;
  }
  save(type = "blob") {
    return this._package.save(type);
  }
  async loadRelationshipPart(path6, type) {
    if (this.partsMap[path6])
      return this.partsMap[path6];
    if (!this._package.get(path6))
      return null;
    let part = null;
    switch (type) {
      case RelationshipTypes.OfficeDocument:
        this.documentPart = part = new DocumentPart(this._package, path6, this._parser);
        break;
      case RelationshipTypes.FontTable:
        this.fontTablePart = part = new FontTablePart(this._package, path6);
        break;
      case RelationshipTypes.Numbering:
        this.numberingPart = part = new NumberingPart(this._package, path6, this._parser);
        break;
      case RelationshipTypes.Styles:
        this.stylesPart = part = new StylesPart(this._package, path6, this._parser);
        break;
      case RelationshipTypes.Theme:
        this.themePart = part = new ThemePart(this._package, path6);
        break;
      case RelationshipTypes.Footnotes:
        this.footnotesPart = part = new FootnotesPart(this._package, path6, this._parser);
        break;
      case RelationshipTypes.Endnotes:
        this.endnotesPart = part = new EndnotesPart(this._package, path6, this._parser);
        break;
      case RelationshipTypes.Footer:
        part = new FooterPart(this._package, path6, this._parser);
        break;
      case RelationshipTypes.Header:
        part = new HeaderPart(this._package, path6, this._parser);
        break;
      case RelationshipTypes.CoreProperties:
        this.corePropsPart = part = new CorePropsPart(this._package, path6);
        break;
      case RelationshipTypes.ExtendedProperties:
        this.extendedPropsPart = part = new ExtendedPropsPart(this._package, path6);
        break;
      case RelationshipTypes.CustomProperties:
        part = new CustomPropsPart(this._package, path6);
        break;
      case RelationshipTypes.Settings:
        this.settingsPart = part = new SettingsPart(this._package, path6);
        break;
      case RelationshipTypes.Comments:
        this.commentsPart = part = new CommentsPart(this._package, path6, this._parser);
        break;
      case RelationshipTypes.CommentsExtended:
        this.commentsExtendedPart = part = new CommentsExtendedPart(this._package, path6);
        break;
    }
    if (part == null)
      return Promise.resolve(null);
    this.partsMap[path6] = part;
    this.parts.push(part);
    await part.load();
    if (part.rels?.length > 0) {
      const [folder] = splitPath(part.path);
      await Promise.all(part.rels.map((rel2) => this.loadRelationshipPart(resolvePath(rel2.target, folder), rel2.type)));
    }
    return part;
  }
  async loadDocumentImage(id, part) {
    const x2 = await this.loadResource(part ?? this.documentPart, id, "blob");
    return this.blobToURL(x2);
  }
  async loadNumberingImage(id) {
    const x2 = await this.loadResource(this.numberingPart, id, "blob");
    return this.blobToURL(x2);
  }
  async loadFont(id, key) {
    const x2 = await this.loadResource(this.fontTablePart, id, "uint8array");
    return x2 ? this.blobToURL(new Blob([deobfuscate(x2, key)])) : x2;
  }
  async loadAltChunk(id, part) {
    return await this.loadResource(part ?? this.documentPart, id, "string");
  }
  blobToURL(blob) {
    if (!blob)
      return null;
    if (this._options.useBase64URL) {
      return blobToBase64(blob);
    }
    return URL.createObjectURL(blob);
  }
  findPartByRelId(id, basePart = null) {
    var rel2 = (basePart.rels ?? this.rels).find((r8) => r8.id == id);
    const folder = basePart ? splitPath(basePart.path)[0] : "";
    return rel2 ? this.partsMap[resolvePath(rel2.target, folder)] : null;
  }
  getPathById(part, id) {
    const rel2 = part.rels.find((x2) => x2.id == id);
    const [folder] = splitPath(part.path);
    return rel2 ? resolvePath(rel2.target, folder) : null;
  }
  loadResource(part, id, outputType) {
    const path6 = this.getPathById(part, id);
    return path6 ? this._package.load(path6, outputType) : Promise.resolve(null);
  }
};
function deobfuscate(data, guidKey) {
  const len = 16;
  const trimmed = guidKey.replace(/{|}|-/g, "");
  const numbers = new Array(len);
  for (let i7 = 0; i7 < len; i7++)
    numbers[len - i7 - 1] = parseInt(trimmed.substring(i7 * 2, i7 * 2 + 2), 16);
  for (let i7 = 0; i7 < 32; i7++)
    data[i7] = data[i7] ^ numbers[i7 % len];
  return data;
}
function parseBookmarkStart(elem, xml2) {
  return {
    type: DomType.BookmarkStart,
    id: xml2.attr(elem, "id"),
    name: xml2.attr(elem, "name"),
    colFirst: xml2.intAttr(elem, "colFirst"),
    colLast: xml2.intAttr(elem, "colLast")
  };
}
function parseBookmarkEnd(elem, xml2) {
  return {
    type: DomType.BookmarkEnd,
    id: xml2.attr(elem, "id")
  };
}
var VmlElement = class extends OpenXmlElementBase {
  constructor() {
    super(...arguments);
    this.type = DomType.VmlElement;
    this.attrs = {};
  }
};
function parseVmlElement(elem, parser) {
  var result = new VmlElement();
  switch (elem.localName) {
    case "rect":
      result.tagName = "rect";
      Object.assign(result.attrs, { width: "100%", height: "100%" });
      break;
    case "oval":
      result.tagName = "ellipse";
      Object.assign(result.attrs, { cx: "50%", cy: "50%", rx: "50%", ry: "50%" });
      break;
    case "line":
      result.tagName = "line";
      break;
    case "shape":
      result.tagName = "g";
      break;
    case "textbox":
      result.tagName = "foreignObject";
      Object.assign(result.attrs, { width: "100%", height: "100%" });
      break;
    default:
      return null;
  }
  for (const at of globalXmlParser.attrs(elem)) {
    switch (at.localName) {
      case "style":
        result.cssStyleText = at.value;
        break;
      case "fillcolor":
        result.attrs.fill = at.value;
        break;
      case "from":
        const [x1, y1] = parsePoint(at.value);
        Object.assign(result.attrs, { x1, y1 });
        break;
      case "to":
        const [x2, y22] = parsePoint(at.value);
        Object.assign(result.attrs, { x2, y2: y22 });
        break;
    }
  }
  for (const el of globalXmlParser.elements(elem)) {
    switch (el.localName) {
      case "stroke":
        Object.assign(result.attrs, parseStroke(el));
        break;
      case "fill":
        Object.assign(result.attrs, parseFill());
        break;
      case "imagedata":
        result.tagName = "image";
        Object.assign(result.attrs, { width: "100%", height: "100%" });
        result.imageHref = {
          id: globalXmlParser.attr(el, "id"),
          title: globalXmlParser.attr(el, "title")
        };
        break;
      case "txbxContent":
        result.children.push(...parser.parseBodyElements(el));
        break;
      default:
        const child = parseVmlElement(el, parser);
        child && result.children.push(child);
        break;
    }
  }
  return result;
}
function parseStroke(el) {
  return {
    "stroke": globalXmlParser.attr(el, "color"),
    "stroke-width": globalXmlParser.lengthAttr(el, "weight", LengthUsage.Emu) ?? "1px"
  };
}
function parseFill(el) {
  return {};
}
function parsePoint(val2) {
  return val2.split(",");
}
var WmlComment = class extends OpenXmlElementBase {
  constructor() {
    super(...arguments);
    this.type = DomType.Comment;
  }
};
var WmlCommentReference = class extends OpenXmlElementBase {
  constructor(id) {
    super();
    this.id = id;
    this.type = DomType.CommentReference;
  }
};
var WmlCommentRangeStart = class extends OpenXmlElementBase {
  constructor(id) {
    super();
    this.id = id;
    this.type = DomType.CommentRangeStart;
  }
};
var WmlCommentRangeEnd = class extends OpenXmlElementBase {
  constructor(id) {
    super();
    this.id = id;
    this.type = DomType.CommentRangeEnd;
  }
};
var autos = {
  shd: "inherit",
  color: "black",
  borderColor: "black",
  highlight: "transparent"
};
var supportedNamespaceURIs = [];
var mmlTagMap = {
  "oMath": DomType.MmlMath,
  "oMathPara": DomType.MmlMathParagraph,
  "f": DomType.MmlFraction,
  "func": DomType.MmlFunction,
  "fName": DomType.MmlFunctionName,
  "num": DomType.MmlNumerator,
  "den": DomType.MmlDenominator,
  "rad": DomType.MmlRadical,
  "deg": DomType.MmlDegree,
  "e": DomType.MmlBase,
  "sSup": DomType.MmlSuperscript,
  "sSub": DomType.MmlSubscript,
  "sPre": DomType.MmlPreSubSuper,
  "sup": DomType.MmlSuperArgument,
  "sub": DomType.MmlSubArgument,
  "d": DomType.MmlDelimiter,
  "nary": DomType.MmlNary,
  "eqArr": DomType.MmlEquationArray,
  "lim": DomType.MmlLimit,
  "limLow": DomType.MmlLimitLower,
  "m": DomType.MmlMatrix,
  "mr": DomType.MmlMatrixRow,
  "box": DomType.MmlBox,
  "bar": DomType.MmlBar,
  "groupChr": DomType.MmlGroupChar
};
var DocumentParser = class {
  constructor(options) {
    this.options = {
      ignoreWidth: false,
      debug: false,
      ...options
    };
  }
  parseNotes(xmlDoc, elemName, elemClass) {
    var result = [];
    for (let el of globalXmlParser.elements(xmlDoc, elemName)) {
      const node = new elemClass();
      node.id = globalXmlParser.attr(el, "id");
      node.noteType = globalXmlParser.attr(el, "type");
      node.children = this.parseBodyElements(el);
      result.push(node);
    }
    return result;
  }
  parseComments(xmlDoc) {
    var result = [];
    for (let el of globalXmlParser.elements(xmlDoc, "comment")) {
      const item = new WmlComment();
      item.id = globalXmlParser.attr(el, "id");
      item.author = globalXmlParser.attr(el, "author");
      item.initials = globalXmlParser.attr(el, "initials");
      item.date = globalXmlParser.attr(el, "date");
      item.children = this.parseBodyElements(el);
      result.push(item);
    }
    return result;
  }
  parseDocumentFile(xmlDoc) {
    var xbody = globalXmlParser.element(xmlDoc, "body");
    var background = globalXmlParser.element(xmlDoc, "background");
    var sectPr = globalXmlParser.element(xbody, "sectPr");
    return {
      type: DomType.Document,
      children: this.parseBodyElements(xbody),
      props: sectPr ? parseSectionProperties(sectPr, globalXmlParser) : {},
      cssStyle: background ? this.parseBackground(background) : {}
    };
  }
  parseBackground(elem) {
    var result = {};
    var color = xmlUtil.colorAttr(elem, "color");
    if (color) {
      result["background-color"] = color;
    }
    return result;
  }
  parseBodyElements(element) {
    var children = [];
    for (const elem of globalXmlParser.elements(element)) {
      switch (elem.localName) {
        case "p":
          children.push(this.parseParagraph(elem));
          break;
        case "altChunk":
          children.push(this.parseAltChunk(elem));
          break;
        case "tbl":
          children.push(this.parseTable(elem));
          break;
        case "sdt":
          children.push(...this.parseSdt(elem, (e9) => this.parseBodyElements(e9)));
          break;
      }
    }
    return children;
  }
  parseStylesFile(xstyles) {
    var result = [];
    for (const n7 of globalXmlParser.elements(xstyles)) {
      switch (n7.localName) {
        case "style":
          result.push(this.parseStyle(n7));
          break;
        case "docDefaults":
          result.push(this.parseDefaultStyles(n7));
          break;
      }
    }
    return result;
  }
  parseDefaultStyles(node) {
    var result = {
      id: null,
      name: null,
      target: null,
      basedOn: null,
      styles: []
    };
    for (const c6 of globalXmlParser.elements(node)) {
      switch (c6.localName) {
        case "rPrDefault":
          var rPr = globalXmlParser.element(c6, "rPr");
          if (rPr)
            result.styles.push({
              target: "span",
              values: this.parseDefaultProperties(rPr, {})
            });
          break;
        case "pPrDefault":
          var pPr = globalXmlParser.element(c6, "pPr");
          if (pPr)
            result.styles.push({
              target: "p",
              values: this.parseDefaultProperties(pPr, {})
            });
          break;
      }
    }
    return result;
  }
  parseStyle(node) {
    var result = {
      id: globalXmlParser.attr(node, "styleId"),
      isDefault: globalXmlParser.boolAttr(node, "default"),
      name: null,
      target: null,
      basedOn: null,
      styles: [],
      linked: null
    };
    switch (globalXmlParser.attr(node, "type")) {
      case "paragraph":
        result.target = "p";
        break;
      case "table":
        result.target = "table";
        break;
      case "character":
        result.target = "span";
        break;
    }
    for (const n7 of globalXmlParser.elements(node)) {
      switch (n7.localName) {
        case "basedOn":
          result.basedOn = globalXmlParser.attr(n7, "val");
          break;
        case "name":
          result.name = globalXmlParser.attr(n7, "val");
          break;
        case "link":
          result.linked = globalXmlParser.attr(n7, "val");
          break;
        case "next":
          result.next = globalXmlParser.attr(n7, "val");
          break;
        case "aliases":
          result.aliases = globalXmlParser.attr(n7, "val").split(",");
          break;
        case "pPr":
          result.styles.push({
            target: "p",
            values: this.parseDefaultProperties(n7, {})
          });
          result.paragraphProps = parseParagraphProperties(n7, globalXmlParser);
          break;
        case "rPr":
          result.styles.push({
            target: "span",
            values: this.parseDefaultProperties(n7, {})
          });
          result.runProps = parseRunProperties(n7, globalXmlParser);
          break;
        case "tblPr":
        case "tcPr":
          result.styles.push({
            target: "td",
            values: this.parseDefaultProperties(n7, {})
          });
          break;
        case "tblStylePr":
          for (let s6 of this.parseTableStyle(n7))
            result.styles.push(s6);
          break;
        case "rsid":
        case "qFormat":
        case "hidden":
        case "semiHidden":
        case "unhideWhenUsed":
        case "autoRedefine":
        case "uiPriority":
          break;
        default:
          this.options.debug && console.warn(`DOCX: Unknown style element: ${n7.localName}`);
      }
    }
    return result;
  }
  parseTableStyle(node) {
    var result = [];
    var type = globalXmlParser.attr(node, "type");
    var selector = "";
    var modificator = "";
    switch (type) {
      case "firstRow":
        modificator = ".first-row";
        selector = "tr.first-row td";
        break;
      case "lastRow":
        modificator = ".last-row";
        selector = "tr.last-row td";
        break;
      case "firstCol":
        modificator = ".first-col";
        selector = "td.first-col";
        break;
      case "lastCol":
        modificator = ".last-col";
        selector = "td.last-col";
        break;
      case "band1Vert":
        modificator = ":not(.no-vband)";
        selector = "td.odd-col";
        break;
      case "band2Vert":
        modificator = ":not(.no-vband)";
        selector = "td.even-col";
        break;
      case "band1Horz":
        modificator = ":not(.no-hband)";
        selector = "tr.odd-row";
        break;
      case "band2Horz":
        modificator = ":not(.no-hband)";
        selector = "tr.even-row";
        break;
      default:
        return [];
    }
    for (const n7 of globalXmlParser.elements(node)) {
      switch (n7.localName) {
        case "pPr":
          result.push({
            target: `${selector} p`,
            mod: modificator,
            values: this.parseDefaultProperties(n7, {})
          });
          break;
        case "rPr":
          result.push({
            target: `${selector} span`,
            mod: modificator,
            values: this.parseDefaultProperties(n7, {})
          });
          break;
        case "tblPr":
        case "tcPr":
          result.push({
            target: selector,
            mod: modificator,
            values: this.parseDefaultProperties(n7, {})
          });
          break;
      }
    }
    return result;
  }
  parseNumberingFile(node) {
    var result = [];
    var mapping = {};
    var bullets = [];
    for (const n7 of globalXmlParser.elements(node)) {
      switch (n7.localName) {
        case "abstractNum":
          this.parseAbstractNumbering(n7, bullets).forEach((x2) => result.push(x2));
          break;
        case "numPicBullet":
          bullets.push(this.parseNumberingPicBullet(n7));
          break;
        case "num":
          var numId = globalXmlParser.attr(n7, "numId");
          var abstractNumId = globalXmlParser.elementAttr(n7, "abstractNumId", "val");
          mapping[abstractNumId] = numId;
          break;
      }
    }
    result.forEach((x2) => x2.id = mapping[x2.id]);
    return result;
  }
  parseNumberingPicBullet(elem) {
    var pict = globalXmlParser.element(elem, "pict");
    var shape = pict && globalXmlParser.element(pict, "shape");
    var imagedata = shape && globalXmlParser.element(shape, "imagedata");
    return imagedata ? {
      id: globalXmlParser.intAttr(elem, "numPicBulletId"),
      src: globalXmlParser.attr(imagedata, "id"),
      style: globalXmlParser.attr(shape, "style")
    } : null;
  }
  parseAbstractNumbering(node, bullets) {
    var result = [];
    var id = globalXmlParser.attr(node, "abstractNumId");
    for (const n7 of globalXmlParser.elements(node)) {
      switch (n7.localName) {
        case "lvl":
          result.push(this.parseNumberingLevel(id, n7, bullets));
          break;
      }
    }
    return result;
  }
  parseNumberingLevel(id, node, bullets) {
    var result = {
      id,
      level: globalXmlParser.intAttr(node, "ilvl"),
      start: 1,
      pStyleName: void 0,
      pStyle: {},
      rStyle: {},
      suff: "tab"
    };
    for (const n7 of globalXmlParser.elements(node)) {
      switch (n7.localName) {
        case "start":
          result.start = globalXmlParser.intAttr(n7, "val");
          break;
        case "pPr":
          this.parseDefaultProperties(n7, result.pStyle);
          break;
        case "rPr":
          this.parseDefaultProperties(n7, result.rStyle);
          break;
        case "lvlPicBulletId":
          var bulletId = globalXmlParser.intAttr(n7, "val");
          result.bullet = bullets.find((x2) => x2?.id == bulletId);
          break;
        case "lvlText":
          result.levelText = globalXmlParser.attr(n7, "val");
          break;
        case "pStyle":
          result.pStyleName = globalXmlParser.attr(n7, "val");
          break;
        case "numFmt":
          result.format = globalXmlParser.attr(n7, "val");
          break;
        case "suff":
          result.suff = globalXmlParser.attr(n7, "val");
          break;
      }
    }
    return result;
  }
  parseSdt(node, parser) {
    const sdtContent = globalXmlParser.element(node, "sdtContent");
    return sdtContent ? parser(sdtContent) : [];
  }
  parseInserted(node, parentParser) {
    return {
      type: DomType.Inserted,
      children: parentParser(node)?.children ?? []
    };
  }
  parseDeleted(node, parentParser) {
    return {
      type: DomType.Deleted,
      children: parentParser(node)?.children ?? []
    };
  }
  parseAltChunk(node) {
    return { type: DomType.AltChunk, children: [], id: globalXmlParser.attr(node, "id") };
  }
  parseParagraph(node) {
    var result = { type: DomType.Paragraph, children: [] };
    for (let el of globalXmlParser.elements(node)) {
      switch (el.localName) {
        case "pPr":
          this.parseParagraphProperties(el, result);
          break;
        case "r":
          result.children.push(this.parseRun(el, result));
          break;
        case "hyperlink":
          result.children.push(this.parseHyperlink(el, result));
          break;
        case "smartTag":
          result.children.push(this.parseSmartTag(el, result));
          break;
        case "bookmarkStart":
          result.children.push(parseBookmarkStart(el, globalXmlParser));
          break;
        case "bookmarkEnd":
          result.children.push(parseBookmarkEnd(el, globalXmlParser));
          break;
        case "commentRangeStart":
          result.children.push(new WmlCommentRangeStart(globalXmlParser.attr(el, "id")));
          break;
        case "commentRangeEnd":
          result.children.push(new WmlCommentRangeEnd(globalXmlParser.attr(el, "id")));
          break;
        case "oMath":
        case "oMathPara":
          result.children.push(this.parseMathElement(el));
          break;
        case "sdt":
          result.children.push(...this.parseSdt(el, (e9) => this.parseParagraph(e9).children));
          break;
        case "ins":
          result.children.push(this.parseInserted(el, (e9) => this.parseParagraph(e9)));
          break;
        case "del":
          result.children.push(this.parseDeleted(el, (e9) => this.parseParagraph(e9)));
          break;
      }
    }
    return result;
  }
  parseParagraphProperties(elem, paragraph) {
    this.parseDefaultProperties(elem, paragraph.cssStyle = {}, null, (c6) => {
      if (parseParagraphProperty(c6, paragraph, globalXmlParser))
        return true;
      switch (c6.localName) {
        case "pStyle":
          paragraph.styleName = globalXmlParser.attr(c6, "val");
          break;
        case "cnfStyle":
          paragraph.className = values.classNameOfCnfStyle(c6);
          break;
        case "framePr":
          this.parseFrame(c6, paragraph);
          break;
        case "rPr":
          break;
        default:
          return false;
      }
      return true;
    });
  }
  parseFrame(node, paragraph) {
    var dropCap = globalXmlParser.attr(node, "dropCap");
    if (dropCap == "drop")
      paragraph.cssStyle["float"] = "left";
  }
  parseHyperlink(node, parent) {
    var result = { type: DomType.Hyperlink, parent, children: [] };
    result.anchor = globalXmlParser.attr(node, "anchor");
    result.id = globalXmlParser.attr(node, "id");
    for (const c6 of globalXmlParser.elements(node)) {
      switch (c6.localName) {
        case "r":
          result.children.push(this.parseRun(c6, result));
          break;
      }
    }
    return result;
  }
  parseSmartTag(node, parent) {
    var result = { type: DomType.SmartTag, parent, children: [] };
    var uri = globalXmlParser.attr(node, "uri");
    var element = globalXmlParser.attr(node, "element");
    if (uri)
      result.uri = uri;
    if (element)
      result.element = element;
    for (const c6 of globalXmlParser.elements(node)) {
      switch (c6.localName) {
        case "r":
          result.children.push(this.parseRun(c6, result));
          break;
      }
    }
    return result;
  }
  parseRun(node, parent) {
    var result = { type: DomType.Run, parent, children: [] };
    for (let c6 of globalXmlParser.elements(node)) {
      c6 = this.checkAlternateContent(c6);
      switch (c6.localName) {
        case "t":
          result.children.push({
            type: DomType.Text,
            text: c6.textContent
          });
          break;
        case "delText":
          result.children.push({
            type: DomType.DeletedText,
            text: c6.textContent
          });
          break;
        case "commentReference":
          result.children.push(new WmlCommentReference(globalXmlParser.attr(c6, "id")));
          break;
        case "fldSimple":
          result.children.push({
            type: DomType.SimpleField,
            instruction: globalXmlParser.attr(c6, "instr"),
            lock: globalXmlParser.boolAttr(c6, "lock", false),
            dirty: globalXmlParser.boolAttr(c6, "dirty", false)
          });
          break;
        case "instrText":
          result.fieldRun = true;
          result.children.push({
            type: DomType.Instruction,
            text: c6.textContent
          });
          break;
        case "fldChar":
          result.fieldRun = true;
          result.children.push({
            type: DomType.ComplexField,
            charType: globalXmlParser.attr(c6, "fldCharType"),
            lock: globalXmlParser.boolAttr(c6, "lock", false),
            dirty: globalXmlParser.boolAttr(c6, "dirty", false)
          });
          break;
        case "noBreakHyphen":
          result.children.push({ type: DomType.NoBreakHyphen });
          break;
        case "br":
          result.children.push({
            type: DomType.Break,
            break: globalXmlParser.attr(c6, "type") || "textWrapping"
          });
          break;
        case "lastRenderedPageBreak":
          result.children.push({
            type: DomType.Break,
            break: "lastRenderedPageBreak"
          });
          break;
        case "sym":
          result.children.push({
            type: DomType.Symbol,
            font: encloseFontFamily(globalXmlParser.attr(c6, "font")),
            char: globalXmlParser.attr(c6, "char")
          });
          break;
        case "tab":
          result.children.push({ type: DomType.Tab });
          break;
        case "footnoteReference":
          result.children.push({
            type: DomType.FootnoteReference,
            id: globalXmlParser.attr(c6, "id")
          });
          break;
        case "endnoteReference":
          result.children.push({
            type: DomType.EndnoteReference,
            id: globalXmlParser.attr(c6, "id")
          });
          break;
        case "drawing":
          let d4 = this.parseDrawing(c6);
          if (d4)
            result.children = [d4];
          break;
        case "pict":
          result.children.push(this.parseVmlPicture(c6));
          break;
        case "rPr":
          this.parseRunProperties(c6, result);
          break;
      }
    }
    return result;
  }
  parseMathElement(elem) {
    const propsTag = `${elem.localName}Pr`;
    const result = { type: mmlTagMap[elem.localName], children: [] };
    for (const el of globalXmlParser.elements(elem)) {
      const childType = mmlTagMap[el.localName];
      if (childType) {
        result.children.push(this.parseMathElement(el));
      } else if (el.localName == "r") {
        var run = this.parseRun(el);
        run.type = DomType.MmlRun;
        result.children.push(run);
      } else if (el.localName == propsTag) {
        result.props = this.parseMathProperies(el);
      }
    }
    return result;
  }
  parseMathProperies(elem) {
    const result = {};
    for (const el of globalXmlParser.elements(elem)) {
      switch (el.localName) {
        case "chr":
          result.char = globalXmlParser.attr(el, "val");
          break;
        case "vertJc":
          result.verticalJustification = globalXmlParser.attr(el, "val");
          break;
        case "pos":
          result.position = globalXmlParser.attr(el, "val");
          break;
        case "degHide":
          result.hideDegree = globalXmlParser.boolAttr(el, "val");
          break;
        case "begChr":
          result.beginChar = globalXmlParser.attr(el, "val");
          break;
        case "endChr":
          result.endChar = globalXmlParser.attr(el, "val");
          break;
      }
    }
    return result;
  }
  parseRunProperties(elem, run) {
    this.parseDefaultProperties(elem, run.cssStyle = {}, null, (c6) => {
      switch (c6.localName) {
        case "rStyle":
          run.styleName = globalXmlParser.attr(c6, "val");
          break;
        case "vertAlign":
          run.verticalAlign = values.valueOfVertAlign(c6, true);
          break;
        default:
          return false;
      }
      return true;
    });
  }
  parseVmlPicture(elem) {
    const result = { type: DomType.VmlPicture, children: [] };
    for (const el of globalXmlParser.elements(elem)) {
      const child = parseVmlElement(el, this);
      child && result.children.push(child);
    }
    return result;
  }
  checkAlternateContent(elem) {
    if (elem.localName != "AlternateContent")
      return elem;
    var choice = globalXmlParser.element(elem, "Choice");
    if (choice) {
      var requires = globalXmlParser.attr(choice, "Requires");
      var namespaceURI = elem.lookupNamespaceURI(requires);
      if (supportedNamespaceURIs.includes(namespaceURI))
        return choice.firstElementChild;
    }
    return globalXmlParser.element(elem, "Fallback")?.firstElementChild;
  }
  parseDrawing(node) {
    for (var n7 of globalXmlParser.elements(node)) {
      switch (n7.localName) {
        case "inline":
        case "anchor":
          return this.parseDrawingWrapper(n7);
      }
    }
  }
  parseDrawingWrapper(node) {
    var result = { type: DomType.Drawing, children: [], cssStyle: {} };
    var isAnchor = node.localName == "anchor";
    let wrapType = null;
    let simplePos = globalXmlParser.boolAttr(node, "simplePos");
    globalXmlParser.boolAttr(node, "behindDoc");
    let posX = { relative: "page", align: "left", offset: "0" };
    let posY = { relative: "page", align: "top", offset: "0" };
    for (var n7 of globalXmlParser.elements(node)) {
      switch (n7.localName) {
        case "simplePos":
          if (simplePos) {
            posX.offset = globalXmlParser.lengthAttr(n7, "x", LengthUsage.Emu);
            posY.offset = globalXmlParser.lengthAttr(n7, "y", LengthUsage.Emu);
          }
          break;
        case "extent":
          result.cssStyle["width"] = globalXmlParser.lengthAttr(n7, "cx", LengthUsage.Emu);
          result.cssStyle["height"] = globalXmlParser.lengthAttr(n7, "cy", LengthUsage.Emu);
          break;
        case "positionH":
        case "positionV":
          if (!simplePos) {
            let pos = n7.localName == "positionH" ? posX : posY;
            var alignNode = globalXmlParser.element(n7, "align");
            var offsetNode = globalXmlParser.element(n7, "posOffset");
            pos.relative = globalXmlParser.attr(n7, "relativeFrom") ?? pos.relative;
            if (alignNode)
              pos.align = alignNode.textContent;
            if (offsetNode)
              pos.offset = convertLength(offsetNode.textContent, LengthUsage.Emu);
          }
          break;
        case "wrapTopAndBottom":
          wrapType = "wrapTopAndBottom";
          break;
        case "wrapNone":
          wrapType = "wrapNone";
          break;
        case "graphic":
          var g3 = this.parseGraphic(n7);
          if (g3)
            result.children.push(g3);
          break;
      }
    }
    if (wrapType == "wrapTopAndBottom") {
      result.cssStyle["display"] = "block";
      if (posX.align) {
        result.cssStyle["text-align"] = posX.align;
        result.cssStyle["width"] = "100%";
      }
    } else if (wrapType == "wrapNone") {
      result.cssStyle["display"] = "block";
      result.cssStyle["position"] = "relative";
      result.cssStyle["width"] = "0px";
      result.cssStyle["height"] = "0px";
      if (posX.offset)
        result.cssStyle["left"] = posX.offset;
      if (posY.offset)
        result.cssStyle["top"] = posY.offset;
    } else if (isAnchor && (posX.align == "left" || posX.align == "right")) {
      result.cssStyle["float"] = posX.align;
    }
    return result;
  }
  parseGraphic(elem) {
    var graphicData = globalXmlParser.element(elem, "graphicData");
    for (let n7 of globalXmlParser.elements(graphicData)) {
      switch (n7.localName) {
        case "pic":
          return this.parsePicture(n7);
      }
    }
    return null;
  }
  parsePicture(elem) {
    var result = { type: DomType.Image, src: "", cssStyle: {} };
    var blipFill = globalXmlParser.element(elem, "blipFill");
    var blip = globalXmlParser.element(blipFill, "blip");
    var srcRect = globalXmlParser.element(blipFill, "srcRect");
    result.src = globalXmlParser.attr(blip, "embed");
    if (srcRect) {
      result.srcRect = [
        globalXmlParser.intAttr(srcRect, "l", 0) / 1e5,
        globalXmlParser.intAttr(srcRect, "t", 0) / 1e5,
        globalXmlParser.intAttr(srcRect, "r", 0) / 1e5,
        globalXmlParser.intAttr(srcRect, "b", 0) / 1e5
      ];
    }
    var spPr = globalXmlParser.element(elem, "spPr");
    var xfrm = globalXmlParser.element(spPr, "xfrm");
    result.cssStyle["position"] = "relative";
    if (xfrm) {
      result.rotation = globalXmlParser.intAttr(xfrm, "rot", 0) / 6e4;
      for (var n7 of globalXmlParser.elements(xfrm)) {
        switch (n7.localName) {
          case "ext":
            result.cssStyle["width"] = globalXmlParser.lengthAttr(n7, "cx", LengthUsage.Emu);
            result.cssStyle["height"] = globalXmlParser.lengthAttr(n7, "cy", LengthUsage.Emu);
            break;
          case "off":
            result.cssStyle["left"] = globalXmlParser.lengthAttr(n7, "x", LengthUsage.Emu);
            result.cssStyle["top"] = globalXmlParser.lengthAttr(n7, "y", LengthUsage.Emu);
            break;
        }
      }
    }
    return result;
  }
  parseTable(node) {
    var result = { type: DomType.Table, children: [] };
    for (const c6 of globalXmlParser.elements(node)) {
      switch (c6.localName) {
        case "tr":
          result.children.push(this.parseTableRow(c6));
          break;
        case "tblGrid":
          result.columns = this.parseTableColumns(c6);
          break;
        case "tblPr":
          this.parseTableProperties(c6, result);
          break;
      }
    }
    return result;
  }
  parseTableColumns(node) {
    var result = [];
    for (const n7 of globalXmlParser.elements(node)) {
      switch (n7.localName) {
        case "gridCol":
          result.push({ width: globalXmlParser.lengthAttr(n7, "w") });
          break;
      }
    }
    return result;
  }
  parseTableProperties(elem, table) {
    table.cssStyle = {};
    table.cellStyle = {};
    this.parseDefaultProperties(elem, table.cssStyle, table.cellStyle, (c6) => {
      switch (c6.localName) {
        case "tblStyle":
          table.styleName = globalXmlParser.attr(c6, "val");
          break;
        case "tblLook":
          table.className = values.classNameOftblLook(c6);
          break;
        case "tblpPr":
          this.parseTablePosition(c6, table);
          break;
        case "tblStyleColBandSize":
          table.colBandSize = globalXmlParser.intAttr(c6, "val");
          break;
        case "tblStyleRowBandSize":
          table.rowBandSize = globalXmlParser.intAttr(c6, "val");
          break;
        case "hidden":
          table.cssStyle["display"] = "none";
          break;
        default:
          return false;
      }
      return true;
    });
    switch (table.cssStyle["text-align"]) {
      case "center":
        delete table.cssStyle["text-align"];
        table.cssStyle["margin-left"] = "auto";
        table.cssStyle["margin-right"] = "auto";
        break;
      case "right":
        delete table.cssStyle["text-align"];
        table.cssStyle["margin-left"] = "auto";
        break;
    }
  }
  parseTablePosition(node, table) {
    var topFromText = globalXmlParser.lengthAttr(node, "topFromText");
    var bottomFromText = globalXmlParser.lengthAttr(node, "bottomFromText");
    var rightFromText = globalXmlParser.lengthAttr(node, "rightFromText");
    var leftFromText = globalXmlParser.lengthAttr(node, "leftFromText");
    table.cssStyle["float"] = "left";
    table.cssStyle["margin-bottom"] = values.addSize(table.cssStyle["margin-bottom"], bottomFromText);
    table.cssStyle["margin-left"] = values.addSize(table.cssStyle["margin-left"], leftFromText);
    table.cssStyle["margin-right"] = values.addSize(table.cssStyle["margin-right"], rightFromText);
    table.cssStyle["margin-top"] = values.addSize(table.cssStyle["margin-top"], topFromText);
  }
  parseTableRow(node) {
    var result = { type: DomType.Row, children: [] };
    for (const c6 of globalXmlParser.elements(node)) {
      switch (c6.localName) {
        case "tc":
          result.children.push(this.parseTableCell(c6));
          break;
        case "trPr":
        case "tblPrEx":
          this.parseTableRowProperties(c6, result);
          break;
      }
    }
    return result;
  }
  parseTableRowProperties(elem, row) {
    row.cssStyle = this.parseDefaultProperties(elem, {}, null, (c6) => {
      switch (c6.localName) {
        case "cnfStyle":
          row.className = values.classNameOfCnfStyle(c6);
          break;
        case "tblHeader":
          row.isHeader = globalXmlParser.boolAttr(c6, "val");
          break;
        case "gridBefore":
          row.gridBefore = globalXmlParser.intAttr(c6, "val");
          break;
        case "gridAfter":
          row.gridAfter = globalXmlParser.intAttr(c6, "val");
          break;
        default:
          return false;
      }
      return true;
    });
  }
  parseTableCell(node) {
    var result = { type: DomType.Cell, children: [] };
    for (const c6 of globalXmlParser.elements(node)) {
      switch (c6.localName) {
        case "tbl":
          result.children.push(this.parseTable(c6));
          break;
        case "p":
          result.children.push(this.parseParagraph(c6));
          break;
        case "tcPr":
          this.parseTableCellProperties(c6, result);
          break;
      }
    }
    return result;
  }
  parseTableCellProperties(elem, cell) {
    cell.cssStyle = this.parseDefaultProperties(elem, {}, null, (c6) => {
      switch (c6.localName) {
        case "gridSpan":
          cell.span = globalXmlParser.intAttr(c6, "val", null);
          break;
        case "vMerge":
          cell.verticalMerge = globalXmlParser.attr(c6, "val") ?? "continue";
          break;
        case "cnfStyle":
          cell.className = values.classNameOfCnfStyle(c6);
          break;
        default:
          return false;
      }
      return true;
    });
    this.parseTableCellVerticalText(elem, cell);
  }
  parseTableCellVerticalText(elem, cell) {
    const directionMap = {
      "btLr": {
        writingMode: "vertical-rl",
        transform: "rotate(180deg)"
      },
      "lrTb": {
        writingMode: "vertical-lr",
        transform: "none"
      },
      "tbRl": {
        writingMode: "vertical-rl",
        transform: "none"
      }
    };
    for (const c6 of globalXmlParser.elements(elem)) {
      if (c6.localName === "textDirection") {
        const direction = globalXmlParser.attr(c6, "val");
        const style = directionMap[direction] || { writingMode: "horizontal-tb" };
        cell.cssStyle["writing-mode"] = style.writingMode;
        cell.cssStyle["transform"] = style.transform;
      }
    }
  }
  parseDefaultProperties(elem, style = null, childStyle = null, handler = null) {
    style = style || {};
    for (const c6 of globalXmlParser.elements(elem)) {
      if (handler?.(c6))
        continue;
      switch (c6.localName) {
        case "jc":
          style["text-align"] = values.valueOfJc(c6);
          break;
        case "textAlignment":
          style["vertical-align"] = values.valueOfTextAlignment(c6);
          break;
        case "color":
          style["color"] = xmlUtil.colorAttr(c6, "val", null, autos.color);
          break;
        case "sz":
          style["font-size"] = style["min-height"] = globalXmlParser.lengthAttr(c6, "val", LengthUsage.FontSize);
          break;
        case "shd":
          style["background-color"] = xmlUtil.colorAttr(c6, "fill", null, autos.shd);
          break;
        case "highlight":
          style["background-color"] = xmlUtil.colorAttr(c6, "val", null, autos.highlight);
          break;
        case "vertAlign":
          break;
        case "position":
          style.verticalAlign = globalXmlParser.lengthAttr(c6, "val", LengthUsage.FontSize);
          break;
        case "tcW":
          if (this.options.ignoreWidth)
            break;
        case "tblW":
          style["width"] = values.valueOfSize(c6, "w");
          break;
        case "trHeight":
          this.parseTrHeight(c6, style);
          break;
        case "strike":
          style["text-decoration"] = globalXmlParser.boolAttr(c6, "val", true) ? "line-through" : "none";
          break;
        case "b":
          style["font-weight"] = globalXmlParser.boolAttr(c6, "val", true) ? "bold" : "normal";
          break;
        case "i":
          style["font-style"] = globalXmlParser.boolAttr(c6, "val", true) ? "italic" : "normal";
          break;
        case "caps":
          style["text-transform"] = globalXmlParser.boolAttr(c6, "val", true) ? "uppercase" : "none";
          break;
        case "smallCaps":
          style["font-variant"] = globalXmlParser.boolAttr(c6, "val", true) ? "small-caps" : "none";
          break;
        case "u":
          this.parseUnderline(c6, style);
          break;
        case "ind":
        case "tblInd":
          this.parseIndentation(c6, style);
          break;
        case "rFonts":
          this.parseFont(c6, style);
          break;
        case "tblBorders":
          this.parseBorderProperties(c6, childStyle || style);
          break;
        case "tblCellSpacing":
          style["border-spacing"] = values.valueOfMargin(c6);
          style["border-collapse"] = "separate";
          break;
        case "pBdr":
          this.parseBorderProperties(c6, style);
          break;
        case "bdr":
          style["border"] = values.valueOfBorder(c6);
          break;
        case "tcBorders":
          this.parseBorderProperties(c6, style);
          break;
        case "vanish":
          if (globalXmlParser.boolAttr(c6, "val", true))
            style["display"] = "none";
          break;
        case "kern":
          break;
        case "noWrap":
          break;
        case "tblCellMar":
        case "tcMar":
          this.parseMarginProperties(c6, childStyle || style);
          break;
        case "tblLayout":
          style["table-layout"] = values.valueOfTblLayout(c6);
          break;
        case "vAlign":
          style["vertical-align"] = values.valueOfTextAlignment(c6);
          break;
        case "spacing":
          if (elem.localName == "pPr")
            this.parseSpacing(c6, style);
          break;
        case "wordWrap":
          if (globalXmlParser.boolAttr(c6, "val"))
            style["overflow-wrap"] = "break-word";
          break;
        case "suppressAutoHyphens":
          style["hyphens"] = globalXmlParser.boolAttr(c6, "val", true) ? "none" : "auto";
          break;
        case "lang":
          style["$lang"] = globalXmlParser.attr(c6, "val");
          break;
        case "rtl":
        case "bidi":
          if (globalXmlParser.boolAttr(c6, "val", true))
            style["direction"] = "rtl";
          break;
        case "bCs":
        case "iCs":
        case "szCs":
        case "tabs":
        case "outlineLvl":
        case "contextualSpacing":
        case "tblStyleColBandSize":
        case "tblStyleRowBandSize":
        case "webHidden":
        case "pageBreakBefore":
        case "suppressLineNumbers":
        case "keepLines":
        case "keepNext":
        case "widowControl":
        case "bidi":
        case "rtl":
        case "noProof":
          break;
        default:
          if (this.options.debug)
            console.warn(`DOCX: Unknown document element: ${elem.localName}.${c6.localName}`);
          break;
      }
    }
    return style;
  }
  parseUnderline(node, style) {
    var val2 = globalXmlParser.attr(node, "val");
    if (val2 == null)
      return;
    switch (val2) {
      case "dash":
      case "dashDotDotHeavy":
      case "dashDotHeavy":
      case "dashedHeavy":
      case "dashLong":
      case "dashLongHeavy":
      case "dotDash":
      case "dotDotDash":
        style["text-decoration"] = "underline dashed";
        break;
      case "dotted":
      case "dottedHeavy":
        style["text-decoration"] = "underline dotted";
        break;
      case "double":
        style["text-decoration"] = "underline double";
        break;
      case "single":
      case "thick":
        style["text-decoration"] = "underline";
        break;
      case "wave":
      case "wavyDouble":
      case "wavyHeavy":
        style["text-decoration"] = "underline wavy";
        break;
      case "words":
        style["text-decoration"] = "underline";
        break;
      case "none":
        style["text-decoration"] = "none";
        break;
    }
    var col = xmlUtil.colorAttr(node, "color");
    if (col)
      style["text-decoration-color"] = col;
  }
  parseFont(node, style) {
    var ascii = globalXmlParser.attr(node, "ascii");
    var asciiTheme = values.themeValue(node, "asciiTheme");
    var eastAsia = globalXmlParser.attr(node, "eastAsia");
    var fonts = [ascii, asciiTheme, eastAsia].filter((x2) => x2).map((x2) => encloseFontFamily(x2));
    if (fonts.length > 0)
      style["font-family"] = [...new Set(fonts)].join(", ");
  }
  parseIndentation(node, style) {
    var firstLine = globalXmlParser.lengthAttr(node, "firstLine");
    var hanging = globalXmlParser.lengthAttr(node, "hanging");
    var left = globalXmlParser.lengthAttr(node, "left");
    var start = globalXmlParser.lengthAttr(node, "start");
    var right = globalXmlParser.lengthAttr(node, "right");
    var end = globalXmlParser.lengthAttr(node, "end");
    if (firstLine)
      style["text-indent"] = firstLine;
    if (hanging)
      style["text-indent"] = `-${hanging}`;
    if (left || start)
      style["margin-inline-start"] = left || start;
    if (right || end)
      style["margin-inline-end"] = right || end;
  }
  parseSpacing(node, style) {
    var before = globalXmlParser.lengthAttr(node, "before");
    var after = globalXmlParser.lengthAttr(node, "after");
    var line = globalXmlParser.intAttr(node, "line", null);
    var lineRule = globalXmlParser.attr(node, "lineRule");
    if (before)
      style["margin-top"] = before;
    if (after)
      style["margin-bottom"] = after;
    if (line !== null) {
      switch (lineRule) {
        case "auto":
          style["line-height"] = `${(line / 240).toFixed(2)}`;
          break;
        case "atLeast":
          style["line-height"] = `calc(100% + ${line / 20}pt)`;
          break;
        default:
          style["line-height"] = style["min-height"] = `${line / 20}pt`;
          break;
      }
    }
  }
  parseMarginProperties(node, output) {
    for (const c6 of globalXmlParser.elements(node)) {
      switch (c6.localName) {
        case "left":
          output["padding-left"] = values.valueOfMargin(c6);
          break;
        case "right":
          output["padding-right"] = values.valueOfMargin(c6);
          break;
        case "top":
          output["padding-top"] = values.valueOfMargin(c6);
          break;
        case "bottom":
          output["padding-bottom"] = values.valueOfMargin(c6);
          break;
      }
    }
  }
  parseTrHeight(node, output) {
    switch (globalXmlParser.attr(node, "hRule")) {
      case "exact":
        output["height"] = globalXmlParser.lengthAttr(node, "val");
        break;
      case "atLeast":
      default:
        output["height"] = globalXmlParser.lengthAttr(node, "val");
        break;
    }
  }
  parseBorderProperties(node, output) {
    for (const c6 of globalXmlParser.elements(node)) {
      switch (c6.localName) {
        case "start":
        case "left":
          output["border-left"] = values.valueOfBorder(c6);
          break;
        case "end":
        case "right":
          output["border-right"] = values.valueOfBorder(c6);
          break;
        case "top":
          output["border-top"] = values.valueOfBorder(c6);
          break;
        case "bottom":
          output["border-bottom"] = values.valueOfBorder(c6);
          break;
      }
    }
  }
};
var knownColors = ["black", "blue", "cyan", "darkBlue", "darkCyan", "darkGray", "darkGreen", "darkMagenta", "darkRed", "darkYellow", "green", "lightGray", "magenta", "none", "red", "white", "yellow"];
var xmlUtil = class {
  static colorAttr(node, attrName, defValue = null, autoColor = "black") {
    var v4 = globalXmlParser.attr(node, attrName);
    if (v4) {
      if (v4 == "auto") {
        return autoColor;
      } else if (knownColors.includes(v4)) {
        return v4;
      }
      return `#${v4}`;
    }
    var themeColor = globalXmlParser.attr(node, "themeColor");
    return themeColor ? `var(--docx-${themeColor}-color)` : defValue;
  }
};
var values = class _values {
  static themeValue(c6, attr) {
    var val2 = globalXmlParser.attr(c6, attr);
    return val2 ? `var(--docx-${val2}-font)` : null;
  }
  static valueOfSize(c6, attr) {
    var type = LengthUsage.Dxa;
    switch (globalXmlParser.attr(c6, "type")) {
      case "dxa":
        break;
      case "pct":
        type = LengthUsage.Percent;
        break;
      case "auto":
        return "auto";
    }
    return globalXmlParser.lengthAttr(c6, attr, type);
  }
  static valueOfMargin(c6) {
    return globalXmlParser.lengthAttr(c6, "w");
  }
  static valueOfBorder(c6) {
    var type = _values.parseBorderType(globalXmlParser.attr(c6, "val"));
    if (type == "none")
      return "none";
    var color = xmlUtil.colorAttr(c6, "color");
    var size = globalXmlParser.lengthAttr(c6, "sz", LengthUsage.Border);
    return `${size} ${type} ${color == "auto" ? autos.borderColor : color}`;
  }
  static parseBorderType(type) {
    switch (type) {
      case "single":
        return "solid";
      case "dashDotStroked":
        return "solid";
      case "dashed":
        return "dashed";
      case "dashSmallGap":
        return "dashed";
      case "dotDash":
        return "dotted";
      case "dotDotDash":
        return "dotted";
      case "dotted":
        return "dotted";
      case "double":
        return "double";
      case "doubleWave":
        return "double";
      case "inset":
        return "inset";
      case "nil":
        return "none";
      case "none":
        return "none";
      case "outset":
        return "outset";
      case "thick":
        return "solid";
      case "thickThinLargeGap":
        return "solid";
      case "thickThinMediumGap":
        return "solid";
      case "thickThinSmallGap":
        return "solid";
      case "thinThickLargeGap":
        return "solid";
      case "thinThickMediumGap":
        return "solid";
      case "thinThickSmallGap":
        return "solid";
      case "thinThickThinLargeGap":
        return "solid";
      case "thinThickThinMediumGap":
        return "solid";
      case "thinThickThinSmallGap":
        return "solid";
      case "threeDEmboss":
        return "solid";
      case "threeDEngrave":
        return "solid";
      case "triple":
        return "double";
      case "wave":
        return "solid";
    }
    return "solid";
  }
  static valueOfTblLayout(c6) {
    var type = globalXmlParser.attr(c6, "val");
    return type == "fixed" ? "fixed" : "auto";
  }
  static classNameOfCnfStyle(c6) {
    const val2 = globalXmlParser.attr(c6, "val");
    const classes = [
      "first-row",
      "last-row",
      "first-col",
      "last-col",
      "odd-col",
      "even-col",
      "odd-row",
      "even-row",
      "ne-cell",
      "nw-cell",
      "se-cell",
      "sw-cell"
    ];
    return classes.filter((_3, i7) => val2[i7] == "1").join(" ");
  }
  static valueOfJc(c6) {
    var type = globalXmlParser.attr(c6, "val");
    switch (type) {
      case "start":
      case "left":
        return "left";
      case "center":
        return "center";
      case "end":
      case "right":
        return "right";
      case "both":
        return "justify";
    }
    return type;
  }
  static valueOfVertAlign(c6, asTagName = false) {
    var type = globalXmlParser.attr(c6, "val");
    switch (type) {
      case "subscript":
        return "sub";
      case "superscript":
        return asTagName ? "sup" : "super";
    }
    return asTagName ? null : type;
  }
  static valueOfTextAlignment(c6) {
    var type = globalXmlParser.attr(c6, "val");
    switch (type) {
      case "auto":
      case "baseline":
        return "baseline";
      case "top":
        return "top";
      case "center":
        return "middle";
      case "bottom":
        return "bottom";
    }
    return type;
  }
  static addSize(a3, b4) {
    if (a3 == null)
      return b4;
    if (b4 == null)
      return a3;
    return `calc(${a3} + ${b4})`;
  }
  static classNameOftblLook(c6) {
    const val2 = globalXmlParser.hexAttr(c6, "val", 0);
    let className = "";
    if (globalXmlParser.boolAttr(c6, "firstRow") || val2 & 32)
      className += " first-row";
    if (globalXmlParser.boolAttr(c6, "lastRow") || val2 & 64)
      className += " last-row";
    if (globalXmlParser.boolAttr(c6, "firstColumn") || val2 & 128)
      className += " first-col";
    if (globalXmlParser.boolAttr(c6, "lastColumn") || val2 & 256)
      className += " last-col";
    if (globalXmlParser.boolAttr(c6, "noHBand") || val2 & 512)
      className += " no-hband";
    if (globalXmlParser.boolAttr(c6, "noVBand") || val2 & 1024)
      className += " no-vband";
    return className.trim();
  }
};
var defaultTab = { pos: 0, leader: "none", style: "left" };
var maxTabs = 50;
function computePixelToPoint(container = document.body) {
  const temp = document.createElement("div");
  temp.style.width = "100pt";
  container.appendChild(temp);
  const result = 100 / temp.offsetWidth;
  container.removeChild(temp);
  return result;
}
function updateTabStop(elem, tabs, defaultTabSize, pixelToPoint = 72 / 96) {
  const p4 = elem.closest("p");
  const ebb = elem.getBoundingClientRect();
  const pbb = p4.getBoundingClientRect();
  const pcs = getComputedStyle(p4);
  const tabStops = tabs?.length > 0 ? tabs.map((t6) => ({
    pos: lengthToPoint(t6.position),
    leader: t6.leader,
    style: t6.style
  })).sort((a3, b4) => a3.pos - b4.pos) : [defaultTab];
  const lastTab = tabStops[tabStops.length - 1];
  const pWidthPt = pbb.width * pixelToPoint;
  const size = lengthToPoint(defaultTabSize);
  let pos = lastTab.pos + size;
  if (pos < pWidthPt) {
    for (; pos < pWidthPt && tabStops.length < maxTabs; pos += size) {
      tabStops.push({ ...defaultTab, pos });
    }
  }
  const marginLeft = parseFloat(pcs.marginLeft);
  const pOffset = pbb.left + marginLeft;
  const left = (ebb.left - pOffset) * pixelToPoint;
  const tab = tabStops.find((t6) => t6.style != "clear" && t6.pos > left);
  if (tab == null)
    return;
  let width = 1;
  if (tab.style == "right" || tab.style == "center") {
    const tabStops2 = Array.from(p4.querySelectorAll(`.${elem.className}`));
    const nextIdx = tabStops2.indexOf(elem) + 1;
    const range2 = document.createRange();
    range2.setStart(elem, 1);
    if (nextIdx < tabStops2.length) {
      range2.setEndBefore(tabStops2[nextIdx]);
    } else {
      range2.setEndAfter(p4);
    }
    const mul = tab.style == "center" ? 0.5 : 1;
    const nextBB = range2.getBoundingClientRect();
    const offset = nextBB.left + mul * nextBB.width - (pbb.left - marginLeft);
    width = tab.pos - offset * pixelToPoint;
  } else {
    width = tab.pos - left;
  }
  elem.innerHTML = "&nbsp;";
  elem.style.textDecoration = "inherit";
  elem.style.wordSpacing = `${width.toFixed(0)}pt`;
  switch (tab.leader) {
    case "dot":
    case "middleDot":
      elem.style.textDecoration = "underline";
      elem.style.textDecorationStyle = "dotted";
      break;
    case "hyphen":
    case "heavy":
    case "underscore":
      elem.style.textDecoration = "underline";
      break;
  }
}
function lengthToPoint(length) {
  return parseFloat(length);
}
var ns = {
  svg: "http://www.w3.org/2000/svg",
  mathML: "http://www.w3.org/1998/Math/MathML"
};
var HtmlRenderer = class {
  constructor(htmlDocument) {
    this.htmlDocument = htmlDocument;
    this.className = "docx";
    this.styleMap = {};
    this.currentPart = null;
    this.tableVerticalMerges = [];
    this.currentVerticalMerge = null;
    this.tableCellPositions = [];
    this.currentCellPosition = null;
    this.footnoteMap = {};
    this.endnoteMap = {};
    this.currentEndnoteIds = [];
    this.usedHederFooterParts = [];
    this.currentTabs = [];
    this.commentMap = {};
    this.tasks = [];
    this.postRenderTasks = [];
  }
  async render(document2, bodyContainer, styleContainer = null, options) {
    this.document = document2;
    this.options = options;
    this.className = options.className;
    this.rootSelector = options.inWrapper ? `.${this.className}-wrapper` : ":root";
    this.styleMap = null;
    this.tasks = [];
    if (this.options.renderComments && globalThis.Highlight) {
      this.commentHighlight = new Highlight();
    }
    styleContainer = styleContainer || bodyContainer;
    removeAllElements(styleContainer);
    removeAllElements(bodyContainer);
    styleContainer.appendChild(this.createComment("docxjs library predefined styles"));
    styleContainer.appendChild(this.renderDefaultStyle());
    if (document2.themePart) {
      styleContainer.appendChild(this.createComment("docxjs document theme values"));
      this.renderTheme(document2.themePart, styleContainer);
    }
    if (document2.stylesPart != null) {
      this.styleMap = this.processStyles(document2.stylesPart.styles);
      styleContainer.appendChild(this.createComment("docxjs document styles"));
      styleContainer.appendChild(this.renderStyles(document2.stylesPart.styles));
    }
    if (document2.numberingPart) {
      this.prodessNumberings(document2.numberingPart.domNumberings);
      styleContainer.appendChild(this.createComment("docxjs document numbering styles"));
      styleContainer.appendChild(this.renderNumbering(document2.numberingPart.domNumberings, styleContainer));
    }
    if (document2.footnotesPart) {
      this.footnoteMap = keyBy(document2.footnotesPart.notes, (x2) => x2.id);
    }
    if (document2.endnotesPart) {
      this.endnoteMap = keyBy(document2.endnotesPart.notes, (x2) => x2.id);
    }
    if (document2.settingsPart) {
      this.defaultTabSize = document2.settingsPart.settings?.defaultTabStop;
    }
    if (!options.ignoreFonts && document2.fontTablePart)
      this.renderFontTable(document2.fontTablePart, styleContainer);
    var sectionElements = this.renderSections(document2.documentPart.body);
    if (this.options.inWrapper) {
      bodyContainer.appendChild(this.renderWrapper(sectionElements));
    } else {
      appendChildren(bodyContainer, sectionElements);
    }
    if (this.commentHighlight && options.renderComments) {
      CSS.highlights.set(`${this.className}-comments`, this.commentHighlight);
    }
    this.postRenderTasks.forEach((t6) => t6());
    await Promise.allSettled(this.tasks);
    this.refreshTabStops();
  }
  renderTheme(themePart, styleContainer) {
    const variables = {};
    const fontScheme = themePart.theme?.fontScheme;
    if (fontScheme) {
      if (fontScheme.majorFont) {
        variables["--docx-majorHAnsi-font"] = fontScheme.majorFont.latinTypeface;
      }
      if (fontScheme.minorFont) {
        variables["--docx-minorHAnsi-font"] = fontScheme.minorFont.latinTypeface;
      }
    }
    const colorScheme = themePart.theme?.colorScheme;
    if (colorScheme) {
      for (let [k2, v4] of Object.entries(colorScheme.colors)) {
        variables[`--docx-${k2}-color`] = `#${v4}`;
      }
    }
    const cssText = this.styleToString(`.${this.className}`, variables);
    styleContainer.appendChild(this.createStyleElement(cssText));
  }
  renderFontTable(fontsPart, styleContainer) {
    for (let f4 of fontsPart.fonts) {
      for (let ref of f4.embedFontRefs) {
        this.tasks.push(this.document.loadFont(ref.id, ref.key).then((fontData) => {
          const cssValues = {
            "font-family": encloseFontFamily(f4.name),
            "src": `url(${fontData})`
          };
          if (ref.type == "bold" || ref.type == "boldItalic") {
            cssValues["font-weight"] = "bold";
          }
          if (ref.type == "italic" || ref.type == "boldItalic") {
            cssValues["font-style"] = "italic";
          }
          const cssText = this.styleToString("@font-face", cssValues);
          styleContainer.appendChild(this.createComment(`docxjs ${f4.name} font`));
          styleContainer.appendChild(this.createStyleElement(cssText));
        }));
      }
    }
  }
  processStyleName(className) {
    return className ? `${this.className}_${escapeClassName(className)}` : this.className;
  }
  processStyles(styles2) {
    const stylesMap = keyBy(styles2.filter((x2) => x2.id != null), (x2) => x2.id);
    for (const style of styles2.filter((x2) => x2.basedOn)) {
      var baseStyle = stylesMap[style.basedOn];
      if (baseStyle) {
        style.paragraphProps = mergeDeep(style.paragraphProps, baseStyle.paragraphProps);
        style.runProps = mergeDeep(style.runProps, baseStyle.runProps);
        for (const baseValues of baseStyle.styles) {
          const styleValues = style.styles.find((x2) => x2.target == baseValues.target);
          if (styleValues) {
            this.copyStyleProperties(baseValues.values, styleValues.values);
          } else {
            style.styles.push({ ...baseValues, values: { ...baseValues.values } });
          }
        }
      } else if (this.options.debug)
        console.warn(`Can't find base style ${style.basedOn}`);
    }
    for (let style of styles2) {
      style.cssName = this.processStyleName(style.id);
    }
    return stylesMap;
  }
  prodessNumberings(numberings) {
    for (let num of numberings.filter((n7) => n7.pStyleName)) {
      const style = this.findStyle(num.pStyleName);
      if (style?.paragraphProps?.numbering) {
        style.paragraphProps.numbering.level = num.level;
      }
    }
  }
  processElement(element) {
    if (element.children) {
      for (var e9 of element.children) {
        e9.parent = element;
        if (e9.type == DomType.Table) {
          this.processTable(e9);
        } else {
          this.processElement(e9);
        }
      }
    }
  }
  processTable(table) {
    for (var r8 of table.children) {
      for (var c6 of r8.children) {
        c6.cssStyle = this.copyStyleProperties(table.cellStyle, c6.cssStyle, [
          "border-left",
          "border-right",
          "border-top",
          "border-bottom",
          "padding-left",
          "padding-right",
          "padding-top",
          "padding-bottom"
        ]);
        this.processElement(c6);
      }
    }
  }
  copyStyleProperties(input, output, attrs = null) {
    if (!input)
      return output;
    if (output == null)
      output = {};
    if (attrs == null)
      attrs = Object.getOwnPropertyNames(input);
    for (var key of attrs) {
      if (input.hasOwnProperty(key) && !output.hasOwnProperty(key))
        output[key] = input[key];
    }
    return output;
  }
  createPageElement(className, props) {
    var elem = this.createElement("section", { className });
    if (props) {
      if (props.pageMargins) {
        elem.style.paddingLeft = props.pageMargins.left;
        elem.style.paddingRight = props.pageMargins.right;
        elem.style.paddingTop = props.pageMargins.top;
        elem.style.paddingBottom = props.pageMargins.bottom;
      }
      if (props.pageSize) {
        if (!this.options.ignoreWidth)
          elem.style.width = props.pageSize.width;
        if (!this.options.ignoreHeight)
          elem.style.minHeight = props.pageSize.height;
      }
    }
    return elem;
  }
  createSectionContent(props) {
    var elem = this.createElement("article");
    if (props.columns && props.columns.numberOfColumns) {
      elem.style.columnCount = `${props.columns.numberOfColumns}`;
      elem.style.columnGap = props.columns.space;
      if (props.columns.separator) {
        elem.style.columnRule = "1px solid black";
      }
    }
    return elem;
  }
  renderSections(document2) {
    const result = [];
    this.processElement(document2);
    const sections = this.splitBySection(document2.children, document2.props);
    const pages = this.groupByPageBreaks(sections);
    let prevProps = null;
    for (let i7 = 0, l5 = pages.length; i7 < l5; i7++) {
      this.currentFootnoteIds = [];
      const section = pages[i7][0];
      let props = section.sectProps;
      const pageElement = this.createPageElement(this.className, props);
      this.renderStyleValues(document2.cssStyle, pageElement);
      this.options.renderHeaders && this.renderHeaderFooter(props.headerRefs, props, result.length, prevProps != props, pageElement);
      for (const sect of pages[i7]) {
        var contentElement = this.createSectionContent(sect.sectProps);
        this.renderElements(sect.elements, contentElement);
        pageElement.appendChild(contentElement);
        props = sect.sectProps;
      }
      if (this.options.renderFootnotes) {
        this.renderNotes(this.currentFootnoteIds, this.footnoteMap, pageElement);
      }
      if (this.options.renderEndnotes && i7 == l5 - 1) {
        this.renderNotes(this.currentEndnoteIds, this.endnoteMap, pageElement);
      }
      this.options.renderFooters && this.renderHeaderFooter(props.footerRefs, props, result.length, prevProps != props, pageElement);
      result.push(pageElement);
      prevProps = props;
    }
    return result;
  }
  renderHeaderFooter(refs, props, page, firstOfSection, into) {
    if (!refs)
      return;
    var ref = (props.titlePage && firstOfSection ? refs.find((x2) => x2.type == "first") : null) ?? (page % 2 == 1 ? refs.find((x2) => x2.type == "even") : null) ?? refs.find((x2) => x2.type == "default");
    var part = ref && this.document.findPartByRelId(ref.id, this.document.documentPart);
    if (part) {
      this.currentPart = part;
      if (!this.usedHederFooterParts.includes(part.path)) {
        this.processElement(part.rootElement);
        this.usedHederFooterParts.push(part.path);
      }
      const [el] = this.renderElements([part.rootElement], into);
      if (props?.pageMargins) {
        if (part.rootElement.type === DomType.Header) {
          el.style.marginTop = `calc(${props.pageMargins.header} - ${props.pageMargins.top})`;
          el.style.minHeight = `calc(${props.pageMargins.top} - ${props.pageMargins.header})`;
        } else if (part.rootElement.type === DomType.Footer) {
          el.style.marginBottom = `calc(${props.pageMargins.footer} - ${props.pageMargins.bottom})`;
          el.style.minHeight = `calc(${props.pageMargins.bottom} - ${props.pageMargins.footer})`;
        }
      }
      this.currentPart = null;
    }
  }
  isPageBreakElement(elem) {
    if (elem.type != DomType.Break)
      return false;
    if (elem.break == "lastRenderedPageBreak")
      return !this.options.ignoreLastRenderedPageBreak;
    return elem.break == "page";
  }
  isPageBreakSection(prev, next) {
    if (!prev)
      return false;
    if (!next)
      return false;
    return prev.pageSize?.orientation != next.pageSize?.orientation || prev.pageSize?.width != next.pageSize?.width || prev.pageSize?.height != next.pageSize?.height;
  }
  splitBySection(elements, defaultProps) {
    var current2 = { sectProps: null, elements: [], pageBreak: false };
    var result = [current2];
    for (let elem of elements) {
      if (elem.type == DomType.Paragraph) {
        const s6 = this.findStyle(elem.styleName);
        if (s6?.paragraphProps?.pageBreakBefore) {
          current2.sectProps = sectProps;
          current2.pageBreak = true;
          current2 = { sectProps: null, elements: [], pageBreak: false };
          result.push(current2);
        }
      }
      current2.elements.push(elem);
      if (elem.type == DomType.Paragraph) {
        const p4 = elem;
        var sectProps = p4.sectionProps;
        var pBreakIndex = -1;
        var rBreakIndex = -1;
        if (this.options.breakPages && p4.children) {
          pBreakIndex = p4.children.findIndex((r8) => {
            rBreakIndex = r8.children?.findIndex(this.isPageBreakElement.bind(this)) ?? -1;
            return rBreakIndex != -1;
          });
        }
        if (sectProps || pBreakIndex != -1) {
          current2.sectProps = sectProps;
          current2.pageBreak = pBreakIndex != -1;
          current2 = { sectProps: null, elements: [], pageBreak: false };
          result.push(current2);
        }
        if (pBreakIndex != -1) {
          let breakRun = p4.children[pBreakIndex];
          let splitRun = rBreakIndex < breakRun.children.length - 1;
          if (pBreakIndex < p4.children.length - 1 || splitRun) {
            var children = elem.children;
            var newParagraph = { ...elem, children: children.slice(pBreakIndex) };
            elem.children = children.slice(0, pBreakIndex);
            current2.elements.push(newParagraph);
            if (splitRun) {
              let runChildren = breakRun.children;
              let newRun = { ...breakRun, children: runChildren.slice(0, rBreakIndex) };
              elem.children.push(newRun);
              breakRun.children = runChildren.slice(rBreakIndex);
            }
          }
        }
      }
    }
    let currentSectProps = null;
    for (let i7 = result.length - 1; i7 >= 0; i7--) {
      if (result[i7].sectProps == null) {
        result[i7].sectProps = currentSectProps ?? defaultProps;
      } else {
        currentSectProps = result[i7].sectProps;
      }
    }
    return result;
  }
  groupByPageBreaks(sections) {
    let current2 = [];
    let prev;
    const result = [current2];
    for (let s6 of sections) {
      current2.push(s6);
      if (this.options.ignoreLastRenderedPageBreak || s6.pageBreak || this.isPageBreakSection(prev, s6.sectProps))
        result.push(current2 = []);
      prev = s6.sectProps;
    }
    return result.filter((x2) => x2.length > 0);
  }
  renderWrapper(children) {
    return this.createElement("div", { className: `${this.className}-wrapper` }, children);
  }
  renderDefaultStyle() {
    var c6 = this.className;
    var wrapperStyle = `
.${c6}-wrapper { background: gray; padding: 30px; padding-bottom: 0px; display: flex; flex-flow: column; align-items: center; } 
.${c6}-wrapper>section.${c6} { background: white; box-shadow: 0 0 10px rgba(0, 0, 0, 0.5); margin-bottom: 30px; }`;
    if (this.options.hideWrapperOnPrint) {
      wrapperStyle = `@media not print { ${wrapperStyle} }`;
    }
    var styleText = `${wrapperStyle}
.${c6} { color: black; hyphens: auto; text-underline-position: from-font; }
section.${c6} { box-sizing: border-box; display: flex; flex-flow: column nowrap; position: relative; overflow: hidden; }
section.${c6}>article { margin-bottom: auto; z-index: 1; }
section.${c6}>footer { z-index: 1; }
.${c6} table { border-collapse: collapse; }
.${c6} table td, .${c6} table th { vertical-align: top; }
.${c6} p { margin: 0pt; min-height: 1em; }
.${c6} span { white-space: pre-wrap; overflow-wrap: break-word; }
.${c6} a { color: inherit; text-decoration: inherit; }
.${c6} svg { fill: transparent; }
`;
    if (this.options.renderComments) {
      styleText += `
.${c6}-comment-ref { cursor: default; }
.${c6}-comment-popover { display: none; z-index: 1000; padding: 0.5rem; background: white; position: absolute; box-shadow: 0 0 0.25rem rgba(0, 0, 0, 0.25); width: 30ch; }
.${c6}-comment-ref:hover~.${c6}-comment-popover { display: block; }
.${c6}-comment-author,.${c6}-comment-date { font-size: 0.875rem; color: #888; }
`;
    }
    return this.createStyleElement(styleText);
  }
  renderNumbering(numberings, styleContainer) {
    var styleText = "";
    var resetCounters = [];
    for (var num of numberings) {
      var selector = `p.${this.numberingClass(num.id, num.level)}`;
      var listStyleType = "none";
      if (num.bullet) {
        let valiable = `--${this.className}-${num.bullet.src}`.toLowerCase();
        styleText += this.styleToString(`${selector}:before`, {
          "content": "' '",
          "display": "inline-block",
          "background": `var(${valiable})`
        }, num.bullet.style);
        this.tasks.push(this.document.loadNumberingImage(num.bullet.src).then((data) => {
          var text3 = `${this.rootSelector} { ${valiable}: url(${data}) }`;
          styleContainer.appendChild(this.createStyleElement(text3));
        }));
      } else if (num.levelText) {
        let counter = this.numberingCounter(num.id, num.level);
        const counterReset = counter + " " + (num.start - 1);
        if (num.level > 0) {
          styleText += this.styleToString(`p.${this.numberingClass(num.id, num.level - 1)}`, {
            "counter-set": counterReset
          });
        }
        resetCounters.push(counterReset);
        styleText += this.styleToString(`${selector}:before`, {
          "content": this.levelTextToContent(num.levelText, num.suff, num.id, this.numFormatToCssValue(num.format)),
          "counter-increment": counter,
          ...num.rStyle
        });
      } else {
        listStyleType = this.numFormatToCssValue(num.format);
      }
      styleText += this.styleToString(selector, {
        "display": "list-item",
        "list-style-position": "inside",
        "list-style-type": listStyleType,
        ...num.pStyle
      });
    }
    if (resetCounters.length > 0) {
      styleText += this.styleToString(this.rootSelector, {
        "counter-reset": resetCounters.join(" ")
      });
    }
    return this.createStyleElement(styleText);
  }
  renderStyles(styles2) {
    var styleText = "";
    const stylesMap = this.styleMap;
    const defautStyles = keyBy(styles2.filter((s6) => s6.isDefault), (s6) => s6.target);
    for (const style of styles2) {
      var subStyles = style.styles;
      if (style.linked) {
        var linkedStyle = style.linked && stylesMap[style.linked];
        if (linkedStyle)
          subStyles = subStyles.concat(linkedStyle.styles);
        else if (this.options.debug)
          console.warn(`Can't find linked style ${style.linked}`);
      }
      for (const subStyle of subStyles) {
        var selector = `${style.target ?? ""}.${style.cssName}`;
        if (style.target != subStyle.target)
          selector += ` ${subStyle.target}`;
        if (defautStyles[style.target] == style)
          selector = `.${this.className} ${style.target}, ` + selector;
        styleText += this.styleToString(selector, subStyle.values);
      }
    }
    return this.createStyleElement(styleText);
  }
  renderNotes(noteIds, notesMap, into) {
    var notes = noteIds.map((id) => notesMap[id]).filter((x2) => x2);
    if (notes.length > 0) {
      var result = this.createElement("ol", null, this.renderElements(notes));
      into.appendChild(result);
    }
  }
  renderElement(elem) {
    switch (elem.type) {
      case DomType.Paragraph:
        return this.renderParagraph(elem);
      case DomType.BookmarkStart:
        return this.renderBookmarkStart(elem);
      case DomType.BookmarkEnd:
        return null;
      case DomType.Run:
        return this.renderRun(elem);
      case DomType.Table:
        return this.renderTable(elem);
      case DomType.Row:
        return this.renderTableRow(elem);
      case DomType.Cell:
        return this.renderTableCell(elem);
      case DomType.Hyperlink:
        return this.renderHyperlink(elem);
      case DomType.SmartTag:
        return this.renderSmartTag(elem);
      case DomType.Drawing:
        return this.renderDrawing(elem);
      case DomType.Image:
        return this.renderImage(elem);
      case DomType.Text:
        return this.renderText(elem);
      case DomType.Text:
        return this.renderText(elem);
      case DomType.DeletedText:
        return this.renderDeletedText(elem);
      case DomType.Tab:
        return this.renderTab(elem);
      case DomType.Symbol:
        return this.renderSymbol(elem);
      case DomType.Break:
        return this.renderBreak(elem);
      case DomType.Footer:
        return this.renderContainer(elem, "footer");
      case DomType.Header:
        return this.renderContainer(elem, "header");
      case DomType.Footnote:
      case DomType.Endnote:
        return this.renderContainer(elem, "li");
      case DomType.FootnoteReference:
        return this.renderFootnoteReference(elem);
      case DomType.EndnoteReference:
        return this.renderEndnoteReference(elem);
      case DomType.NoBreakHyphen:
        return this.createElement("wbr");
      case DomType.VmlPicture:
        return this.renderVmlPicture(elem);
      case DomType.VmlElement:
        return this.renderVmlElement(elem);
      case DomType.MmlMath:
        return this.renderContainerNS(elem, ns.mathML, "math", { xmlns: ns.mathML });
      case DomType.MmlMathParagraph:
        return this.renderContainer(elem, "span");
      case DomType.MmlFraction:
        return this.renderContainerNS(elem, ns.mathML, "mfrac");
      case DomType.MmlBase:
        return this.renderContainerNS(elem, ns.mathML, elem.parent.type == DomType.MmlMatrixRow ? "mtd" : "mrow");
      case DomType.MmlNumerator:
      case DomType.MmlDenominator:
      case DomType.MmlFunction:
      case DomType.MmlLimit:
      case DomType.MmlBox:
        return this.renderContainerNS(elem, ns.mathML, "mrow");
      case DomType.MmlGroupChar:
        return this.renderMmlGroupChar(elem);
      case DomType.MmlLimitLower:
        return this.renderContainerNS(elem, ns.mathML, "munder");
      case DomType.MmlMatrix:
        return this.renderContainerNS(elem, ns.mathML, "mtable");
      case DomType.MmlMatrixRow:
        return this.renderContainerNS(elem, ns.mathML, "mtr");
      case DomType.MmlRadical:
        return this.renderMmlRadical(elem);
      case DomType.MmlSuperscript:
        return this.renderContainerNS(elem, ns.mathML, "msup");
      case DomType.MmlSubscript:
        return this.renderContainerNS(elem, ns.mathML, "msub");
      case DomType.MmlDegree:
      case DomType.MmlSuperArgument:
      case DomType.MmlSubArgument:
        return this.renderContainerNS(elem, ns.mathML, "mn");
      case DomType.MmlFunctionName:
        return this.renderContainerNS(elem, ns.mathML, "ms");
      case DomType.MmlDelimiter:
        return this.renderMmlDelimiter(elem);
      case DomType.MmlRun:
        return this.renderMmlRun(elem);
      case DomType.MmlNary:
        return this.renderMmlNary(elem);
      case DomType.MmlPreSubSuper:
        return this.renderMmlPreSubSuper(elem);
      case DomType.MmlBar:
        return this.renderMmlBar(elem);
      case DomType.MmlEquationArray:
        return this.renderMllList(elem);
      case DomType.Inserted:
        return this.renderInserted(elem);
      case DomType.Deleted:
        return this.renderDeleted(elem);
      case DomType.CommentRangeStart:
        return this.renderCommentRangeStart(elem);
      case DomType.CommentRangeEnd:
        return this.renderCommentRangeEnd(elem);
      case DomType.CommentReference:
        return this.renderCommentReference(elem);
      case DomType.AltChunk:
        return this.renderAltChunk(elem);
    }
    return null;
  }
  renderElements(elems, into) {
    if (elems == null)
      return null;
    var result = elems.flatMap((e9) => this.renderElement(e9)).filter((e9) => e9 != null);
    if (into)
      appendChildren(into, result);
    return result;
  }
  renderContainer(elem, tagName, props) {
    return this.createElement(tagName, props, this.renderElements(elem.children));
  }
  renderContainerNS(elem, ns2, tagName, props) {
    return this.createElementNS(ns2, tagName, props, this.renderElements(elem.children));
  }
  renderParagraph(elem) {
    var result = this.renderContainer(elem, "p");
    const style = this.findStyle(elem.styleName);
    elem.tabs ?? (elem.tabs = style?.paragraphProps?.tabs);
    this.renderClass(elem, result);
    this.renderStyleValues(elem.cssStyle, result);
    this.renderCommonProperties(result.style, elem);
    const numbering = elem.numbering ?? style?.paragraphProps?.numbering;
    if (numbering) {
      result.classList.add(this.numberingClass(numbering.id, numbering.level));
    }
    return result;
  }
  renderRunProperties(style, props) {
    this.renderCommonProperties(style, props);
  }
  renderCommonProperties(style, props) {
    if (props == null)
      return;
    if (props.color) {
      style["color"] = props.color;
    }
    if (props.fontSize) {
      style["font-size"] = props.fontSize;
    }
  }
  renderHyperlink(elem) {
    var result = this.renderContainer(elem, "a");
    this.renderStyleValues(elem.cssStyle, result);
    let href = "";
    if (elem.id) {
      const rel2 = this.document.documentPart.rels.find((it) => it.id == elem.id && it.targetMode === "External");
      href = rel2?.target ?? href;
    }
    if (elem.anchor) {
      href += `#${elem.anchor}`;
    }
    result.href = href;
    return result;
  }
  renderSmartTag(elem) {
    return this.renderContainer(elem, "span");
  }
  renderCommentRangeStart(commentStart) {
    if (!this.options.renderComments)
      return null;
    const rng = new Range();
    this.commentHighlight?.add(rng);
    const result = this.createComment(`start of comment #${commentStart.id}`);
    this.later(() => rng.setStart(result, 0));
    this.commentMap[commentStart.id] = rng;
    return result;
  }
  renderCommentRangeEnd(commentEnd) {
    if (!this.options.renderComments)
      return null;
    const rng = this.commentMap[commentEnd.id];
    const result = this.createComment(`end of comment #${commentEnd.id}`);
    this.later(() => rng?.setEnd(result, 0));
    return result;
  }
  renderCommentReference(commentRef) {
    if (!this.options.renderComments)
      return null;
    var comment = this.document.commentsPart?.commentMap[commentRef.id];
    if (!comment)
      return null;
    const frg = new DocumentFragment();
    const commentRefEl = this.createElement("span", { className: `${this.className}-comment-ref` }, ["\u{1F4AC}"]);
    const commentsContainerEl = this.createElement("div", { className: `${this.className}-comment-popover` });
    this.renderCommentContent(comment, commentsContainerEl);
    frg.appendChild(this.createComment(`comment #${comment.id} by ${comment.author} on ${comment.date}`));
    frg.appendChild(commentRefEl);
    frg.appendChild(commentsContainerEl);
    return frg;
  }
  renderAltChunk(elem) {
    if (!this.options.renderAltChunks)
      return null;
    var result = this.createElement("iframe");
    this.tasks.push(this.document.loadAltChunk(elem.id, this.currentPart).then((x2) => {
      result.srcdoc = x2;
    }));
    return result;
  }
  renderCommentContent(comment, container) {
    container.appendChild(this.createElement("div", { className: `${this.className}-comment-author` }, [comment.author]));
    container.appendChild(this.createElement("div", { className: `${this.className}-comment-date` }, [new Date(comment.date).toLocaleString()]));
    this.renderElements(comment.children, container);
  }
  renderDrawing(elem) {
    var result = this.renderContainer(elem, "div");
    result.style.display = "inline-block";
    result.style.position = "relative";
    result.style.textIndent = "0px";
    this.renderStyleValues(elem.cssStyle, result);
    return result;
  }
  renderImage(elem) {
    let result = this.createElement("img");
    let transform = elem.cssStyle?.transform;
    this.renderStyleValues(elem.cssStyle, result);
    if (elem.srcRect && elem.srcRect.some((x2) => x2 != 0)) {
      var [left, top, right, bottom] = elem.srcRect;
      transform = `scale(${1 / (1 - left - right)}, ${1 / (1 - top - bottom)})`;
      result.style["clip-path"] = `rect(${(100 * top).toFixed(2)}% ${(100 * (1 - right)).toFixed(2)}% ${(100 * (1 - bottom)).toFixed(2)}% ${(100 * left).toFixed(2)}%)`;
    }
    if (elem.rotation)
      transform = `rotate(${elem.rotation}deg) ${transform ?? ""}`;
    result.style.transform = transform?.trim();
    if (this.document) {
      this.tasks.push(this.document.loadDocumentImage(elem.src, this.currentPart).then((x2) => {
        result.src = x2;
      }));
    }
    return result;
  }
  renderText(elem) {
    return this.htmlDocument.createTextNode(elem.text);
  }
  renderDeletedText(elem) {
    return this.options.renderChanges ? this.renderText(elem) : null;
  }
  renderBreak(elem) {
    if (elem.break == "textWrapping") {
      return this.createElement("br");
    }
    return null;
  }
  renderInserted(elem) {
    if (this.options.renderChanges)
      return this.renderContainer(elem, "ins");
    return this.renderElements(elem.children);
  }
  renderDeleted(elem) {
    if (this.options.renderChanges)
      return this.renderContainer(elem, "del");
    return null;
  }
  renderSymbol(elem) {
    var span = this.createElement("span");
    span.style.fontFamily = elem.font;
    span.innerHTML = `&#x${elem.char};`;
    return span;
  }
  renderFootnoteReference(elem) {
    var result = this.createElement("sup");
    this.currentFootnoteIds.push(elem.id);
    result.textContent = `${this.currentFootnoteIds.length}`;
    return result;
  }
  renderEndnoteReference(elem) {
    var result = this.createElement("sup");
    this.currentEndnoteIds.push(elem.id);
    result.textContent = `${this.currentEndnoteIds.length}`;
    return result;
  }
  renderTab(elem) {
    var tabSpan = this.createElement("span");
    tabSpan.innerHTML = "&emsp;";
    if (this.options.experimental) {
      tabSpan.className = this.tabStopClass();
      var stops = findParent(elem, DomType.Paragraph)?.tabs;
      this.currentTabs.push({ stops, span: tabSpan });
    }
    return tabSpan;
  }
  renderBookmarkStart(elem) {
    return this.createElement("span", { id: elem.name });
  }
  renderRun(elem) {
    if (elem.fieldRun)
      return null;
    const result = this.createElement("span");
    if (elem.id)
      result.id = elem.id;
    this.renderClass(elem, result);
    this.renderStyleValues(elem.cssStyle, result);
    if (elem.verticalAlign) {
      const wrapper = this.createElement(elem.verticalAlign);
      this.renderElements(elem.children, wrapper);
      result.appendChild(wrapper);
    } else {
      this.renderElements(elem.children, result);
    }
    return result;
  }
  renderTable(elem) {
    let result = this.createElement("table");
    this.tableCellPositions.push(this.currentCellPosition);
    this.tableVerticalMerges.push(this.currentVerticalMerge);
    this.currentVerticalMerge = {};
    this.currentCellPosition = { col: 0, row: 0 };
    if (elem.columns)
      result.appendChild(this.renderTableColumns(elem.columns));
    this.renderClass(elem, result);
    this.renderElements(elem.children, result);
    this.renderStyleValues(elem.cssStyle, result);
    this.currentVerticalMerge = this.tableVerticalMerges.pop();
    this.currentCellPosition = this.tableCellPositions.pop();
    return result;
  }
  renderTableColumns(columns) {
    let result = this.createElement("colgroup");
    for (let col of columns) {
      let colElem = this.createElement("col");
      if (col.width)
        colElem.style.width = col.width;
      result.appendChild(colElem);
    }
    return result;
  }
  renderTableRow(elem) {
    let result = this.createElement("tr");
    this.currentCellPosition.col = 0;
    if (elem.gridBefore)
      result.appendChild(this.renderTableCellPlaceholder(elem.gridBefore));
    this.renderClass(elem, result);
    this.renderElements(elem.children, result);
    this.renderStyleValues(elem.cssStyle, result);
    if (elem.gridAfter)
      result.appendChild(this.renderTableCellPlaceholder(elem.gridAfter));
    this.currentCellPosition.row++;
    return result;
  }
  renderTableCellPlaceholder(colSpan) {
    const result = this.createElement("td", { colSpan });
    result.style["border"] = "none";
    return result;
  }
  renderTableCell(elem) {
    let result = this.renderContainer(elem, "td");
    const key = this.currentCellPosition.col;
    if (elem.verticalMerge) {
      if (elem.verticalMerge == "restart") {
        this.currentVerticalMerge[key] = result;
        result.rowSpan = 1;
      } else if (this.currentVerticalMerge[key]) {
        this.currentVerticalMerge[key].rowSpan += 1;
        result.style.display = "none";
      }
    } else {
      this.currentVerticalMerge[key] = null;
    }
    this.renderClass(elem, result);
    this.renderStyleValues(elem.cssStyle, result);
    if (elem.span)
      result.colSpan = elem.span;
    this.currentCellPosition.col += result.colSpan;
    return result;
  }
  renderVmlPicture(elem) {
    return this.renderContainer(elem, "div");
  }
  renderVmlElement(elem) {
    var container = this.createSvgElement("svg");
    container.setAttribute("style", elem.cssStyleText);
    const result = this.renderVmlChildElement(elem);
    if (elem.imageHref?.id) {
      this.tasks.push(this.document?.loadDocumentImage(elem.imageHref.id, this.currentPart).then((x2) => result.setAttribute("href", x2)));
    }
    container.appendChild(result);
    requestAnimationFrame(() => {
      const bb = container.firstElementChild.getBBox();
      container.setAttribute("width", `${Math.ceil(bb.x + bb.width)}`);
      container.setAttribute("height", `${Math.ceil(bb.y + bb.height)}`);
    });
    return container;
  }
  renderVmlChildElement(elem) {
    const result = this.createSvgElement(elem.tagName);
    Object.entries(elem.attrs).forEach(([k2, v4]) => result.setAttribute(k2, v4));
    for (let child of elem.children) {
      if (child.type == DomType.VmlElement) {
        result.appendChild(this.renderVmlChildElement(child));
      } else {
        result.appendChild(...asArray(this.renderElement(child)));
      }
    }
    return result;
  }
  renderMmlRadical(elem) {
    const base = elem.children.find((el) => el.type == DomType.MmlBase);
    if (elem.props?.hideDegree) {
      return this.createElementNS(ns.mathML, "msqrt", null, this.renderElements([base]));
    }
    const degree = elem.children.find((el) => el.type == DomType.MmlDegree);
    return this.createElementNS(ns.mathML, "mroot", null, this.renderElements([base, degree]));
  }
  renderMmlDelimiter(elem) {
    const children = [];
    children.push(this.createElementNS(ns.mathML, "mo", null, [elem.props.beginChar ?? "("]));
    children.push(...this.renderElements(elem.children));
    children.push(this.createElementNS(ns.mathML, "mo", null, [elem.props.endChar ?? ")"]));
    return this.createElementNS(ns.mathML, "mrow", null, children);
  }
  renderMmlNary(elem) {
    const children = [];
    const grouped = keyBy(elem.children, (x2) => x2.type);
    const sup2 = grouped[DomType.MmlSuperArgument];
    const sub2 = grouped[DomType.MmlSubArgument];
    const supElem = sup2 ? this.createElementNS(ns.mathML, "mo", null, asArray(this.renderElement(sup2))) : null;
    const subElem = sub2 ? this.createElementNS(ns.mathML, "mo", null, asArray(this.renderElement(sub2))) : null;
    const charElem = this.createElementNS(ns.mathML, "mo", null, [elem.props?.char ?? "\u222B"]);
    if (supElem || subElem) {
      children.push(this.createElementNS(ns.mathML, "munderover", null, [charElem, subElem, supElem]));
    } else if (supElem) {
      children.push(this.createElementNS(ns.mathML, "mover", null, [charElem, supElem]));
    } else if (subElem) {
      children.push(this.createElementNS(ns.mathML, "munder", null, [charElem, subElem]));
    } else {
      children.push(charElem);
    }
    children.push(...this.renderElements(grouped[DomType.MmlBase].children));
    return this.createElementNS(ns.mathML, "mrow", null, children);
  }
  renderMmlPreSubSuper(elem) {
    const children = [];
    const grouped = keyBy(elem.children, (x2) => x2.type);
    const sup2 = grouped[DomType.MmlSuperArgument];
    const sub2 = grouped[DomType.MmlSubArgument];
    const supElem = sup2 ? this.createElementNS(ns.mathML, "mo", null, asArray(this.renderElement(sup2))) : null;
    const subElem = sub2 ? this.createElementNS(ns.mathML, "mo", null, asArray(this.renderElement(sub2))) : null;
    const stubElem = this.createElementNS(ns.mathML, "mo", null);
    children.push(this.createElementNS(ns.mathML, "msubsup", null, [stubElem, subElem, supElem]));
    children.push(...this.renderElements(grouped[DomType.MmlBase].children));
    return this.createElementNS(ns.mathML, "mrow", null, children);
  }
  renderMmlGroupChar(elem) {
    const tagName = elem.props.verticalJustification === "bot" ? "mover" : "munder";
    const result = this.renderContainerNS(elem, ns.mathML, tagName);
    if (elem.props.char) {
      result.appendChild(this.createElementNS(ns.mathML, "mo", null, [elem.props.char]));
    }
    return result;
  }
  renderMmlBar(elem) {
    const result = this.renderContainerNS(elem, ns.mathML, "mrow");
    switch (elem.props.position) {
      case "top":
        result.style.textDecoration = "overline";
        break;
      case "bottom":
        result.style.textDecoration = "underline";
        break;
    }
    return result;
  }
  renderMmlRun(elem) {
    const result = this.createElementNS(ns.mathML, "ms", null, this.renderElements(elem.children));
    this.renderClass(elem, result);
    this.renderStyleValues(elem.cssStyle, result);
    return result;
  }
  renderMllList(elem) {
    const result = this.createElementNS(ns.mathML, "mtable");
    this.renderClass(elem, result);
    this.renderStyleValues(elem.cssStyle, result);
    for (let child of this.renderElements(elem.children)) {
      result.appendChild(this.createElementNS(ns.mathML, "mtr", null, [
        this.createElementNS(ns.mathML, "mtd", null, [child])
      ]));
    }
    return result;
  }
  renderStyleValues(style, ouput) {
    for (let k2 in style) {
      if (k2.startsWith("$")) {
        ouput.setAttribute(k2.slice(1), style[k2]);
      } else {
        ouput.style[k2] = style[k2];
      }
    }
  }
  renderClass(input, ouput) {
    if (input.className)
      ouput.className = input.className;
    if (input.styleName)
      ouput.classList.add(this.processStyleName(input.styleName));
  }
  findStyle(styleName) {
    return styleName && this.styleMap?.[styleName];
  }
  numberingClass(id, lvl) {
    return `${this.className}-num-${id}-${lvl}`;
  }
  tabStopClass() {
    return `${this.className}-tab-stop`;
  }
  styleToString(selectors, values2, cssText = null) {
    let result = `${selectors} {\r
`;
    for (const key in values2) {
      if (key.startsWith("$"))
        continue;
      result += `  ${key}: ${values2[key]};\r
`;
    }
    if (cssText)
      result += cssText;
    return result + "}\r\n";
  }
  numberingCounter(id, lvl) {
    return `${this.className}-num-${id}-${lvl}`;
  }
  levelTextToContent(text3, suff, id, numformat) {
    const suffMap = {
      "tab": "\\9",
      "space": "\\a0"
    };
    var result = text3.replace(/%\d*/g, (s6) => {
      let lvl = parseInt(s6.substring(1), 10) - 1;
      return `"counter(${this.numberingCounter(id, lvl)}, ${numformat})"`;
    });
    return `"${result}${suffMap[suff] ?? ""}"`;
  }
  numFormatToCssValue(format) {
    var mapping = {
      none: "none",
      bullet: "disc",
      decimal: "decimal",
      lowerLetter: "lower-alpha",
      upperLetter: "upper-alpha",
      lowerRoman: "lower-roman",
      upperRoman: "upper-roman",
      decimalZero: "decimal-leading-zero",
      aiueo: "katakana",
      aiueoFullWidth: "katakana",
      chineseCounting: "simp-chinese-informal",
      chineseCountingThousand: "simp-chinese-informal",
      chineseLegalSimplified: "simp-chinese-formal",
      chosung: "hangul-consonant",
      ideographDigital: "cjk-ideographic",
      ideographTraditional: "cjk-heavenly-stem",
      ideographLegalTraditional: "trad-chinese-formal",
      ideographZodiac: "cjk-earthly-branch",
      iroha: "katakana-iroha",
      irohaFullWidth: "katakana-iroha",
      japaneseCounting: "japanese-informal",
      japaneseDigitalTenThousand: "cjk-decimal",
      japaneseLegal: "japanese-formal",
      thaiNumbers: "thai",
      koreanCounting: "korean-hangul-formal",
      koreanDigital: "korean-hangul-formal",
      koreanDigital2: "korean-hanja-informal",
      hebrew1: "hebrew",
      hebrew2: "hebrew",
      hindiNumbers: "devanagari",
      ganada: "hangul",
      taiwaneseCounting: "cjk-ideographic",
      taiwaneseCountingThousand: "cjk-ideographic",
      taiwaneseDigital: "cjk-decimal"
    };
    return mapping[format] ?? format;
  }
  refreshTabStops() {
    if (!this.options.experimental)
      return;
    setTimeout(() => {
      const pixelToPoint = computePixelToPoint();
      for (let tab of this.currentTabs) {
        updateTabStop(tab.span, tab.stops, this.defaultTabSize, pixelToPoint);
      }
    }, 500);
  }
  createElementNS(ns2, tagName, props, children) {
    var result = ns2 ? this.htmlDocument.createElementNS(ns2, tagName) : this.htmlDocument.createElement(tagName);
    Object.assign(result, props);
    children && appendChildren(result, children);
    return result;
  }
  createElement(tagName, props, children) {
    return this.createElementNS(void 0, tagName, props, children);
  }
  createSvgElement(tagName, props, children) {
    return this.createElementNS(ns.svg, tagName, props, children);
  }
  createStyleElement(cssText) {
    return this.createElement("style", { innerHTML: cssText });
  }
  createComment(text3) {
    return this.htmlDocument.createComment(text3);
  }
  later(func) {
    this.postRenderTasks.push(func);
  }
};
function removeAllElements(elem) {
  elem.innerHTML = "";
}
function appendChildren(elem, children) {
  children.forEach((c6) => elem.appendChild(isString2(c6) ? document.createTextNode(c6) : c6));
}
function findParent(elem, type) {
  var parent = elem.parent;
  while (parent != null && parent.type != type)
    parent = parent.parent;
  return parent;
}
var defaultOptions2 = {
  ignoreHeight: false,
  ignoreWidth: false,
  ignoreFonts: false,
  breakPages: true,
  debug: false,
  experimental: false,
  className: "docx",
  inWrapper: true,
  hideWrapperOnPrint: false,
  trimXmlDeclaration: true,
  ignoreLastRenderedPageBreak: true,
  renderHeaders: true,
  renderFooters: true,
  renderFootnotes: true,
  renderEndnotes: true,
  useBase64URL: false,
  renderChanges: false,
  renderComments: false,
  renderAltChunks: true
};
function parseAsync(data, userOptions) {
  const ops = { ...defaultOptions2, ...userOptions };
  return WordDocument.load(data, new DocumentParser(ops), ops);
}
async function renderDocument(document2, bodyContainer, styleContainer, userOptions) {
  const ops = { ...defaultOptions2, ...userOptions };
  const renderer = new HtmlRenderer(window.document);
  return await renderer.render(document2, bodyContainer, styleContainer, ops);
}
async function renderAsync(data, bodyContainer, styleContainer, userOptions) {
  const doc = await parseAsync(data, userOptions);
  await renderDocument(doc, bodyContainer, styleContainer, userOptions);
  return doc;
}

// ../pi-mono/packages/web-ui/dist/utils/attachment-utils.js
var import_jszip2 = __toESM(require_jszip_min(), 1);

// ../pi-mono/node_modules/pdfjs-dist/build/pdf.mjs
init_process_shim();
var __webpack_require__ = {};
(() => {
  __webpack_require__.d = (exports, definition) => {
    for (var key in definition) {
      if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
        Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
      }
    }
  };
})();
(() => {
  __webpack_require__.o = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop);
})();
var isNodeJS = typeof process === "object" && process + "" === "[object process]" && !process.versions.nw && !(process.versions.electron && process.type && process.type !== "browser");
var FONT_IDENTITY_MATRIX = [1e-3, 0, 0, 1e-3, 0, 0];
var LINE_FACTOR = 1.35;
var LINE_DESCENT_FACTOR = 0.35;
var BASELINE_FACTOR = LINE_DESCENT_FACTOR / LINE_FACTOR;
var RenderingIntentFlag = {
  ANY: 1,
  DISPLAY: 2,
  PRINT: 4,
  SAVE: 8,
  ANNOTATIONS_FORMS: 16,
  ANNOTATIONS_STORAGE: 32,
  ANNOTATIONS_DISABLE: 64,
  IS_EDITING: 128,
  OPLIST: 256
};
var AnnotationMode = {
  DISABLE: 0,
  ENABLE: 1,
  ENABLE_FORMS: 2,
  ENABLE_STORAGE: 3
};
var AnnotationEditorPrefix = "pdfjs_internal_editor_";
var AnnotationEditorType = {
  DISABLE: -1,
  NONE: 0,
  FREETEXT: 3,
  HIGHLIGHT: 9,
  STAMP: 13,
  INK: 15,
  POPUP: 16,
  SIGNATURE: 101,
  COMMENT: 102
};
var AnnotationEditorParamsType = {
  RESIZE: 1,
  CREATE: 2,
  FREETEXT_SIZE: 11,
  FREETEXT_COLOR: 12,
  FREETEXT_OPACITY: 13,
  INK_COLOR: 21,
  INK_THICKNESS: 22,
  INK_OPACITY: 23,
  HIGHLIGHT_COLOR: 31,
  HIGHLIGHT_THICKNESS: 32,
  HIGHLIGHT_FREE: 33,
  HIGHLIGHT_SHOW_ALL: 34,
  DRAW_STEP: 41
};
var PermissionFlag = {
  PRINT: 4,
  MODIFY_CONTENTS: 8,
  COPY: 16,
  MODIFY_ANNOTATIONS: 32,
  FILL_INTERACTIVE_FORMS: 256,
  COPY_FOR_ACCESSIBILITY: 512,
  ASSEMBLE: 1024,
  PRINT_HIGH_QUALITY: 2048
};
var MeshFigureType = {
  TRIANGLES: 1,
  LATTICE: 2,
  PATCH: 3
};
var TextRenderingMode = {
  FILL: 0,
  STROKE: 1,
  FILL_STROKE: 2,
  INVISIBLE: 3,
  FILL_ADD_TO_PATH: 4,
  STROKE_ADD_TO_PATH: 5,
  FILL_STROKE_ADD_TO_PATH: 6,
  ADD_TO_PATH: 7,
  FILL_STROKE_MASK: 3,
  ADD_TO_PATH_FLAG: 4
};
var util_ImageKind = {
  GRAYSCALE_1BPP: 1,
  RGB_24BPP: 2,
  RGBA_32BPP: 3
};
var AnnotationType = {
  TEXT: 1,
  LINK: 2,
  FREETEXT: 3,
  LINE: 4,
  SQUARE: 5,
  CIRCLE: 6,
  POLYGON: 7,
  POLYLINE: 8,
  HIGHLIGHT: 9,
  UNDERLINE: 10,
  SQUIGGLY: 11,
  STRIKEOUT: 12,
  STAMP: 13,
  CARET: 14,
  INK: 15,
  POPUP: 16,
  FILEATTACHMENT: 17,
  SOUND: 18,
  MOVIE: 19,
  WIDGET: 20,
  SCREEN: 21,
  PRINTERMARK: 22,
  TRAPNET: 23,
  WATERMARK: 24,
  THREED: 25,
  REDACT: 26
};
var AnnotationBorderStyleType = {
  SOLID: 1,
  DASHED: 2,
  BEVELED: 3,
  INSET: 4,
  UNDERLINE: 5
};
var VerbosityLevel = {
  ERRORS: 0,
  WARNINGS: 1,
  INFOS: 5
};
var OPS = {
  dependency: 1,
  setLineWidth: 2,
  setLineCap: 3,
  setLineJoin: 4,
  setMiterLimit: 5,
  setDash: 6,
  setRenderingIntent: 7,
  setFlatness: 8,
  setGState: 9,
  save: 10,
  restore: 11,
  transform: 12,
  moveTo: 13,
  lineTo: 14,
  curveTo: 15,
  curveTo2: 16,
  curveTo3: 17,
  closePath: 18,
  rectangle: 19,
  stroke: 20,
  closeStroke: 21,
  fill: 22,
  eoFill: 23,
  fillStroke: 24,
  eoFillStroke: 25,
  closeFillStroke: 26,
  closeEOFillStroke: 27,
  endPath: 28,
  clip: 29,
  eoClip: 30,
  beginText: 31,
  endText: 32,
  setCharSpacing: 33,
  setWordSpacing: 34,
  setHScale: 35,
  setLeading: 36,
  setFont: 37,
  setTextRenderingMode: 38,
  setTextRise: 39,
  moveText: 40,
  setLeadingMoveText: 41,
  setTextMatrix: 42,
  nextLine: 43,
  showText: 44,
  showSpacedText: 45,
  nextLineShowText: 46,
  nextLineSetSpacingShowText: 47,
  setCharWidth: 48,
  setCharWidthAndBounds: 49,
  setStrokeColorSpace: 50,
  setFillColorSpace: 51,
  setStrokeColor: 52,
  setStrokeColorN: 53,
  setFillColor: 54,
  setFillColorN: 55,
  setStrokeGray: 56,
  setFillGray: 57,
  setStrokeRGBColor: 58,
  setFillRGBColor: 59,
  setStrokeCMYKColor: 60,
  setFillCMYKColor: 61,
  shadingFill: 62,
  beginInlineImage: 63,
  beginImageData: 64,
  endInlineImage: 65,
  paintXObject: 66,
  markPoint: 67,
  markPointProps: 68,
  beginMarkedContent: 69,
  beginMarkedContentProps: 70,
  endMarkedContent: 71,
  beginCompat: 72,
  endCompat: 73,
  paintFormXObjectBegin: 74,
  paintFormXObjectEnd: 75,
  beginGroup: 76,
  endGroup: 77,
  beginAnnotation: 80,
  endAnnotation: 81,
  paintImageMaskXObject: 83,
  paintImageMaskXObjectGroup: 84,
  paintImageXObject: 85,
  paintInlineImageXObject: 86,
  paintInlineImageXObjectGroup: 87,
  paintImageXObjectRepeat: 88,
  paintImageMaskXObjectRepeat: 89,
  paintSolidColorImageMask: 90,
  constructPath: 91,
  setStrokeTransparent: 92,
  setFillTransparent: 93,
  rawFillPath: 94
};
var DrawOPS = {
  moveTo: 0,
  lineTo: 1,
  curveTo: 2,
  quadraticCurveTo: 3,
  closePath: 4
};
var PasswordResponses = {
  NEED_PASSWORD: 1,
  INCORRECT_PASSWORD: 2
};
var verbosity = VerbosityLevel.WARNINGS;
function setVerbosityLevel(level) {
  if (Number.isInteger(level)) {
    verbosity = level;
  }
}
function getVerbosityLevel() {
  return verbosity;
}
function info(msg) {
  if (verbosity >= VerbosityLevel.INFOS) {
    console.info(`Info: ${msg}`);
  }
}
function warn(msg) {
  if (verbosity >= VerbosityLevel.WARNINGS) {
    console.warn(`Warning: ${msg}`);
  }
}
function unreachable(msg) {
  throw new Error(msg);
}
function assert(cond, msg) {
  if (!cond) {
    unreachable(msg);
  }
}
function _isValidProtocol(url) {
  switch (url?.protocol) {
    case "http:":
    case "https:":
    case "ftp:":
    case "mailto:":
    case "tel:":
      return true;
    default:
      return false;
  }
}
function createValidAbsoluteUrl(url, baseUrl = null, options = null) {
  if (!url) {
    return null;
  }
  if (options && typeof url === "string") {
    if (options.addDefaultProtocol && url.startsWith("www.")) {
      const dots = url.match(/\./g);
      if (dots?.length >= 2) {
        url = `http://${url}`;
      }
    }
    if (options.tryConvertEncoding) {
      try {
        url = stringToUTF8String(url);
      } catch {
      }
    }
  }
  const absoluteUrl = baseUrl ? URL.parse(url, baseUrl) : URL.parse(url);
  return _isValidProtocol(absoluteUrl) ? absoluteUrl : null;
}
function updateUrlHash(url, hash, allowRel = false) {
  const res = URL.parse(url);
  if (res) {
    res.hash = hash;
    return res.href;
  }
  if (allowRel && createValidAbsoluteUrl(url, "http://example.com")) {
    return url.split("#", 1)[0] + `${hash ? `#${hash}` : ""}`;
  }
  return "";
}
function shadow(obj, prop, value, nonSerializable = false) {
  Object.defineProperty(obj, prop, {
    value,
    enumerable: !nonSerializable,
    configurable: true,
    writable: false
  });
  return value;
}
var BaseException = (function BaseExceptionClosure() {
  function BaseException2(message, name) {
    this.message = message;
    this.name = name;
  }
  BaseException2.prototype = new Error();
  BaseException2.constructor = BaseException2;
  return BaseException2;
})();
var PasswordException = class extends BaseException {
  constructor(msg, code) {
    super(msg, "PasswordException");
    this.code = code;
  }
};
var UnknownErrorException = class extends BaseException {
  constructor(msg, details) {
    super(msg, "UnknownErrorException");
    this.details = details;
  }
};
var InvalidPDFException = class extends BaseException {
  constructor(msg) {
    super(msg, "InvalidPDFException");
  }
};
var ResponseException = class extends BaseException {
  constructor(msg, status, missing) {
    super(msg, "ResponseException");
    this.status = status;
    this.missing = missing;
  }
};
var FormatError = class extends BaseException {
  constructor(msg) {
    super(msg, "FormatError");
  }
};
var AbortException = class extends BaseException {
  constructor(msg) {
    super(msg, "AbortException");
  }
};
function bytesToString(bytes) {
  if (typeof bytes !== "object" || bytes?.length === void 0) {
    unreachable("Invalid argument for bytesToString");
  }
  const length = bytes.length;
  const MAX_ARGUMENT_COUNT = 8192;
  if (length < MAX_ARGUMENT_COUNT) {
    return String.fromCharCode.apply(null, bytes);
  }
  const strBuf = [];
  for (let i7 = 0; i7 < length; i7 += MAX_ARGUMENT_COUNT) {
    const chunkEnd = Math.min(i7 + MAX_ARGUMENT_COUNT, length);
    const chunk = bytes.subarray(i7, chunkEnd);
    strBuf.push(String.fromCharCode.apply(null, chunk));
  }
  return strBuf.join("");
}
function stringToBytes(str2) {
  if (typeof str2 !== "string") {
    unreachable("Invalid argument for stringToBytes");
  }
  const length = str2.length;
  const bytes = new Uint8Array(length);
  for (let i7 = 0; i7 < length; ++i7) {
    bytes[i7] = str2.charCodeAt(i7) & 255;
  }
  return bytes;
}
function string32(value) {
  return String.fromCharCode(value >> 24 & 255, value >> 16 & 255, value >> 8 & 255, value & 255);
}
function isLittleEndian() {
  const buffer8 = new Uint8Array(4);
  buffer8[0] = 1;
  const view32 = new Uint32Array(buffer8.buffer, 0, 1);
  return view32[0] === 1;
}
function isEvalSupported() {
  try {
    new Function("");
    return true;
  } catch {
    return false;
  }
}
var util_FeatureTest = class {
  static get isLittleEndian() {
    return shadow(this, "isLittleEndian", isLittleEndian());
  }
  static get isEvalSupported() {
    return shadow(this, "isEvalSupported", isEvalSupported());
  }
  static get isOffscreenCanvasSupported() {
    return shadow(this, "isOffscreenCanvasSupported", typeof OffscreenCanvas !== "undefined");
  }
  static get isImageDecoderSupported() {
    return shadow(this, "isImageDecoderSupported", typeof ImageDecoder !== "undefined");
  }
  static get isFloat16ArraySupported() {
    return shadow(this, "isFloat16ArraySupported", typeof Float16Array !== "undefined");
  }
  static get isSanitizerSupported() {
    return shadow(this, "isSanitizerSupported", typeof Sanitizer !== "undefined");
  }
  static get platform() {
    const {
      platform,
      userAgent
    } = navigator;
    return shadow(this, "platform", {
      isAndroid: userAgent.includes("Android"),
      isLinux: platform.includes("Linux"),
      isMac: platform.includes("Mac"),
      isWindows: platform.includes("Win"),
      isFirefox: userAgent.includes("Firefox")
    });
  }
  static get isCSSRoundSupported() {
    return shadow(this, "isCSSRoundSupported", globalThis.CSS?.supports?.("width: round(1.5px, 1px)"));
  }
};
var hexNumbers = Array.from(Array(256).keys(), (n7) => n7.toString(16).padStart(2, "0"));
var Util = class {
  static makeHexColor(r8, g3, b4) {
    return `#${hexNumbers[r8]}${hexNumbers[g3]}${hexNumbers[b4]}`;
  }
  static domMatrixToTransform(dm) {
    return [dm.a, dm.b, dm.c, dm.d, dm.e, dm.f];
  }
  static scaleMinMax(transform, minMax) {
    let temp;
    if (transform[0]) {
      if (transform[0] < 0) {
        temp = minMax[0];
        minMax[0] = minMax[2];
        minMax[2] = temp;
      }
      minMax[0] *= transform[0];
      minMax[2] *= transform[0];
      if (transform[3] < 0) {
        temp = minMax[1];
        minMax[1] = minMax[3];
        minMax[3] = temp;
      }
      minMax[1] *= transform[3];
      minMax[3] *= transform[3];
    } else {
      temp = minMax[0];
      minMax[0] = minMax[1];
      minMax[1] = temp;
      temp = minMax[2];
      minMax[2] = minMax[3];
      minMax[3] = temp;
      if (transform[1] < 0) {
        temp = minMax[1];
        minMax[1] = minMax[3];
        minMax[3] = temp;
      }
      minMax[1] *= transform[1];
      minMax[3] *= transform[1];
      if (transform[2] < 0) {
        temp = minMax[0];
        minMax[0] = minMax[2];
        minMax[2] = temp;
      }
      minMax[0] *= transform[2];
      minMax[2] *= transform[2];
    }
    minMax[0] += transform[4];
    minMax[1] += transform[5];
    minMax[2] += transform[4];
    minMax[3] += transform[5];
  }
  static transform(m1, m22) {
    return [m1[0] * m22[0] + m1[2] * m22[1], m1[1] * m22[0] + m1[3] * m22[1], m1[0] * m22[2] + m1[2] * m22[3], m1[1] * m22[2] + m1[3] * m22[3], m1[0] * m22[4] + m1[2] * m22[5] + m1[4], m1[1] * m22[4] + m1[3] * m22[5] + m1[5]];
  }
  static multiplyByDOMMatrix(m4, md) {
    return [m4[0] * md.a + m4[2] * md.b, m4[1] * md.a + m4[3] * md.b, m4[0] * md.c + m4[2] * md.d, m4[1] * md.c + m4[3] * md.d, m4[0] * md.e + m4[2] * md.f + m4[4], m4[1] * md.e + m4[3] * md.f + m4[5]];
  }
  static applyTransform(p4, m4, pos = 0) {
    const p0 = p4[pos];
    const p1 = p4[pos + 1];
    p4[pos] = p0 * m4[0] + p1 * m4[2] + m4[4];
    p4[pos + 1] = p0 * m4[1] + p1 * m4[3] + m4[5];
  }
  static applyTransformToBezier(p4, transform, pos = 0) {
    const m0 = transform[0];
    const m1 = transform[1];
    const m22 = transform[2];
    const m32 = transform[3];
    const m4 = transform[4];
    const m5 = transform[5];
    for (let i7 = 0; i7 < 6; i7 += 2) {
      const pI = p4[pos + i7];
      const pI1 = p4[pos + i7 + 1];
      p4[pos + i7] = pI * m0 + pI1 * m22 + m4;
      p4[pos + i7 + 1] = pI * m1 + pI1 * m32 + m5;
    }
  }
  static applyInverseTransform(p4, m4) {
    const p0 = p4[0];
    const p1 = p4[1];
    const d4 = m4[0] * m4[3] - m4[1] * m4[2];
    p4[0] = (p0 * m4[3] - p1 * m4[2] + m4[2] * m4[5] - m4[4] * m4[3]) / d4;
    p4[1] = (-p0 * m4[1] + p1 * m4[0] + m4[4] * m4[1] - m4[5] * m4[0]) / d4;
  }
  static axialAlignedBoundingBox(rect, transform, output) {
    const m0 = transform[0];
    const m1 = transform[1];
    const m22 = transform[2];
    const m32 = transform[3];
    const m4 = transform[4];
    const m5 = transform[5];
    const r0 = rect[0];
    const r1 = rect[1];
    const r22 = rect[2];
    const r32 = rect[3];
    let a0 = m0 * r0 + m4;
    let a22 = a0;
    let a1 = m0 * r22 + m4;
    let a3 = a1;
    let b0 = m32 * r1 + m5;
    let b22 = b0;
    let b1 = m32 * r32 + m5;
    let b32 = b1;
    if (m1 !== 0 || m22 !== 0) {
      const m1r0 = m1 * r0;
      const m1r2 = m1 * r22;
      const m2r1 = m22 * r1;
      const m2r3 = m22 * r32;
      a0 += m2r1;
      a3 += m2r1;
      a1 += m2r3;
      a22 += m2r3;
      b0 += m1r0;
      b32 += m1r0;
      b1 += m1r2;
      b22 += m1r2;
    }
    output[0] = Math.min(output[0], a0, a1, a22, a3);
    output[1] = Math.min(output[1], b0, b1, b22, b32);
    output[2] = Math.max(output[2], a0, a1, a22, a3);
    output[3] = Math.max(output[3], b0, b1, b22, b32);
  }
  static inverseTransform(m4) {
    const d4 = m4[0] * m4[3] - m4[1] * m4[2];
    return [m4[3] / d4, -m4[1] / d4, -m4[2] / d4, m4[0] / d4, (m4[2] * m4[5] - m4[4] * m4[3]) / d4, (m4[4] * m4[1] - m4[5] * m4[0]) / d4];
  }
  static singularValueDecompose2dScale(matrix, output) {
    const m0 = matrix[0];
    const m1 = matrix[1];
    const m22 = matrix[2];
    const m32 = matrix[3];
    const a3 = m0 ** 2 + m1 ** 2;
    const b4 = m0 * m22 + m1 * m32;
    const c6 = m22 ** 2 + m32 ** 2;
    const first = (a3 + c6) / 2;
    const second = Math.sqrt(first ** 2 - (a3 * c6 - b4 ** 2));
    output[0] = Math.sqrt(first + second || 1);
    output[1] = Math.sqrt(first - second || 1);
  }
  static normalizeRect(rect) {
    const r8 = rect.slice(0);
    if (rect[0] > rect[2]) {
      r8[0] = rect[2];
      r8[2] = rect[0];
    }
    if (rect[1] > rect[3]) {
      r8[1] = rect[3];
      r8[3] = rect[1];
    }
    return r8;
  }
  static intersect(rect1, rect2) {
    const xLow = Math.max(Math.min(rect1[0], rect1[2]), Math.min(rect2[0], rect2[2]));
    const xHigh = Math.min(Math.max(rect1[0], rect1[2]), Math.max(rect2[0], rect2[2]));
    if (xLow > xHigh) {
      return null;
    }
    const yLow = Math.max(Math.min(rect1[1], rect1[3]), Math.min(rect2[1], rect2[3]));
    const yHigh = Math.min(Math.max(rect1[1], rect1[3]), Math.max(rect2[1], rect2[3]));
    if (yLow > yHigh) {
      return null;
    }
    return [xLow, yLow, xHigh, yHigh];
  }
  static pointBoundingBox(x2, y4, minMax) {
    minMax[0] = Math.min(minMax[0], x2);
    minMax[1] = Math.min(minMax[1], y4);
    minMax[2] = Math.max(minMax[2], x2);
    minMax[3] = Math.max(minMax[3], y4);
  }
  static rectBoundingBox(x0, y0, x1, y1, minMax) {
    minMax[0] = Math.min(minMax[0], x0, x1);
    minMax[1] = Math.min(minMax[1], y0, y1);
    minMax[2] = Math.max(minMax[2], x0, x1);
    minMax[3] = Math.max(minMax[3], y0, y1);
  }
  static #getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y22, y32, t6, minMax) {
    if (t6 <= 0 || t6 >= 1) {
      return;
    }
    const mt = 1 - t6;
    const tt = t6 * t6;
    const ttt = tt * t6;
    const x4 = mt * (mt * (mt * x0 + 3 * t6 * x1) + 3 * tt * x2) + ttt * x3;
    const y4 = mt * (mt * (mt * y0 + 3 * t6 * y1) + 3 * tt * y22) + ttt * y32;
    minMax[0] = Math.min(minMax[0], x4);
    minMax[1] = Math.min(minMax[1], y4);
    minMax[2] = Math.max(minMax[2], x4);
    minMax[3] = Math.max(minMax[3], y4);
  }
  static #getExtremum(x0, x1, x2, x3, y0, y1, y22, y32, a3, b4, c6, minMax) {
    if (Math.abs(a3) < 1e-12) {
      if (Math.abs(b4) >= 1e-12) {
        this.#getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y22, y32, -c6 / b4, minMax);
      }
      return;
    }
    const delta = b4 ** 2 - 4 * c6 * a3;
    if (delta < 0) {
      return;
    }
    const sqrtDelta = Math.sqrt(delta);
    const a22 = 2 * a3;
    this.#getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y22, y32, (-b4 + sqrtDelta) / a22, minMax);
    this.#getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y22, y32, (-b4 - sqrtDelta) / a22, minMax);
  }
  static bezierBoundingBox(x0, y0, x1, y1, x2, y22, x3, y32, minMax) {
    minMax[0] = Math.min(minMax[0], x0, x3);
    minMax[1] = Math.min(minMax[1], y0, y32);
    minMax[2] = Math.max(minMax[2], x0, x3);
    minMax[3] = Math.max(minMax[3], y0, y32);
    this.#getExtremum(x0, x1, x2, x3, y0, y1, y22, y32, 3 * (-x0 + 3 * (x1 - x2) + x3), 6 * (x0 - 2 * x1 + x2), 3 * (x1 - x0), minMax);
    this.#getExtremum(x0, x1, x2, x3, y0, y1, y22, y32, 3 * (-y0 + 3 * (y1 - y22) + y32), 6 * (y0 - 2 * y1 + y22), 3 * (y1 - y0), minMax);
  }
};
function stringToUTF8String(str2) {
  return decodeURIComponent(escape(str2));
}
var NormalizeRegex = null;
var NormalizationMap = null;
function normalizeUnicode(str2) {
  if (!NormalizeRegex) {
    NormalizeRegex = /([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu;
    NormalizationMap = /* @__PURE__ */ new Map([["\uFB05", "\u017Ft"]]);
  }
  return str2.replaceAll(NormalizeRegex, (_3, p1, p22) => p1 ? p1.normalize("NFKC") : NormalizationMap.get(p22));
}
function getUuid() {
  if (typeof crypto.randomUUID === "function") {
    return crypto.randomUUID();
  }
  const buf = new Uint8Array(32);
  crypto.getRandomValues(buf);
  return bytesToString(buf);
}
var AnnotationPrefix = "pdfjs_internal_id_";
function _isValidExplicitDest(validRef, validName, dest) {
  if (!Array.isArray(dest) || dest.length < 2) {
    return false;
  }
  const [page, zoom, ...args] = dest;
  if (!validRef(page) && !Number.isInteger(page)) {
    return false;
  }
  if (!validName(zoom)) {
    return false;
  }
  const argsLen = args.length;
  let allowNull = true;
  switch (zoom.name) {
    case "XYZ":
      if (argsLen < 2 || argsLen > 3) {
        return false;
      }
      break;
    case "Fit":
    case "FitB":
      return argsLen === 0;
    case "FitH":
    case "FitBH":
    case "FitV":
    case "FitBV":
      if (argsLen > 1) {
        return false;
      }
      break;
    case "FitR":
      if (argsLen !== 4) {
        return false;
      }
      allowNull = false;
      break;
    default:
      return false;
  }
  for (const arg of args) {
    if (typeof arg === "number" || allowNull && arg === null) {
      continue;
    }
    return false;
  }
  return true;
}
function MathClamp(v4, min, max) {
  return Math.min(Math.max(v4, min), max);
}
function toBase64Util(arr) {
  if (Uint8Array.prototype.toBase64) {
    return arr.toBase64();
  }
  return btoa(bytesToString(arr));
}
function fromBase64Util(str2) {
  if (Uint8Array.fromBase64) {
    return Uint8Array.fromBase64(str2);
  }
  return stringToBytes(atob(str2));
}
if (typeof Promise.try !== "function") {
  Promise.try = function(fn, ...args) {
    return new Promise((resolve) => {
      resolve(fn(...args));
    });
  };
}
if (typeof Math.sumPrecise !== "function") {
  Math.sumPrecise = function(numbers) {
    return numbers.reduce((a3, b4) => a3 + b4, 0);
  };
}
var XfaText = class _XfaText {
  static textContent(xfa) {
    const items = [];
    const output = {
      items,
      styles: /* @__PURE__ */ Object.create(null)
    };
    function walk(node) {
      if (!node) {
        return;
      }
      let str2 = null;
      const name = node.name;
      if (name === "#text") {
        str2 = node.value;
      } else if (!_XfaText.shouldBuildText(name)) {
        return;
      } else if (node?.attributes?.textContent) {
        str2 = node.attributes.textContent;
      } else if (node.value) {
        str2 = node.value;
      }
      if (str2 !== null) {
        items.push({
          str: str2
        });
      }
      if (!node.children) {
        return;
      }
      for (const child of node.children) {
        walk(child);
      }
    }
    walk(xfa);
    return output;
  }
  static shouldBuildText(name) {
    return !(name === "textarea" || name === "input" || name === "option" || name === "select");
  }
};
var XfaLayer = class {
  static setupStorage(html, id, element, storage2, intent) {
    const storedData = storage2.getValue(id, {
      value: null
    });
    switch (element.name) {
      case "textarea":
        if (storedData.value !== null) {
          html.textContent = storedData.value;
        }
        if (intent === "print") {
          break;
        }
        html.addEventListener("input", (event) => {
          storage2.setValue(id, {
            value: event.target.value
          });
        });
        break;
      case "input":
        if (element.attributes.type === "radio" || element.attributes.type === "checkbox") {
          if (storedData.value === element.attributes.xfaOn) {
            html.setAttribute("checked", true);
          } else if (storedData.value === element.attributes.xfaOff) {
            html.removeAttribute("checked");
          }
          if (intent === "print") {
            break;
          }
          html.addEventListener("change", (event) => {
            storage2.setValue(id, {
              value: event.target.checked ? event.target.getAttribute("xfaOn") : event.target.getAttribute("xfaOff")
            });
          });
        } else {
          if (storedData.value !== null) {
            html.setAttribute("value", storedData.value);
          }
          if (intent === "print") {
            break;
          }
          html.addEventListener("input", (event) => {
            storage2.setValue(id, {
              value: event.target.value
            });
          });
        }
        break;
      case "select":
        if (storedData.value !== null) {
          html.setAttribute("value", storedData.value);
          for (const option of element.children) {
            if (option.attributes.value === storedData.value) {
              option.attributes.selected = true;
            } else if (option.attributes.hasOwnProperty("selected")) {
              delete option.attributes.selected;
            }
          }
        }
        html.addEventListener("input", (event) => {
          const options = event.target.options;
          const value = options.selectedIndex === -1 ? "" : options[options.selectedIndex].value;
          storage2.setValue(id, {
            value
          });
        });
        break;
    }
  }
  static setAttributes({
    html,
    element,
    storage: storage2 = null,
    intent,
    linkService
  }) {
    const {
      attributes
    } = element;
    const isHTMLAnchorElement = html instanceof HTMLAnchorElement;
    if (attributes.type === "radio") {
      attributes.name = `${attributes.name}-${intent}`;
    }
    for (const [key, value] of Object.entries(attributes)) {
      if (value === null || value === void 0) {
        continue;
      }
      switch (key) {
        case "class":
          if (value.length) {
            html.setAttribute(key, value.join(" "));
          }
          break;
        case "dataId":
          break;
        case "id":
          html.setAttribute("data-element-id", value);
          break;
        case "style":
          Object.assign(html.style, value);
          break;
        case "textContent":
          html.textContent = value;
          break;
        default:
          if (!isHTMLAnchorElement || key !== "href" && key !== "newWindow") {
            html.setAttribute(key, value);
          }
      }
    }
    if (isHTMLAnchorElement) {
      linkService.addLinkAttributes(html, attributes.href, attributes.newWindow);
    }
    if (storage2 && attributes.dataId) {
      this.setupStorage(html, attributes.dataId, element, storage2);
    }
  }
  static render(parameters) {
    const storage2 = parameters.annotationStorage;
    const linkService = parameters.linkService;
    const root = parameters.xfaHtml;
    const intent = parameters.intent || "display";
    const rootHtml = document.createElement(root.name);
    if (root.attributes) {
      this.setAttributes({
        html: rootHtml,
        element: root,
        intent,
        linkService
      });
    }
    const isNotForRichText = intent !== "richText";
    const rootDiv = parameters.div;
    rootDiv.append(rootHtml);
    if (parameters.viewport) {
      const transform = `matrix(${parameters.viewport.transform.join(",")})`;
      rootDiv.style.transform = transform;
    }
    if (isNotForRichText) {
      rootDiv.setAttribute("class", "xfaLayer xfaFont");
    }
    const textDivs = [];
    if (root.children.length === 0) {
      if (root.value) {
        const node = document.createTextNode(root.value);
        rootHtml.append(node);
        if (isNotForRichText && XfaText.shouldBuildText(root.name)) {
          textDivs.push(node);
        }
      }
      return {
        textDivs
      };
    }
    const stack = [[root, -1, rootHtml]];
    while (stack.length > 0) {
      const [parent, i7, html] = stack.at(-1);
      if (i7 + 1 === parent.children.length) {
        stack.pop();
        continue;
      }
      const child = parent.children[++stack.at(-1)[1]];
      if (child === null) {
        continue;
      }
      const {
        name
      } = child;
      if (name === "#text") {
        const node = document.createTextNode(child.value);
        textDivs.push(node);
        html.append(node);
        continue;
      }
      const childHtml = child?.attributes?.xmlns ? document.createElementNS(child.attributes.xmlns, name) : document.createElement(name);
      html.append(childHtml);
      if (child.attributes) {
        this.setAttributes({
          html: childHtml,
          element: child,
          storage: storage2,
          intent,
          linkService
        });
      }
      if (child.children?.length > 0) {
        stack.push([child, -1, childHtml]);
      } else if (child.value) {
        const node = document.createTextNode(child.value);
        if (isNotForRichText && XfaText.shouldBuildText(name)) {
          textDivs.push(node);
        }
        childHtml.append(node);
      }
    }
    for (const el of rootDiv.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea")) {
      el.setAttribute("readOnly", true);
    }
    return {
      textDivs
    };
  }
  static update(parameters) {
    const transform = `matrix(${parameters.viewport.transform.join(",")})`;
    parameters.div.style.transform = transform;
    parameters.div.hidden = false;
  }
};
var SVG_NS = "http://www.w3.org/2000/svg";
var PixelsPerInch = class {
  static CSS = 96;
  static PDF = 72;
  static PDF_TO_CSS_UNITS = this.CSS / this.PDF;
};
async function fetchData(url, type = "text") {
  if (isValidFetchUrl(url, document.baseURI)) {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(response.statusText);
    }
    switch (type) {
      case "arraybuffer":
        return response.arrayBuffer();
      case "blob":
        return response.blob();
      case "json":
        return response.json();
    }
    return response.text();
  }
  return new Promise((resolve, reject) => {
    const request = new XMLHttpRequest();
    request.open("GET", url, true);
    request.responseType = type;
    request.onreadystatechange = () => {
      if (request.readyState !== XMLHttpRequest.DONE) {
        return;
      }
      if (request.status === 200 || request.status === 0) {
        switch (type) {
          case "arraybuffer":
          case "blob":
          case "json":
            resolve(request.response);
            return;
        }
        resolve(request.responseText);
        return;
      }
      reject(new Error(request.statusText));
    };
    request.send(null);
  });
}
var PageViewport = class _PageViewport {
  constructor({
    viewBox,
    userUnit,
    scale,
    rotation,
    offsetX = 0,
    offsetY = 0,
    dontFlip = false
  }) {
    this.viewBox = viewBox;
    this.userUnit = userUnit;
    this.scale = scale;
    this.rotation = rotation;
    this.offsetX = offsetX;
    this.offsetY = offsetY;
    scale *= userUnit;
    const centerX = (viewBox[2] + viewBox[0]) / 2;
    const centerY = (viewBox[3] + viewBox[1]) / 2;
    let rotateA, rotateB, rotateC, rotateD;
    rotation %= 360;
    if (rotation < 0) {
      rotation += 360;
    }
    switch (rotation) {
      case 180:
        rotateA = -1;
        rotateB = 0;
        rotateC = 0;
        rotateD = 1;
        break;
      case 90:
        rotateA = 0;
        rotateB = 1;
        rotateC = 1;
        rotateD = 0;
        break;
      case 270:
        rotateA = 0;
        rotateB = -1;
        rotateC = -1;
        rotateD = 0;
        break;
      case 0:
        rotateA = 1;
        rotateB = 0;
        rotateC = 0;
        rotateD = -1;
        break;
      default:
        throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.");
    }
    if (dontFlip) {
      rotateC = -rotateC;
      rotateD = -rotateD;
    }
    let offsetCanvasX, offsetCanvasY;
    let width, height;
    if (rotateA === 0) {
      offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
      offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
      width = (viewBox[3] - viewBox[1]) * scale;
      height = (viewBox[2] - viewBox[0]) * scale;
    } else {
      offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
      offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
      width = (viewBox[2] - viewBox[0]) * scale;
      height = (viewBox[3] - viewBox[1]) * scale;
    }
    this.transform = [rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY];
    this.width = width;
    this.height = height;
  }
  get rawDims() {
    const dims = this.viewBox;
    return shadow(this, "rawDims", {
      pageWidth: dims[2] - dims[0],
      pageHeight: dims[3] - dims[1],
      pageX: dims[0],
      pageY: dims[1]
    });
  }
  clone({
    scale = this.scale,
    rotation = this.rotation,
    offsetX = this.offsetX,
    offsetY = this.offsetY,
    dontFlip = false
  } = {}) {
    return new _PageViewport({
      viewBox: this.viewBox.slice(),
      userUnit: this.userUnit,
      scale,
      rotation,
      offsetX,
      offsetY,
      dontFlip
    });
  }
  convertToViewportPoint(x2, y4) {
    const p4 = [x2, y4];
    Util.applyTransform(p4, this.transform);
    return p4;
  }
  convertToViewportRectangle(rect) {
    const topLeft = [rect[0], rect[1]];
    Util.applyTransform(topLeft, this.transform);
    const bottomRight = [rect[2], rect[3]];
    Util.applyTransform(bottomRight, this.transform);
    return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]];
  }
  convertToPdfPoint(x2, y4) {
    const p4 = [x2, y4];
    Util.applyInverseTransform(p4, this.transform);
    return p4;
  }
};
var RenderingCancelledException = class extends BaseException {
  constructor(msg, extraDelay = 0) {
    super(msg, "RenderingCancelledException");
    this.extraDelay = extraDelay;
  }
};
function isDataScheme(url) {
  const ii = url.length;
  let i7 = 0;
  while (i7 < ii && url[i7].trim() === "") {
    i7++;
  }
  return url.substring(i7, i7 + 5).toLowerCase() === "data:";
}
function isPdfFile(filename) {
  return typeof filename === "string" && /\.pdf$/i.test(filename);
}
function getFilenameFromUrl(url) {
  [url] = url.split(/[#?]/, 1);
  return url.substring(url.lastIndexOf("/") + 1);
}
function getPdfFilenameFromUrl(url, defaultFilename = "document.pdf") {
  if (typeof url !== "string") {
    return defaultFilename;
  }
  if (isDataScheme(url)) {
    warn('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.');
    return defaultFilename;
  }
  const getURL = (urlString) => {
    try {
      return new URL(urlString);
    } catch {
      try {
        return new URL(decodeURIComponent(urlString));
      } catch {
        try {
          return new URL(urlString, "https://foo.bar");
        } catch {
          try {
            return new URL(decodeURIComponent(urlString), "https://foo.bar");
          } catch {
            return null;
          }
        }
      }
    }
  };
  const newURL = getURL(url);
  if (!newURL) {
    return defaultFilename;
  }
  const decode2 = (name) => {
    try {
      let decoded = decodeURIComponent(name);
      if (decoded.includes("/")) {
        decoded = decoded.split("/").at(-1);
        if (decoded.test(/^\.pdf$/i)) {
          return decoded;
        }
        return name;
      }
      return decoded;
    } catch {
      return name;
    }
  };
  const pdfRegex = /\.pdf$/i;
  const filename = newURL.pathname.split("/").at(-1);
  if (pdfRegex.test(filename)) {
    return decode2(filename);
  }
  if (newURL.searchParams.size > 0) {
    const values2 = Array.from(newURL.searchParams.values()).reverse();
    for (const value of values2) {
      if (pdfRegex.test(value)) {
        return decode2(value);
      }
    }
    const keys2 = Array.from(newURL.searchParams.keys()).reverse();
    for (const key of keys2) {
      if (pdfRegex.test(key)) {
        return decode2(key);
      }
    }
  }
  if (newURL.hash) {
    const reFilename = /[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
    const hashFilename = reFilename.exec(newURL.hash);
    if (hashFilename) {
      return decode2(hashFilename[0]);
    }
  }
  return defaultFilename;
}
var StatTimer = class {
  started = /* @__PURE__ */ Object.create(null);
  times = [];
  time(name) {
    if (name in this.started) {
      warn(`Timer is already running for ${name}`);
    }
    this.started[name] = Date.now();
  }
  timeEnd(name) {
    if (!(name in this.started)) {
      warn(`Timer has not been started for ${name}`);
    }
    this.times.push({
      name,
      start: this.started[name],
      end: Date.now()
    });
    delete this.started[name];
  }
  toString() {
    const outBuf = [];
    let longest = 0;
    for (const {
      name
    } of this.times) {
      longest = Math.max(name.length, longest);
    }
    for (const {
      name,
      start,
      end
    } of this.times) {
      outBuf.push(`${name.padEnd(longest)} ${end - start}ms
`);
    }
    return outBuf.join("");
  }
};
function isValidFetchUrl(url, baseUrl) {
  const res = baseUrl ? URL.parse(url, baseUrl) : URL.parse(url);
  return res?.protocol === "http:" || res?.protocol === "https:";
}
function noContextMenu(e9) {
  e9.preventDefault();
}
function stopEvent(e9) {
  e9.preventDefault();
  e9.stopPropagation();
}
function deprecated(details) {
  console.log("Deprecated API usage: " + details);
}
var PDFDateString = class {
  static #regex;
  static toDateObject(input) {
    if (input instanceof Date) {
      return input;
    }
    if (!input || typeof input !== "string") {
      return null;
    }
    this.#regex ||= new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?");
    const matches = this.#regex.exec(input);
    if (!matches) {
      return null;
    }
    const year = parseInt(matches[1], 10);
    let month = parseInt(matches[2], 10);
    month = month >= 1 && month <= 12 ? month - 1 : 0;
    let day = parseInt(matches[3], 10);
    day = day >= 1 && day <= 31 ? day : 1;
    let hour = parseInt(matches[4], 10);
    hour = hour >= 0 && hour <= 23 ? hour : 0;
    let minute = parseInt(matches[5], 10);
    minute = minute >= 0 && minute <= 59 ? minute : 0;
    let second = parseInt(matches[6], 10);
    second = second >= 0 && second <= 59 ? second : 0;
    const universalTimeRelation = matches[7] || "Z";
    let offsetHour = parseInt(matches[8], 10);
    offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0;
    let offsetMinute = parseInt(matches[9], 10) || 0;
    offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0;
    if (universalTimeRelation === "-") {
      hour += offsetHour;
      minute += offsetMinute;
    } else if (universalTimeRelation === "+") {
      hour -= offsetHour;
      minute -= offsetMinute;
    }
    return new Date(Date.UTC(year, month, day, hour, minute, second));
  }
};
function getXfaPageViewport(xfaPage, {
  scale = 1,
  rotation = 0
}) {
  const {
    width,
    height
  } = xfaPage.attributes.style;
  const viewBox = [0, 0, parseInt(width), parseInt(height)];
  return new PageViewport({
    viewBox,
    userUnit: 1,
    scale,
    rotation
  });
}
function getRGB(color) {
  if (color.startsWith("#")) {
    const colorRGB = parseInt(color.slice(1), 16);
    return [(colorRGB & 16711680) >> 16, (colorRGB & 65280) >> 8, colorRGB & 255];
  }
  if (color.startsWith("rgb(")) {
    return color.slice(4, -1).split(",").map((x2) => parseInt(x2));
  }
  if (color.startsWith("rgba(")) {
    return color.slice(5, -1).split(",").map((x2) => parseInt(x2)).slice(0, 3);
  }
  warn(`Not a valid color format: "${color}"`);
  return [0, 0, 0];
}
function getColorValues(colors) {
  const span = document.createElement("span");
  span.style.visibility = "hidden";
  span.style.colorScheme = "only light";
  document.body.append(span);
  for (const name of colors.keys()) {
    span.style.color = name;
    const computedColor = window.getComputedStyle(span).color;
    colors.set(name, getRGB(computedColor));
  }
  span.remove();
}
function getCurrentTransform(ctx) {
  const {
    a: a3,
    b: b4,
    c: c6,
    d: d4,
    e: e9,
    f: f4
  } = ctx.getTransform();
  return [a3, b4, c6, d4, e9, f4];
}
function getCurrentTransformInverse(ctx) {
  const {
    a: a3,
    b: b4,
    c: c6,
    d: d4,
    e: e9,
    f: f4
  } = ctx.getTransform().invertSelf();
  return [a3, b4, c6, d4, e9, f4];
}
function setLayerDimensions(div, viewport, mustFlip = false, mustRotate = true) {
  if (viewport instanceof PageViewport) {
    const {
      pageWidth,
      pageHeight
    } = viewport.rawDims;
    const {
      style
    } = div;
    const useRound = util_FeatureTest.isCSSRoundSupported;
    const w3 = `var(--total-scale-factor) * ${pageWidth}px`, h7 = `var(--total-scale-factor) * ${pageHeight}px`;
    const widthStr = useRound ? `round(down, ${w3}, var(--scale-round-x))` : `calc(${w3})`, heightStr = useRound ? `round(down, ${h7}, var(--scale-round-y))` : `calc(${h7})`;
    if (!mustFlip || viewport.rotation % 180 === 0) {
      style.width = widthStr;
      style.height = heightStr;
    } else {
      style.width = heightStr;
      style.height = widthStr;
    }
  }
  if (mustRotate) {
    div.setAttribute("data-main-rotation", viewport.rotation);
  }
}
var OutputScale = class _OutputScale {
  constructor() {
    const {
      pixelRatio
    } = _OutputScale;
    this.sx = pixelRatio;
    this.sy = pixelRatio;
  }
  get scaled() {
    return this.sx !== 1 || this.sy !== 1;
  }
  get symmetric() {
    return this.sx === this.sy;
  }
  limitCanvas(width, height, maxPixels, maxDim, capAreaFactor = -1) {
    let maxAreaScale = Infinity, maxWidthScale = Infinity, maxHeightScale = Infinity;
    maxPixels = _OutputScale.capPixels(maxPixels, capAreaFactor);
    if (maxPixels > 0) {
      maxAreaScale = Math.sqrt(maxPixels / (width * height));
    }
    if (maxDim !== -1) {
      maxWidthScale = maxDim / width;
      maxHeightScale = maxDim / height;
    }
    const maxScale = Math.min(maxAreaScale, maxWidthScale, maxHeightScale);
    if (this.sx > maxScale || this.sy > maxScale) {
      this.sx = maxScale;
      this.sy = maxScale;
      return true;
    }
    return false;
  }
  static get pixelRatio() {
    return globalThis.devicePixelRatio || 1;
  }
  static capPixels(maxPixels, capAreaFactor) {
    if (capAreaFactor >= 0) {
      const winPixels = Math.ceil(window.screen.availWidth * window.screen.availHeight * this.pixelRatio ** 2 * (1 + capAreaFactor / 100));
      return maxPixels > 0 ? Math.min(maxPixels, winPixels) : winPixels;
    }
    return maxPixels;
  }
};
var SupportedImageMimeTypes = ["image/apng", "image/avif", "image/bmp", "image/gif", "image/jpeg", "image/png", "image/svg+xml", "image/webp", "image/x-icon"];
var ColorScheme = class {
  static get isDarkMode() {
    return shadow(this, "isDarkMode", !!window?.matchMedia?.("(prefers-color-scheme: dark)").matches);
  }
};
var CSSConstants = class {
  static get commentForegroundColor() {
    const element = document.createElement("span");
    element.classList.add("comment", "sidebar");
    const {
      style
    } = element;
    style.width = style.height = "0";
    style.display = "none";
    style.color = "var(--comment-fg-color)";
    document.body.append(element);
    const {
      color
    } = window.getComputedStyle(element);
    element.remove();
    return shadow(this, "commentForegroundColor", getRGB(color));
  }
};
function applyOpacity(r8, g3, b4, opacity) {
  opacity = Math.min(Math.max(opacity ?? 1, 0), 1);
  const white = 255 * (1 - opacity);
  r8 = Math.round(r8 * opacity + white);
  g3 = Math.round(g3 * opacity + white);
  b4 = Math.round(b4 * opacity + white);
  return [r8, g3, b4];
}
function RGBToHSL(rgb, output) {
  const r8 = rgb[0] / 255;
  const g3 = rgb[1] / 255;
  const b4 = rgb[2] / 255;
  const max = Math.max(r8, g3, b4);
  const min = Math.min(r8, g3, b4);
  const l5 = (max + min) / 2;
  if (max === min) {
    output[0] = output[1] = 0;
  } else {
    const d4 = max - min;
    output[1] = l5 < 0.5 ? d4 / (max + min) : d4 / (2 - max - min);
    switch (max) {
      case r8:
        output[0] = ((g3 - b4) / d4 + (g3 < b4 ? 6 : 0)) * 60;
        break;
      case g3:
        output[0] = ((b4 - r8) / d4 + 2) * 60;
        break;
      case b4:
        output[0] = ((r8 - g3) / d4 + 4) * 60;
        break;
    }
  }
  output[2] = l5;
}
function HSLToRGB(hsl, output) {
  const h7 = hsl[0];
  const s6 = hsl[1];
  const l5 = hsl[2];
  const c6 = (1 - Math.abs(2 * l5 - 1)) * s6;
  const x2 = c6 * (1 - Math.abs(h7 / 60 % 2 - 1));
  const m4 = l5 - c6 / 2;
  switch (Math.floor(h7 / 60)) {
    case 0:
      output[0] = c6 + m4;
      output[1] = x2 + m4;
      output[2] = m4;
      break;
    case 1:
      output[0] = x2 + m4;
      output[1] = c6 + m4;
      output[2] = m4;
      break;
    case 2:
      output[0] = m4;
      output[1] = c6 + m4;
      output[2] = x2 + m4;
      break;
    case 3:
      output[0] = m4;
      output[1] = x2 + m4;
      output[2] = c6 + m4;
      break;
    case 4:
      output[0] = x2 + m4;
      output[1] = m4;
      output[2] = c6 + m4;
      break;
    case 5:
    case 6:
      output[0] = c6 + m4;
      output[1] = m4;
      output[2] = x2 + m4;
      break;
  }
}
function computeLuminance(x2) {
  return x2 <= 0.03928 ? x2 / 12.92 : ((x2 + 0.055) / 1.055) ** 2.4;
}
function contrastRatio(hsl1, hsl2, output) {
  HSLToRGB(hsl1, output);
  output.map(computeLuminance);
  const lum1 = 0.2126 * output[0] + 0.7152 * output[1] + 0.0722 * output[2];
  HSLToRGB(hsl2, output);
  output.map(computeLuminance);
  const lum2 = 0.2126 * output[0] + 0.7152 * output[1] + 0.0722 * output[2];
  return lum1 > lum2 ? (lum1 + 0.05) / (lum2 + 0.05) : (lum2 + 0.05) / (lum1 + 0.05);
}
var contrastCache = /* @__PURE__ */ new Map();
function findContrastColor(baseColor, fixedColor) {
  const key = baseColor[0] + baseColor[1] * 256 + baseColor[2] * 65536 + fixedColor[0] * 16777216 + fixedColor[1] * 4294967296 + fixedColor[2] * 1099511627776;
  let cachedValue = contrastCache.get(key);
  if (cachedValue) {
    return cachedValue;
  }
  const array = new Float32Array(9);
  const output = array.subarray(0, 3);
  const baseHSL = array.subarray(3, 6);
  RGBToHSL(baseColor, baseHSL);
  const fixedHSL = array.subarray(6, 9);
  RGBToHSL(fixedColor, fixedHSL);
  const isFixedColorDark = fixedHSL[2] < 0.5;
  const minContrast = isFixedColorDark ? 12 : 4.5;
  baseHSL[2] = isFixedColorDark ? Math.sqrt(baseHSL[2]) : 1 - Math.sqrt(1 - baseHSL[2]);
  if (contrastRatio(baseHSL, fixedHSL, output) < minContrast) {
    let start, end;
    if (isFixedColorDark) {
      start = baseHSL[2];
      end = 1;
    } else {
      start = 0;
      end = baseHSL[2];
    }
    const PRECISION = 5e-3;
    while (end - start > PRECISION) {
      const mid = baseHSL[2] = (start + end) / 2;
      if (isFixedColorDark === contrastRatio(baseHSL, fixedHSL, output) < minContrast) {
        start = mid;
      } else {
        end = mid;
      }
    }
    baseHSL[2] = isFixedColorDark ? end : start;
  }
  HSLToRGB(baseHSL, output);
  cachedValue = Util.makeHexColor(Math.round(output[0] * 255), Math.round(output[1] * 255), Math.round(output[2] * 255));
  contrastCache.set(key, cachedValue);
  return cachedValue;
}
function renderRichText({
  html,
  dir,
  className
}, container) {
  const fragment = document.createDocumentFragment();
  if (typeof html === "string") {
    const p4 = document.createElement("p");
    p4.dir = dir || "auto";
    const lines = html.split(/(?:\r\n?|\n)/);
    for (let i7 = 0, ii = lines.length; i7 < ii; ++i7) {
      const line = lines[i7];
      p4.append(document.createTextNode(line));
      if (i7 < ii - 1) {
        p4.append(document.createElement("br"));
      }
    }
    fragment.append(p4);
  } else {
    XfaLayer.render({
      xfaHtml: html,
      div: fragment,
      intent: "richText"
    });
  }
  fragment.firstChild.classList.add("richText", className);
  container.append(fragment);
}
function makePathFromDrawOPS(data) {
  const path6 = new Path2D();
  if (!data) {
    return path6;
  }
  for (let i7 = 0, ii = data.length; i7 < ii; ) {
    switch (data[i7++]) {
      case DrawOPS.moveTo:
        path6.moveTo(data[i7++], data[i7++]);
        break;
      case DrawOPS.lineTo:
        path6.lineTo(data[i7++], data[i7++]);
        break;
      case DrawOPS.curveTo:
        path6.bezierCurveTo(data[i7++], data[i7++], data[i7++], data[i7++], data[i7++], data[i7++]);
        break;
      case DrawOPS.quadraticCurveTo:
        path6.quadraticCurveTo(data[i7++], data[i7++], data[i7++], data[i7++]);
        break;
      case DrawOPS.closePath:
        path6.closePath();
        break;
      default:
        warn(`Unrecognized drawing path operator: ${data[i7 - 1]}`);
        break;
    }
  }
  return path6;
}
var EditorToolbar = class _EditorToolbar {
  #toolbar = null;
  #colorPicker = null;
  #editor;
  #buttons = null;
  #altText = null;
  #comment = null;
  #commentButtonDivider = null;
  #signatureDescriptionButton = null;
  static #l10nRemove = null;
  constructor(editor) {
    this.#editor = editor;
    _EditorToolbar.#l10nRemove ||= Object.freeze({
      freetext: "pdfjs-editor-remove-freetext-button",
      highlight: "pdfjs-editor-remove-highlight-button",
      ink: "pdfjs-editor-remove-ink-button",
      stamp: "pdfjs-editor-remove-stamp-button",
      signature: "pdfjs-editor-remove-signature-button"
    });
  }
  render() {
    const editToolbar = this.#toolbar = document.createElement("div");
    editToolbar.classList.add("editToolbar", "hidden");
    editToolbar.setAttribute("role", "toolbar");
    const signal = this.#editor._uiManager._signal;
    if (signal instanceof AbortSignal && !signal.aborted) {
      editToolbar.addEventListener("contextmenu", noContextMenu, {
        signal
      });
      editToolbar.addEventListener("pointerdown", _EditorToolbar.#pointerDown, {
        signal
      });
    }
    const buttons = this.#buttons = document.createElement("div");
    buttons.className = "buttons";
    editToolbar.append(buttons);
    const position = this.#editor.toolbarPosition;
    if (position) {
      const {
        style
      } = editToolbar;
      const x2 = this.#editor._uiManager.direction === "ltr" ? 1 - position[0] : position[0];
      style.insetInlineEnd = `${100 * x2}%`;
      style.top = `calc(${100 * position[1]}% + var(--editor-toolbar-vert-offset))`;
    }
    return editToolbar;
  }
  get div() {
    return this.#toolbar;
  }
  static #pointerDown(e9) {
    e9.stopPropagation();
  }
  #focusIn(e9) {
    this.#editor._focusEventsAllowed = false;
    stopEvent(e9);
  }
  #focusOut(e9) {
    this.#editor._focusEventsAllowed = true;
    stopEvent(e9);
  }
  #addListenersToElement(element) {
    const signal = this.#editor._uiManager._signal;
    if (!(signal instanceof AbortSignal) || signal.aborted) {
      return false;
    }
    element.addEventListener("focusin", this.#focusIn.bind(this), {
      capture: true,
      signal
    });
    element.addEventListener("focusout", this.#focusOut.bind(this), {
      capture: true,
      signal
    });
    element.addEventListener("contextmenu", noContextMenu, {
      signal
    });
    return true;
  }
  hide() {
    this.#toolbar.classList.add("hidden");
    this.#colorPicker?.hideDropdown();
  }
  show() {
    this.#toolbar.classList.remove("hidden");
    this.#altText?.shown();
    this.#comment?.shown();
  }
  addDeleteButton() {
    const {
      editorType,
      _uiManager
    } = this.#editor;
    const button = document.createElement("button");
    button.classList.add("basic", "deleteButton");
    button.tabIndex = 0;
    button.setAttribute("data-l10n-id", _EditorToolbar.#l10nRemove[editorType]);
    if (this.#addListenersToElement(button)) {
      button.addEventListener("click", (e9) => {
        _uiManager.delete();
      }, {
        signal: _uiManager._signal
      });
    }
    this.#buttons.append(button);
  }
  get #divider() {
    const divider = document.createElement("div");
    divider.className = "divider";
    return divider;
  }
  async addAltText(altText) {
    const button = await altText.render();
    this.#addListenersToElement(button);
    this.#buttons.append(button, this.#divider);
    this.#altText = altText;
  }
  addComment(comment, beforeElement = null) {
    if (this.#comment) {
      return;
    }
    const button = comment.renderForToolbar();
    if (!button) {
      return;
    }
    this.#addListenersToElement(button);
    const divider = this.#commentButtonDivider = this.#divider;
    if (!beforeElement) {
      this.#buttons.append(button, divider);
    } else {
      this.#buttons.insertBefore(button, beforeElement);
      this.#buttons.insertBefore(divider, beforeElement);
    }
    this.#comment = comment;
    comment.toolbar = this;
  }
  addColorPicker(colorPicker) {
    if (this.#colorPicker) {
      return;
    }
    this.#colorPicker = colorPicker;
    const button = colorPicker.renderButton();
    this.#addListenersToElement(button);
    this.#buttons.append(button, this.#divider);
  }
  async addEditSignatureButton(signatureManager) {
    const button = this.#signatureDescriptionButton = await signatureManager.renderEditButton(this.#editor);
    this.#addListenersToElement(button);
    this.#buttons.append(button, this.#divider);
  }
  removeButton(name) {
    switch (name) {
      case "comment":
        this.#comment?.removeToolbarCommentButton();
        this.#comment = null;
        this.#commentButtonDivider?.remove();
        this.#commentButtonDivider = null;
        break;
    }
  }
  async addButton(name, tool) {
    switch (name) {
      case "colorPicker":
        if (tool) {
          this.addColorPicker(tool);
        }
        break;
      case "altText":
        if (tool) {
          await this.addAltText(tool);
        }
        break;
      case "editSignature":
        if (tool) {
          await this.addEditSignatureButton(tool);
        }
        break;
      case "delete":
        this.addDeleteButton();
        break;
      case "comment":
        if (tool) {
          this.addComment(tool);
        }
        break;
    }
  }
  async addButtonBefore(name, tool, beforeSelector) {
    if (!tool && name === "comment") {
      return;
    }
    const beforeElement = this.#buttons.querySelector(beforeSelector);
    if (!beforeElement) {
      return;
    }
    if (name === "comment") {
      this.addComment(tool, beforeElement);
    }
  }
  updateEditSignatureButton(description) {
    if (this.#signatureDescriptionButton) {
      this.#signatureDescriptionButton.title = description;
    }
  }
  remove() {
    this.#toolbar.remove();
    this.#colorPicker?.destroy();
    this.#colorPicker = null;
  }
};
var FloatingToolbar = class {
  #buttons = null;
  #toolbar = null;
  #uiManager;
  constructor(uiManager) {
    this.#uiManager = uiManager;
  }
  #render() {
    const editToolbar = this.#toolbar = document.createElement("div");
    editToolbar.className = "editToolbar";
    editToolbar.setAttribute("role", "toolbar");
    const signal = this.#uiManager._signal;
    if (signal instanceof AbortSignal && !signal.aborted) {
      editToolbar.addEventListener("contextmenu", noContextMenu, {
        signal
      });
    }
    const buttons = this.#buttons = document.createElement("div");
    buttons.className = "buttons";
    editToolbar.append(buttons);
    if (this.#uiManager.hasCommentManager()) {
      this.#makeButton("commentButton", `pdfjs-comment-floating-button`, "pdfjs-comment-floating-button-label", () => {
        this.#uiManager.commentSelection("floating_button");
      });
    }
    this.#makeButton("highlightButton", `pdfjs-highlight-floating-button1`, "pdfjs-highlight-floating-button-label", () => {
      this.#uiManager.highlightSelection("floating_button");
    });
    return editToolbar;
  }
  #getLastPoint(boxes, isLTR) {
    let lastY = 0;
    let lastX = 0;
    for (const box of boxes) {
      const y4 = box.y + box.height;
      if (y4 < lastY) {
        continue;
      }
      const x2 = box.x + (isLTR ? box.width : 0);
      if (y4 > lastY) {
        lastX = x2;
        lastY = y4;
        continue;
      }
      if (isLTR) {
        if (x2 > lastX) {
          lastX = x2;
        }
      } else if (x2 < lastX) {
        lastX = x2;
      }
    }
    return [isLTR ? 1 - lastX : lastX, lastY];
  }
  show(parent, boxes, isLTR) {
    const [x2, y4] = this.#getLastPoint(boxes, isLTR);
    const {
      style
    } = this.#toolbar ||= this.#render();
    parent.append(this.#toolbar);
    style.insetInlineEnd = `${100 * x2}%`;
    style.top = `calc(${100 * y4}% + var(--editor-toolbar-vert-offset))`;
  }
  hide() {
    this.#toolbar.remove();
  }
  #makeButton(buttonClass, l10nId, labelL10nId, clickHandler) {
    const button = document.createElement("button");
    button.classList.add("basic", buttonClass);
    button.tabIndex = 0;
    button.setAttribute("data-l10n-id", l10nId);
    const span = document.createElement("span");
    button.append(span);
    span.className = "visuallyHidden";
    span.setAttribute("data-l10n-id", labelL10nId);
    const signal = this.#uiManager._signal;
    if (signal instanceof AbortSignal && !signal.aborted) {
      button.addEventListener("contextmenu", noContextMenu, {
        signal
      });
      button.addEventListener("click", clickHandler, {
        signal
      });
    }
    this.#buttons.append(button);
  }
};
function bindEvents(obj, element, names) {
  for (const name of names) {
    element.addEventListener(name, obj[name].bind(obj));
  }
}
var CurrentPointers = class _CurrentPointers {
  static #pointerId = NaN;
  static #pointerIds = null;
  static #moveTimestamp = NaN;
  static #pointerType = null;
  static initializeAndAddPointerId(pointerId) {
    (_CurrentPointers.#pointerIds ||= /* @__PURE__ */ new Set()).add(pointerId);
  }
  static setPointer(pointerType, pointerId) {
    _CurrentPointers.#pointerId ||= pointerId;
    _CurrentPointers.#pointerType ??= pointerType;
  }
  static setTimeStamp(timeStamp) {
    _CurrentPointers.#moveTimestamp = timeStamp;
  }
  static isSamePointerId(pointerId) {
    return _CurrentPointers.#pointerId === pointerId;
  }
  static isSamePointerIdOrRemove(pointerId) {
    if (_CurrentPointers.#pointerId === pointerId) {
      return true;
    }
    _CurrentPointers.#pointerIds?.delete(pointerId);
    return false;
  }
  static isSamePointerType(pointerType) {
    return _CurrentPointers.#pointerType === pointerType;
  }
  static isInitializedAndDifferentPointerType(pointerType) {
    return _CurrentPointers.#pointerType !== null && !_CurrentPointers.isSamePointerType(pointerType);
  }
  static isSameTimeStamp(timeStamp) {
    return _CurrentPointers.#moveTimestamp === timeStamp;
  }
  static isUsingMultiplePointers() {
    return _CurrentPointers.#pointerIds?.size >= 1;
  }
  static clearPointerType() {
    _CurrentPointers.#pointerType = null;
  }
  static clearPointerIds() {
    _CurrentPointers.#pointerId = NaN;
    _CurrentPointers.#pointerIds = null;
  }
  static clearTimeStamp() {
    _CurrentPointers.#moveTimestamp = NaN;
  }
};
var IdManager = class {
  #id = 0;
  get id() {
    return `${AnnotationEditorPrefix}${this.#id++}`;
  }
};
var ImageManager = class _ImageManager {
  #baseId = getUuid();
  #id = 0;
  #cache = null;
  static get _isSVGFittingCanvas() {
    const svg = `data:image/svg+xml;charset=UTF-8,<svg viewBox="0 0 1 1" width="1" height="1" xmlns="http://www.w3.org/2000/svg"><rect width="1" height="1" style="fill:red;"/></svg>`;
    const canvas = new OffscreenCanvas(1, 3);
    const ctx = canvas.getContext("2d", {
      willReadFrequently: true
    });
    const image = new Image();
    image.src = svg;
    const promise = image.decode().then(() => {
      ctx.drawImage(image, 0, 0, 1, 1, 0, 0, 1, 3);
      return new Uint32Array(ctx.getImageData(0, 0, 1, 1).data.buffer)[0] === 0;
    });
    return shadow(this, "_isSVGFittingCanvas", promise);
  }
  async #get(key, rawData) {
    this.#cache ||= /* @__PURE__ */ new Map();
    let data = this.#cache.get(key);
    if (data === null) {
      return null;
    }
    if (data?.bitmap) {
      data.refCounter += 1;
      return data;
    }
    try {
      data ||= {
        bitmap: null,
        id: `image_${this.#baseId}_${this.#id++}`,
        refCounter: 0,
        isSvg: false
      };
      let image;
      if (typeof rawData === "string") {
        data.url = rawData;
        image = await fetchData(rawData, "blob");
      } else if (rawData instanceof File) {
        image = data.file = rawData;
      } else if (rawData instanceof Blob) {
        image = rawData;
      }
      if (image.type === "image/svg+xml") {
        const mustRemoveAspectRatioPromise = _ImageManager._isSVGFittingCanvas;
        const fileReader = new FileReader();
        const imageElement = new Image();
        const imagePromise = new Promise((resolve, reject) => {
          imageElement.onload = () => {
            data.bitmap = imageElement;
            data.isSvg = true;
            resolve();
          };
          fileReader.onload = async () => {
            const url = data.svgUrl = fileReader.result;
            imageElement.src = await mustRemoveAspectRatioPromise ? `${url}#svgView(preserveAspectRatio(none))` : url;
          };
          imageElement.onerror = fileReader.onerror = reject;
        });
        fileReader.readAsDataURL(image);
        await imagePromise;
      } else {
        data.bitmap = await createImageBitmap(image);
      }
      data.refCounter = 1;
    } catch (e9) {
      warn(e9);
      data = null;
    }
    this.#cache.set(key, data);
    if (data) {
      this.#cache.set(data.id, data);
    }
    return data;
  }
  async getFromFile(file) {
    const {
      lastModified,
      name,
      size,
      type
    } = file;
    return this.#get(`${lastModified}_${name}_${size}_${type}`, file);
  }
  async getFromUrl(url) {
    return this.#get(url, url);
  }
  async getFromBlob(id, blobPromise) {
    const blob = await blobPromise;
    return this.#get(id, blob);
  }
  async getFromId(id) {
    this.#cache ||= /* @__PURE__ */ new Map();
    const data = this.#cache.get(id);
    if (!data) {
      return null;
    }
    if (data.bitmap) {
      data.refCounter += 1;
      return data;
    }
    if (data.file) {
      return this.getFromFile(data.file);
    }
    if (data.blobPromise) {
      const {
        blobPromise
      } = data;
      delete data.blobPromise;
      return this.getFromBlob(data.id, blobPromise);
    }
    return this.getFromUrl(data.url);
  }
  getFromCanvas(id, canvas) {
    this.#cache ||= /* @__PURE__ */ new Map();
    let data = this.#cache.get(id);
    if (data?.bitmap) {
      data.refCounter += 1;
      return data;
    }
    const offscreen = new OffscreenCanvas(canvas.width, canvas.height);
    const ctx = offscreen.getContext("2d");
    ctx.drawImage(canvas, 0, 0);
    data = {
      bitmap: offscreen.transferToImageBitmap(),
      id: `image_${this.#baseId}_${this.#id++}`,
      refCounter: 1,
      isSvg: false
    };
    this.#cache.set(id, data);
    this.#cache.set(data.id, data);
    return data;
  }
  getSvgUrl(id) {
    const data = this.#cache.get(id);
    if (!data?.isSvg) {
      return null;
    }
    return data.svgUrl;
  }
  deleteId(id) {
    this.#cache ||= /* @__PURE__ */ new Map();
    const data = this.#cache.get(id);
    if (!data) {
      return;
    }
    data.refCounter -= 1;
    if (data.refCounter !== 0) {
      return;
    }
    const {
      bitmap
    } = data;
    if (!data.url && !data.file) {
      const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
      const ctx = canvas.getContext("bitmaprenderer");
      ctx.transferFromImageBitmap(bitmap);
      data.blobPromise = canvas.convertToBlob();
    }
    bitmap.close?.();
    data.bitmap = null;
  }
  isValidId(id) {
    return id.startsWith(`image_${this.#baseId}_`);
  }
};
var CommandManager = class {
  #commands = [];
  #locked = false;
  #maxSize;
  #position = -1;
  constructor(maxSize = 128) {
    this.#maxSize = maxSize;
  }
  add({
    cmd,
    undo,
    post: post2,
    mustExec,
    type = NaN,
    overwriteIfSameType = false,
    keepUndo = false
  }) {
    if (mustExec) {
      cmd();
    }
    if (this.#locked) {
      return;
    }
    const save = {
      cmd,
      undo,
      post: post2,
      type
    };
    if (this.#position === -1) {
      if (this.#commands.length > 0) {
        this.#commands.length = 0;
      }
      this.#position = 0;
      this.#commands.push(save);
      return;
    }
    if (overwriteIfSameType && this.#commands[this.#position].type === type) {
      if (keepUndo) {
        save.undo = this.#commands[this.#position].undo;
      }
      this.#commands[this.#position] = save;
      return;
    }
    const next = this.#position + 1;
    if (next === this.#maxSize) {
      this.#commands.splice(0, 1);
    } else {
      this.#position = next;
      if (next < this.#commands.length) {
        this.#commands.splice(next);
      }
    }
    this.#commands.push(save);
  }
  undo() {
    if (this.#position === -1) {
      return;
    }
    this.#locked = true;
    const {
      undo,
      post: post2
    } = this.#commands[this.#position];
    undo();
    post2?.();
    this.#locked = false;
    this.#position -= 1;
  }
  redo() {
    if (this.#position < this.#commands.length - 1) {
      this.#position += 1;
      this.#locked = true;
      const {
        cmd,
        post: post2
      } = this.#commands[this.#position];
      cmd();
      post2?.();
      this.#locked = false;
    }
  }
  hasSomethingToUndo() {
    return this.#position !== -1;
  }
  hasSomethingToRedo() {
    return this.#position < this.#commands.length - 1;
  }
  cleanType(type) {
    if (this.#position === -1) {
      return;
    }
    for (let i7 = this.#position; i7 >= 0; i7--) {
      if (this.#commands[i7].type !== type) {
        this.#commands.splice(i7 + 1, this.#position - i7);
        this.#position = i7;
        return;
      }
    }
    this.#commands.length = 0;
    this.#position = -1;
  }
  destroy() {
    this.#commands = null;
  }
};
var KeyboardManager = class {
  constructor(callbacks) {
    this.buffer = [];
    this.callbacks = /* @__PURE__ */ new Map();
    this.allKeys = /* @__PURE__ */ new Set();
    const {
      isMac
    } = util_FeatureTest.platform;
    for (const [keys2, callback, options = {}] of callbacks) {
      for (const key of keys2) {
        const isMacKey = key.startsWith("mac+");
        if (isMac && isMacKey) {
          this.callbacks.set(key.slice(4), {
            callback,
            options
          });
          this.allKeys.add(key.split("+").at(-1));
        } else if (!isMac && !isMacKey) {
          this.callbacks.set(key, {
            callback,
            options
          });
          this.allKeys.add(key.split("+").at(-1));
        }
      }
    }
  }
  #serialize(event) {
    if (event.altKey) {
      this.buffer.push("alt");
    }
    if (event.ctrlKey) {
      this.buffer.push("ctrl");
    }
    if (event.metaKey) {
      this.buffer.push("meta");
    }
    if (event.shiftKey) {
      this.buffer.push("shift");
    }
    this.buffer.push(event.key);
    const str2 = this.buffer.join("+");
    this.buffer.length = 0;
    return str2;
  }
  exec(self2, event) {
    if (!this.allKeys.has(event.key)) {
      return;
    }
    const info2 = this.callbacks.get(this.#serialize(event));
    if (!info2) {
      return;
    }
    const {
      callback,
      options: {
        bubbles = false,
        args = [],
        checker = null
      }
    } = info2;
    if (checker && !checker(self2, event)) {
      return;
    }
    callback.bind(self2, ...args, event)();
    if (!bubbles) {
      stopEvent(event);
    }
  }
};
var ColorManager = class _ColorManager {
  static _colorsMapping = /* @__PURE__ */ new Map([["CanvasText", [0, 0, 0]], ["Canvas", [255, 255, 255]]]);
  get _colors() {
    const colors = /* @__PURE__ */ new Map([["CanvasText", null], ["Canvas", null]]);
    getColorValues(colors);
    return shadow(this, "_colors", colors);
  }
  convert(color) {
    const rgb = getRGB(color);
    if (!window.matchMedia("(forced-colors: active)").matches) {
      return rgb;
    }
    for (const [name, RGB] of this._colors) {
      if (RGB.every((x2, i7) => x2 === rgb[i7])) {
        return _ColorManager._colorsMapping.get(name);
      }
    }
    return rgb;
  }
  getHexCode(name) {
    const rgb = this._colors.get(name);
    if (!rgb) {
      return name;
    }
    return Util.makeHexColor(...rgb);
  }
};
var AnnotationEditorUIManager = class _AnnotationEditorUIManager {
  #abortController = new AbortController();
  #activeEditor = null;
  #allEditableAnnotations = null;
  #allEditors = /* @__PURE__ */ new Map();
  #allLayers = /* @__PURE__ */ new Map();
  #altTextManager = null;
  #annotationStorage = null;
  #changedExistingAnnotations = null;
  #commandManager = new CommandManager();
  #commentManager = null;
  #copyPasteAC = null;
  #currentDrawingSession = null;
  #currentPageIndex = 0;
  #deletedAnnotationsElementIds = /* @__PURE__ */ new Set();
  #draggingEditors = null;
  #editorTypes = null;
  #editorsToRescale = /* @__PURE__ */ new Set();
  _editorUndoBar = null;
  #enableHighlightFloatingButton = false;
  #enableUpdatedAddImage = false;
  #enableNewAltTextWhenAddingImage = false;
  #filterFactory = null;
  #focusMainContainerTimeoutId = null;
  #focusManagerAC = null;
  #highlightColors = null;
  #highlightWhenShiftUp = false;
  #floatingToolbar = null;
  #idManager = new IdManager();
  #isEnabled = false;
  #isPointerDown = false;
  #isWaiting = false;
  #keyboardManagerAC = null;
  #lastActiveElement = null;
  #mainHighlightColorPicker = null;
  #missingCanvases = null;
  #mlManager = null;
  #mode = AnnotationEditorType.NONE;
  #selectedEditors = /* @__PURE__ */ new Set();
  #selectedTextNode = null;
  #signatureManager = null;
  #pageColors = null;
  #showAllStates = null;
  #pdfDocument = null;
  #previousStates = {
    isEditing: false,
    isEmpty: true,
    hasSomethingToUndo: false,
    hasSomethingToRedo: false,
    hasSelectedEditor: false,
    hasSelectedText: false
  };
  #translation = [0, 0];
  #translationTimeoutId = null;
  #container = null;
  #viewer = null;
  #viewerAlert = null;
  #updateModeCapability = null;
  static TRANSLATE_SMALL = 1;
  static TRANSLATE_BIG = 10;
  static get _keyboardManager() {
    const proto = _AnnotationEditorUIManager.prototype;
    const arrowChecker = (self2) => self2.#container.contains(document.activeElement) && document.activeElement.tagName !== "BUTTON" && self2.hasSomethingToControl();
    const textInputChecker = (_self, {
      target: el
    }) => {
      if (el instanceof HTMLInputElement) {
        const {
          type
        } = el;
        return type !== "text" && type !== "number";
      }
      return true;
    };
    const small = this.TRANSLATE_SMALL;
    const big = this.TRANSLATE_BIG;
    return shadow(this, "_keyboardManager", new KeyboardManager([[["ctrl+a", "mac+meta+a"], proto.selectAll, {
      checker: textInputChecker
    }], [["ctrl+z", "mac+meta+z"], proto.undo, {
      checker: textInputChecker
    }], [["ctrl+y", "ctrl+shift+z", "mac+meta+shift+z", "ctrl+shift+Z", "mac+meta+shift+Z"], proto.redo, {
      checker: textInputChecker
    }], [["Backspace", "alt+Backspace", "ctrl+Backspace", "shift+Backspace", "mac+Backspace", "mac+alt+Backspace", "mac+ctrl+Backspace", "Delete", "ctrl+Delete", "shift+Delete", "mac+Delete"], proto.delete, {
      checker: textInputChecker
    }], [["Enter", "mac+Enter"], proto.addNewEditorFromKeyboard, {
      checker: (self2, {
        target: el
      }) => !(el instanceof HTMLButtonElement) && self2.#container.contains(el) && !self2.isEnterHandled
    }], [[" ", "mac+ "], proto.addNewEditorFromKeyboard, {
      checker: (self2, {
        target: el
      }) => !(el instanceof HTMLButtonElement) && self2.#container.contains(document.activeElement)
    }], [["Escape", "mac+Escape"], proto.unselectAll], [["ArrowLeft", "mac+ArrowLeft"], proto.translateSelectedEditors, {
      args: [-small, 0],
      checker: arrowChecker
    }], [["ctrl+ArrowLeft", "mac+shift+ArrowLeft"], proto.translateSelectedEditors, {
      args: [-big, 0],
      checker: arrowChecker
    }], [["ArrowRight", "mac+ArrowRight"], proto.translateSelectedEditors, {
      args: [small, 0],
      checker: arrowChecker
    }], [["ctrl+ArrowRight", "mac+shift+ArrowRight"], proto.translateSelectedEditors, {
      args: [big, 0],
      checker: arrowChecker
    }], [["ArrowUp", "mac+ArrowUp"], proto.translateSelectedEditors, {
      args: [0, -small],
      checker: arrowChecker
    }], [["ctrl+ArrowUp", "mac+shift+ArrowUp"], proto.translateSelectedEditors, {
      args: [0, -big],
      checker: arrowChecker
    }], [["ArrowDown", "mac+ArrowDown"], proto.translateSelectedEditors, {
      args: [0, small],
      checker: arrowChecker
    }], [["ctrl+ArrowDown", "mac+shift+ArrowDown"], proto.translateSelectedEditors, {
      args: [0, big],
      checker: arrowChecker
    }]]));
  }
  constructor(container, viewer, viewerAlert, altTextManager, commentManager, signatureManager, eventBus, pdfDocument, pageColors, highlightColors, enableHighlightFloatingButton, enableUpdatedAddImage, enableNewAltTextWhenAddingImage, mlManager, editorUndoBar, supportsPinchToZoom) {
    const signal = this._signal = this.#abortController.signal;
    this.#container = container;
    this.#viewer = viewer;
    this.#viewerAlert = viewerAlert;
    this.#altTextManager = altTextManager;
    this.#commentManager = commentManager;
    this.#signatureManager = signatureManager;
    this.#pdfDocument = pdfDocument;
    this._eventBus = eventBus;
    eventBus._on("editingaction", this.onEditingAction.bind(this), {
      signal
    });
    eventBus._on("pagechanging", this.onPageChanging.bind(this), {
      signal
    });
    eventBus._on("scalechanging", this.onScaleChanging.bind(this), {
      signal
    });
    eventBus._on("rotationchanging", this.onRotationChanging.bind(this), {
      signal
    });
    eventBus._on("setpreference", this.onSetPreference.bind(this), {
      signal
    });
    eventBus._on("switchannotationeditorparams", (evt) => this.updateParams(evt.type, evt.value), {
      signal
    });
    window.addEventListener("pointerdown", () => {
      this.#isPointerDown = true;
    }, {
      capture: true,
      signal
    });
    window.addEventListener("pointerup", () => {
      this.#isPointerDown = false;
    }, {
      capture: true,
      signal
    });
    this.#addSelectionListener();
    this.#addDragAndDropListeners();
    this.#addKeyboardManager();
    this.#annotationStorage = pdfDocument.annotationStorage;
    this.#filterFactory = pdfDocument.filterFactory;
    this.#pageColors = pageColors;
    this.#highlightColors = highlightColors || null;
    this.#enableHighlightFloatingButton = enableHighlightFloatingButton;
    this.#enableUpdatedAddImage = enableUpdatedAddImage;
    this.#enableNewAltTextWhenAddingImage = enableNewAltTextWhenAddingImage;
    this.#mlManager = mlManager || null;
    this.viewParameters = {
      realScale: PixelsPerInch.PDF_TO_CSS_UNITS,
      rotation: 0
    };
    this.isShiftKeyDown = false;
    this._editorUndoBar = editorUndoBar || null;
    this._supportsPinchToZoom = supportsPinchToZoom !== false;
    commentManager?.setSidebarUiManager(this);
  }
  destroy() {
    this.#updateModeCapability?.resolve();
    this.#updateModeCapability = null;
    this.#abortController?.abort();
    this.#abortController = null;
    this._signal = null;
    for (const layer of this.#allLayers.values()) {
      layer.destroy();
    }
    this.#allLayers.clear();
    this.#allEditors.clear();
    this.#editorsToRescale.clear();
    this.#missingCanvases?.clear();
    this.#activeEditor = null;
    this.#selectedEditors.clear();
    this.#commandManager.destroy();
    this.#altTextManager?.destroy();
    this.#commentManager?.destroy();
    this.#signatureManager?.destroy();
    this.#floatingToolbar?.hide();
    this.#floatingToolbar = null;
    this.#mainHighlightColorPicker?.destroy();
    this.#mainHighlightColorPicker = null;
    this.#allEditableAnnotations = null;
    if (this.#focusMainContainerTimeoutId) {
      clearTimeout(this.#focusMainContainerTimeoutId);
      this.#focusMainContainerTimeoutId = null;
    }
    if (this.#translationTimeoutId) {
      clearTimeout(this.#translationTimeoutId);
      this.#translationTimeoutId = null;
    }
    this._editorUndoBar?.destroy();
    this.#pdfDocument = null;
  }
  combinedSignal(ac) {
    return AbortSignal.any([this._signal, ac.signal]);
  }
  get mlManager() {
    return this.#mlManager;
  }
  get useNewAltTextFlow() {
    return this.#enableUpdatedAddImage;
  }
  get useNewAltTextWhenAddingImage() {
    return this.#enableNewAltTextWhenAddingImage;
  }
  get hcmFilter() {
    return shadow(this, "hcmFilter", this.#pageColors ? this.#filterFactory.addHCMFilter(this.#pageColors.foreground, this.#pageColors.background) : "none");
  }
  get direction() {
    return shadow(this, "direction", getComputedStyle(this.#container).direction);
  }
  get _highlightColors() {
    return shadow(this, "_highlightColors", this.#highlightColors ? new Map(this.#highlightColors.split(",").map((pair) => {
      pair = pair.split("=").map((x2) => x2.trim());
      pair[1] = pair[1].toUpperCase();
      return pair;
    })) : null);
  }
  get highlightColors() {
    const {
      _highlightColors
    } = this;
    if (!_highlightColors) {
      return shadow(this, "highlightColors", null);
    }
    const map = /* @__PURE__ */ new Map();
    const hasHCM = !!this.#pageColors;
    for (const [name, color] of _highlightColors) {
      const isNameForHCM = name.endsWith("_HCM");
      if (hasHCM && isNameForHCM) {
        map.set(name.replace("_HCM", ""), color);
        continue;
      }
      if (!hasHCM && !isNameForHCM) {
        map.set(name, color);
      }
    }
    return shadow(this, "highlightColors", map);
  }
  get highlightColorNames() {
    return shadow(this, "highlightColorNames", this.highlightColors ? new Map(Array.from(this.highlightColors, (e9) => e9.reverse())) : null);
  }
  getNonHCMColor(color) {
    if (!this._highlightColors) {
      return color;
    }
    const colorName2 = this.highlightColorNames.get(color);
    return this._highlightColors.get(colorName2) || color;
  }
  getNonHCMColorName(color) {
    return this.highlightColorNames.get(color) || color;
  }
  setCurrentDrawingSession(layer) {
    if (layer) {
      this.unselectAll();
      this.disableUserSelect(true);
    } else {
      this.disableUserSelect(false);
    }
    this.#currentDrawingSession = layer;
  }
  setMainHighlightColorPicker(colorPicker) {
    this.#mainHighlightColorPicker = colorPicker;
  }
  editAltText(editor, firstTime = false) {
    this.#altTextManager?.editAltText(this, editor, firstTime);
  }
  hasCommentManager() {
    return !!this.#commentManager;
  }
  editComment(editor, posX, posY, options) {
    this.#commentManager?.showDialog(this, editor, posX, posY, options);
  }
  selectComment(pageIndex, uid) {
    const layer = this.#allLayers.get(pageIndex);
    const editor = layer?.getEditorByUID(uid);
    editor?.toggleComment(true, true);
  }
  updateComment(editor) {
    this.#commentManager?.updateComment(editor.getData());
  }
  updatePopupColor(editor) {
    this.#commentManager?.updatePopupColor(editor);
  }
  removeComment(editor) {
    this.#commentManager?.removeComments([editor.uid]);
  }
  toggleComment(editor, isSelected, visibility = void 0) {
    this.#commentManager?.toggleCommentPopup(editor, isSelected, visibility);
  }
  makeCommentColor(color, opacity) {
    return color && this.#commentManager?.makeCommentColor(color, opacity) || null;
  }
  getCommentDialogElement() {
    return this.#commentManager?.dialogElement || null;
  }
  async waitForEditorsRendered(pageNumber) {
    if (this.#allLayers.has(pageNumber - 1)) {
      return;
    }
    const {
      resolve,
      promise
    } = Promise.withResolvers();
    const onEditorsRendered = (evt) => {
      if (evt.pageNumber === pageNumber) {
        this._eventBus._off("editorsrendered", onEditorsRendered);
        resolve();
      }
    };
    this._eventBus.on("editorsrendered", onEditorsRendered);
    await promise;
  }
  getSignature(editor) {
    this.#signatureManager?.getSignature({
      uiManager: this,
      editor
    });
  }
  get signatureManager() {
    return this.#signatureManager;
  }
  switchToMode(mode, callback) {
    this._eventBus.on("annotationeditormodechanged", callback, {
      once: true,
      signal: this._signal
    });
    this._eventBus.dispatch("showannotationeditorui", {
      source: this,
      mode
    });
  }
  setPreference(name, value) {
    this._eventBus.dispatch("setpreference", {
      source: this,
      name,
      value
    });
  }
  onSetPreference({
    name,
    value
  }) {
    switch (name) {
      case "enableNewAltTextWhenAddingImage":
        this.#enableNewAltTextWhenAddingImage = value;
        break;
    }
  }
  onPageChanging({
    pageNumber
  }) {
    this.#currentPageIndex = pageNumber - 1;
  }
  focusMainContainer() {
    this.#container.focus();
  }
  findParent(x2, y4) {
    for (const layer of this.#allLayers.values()) {
      const {
        x: layerX,
        y: layerY,
        width,
        height
      } = layer.div.getBoundingClientRect();
      if (x2 >= layerX && x2 <= layerX + width && y4 >= layerY && y4 <= layerY + height) {
        return layer;
      }
    }
    return null;
  }
  disableUserSelect(value = false) {
    this.#viewer.classList.toggle("noUserSelect", value);
  }
  addShouldRescale(editor) {
    this.#editorsToRescale.add(editor);
  }
  removeShouldRescale(editor) {
    this.#editorsToRescale.delete(editor);
  }
  onScaleChanging({
    scale
  }) {
    this.commitOrRemove();
    this.viewParameters.realScale = scale * PixelsPerInch.PDF_TO_CSS_UNITS;
    for (const editor of this.#editorsToRescale) {
      editor.onScaleChanging();
    }
    this.#currentDrawingSession?.onScaleChanging();
  }
  onRotationChanging({
    pagesRotation
  }) {
    this.commitOrRemove();
    this.viewParameters.rotation = pagesRotation;
  }
  #getAnchorElementForSelection({
    anchorNode
  }) {
    return anchorNode.nodeType === Node.TEXT_NODE ? anchorNode.parentElement : anchorNode;
  }
  #getLayerForTextLayer(textLayer) {
    const {
      currentLayer
    } = this;
    if (currentLayer.hasTextLayer(textLayer)) {
      return currentLayer;
    }
    for (const layer of this.#allLayers.values()) {
      if (layer.hasTextLayer(textLayer)) {
        return layer;
      }
    }
    return null;
  }
  highlightSelection(methodOfCreation = "", comment = false) {
    const selection = document.getSelection();
    if (!selection || selection.isCollapsed) {
      return;
    }
    const {
      anchorNode,
      anchorOffset,
      focusNode,
      focusOffset
    } = selection;
    const text3 = selection.toString();
    const anchorElement = this.#getAnchorElementForSelection(selection);
    const textLayer = anchorElement.closest(".textLayer");
    const boxes = this.getSelectionBoxes(textLayer);
    if (!boxes) {
      return;
    }
    selection.empty();
    const layer = this.#getLayerForTextLayer(textLayer);
    const isNoneMode = this.#mode === AnnotationEditorType.NONE;
    const callback = () => {
      const editor = layer?.createAndAddNewEditor({
        x: 0,
        y: 0
      }, false, {
        methodOfCreation,
        boxes,
        anchorNode,
        anchorOffset,
        focusNode,
        focusOffset,
        text: text3
      });
      if (isNoneMode) {
        this.showAllEditors("highlight", true, true);
      }
      if (comment) {
        editor?.editComment();
      }
    };
    if (isNoneMode) {
      this.switchToMode(AnnotationEditorType.HIGHLIGHT, callback);
      return;
    }
    callback();
  }
  commentSelection(methodOfCreation = "") {
    this.highlightSelection(methodOfCreation, true);
  }
  #displayFloatingToolbar() {
    const selection = document.getSelection();
    if (!selection || selection.isCollapsed) {
      return;
    }
    const anchorElement = this.#getAnchorElementForSelection(selection);
    const textLayer = anchorElement.closest(".textLayer");
    const boxes = this.getSelectionBoxes(textLayer);
    if (!boxes) {
      return;
    }
    this.#floatingToolbar ||= new FloatingToolbar(this);
    this.#floatingToolbar.show(textLayer, boxes, this.direction === "ltr");
  }
  getAndRemoveDataFromAnnotationStorage(annotationId) {
    if (!this.#annotationStorage) {
      return null;
    }
    const key = `${AnnotationEditorPrefix}${annotationId}`;
    const storedValue = this.#annotationStorage.getRawValue(key);
    if (storedValue) {
      this.#annotationStorage.remove(key);
    }
    return storedValue;
  }
  addToAnnotationStorage(editor) {
    if (!editor.isEmpty() && this.#annotationStorage && !this.#annotationStorage.has(editor.id)) {
      this.#annotationStorage.setValue(editor.id, editor);
    }
  }
  a11yAlert(messageId, args = null) {
    const viewerAlert = this.#viewerAlert;
    if (!viewerAlert) {
      return;
    }
    viewerAlert.setAttribute("data-l10n-id", messageId);
    if (args) {
      viewerAlert.setAttribute("data-l10n-args", JSON.stringify(args));
    } else {
      viewerAlert.removeAttribute("data-l10n-args");
    }
  }
  #selectionChange() {
    const selection = document.getSelection();
    if (!selection || selection.isCollapsed) {
      if (this.#selectedTextNode) {
        this.#floatingToolbar?.hide();
        this.#selectedTextNode = null;
        this.#dispatchUpdateStates({
          hasSelectedText: false
        });
      }
      return;
    }
    const {
      anchorNode
    } = selection;
    if (anchorNode === this.#selectedTextNode) {
      return;
    }
    const anchorElement = this.#getAnchorElementForSelection(selection);
    const textLayer = anchorElement.closest(".textLayer");
    if (!textLayer) {
      if (this.#selectedTextNode) {
        this.#floatingToolbar?.hide();
        this.#selectedTextNode = null;
        this.#dispatchUpdateStates({
          hasSelectedText: false
        });
      }
      return;
    }
    this.#floatingToolbar?.hide();
    this.#selectedTextNode = anchorNode;
    this.#dispatchUpdateStates({
      hasSelectedText: true
    });
    if (this.#mode !== AnnotationEditorType.HIGHLIGHT && this.#mode !== AnnotationEditorType.NONE) {
      return;
    }
    if (this.#mode === AnnotationEditorType.HIGHLIGHT) {
      this.showAllEditors("highlight", true, true);
    }
    this.#highlightWhenShiftUp = this.isShiftKeyDown;
    if (!this.isShiftKeyDown) {
      const activeLayer = this.#mode === AnnotationEditorType.HIGHLIGHT ? this.#getLayerForTextLayer(textLayer) : null;
      activeLayer?.toggleDrawing();
      if (this.#isPointerDown) {
        const ac = new AbortController();
        const signal = this.combinedSignal(ac);
        const pointerup = (e9) => {
          if (e9.type === "pointerup" && e9.button !== 0) {
            return;
          }
          ac.abort();
          activeLayer?.toggleDrawing(true);
          if (e9.type === "pointerup") {
            this.#onSelectEnd("main_toolbar");
          }
        };
        window.addEventListener("pointerup", pointerup, {
          signal
        });
        window.addEventListener("blur", pointerup, {
          signal
        });
      } else {
        activeLayer?.toggleDrawing(true);
        this.#onSelectEnd("main_toolbar");
      }
    }
  }
  #onSelectEnd(methodOfCreation = "") {
    if (this.#mode === AnnotationEditorType.HIGHLIGHT) {
      this.highlightSelection(methodOfCreation);
    } else if (this.#enableHighlightFloatingButton) {
      this.#displayFloatingToolbar();
    }
  }
  #addSelectionListener() {
    document.addEventListener("selectionchange", this.#selectionChange.bind(this), {
      signal: this._signal
    });
  }
  #addFocusManager() {
    if (this.#focusManagerAC) {
      return;
    }
    this.#focusManagerAC = new AbortController();
    const signal = this.combinedSignal(this.#focusManagerAC);
    window.addEventListener("focus", this.focus.bind(this), {
      signal
    });
    window.addEventListener("blur", this.blur.bind(this), {
      signal
    });
  }
  #removeFocusManager() {
    this.#focusManagerAC?.abort();
    this.#focusManagerAC = null;
  }
  blur() {
    this.isShiftKeyDown = false;
    if (this.#highlightWhenShiftUp) {
      this.#highlightWhenShiftUp = false;
      this.#onSelectEnd("main_toolbar");
    }
    if (!this.hasSelection) {
      return;
    }
    const {
      activeElement
    } = document;
    for (const editor of this.#selectedEditors) {
      if (editor.div.contains(activeElement)) {
        this.#lastActiveElement = [editor, activeElement];
        editor._focusEventsAllowed = false;
        break;
      }
    }
  }
  focus() {
    if (!this.#lastActiveElement) {
      return;
    }
    const [lastEditor, lastActiveElement] = this.#lastActiveElement;
    this.#lastActiveElement = null;
    lastActiveElement.addEventListener("focusin", () => {
      lastEditor._focusEventsAllowed = true;
    }, {
      once: true,
      signal: this._signal
    });
    lastActiveElement.focus();
  }
  #addKeyboardManager() {
    if (this.#keyboardManagerAC) {
      return;
    }
    this.#keyboardManagerAC = new AbortController();
    const signal = this.combinedSignal(this.#keyboardManagerAC);
    window.addEventListener("keydown", this.keydown.bind(this), {
      signal
    });
    window.addEventListener("keyup", this.keyup.bind(this), {
      signal
    });
  }
  #removeKeyboardManager() {
    this.#keyboardManagerAC?.abort();
    this.#keyboardManagerAC = null;
  }
  #addCopyPasteListeners() {
    if (this.#copyPasteAC) {
      return;
    }
    this.#copyPasteAC = new AbortController();
    const signal = this.combinedSignal(this.#copyPasteAC);
    document.addEventListener("copy", this.copy.bind(this), {
      signal
    });
    document.addEventListener("cut", this.cut.bind(this), {
      signal
    });
    document.addEventListener("paste", this.paste.bind(this), {
      signal
    });
  }
  #removeCopyPasteListeners() {
    this.#copyPasteAC?.abort();
    this.#copyPasteAC = null;
  }
  #addDragAndDropListeners() {
    const signal = this._signal;
    document.addEventListener("dragover", this.dragOver.bind(this), {
      signal
    });
    document.addEventListener("drop", this.drop.bind(this), {
      signal
    });
  }
  addEditListeners() {
    this.#addKeyboardManager();
    this.setEditingState(true);
  }
  removeEditListeners() {
    this.#removeKeyboardManager();
    this.setEditingState(false);
  }
  dragOver(event) {
    for (const {
      type
    } of event.dataTransfer.items) {
      for (const editorType of this.#editorTypes) {
        if (editorType.isHandlingMimeForPasting(type)) {
          event.dataTransfer.dropEffect = "copy";
          event.preventDefault();
          return;
        }
      }
    }
  }
  drop(event) {
    for (const item of event.dataTransfer.items) {
      for (const editorType of this.#editorTypes) {
        if (editorType.isHandlingMimeForPasting(item.type)) {
          editorType.paste(item, this.currentLayer);
          event.preventDefault();
          return;
        }
      }
    }
  }
  copy(event) {
    event.preventDefault();
    this.#activeEditor?.commitOrRemove();
    if (!this.hasSelection) {
      return;
    }
    const editors = [];
    for (const editor of this.#selectedEditors) {
      const serialized = editor.serialize(true);
      if (serialized) {
        editors.push(serialized);
      }
    }
    if (editors.length === 0) {
      return;
    }
    event.clipboardData.setData("application/pdfjs", JSON.stringify(editors));
  }
  cut(event) {
    this.copy(event);
    this.delete();
  }
  async paste(event) {
    event.preventDefault();
    const {
      clipboardData
    } = event;
    for (const item of clipboardData.items) {
      for (const editorType of this.#editorTypes) {
        if (editorType.isHandlingMimeForPasting(item.type)) {
          editorType.paste(item, this.currentLayer);
          return;
        }
      }
    }
    let data = clipboardData.getData("application/pdfjs");
    if (!data) {
      return;
    }
    try {
      data = JSON.parse(data);
    } catch (ex) {
      warn(`paste: "${ex.message}".`);
      return;
    }
    if (!Array.isArray(data)) {
      return;
    }
    this.unselectAll();
    const layer = this.currentLayer;
    try {
      const newEditors = [];
      for (const editor of data) {
        const deserializedEditor = await layer.deserialize(editor);
        if (!deserializedEditor) {
          return;
        }
        newEditors.push(deserializedEditor);
      }
      const cmd = () => {
        for (const editor of newEditors) {
          this.#addEditorToLayer(editor);
        }
        this.#selectEditors(newEditors);
      };
      const undo = () => {
        for (const editor of newEditors) {
          editor.remove();
        }
      };
      this.addCommands({
        cmd,
        undo,
        mustExec: true
      });
    } catch (ex) {
      warn(`paste: "${ex.message}".`);
    }
  }
  keydown(event) {
    if (!this.isShiftKeyDown && event.key === "Shift") {
      this.isShiftKeyDown = true;
    }
    if (this.#mode !== AnnotationEditorType.NONE && !this.isEditorHandlingKeyboard) {
      _AnnotationEditorUIManager._keyboardManager.exec(this, event);
    }
  }
  keyup(event) {
    if (this.isShiftKeyDown && event.key === "Shift") {
      this.isShiftKeyDown = false;
      if (this.#highlightWhenShiftUp) {
        this.#highlightWhenShiftUp = false;
        this.#onSelectEnd("main_toolbar");
      }
    }
  }
  onEditingAction({
    name
  }) {
    switch (name) {
      case "undo":
      case "redo":
      case "delete":
      case "selectAll":
        this[name]();
        break;
      case "highlightSelection":
        this.highlightSelection("context_menu");
        break;
      case "commentSelection":
        this.commentSelection("context_menu");
        break;
    }
  }
  #dispatchUpdateStates(details) {
    const hasChanged = Object.entries(details).some(([key, value]) => this.#previousStates[key] !== value);
    if (hasChanged) {
      this._eventBus.dispatch("annotationeditorstateschanged", {
        source: this,
        details: Object.assign(this.#previousStates, details)
      });
      if (this.#mode === AnnotationEditorType.HIGHLIGHT && details.hasSelectedEditor === false) {
        this.#dispatchUpdateUI([[AnnotationEditorParamsType.HIGHLIGHT_FREE, true]]);
      }
    }
  }
  #dispatchUpdateUI(details) {
    this._eventBus.dispatch("annotationeditorparamschanged", {
      source: this,
      details
    });
  }
  setEditingState(isEditing) {
    if (isEditing) {
      this.#addFocusManager();
      this.#addCopyPasteListeners();
      this.#dispatchUpdateStates({
        isEditing: this.#mode !== AnnotationEditorType.NONE,
        isEmpty: this.#isEmpty(),
        hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(),
        hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(),
        hasSelectedEditor: false
      });
    } else {
      this.#removeFocusManager();
      this.#removeCopyPasteListeners();
      this.#dispatchUpdateStates({
        isEditing: false
      });
      this.disableUserSelect(false);
    }
  }
  registerEditorTypes(types2) {
    if (this.#editorTypes) {
      return;
    }
    this.#editorTypes = types2;
    for (const editorType of this.#editorTypes) {
      this.#dispatchUpdateUI(editorType.defaultPropertiesToUpdate);
    }
  }
  getId() {
    return this.#idManager.id;
  }
  get currentLayer() {
    return this.#allLayers.get(this.#currentPageIndex);
  }
  getLayer(pageIndex) {
    return this.#allLayers.get(pageIndex);
  }
  get currentPageIndex() {
    return this.#currentPageIndex;
  }
  addLayer(layer) {
    this.#allLayers.set(layer.pageIndex, layer);
    if (this.#isEnabled) {
      layer.enable();
    } else {
      layer.disable();
    }
  }
  removeLayer(layer) {
    this.#allLayers.delete(layer.pageIndex);
  }
  async updateMode(mode, editId = null, isFromKeyboard = false, mustEnterInEditMode = false, editComment = false) {
    if (this.#mode === mode) {
      return;
    }
    if (this.#updateModeCapability) {
      await this.#updateModeCapability.promise;
      if (!this.#updateModeCapability) {
        return;
      }
    }
    this.#updateModeCapability = Promise.withResolvers();
    this.#currentDrawingSession?.commitOrRemove();
    if (this.#mode === AnnotationEditorType.POPUP) {
      this.#commentManager?.hideSidebar();
    }
    this.#commentManager?.destroyPopup();
    this.#mode = mode;
    if (mode === AnnotationEditorType.NONE) {
      this.setEditingState(false);
      this.#disableAll();
      for (const editor of this.#allEditors.values()) {
        editor.hideStandaloneCommentButton();
      }
      this._editorUndoBar?.hide();
      this.toggleComment(null);
      this.#updateModeCapability.resolve();
      return;
    }
    for (const editor of this.#allEditors.values()) {
      editor.addStandaloneCommentButton();
    }
    if (mode === AnnotationEditorType.SIGNATURE) {
      await this.#signatureManager?.loadSignatures();
    }
    this.setEditingState(true);
    await this.#enableAll();
    this.unselectAll();
    for (const layer of this.#allLayers.values()) {
      layer.updateMode(mode);
    }
    if (mode === AnnotationEditorType.POPUP) {
      this.#allEditableAnnotations ||= await this.#pdfDocument.getAnnotationsByType(new Set(this.#editorTypes.map((editorClass) => editorClass._editorType)));
      const elementIds = /* @__PURE__ */ new Set();
      const allComments = [];
      for (const editor of this.#allEditors.values()) {
        const {
          annotationElementId,
          hasComment,
          deleted
        } = editor;
        if (annotationElementId) {
          elementIds.add(annotationElementId);
        }
        if (hasComment && !deleted) {
          allComments.push(editor.getData());
        }
      }
      for (const annotation of this.#allEditableAnnotations) {
        const {
          id,
          popupRef,
          contentsObj
        } = annotation;
        if (popupRef && contentsObj?.str && !elementIds.has(id) && !this.#deletedAnnotationsElementIds.has(id)) {
          allComments.push(annotation);
        }
      }
      this.#commentManager?.showSidebar(allComments);
    }
    if (!editId) {
      if (isFromKeyboard) {
        this.addNewEditorFromKeyboard();
      }
      this.#updateModeCapability.resolve();
      return;
    }
    for (const editor of this.#allEditors.values()) {
      if (editor.uid === editId) {
        this.setSelected(editor);
        if (editComment) {
          editor.editComment();
        } else if (mustEnterInEditMode) {
          editor.enterInEditMode();
        } else {
          editor.focus();
        }
      } else {
        editor.unselect();
      }
    }
    this.#updateModeCapability.resolve();
  }
  addNewEditorFromKeyboard() {
    if (this.currentLayer.canCreateNewEmptyEditor()) {
      this.currentLayer.addNewEditor();
    }
  }
  updateToolbar(options) {
    if (options.mode === this.#mode) {
      return;
    }
    this._eventBus.dispatch("switchannotationeditormode", {
      source: this,
      ...options
    });
  }
  updateParams(type, value) {
    if (!this.#editorTypes) {
      return;
    }
    switch (type) {
      case AnnotationEditorParamsType.CREATE:
        this.currentLayer.addNewEditor(value);
        return;
      case AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL:
        this._eventBus.dispatch("reporttelemetry", {
          source: this,
          details: {
            type: "editing",
            data: {
              type: "highlight",
              action: "toggle_visibility"
            }
          }
        });
        (this.#showAllStates ||= /* @__PURE__ */ new Map()).set(type, value);
        this.showAllEditors("highlight", value);
        break;
    }
    if (this.hasSelection) {
      for (const editor of this.#selectedEditors) {
        editor.updateParams(type, value);
      }
    } else {
      for (const editorType of this.#editorTypes) {
        editorType.updateDefaultParams(type, value);
      }
    }
  }
  showAllEditors(type, visible, updateButton = false) {
    for (const editor of this.#allEditors.values()) {
      if (editor.editorType === type) {
        editor.show(visible);
      }
    }
    const state = this.#showAllStates?.get(AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL) ?? true;
    if (state !== visible) {
      this.#dispatchUpdateUI([[AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL, visible]]);
    }
  }
  enableWaiting(mustWait = false) {
    if (this.#isWaiting === mustWait) {
      return;
    }
    this.#isWaiting = mustWait;
    for (const layer of this.#allLayers.values()) {
      if (mustWait) {
        layer.disableClick();
      } else {
        layer.enableClick();
      }
      layer.div.classList.toggle("waiting", mustWait);
    }
  }
  async #enableAll() {
    if (!this.#isEnabled) {
      this.#isEnabled = true;
      const promises = [];
      for (const layer of this.#allLayers.values()) {
        promises.push(layer.enable());
      }
      await Promise.all(promises);
      for (const editor of this.#allEditors.values()) {
        editor.enable();
      }
    }
  }
  #disableAll() {
    this.unselectAll();
    if (this.#isEnabled) {
      this.#isEnabled = false;
      for (const layer of this.#allLayers.values()) {
        layer.disable();
      }
      for (const editor of this.#allEditors.values()) {
        editor.disable();
      }
    }
  }
  *getEditors(pageIndex) {
    for (const editor of this.#allEditors.values()) {
      if (editor.pageIndex === pageIndex) {
        yield editor;
      }
    }
  }
  getEditor(id) {
    return this.#allEditors.get(id);
  }
  addEditor(editor) {
    this.#allEditors.set(editor.id, editor);
  }
  removeEditor(editor) {
    if (editor.div.contains(document.activeElement)) {
      if (this.#focusMainContainerTimeoutId) {
        clearTimeout(this.#focusMainContainerTimeoutId);
      }
      this.#focusMainContainerTimeoutId = setTimeout(() => {
        this.focusMainContainer();
        this.#focusMainContainerTimeoutId = null;
      }, 0);
    }
    this.#allEditors.delete(editor.id);
    if (editor.annotationElementId) {
      this.#missingCanvases?.delete(editor.annotationElementId);
    }
    this.unselect(editor);
    if (!editor.annotationElementId || !this.#deletedAnnotationsElementIds.has(editor.annotationElementId)) {
      this.#annotationStorage?.remove(editor.id);
    }
  }
  addDeletedAnnotationElement(editor) {
    this.#deletedAnnotationsElementIds.add(editor.annotationElementId);
    this.addChangedExistingAnnotation(editor);
    editor.deleted = true;
  }
  isDeletedAnnotationElement(annotationElementId) {
    return this.#deletedAnnotationsElementIds.has(annotationElementId);
  }
  removeDeletedAnnotationElement(editor) {
    this.#deletedAnnotationsElementIds.delete(editor.annotationElementId);
    this.removeChangedExistingAnnotation(editor);
    editor.deleted = false;
  }
  #addEditorToLayer(editor) {
    const layer = this.#allLayers.get(editor.pageIndex);
    if (layer) {
      layer.addOrRebuild(editor);
    } else {
      this.addEditor(editor);
      this.addToAnnotationStorage(editor);
    }
  }
  setActiveEditor(editor) {
    if (this.#activeEditor === editor) {
      return;
    }
    this.#activeEditor = editor;
    if (editor) {
      this.#dispatchUpdateUI(editor.propertiesToUpdate);
    }
  }
  get #lastSelectedEditor() {
    let ed = null;
    for (ed of this.#selectedEditors) {
    }
    return ed;
  }
  updateUI(editor) {
    if (this.#lastSelectedEditor === editor) {
      this.#dispatchUpdateUI(editor.propertiesToUpdate);
    }
  }
  updateUIForDefaultProperties(editorType) {
    this.#dispatchUpdateUI(editorType.defaultPropertiesToUpdate);
  }
  toggleSelected(editor) {
    if (this.#selectedEditors.has(editor)) {
      this.#selectedEditors.delete(editor);
      editor.unselect();
      this.#dispatchUpdateStates({
        hasSelectedEditor: this.hasSelection
      });
      return;
    }
    this.#selectedEditors.add(editor);
    editor.select();
    this.#dispatchUpdateUI(editor.propertiesToUpdate);
    this.#dispatchUpdateStates({
      hasSelectedEditor: true
    });
  }
  setSelected(editor) {
    this.updateToolbar({
      mode: editor.mode,
      editId: editor.uid
    });
    this.#currentDrawingSession?.commitOrRemove();
    for (const ed of this.#selectedEditors) {
      if (ed !== editor) {
        ed.unselect();
      }
    }
    this.#selectedEditors.clear();
    this.#selectedEditors.add(editor);
    editor.select();
    this.#dispatchUpdateUI(editor.propertiesToUpdate);
    this.#dispatchUpdateStates({
      hasSelectedEditor: true
    });
  }
  isSelected(editor) {
    return this.#selectedEditors.has(editor);
  }
  get firstSelectedEditor() {
    return this.#selectedEditors.values().next().value;
  }
  unselect(editor) {
    editor.unselect();
    this.#selectedEditors.delete(editor);
    this.#dispatchUpdateStates({
      hasSelectedEditor: this.hasSelection
    });
  }
  get hasSelection() {
    return this.#selectedEditors.size !== 0;
  }
  get isEnterHandled() {
    return this.#selectedEditors.size === 1 && this.firstSelectedEditor.isEnterHandled;
  }
  undo() {
    this.#commandManager.undo();
    this.#dispatchUpdateStates({
      hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(),
      hasSomethingToRedo: true,
      isEmpty: this.#isEmpty()
    });
    this._editorUndoBar?.hide();
  }
  redo() {
    this.#commandManager.redo();
    this.#dispatchUpdateStates({
      hasSomethingToUndo: true,
      hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(),
      isEmpty: this.#isEmpty()
    });
  }
  addCommands(params) {
    this.#commandManager.add(params);
    this.#dispatchUpdateStates({
      hasSomethingToUndo: true,
      hasSomethingToRedo: false,
      isEmpty: this.#isEmpty()
    });
  }
  cleanUndoStack(type) {
    this.#commandManager.cleanType(type);
  }
  #isEmpty() {
    if (this.#allEditors.size === 0) {
      return true;
    }
    if (this.#allEditors.size === 1) {
      for (const editor of this.#allEditors.values()) {
        return editor.isEmpty();
      }
    }
    return false;
  }
  delete() {
    this.commitOrRemove();
    const drawingEditor = this.currentLayer?.endDrawingSession(true);
    if (!this.hasSelection && !drawingEditor) {
      return;
    }
    const editors = drawingEditor ? [drawingEditor] : [...this.#selectedEditors];
    const cmd = () => {
      this._editorUndoBar?.show(undo, editors.length === 1 ? editors[0].editorType : editors.length);
      for (const editor of editors) {
        editor.remove();
      }
    };
    const undo = () => {
      for (const editor of editors) {
        this.#addEditorToLayer(editor);
      }
    };
    this.addCommands({
      cmd,
      undo,
      mustExec: true
    });
  }
  commitOrRemove() {
    this.#activeEditor?.commitOrRemove();
  }
  hasSomethingToControl() {
    return this.#activeEditor || this.hasSelection;
  }
  #selectEditors(editors) {
    for (const editor of this.#selectedEditors) {
      editor.unselect();
    }
    this.#selectedEditors.clear();
    for (const editor of editors) {
      if (editor.isEmpty()) {
        continue;
      }
      this.#selectedEditors.add(editor);
      editor.select();
    }
    this.#dispatchUpdateStates({
      hasSelectedEditor: this.hasSelection
    });
  }
  selectAll() {
    for (const editor of this.#selectedEditors) {
      editor.commit();
    }
    this.#selectEditors(this.#allEditors.values());
  }
  unselectAll() {
    if (this.#activeEditor) {
      this.#activeEditor.commitOrRemove();
      if (this.#mode !== AnnotationEditorType.NONE) {
        return;
      }
    }
    if (this.#currentDrawingSession?.commitOrRemove()) {
      return;
    }
    if (!this.hasSelection) {
      return;
    }
    for (const editor of this.#selectedEditors) {
      editor.unselect();
    }
    this.#selectedEditors.clear();
    this.#dispatchUpdateStates({
      hasSelectedEditor: false
    });
  }
  translateSelectedEditors(x2, y4, noCommit = false) {
    if (!noCommit) {
      this.commitOrRemove();
    }
    if (!this.hasSelection) {
      return;
    }
    this.#translation[0] += x2;
    this.#translation[1] += y4;
    const [totalX, totalY] = this.#translation;
    const editors = [...this.#selectedEditors];
    const TIME_TO_WAIT = 1e3;
    if (this.#translationTimeoutId) {
      clearTimeout(this.#translationTimeoutId);
    }
    this.#translationTimeoutId = setTimeout(() => {
      this.#translationTimeoutId = null;
      this.#translation[0] = this.#translation[1] = 0;
      this.addCommands({
        cmd: () => {
          for (const editor of editors) {
            if (this.#allEditors.has(editor.id)) {
              editor.translateInPage(totalX, totalY);
              editor.translationDone();
            }
          }
        },
        undo: () => {
          for (const editor of editors) {
            if (this.#allEditors.has(editor.id)) {
              editor.translateInPage(-totalX, -totalY);
              editor.translationDone();
            }
          }
        },
        mustExec: false
      });
    }, TIME_TO_WAIT);
    for (const editor of editors) {
      editor.translateInPage(x2, y4);
      editor.translationDone();
    }
  }
  setUpDragSession() {
    if (!this.hasSelection) {
      return;
    }
    this.disableUserSelect(true);
    this.#draggingEditors = /* @__PURE__ */ new Map();
    for (const editor of this.#selectedEditors) {
      this.#draggingEditors.set(editor, {
        savedX: editor.x,
        savedY: editor.y,
        savedPageIndex: editor.pageIndex,
        newX: 0,
        newY: 0,
        newPageIndex: -1
      });
    }
  }
  endDragSession() {
    if (!this.#draggingEditors) {
      return false;
    }
    this.disableUserSelect(false);
    const map = this.#draggingEditors;
    this.#draggingEditors = null;
    let mustBeAddedInUndoStack = false;
    for (const [{
      x: x2,
      y: y4,
      pageIndex
    }, value] of map) {
      value.newX = x2;
      value.newY = y4;
      value.newPageIndex = pageIndex;
      mustBeAddedInUndoStack ||= x2 !== value.savedX || y4 !== value.savedY || pageIndex !== value.savedPageIndex;
    }
    if (!mustBeAddedInUndoStack) {
      return false;
    }
    const move = (editor, x2, y4, pageIndex) => {
      if (this.#allEditors.has(editor.id)) {
        const parent = this.#allLayers.get(pageIndex);
        if (parent) {
          editor._setParentAndPosition(parent, x2, y4);
        } else {
          editor.pageIndex = pageIndex;
          editor.x = x2;
          editor.y = y4;
        }
      }
    };
    this.addCommands({
      cmd: () => {
        for (const [editor, {
          newX,
          newY,
          newPageIndex
        }] of map) {
          move(editor, newX, newY, newPageIndex);
        }
      },
      undo: () => {
        for (const [editor, {
          savedX,
          savedY,
          savedPageIndex
        }] of map) {
          move(editor, savedX, savedY, savedPageIndex);
        }
      },
      mustExec: true
    });
    return true;
  }
  dragSelectedEditors(tx, ty) {
    if (!this.#draggingEditors) {
      return;
    }
    for (const editor of this.#draggingEditors.keys()) {
      editor.drag(tx, ty);
    }
  }
  rebuild(editor) {
    if (editor.parent === null) {
      const parent = this.getLayer(editor.pageIndex);
      if (parent) {
        parent.changeParent(editor);
        parent.addOrRebuild(editor);
      } else {
        this.addEditor(editor);
        this.addToAnnotationStorage(editor);
        editor.rebuild();
      }
    } else {
      editor.parent.addOrRebuild(editor);
    }
  }
  get isEditorHandlingKeyboard() {
    return this.getActive()?.shouldGetKeyboardEvents() || this.#selectedEditors.size === 1 && this.firstSelectedEditor.shouldGetKeyboardEvents();
  }
  isActive(editor) {
    return this.#activeEditor === editor;
  }
  getActive() {
    return this.#activeEditor;
  }
  getMode() {
    return this.#mode;
  }
  isEditingMode() {
    return this.#mode !== AnnotationEditorType.NONE;
  }
  get imageManager() {
    return shadow(this, "imageManager", new ImageManager());
  }
  getSelectionBoxes(textLayer) {
    if (!textLayer) {
      return null;
    }
    const selection = document.getSelection();
    for (let i7 = 0, ii = selection.rangeCount; i7 < ii; i7++) {
      if (!textLayer.contains(selection.getRangeAt(i7).commonAncestorContainer)) {
        return null;
      }
    }
    const {
      x: layerX,
      y: layerY,
      width: parentWidth,
      height: parentHeight
    } = textLayer.getBoundingClientRect();
    let rotator;
    switch (textLayer.getAttribute("data-main-rotation")) {
      case "90":
        rotator = (x2, y4, w3, h7) => ({
          x: (y4 - layerY) / parentHeight,
          y: 1 - (x2 + w3 - layerX) / parentWidth,
          width: h7 / parentHeight,
          height: w3 / parentWidth
        });
        break;
      case "180":
        rotator = (x2, y4, w3, h7) => ({
          x: 1 - (x2 + w3 - layerX) / parentWidth,
          y: 1 - (y4 + h7 - layerY) / parentHeight,
          width: w3 / parentWidth,
          height: h7 / parentHeight
        });
        break;
      case "270":
        rotator = (x2, y4, w3, h7) => ({
          x: 1 - (y4 + h7 - layerY) / parentHeight,
          y: (x2 - layerX) / parentWidth,
          width: h7 / parentHeight,
          height: w3 / parentWidth
        });
        break;
      default:
        rotator = (x2, y4, w3, h7) => ({
          x: (x2 - layerX) / parentWidth,
          y: (y4 - layerY) / parentHeight,
          width: w3 / parentWidth,
          height: h7 / parentHeight
        });
        break;
    }
    const boxes = [];
    for (let i7 = 0, ii = selection.rangeCount; i7 < ii; i7++) {
      const range2 = selection.getRangeAt(i7);
      if (range2.collapsed) {
        continue;
      }
      for (const {
        x: x2,
        y: y4,
        width,
        height
      } of range2.getClientRects()) {
        if (width === 0 || height === 0) {
          continue;
        }
        boxes.push(rotator(x2, y4, width, height));
      }
    }
    return boxes.length === 0 ? null : boxes;
  }
  addChangedExistingAnnotation({
    annotationElementId,
    id
  }) {
    (this.#changedExistingAnnotations ||= /* @__PURE__ */ new Map()).set(annotationElementId, id);
  }
  removeChangedExistingAnnotation({
    annotationElementId
  }) {
    this.#changedExistingAnnotations?.delete(annotationElementId);
  }
  renderAnnotationElement(annotation) {
    const editorId = this.#changedExistingAnnotations?.get(annotation.data.id);
    if (!editorId) {
      return;
    }
    const editor = this.#annotationStorage.getRawValue(editorId);
    if (!editor) {
      return;
    }
    if (this.#mode === AnnotationEditorType.NONE && !editor.hasBeenModified) {
      return;
    }
    editor.renderAnnotationElement(annotation);
  }
  setMissingCanvas(annotationId, annotationElementId, canvas) {
    const editor = this.#missingCanvases?.get(annotationId);
    if (!editor) {
      return;
    }
    editor.setCanvas(annotationElementId, canvas);
    this.#missingCanvases.delete(annotationId);
  }
  addMissingCanvas(annotationId, editor) {
    (this.#missingCanvases ||= /* @__PURE__ */ new Map()).set(annotationId, editor);
  }
};
var AltText = class _AltText {
  #altText = null;
  #altTextDecorative = false;
  #altTextButton = null;
  #altTextButtonLabel = null;
  #altTextTooltip = null;
  #altTextTooltipTimeout = null;
  #altTextWasFromKeyBoard = false;
  #badge = null;
  #editor = null;
  #guessedText = null;
  #textWithDisclaimer = null;
  #useNewAltTextFlow = false;
  static #l10nNewButton = null;
  static _l10n = null;
  constructor(editor) {
    this.#editor = editor;
    this.#useNewAltTextFlow = editor._uiManager.useNewAltTextFlow;
    _AltText.#l10nNewButton ||= Object.freeze({
      added: "pdfjs-editor-new-alt-text-added-button",
      "added-label": "pdfjs-editor-new-alt-text-added-button-label",
      missing: "pdfjs-editor-new-alt-text-missing-button",
      "missing-label": "pdfjs-editor-new-alt-text-missing-button-label",
      review: "pdfjs-editor-new-alt-text-to-review-button",
      "review-label": "pdfjs-editor-new-alt-text-to-review-button-label"
    });
  }
  static initialize(l10n) {
    _AltText._l10n ??= l10n;
  }
  async render() {
    const altText = this.#altTextButton = document.createElement("button");
    altText.className = "altText";
    altText.tabIndex = "0";
    const label = this.#altTextButtonLabel = document.createElement("span");
    altText.append(label);
    if (this.#useNewAltTextFlow) {
      altText.classList.add("new");
      altText.setAttribute("data-l10n-id", _AltText.#l10nNewButton.missing);
      label.setAttribute("data-l10n-id", _AltText.#l10nNewButton["missing-label"]);
    } else {
      altText.setAttribute("data-l10n-id", "pdfjs-editor-alt-text-button");
      label.setAttribute("data-l10n-id", "pdfjs-editor-alt-text-button-label");
    }
    const signal = this.#editor._uiManager._signal;
    altText.addEventListener("contextmenu", noContextMenu, {
      signal
    });
    altText.addEventListener("pointerdown", (event) => event.stopPropagation(), {
      signal
    });
    const onClick = (event) => {
      event.preventDefault();
      this.#editor._uiManager.editAltText(this.#editor);
      if (this.#useNewAltTextFlow) {
        this.#editor._reportTelemetry({
          action: "pdfjs.image.alt_text.image_status_label_clicked",
          data: {
            label: this.#label
          }
        });
      }
    };
    altText.addEventListener("click", onClick, {
      capture: true,
      signal
    });
    altText.addEventListener("keydown", (event) => {
      if (event.target === altText && event.key === "Enter") {
        this.#altTextWasFromKeyBoard = true;
        onClick(event);
      }
    }, {
      signal
    });
    await this.#setState();
    return altText;
  }
  get #label() {
    return this.#altText && "added" || this.#altText === null && this.guessedText && "review" || "missing";
  }
  finish() {
    if (!this.#altTextButton) {
      return;
    }
    this.#altTextButton.focus({
      focusVisible: this.#altTextWasFromKeyBoard
    });
    this.#altTextWasFromKeyBoard = false;
  }
  isEmpty() {
    if (this.#useNewAltTextFlow) {
      return this.#altText === null;
    }
    return !this.#altText && !this.#altTextDecorative;
  }
  hasData() {
    if (this.#useNewAltTextFlow) {
      return this.#altText !== null || !!this.#guessedText;
    }
    return this.isEmpty();
  }
  get guessedText() {
    return this.#guessedText;
  }
  async setGuessedText(guessedText) {
    if (this.#altText !== null) {
      return;
    }
    this.#guessedText = guessedText;
    this.#textWithDisclaimer = await _AltText._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer", {
      generatedAltText: guessedText
    });
    this.#setState();
  }
  toggleAltTextBadge(visibility = false) {
    if (!this.#useNewAltTextFlow || this.#altText) {
      this.#badge?.remove();
      this.#badge = null;
      return;
    }
    if (!this.#badge) {
      const badge = this.#badge = document.createElement("div");
      badge.className = "noAltTextBadge";
      this.#editor.div.append(badge);
    }
    this.#badge.classList.toggle("hidden", !visibility);
  }
  serialize(isForCopying) {
    let altText = this.#altText;
    if (!isForCopying && this.#guessedText === altText) {
      altText = this.#textWithDisclaimer;
    }
    return {
      altText,
      decorative: this.#altTextDecorative,
      guessedText: this.#guessedText,
      textWithDisclaimer: this.#textWithDisclaimer
    };
  }
  get data() {
    return {
      altText: this.#altText,
      decorative: this.#altTextDecorative
    };
  }
  set data({
    altText,
    decorative,
    guessedText,
    textWithDisclaimer,
    cancel = false
  }) {
    if (guessedText) {
      this.#guessedText = guessedText;
      this.#textWithDisclaimer = textWithDisclaimer;
    }
    if (this.#altText === altText && this.#altTextDecorative === decorative) {
      return;
    }
    if (!cancel) {
      this.#altText = altText;
      this.#altTextDecorative = decorative;
    }
    this.#setState();
  }
  toggle(enabled = false) {
    if (!this.#altTextButton) {
      return;
    }
    if (!enabled && this.#altTextTooltipTimeout) {
      clearTimeout(this.#altTextTooltipTimeout);
      this.#altTextTooltipTimeout = null;
    }
    this.#altTextButton.disabled = !enabled;
  }
  shown() {
    this.#editor._reportTelemetry({
      action: "pdfjs.image.alt_text.image_status_label_displayed",
      data: {
        label: this.#label
      }
    });
  }
  destroy() {
    this.#altTextButton?.remove();
    this.#altTextButton = null;
    this.#altTextButtonLabel = null;
    this.#altTextTooltip = null;
    this.#badge?.remove();
    this.#badge = null;
  }
  async #setState() {
    const button = this.#altTextButton;
    if (!button) {
      return;
    }
    if (this.#useNewAltTextFlow) {
      button.classList.toggle("done", !!this.#altText);
      button.setAttribute("data-l10n-id", _AltText.#l10nNewButton[this.#label]);
      this.#altTextButtonLabel?.setAttribute("data-l10n-id", _AltText.#l10nNewButton[`${this.#label}-label`]);
      if (!this.#altText) {
        this.#altTextTooltip?.remove();
        return;
      }
    } else {
      if (!this.#altText && !this.#altTextDecorative) {
        button.classList.remove("done");
        this.#altTextTooltip?.remove();
        return;
      }
      button.classList.add("done");
      button.setAttribute("data-l10n-id", "pdfjs-editor-alt-text-edit-button");
    }
    let tooltip = this.#altTextTooltip;
    if (!tooltip) {
      this.#altTextTooltip = tooltip = document.createElement("span");
      tooltip.className = "tooltip";
      tooltip.setAttribute("role", "tooltip");
      tooltip.id = `alt-text-tooltip-${this.#editor.id}`;
      const DELAY_TO_SHOW_TOOLTIP = 100;
      const signal = this.#editor._uiManager._signal;
      signal.addEventListener("abort", () => {
        clearTimeout(this.#altTextTooltipTimeout);
        this.#altTextTooltipTimeout = null;
      }, {
        once: true
      });
      button.addEventListener("mouseenter", () => {
        this.#altTextTooltipTimeout = setTimeout(() => {
          this.#altTextTooltipTimeout = null;
          this.#altTextTooltip.classList.add("show");
          this.#editor._reportTelemetry({
            action: "alt_text_tooltip"
          });
        }, DELAY_TO_SHOW_TOOLTIP);
      }, {
        signal
      });
      button.addEventListener("mouseleave", () => {
        if (this.#altTextTooltipTimeout) {
          clearTimeout(this.#altTextTooltipTimeout);
          this.#altTextTooltipTimeout = null;
        }
        this.#altTextTooltip?.classList.remove("show");
      }, {
        signal
      });
    }
    if (this.#altTextDecorative) {
      tooltip.setAttribute("data-l10n-id", "pdfjs-editor-alt-text-decorative-tooltip");
    } else {
      tooltip.removeAttribute("data-l10n-id");
      tooltip.textContent = this.#altText;
    }
    if (!tooltip.parentNode) {
      button.append(tooltip);
    }
    const element = this.#editor.getElementForAltText();
    element?.setAttribute("aria-describedby", tooltip.id);
  }
};
var Comment = class {
  #commentStandaloneButton = null;
  #commentToolbarButton = null;
  #commentWasFromKeyBoard = false;
  #editor = null;
  #initialText = null;
  #richText = null;
  #text = null;
  #date = null;
  #deleted = false;
  #popupPosition = null;
  constructor(editor) {
    this.#editor = editor;
  }
  renderForToolbar() {
    const button = this.#commentToolbarButton = document.createElement("button");
    button.className = "comment";
    return this.#render(button, false);
  }
  renderForStandalone() {
    const button = this.#commentStandaloneButton = document.createElement("button");
    button.className = "annotationCommentButton";
    const position = this.#editor.commentButtonPosition;
    if (position) {
      const {
        style
      } = button;
      style.insetInlineEnd = `calc(${100 * (this.#editor._uiManager.direction === "ltr" ? 1 - position[0] : position[0])}% - var(--comment-button-dim))`;
      style.top = `calc(${100 * position[1]}% - var(--comment-button-dim))`;
      const color = this.#editor.commentButtonColor;
      if (color) {
        style.backgroundColor = color;
      }
    }
    return this.#render(button, true);
  }
  focusButton() {
    setTimeout(() => {
      (this.#commentStandaloneButton ?? this.#commentToolbarButton)?.focus();
    }, 0);
  }
  onUpdatedColor() {
    if (!this.#commentStandaloneButton) {
      return;
    }
    const color = this.#editor.commentButtonColor;
    if (color) {
      this.#commentStandaloneButton.style.backgroundColor = color;
    }
    this.#editor._uiManager.updatePopupColor(this.#editor);
  }
  get commentButtonWidth() {
    return (this.#commentStandaloneButton?.getBoundingClientRect().width ?? 0) / this.#editor.parent.boundingClientRect.width;
  }
  get commentPopupPositionInLayer() {
    if (this.#popupPosition) {
      return this.#popupPosition;
    }
    if (!this.#commentStandaloneButton) {
      return null;
    }
    const {
      x: x2,
      y: y4,
      height
    } = this.#commentStandaloneButton.getBoundingClientRect();
    const {
      x: parentX,
      y: parentY,
      width: parentWidth,
      height: parentHeight
    } = this.#editor.parent.boundingClientRect;
    return [(x2 - parentX) / parentWidth, (y4 + height - parentY) / parentHeight];
  }
  set commentPopupPositionInLayer(pos) {
    this.#popupPosition = pos;
  }
  hasDefaultPopupPosition() {
    return this.#popupPosition === null;
  }
  removeStandaloneCommentButton() {
    this.#commentStandaloneButton?.remove();
    this.#commentStandaloneButton = null;
  }
  removeToolbarCommentButton() {
    this.#commentToolbarButton?.remove();
    this.#commentToolbarButton = null;
  }
  setCommentButtonStates({
    selected,
    hasPopup
  }) {
    if (!this.#commentStandaloneButton) {
      return;
    }
    this.#commentStandaloneButton.classList.toggle("selected", selected);
    this.#commentStandaloneButton.ariaExpanded = hasPopup;
  }
  #render(comment, isStandalone) {
    if (!this.#editor._uiManager.hasCommentManager()) {
      return null;
    }
    comment.tabIndex = "0";
    comment.ariaHasPopup = "dialog";
    if (isStandalone) {
      comment.ariaControls = "commentPopup";
      comment.setAttribute("data-l10n-id", "pdfjs-show-comment-button");
    } else {
      comment.ariaControlsElements = [this.#editor._uiManager.getCommentDialogElement()];
      comment.setAttribute("data-l10n-id", "pdfjs-editor-add-comment-button");
    }
    const signal = this.#editor._uiManager._signal;
    if (!(signal instanceof AbortSignal) || signal.aborted) {
      return comment;
    }
    comment.addEventListener("contextmenu", noContextMenu, {
      signal
    });
    if (isStandalone) {
      comment.addEventListener("focusin", (e9) => {
        this.#editor._focusEventsAllowed = false;
        stopEvent(e9);
      }, {
        capture: true,
        signal
      });
      comment.addEventListener("focusout", (e9) => {
        this.#editor._focusEventsAllowed = true;
        stopEvent(e9);
      }, {
        capture: true,
        signal
      });
    }
    comment.addEventListener("pointerdown", (event) => event.stopPropagation(), {
      signal
    });
    const onClick = (event) => {
      event.preventDefault();
      if (comment === this.#commentToolbarButton) {
        this.edit();
      } else {
        this.#editor.toggleComment(true);
      }
    };
    comment.addEventListener("click", onClick, {
      capture: true,
      signal
    });
    comment.addEventListener("keydown", (event) => {
      if (event.target === comment && event.key === "Enter") {
        this.#commentWasFromKeyBoard = true;
        onClick(event);
      }
    }, {
      signal
    });
    comment.addEventListener("pointerenter", () => {
      this.#editor.toggleComment(false, true);
    }, {
      signal
    });
    comment.addEventListener("pointerleave", () => {
      this.#editor.toggleComment(false, false);
    }, {
      signal
    });
    return comment;
  }
  edit(options) {
    const position = this.commentPopupPositionInLayer;
    let posX, posY;
    if (position) {
      [posX, posY] = position;
    } else {
      [posX, posY] = this.#editor.commentButtonPosition;
      const {
        width,
        height,
        x: x2,
        y: y4
      } = this.#editor;
      posX = x2 + posX * width;
      posY = y4 + posY * height;
    }
    const parentDimensions = this.#editor.parent.boundingClientRect;
    const {
      x: parentX,
      y: parentY,
      width: parentWidth,
      height: parentHeight
    } = parentDimensions;
    this.#editor._uiManager.editComment(this.#editor, parentX + posX * parentWidth, parentY + posY * parentHeight, {
      ...options,
      parentDimensions
    });
  }
  finish() {
    if (!this.#commentToolbarButton) {
      return;
    }
    this.#commentToolbarButton.focus({
      focusVisible: this.#commentWasFromKeyBoard
    });
    this.#commentWasFromKeyBoard = false;
  }
  isDeleted() {
    return this.#deleted || this.#text === "";
  }
  isEmpty() {
    return this.#text === null;
  }
  hasBeenEdited() {
    return this.isDeleted() || this.#text !== this.#initialText;
  }
  serialize() {
    return this.data;
  }
  get data() {
    return {
      text: this.#text,
      richText: this.#richText,
      date: this.#date,
      deleted: this.isDeleted()
    };
  }
  set data(text3) {
    if (text3 !== this.#text) {
      this.#richText = null;
    }
    if (text3 === null) {
      this.#text = "";
      this.#deleted = true;
      return;
    }
    this.#text = text3;
    this.#date = /* @__PURE__ */ new Date();
    this.#deleted = false;
  }
  setInitialText(text3, richText = null) {
    this.#initialText = text3;
    this.data = text3;
    this.#date = null;
    this.#richText = richText;
  }
  shown() {
  }
  destroy() {
    this.#commentToolbarButton?.remove();
    this.#commentToolbarButton = null;
    this.#commentStandaloneButton?.remove();
    this.#commentStandaloneButton = null;
    this.#text = "";
    this.#richText = null;
    this.#date = null;
    this.#editor = null;
    this.#commentWasFromKeyBoard = false;
    this.#deleted = false;
  }
};
var TouchManager = class _TouchManager {
  #container;
  #isPinching = false;
  #isPinchingStopped = null;
  #isPinchingDisabled;
  #onPinchStart;
  #onPinching;
  #onPinchEnd;
  #pointerDownAC = null;
  #signal;
  #touchInfo = null;
  #touchManagerAC;
  #touchMoveAC = null;
  constructor({
    container,
    isPinchingDisabled = null,
    isPinchingStopped = null,
    onPinchStart = null,
    onPinching = null,
    onPinchEnd = null,
    signal
  }) {
    this.#container = container;
    this.#isPinchingStopped = isPinchingStopped;
    this.#isPinchingDisabled = isPinchingDisabled;
    this.#onPinchStart = onPinchStart;
    this.#onPinching = onPinching;
    this.#onPinchEnd = onPinchEnd;
    this.#touchManagerAC = new AbortController();
    this.#signal = AbortSignal.any([signal, this.#touchManagerAC.signal]);
    container.addEventListener("touchstart", this.#onTouchStart.bind(this), {
      passive: false,
      signal: this.#signal
    });
  }
  get MIN_TOUCH_DISTANCE_TO_PINCH() {
    return 35 / OutputScale.pixelRatio;
  }
  #onTouchStart(evt) {
    if (this.#isPinchingDisabled?.()) {
      return;
    }
    if (evt.touches.length === 1) {
      if (this.#pointerDownAC) {
        return;
      }
      const pointerDownAC = this.#pointerDownAC = new AbortController();
      const signal = AbortSignal.any([this.#signal, pointerDownAC.signal]);
      const container = this.#container;
      const opts = {
        capture: true,
        signal,
        passive: false
      };
      const cancelPointerDown = (e9) => {
        if (e9.pointerType === "touch") {
          this.#pointerDownAC?.abort();
          this.#pointerDownAC = null;
        }
      };
      container.addEventListener("pointerdown", (e9) => {
        if (e9.pointerType === "touch") {
          stopEvent(e9);
          cancelPointerDown(e9);
        }
      }, opts);
      container.addEventListener("pointerup", cancelPointerDown, opts);
      container.addEventListener("pointercancel", cancelPointerDown, opts);
      return;
    }
    if (!this.#touchMoveAC) {
      this.#touchMoveAC = new AbortController();
      const signal = AbortSignal.any([this.#signal, this.#touchMoveAC.signal]);
      const container = this.#container;
      const opt = {
        signal,
        capture: false,
        passive: false
      };
      container.addEventListener("touchmove", this.#onTouchMove.bind(this), opt);
      const onTouchEnd = this.#onTouchEnd.bind(this);
      container.addEventListener("touchend", onTouchEnd, opt);
      container.addEventListener("touchcancel", onTouchEnd, opt);
      opt.capture = true;
      container.addEventListener("pointerdown", stopEvent, opt);
      container.addEventListener("pointermove", stopEvent, opt);
      container.addEventListener("pointercancel", stopEvent, opt);
      container.addEventListener("pointerup", stopEvent, opt);
      this.#onPinchStart?.();
    }
    stopEvent(evt);
    if (evt.touches.length !== 2 || this.#isPinchingStopped?.()) {
      this.#touchInfo = null;
      return;
    }
    let [touch0, touch1] = evt.touches;
    if (touch0.identifier > touch1.identifier) {
      [touch0, touch1] = [touch1, touch0];
    }
    this.#touchInfo = {
      touch0X: touch0.screenX,
      touch0Y: touch0.screenY,
      touch1X: touch1.screenX,
      touch1Y: touch1.screenY
    };
  }
  #onTouchMove(evt) {
    if (!this.#touchInfo || evt.touches.length !== 2) {
      return;
    }
    stopEvent(evt);
    let [touch0, touch1] = evt.touches;
    if (touch0.identifier > touch1.identifier) {
      [touch0, touch1] = [touch1, touch0];
    }
    const {
      screenX: screen0X,
      screenY: screen0Y
    } = touch0;
    const {
      screenX: screen1X,
      screenY: screen1Y
    } = touch1;
    const touchInfo = this.#touchInfo;
    const {
      touch0X: pTouch0X,
      touch0Y: pTouch0Y,
      touch1X: pTouch1X,
      touch1Y: pTouch1Y
    } = touchInfo;
    const prevGapX = pTouch1X - pTouch0X;
    const prevGapY = pTouch1Y - pTouch0Y;
    const currGapX = screen1X - screen0X;
    const currGapY = screen1Y - screen0Y;
    const distance = Math.hypot(currGapX, currGapY) || 1;
    const pDistance = Math.hypot(prevGapX, prevGapY) || 1;
    if (!this.#isPinching && Math.abs(pDistance - distance) <= _TouchManager.MIN_TOUCH_DISTANCE_TO_PINCH) {
      return;
    }
    touchInfo.touch0X = screen0X;
    touchInfo.touch0Y = screen0Y;
    touchInfo.touch1X = screen1X;
    touchInfo.touch1Y = screen1Y;
    if (!this.#isPinching) {
      this.#isPinching = true;
      return;
    }
    const origin = [(screen0X + screen1X) / 2, (screen0Y + screen1Y) / 2];
    this.#onPinching?.(origin, pDistance, distance);
  }
  #onTouchEnd(evt) {
    if (evt.touches.length >= 2) {
      return;
    }
    if (this.#touchMoveAC) {
      this.#touchMoveAC.abort();
      this.#touchMoveAC = null;
      this.#onPinchEnd?.();
    }
    if (!this.#touchInfo) {
      return;
    }
    stopEvent(evt);
    this.#touchInfo = null;
    this.#isPinching = false;
  }
  destroy() {
    this.#touchManagerAC?.abort();
    this.#touchManagerAC = null;
    this.#pointerDownAC?.abort();
    this.#pointerDownAC = null;
  }
};
var AnnotationEditor = class _AnnotationEditor {
  #accessibilityData = null;
  #allResizerDivs = null;
  #altText = null;
  #comment = null;
  #commentStandaloneButton = null;
  #disabled = false;
  #dragPointerId = null;
  #dragPointerType = "";
  #resizersDiv = null;
  #lastPointerCoords = null;
  #savedDimensions = null;
  #fakeAnnotation = null;
  #focusAC = null;
  #focusedResizerName = "";
  #hasBeenClicked = false;
  #initialRect = null;
  #isEditing = false;
  #isInEditMode = false;
  #isResizerEnabledForKeyboard = false;
  #moveInDOMTimeout = null;
  #prevDragX = 0;
  #prevDragY = 0;
  #telemetryTimeouts = null;
  #touchManager = null;
  isSelected = false;
  _isCopy = false;
  _editToolbar = null;
  _initialOptions = /* @__PURE__ */ Object.create(null);
  _initialData = null;
  _isVisible = true;
  _uiManager = null;
  _focusEventsAllowed = true;
  static _l10n = null;
  static _l10nResizer = null;
  #isDraggable = false;
  #zIndex = _AnnotationEditor._zIndex++;
  static _borderLineWidth = -1;
  static _colorManager = new ColorManager();
  static _zIndex = 1;
  static _telemetryTimeout = 1e3;
  static get _resizerKeyboardManager() {
    const resize = _AnnotationEditor.prototype._resizeWithKeyboard;
    const small = AnnotationEditorUIManager.TRANSLATE_SMALL;
    const big = AnnotationEditorUIManager.TRANSLATE_BIG;
    return shadow(this, "_resizerKeyboardManager", new KeyboardManager([[["ArrowLeft", "mac+ArrowLeft"], resize, {
      args: [-small, 0]
    }], [["ctrl+ArrowLeft", "mac+shift+ArrowLeft"], resize, {
      args: [-big, 0]
    }], [["ArrowRight", "mac+ArrowRight"], resize, {
      args: [small, 0]
    }], [["ctrl+ArrowRight", "mac+shift+ArrowRight"], resize, {
      args: [big, 0]
    }], [["ArrowUp", "mac+ArrowUp"], resize, {
      args: [0, -small]
    }], [["ctrl+ArrowUp", "mac+shift+ArrowUp"], resize, {
      args: [0, -big]
    }], [["ArrowDown", "mac+ArrowDown"], resize, {
      args: [0, small]
    }], [["ctrl+ArrowDown", "mac+shift+ArrowDown"], resize, {
      args: [0, big]
    }], [["Escape", "mac+Escape"], _AnnotationEditor.prototype._stopResizingWithKeyboard]]));
  }
  constructor(parameters) {
    this.parent = parameters.parent;
    this.id = parameters.id;
    this.width = this.height = null;
    this.pageIndex = parameters.parent.pageIndex;
    this.name = parameters.name;
    this.div = null;
    this._uiManager = parameters.uiManager;
    this.annotationElementId = null;
    this._willKeepAspectRatio = false;
    this._initialOptions.isCentered = parameters.isCentered;
    this._structTreeParentId = null;
    this.annotationElementId = parameters.annotationElementId || null;
    this.creationDate = parameters.creationDate || /* @__PURE__ */ new Date();
    this.modificationDate = parameters.modificationDate || null;
    this.canAddComment = true;
    const {
      rotation,
      rawDims: {
        pageWidth,
        pageHeight,
        pageX,
        pageY
      }
    } = this.parent.viewport;
    this.rotation = rotation;
    this.pageRotation = (360 + rotation - this._uiManager.viewParameters.rotation) % 360;
    this.pageDimensions = [pageWidth, pageHeight];
    this.pageTranslation = [pageX, pageY];
    const [width, height] = this.parentDimensions;
    this.x = parameters.x / width;
    this.y = parameters.y / height;
    this.isAttachedToDOM = false;
    this.deleted = false;
  }
  get editorType() {
    return Object.getPrototypeOf(this).constructor._type;
  }
  get mode() {
    return Object.getPrototypeOf(this).constructor._editorType;
  }
  static get isDrawer() {
    return false;
  }
  static get _defaultLineColor() {
    return shadow(this, "_defaultLineColor", this._colorManager.getHexCode("CanvasText"));
  }
  static deleteAnnotationElement(editor) {
    const fakeEditor = new FakeEditor({
      id: editor.parent.getNextId(),
      parent: editor.parent,
      uiManager: editor._uiManager
    });
    fakeEditor.annotationElementId = editor.annotationElementId;
    fakeEditor.deleted = true;
    fakeEditor._uiManager.addToAnnotationStorage(fakeEditor);
  }
  static initialize(l10n, _uiManager) {
    _AnnotationEditor._l10n ??= l10n;
    _AnnotationEditor._l10nResizer ||= Object.freeze({
      topLeft: "pdfjs-editor-resizer-top-left",
      topMiddle: "pdfjs-editor-resizer-top-middle",
      topRight: "pdfjs-editor-resizer-top-right",
      middleRight: "pdfjs-editor-resizer-middle-right",
      bottomRight: "pdfjs-editor-resizer-bottom-right",
      bottomMiddle: "pdfjs-editor-resizer-bottom-middle",
      bottomLeft: "pdfjs-editor-resizer-bottom-left",
      middleLeft: "pdfjs-editor-resizer-middle-left"
    });
    if (_AnnotationEditor._borderLineWidth !== -1) {
      return;
    }
    const style = getComputedStyle(document.documentElement);
    _AnnotationEditor._borderLineWidth = parseFloat(style.getPropertyValue("--outline-width")) || 0;
  }
  static updateDefaultParams(_type, _value) {
  }
  static get defaultPropertiesToUpdate() {
    return [];
  }
  static isHandlingMimeForPasting(mime) {
    return false;
  }
  static paste(item, parent) {
    unreachable("Not implemented");
  }
  get propertiesToUpdate() {
    return [];
  }
  get _isDraggable() {
    return this.#isDraggable;
  }
  set _isDraggable(value) {
    this.#isDraggable = value;
    this.div?.classList.toggle("draggable", value);
  }
  get uid() {
    return this.annotationElementId || this.id;
  }
  get isEnterHandled() {
    return true;
  }
  center() {
    const [pageWidth, pageHeight] = this.pageDimensions;
    switch (this.parentRotation) {
      case 90:
        this.x -= this.height * pageHeight / (pageWidth * 2);
        this.y += this.width * pageWidth / (pageHeight * 2);
        break;
      case 180:
        this.x += this.width / 2;
        this.y += this.height / 2;
        break;
      case 270:
        this.x += this.height * pageHeight / (pageWidth * 2);
        this.y -= this.width * pageWidth / (pageHeight * 2);
        break;
      default:
        this.x -= this.width / 2;
        this.y -= this.height / 2;
        break;
    }
    this.fixAndSetPosition();
  }
  addCommands(params) {
    this._uiManager.addCommands(params);
  }
  get currentLayer() {
    return this._uiManager.currentLayer;
  }
  setInBackground() {
    this.div.style.zIndex = 0;
  }
  setInForeground() {
    this.div.style.zIndex = this.#zIndex;
  }
  setParent(parent) {
    if (parent !== null) {
      this.pageIndex = parent.pageIndex;
      this.pageDimensions = parent.pageDimensions;
    } else {
      this.#stopResizing();
      this.#fakeAnnotation?.remove();
      this.#fakeAnnotation = null;
    }
    this.parent = parent;
  }
  focusin(event) {
    if (!this._focusEventsAllowed) {
      return;
    }
    if (!this.#hasBeenClicked) {
      this.parent.setSelected(this);
    } else {
      this.#hasBeenClicked = false;
    }
  }
  focusout(event) {
    if (!this._focusEventsAllowed) {
      return;
    }
    if (!this.isAttachedToDOM) {
      return;
    }
    const target = event.relatedTarget;
    if (target?.closest(`#${this.id}`)) {
      return;
    }
    event.preventDefault();
    if (!this.parent?.isMultipleSelection) {
      this.commitOrRemove();
    }
  }
  commitOrRemove() {
    if (this.isEmpty()) {
      this.remove();
    } else {
      this.commit();
    }
  }
  commit() {
    if (!this.isInEditMode()) {
      return;
    }
    this.addToAnnotationStorage();
  }
  addToAnnotationStorage() {
    this._uiManager.addToAnnotationStorage(this);
  }
  setAt(x2, y4, tx, ty) {
    const [width, height] = this.parentDimensions;
    [tx, ty] = this.screenToPageTranslation(tx, ty);
    this.x = (x2 + tx) / width;
    this.y = (y4 + ty) / height;
    this.fixAndSetPosition();
  }
  _moveAfterPaste(baseX, baseY) {
    const [parentWidth, parentHeight] = this.parentDimensions;
    this.setAt(baseX * parentWidth, baseY * parentHeight, this.width * parentWidth, this.height * parentHeight);
    this._onTranslated();
  }
  #translate([width, height], x2, y4) {
    [x2, y4] = this.screenToPageTranslation(x2, y4);
    this.x += x2 / width;
    this.y += y4 / height;
    this._onTranslating(this.x, this.y);
    this.fixAndSetPosition();
  }
  translate(x2, y4) {
    this.#translate(this.parentDimensions, x2, y4);
  }
  translateInPage(x2, y4) {
    this.#initialRect ||= [this.x, this.y, this.width, this.height];
    this.#translate(this.pageDimensions, x2, y4);
    this.div.scrollIntoView({
      block: "nearest"
    });
  }
  translationDone() {
    this._onTranslated(this.x, this.y);
  }
  drag(tx, ty) {
    this.#initialRect ||= [this.x, this.y, this.width, this.height];
    const {
      div,
      parentDimensions: [parentWidth, parentHeight]
    } = this;
    this.x += tx / parentWidth;
    this.y += ty / parentHeight;
    if (this.parent && (this.x < 0 || this.x > 1 || this.y < 0 || this.y > 1)) {
      const {
        x: x3,
        y: y5
      } = this.div.getBoundingClientRect();
      if (this.parent.findNewParent(this, x3, y5)) {
        this.x -= Math.floor(this.x);
        this.y -= Math.floor(this.y);
      }
    }
    let {
      x: x2,
      y: y4
    } = this;
    const [bx, by] = this.getBaseTranslation();
    x2 += bx;
    y4 += by;
    const {
      style
    } = div;
    style.left = `${(100 * x2).toFixed(2)}%`;
    style.top = `${(100 * y4).toFixed(2)}%`;
    this._onTranslating(x2, y4);
    div.scrollIntoView({
      block: "nearest"
    });
  }
  _onTranslating(x2, y4) {
  }
  _onTranslated(x2, y4) {
  }
  get _hasBeenMoved() {
    return !!this.#initialRect && (this.#initialRect[0] !== this.x || this.#initialRect[1] !== this.y);
  }
  get _hasBeenResized() {
    return !!this.#initialRect && (this.#initialRect[2] !== this.width || this.#initialRect[3] !== this.height);
  }
  getBaseTranslation() {
    const [parentWidth, parentHeight] = this.parentDimensions;
    const {
      _borderLineWidth
    } = _AnnotationEditor;
    const x2 = _borderLineWidth / parentWidth;
    const y4 = _borderLineWidth / parentHeight;
    switch (this.rotation) {
      case 90:
        return [-x2, y4];
      case 180:
        return [x2, y4];
      case 270:
        return [x2, -y4];
      default:
        return [-x2, -y4];
    }
  }
  get _mustFixPosition() {
    return true;
  }
  fixAndSetPosition(rotation = this.rotation) {
    const {
      div: {
        style
      },
      pageDimensions: [pageWidth, pageHeight]
    } = this;
    let {
      x: x2,
      y: y4,
      width,
      height
    } = this;
    width *= pageWidth;
    height *= pageHeight;
    x2 *= pageWidth;
    y4 *= pageHeight;
    if (this._mustFixPosition) {
      switch (rotation) {
        case 0:
          x2 = MathClamp(x2, 0, pageWidth - width);
          y4 = MathClamp(y4, 0, pageHeight - height);
          break;
        case 90:
          x2 = MathClamp(x2, 0, pageWidth - height);
          y4 = MathClamp(y4, width, pageHeight);
          break;
        case 180:
          x2 = MathClamp(x2, width, pageWidth);
          y4 = MathClamp(y4, height, pageHeight);
          break;
        case 270:
          x2 = MathClamp(x2, height, pageWidth);
          y4 = MathClamp(y4, 0, pageHeight - width);
          break;
      }
    }
    this.x = x2 /= pageWidth;
    this.y = y4 /= pageHeight;
    const [bx, by] = this.getBaseTranslation();
    x2 += bx;
    y4 += by;
    style.left = `${(100 * x2).toFixed(2)}%`;
    style.top = `${(100 * y4).toFixed(2)}%`;
    this.moveInDOM();
  }
  static #rotatePoint(x2, y4, angle) {
    switch (angle) {
      case 90:
        return [y4, -x2];
      case 180:
        return [-x2, -y4];
      case 270:
        return [-y4, x2];
      default:
        return [x2, y4];
    }
  }
  screenToPageTranslation(x2, y4) {
    return _AnnotationEditor.#rotatePoint(x2, y4, this.parentRotation);
  }
  pageTranslationToScreen(x2, y4) {
    return _AnnotationEditor.#rotatePoint(x2, y4, 360 - this.parentRotation);
  }
  #getRotationMatrix(rotation) {
    switch (rotation) {
      case 90: {
        const [pageWidth, pageHeight] = this.pageDimensions;
        return [0, -pageWidth / pageHeight, pageHeight / pageWidth, 0];
      }
      case 180:
        return [-1, 0, 0, -1];
      case 270: {
        const [pageWidth, pageHeight] = this.pageDimensions;
        return [0, pageWidth / pageHeight, -pageHeight / pageWidth, 0];
      }
      default:
        return [1, 0, 0, 1];
    }
  }
  get parentScale() {
    return this._uiManager.viewParameters.realScale;
  }
  get parentRotation() {
    return (this._uiManager.viewParameters.rotation + this.pageRotation) % 360;
  }
  get parentDimensions() {
    const {
      parentScale,
      pageDimensions: [pageWidth, pageHeight]
    } = this;
    return [pageWidth * parentScale, pageHeight * parentScale];
  }
  setDims() {
    const {
      div: {
        style
      },
      width,
      height
    } = this;
    style.width = `${(100 * width).toFixed(2)}%`;
    style.height = `${(100 * height).toFixed(2)}%`;
  }
  getInitialTranslation() {
    return [0, 0];
  }
  #createResizers() {
    if (this.#resizersDiv) {
      return;
    }
    this.#resizersDiv = document.createElement("div");
    this.#resizersDiv.classList.add("resizers");
    const classes = this._willKeepAspectRatio ? ["topLeft", "topRight", "bottomRight", "bottomLeft"] : ["topLeft", "topMiddle", "topRight", "middleRight", "bottomRight", "bottomMiddle", "bottomLeft", "middleLeft"];
    const signal = this._uiManager._signal;
    for (const name of classes) {
      const div = document.createElement("div");
      this.#resizersDiv.append(div);
      div.classList.add("resizer", name);
      div.setAttribute("data-resizer-name", name);
      div.addEventListener("pointerdown", this.#resizerPointerdown.bind(this, name), {
        signal
      });
      div.addEventListener("contextmenu", noContextMenu, {
        signal
      });
      div.tabIndex = -1;
    }
    this.div.prepend(this.#resizersDiv);
  }
  #resizerPointerdown(name, event) {
    event.preventDefault();
    const {
      isMac
    } = util_FeatureTest.platform;
    if (event.button !== 0 || event.ctrlKey && isMac) {
      return;
    }
    this.#altText?.toggle(false);
    const savedDraggable = this._isDraggable;
    this._isDraggable = false;
    this.#lastPointerCoords = [event.screenX, event.screenY];
    const ac = new AbortController();
    const signal = this._uiManager.combinedSignal(ac);
    this.parent.togglePointerEvents(false);
    window.addEventListener("pointermove", this.#resizerPointermove.bind(this, name), {
      passive: true,
      capture: true,
      signal
    });
    window.addEventListener("touchmove", stopEvent, {
      passive: false,
      signal
    });
    window.addEventListener("contextmenu", noContextMenu, {
      signal
    });
    this.#savedDimensions = {
      savedX: this.x,
      savedY: this.y,
      savedWidth: this.width,
      savedHeight: this.height
    };
    const savedParentCursor = this.parent.div.style.cursor;
    const savedCursor = this.div.style.cursor;
    this.div.style.cursor = this.parent.div.style.cursor = window.getComputedStyle(event.target).cursor;
    const pointerUpCallback = () => {
      ac.abort();
      this.parent.togglePointerEvents(true);
      this.#altText?.toggle(true);
      this._isDraggable = savedDraggable;
      this.parent.div.style.cursor = savedParentCursor;
      this.div.style.cursor = savedCursor;
      this.#addResizeToUndoStack();
    };
    window.addEventListener("pointerup", pointerUpCallback, {
      signal
    });
    window.addEventListener("blur", pointerUpCallback, {
      signal
    });
  }
  #resize(x2, y4, width, height) {
    this.width = width;
    this.height = height;
    this.x = x2;
    this.y = y4;
    this.setDims();
    this.fixAndSetPosition();
    this._onResized();
  }
  _onResized() {
  }
  #addResizeToUndoStack() {
    if (!this.#savedDimensions) {
      return;
    }
    const {
      savedX,
      savedY,
      savedWidth,
      savedHeight
    } = this.#savedDimensions;
    this.#savedDimensions = null;
    const newX = this.x;
    const newY = this.y;
    const newWidth = this.width;
    const newHeight = this.height;
    if (newX === savedX && newY === savedY && newWidth === savedWidth && newHeight === savedHeight) {
      return;
    }
    this.addCommands({
      cmd: this.#resize.bind(this, newX, newY, newWidth, newHeight),
      undo: this.#resize.bind(this, savedX, savedY, savedWidth, savedHeight),
      mustExec: true
    });
  }
  static _round(x2) {
    return Math.round(x2 * 1e4) / 1e4;
  }
  #resizerPointermove(name, event) {
    const [parentWidth, parentHeight] = this.parentDimensions;
    const savedX = this.x;
    const savedY = this.y;
    const savedWidth = this.width;
    const savedHeight = this.height;
    const minWidth = _AnnotationEditor.MIN_SIZE / parentWidth;
    const minHeight = _AnnotationEditor.MIN_SIZE / parentHeight;
    const rotationMatrix = this.#getRotationMatrix(this.rotation);
    const transf = (x2, y4) => [rotationMatrix[0] * x2 + rotationMatrix[2] * y4, rotationMatrix[1] * x2 + rotationMatrix[3] * y4];
    const invRotationMatrix = this.#getRotationMatrix(360 - this.rotation);
    const invTransf = (x2, y4) => [invRotationMatrix[0] * x2 + invRotationMatrix[2] * y4, invRotationMatrix[1] * x2 + invRotationMatrix[3] * y4];
    let getPoint;
    let getOpposite;
    let isDiagonal = false;
    let isHorizontal = false;
    switch (name) {
      case "topLeft":
        isDiagonal = true;
        getPoint = (w3, h7) => [0, 0];
        getOpposite = (w3, h7) => [w3, h7];
        break;
      case "topMiddle":
        getPoint = (w3, h7) => [w3 / 2, 0];
        getOpposite = (w3, h7) => [w3 / 2, h7];
        break;
      case "topRight":
        isDiagonal = true;
        getPoint = (w3, h7) => [w3, 0];
        getOpposite = (w3, h7) => [0, h7];
        break;
      case "middleRight":
        isHorizontal = true;
        getPoint = (w3, h7) => [w3, h7 / 2];
        getOpposite = (w3, h7) => [0, h7 / 2];
        break;
      case "bottomRight":
        isDiagonal = true;
        getPoint = (w3, h7) => [w3, h7];
        getOpposite = (w3, h7) => [0, 0];
        break;
      case "bottomMiddle":
        getPoint = (w3, h7) => [w3 / 2, h7];
        getOpposite = (w3, h7) => [w3 / 2, 0];
        break;
      case "bottomLeft":
        isDiagonal = true;
        getPoint = (w3, h7) => [0, h7];
        getOpposite = (w3, h7) => [w3, 0];
        break;
      case "middleLeft":
        isHorizontal = true;
        getPoint = (w3, h7) => [0, h7 / 2];
        getOpposite = (w3, h7) => [w3, h7 / 2];
        break;
    }
    const point = getPoint(savedWidth, savedHeight);
    const oppositePoint = getOpposite(savedWidth, savedHeight);
    let transfOppositePoint = transf(...oppositePoint);
    const oppositeX = _AnnotationEditor._round(savedX + transfOppositePoint[0]);
    const oppositeY = _AnnotationEditor._round(savedY + transfOppositePoint[1]);
    let ratioX = 1;
    let ratioY = 1;
    let deltaX, deltaY;
    if (!event.fromKeyboard) {
      const {
        screenX,
        screenY
      } = event;
      const [lastScreenX, lastScreenY] = this.#lastPointerCoords;
      [deltaX, deltaY] = this.screenToPageTranslation(screenX - lastScreenX, screenY - lastScreenY);
      this.#lastPointerCoords[0] = screenX;
      this.#lastPointerCoords[1] = screenY;
    } else {
      ({
        deltaX,
        deltaY
      } = event);
    }
    [deltaX, deltaY] = invTransf(deltaX / parentWidth, deltaY / parentHeight);
    if (isDiagonal) {
      const oldDiag = Math.hypot(savedWidth, savedHeight);
      ratioX = ratioY = Math.max(Math.min(Math.hypot(oppositePoint[0] - point[0] - deltaX, oppositePoint[1] - point[1] - deltaY) / oldDiag, 1 / savedWidth, 1 / savedHeight), minWidth / savedWidth, minHeight / savedHeight);
    } else if (isHorizontal) {
      ratioX = MathClamp(Math.abs(oppositePoint[0] - point[0] - deltaX), minWidth, 1) / savedWidth;
    } else {
      ratioY = MathClamp(Math.abs(oppositePoint[1] - point[1] - deltaY), minHeight, 1) / savedHeight;
    }
    const newWidth = _AnnotationEditor._round(savedWidth * ratioX);
    const newHeight = _AnnotationEditor._round(savedHeight * ratioY);
    transfOppositePoint = transf(...getOpposite(newWidth, newHeight));
    const newX = oppositeX - transfOppositePoint[0];
    const newY = oppositeY - transfOppositePoint[1];
    this.#initialRect ||= [this.x, this.y, this.width, this.height];
    this.width = newWidth;
    this.height = newHeight;
    this.x = newX;
    this.y = newY;
    this.setDims();
    this.fixAndSetPosition();
    this._onResizing();
  }
  _onResizing() {
  }
  altTextFinish() {
    this.#altText?.finish();
  }
  get toolbarButtons() {
    return null;
  }
  async addEditToolbar() {
    if (this._editToolbar || this.#isInEditMode) {
      return this._editToolbar;
    }
    this._editToolbar = new EditorToolbar(this);
    this.div.append(this._editToolbar.render());
    const {
      toolbarButtons
    } = this;
    if (toolbarButtons) {
      for (const [name, tool] of toolbarButtons) {
        await this._editToolbar.addButton(name, tool);
      }
    }
    if (!this.hasComment) {
      this._editToolbar.addButton("comment", this.addCommentButton());
    }
    this._editToolbar.addButton("delete");
    return this._editToolbar;
  }
  addCommentButtonInToolbar() {
    this._editToolbar?.addButtonBefore("comment", this.addCommentButton(), ".deleteButton");
  }
  removeCommentButtonFromToolbar() {
    this._editToolbar?.removeButton("comment");
  }
  removeEditToolbar() {
    this._editToolbar?.remove();
    this._editToolbar = null;
    this.#altText?.destroy();
  }
  addContainer(container) {
    const editToolbarDiv = this._editToolbar?.div;
    if (editToolbarDiv) {
      editToolbarDiv.before(container);
    } else {
      this.div.append(container);
    }
  }
  getClientDimensions() {
    return this.div.getBoundingClientRect();
  }
  createAltText() {
    if (!this.#altText) {
      AltText.initialize(_AnnotationEditor._l10n);
      this.#altText = new AltText(this);
      if (this.#accessibilityData) {
        this.#altText.data = this.#accessibilityData;
        this.#accessibilityData = null;
      }
    }
    return this.#altText;
  }
  get altTextData() {
    return this.#altText?.data;
  }
  set altTextData(data) {
    if (!this.#altText) {
      return;
    }
    this.#altText.data = data;
  }
  get guessedAltText() {
    return this.#altText?.guessedText;
  }
  async setGuessedAltText(text3) {
    await this.#altText?.setGuessedText(text3);
  }
  serializeAltText(isForCopying) {
    return this.#altText?.serialize(isForCopying);
  }
  hasAltText() {
    return !!this.#altText && !this.#altText.isEmpty();
  }
  hasAltTextData() {
    return this.#altText?.hasData() ?? false;
  }
  focusCommentButton() {
    this.#comment?.focusButton();
  }
  addCommentButton() {
    return this.canAddComment ? this.#comment ||= new Comment(this) : null;
  }
  addStandaloneCommentButton() {
    if (!this._uiManager.hasCommentManager()) {
      return;
    }
    if (this.#commentStandaloneButton) {
      if (this._uiManager.isEditingMode()) {
        this.#commentStandaloneButton.classList.remove("hidden");
      }
      return;
    }
    if (!this.hasComment) {
      return;
    }
    this.#commentStandaloneButton = this.#comment.renderForStandalone();
    this.div.append(this.#commentStandaloneButton);
  }
  removeStandaloneCommentButton() {
    this.#comment.removeStandaloneCommentButton();
    this.#commentStandaloneButton = null;
  }
  hideStandaloneCommentButton() {
    this.#commentStandaloneButton?.classList.add("hidden");
  }
  get comment() {
    const {
      data: {
        richText,
        text: text3,
        date,
        deleted
      }
    } = this.#comment;
    return {
      text: text3,
      richText,
      date,
      deleted,
      color: this.getNonHCMColor(),
      opacity: this.opacity ?? 1
    };
  }
  set comment(text3) {
    this.#comment ||= new Comment(this);
    this.#comment.data = text3;
    if (this.hasComment) {
      this.removeCommentButtonFromToolbar();
      this.addStandaloneCommentButton();
      this._uiManager.updateComment(this);
    } else {
      this.addCommentButtonInToolbar();
      this.removeStandaloneCommentButton();
      this._uiManager.removeComment(this);
    }
  }
  setCommentData({
    comment,
    popupRef,
    richText
  }) {
    if (!popupRef) {
      return;
    }
    this.#comment ||= new Comment(this);
    this.#comment.setInitialText(comment, richText);
    if (!this.annotationElementId) {
      return;
    }
    const storedData = this._uiManager.getAndRemoveDataFromAnnotationStorage(this.annotationElementId);
    if (storedData) {
      this.updateFromAnnotationLayer(storedData);
    }
  }
  get hasEditedComment() {
    return this.#comment?.hasBeenEdited();
  }
  get hasDeletedComment() {
    return this.#comment?.isDeleted();
  }
  get hasComment() {
    return !!this.#comment && !this.#comment.isEmpty() && !this.#comment.isDeleted();
  }
  async editComment(options) {
    this.#comment ||= new Comment(this);
    this.#comment.edit(options);
  }
  toggleComment(isSelected, visibility = void 0) {
    if (this.hasComment) {
      this._uiManager.toggleComment(this, isSelected, visibility);
    }
  }
  setSelectedCommentButton(selected) {
    this.#comment.setSelectedButton(selected);
  }
  addComment(serialized) {
    if (this.hasEditedComment) {
      const DEFAULT_POPUP_WIDTH = 180;
      const DEFAULT_POPUP_HEIGHT = 100;
      const [, , , trY] = serialized.rect;
      const [pageWidth] = this.pageDimensions;
      const [pageX] = this.pageTranslation;
      const blX = pageX + pageWidth + 1;
      const blY = trY - DEFAULT_POPUP_HEIGHT;
      const trX = blX + DEFAULT_POPUP_WIDTH;
      serialized.popup = {
        contents: this.comment.text,
        deleted: this.comment.deleted,
        rect: [blX, blY, trX, trY]
      };
    }
  }
  updateFromAnnotationLayer({
    popup: {
      contents,
      deleted
    }
  }) {
    this.#comment.data = deleted ? null : contents;
  }
  get parentBoundingClientRect() {
    return this.parent.boundingClientRect;
  }
  render() {
    const div = this.div = document.createElement("div");
    div.setAttribute("data-editor-rotation", (360 - this.rotation) % 360);
    div.className = this.name;
    div.setAttribute("id", this.id);
    div.tabIndex = this.#disabled ? -1 : 0;
    div.setAttribute("role", "application");
    if (this.defaultL10nId) {
      div.setAttribute("data-l10n-id", this.defaultL10nId);
    }
    if (!this._isVisible) {
      div.classList.add("hidden");
    }
    this.setInForeground();
    this.#addFocusListeners();
    const [parentWidth, parentHeight] = this.parentDimensions;
    if (this.parentRotation % 180 !== 0) {
      div.style.maxWidth = `${(100 * parentHeight / parentWidth).toFixed(2)}%`;
      div.style.maxHeight = `${(100 * parentWidth / parentHeight).toFixed(2)}%`;
    }
    const [tx, ty] = this.getInitialTranslation();
    this.translate(tx, ty);
    bindEvents(this, div, ["keydown", "pointerdown", "dblclick"]);
    if (this.isResizable && this._uiManager._supportsPinchToZoom) {
      this.#touchManager ||= new TouchManager({
        container: div,
        isPinchingDisabled: () => !this.isSelected,
        onPinchStart: this.#touchPinchStartCallback.bind(this),
        onPinching: this.#touchPinchCallback.bind(this),
        onPinchEnd: this.#touchPinchEndCallback.bind(this),
        signal: this._uiManager._signal
      });
    }
    this.addStandaloneCommentButton();
    this._uiManager._editorUndoBar?.hide();
    return div;
  }
  #touchPinchStartCallback() {
    this.#savedDimensions = {
      savedX: this.x,
      savedY: this.y,
      savedWidth: this.width,
      savedHeight: this.height
    };
    this.#altText?.toggle(false);
    this.parent.togglePointerEvents(false);
  }
  #touchPinchCallback(_origin, prevDistance, distance) {
    const slowDownFactor = 0.7;
    let factor = slowDownFactor * (distance / prevDistance) + 1 - slowDownFactor;
    if (factor === 1) {
      return;
    }
    const rotationMatrix = this.#getRotationMatrix(this.rotation);
    const transf = (x2, y4) => [rotationMatrix[0] * x2 + rotationMatrix[2] * y4, rotationMatrix[1] * x2 + rotationMatrix[3] * y4];
    const [parentWidth, parentHeight] = this.parentDimensions;
    const savedX = this.x;
    const savedY = this.y;
    const savedWidth = this.width;
    const savedHeight = this.height;
    const minWidth = _AnnotationEditor.MIN_SIZE / parentWidth;
    const minHeight = _AnnotationEditor.MIN_SIZE / parentHeight;
    factor = Math.max(Math.min(factor, 1 / savedWidth, 1 / savedHeight), minWidth / savedWidth, minHeight / savedHeight);
    const newWidth = _AnnotationEditor._round(savedWidth * factor);
    const newHeight = _AnnotationEditor._round(savedHeight * factor);
    if (newWidth === savedWidth && newHeight === savedHeight) {
      return;
    }
    this.#initialRect ||= [savedX, savedY, savedWidth, savedHeight];
    const transfCenterPoint = transf(savedWidth / 2, savedHeight / 2);
    const centerX = _AnnotationEditor._round(savedX + transfCenterPoint[0]);
    const centerY = _AnnotationEditor._round(savedY + transfCenterPoint[1]);
    const newTransfCenterPoint = transf(newWidth / 2, newHeight / 2);
    this.x = centerX - newTransfCenterPoint[0];
    this.y = centerY - newTransfCenterPoint[1];
    this.width = newWidth;
    this.height = newHeight;
    this.setDims();
    this.fixAndSetPosition();
    this._onResizing();
  }
  #touchPinchEndCallback() {
    this.#altText?.toggle(true);
    this.parent.togglePointerEvents(true);
    this.#addResizeToUndoStack();
  }
  pointerdown(event) {
    const {
      isMac
    } = util_FeatureTest.platform;
    if (event.button !== 0 || event.ctrlKey && isMac) {
      event.preventDefault();
      return;
    }
    this.#hasBeenClicked = true;
    if (this._isDraggable) {
      this.#setUpDragSession(event);
      return;
    }
    this.#selectOnPointerEvent(event);
  }
  #selectOnPointerEvent(event) {
    const {
      isMac
    } = util_FeatureTest.platform;
    if (event.ctrlKey && !isMac || event.shiftKey || event.metaKey && isMac) {
      this.parent.toggleSelected(this);
    } else {
      this.parent.setSelected(this);
    }
  }
  #setUpDragSession(event) {
    const {
      isSelected
    } = this;
    this._uiManager.setUpDragSession();
    let hasDraggingStarted = false;
    const ac = new AbortController();
    const signal = this._uiManager.combinedSignal(ac);
    const opts = {
      capture: true,
      passive: false,
      signal
    };
    const cancelDrag = (e9) => {
      ac.abort();
      this.#dragPointerId = null;
      this.#hasBeenClicked = false;
      if (!this._uiManager.endDragSession()) {
        this.#selectOnPointerEvent(e9);
      }
      if (hasDraggingStarted) {
        this._onStopDragging();
      }
    };
    if (isSelected) {
      this.#prevDragX = event.clientX;
      this.#prevDragY = event.clientY;
      this.#dragPointerId = event.pointerId;
      this.#dragPointerType = event.pointerType;
      window.addEventListener("pointermove", (e9) => {
        if (!hasDraggingStarted) {
          hasDraggingStarted = true;
          this._uiManager.toggleComment(this, true, false);
          this._onStartDragging();
        }
        const {
          clientX: x2,
          clientY: y4,
          pointerId
        } = e9;
        if (pointerId !== this.#dragPointerId) {
          stopEvent(e9);
          return;
        }
        const [tx, ty] = this.screenToPageTranslation(x2 - this.#prevDragX, y4 - this.#prevDragY);
        this.#prevDragX = x2;
        this.#prevDragY = y4;
        this._uiManager.dragSelectedEditors(tx, ty);
      }, opts);
      window.addEventListener("touchmove", stopEvent, opts);
      window.addEventListener("pointerdown", (e9) => {
        if (e9.pointerType === this.#dragPointerType) {
          if (this.#touchManager || e9.isPrimary) {
            cancelDrag(e9);
          }
        }
        stopEvent(e9);
      }, opts);
    }
    const pointerUpCallback = (e9) => {
      if (!this.#dragPointerId || this.#dragPointerId === e9.pointerId) {
        cancelDrag(e9);
        return;
      }
      stopEvent(e9);
    };
    window.addEventListener("pointerup", pointerUpCallback, {
      signal
    });
    window.addEventListener("blur", pointerUpCallback, {
      signal
    });
  }
  _onStartDragging() {
  }
  _onStopDragging() {
  }
  moveInDOM() {
    if (this.#moveInDOMTimeout) {
      clearTimeout(this.#moveInDOMTimeout);
    }
    this.#moveInDOMTimeout = setTimeout(() => {
      this.#moveInDOMTimeout = null;
      this.parent?.moveEditorInDOM(this);
    }, 0);
  }
  _setParentAndPosition(parent, x2, y4) {
    parent.changeParent(this);
    this.x = x2;
    this.y = y4;
    this.fixAndSetPosition();
    this._onTranslated();
  }
  getRect(tx, ty, rotation = this.rotation) {
    const scale = this.parentScale;
    const [pageWidth, pageHeight] = this.pageDimensions;
    const [pageX, pageY] = this.pageTranslation;
    const shiftX = tx / scale;
    const shiftY = ty / scale;
    const x2 = this.x * pageWidth;
    const y4 = this.y * pageHeight;
    const width = this.width * pageWidth;
    const height = this.height * pageHeight;
    switch (rotation) {
      case 0:
        return [x2 + shiftX + pageX, pageHeight - y4 - shiftY - height + pageY, x2 + shiftX + width + pageX, pageHeight - y4 - shiftY + pageY];
      case 90:
        return [x2 + shiftY + pageX, pageHeight - y4 + shiftX + pageY, x2 + shiftY + height + pageX, pageHeight - y4 + shiftX + width + pageY];
      case 180:
        return [x2 - shiftX - width + pageX, pageHeight - y4 + shiftY + pageY, x2 - shiftX + pageX, pageHeight - y4 + shiftY + height + pageY];
      case 270:
        return [x2 - shiftY - height + pageX, pageHeight - y4 - shiftX - width + pageY, x2 - shiftY + pageX, pageHeight - y4 - shiftX + pageY];
      default:
        throw new Error("Invalid rotation");
    }
  }
  getRectInCurrentCoords(rect, pageHeight) {
    const [x1, y1, x2, y22] = rect;
    const width = x2 - x1;
    const height = y22 - y1;
    switch (this.rotation) {
      case 0:
        return [x1, pageHeight - y22, width, height];
      case 90:
        return [x1, pageHeight - y1, height, width];
      case 180:
        return [x2, pageHeight - y1, width, height];
      case 270:
        return [x2, pageHeight - y22, height, width];
      default:
        throw new Error("Invalid rotation");
    }
  }
  getPDFRect() {
    return this.getRect(0, 0);
  }
  getNonHCMColor() {
    return this.color && _AnnotationEditor._colorManager.convert(this._uiManager.getNonHCMColor(this.color));
  }
  onUpdatedColor() {
    this.#comment?.onUpdatedColor();
  }
  getData() {
    const {
      comment: {
        text: str2,
        color,
        date,
        opacity,
        deleted,
        richText
      },
      uid: id,
      pageIndex,
      creationDate,
      modificationDate
    } = this;
    return {
      id,
      pageIndex,
      rect: this.getPDFRect(),
      richText,
      contentsObj: {
        str: str2
      },
      creationDate,
      modificationDate: date || modificationDate,
      popupRef: !deleted,
      color,
      opacity
    };
  }
  onceAdded(focus) {
  }
  isEmpty() {
    return false;
  }
  enableEditMode() {
    if (this.isInEditMode()) {
      return false;
    }
    this.parent.setEditingState(false);
    this.#isInEditMode = true;
    return true;
  }
  disableEditMode() {
    if (!this.isInEditMode()) {
      return false;
    }
    this.parent.setEditingState(true);
    this.#isInEditMode = false;
    return true;
  }
  isInEditMode() {
    return this.#isInEditMode;
  }
  shouldGetKeyboardEvents() {
    return this.#isResizerEnabledForKeyboard;
  }
  needsToBeRebuilt() {
    return this.div && !this.isAttachedToDOM;
  }
  get isOnScreen() {
    const {
      top,
      left,
      bottom,
      right
    } = this.getClientDimensions();
    const {
      innerHeight,
      innerWidth
    } = window;
    return left < innerWidth && right > 0 && top < innerHeight && bottom > 0;
  }
  #addFocusListeners() {
    if (this.#focusAC || !this.div) {
      return;
    }
    this.#focusAC = new AbortController();
    const signal = this._uiManager.combinedSignal(this.#focusAC);
    this.div.addEventListener("focusin", this.focusin.bind(this), {
      signal
    });
    this.div.addEventListener("focusout", this.focusout.bind(this), {
      signal
    });
  }
  rebuild() {
    this.#addFocusListeners();
  }
  rotate(_angle) {
  }
  resize() {
  }
  serializeDeleted() {
    return {
      id: this.annotationElementId,
      deleted: true,
      pageIndex: this.pageIndex,
      popupRef: this._initialData?.popupRef || ""
    };
  }
  serialize(isForCopying = false, context = null) {
    return {
      annotationType: this.mode,
      pageIndex: this.pageIndex,
      rect: this.getPDFRect(),
      rotation: this.rotation,
      structTreeParentId: this._structTreeParentId,
      popupRef: this._initialData?.popupRef || ""
    };
  }
  static async deserialize(data, parent, uiManager) {
    const editor = new this.prototype.constructor({
      parent,
      id: parent.getNextId(),
      uiManager,
      annotationElementId: data.annotationElementId,
      creationDate: data.creationDate,
      modificationDate: data.modificationDate
    });
    editor.rotation = data.rotation;
    editor.#accessibilityData = data.accessibilityData;
    editor._isCopy = data.isCopy || false;
    const [pageWidth, pageHeight] = editor.pageDimensions;
    const [x2, y4, width, height] = editor.getRectInCurrentCoords(data.rect, pageHeight);
    editor.x = x2 / pageWidth;
    editor.y = y4 / pageHeight;
    editor.width = width / pageWidth;
    editor.height = height / pageHeight;
    return editor;
  }
  get hasBeenModified() {
    return !!this.annotationElementId && (this.deleted || this.serialize() !== null);
  }
  remove() {
    this.#focusAC?.abort();
    this.#focusAC = null;
    if (!this.isEmpty()) {
      this.commit();
    }
    if (this.parent) {
      this.parent.remove(this);
    } else {
      this._uiManager.removeEditor(this);
    }
    this.hideCommentPopup();
    if (this.#moveInDOMTimeout) {
      clearTimeout(this.#moveInDOMTimeout);
      this.#moveInDOMTimeout = null;
    }
    this.#stopResizing();
    this.removeEditToolbar();
    if (this.#telemetryTimeouts) {
      for (const timeout of this.#telemetryTimeouts.values()) {
        clearTimeout(timeout);
      }
      this.#telemetryTimeouts = null;
    }
    this.parent = null;
    this.#touchManager?.destroy();
    this.#touchManager = null;
    this.#fakeAnnotation?.remove();
    this.#fakeAnnotation = null;
  }
  get isResizable() {
    return false;
  }
  makeResizable() {
    if (this.isResizable) {
      this.#createResizers();
      this.#resizersDiv.classList.remove("hidden");
    }
  }
  get toolbarPosition() {
    return null;
  }
  get commentButtonPosition() {
    return this._uiManager.direction === "ltr" ? [1, 0] : [0, 0];
  }
  get commentButtonPositionInPage() {
    const {
      commentButtonPosition: [posX, posY]
    } = this;
    const [blX, blY, trX, trY] = this.getPDFRect();
    return [_AnnotationEditor._round(blX + (trX - blX) * posX), _AnnotationEditor._round(blY + (trY - blY) * (1 - posY))];
  }
  get commentButtonColor() {
    return this._uiManager.makeCommentColor(this.getNonHCMColor(), this.opacity);
  }
  get commentPopupPosition() {
    return this.#comment.commentPopupPositionInLayer;
  }
  set commentPopupPosition(pos) {
    this.#comment.commentPopupPositionInLayer = pos;
  }
  hasDefaultPopupPosition() {
    return this.#comment.hasDefaultPopupPosition();
  }
  get commentButtonWidth() {
    return this.#comment.commentButtonWidth;
  }
  get elementBeforePopup() {
    return this.div;
  }
  setCommentButtonStates(options) {
    this.#comment?.setCommentButtonStates(options);
  }
  keydown(event) {
    if (!this.isResizable || event.target !== this.div || event.key !== "Enter") {
      return;
    }
    this._uiManager.setSelected(this);
    this.#savedDimensions = {
      savedX: this.x,
      savedY: this.y,
      savedWidth: this.width,
      savedHeight: this.height
    };
    const children = this.#resizersDiv.children;
    if (!this.#allResizerDivs) {
      this.#allResizerDivs = Array.from(children);
      const boundResizerKeydown = this.#resizerKeydown.bind(this);
      const boundResizerBlur = this.#resizerBlur.bind(this);
      const signal = this._uiManager._signal;
      for (const div of this.#allResizerDivs) {
        const name = div.getAttribute("data-resizer-name");
        div.setAttribute("role", "spinbutton");
        div.addEventListener("keydown", boundResizerKeydown, {
          signal
        });
        div.addEventListener("blur", boundResizerBlur, {
          signal
        });
        div.addEventListener("focus", this.#resizerFocus.bind(this, name), {
          signal
        });
        div.setAttribute("data-l10n-id", _AnnotationEditor._l10nResizer[name]);
      }
    }
    const first = this.#allResizerDivs[0];
    let firstPosition = 0;
    for (const div of children) {
      if (div === first) {
        break;
      }
      firstPosition++;
    }
    const nextFirstPosition = (360 - this.rotation + this.parentRotation) % 360 / 90 * (this.#allResizerDivs.length / 4);
    if (nextFirstPosition !== firstPosition) {
      if (nextFirstPosition < firstPosition) {
        for (let i8 = 0; i8 < firstPosition - nextFirstPosition; i8++) {
          this.#resizersDiv.append(this.#resizersDiv.firstChild);
        }
      } else if (nextFirstPosition > firstPosition) {
        for (let i8 = 0; i8 < nextFirstPosition - firstPosition; i8++) {
          this.#resizersDiv.firstChild.before(this.#resizersDiv.lastChild);
        }
      }
      let i7 = 0;
      for (const child of children) {
        const div = this.#allResizerDivs[i7++];
        const name = div.getAttribute("data-resizer-name");
        child.setAttribute("data-l10n-id", _AnnotationEditor._l10nResizer[name]);
      }
    }
    this.#setResizerTabIndex(0);
    this.#isResizerEnabledForKeyboard = true;
    this.#resizersDiv.firstChild.focus({
      focusVisible: true
    });
    event.preventDefault();
    event.stopImmediatePropagation();
  }
  #resizerKeydown(event) {
    _AnnotationEditor._resizerKeyboardManager.exec(this, event);
  }
  #resizerBlur(event) {
    if (this.#isResizerEnabledForKeyboard && event.relatedTarget?.parentNode !== this.#resizersDiv) {
      this.#stopResizing();
    }
  }
  #resizerFocus(name) {
    this.#focusedResizerName = this.#isResizerEnabledForKeyboard ? name : "";
  }
  #setResizerTabIndex(value) {
    if (!this.#allResizerDivs) {
      return;
    }
    for (const div of this.#allResizerDivs) {
      div.tabIndex = value;
    }
  }
  _resizeWithKeyboard(x2, y4) {
    if (!this.#isResizerEnabledForKeyboard) {
      return;
    }
    this.#resizerPointermove(this.#focusedResizerName, {
      deltaX: x2,
      deltaY: y4,
      fromKeyboard: true
    });
  }
  #stopResizing() {
    this.#isResizerEnabledForKeyboard = false;
    this.#setResizerTabIndex(-1);
    this.#addResizeToUndoStack();
  }
  _stopResizingWithKeyboard() {
    this.#stopResizing();
    this.div.focus();
  }
  select() {
    if (this.isSelected && this._editToolbar) {
      this._editToolbar.show();
      return;
    }
    this.isSelected = true;
    this.makeResizable();
    this.div?.classList.add("selectedEditor");
    if (!this._editToolbar) {
      this.addEditToolbar().then(() => {
        if (this.div?.classList.contains("selectedEditor")) {
          this._editToolbar?.show();
        }
      });
      return;
    }
    this._editToolbar?.show();
    this.#altText?.toggleAltTextBadge(false);
  }
  focus() {
    if (this.div && !this.div.contains(document.activeElement)) {
      setTimeout(() => this.div?.focus({
        preventScroll: true
      }), 0);
    }
  }
  unselect() {
    if (!this.isSelected) {
      return;
    }
    this.isSelected = false;
    this.#resizersDiv?.classList.add("hidden");
    this.div?.classList.remove("selectedEditor");
    if (this.div?.contains(document.activeElement)) {
      this._uiManager.currentLayer.div.focus({
        preventScroll: true
      });
    }
    this._editToolbar?.hide();
    this.#altText?.toggleAltTextBadge(true);
    this.hideCommentPopup();
  }
  hideCommentPopup() {
    if (this.hasComment) {
      this._uiManager.toggleComment(null);
    }
  }
  updateParams(type, value) {
  }
  disableEditing() {
  }
  enableEditing() {
  }
  get canChangeContent() {
    return false;
  }
  enterInEditMode() {
    if (!this.canChangeContent) {
      return;
    }
    this.enableEditMode();
    this.div.focus();
  }
  dblclick(event) {
    if (event.target.nodeName === "BUTTON") {
      return;
    }
    this.enterInEditMode();
    this.parent.updateToolbar({
      mode: this.constructor._editorType,
      editId: this.uid
    });
  }
  getElementForAltText() {
    return this.div;
  }
  get contentDiv() {
    return this.div;
  }
  get isEditing() {
    return this.#isEditing;
  }
  set isEditing(value) {
    this.#isEditing = value;
    if (!this.parent) {
      return;
    }
    if (value) {
      this.parent.setSelected(this);
      this.parent.setActiveEditor(this);
    } else {
      this.parent.setActiveEditor(null);
    }
  }
  static get MIN_SIZE() {
    return 16;
  }
  static canCreateNewEmptyEditor() {
    return true;
  }
  get telemetryInitialData() {
    return {
      action: "added"
    };
  }
  get telemetryFinalData() {
    return null;
  }
  _reportTelemetry(data, mustWait = false) {
    if (mustWait) {
      this.#telemetryTimeouts ||= /* @__PURE__ */ new Map();
      const {
        action
      } = data;
      let timeout = this.#telemetryTimeouts.get(action);
      if (timeout) {
        clearTimeout(timeout);
      }
      timeout = setTimeout(() => {
        this._reportTelemetry(data);
        this.#telemetryTimeouts.delete(action);
        if (this.#telemetryTimeouts.size === 0) {
          this.#telemetryTimeouts = null;
        }
      }, _AnnotationEditor._telemetryTimeout);
      this.#telemetryTimeouts.set(action, timeout);
      return;
    }
    data.type ||= this.editorType;
    this._uiManager._eventBus.dispatch("reporttelemetry", {
      source: this,
      details: {
        type: "editing",
        data
      }
    });
  }
  show(visible = this._isVisible) {
    this.div.classList.toggle("hidden", !visible);
    this._isVisible = visible;
  }
  enable() {
    if (this.div) {
      this.div.tabIndex = 0;
    }
    this.#disabled = false;
  }
  disable() {
    if (this.div) {
      this.div.tabIndex = -1;
    }
    this.#disabled = true;
  }
  updateFakeAnnotationElement(annotationLayer) {
    if (!this.#fakeAnnotation && !this.deleted) {
      this.#fakeAnnotation = annotationLayer.addFakeAnnotation(this);
      return;
    }
    if (this.deleted) {
      this.#fakeAnnotation.remove();
      this.#fakeAnnotation = null;
      return;
    }
    if (this.hasEditedComment || this._hasBeenMoved || this._hasBeenResized) {
      this.#fakeAnnotation.updateEdited({
        rect: this.getPDFRect(),
        popup: this.comment
      });
    }
  }
  renderAnnotationElement(annotation) {
    if (this.deleted) {
      annotation.hide();
      return null;
    }
    let content = annotation.container.querySelector(".annotationContent");
    if (!content) {
      content = document.createElement("div");
      content.classList.add("annotationContent", this.editorType);
      annotation.container.prepend(content);
    } else if (content.nodeName === "CANVAS") {
      const canvas = content;
      content = document.createElement("div");
      content.classList.add("annotationContent", this.editorType);
      canvas.before(content);
    }
    return content;
  }
  resetAnnotationElement(annotation) {
    const {
      firstChild
    } = annotation.container;
    if (firstChild?.nodeName === "DIV" && firstChild.classList.contains("annotationContent")) {
      firstChild.remove();
    }
  }
};
var FakeEditor = class extends AnnotationEditor {
  constructor(params) {
    super(params);
    this.annotationElementId = params.annotationElementId;
    this.deleted = true;
  }
  serialize() {
    return this.serializeDeleted();
  }
};
var SEED = 3285377520;
var MASK_HIGH = 4294901760;
var MASK_LOW = 65535;
var MurmurHash3_64 = class {
  constructor(seed) {
    this.h1 = seed ? seed & 4294967295 : SEED;
    this.h2 = seed ? seed & 4294967295 : SEED;
  }
  update(input) {
    let data, length;
    if (typeof input === "string") {
      data = new Uint8Array(input.length * 2);
      length = 0;
      for (let i7 = 0, ii = input.length; i7 < ii; i7++) {
        const code = input.charCodeAt(i7);
        if (code <= 255) {
          data[length++] = code;
        } else {
          data[length++] = code >>> 8;
          data[length++] = code & 255;
        }
      }
    } else if (ArrayBuffer.isView(input)) {
      data = input.slice();
      length = data.byteLength;
    } else {
      throw new Error("Invalid data format, must be a string or TypedArray.");
    }
    const blockCounts = length >> 2;
    const tailLength = length - blockCounts * 4;
    const dataUint32 = new Uint32Array(data.buffer, 0, blockCounts);
    let k1 = 0, k2 = 0;
    let h1 = this.h1, h22 = this.h2;
    const C1 = 3432918353, C22 = 461845907;
    const C1_LOW = C1 & MASK_LOW, C2_LOW = C22 & MASK_LOW;
    for (let i7 = 0; i7 < blockCounts; i7++) {
      if (i7 & 1) {
        k1 = dataUint32[i7];
        k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW;
        k1 = k1 << 15 | k1 >>> 17;
        k1 = k1 * C22 & MASK_HIGH | k1 * C2_LOW & MASK_LOW;
        h1 ^= k1;
        h1 = h1 << 13 | h1 >>> 19;
        h1 = h1 * 5 + 3864292196;
      } else {
        k2 = dataUint32[i7];
        k2 = k2 * C1 & MASK_HIGH | k2 * C1_LOW & MASK_LOW;
        k2 = k2 << 15 | k2 >>> 17;
        k2 = k2 * C22 & MASK_HIGH | k2 * C2_LOW & MASK_LOW;
        h22 ^= k2;
        h22 = h22 << 13 | h22 >>> 19;
        h22 = h22 * 5 + 3864292196;
      }
    }
    k1 = 0;
    switch (tailLength) {
      case 3:
        k1 ^= data[blockCounts * 4 + 2] << 16;
      case 2:
        k1 ^= data[blockCounts * 4 + 1] << 8;
      case 1:
        k1 ^= data[blockCounts * 4];
        k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW;
        k1 = k1 << 15 | k1 >>> 17;
        k1 = k1 * C22 & MASK_HIGH | k1 * C2_LOW & MASK_LOW;
        if (blockCounts & 1) {
          h1 ^= k1;
        } else {
          h22 ^= k1;
        }
    }
    this.h1 = h1;
    this.h2 = h22;
  }
  hexdigest() {
    let h1 = this.h1, h22 = this.h2;
    h1 ^= h22 >>> 1;
    h1 = h1 * 3981806797 & MASK_HIGH | h1 * 36045 & MASK_LOW;
    h22 = h22 * 4283543511 & MASK_HIGH | ((h22 << 16 | h1 >>> 16) * 2950163797 & MASK_HIGH) >>> 16;
    h1 ^= h22 >>> 1;
    h1 = h1 * 444984403 & MASK_HIGH | h1 * 60499 & MASK_LOW;
    h22 = h22 * 3301882366 & MASK_HIGH | ((h22 << 16 | h1 >>> 16) * 3120437893 & MASK_HIGH) >>> 16;
    h1 ^= h22 >>> 1;
    return (h1 >>> 0).toString(16).padStart(8, "0") + (h22 >>> 0).toString(16).padStart(8, "0");
  }
};
var SerializableEmpty = Object.freeze({
  map: null,
  hash: "",
  transfer: void 0
});
var AnnotationStorage = class {
  #modified = false;
  #modifiedIds = null;
  #editorsMap = null;
  #storage = /* @__PURE__ */ new Map();
  constructor() {
    this.onSetModified = null;
    this.onResetModified = null;
    this.onAnnotationEditor = null;
  }
  getValue(key, defaultValue) {
    const value = this.#storage.get(key);
    if (value === void 0) {
      return defaultValue;
    }
    return Object.assign(defaultValue, value);
  }
  getRawValue(key) {
    return this.#storage.get(key);
  }
  remove(key) {
    const storedValue = this.#storage.get(key);
    if (storedValue === void 0) {
      return;
    }
    if (storedValue instanceof AnnotationEditor) {
      this.#editorsMap.delete(storedValue.annotationElementId);
    }
    this.#storage.delete(key);
    if (this.#storage.size === 0) {
      this.resetModified();
    }
    if (typeof this.onAnnotationEditor === "function") {
      for (const value of this.#storage.values()) {
        if (value instanceof AnnotationEditor) {
          return;
        }
      }
      this.onAnnotationEditor(null);
    }
  }
  setValue(key, value) {
    const obj = this.#storage.get(key);
    let modified = false;
    if (obj !== void 0) {
      for (const [entry, val2] of Object.entries(value)) {
        if (obj[entry] !== val2) {
          modified = true;
          obj[entry] = val2;
        }
      }
    } else {
      modified = true;
      this.#storage.set(key, value);
    }
    if (modified) {
      this.#setModified();
    }
    if (value instanceof AnnotationEditor) {
      (this.#editorsMap ||= /* @__PURE__ */ new Map()).set(value.annotationElementId, value);
      if (typeof this.onAnnotationEditor === "function") {
        this.onAnnotationEditor(value.constructor._type);
      }
    }
  }
  has(key) {
    return this.#storage.has(key);
  }
  get size() {
    return this.#storage.size;
  }
  #setModified() {
    if (!this.#modified) {
      this.#modified = true;
      if (typeof this.onSetModified === "function") {
        this.onSetModified();
      }
    }
  }
  resetModified() {
    if (this.#modified) {
      this.#modified = false;
      if (typeof this.onResetModified === "function") {
        this.onResetModified();
      }
    }
  }
  get print() {
    return new PrintAnnotationStorage(this);
  }
  get serializable() {
    if (this.#storage.size === 0) {
      return SerializableEmpty;
    }
    const map = /* @__PURE__ */ new Map(), hash = new MurmurHash3_64(), transfer = [];
    const context = /* @__PURE__ */ Object.create(null);
    let hasBitmap = false;
    for (const [key, val2] of this.#storage) {
      const serialized = val2 instanceof AnnotationEditor ? val2.serialize(false, context) : val2;
      if (serialized) {
        map.set(key, serialized);
        hash.update(`${key}:${JSON.stringify(serialized)}`);
        hasBitmap ||= !!serialized.bitmap;
      }
    }
    if (hasBitmap) {
      for (const value of map.values()) {
        if (value.bitmap) {
          transfer.push(value.bitmap);
        }
      }
    }
    return map.size > 0 ? {
      map,
      hash: hash.hexdigest(),
      transfer
    } : SerializableEmpty;
  }
  get editorStats() {
    let stats = null;
    const typeToEditor = /* @__PURE__ */ new Map();
    let numberOfEditedComments = 0;
    let numberOfDeletedComments = 0;
    for (const value of this.#storage.values()) {
      if (!(value instanceof AnnotationEditor)) {
        if (value.popup) {
          if (value.popup.deleted) {
            numberOfDeletedComments += 1;
          } else {
            numberOfEditedComments += 1;
          }
        }
        continue;
      }
      if (value.isCommentDeleted) {
        numberOfDeletedComments += 1;
      } else if (value.hasEditedComment) {
        numberOfEditedComments += 1;
      }
      const editorStats = value.telemetryFinalData;
      if (!editorStats) {
        continue;
      }
      const {
        type
      } = editorStats;
      if (!typeToEditor.has(type)) {
        typeToEditor.set(type, Object.getPrototypeOf(value).constructor);
      }
      stats ||= /* @__PURE__ */ Object.create(null);
      const map = stats[type] ||= /* @__PURE__ */ new Map();
      for (const [key, val2] of Object.entries(editorStats)) {
        if (key === "type") {
          continue;
        }
        let counters = map.get(key);
        if (!counters) {
          counters = /* @__PURE__ */ new Map();
          map.set(key, counters);
        }
        const count = counters.get(val2) ?? 0;
        counters.set(val2, count + 1);
      }
    }
    if (numberOfDeletedComments > 0 || numberOfEditedComments > 0) {
      stats ||= /* @__PURE__ */ Object.create(null);
      stats.comments = {
        deleted: numberOfDeletedComments,
        edited: numberOfEditedComments
      };
    }
    if (!stats) {
      return null;
    }
    for (const [type, editor] of typeToEditor) {
      stats[type] = editor.computeTelemetryFinalData(stats[type]);
    }
    return stats;
  }
  resetModifiedIds() {
    this.#modifiedIds = null;
  }
  updateEditor(annotationId, data) {
    const value = this.#editorsMap?.get(annotationId);
    if (value) {
      value.updateFromAnnotationLayer(data);
      return true;
    }
    return false;
  }
  getEditor(annotationId) {
    return this.#editorsMap?.get(annotationId) || null;
  }
  get modifiedIds() {
    if (this.#modifiedIds) {
      return this.#modifiedIds;
    }
    const ids = [];
    if (this.#editorsMap) {
      for (const value of this.#editorsMap.values()) {
        if (!value.serialize()) {
          continue;
        }
        ids.push(value.annotationElementId);
      }
    }
    return this.#modifiedIds = {
      ids: new Set(ids),
      hash: ids.join(",")
    };
  }
  [Symbol.iterator]() {
    return this.#storage.entries();
  }
};
var PrintAnnotationStorage = class extends AnnotationStorage {
  #serializable;
  constructor(parent) {
    super();
    const {
      map,
      hash,
      transfer
    } = parent.serializable;
    const clone = structuredClone(map, transfer ? {
      transfer
    } : null);
    this.#serializable = {
      map: clone,
      hash,
      transfer
    };
  }
  get print() {
    unreachable("Should not call PrintAnnotationStorage.print");
  }
  get serializable() {
    return this.#serializable;
  }
  get modifiedIds() {
    return shadow(this, "modifiedIds", {
      ids: /* @__PURE__ */ new Set(),
      hash: ""
    });
  }
};
var FontLoader = class {
  #systemFonts = /* @__PURE__ */ new Set();
  constructor({
    ownerDocument = globalThis.document,
    styleElement = null
  }) {
    this._document = ownerDocument;
    this.nativeFontFaces = /* @__PURE__ */ new Set();
    this.styleElement = null;
    this.loadingRequests = [];
    this.loadTestFontId = 0;
  }
  addNativeFontFace(nativeFontFace) {
    this.nativeFontFaces.add(nativeFontFace);
    this._document.fonts.add(nativeFontFace);
  }
  removeNativeFontFace(nativeFontFace) {
    this.nativeFontFaces.delete(nativeFontFace);
    this._document.fonts.delete(nativeFontFace);
  }
  insertRule(rule) {
    if (!this.styleElement) {
      this.styleElement = this._document.createElement("style");
      this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement);
    }
    const styleSheet = this.styleElement.sheet;
    styleSheet.insertRule(rule, styleSheet.cssRules.length);
  }
  clear() {
    for (const nativeFontFace of this.nativeFontFaces) {
      this._document.fonts.delete(nativeFontFace);
    }
    this.nativeFontFaces.clear();
    this.#systemFonts.clear();
    if (this.styleElement) {
      this.styleElement.remove();
      this.styleElement = null;
    }
  }
  async loadSystemFont({
    systemFontInfo: info2,
    disableFontFace,
    _inspectFont
  }) {
    if (!info2 || this.#systemFonts.has(info2.loadedName)) {
      return;
    }
    assert(!disableFontFace, "loadSystemFont shouldn't be called when `disableFontFace` is set.");
    if (this.isFontLoadingAPISupported) {
      const {
        loadedName,
        src,
        style
      } = info2;
      const fontFace = new FontFace(loadedName, src, style);
      this.addNativeFontFace(fontFace);
      try {
        await fontFace.load();
        this.#systemFonts.add(loadedName);
        _inspectFont?.(info2);
      } catch {
        warn(`Cannot load system font: ${info2.baseFontName}, installing it could help to improve PDF rendering.`);
        this.removeNativeFontFace(fontFace);
      }
      return;
    }
    unreachable("Not implemented: loadSystemFont without the Font Loading API.");
  }
  async bind(font) {
    if (font.attached || font.missingFile && !font.systemFontInfo) {
      return;
    }
    font.attached = true;
    if (font.systemFontInfo) {
      await this.loadSystemFont(font);
      return;
    }
    if (this.isFontLoadingAPISupported) {
      const nativeFontFace = font.createNativeFontFace();
      if (nativeFontFace) {
        this.addNativeFontFace(nativeFontFace);
        try {
          await nativeFontFace.loaded;
        } catch (ex) {
          warn(`Failed to load font '${nativeFontFace.family}': '${ex}'.`);
          font.disableFontFace = true;
          throw ex;
        }
      }
      return;
    }
    const rule = font.createFontFaceRule();
    if (rule) {
      this.insertRule(rule);
      if (this.isSyncFontLoadingSupported) {
        return;
      }
      await new Promise((resolve) => {
        const request = this._queueLoadingCallback(resolve);
        this._prepareFontLoadEvent(font, request);
      });
    }
  }
  get isFontLoadingAPISupported() {
    const hasFonts = !!this._document?.fonts;
    return shadow(this, "isFontLoadingAPISupported", hasFonts);
  }
  get isSyncFontLoadingSupported() {
    return shadow(this, "isSyncFontLoadingSupported", isNodeJS || util_FeatureTest.platform.isFirefox);
  }
  _queueLoadingCallback(callback) {
    function completeRequest() {
      assert(!request.done, "completeRequest() cannot be called twice.");
      request.done = true;
      while (loadingRequests.length > 0 && loadingRequests[0].done) {
        const otherRequest = loadingRequests.shift();
        setTimeout(otherRequest.callback, 0);
      }
    }
    const {
      loadingRequests
    } = this;
    const request = {
      done: false,
      complete: completeRequest,
      callback
    };
    loadingRequests.push(request);
    return request;
  }
  get _loadTestFont() {
    const testFont = atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==");
    return shadow(this, "_loadTestFont", testFont);
  }
  _prepareFontLoadEvent(font, request) {
    function int32(data2, offset) {
      return data2.charCodeAt(offset) << 24 | data2.charCodeAt(offset + 1) << 16 | data2.charCodeAt(offset + 2) << 8 | data2.charCodeAt(offset + 3) & 255;
    }
    function spliceString(s6, offset, remove, insert) {
      const chunk1 = s6.substring(0, offset);
      const chunk2 = s6.substring(offset + remove);
      return chunk1 + insert + chunk2;
    }
    let i7, ii;
    const canvas = this._document.createElement("canvas");
    canvas.width = 1;
    canvas.height = 1;
    const ctx = canvas.getContext("2d");
    let called = 0;
    function isFontReady(name, callback) {
      if (++called > 30) {
        warn("Load test font never loaded.");
        callback();
        return;
      }
      ctx.font = "30px " + name;
      ctx.fillText(".", 0, 20);
      const imageData = ctx.getImageData(0, 0, 1, 1);
      if (imageData.data[3] > 0) {
        callback();
        return;
      }
      setTimeout(isFontReady.bind(null, name, callback));
    }
    const loadTestFontId = `lt${Date.now()}${this.loadTestFontId++}`;
    let data = this._loadTestFont;
    const COMMENT_OFFSET = 976;
    data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId);
    const CFF_CHECKSUM_OFFSET = 16;
    const XXXX_VALUE = 1482184792;
    let checksum = int32(data, CFF_CHECKSUM_OFFSET);
    for (i7 = 0, ii = loadTestFontId.length - 3; i7 < ii; i7 += 4) {
      checksum = checksum - XXXX_VALUE + int32(loadTestFontId, i7) | 0;
    }
    if (i7 < loadTestFontId.length) {
      checksum = checksum - XXXX_VALUE + int32(loadTestFontId + "XXX", i7) | 0;
    }
    data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum));
    const url = `url(data:font/opentype;base64,${btoa(data)});`;
    const rule = `@font-face {font-family:"${loadTestFontId}";src:${url}}`;
    this.insertRule(rule);
    const div = this._document.createElement("div");
    div.style.visibility = "hidden";
    div.style.width = div.style.height = "10px";
    div.style.position = "absolute";
    div.style.top = div.style.left = "0px";
    for (const name of [font.loadedName, loadTestFontId]) {
      const span = this._document.createElement("span");
      span.textContent = "Hi";
      span.style.fontFamily = name;
      div.append(span);
    }
    this._document.body.append(div);
    isFontReady(loadTestFontId, () => {
      div.remove();
      request.complete();
    });
  }
};
var FontFaceObject = class {
  #fontData;
  constructor(translatedData, inspectFont = null, extra, charProcOperatorList) {
    this.compiledGlyphs = /* @__PURE__ */ Object.create(null);
    this.#fontData = translatedData;
    this._inspectFont = inspectFont;
    if (extra) {
      Object.assign(this, extra);
    }
    if (charProcOperatorList) {
      this.charProcOperatorList = charProcOperatorList;
    }
  }
  createNativeFontFace() {
    if (!this.data || this.disableFontFace) {
      return null;
    }
    let nativeFontFace;
    if (!this.cssFontInfo) {
      nativeFontFace = new FontFace(this.loadedName, this.data, {});
    } else {
      const css2 = {
        weight: this.cssFontInfo.fontWeight
      };
      if (this.cssFontInfo.italicAngle) {
        css2.style = `oblique ${this.cssFontInfo.italicAngle}deg`;
      }
      nativeFontFace = new FontFace(this.cssFontInfo.fontFamily, this.data, css2);
    }
    this._inspectFont?.(this);
    return nativeFontFace;
  }
  createFontFaceRule() {
    if (!this.data || this.disableFontFace) {
      return null;
    }
    const url = `url(data:${this.mimetype};base64,${toBase64Util(this.data)});`;
    let rule;
    if (!this.cssFontInfo) {
      rule = `@font-face {font-family:"${this.loadedName}";src:${url}}`;
    } else {
      let css2 = `font-weight: ${this.cssFontInfo.fontWeight};`;
      if (this.cssFontInfo.italicAngle) {
        css2 += `font-style: oblique ${this.cssFontInfo.italicAngle}deg;`;
      }
      rule = `@font-face {font-family:"${this.cssFontInfo.fontFamily}";${css2}src:${url}}`;
    }
    this._inspectFont?.(this, url);
    return rule;
  }
  getPathGenerator(objs, character) {
    if (this.compiledGlyphs[character] !== void 0) {
      return this.compiledGlyphs[character];
    }
    const objId = this.loadedName + "_path_" + character;
    let cmds;
    try {
      cmds = objs.get(objId);
    } catch (ex) {
      warn(`getPathGenerator - ignoring character: "${ex}".`);
    }
    const path6 = makePathFromDrawOPS(cmds);
    if (!this.fontExtraProperties) {
      objs.delete(objId);
    }
    return this.compiledGlyphs[character] = path6;
  }
  get black() {
    return this.#fontData.black;
  }
  get bold() {
    return this.#fontData.bold;
  }
  get disableFontFace() {
    return this.#fontData.disableFontFace ?? false;
  }
  get fontExtraProperties() {
    return this.#fontData.fontExtraProperties ?? false;
  }
  get isInvalidPDFjsFont() {
    return this.#fontData.isInvalidPDFjsFont;
  }
  get isType3Font() {
    return this.#fontData.isType3Font;
  }
  get italic() {
    return this.#fontData.italic;
  }
  get missingFile() {
    return this.#fontData.missingFile;
  }
  get remeasure() {
    return this.#fontData.remeasure;
  }
  get vertical() {
    return this.#fontData.vertical;
  }
  get ascent() {
    return this.#fontData.ascent;
  }
  get defaultWidth() {
    return this.#fontData.defaultWidth;
  }
  get descent() {
    return this.#fontData.descent;
  }
  get bbox() {
    return this.#fontData.bbox;
  }
  get fontMatrix() {
    return this.#fontData.fontMatrix;
  }
  get fallbackName() {
    return this.#fontData.fallbackName;
  }
  get loadedName() {
    return this.#fontData.loadedName;
  }
  get mimetype() {
    return this.#fontData.mimetype;
  }
  get name() {
    return this.#fontData.name;
  }
  get data() {
    return this.#fontData.data;
  }
  clearData() {
    this.#fontData.clearData();
  }
  get cssFontInfo() {
    return this.#fontData.cssFontInfo;
  }
  get systemFontInfo() {
    return this.#fontData.systemFontInfo;
  }
  get defaultVMetrics() {
    return this.#fontData.defaultVMetrics;
  }
};
var CssFontInfo = class _CssFontInfo {
  #buffer;
  #view;
  #decoder;
  static strings = ["fontFamily", "fontWeight", "italicAngle"];
  static write(info2) {
    const encoder = new TextEncoder();
    const encodedStrings = {};
    let stringsLength = 0;
    for (const prop of _CssFontInfo.strings) {
      const encoded = encoder.encode(info2[prop]);
      encodedStrings[prop] = encoded;
      stringsLength += 4 + encoded.length;
    }
    const buffer = new ArrayBuffer(stringsLength);
    const data = new Uint8Array(buffer);
    const view = new DataView(buffer);
    let offset = 0;
    for (const prop of _CssFontInfo.strings) {
      const encoded = encodedStrings[prop];
      const length = encoded.length;
      view.setUint32(offset, length);
      data.set(encoded, offset + 4);
      offset += 4 + length;
    }
    assert(offset === buffer.byteLength, "CssFontInfo.write: Buffer overflow");
    return buffer;
  }
  constructor(buffer) {
    this.#buffer = buffer;
    this.#view = new DataView(this.#buffer);
    this.#decoder = new TextDecoder();
  }
  #readString(index) {
    assert(index < _CssFontInfo.strings.length, "Invalid string index");
    let offset = 0;
    for (let i7 = 0; i7 < index; i7++) {
      offset += this.#view.getUint32(offset) + 4;
    }
    const length = this.#view.getUint32(offset);
    return this.#decoder.decode(new Uint8Array(this.#buffer, offset + 4, length));
  }
  get fontFamily() {
    return this.#readString(0);
  }
  get fontWeight() {
    return this.#readString(1);
  }
  get italicAngle() {
    return this.#readString(2);
  }
};
var SystemFontInfo = class _SystemFontInfo {
  #buffer;
  #view;
  #decoder;
  static strings = ["css", "loadedName", "baseFontName", "src"];
  static write(info2) {
    const encoder = new TextEncoder();
    const encodedStrings = {};
    let stringsLength = 0;
    for (const prop of _SystemFontInfo.strings) {
      const encoded = encoder.encode(info2[prop]);
      encodedStrings[prop] = encoded;
      stringsLength += 4 + encoded.length;
    }
    stringsLength += 4;
    let encodedStyleStyle, encodedStyleWeight, lengthEstimate = 1 + stringsLength;
    if (info2.style) {
      encodedStyleStyle = encoder.encode(info2.style.style);
      encodedStyleWeight = encoder.encode(info2.style.weight);
      lengthEstimate += 4 + encodedStyleStyle.length + 4 + encodedStyleWeight.length;
    }
    const buffer = new ArrayBuffer(lengthEstimate);
    const data = new Uint8Array(buffer);
    const view = new DataView(buffer);
    let offset = 0;
    view.setUint8(offset++, info2.guessFallback ? 1 : 0);
    view.setUint32(offset, 0);
    offset += 4;
    stringsLength = 0;
    for (const prop of _SystemFontInfo.strings) {
      const encoded = encodedStrings[prop];
      const length = encoded.length;
      stringsLength += 4 + length;
      view.setUint32(offset, length);
      data.set(encoded, offset + 4);
      offset += 4 + length;
    }
    view.setUint32(offset - stringsLength - 4, stringsLength);
    if (info2.style) {
      view.setUint32(offset, encodedStyleStyle.length);
      data.set(encodedStyleStyle, offset + 4);
      offset += 4 + encodedStyleStyle.length;
      view.setUint32(offset, encodedStyleWeight.length);
      data.set(encodedStyleWeight, offset + 4);
      offset += 4 + encodedStyleWeight.length;
    }
    assert(offset <= buffer.byteLength, "SubstitionInfo.write: Buffer overflow");
    return buffer.transferToFixedLength(offset);
  }
  constructor(buffer) {
    this.#buffer = buffer;
    this.#view = new DataView(this.#buffer);
    this.#decoder = new TextDecoder();
  }
  get guessFallback() {
    return this.#view.getUint8(0) !== 0;
  }
  #readString(index) {
    assert(index < _SystemFontInfo.strings.length, "Invalid string index");
    let offset = 5;
    for (let i7 = 0; i7 < index; i7++) {
      offset += this.#view.getUint32(offset) + 4;
    }
    const length = this.#view.getUint32(offset);
    return this.#decoder.decode(new Uint8Array(this.#buffer, offset + 4, length));
  }
  get css() {
    return this.#readString(0);
  }
  get loadedName() {
    return this.#readString(1);
  }
  get baseFontName() {
    return this.#readString(2);
  }
  get src() {
    return this.#readString(3);
  }
  get style() {
    let offset = 1;
    offset += 4 + this.#view.getUint32(offset);
    const styleLength = this.#view.getUint32(offset);
    const style = this.#decoder.decode(new Uint8Array(this.#buffer, offset + 4, styleLength));
    offset += 4 + styleLength;
    const weightLength = this.#view.getUint32(offset);
    const weight = this.#decoder.decode(new Uint8Array(this.#buffer, offset + 4, weightLength));
    return {
      style,
      weight
    };
  }
};
var FontInfo = class _FontInfo {
  static bools = ["black", "bold", "disableFontFace", "fontExtraProperties", "isInvalidPDFjsFont", "isType3Font", "italic", "missingFile", "remeasure", "vertical"];
  static numbers = ["ascent", "defaultWidth", "descent"];
  static strings = ["fallbackName", "loadedName", "mimetype", "name"];
  static #OFFSET_NUMBERS = Math.ceil(this.bools.length * 2 / 8);
  static #OFFSET_BBOX = this.#OFFSET_NUMBERS + this.numbers.length * 8;
  static #OFFSET_FONT_MATRIX = this.#OFFSET_BBOX + 1 + 2 * 4;
  static #OFFSET_DEFAULT_VMETRICS = this.#OFFSET_FONT_MATRIX + 1 + 8 * 6;
  static #OFFSET_STRINGS = this.#OFFSET_DEFAULT_VMETRICS + 1 + 2 * 3;
  #buffer;
  #decoder;
  #view;
  constructor({
    data,
    extra
  }) {
    this.#buffer = data;
    this.#decoder = new TextDecoder();
    this.#view = new DataView(this.#buffer);
    if (extra) {
      Object.assign(this, extra);
    }
  }
  #readBoolean(index) {
    assert(index < _FontInfo.bools.length, "Invalid boolean index");
    const byteOffset = Math.floor(index / 4);
    const bitOffset = index * 2 % 8;
    const value = this.#view.getUint8(byteOffset) >> bitOffset & 3;
    return value === 0 ? void 0 : value === 2;
  }
  get black() {
    return this.#readBoolean(0);
  }
  get bold() {
    return this.#readBoolean(1);
  }
  get disableFontFace() {
    return this.#readBoolean(2);
  }
  get fontExtraProperties() {
    return this.#readBoolean(3);
  }
  get isInvalidPDFjsFont() {
    return this.#readBoolean(4);
  }
  get isType3Font() {
    return this.#readBoolean(5);
  }
  get italic() {
    return this.#readBoolean(6);
  }
  get missingFile() {
    return this.#readBoolean(7);
  }
  get remeasure() {
    return this.#readBoolean(8);
  }
  get vertical() {
    return this.#readBoolean(9);
  }
  #readNumber(index) {
    assert(index < _FontInfo.numbers.length, "Invalid number index");
    return this.#view.getFloat64(_FontInfo.#OFFSET_NUMBERS + index * 8);
  }
  get ascent() {
    return this.#readNumber(0);
  }
  get defaultWidth() {
    return this.#readNumber(1);
  }
  get descent() {
    return this.#readNumber(2);
  }
  get bbox() {
    let offset = _FontInfo.#OFFSET_BBOX;
    const numCoords = this.#view.getUint8(offset);
    if (numCoords === 0) {
      return void 0;
    }
    offset += 1;
    const bbox = [];
    for (let i7 = 0; i7 < 4; i7++) {
      bbox.push(this.#view.getInt16(offset, true));
      offset += 2;
    }
    return bbox;
  }
  get fontMatrix() {
    let offset = _FontInfo.#OFFSET_FONT_MATRIX;
    const numPoints = this.#view.getUint8(offset);
    if (numPoints === 0) {
      return void 0;
    }
    offset += 1;
    const fontMatrix = [];
    for (let i7 = 0; i7 < 6; i7++) {
      fontMatrix.push(this.#view.getFloat64(offset, true));
      offset += 8;
    }
    return fontMatrix;
  }
  get defaultVMetrics() {
    let offset = _FontInfo.#OFFSET_DEFAULT_VMETRICS;
    const numMetrics = this.#view.getUint8(offset);
    if (numMetrics === 0) {
      return void 0;
    }
    offset += 1;
    const defaultVMetrics = [];
    for (let i7 = 0; i7 < 3; i7++) {
      defaultVMetrics.push(this.#view.getInt16(offset, true));
      offset += 2;
    }
    return defaultVMetrics;
  }
  #readString(index) {
    assert(index < _FontInfo.strings.length, "Invalid string index");
    let offset = _FontInfo.#OFFSET_STRINGS + 4;
    for (let i7 = 0; i7 < index; i7++) {
      offset += this.#view.getUint32(offset) + 4;
    }
    const length = this.#view.getUint32(offset);
    const stringData = new Uint8Array(length);
    stringData.set(new Uint8Array(this.#buffer, offset + 4, length));
    return this.#decoder.decode(stringData);
  }
  get fallbackName() {
    return this.#readString(0);
  }
  get loadedName() {
    return this.#readString(1);
  }
  get mimetype() {
    return this.#readString(2);
  }
  get name() {
    return this.#readString(3);
  }
  get data() {
    let offset = _FontInfo.#OFFSET_STRINGS;
    const stringsLength = this.#view.getUint32(offset);
    offset += 4 + stringsLength;
    const systemFontInfoLength = this.#view.getUint32(offset);
    offset += 4 + systemFontInfoLength;
    const cssFontInfoLength = this.#view.getUint32(offset);
    offset += 4 + cssFontInfoLength;
    const length = this.#view.getUint32(offset);
    if (length === 0) {
      return void 0;
    }
    return new Uint8Array(this.#buffer, offset + 4, length);
  }
  clearData() {
    let offset = _FontInfo.#OFFSET_STRINGS;
    const stringsLength = this.#view.getUint32(offset);
    offset += 4 + stringsLength;
    const systemFontInfoLength = this.#view.getUint32(offset);
    offset += 4 + systemFontInfoLength;
    const cssFontInfoLength = this.#view.getUint32(offset);
    offset += 4 + cssFontInfoLength;
    const length = this.#view.getUint32(offset);
    const data = new Uint8Array(this.#buffer, offset + 4, length);
    data.fill(0);
    this.#view.setUint32(offset, 0);
  }
  get cssFontInfo() {
    let offset = _FontInfo.#OFFSET_STRINGS;
    const stringsLength = this.#view.getUint32(offset);
    offset += 4 + stringsLength;
    const systemFontInfoLength = this.#view.getUint32(offset);
    offset += 4 + systemFontInfoLength;
    const cssFontInfoLength = this.#view.getUint32(offset);
    if (cssFontInfoLength === 0) {
      return null;
    }
    const cssFontInfoData = new Uint8Array(cssFontInfoLength);
    cssFontInfoData.set(new Uint8Array(this.#buffer, offset + 4, cssFontInfoLength));
    return new CssFontInfo(cssFontInfoData.buffer);
  }
  get systemFontInfo() {
    let offset = _FontInfo.#OFFSET_STRINGS;
    const stringsLength = this.#view.getUint32(offset);
    offset += 4 + stringsLength;
    const systemFontInfoLength = this.#view.getUint32(offset);
    if (systemFontInfoLength === 0) {
      return null;
    }
    const systemFontInfoData = new Uint8Array(systemFontInfoLength);
    systemFontInfoData.set(new Uint8Array(this.#buffer, offset + 4, systemFontInfoLength));
    return new SystemFontInfo(systemFontInfoData.buffer);
  }
  static write(font) {
    const systemFontInfoBuffer = font.systemFontInfo ? SystemFontInfo.write(font.systemFontInfo) : null;
    const cssFontInfoBuffer = font.cssFontInfo ? CssFontInfo.write(font.cssFontInfo) : null;
    const encoder = new TextEncoder();
    const encodedStrings = {};
    let stringsLength = 0;
    for (const prop of _FontInfo.strings) {
      encodedStrings[prop] = encoder.encode(font[prop]);
      stringsLength += 4 + encodedStrings[prop].length;
    }
    const lengthEstimate = _FontInfo.#OFFSET_STRINGS + 4 + stringsLength + 4 + (systemFontInfoBuffer ? systemFontInfoBuffer.byteLength : 0) + 4 + (cssFontInfoBuffer ? cssFontInfoBuffer.byteLength : 0) + 4 + (font.data ? font.data.length : 0);
    const buffer = new ArrayBuffer(lengthEstimate);
    const data = new Uint8Array(buffer);
    const view = new DataView(buffer);
    let offset = 0;
    const numBools = _FontInfo.bools.length;
    let boolByte = 0, boolBit = 0;
    for (let i7 = 0; i7 < numBools; i7++) {
      const value = font[_FontInfo.bools[i7]];
      const bits = value === void 0 ? 0 : value ? 2 : 1;
      boolByte |= bits << boolBit;
      boolBit += 2;
      if (boolBit === 8 || i7 === numBools - 1) {
        view.setUint8(offset++, boolByte);
        boolByte = 0;
        boolBit = 0;
      }
    }
    assert(offset === _FontInfo.#OFFSET_NUMBERS, "FontInfo.write: Boolean properties offset mismatch");
    for (const prop of _FontInfo.numbers) {
      view.setFloat64(offset, font[prop]);
      offset += 8;
    }
    assert(offset === _FontInfo.#OFFSET_BBOX, "FontInfo.write: Number properties offset mismatch");
    if (font.bbox) {
      view.setUint8(offset++, 4);
      for (const coord of font.bbox) {
        view.setInt16(offset, coord, true);
        offset += 2;
      }
    } else {
      view.setUint8(offset++, 0);
      offset += 2 * 4;
    }
    assert(offset === _FontInfo.#OFFSET_FONT_MATRIX, "FontInfo.write: BBox properties offset mismatch");
    if (font.fontMatrix) {
      view.setUint8(offset++, 6);
      for (const point of font.fontMatrix) {
        view.setFloat64(offset, point, true);
        offset += 8;
      }
    } else {
      view.setUint8(offset++, 0);
      offset += 8 * 6;
    }
    assert(offset === _FontInfo.#OFFSET_DEFAULT_VMETRICS, "FontInfo.write: FontMatrix properties offset mismatch");
    if (font.defaultVMetrics) {
      view.setUint8(offset++, 1);
      for (const metric of font.defaultVMetrics) {
        view.setInt16(offset, metric, true);
        offset += 2;
      }
    } else {
      view.setUint8(offset++, 0);
      offset += 3 * 2;
    }
    assert(offset === _FontInfo.#OFFSET_STRINGS, "FontInfo.write: DefaultVMetrics properties offset mismatch");
    view.setUint32(_FontInfo.#OFFSET_STRINGS, 0);
    offset += 4;
    for (const prop of _FontInfo.strings) {
      const encoded = encodedStrings[prop];
      const length = encoded.length;
      view.setUint32(offset, length);
      data.set(encoded, offset + 4);
      offset += 4 + length;
    }
    view.setUint32(_FontInfo.#OFFSET_STRINGS, offset - _FontInfo.#OFFSET_STRINGS - 4);
    if (!systemFontInfoBuffer) {
      view.setUint32(offset, 0);
      offset += 4;
    } else {
      const length = systemFontInfoBuffer.byteLength;
      view.setUint32(offset, length);
      assert(offset + 4 + length <= buffer.byteLength, "FontInfo.write: Buffer overflow at systemFontInfo");
      data.set(new Uint8Array(systemFontInfoBuffer), offset + 4);
      offset += 4 + length;
    }
    if (!cssFontInfoBuffer) {
      view.setUint32(offset, 0);
      offset += 4;
    } else {
      const length = cssFontInfoBuffer.byteLength;
      view.setUint32(offset, length);
      assert(offset + 4 + length <= buffer.byteLength, "FontInfo.write: Buffer overflow at cssFontInfo");
      data.set(new Uint8Array(cssFontInfoBuffer), offset + 4);
      offset += 4 + length;
    }
    if (font.data === void 0) {
      view.setUint32(offset, 0);
      offset += 4;
    } else {
      view.setUint32(offset, font.data.length);
      data.set(font.data, offset + 4);
      offset += 4 + font.data.length;
    }
    assert(offset <= buffer.byteLength, "FontInfo.write: Buffer overflow");
    return buffer.transferToFixedLength(offset);
  }
};
var PatternInfo = class _PatternInfo {
  static #KIND = 0;
  static #HAS_BBOX = 1;
  static #HAS_BACKGROUND = 2;
  static #SHADING_TYPE = 3;
  static #N_COORD = 4;
  static #N_COLOR = 8;
  static #N_STOP = 12;
  static #N_FIGURES = 16;
  constructor(buffer) {
    this.buffer = buffer;
    this.view = new DataView(buffer);
    this.data = new Uint8Array(buffer);
  }
  static write(ir) {
    let kind, bbox = null, coords = [], colors = [], colorStops = [], figures = [], shadingType = null, background = null;
    switch (ir[0]) {
      case "RadialAxial":
        kind = ir[1] === "axial" ? 1 : 2;
        bbox = ir[2];
        colorStops = ir[3];
        if (kind === 1) {
          coords.push(...ir[4], ...ir[5]);
        } else {
          coords.push(ir[4][0], ir[4][1], ir[6], ir[5][0], ir[5][1], ir[7]);
        }
        break;
      case "Mesh":
        kind = 3;
        shadingType = ir[1];
        coords = ir[2];
        colors = ir[3];
        figures = ir[4] || [];
        bbox = ir[6];
        background = ir[7];
        break;
      default:
        throw new Error(`Unsupported pattern type: ${ir[0]}`);
    }
    const nCoord = Math.floor(coords.length / 2);
    const nColor = Math.floor(colors.length / 3);
    const nStop = colorStops.length;
    const nFigures = figures.length;
    let figuresSize = 0;
    for (const figure of figures) {
      figuresSize += 1;
      figuresSize = Math.ceil(figuresSize / 4) * 4;
      figuresSize += 4 + figure.coords.length * 4;
      figuresSize += 4 + figure.colors.length * 4;
      if (figure.verticesPerRow !== void 0) {
        figuresSize += 4;
      }
    }
    const byteLen = 20 + nCoord * 8 + nColor * 3 + nStop * 8 + (bbox ? 16 : 0) + (background ? 3 : 0) + figuresSize;
    const buffer = new ArrayBuffer(byteLen);
    const dataView = new DataView(buffer);
    const u8data = new Uint8Array(buffer);
    dataView.setUint8(_PatternInfo.#KIND, kind);
    dataView.setUint8(_PatternInfo.#HAS_BBOX, bbox ? 1 : 0);
    dataView.setUint8(_PatternInfo.#HAS_BACKGROUND, background ? 1 : 0);
    dataView.setUint8(_PatternInfo.#SHADING_TYPE, shadingType);
    dataView.setUint32(_PatternInfo.#N_COORD, nCoord, true);
    dataView.setUint32(_PatternInfo.#N_COLOR, nColor, true);
    dataView.setUint32(_PatternInfo.#N_STOP, nStop, true);
    dataView.setUint32(_PatternInfo.#N_FIGURES, nFigures, true);
    let offset = 20;
    const coordsView = new Float32Array(buffer, offset, nCoord * 2);
    coordsView.set(coords);
    offset += nCoord * 8;
    u8data.set(colors, offset);
    offset += nColor * 3;
    for (const [pos, hex] of colorStops) {
      dataView.setFloat32(offset, pos, true);
      offset += 4;
      dataView.setUint32(offset, parseInt(hex.slice(1), 16), true);
      offset += 4;
    }
    if (bbox) {
      for (const v4 of bbox) {
        dataView.setFloat32(offset, v4, true);
        offset += 4;
      }
    }
    if (background) {
      u8data.set(background, offset);
      offset += 3;
    }
    for (let i7 = 0; i7 < figures.length; i7++) {
      const figure = figures[i7];
      dataView.setUint8(offset, figure.type);
      offset += 1;
      offset = Math.ceil(offset / 4) * 4;
      dataView.setUint32(offset, figure.coords.length, true);
      offset += 4;
      const figureCoordsView = new Int32Array(buffer, offset, figure.coords.length);
      figureCoordsView.set(figure.coords);
      offset += figure.coords.length * 4;
      dataView.setUint32(offset, figure.colors.length, true);
      offset += 4;
      const colorsView = new Int32Array(buffer, offset, figure.colors.length);
      colorsView.set(figure.colors);
      offset += figure.colors.length * 4;
      if (figure.verticesPerRow !== void 0) {
        dataView.setUint32(offset, figure.verticesPerRow, true);
        offset += 4;
      }
    }
    return buffer;
  }
  getIR() {
    const dataView = this.view;
    const kind = this.data[_PatternInfo.#KIND];
    const hasBBox = !!this.data[_PatternInfo.#HAS_BBOX];
    const hasBackground = !!this.data[_PatternInfo.#HAS_BACKGROUND];
    const nCoord = dataView.getUint32(_PatternInfo.#N_COORD, true);
    const nColor = dataView.getUint32(_PatternInfo.#N_COLOR, true);
    const nStop = dataView.getUint32(_PatternInfo.#N_STOP, true);
    const nFigures = dataView.getUint32(_PatternInfo.#N_FIGURES, true);
    let offset = 20;
    const coords = new Float32Array(this.buffer, offset, nCoord * 2);
    offset += nCoord * 8;
    const colors = new Uint8Array(this.buffer, offset, nColor * 3);
    offset += nColor * 3;
    const stops = [];
    for (let i7 = 0; i7 < nStop; ++i7) {
      const p4 = dataView.getFloat32(offset, true);
      offset += 4;
      const rgb = dataView.getUint32(offset, true);
      offset += 4;
      stops.push([p4, `#${rgb.toString(16).padStart(6, "0")}`]);
    }
    let bbox = null;
    if (hasBBox) {
      bbox = [];
      for (let i7 = 0; i7 < 4; ++i7) {
        bbox.push(dataView.getFloat32(offset, true));
        offset += 4;
      }
    }
    let background = null;
    if (hasBackground) {
      background = new Uint8Array(this.buffer, offset, 3);
      offset += 3;
    }
    const figures = [];
    for (let i7 = 0; i7 < nFigures; ++i7) {
      const type = dataView.getUint8(offset);
      offset += 1;
      offset = Math.ceil(offset / 4) * 4;
      const coordsLength = dataView.getUint32(offset, true);
      offset += 4;
      const figureCoords = new Int32Array(this.buffer, offset, coordsLength);
      offset += coordsLength * 4;
      const colorsLength = dataView.getUint32(offset, true);
      offset += 4;
      const figureColors = new Int32Array(this.buffer, offset, colorsLength);
      offset += colorsLength * 4;
      const figure = {
        type,
        coords: figureCoords,
        colors: figureColors
      };
      if (type === MeshFigureType.LATTICE) {
        figure.verticesPerRow = dataView.getUint32(offset, true);
        offset += 4;
      }
      figures.push(figure);
    }
    if (kind === 1) {
      return ["RadialAxial", "axial", bbox, stops, Array.from(coords.slice(0, 2)), Array.from(coords.slice(2, 4)), null, null];
    }
    if (kind === 2) {
      return ["RadialAxial", "radial", bbox, stops, [coords[0], coords[1]], [coords[3], coords[4]], coords[2], coords[5]];
    }
    if (kind === 3) {
      const shadingType = this.data[_PatternInfo.#SHADING_TYPE];
      let bounds = null;
      if (coords.length > 0) {
        let minX = coords[0], maxX = coords[0];
        let minY = coords[1], maxY = coords[1];
        for (let i7 = 0; i7 < coords.length; i7 += 2) {
          const x2 = coords[i7], y4 = coords[i7 + 1];
          minX = minX > x2 ? x2 : minX;
          minY = minY > y4 ? y4 : minY;
          maxX = maxX < x2 ? x2 : maxX;
          maxY = maxY < y4 ? y4 : maxY;
        }
        bounds = [minX, minY, maxX, maxY];
      }
      return ["Mesh", shadingType, coords, colors, figures, bounds, bbox, background];
    }
    throw new Error(`Unsupported pattern kind: ${kind}`);
  }
};
function getUrlProp(val2) {
  if (val2 instanceof URL) {
    return val2.href;
  }
  if (typeof val2 === "string") {
    if (isNodeJS) {
      return val2;
    }
    const url = URL.parse(val2, window.location);
    if (url) {
      return url.href;
    }
  }
  throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.");
}
function getDataProp(val2) {
  if (isNodeJS && typeof Buffer !== "undefined" && val2 instanceof Buffer) {
    throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");
  }
  if (val2 instanceof Uint8Array && val2.byteLength === val2.buffer.byteLength) {
    return val2;
  }
  if (typeof val2 === "string") {
    return stringToBytes(val2);
  }
  if (val2 instanceof ArrayBuffer || ArrayBuffer.isView(val2) || typeof val2 === "object" && !isNaN(val2?.length)) {
    return new Uint8Array(val2);
  }
  throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.");
}
function getFactoryUrlProp(val2) {
  if (typeof val2 !== "string") {
    return null;
  }
  if (val2.endsWith("/")) {
    return val2;
  }
  throw new Error(`Invalid factory url: "${val2}" must include trailing slash.`);
}
var isRefProxy = (v4) => typeof v4 === "object" && Number.isInteger(v4?.num) && v4.num >= 0 && Number.isInteger(v4?.gen) && v4.gen >= 0;
var isNameProxy = (v4) => typeof v4 === "object" && typeof v4?.name === "string";
var isValidExplicitDest = _isValidExplicitDest.bind(null, isRefProxy, isNameProxy);
var LoopbackPort = class {
  #listeners = /* @__PURE__ */ new Map();
  #deferred = Promise.resolve();
  postMessage(obj, transfer) {
    const event = {
      data: structuredClone(obj, transfer ? {
        transfer
      } : null)
    };
    this.#deferred.then(() => {
      for (const [listener] of this.#listeners) {
        listener.call(this, event);
      }
    });
  }
  addEventListener(name, listener, options = null) {
    let rmAbort = null;
    if (options?.signal instanceof AbortSignal) {
      const {
        signal
      } = options;
      if (signal.aborted) {
        warn("LoopbackPort - cannot use an `aborted` signal.");
        return;
      }
      const onAbort = () => this.removeEventListener(name, listener);
      rmAbort = () => signal.removeEventListener("abort", onAbort);
      signal.addEventListener("abort", onAbort);
    }
    this.#listeners.set(listener, rmAbort);
  }
  removeEventListener(name, listener) {
    const rmAbort = this.#listeners.get(listener);
    rmAbort?.();
    this.#listeners.delete(listener);
  }
  terminate() {
    for (const [, rmAbort] of this.#listeners) {
      rmAbort?.();
    }
    this.#listeners.clear();
  }
};
var CallbackKind = {
  DATA: 1,
  ERROR: 2
};
var StreamKind = {
  CANCEL: 1,
  CANCEL_COMPLETE: 2,
  CLOSE: 3,
  ENQUEUE: 4,
  ERROR: 5,
  PULL: 6,
  PULL_COMPLETE: 7,
  START_COMPLETE: 8
};
function onFn() {
}
function wrapReason(ex) {
  if (ex instanceof AbortException || ex instanceof InvalidPDFException || ex instanceof PasswordException || ex instanceof ResponseException || ex instanceof UnknownErrorException) {
    return ex;
  }
  if (!(ex instanceof Error || typeof ex === "object" && ex !== null)) {
    unreachable('wrapReason: Expected "reason" to be a (possibly cloned) Error.');
  }
  switch (ex.name) {
    case "AbortException":
      return new AbortException(ex.message);
    case "InvalidPDFException":
      return new InvalidPDFException(ex.message);
    case "PasswordException":
      return new PasswordException(ex.message, ex.code);
    case "ResponseException":
      return new ResponseException(ex.message, ex.status, ex.missing);
    case "UnknownErrorException":
      return new UnknownErrorException(ex.message, ex.details);
  }
  return new UnknownErrorException(ex.message, ex.toString());
}
var MessageHandler = class {
  #messageAC = new AbortController();
  constructor(sourceName, targetName, comObj) {
    this.sourceName = sourceName;
    this.targetName = targetName;
    this.comObj = comObj;
    this.callbackId = 1;
    this.streamId = 1;
    this.streamSinks = /* @__PURE__ */ Object.create(null);
    this.streamControllers = /* @__PURE__ */ Object.create(null);
    this.callbackCapabilities = /* @__PURE__ */ Object.create(null);
    this.actionHandler = /* @__PURE__ */ Object.create(null);
    comObj.addEventListener("message", this.#onMessage.bind(this), {
      signal: this.#messageAC.signal
    });
  }
  #onMessage({
    data
  }) {
    if (data.targetName !== this.sourceName) {
      return;
    }
    if (data.stream) {
      this.#processStreamMessage(data);
      return;
    }
    if (data.callback) {
      const callbackId = data.callbackId;
      const capability = this.callbackCapabilities[callbackId];
      if (!capability) {
        throw new Error(`Cannot resolve callback ${callbackId}`);
      }
      delete this.callbackCapabilities[callbackId];
      if (data.callback === CallbackKind.DATA) {
        capability.resolve(data.data);
      } else if (data.callback === CallbackKind.ERROR) {
        capability.reject(wrapReason(data.reason));
      } else {
        throw new Error("Unexpected callback case");
      }
      return;
    }
    const action = this.actionHandler[data.action];
    if (!action) {
      throw new Error(`Unknown action from worker: ${data.action}`);
    }
    if (data.callbackId) {
      const sourceName = this.sourceName, targetName = data.sourceName, comObj = this.comObj;
      Promise.try(action, data.data).then(function(result) {
        comObj.postMessage({
          sourceName,
          targetName,
          callback: CallbackKind.DATA,
          callbackId: data.callbackId,
          data: result
        });
      }, function(reason) {
        comObj.postMessage({
          sourceName,
          targetName,
          callback: CallbackKind.ERROR,
          callbackId: data.callbackId,
          reason: wrapReason(reason)
        });
      });
      return;
    }
    if (data.streamId) {
      this.#createStreamSink(data);
      return;
    }
    action(data.data);
  }
  on(actionName, handler) {
    const ah = this.actionHandler;
    if (ah[actionName]) {
      throw new Error(`There is already an actionName called "${actionName}"`);
    }
    ah[actionName] = handler;
  }
  send(actionName, data, transfers) {
    this.comObj.postMessage({
      sourceName: this.sourceName,
      targetName: this.targetName,
      action: actionName,
      data
    }, transfers);
  }
  sendWithPromise(actionName, data, transfers) {
    const callbackId = this.callbackId++;
    const capability = Promise.withResolvers();
    this.callbackCapabilities[callbackId] = capability;
    try {
      this.comObj.postMessage({
        sourceName: this.sourceName,
        targetName: this.targetName,
        action: actionName,
        callbackId,
        data
      }, transfers);
    } catch (ex) {
      capability.reject(ex);
    }
    return capability.promise;
  }
  sendWithStream(actionName, data, queueingStrategy, transfers) {
    const streamId = this.streamId++, sourceName = this.sourceName, targetName = this.targetName, comObj = this.comObj;
    return new ReadableStream({
      start: (controller) => {
        const startCapability = Promise.withResolvers();
        this.streamControllers[streamId] = {
          controller,
          startCall: startCapability,
          pullCall: null,
          cancelCall: null,
          isClosed: false
        };
        comObj.postMessage({
          sourceName,
          targetName,
          action: actionName,
          streamId,
          data,
          desiredSize: controller.desiredSize
        }, transfers);
        return startCapability.promise;
      },
      pull: (controller) => {
        const pullCapability = Promise.withResolvers();
        this.streamControllers[streamId].pullCall = pullCapability;
        comObj.postMessage({
          sourceName,
          targetName,
          stream: StreamKind.PULL,
          streamId,
          desiredSize: controller.desiredSize
        });
        return pullCapability.promise;
      },
      cancel: (reason) => {
        assert(reason instanceof Error, "cancel must have a valid reason");
        const cancelCapability = Promise.withResolvers();
        this.streamControllers[streamId].cancelCall = cancelCapability;
        this.streamControllers[streamId].isClosed = true;
        comObj.postMessage({
          sourceName,
          targetName,
          stream: StreamKind.CANCEL,
          streamId,
          reason: wrapReason(reason)
        });
        return cancelCapability.promise;
      }
    }, queueingStrategy);
  }
  #createStreamSink(data) {
    const streamId = data.streamId, sourceName = this.sourceName, targetName = data.sourceName, comObj = this.comObj;
    const self2 = this, action = this.actionHandler[data.action];
    const streamSink = {
      enqueue(chunk, size = 1, transfers) {
        if (this.isCancelled) {
          return;
        }
        const lastDesiredSize = this.desiredSize;
        this.desiredSize -= size;
        if (lastDesiredSize > 0 && this.desiredSize <= 0) {
          this.sinkCapability = Promise.withResolvers();
          this.ready = this.sinkCapability.promise;
        }
        comObj.postMessage({
          sourceName,
          targetName,
          stream: StreamKind.ENQUEUE,
          streamId,
          chunk
        }, transfers);
      },
      close() {
        if (this.isCancelled) {
          return;
        }
        this.isCancelled = true;
        comObj.postMessage({
          sourceName,
          targetName,
          stream: StreamKind.CLOSE,
          streamId
        });
        delete self2.streamSinks[streamId];
      },
      error(reason) {
        assert(reason instanceof Error, "error must have a valid reason");
        if (this.isCancelled) {
          return;
        }
        this.isCancelled = true;
        comObj.postMessage({
          sourceName,
          targetName,
          stream: StreamKind.ERROR,
          streamId,
          reason: wrapReason(reason)
        });
      },
      sinkCapability: Promise.withResolvers(),
      onPull: null,
      onCancel: null,
      isCancelled: false,
      desiredSize: data.desiredSize,
      ready: null
    };
    streamSink.sinkCapability.resolve();
    streamSink.ready = streamSink.sinkCapability.promise;
    this.streamSinks[streamId] = streamSink;
    Promise.try(action, data.data, streamSink).then(function() {
      comObj.postMessage({
        sourceName,
        targetName,
        stream: StreamKind.START_COMPLETE,
        streamId,
        success: true
      });
    }, function(reason) {
      comObj.postMessage({
        sourceName,
        targetName,
        stream: StreamKind.START_COMPLETE,
        streamId,
        reason: wrapReason(reason)
      });
    });
  }
  #processStreamMessage(data) {
    const streamId = data.streamId, sourceName = this.sourceName, targetName = data.sourceName, comObj = this.comObj;
    const streamController = this.streamControllers[streamId], streamSink = this.streamSinks[streamId];
    switch (data.stream) {
      case StreamKind.START_COMPLETE:
        if (data.success) {
          streamController.startCall.resolve();
        } else {
          streamController.startCall.reject(wrapReason(data.reason));
        }
        break;
      case StreamKind.PULL_COMPLETE:
        if (data.success) {
          streamController.pullCall.resolve();
        } else {
          streamController.pullCall.reject(wrapReason(data.reason));
        }
        break;
      case StreamKind.PULL:
        if (!streamSink) {
          comObj.postMessage({
            sourceName,
            targetName,
            stream: StreamKind.PULL_COMPLETE,
            streamId,
            success: true
          });
          break;
        }
        if (streamSink.desiredSize <= 0 && data.desiredSize > 0) {
          streamSink.sinkCapability.resolve();
        }
        streamSink.desiredSize = data.desiredSize;
        Promise.try(streamSink.onPull || onFn).then(function() {
          comObj.postMessage({
            sourceName,
            targetName,
            stream: StreamKind.PULL_COMPLETE,
            streamId,
            success: true
          });
        }, function(reason) {
          comObj.postMessage({
            sourceName,
            targetName,
            stream: StreamKind.PULL_COMPLETE,
            streamId,
            reason: wrapReason(reason)
          });
        });
        break;
      case StreamKind.ENQUEUE:
        assert(streamController, "enqueue should have stream controller");
        if (streamController.isClosed) {
          break;
        }
        streamController.controller.enqueue(data.chunk);
        break;
      case StreamKind.CLOSE:
        assert(streamController, "close should have stream controller");
        if (streamController.isClosed) {
          break;
        }
        streamController.isClosed = true;
        streamController.controller.close();
        this.#deleteStreamController(streamController, streamId);
        break;
      case StreamKind.ERROR:
        assert(streamController, "error should have stream controller");
        streamController.controller.error(wrapReason(data.reason));
        this.#deleteStreamController(streamController, streamId);
        break;
      case StreamKind.CANCEL_COMPLETE:
        if (data.success) {
          streamController.cancelCall.resolve();
        } else {
          streamController.cancelCall.reject(wrapReason(data.reason));
        }
        this.#deleteStreamController(streamController, streamId);
        break;
      case StreamKind.CANCEL:
        if (!streamSink) {
          break;
        }
        const dataReason = wrapReason(data.reason);
        Promise.try(streamSink.onCancel || onFn, dataReason).then(function() {
          comObj.postMessage({
            sourceName,
            targetName,
            stream: StreamKind.CANCEL_COMPLETE,
            streamId,
            success: true
          });
        }, function(reason) {
          comObj.postMessage({
            sourceName,
            targetName,
            stream: StreamKind.CANCEL_COMPLETE,
            streamId,
            reason: wrapReason(reason)
          });
        });
        streamSink.sinkCapability.reject(dataReason);
        streamSink.isCancelled = true;
        delete this.streamSinks[streamId];
        break;
      default:
        throw new Error("Unexpected stream case");
    }
  }
  async #deleteStreamController(streamController, streamId) {
    await Promise.allSettled([streamController.startCall?.promise, streamController.pullCall?.promise, streamController.cancelCall?.promise]);
    delete this.streamControllers[streamId];
  }
  destroy() {
    this.#messageAC?.abort();
    this.#messageAC = null;
  }
};
var BaseCanvasFactory = class {
  #enableHWA = false;
  constructor({
    enableHWA = false
  }) {
    this.#enableHWA = enableHWA;
  }
  create(width, height) {
    if (width <= 0 || height <= 0) {
      throw new Error("Invalid canvas size");
    }
    const canvas = this._createCanvas(width, height);
    return {
      canvas,
      context: canvas.getContext("2d", {
        willReadFrequently: !this.#enableHWA
      })
    };
  }
  reset(canvasAndContext, width, height) {
    if (!canvasAndContext.canvas) {
      throw new Error("Canvas is not specified");
    }
    if (width <= 0 || height <= 0) {
      throw new Error("Invalid canvas size");
    }
    canvasAndContext.canvas.width = width;
    canvasAndContext.canvas.height = height;
  }
  destroy(canvasAndContext) {
    if (!canvasAndContext.canvas) {
      throw new Error("Canvas is not specified");
    }
    canvasAndContext.canvas.width = 0;
    canvasAndContext.canvas.height = 0;
    canvasAndContext.canvas = null;
    canvasAndContext.context = null;
  }
  _createCanvas(width, height) {
    unreachable("Abstract method `_createCanvas` called.");
  }
};
var DOMCanvasFactory = class extends BaseCanvasFactory {
  constructor({
    ownerDocument = globalThis.document,
    enableHWA = false
  }) {
    super({
      enableHWA
    });
    this._document = ownerDocument;
  }
  _createCanvas(width, height) {
    const canvas = this._document.createElement("canvas");
    canvas.width = width;
    canvas.height = height;
    return canvas;
  }
};
var BaseCMapReaderFactory = class {
  constructor({
    baseUrl = null,
    isCompressed = true
  }) {
    this.baseUrl = baseUrl;
    this.isCompressed = isCompressed;
  }
  async fetch({
    name
  }) {
    if (!this.baseUrl) {
      throw new Error("Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided.");
    }
    if (!name) {
      throw new Error("CMap name must be specified.");
    }
    const url = this.baseUrl + name + (this.isCompressed ? ".bcmap" : "");
    return this._fetch(url).then((cMapData) => ({
      cMapData,
      isCompressed: this.isCompressed
    })).catch((reason) => {
      throw new Error(`Unable to load ${this.isCompressed ? "binary " : ""}CMap at: ${url}`);
    });
  }
  async _fetch(url) {
    unreachable("Abstract method `_fetch` called.");
  }
};
var DOMCMapReaderFactory = class extends BaseCMapReaderFactory {
  async _fetch(url) {
    const data = await fetchData(url, this.isCompressed ? "arraybuffer" : "text");
    return data instanceof ArrayBuffer ? new Uint8Array(data) : stringToBytes(data);
  }
};
var BaseFilterFactory = class {
  addFilter(maps) {
    return "none";
  }
  addHCMFilter(fgColor, bgColor) {
    return "none";
  }
  addAlphaFilter(map) {
    return "none";
  }
  addLuminosityFilter(map) {
    return "none";
  }
  addHighlightHCMFilter(filterName, fgColor, bgColor, newFgColor, newBgColor) {
    return "none";
  }
  destroy(keepHCM = false) {
  }
};
var DOMFilterFactory = class extends BaseFilterFactory {
  #baseUrl;
  #_cache;
  #_defs;
  #docId;
  #document;
  #_hcmCache;
  #id = 0;
  constructor({
    docId,
    ownerDocument = globalThis.document
  }) {
    super();
    this.#docId = docId;
    this.#document = ownerDocument;
  }
  get #cache() {
    return this.#_cache ||= /* @__PURE__ */ new Map();
  }
  get #hcmCache() {
    return this.#_hcmCache ||= /* @__PURE__ */ new Map();
  }
  get #defs() {
    if (!this.#_defs) {
      const div = this.#document.createElement("div");
      const {
        style
      } = div;
      style.visibility = "hidden";
      style.contain = "strict";
      style.width = style.height = 0;
      style.position = "absolute";
      style.top = style.left = 0;
      style.zIndex = -1;
      const svg = this.#document.createElementNS(SVG_NS, "svg");
      svg.setAttribute("width", 0);
      svg.setAttribute("height", 0);
      this.#_defs = this.#document.createElementNS(SVG_NS, "defs");
      div.append(svg);
      svg.append(this.#_defs);
      this.#document.body.append(div);
    }
    return this.#_defs;
  }
  #createTables(maps) {
    if (maps.length === 1) {
      const mapR2 = maps[0];
      const buffer = new Array(256);
      for (let i7 = 0; i7 < 256; i7++) {
        buffer[i7] = mapR2[i7] / 255;
      }
      const table = buffer.join(",");
      return [table, table, table];
    }
    const [mapR, mapG, mapB] = maps;
    const bufferR = new Array(256);
    const bufferG = new Array(256);
    const bufferB = new Array(256);
    for (let i7 = 0; i7 < 256; i7++) {
      bufferR[i7] = mapR[i7] / 255;
      bufferG[i7] = mapG[i7] / 255;
      bufferB[i7] = mapB[i7] / 255;
    }
    return [bufferR.join(","), bufferG.join(","), bufferB.join(",")];
  }
  #createUrl(id) {
    if (this.#baseUrl === void 0) {
      this.#baseUrl = "";
      const url = this.#document.URL;
      if (url !== this.#document.baseURI) {
        if (isDataScheme(url)) {
          warn('#createUrl: ignore "data:"-URL for performance reasons.');
        } else {
          this.#baseUrl = updateUrlHash(url, "");
        }
      }
    }
    return `url(${this.#baseUrl}#${id})`;
  }
  addFilter(maps) {
    if (!maps) {
      return "none";
    }
    let value = this.#cache.get(maps);
    if (value) {
      return value;
    }
    const [tableR, tableG, tableB] = this.#createTables(maps);
    const key = maps.length === 1 ? tableR : `${tableR}${tableG}${tableB}`;
    value = this.#cache.get(key);
    if (value) {
      this.#cache.set(maps, value);
      return value;
    }
    const id = `g_${this.#docId}_transfer_map_${this.#id++}`;
    const url = this.#createUrl(id);
    this.#cache.set(maps, url);
    this.#cache.set(key, url);
    const filter2 = this.#createFilter(id);
    this.#addTransferMapConversion(tableR, tableG, tableB, filter2);
    return url;
  }
  addHCMFilter(fgColor, bgColor) {
    const key = `${fgColor}-${bgColor}`;
    const filterName = "base";
    let info2 = this.#hcmCache.get(filterName);
    if (info2?.key === key) {
      return info2.url;
    }
    if (info2) {
      info2.filter?.remove();
      info2.key = key;
      info2.url = "none";
      info2.filter = null;
    } else {
      info2 = {
        key,
        url: "none",
        filter: null
      };
      this.#hcmCache.set(filterName, info2);
    }
    if (!fgColor || !bgColor) {
      return info2.url;
    }
    const fgRGB = this.#getRGB(fgColor);
    fgColor = Util.makeHexColor(...fgRGB);
    const bgRGB = this.#getRGB(bgColor);
    bgColor = Util.makeHexColor(...bgRGB);
    this.#defs.style.color = "";
    if (fgColor === "#000000" && bgColor === "#ffffff" || fgColor === bgColor) {
      return info2.url;
    }
    const map = new Array(256);
    for (let i7 = 0; i7 <= 255; i7++) {
      const x2 = i7 / 255;
      map[i7] = x2 <= 0.03928 ? x2 / 12.92 : ((x2 + 0.055) / 1.055) ** 2.4;
    }
    const table = map.join(",");
    const id = `g_${this.#docId}_hcm_filter`;
    const filter2 = info2.filter = this.#createFilter(id);
    this.#addTransferMapConversion(table, table, table, filter2);
    this.#addGrayConversion(filter2);
    const getSteps = (c6, n7) => {
      const start = fgRGB[c6] / 255;
      const end = bgRGB[c6] / 255;
      const arr = new Array(n7 + 1);
      for (let i7 = 0; i7 <= n7; i7++) {
        arr[i7] = start + i7 / n7 * (end - start);
      }
      return arr.join(",");
    };
    this.#addTransferMapConversion(getSteps(0, 5), getSteps(1, 5), getSteps(2, 5), filter2);
    info2.url = this.#createUrl(id);
    return info2.url;
  }
  addAlphaFilter(map) {
    let value = this.#cache.get(map);
    if (value) {
      return value;
    }
    const [tableA] = this.#createTables([map]);
    const key = `alpha_${tableA}`;
    value = this.#cache.get(key);
    if (value) {
      this.#cache.set(map, value);
      return value;
    }
    const id = `g_${this.#docId}_alpha_map_${this.#id++}`;
    const url = this.#createUrl(id);
    this.#cache.set(map, url);
    this.#cache.set(key, url);
    const filter2 = this.#createFilter(id);
    this.#addTransferMapAlphaConversion(tableA, filter2);
    return url;
  }
  addLuminosityFilter(map) {
    let value = this.#cache.get(map || "luminosity");
    if (value) {
      return value;
    }
    let tableA, key;
    if (map) {
      [tableA] = this.#createTables([map]);
      key = `luminosity_${tableA}`;
    } else {
      key = "luminosity";
    }
    value = this.#cache.get(key);
    if (value) {
      this.#cache.set(map, value);
      return value;
    }
    const id = `g_${this.#docId}_luminosity_map_${this.#id++}`;
    const url = this.#createUrl(id);
    this.#cache.set(map, url);
    this.#cache.set(key, url);
    const filter2 = this.#createFilter(id);
    this.#addLuminosityConversion(filter2);
    if (map) {
      this.#addTransferMapAlphaConversion(tableA, filter2);
    }
    return url;
  }
  addHighlightHCMFilter(filterName, fgColor, bgColor, newFgColor, newBgColor) {
    const key = `${fgColor}-${bgColor}-${newFgColor}-${newBgColor}`;
    let info2 = this.#hcmCache.get(filterName);
    if (info2?.key === key) {
      return info2.url;
    }
    if (info2) {
      info2.filter?.remove();
      info2.key = key;
      info2.url = "none";
      info2.filter = null;
    } else {
      info2 = {
        key,
        url: "none",
        filter: null
      };
      this.#hcmCache.set(filterName, info2);
    }
    if (!fgColor || !bgColor) {
      return info2.url;
    }
    const [fgRGB, bgRGB] = [fgColor, bgColor].map(this.#getRGB.bind(this));
    let fgGray = Math.round(0.2126 * fgRGB[0] + 0.7152 * fgRGB[1] + 0.0722 * fgRGB[2]);
    let bgGray = Math.round(0.2126 * bgRGB[0] + 0.7152 * bgRGB[1] + 0.0722 * bgRGB[2]);
    let [newFgRGB, newBgRGB] = [newFgColor, newBgColor].map(this.#getRGB.bind(this));
    if (bgGray < fgGray) {
      [fgGray, bgGray, newFgRGB, newBgRGB] = [bgGray, fgGray, newBgRGB, newFgRGB];
    }
    this.#defs.style.color = "";
    const getSteps = (fg, bg, n7) => {
      const arr = new Array(256);
      const step = (bgGray - fgGray) / n7;
      const newStart = fg / 255;
      const newStep = (bg - fg) / (255 * n7);
      let prev = 0;
      for (let i7 = 0; i7 <= n7; i7++) {
        const k2 = Math.round(fgGray + i7 * step);
        const value = newStart + i7 * newStep;
        for (let j3 = prev; j3 <= k2; j3++) {
          arr[j3] = value;
        }
        prev = k2 + 1;
      }
      for (let i7 = prev; i7 < 256; i7++) {
        arr[i7] = arr[prev - 1];
      }
      return arr.join(",");
    };
    const id = `g_${this.#docId}_hcm_${filterName}_filter`;
    const filter2 = info2.filter = this.#createFilter(id);
    this.#addGrayConversion(filter2);
    this.#addTransferMapConversion(getSteps(newFgRGB[0], newBgRGB[0], 5), getSteps(newFgRGB[1], newBgRGB[1], 5), getSteps(newFgRGB[2], newBgRGB[2], 5), filter2);
    info2.url = this.#createUrl(id);
    return info2.url;
  }
  destroy(keepHCM = false) {
    if (keepHCM && this.#_hcmCache?.size) {
      return;
    }
    this.#_defs?.parentNode.parentNode.remove();
    this.#_defs = null;
    this.#_cache?.clear();
    this.#_cache = null;
    this.#_hcmCache?.clear();
    this.#_hcmCache = null;
    this.#id = 0;
  }
  #addLuminosityConversion(filter2) {
    const feColorMatrix = this.#document.createElementNS(SVG_NS, "feColorMatrix");
    feColorMatrix.setAttribute("type", "matrix");
    feColorMatrix.setAttribute("values", "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0");
    filter2.append(feColorMatrix);
  }
  #addGrayConversion(filter2) {
    const feColorMatrix = this.#document.createElementNS(SVG_NS, "feColorMatrix");
    feColorMatrix.setAttribute("type", "matrix");
    feColorMatrix.setAttribute("values", "0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0");
    filter2.append(feColorMatrix);
  }
  #createFilter(id) {
    const filter2 = this.#document.createElementNS(SVG_NS, "filter");
    filter2.setAttribute("color-interpolation-filters", "sRGB");
    filter2.setAttribute("id", id);
    this.#defs.append(filter2);
    return filter2;
  }
  #appendFeFunc(feComponentTransfer, func, table) {
    const feFunc = this.#document.createElementNS(SVG_NS, func);
    feFunc.setAttribute("type", "discrete");
    feFunc.setAttribute("tableValues", table);
    feComponentTransfer.append(feFunc);
  }
  #addTransferMapConversion(rTable, gTable, bTable, filter2) {
    const feComponentTransfer = this.#document.createElementNS(SVG_NS, "feComponentTransfer");
    filter2.append(feComponentTransfer);
    this.#appendFeFunc(feComponentTransfer, "feFuncR", rTable);
    this.#appendFeFunc(feComponentTransfer, "feFuncG", gTable);
    this.#appendFeFunc(feComponentTransfer, "feFuncB", bTable);
  }
  #addTransferMapAlphaConversion(aTable, filter2) {
    const feComponentTransfer = this.#document.createElementNS(SVG_NS, "feComponentTransfer");
    filter2.append(feComponentTransfer);
    this.#appendFeFunc(feComponentTransfer, "feFuncA", aTable);
  }
  #getRGB(color) {
    this.#defs.style.color = color;
    return getRGB(getComputedStyle(this.#defs).getPropertyValue("color"));
  }
};
var BaseStandardFontDataFactory = class {
  constructor({
    baseUrl = null
  }) {
    this.baseUrl = baseUrl;
  }
  async fetch({
    filename
  }) {
    if (!this.baseUrl) {
      throw new Error("Ensure that the `standardFontDataUrl` API parameter is provided.");
    }
    if (!filename) {
      throw new Error("Font filename must be specified.");
    }
    const url = `${this.baseUrl}${filename}`;
    return this._fetch(url).catch((reason) => {
      throw new Error(`Unable to load font data at: ${url}`);
    });
  }
  async _fetch(url) {
    unreachable("Abstract method `_fetch` called.");
  }
};
var DOMStandardFontDataFactory = class extends BaseStandardFontDataFactory {
  async _fetch(url) {
    const data = await fetchData(url, "arraybuffer");
    return new Uint8Array(data);
  }
};
var BaseWasmFactory = class {
  constructor({
    baseUrl = null
  }) {
    this.baseUrl = baseUrl;
  }
  async fetch({
    filename
  }) {
    if (!this.baseUrl) {
      throw new Error("Ensure that the `wasmUrl` API parameter is provided.");
    }
    if (!filename) {
      throw new Error("Wasm filename must be specified.");
    }
    const url = `${this.baseUrl}${filename}`;
    return this._fetch(url).catch((reason) => {
      throw new Error(`Unable to load wasm data at: ${url}`);
    });
  }
  async _fetch(url) {
    unreachable("Abstract method `_fetch` called.");
  }
};
var DOMWasmFactory = class extends BaseWasmFactory {
  async _fetch(url) {
    const data = await fetchData(url, "arraybuffer");
    return new Uint8Array(data);
  }
};
if (isNodeJS) {
  warn("Please use the `legacy` build in Node.js environments.");
}
async function node_utils_fetchData(url) {
  const fs = process.getBuiltinModule("fs");
  const data = await fs.promises.readFile(url);
  return new Uint8Array(data);
}
var NodeFilterFactory = class extends BaseFilterFactory {
};
var NodeCanvasFactory = class extends BaseCanvasFactory {
  _createCanvas(width, height) {
    const require2 = process.getBuiltinModule("module").createRequire(import.meta.url);
    const canvas = require2("@napi-rs/canvas");
    return canvas.createCanvas(width, height);
  }
};
var NodeCMapReaderFactory = class extends BaseCMapReaderFactory {
  async _fetch(url) {
    return node_utils_fetchData(url);
  }
};
var NodeStandardFontDataFactory = class extends BaseStandardFontDataFactory {
  async _fetch(url) {
    return node_utils_fetchData(url);
  }
};
var NodeWasmFactory = class extends BaseWasmFactory {
  async _fetch(url) {
    return node_utils_fetchData(url);
  }
};
var FORCED_DEPENDENCY_LABEL = "__forcedDependency";
var {
  floor,
  ceil
} = Math;
function expandBBox(array, index, minX, minY, maxX, maxY) {
  array[index * 4 + 0] = Math.min(array[index * 4 + 0], minX);
  array[index * 4 + 1] = Math.min(array[index * 4 + 1], minY);
  array[index * 4 + 2] = Math.max(array[index * 4 + 2], maxX);
  array[index * 4 + 3] = Math.max(array[index * 4 + 3], maxY);
}
var EMPTY_BBOX = new Uint32Array(new Uint8Array([255, 255, 0, 0]).buffer)[0];
var BBoxReader = class {
  #bboxes;
  #coords;
  constructor(bboxes, coords) {
    this.#bboxes = bboxes;
    this.#coords = coords;
  }
  get length() {
    return this.#bboxes.length;
  }
  isEmpty(i7) {
    return this.#bboxes[i7] === EMPTY_BBOX;
  }
  minX(i7) {
    return this.#coords[i7 * 4 + 0] / 256;
  }
  minY(i7) {
    return this.#coords[i7 * 4 + 1] / 256;
  }
  maxX(i7) {
    return (this.#coords[i7 * 4 + 2] + 1) / 256;
  }
  maxY(i7) {
    return (this.#coords[i7 * 4 + 3] + 1) / 256;
  }
};
var ensureDebugMetadata = (map, key) => {
  if (!map) {
    return void 0;
  }
  let value = map.get(key);
  if (!value) {
    value = {
      dependencies: /* @__PURE__ */ new Set(),
      isRenderingOperation: false
    };
    map.set(key, value);
  }
  return value;
};
var CanvasDependencyTracker = class {
  #simple = {
    __proto__: null
  };
  #incremental = {
    __proto__: null,
    transform: [],
    moveText: [],
    sameLineText: [],
    [FORCED_DEPENDENCY_LABEL]: []
  };
  #namedDependencies = /* @__PURE__ */ new Map();
  #savesStack = [];
  #markedContentStack = [];
  #baseTransformStack = [[1, 0, 0, 1, 0, 0]];
  #clipBox = [-Infinity, -Infinity, Infinity, Infinity];
  #pendingBBox = new Float64Array([Infinity, Infinity, -Infinity, -Infinity]);
  #pendingBBoxIdx = -1;
  #pendingDependencies = /* @__PURE__ */ new Set();
  #operations = /* @__PURE__ */ new Map();
  #fontBBoxTrustworthy = /* @__PURE__ */ new Map();
  #canvasWidth;
  #canvasHeight;
  #bboxesCoords;
  #bboxes;
  #debugMetadata;
  constructor(canvas, operationsCount, recordDebugMetadata = false) {
    this.#canvasWidth = canvas.width;
    this.#canvasHeight = canvas.height;
    this.#initializeBBoxes(operationsCount);
    if (recordDebugMetadata) {
      this.#debugMetadata = /* @__PURE__ */ new Map();
    }
  }
  growOperationsCount(operationsCount) {
    if (operationsCount >= this.#bboxes.length) {
      this.#initializeBBoxes(operationsCount, this.#bboxes);
    }
  }
  #initializeBBoxes(operationsCount, oldBBoxes) {
    const buffer = new ArrayBuffer(operationsCount * 4);
    this.#bboxesCoords = new Uint8ClampedArray(buffer);
    this.#bboxes = new Uint32Array(buffer);
    if (oldBBoxes && oldBBoxes.length > 0) {
      this.#bboxes.set(oldBBoxes);
      this.#bboxes.fill(EMPTY_BBOX, oldBBoxes.length);
    } else {
      this.#bboxes.fill(EMPTY_BBOX);
    }
  }
  save(opIdx) {
    this.#simple = {
      __proto__: this.#simple
    };
    this.#incremental = {
      __proto__: this.#incremental,
      transform: {
        __proto__: this.#incremental.transform
      },
      moveText: {
        __proto__: this.#incremental.moveText
      },
      sameLineText: {
        __proto__: this.#incremental.sameLineText
      },
      [FORCED_DEPENDENCY_LABEL]: {
        __proto__: this.#incremental[FORCED_DEPENDENCY_LABEL]
      }
    };
    this.#clipBox = {
      __proto__: this.#clipBox
    };
    this.#savesStack.push(opIdx);
    return this;
  }
  restore(opIdx) {
    const previous = Object.getPrototypeOf(this.#simple);
    if (previous === null) {
      return this;
    }
    this.#simple = previous;
    this.#incremental = Object.getPrototypeOf(this.#incremental);
    this.#clipBox = Object.getPrototypeOf(this.#clipBox);
    const lastSave = this.#savesStack.pop();
    if (lastSave !== void 0) {
      ensureDebugMetadata(this.#debugMetadata, opIdx)?.dependencies.add(lastSave);
      this.#bboxes[opIdx] = this.#bboxes[lastSave];
    }
    return this;
  }
  recordOpenMarker(idx) {
    this.#savesStack.push(idx);
    return this;
  }
  getOpenMarker() {
    if (this.#savesStack.length === 0) {
      return null;
    }
    return this.#savesStack.at(-1);
  }
  recordCloseMarker(opIdx) {
    const lastSave = this.#savesStack.pop();
    if (lastSave !== void 0) {
      ensureDebugMetadata(this.#debugMetadata, opIdx)?.dependencies.add(lastSave);
      this.#bboxes[opIdx] = this.#bboxes[lastSave];
    }
    return this;
  }
  beginMarkedContent(opIdx) {
    this.#markedContentStack.push(opIdx);
    return this;
  }
  endMarkedContent(opIdx) {
    const lastSave = this.#markedContentStack.pop();
    if (lastSave !== void 0) {
      ensureDebugMetadata(this.#debugMetadata, opIdx)?.dependencies.add(lastSave);
      this.#bboxes[opIdx] = this.#bboxes[lastSave];
    }
    return this;
  }
  pushBaseTransform(ctx) {
    this.#baseTransformStack.push(Util.multiplyByDOMMatrix(this.#baseTransformStack.at(-1), ctx.getTransform()));
    return this;
  }
  popBaseTransform() {
    if (this.#baseTransformStack.length > 1) {
      this.#baseTransformStack.pop();
    }
    return this;
  }
  recordSimpleData(name, idx) {
    this.#simple[name] = idx;
    return this;
  }
  recordIncrementalData(name, idx) {
    this.#incremental[name].push(idx);
    return this;
  }
  resetIncrementalData(name, idx) {
    this.#incremental[name].length = 0;
    return this;
  }
  recordNamedData(name, idx) {
    this.#namedDependencies.set(name, idx);
    return this;
  }
  recordSimpleDataFromNamed(name, depName, fallbackIdx) {
    this.#simple[name] = this.#namedDependencies.get(depName) ?? fallbackIdx;
  }
  recordFutureForcedDependency(name, idx) {
    this.recordIncrementalData(FORCED_DEPENDENCY_LABEL, idx);
    return this;
  }
  inheritSimpleDataAsFutureForcedDependencies(names) {
    for (const name of names) {
      if (name in this.#simple) {
        this.recordFutureForcedDependency(name, this.#simple[name]);
      }
    }
    return this;
  }
  inheritPendingDependenciesAsFutureForcedDependencies() {
    for (const dep of this.#pendingDependencies) {
      this.recordFutureForcedDependency(FORCED_DEPENDENCY_LABEL, dep);
    }
    return this;
  }
  resetBBox(idx) {
    if (this.#pendingBBoxIdx !== idx) {
      this.#pendingBBoxIdx = idx;
      this.#pendingBBox[0] = Infinity;
      this.#pendingBBox[1] = Infinity;
      this.#pendingBBox[2] = -Infinity;
      this.#pendingBBox[3] = -Infinity;
    }
    return this;
  }
  recordClipBox(idx, ctx, minX, maxX, minY, maxY) {
    const transform = Util.multiplyByDOMMatrix(this.#baseTransformStack.at(-1), ctx.getTransform());
    const clipBox = [Infinity, Infinity, -Infinity, -Infinity];
    Util.axialAlignedBoundingBox([minX, minY, maxX, maxY], transform, clipBox);
    const intersection = Util.intersect(this.#clipBox, clipBox);
    if (intersection) {
      this.#clipBox[0] = intersection[0];
      this.#clipBox[1] = intersection[1];
      this.#clipBox[2] = intersection[2];
      this.#clipBox[3] = intersection[3];
    } else {
      this.#clipBox[0] = this.#clipBox[1] = Infinity;
      this.#clipBox[2] = this.#clipBox[3] = -Infinity;
    }
    return this;
  }
  recordBBox(idx, ctx, minX, maxX, minY, maxY) {
    const clipBox = this.#clipBox;
    if (clipBox[0] === Infinity) {
      return this;
    }
    const transform = Util.multiplyByDOMMatrix(this.#baseTransformStack.at(-1), ctx.getTransform());
    if (clipBox[0] === -Infinity) {
      Util.axialAlignedBoundingBox([minX, minY, maxX, maxY], transform, this.#pendingBBox);
      return this;
    }
    const bbox = [Infinity, Infinity, -Infinity, -Infinity];
    Util.axialAlignedBoundingBox([minX, minY, maxX, maxY], transform, bbox);
    this.#pendingBBox[0] = Math.min(this.#pendingBBox[0], Math.max(bbox[0], clipBox[0]));
    this.#pendingBBox[1] = Math.min(this.#pendingBBox[1], Math.max(bbox[1], clipBox[1]));
    this.#pendingBBox[2] = Math.max(this.#pendingBBox[2], Math.min(bbox[2], clipBox[2]));
    this.#pendingBBox[3] = Math.max(this.#pendingBBox[3], Math.min(bbox[3], clipBox[3]));
    return this;
  }
  recordCharacterBBox(idx, ctx, font, scale = 1, x2 = 0, y4 = 0, getMeasure) {
    const fontBBox = font.bbox;
    let isBBoxTrustworthy;
    let computedBBox;
    if (fontBBox) {
      isBBoxTrustworthy = fontBBox[2] !== fontBBox[0] && fontBBox[3] !== fontBBox[1] && this.#fontBBoxTrustworthy.get(font);
      if (isBBoxTrustworthy !== false) {
        computedBBox = [0, 0, 0, 0];
        Util.axialAlignedBoundingBox(fontBBox, font.fontMatrix, computedBBox);
        if (scale !== 1 || x2 !== 0 || y4 !== 0) {
          Util.scaleMinMax([scale, 0, 0, -scale, x2, y4], computedBBox);
        }
        if (isBBoxTrustworthy) {
          return this.recordBBox(idx, ctx, computedBBox[0], computedBBox[2], computedBBox[1], computedBBox[3]);
        }
      }
    }
    if (!getMeasure) {
      return this.recordFullPageBBox(idx);
    }
    const measure = getMeasure();
    if (fontBBox && computedBBox && isBBoxTrustworthy === void 0) {
      isBBoxTrustworthy = computedBBox[0] <= x2 - measure.actualBoundingBoxLeft && computedBBox[2] >= x2 + measure.actualBoundingBoxRight && computedBBox[1] <= y4 - measure.actualBoundingBoxAscent && computedBBox[3] >= y4 + measure.actualBoundingBoxDescent;
      this.#fontBBoxTrustworthy.set(font, isBBoxTrustworthy);
      if (isBBoxTrustworthy) {
        return this.recordBBox(idx, ctx, computedBBox[0], computedBBox[2], computedBBox[1], computedBBox[3]);
      }
    }
    return this.recordBBox(idx, ctx, x2 - measure.actualBoundingBoxLeft, x2 + measure.actualBoundingBoxRight, y4 - measure.actualBoundingBoxAscent, y4 + measure.actualBoundingBoxDescent);
  }
  recordFullPageBBox(idx) {
    this.#pendingBBox[0] = Math.max(0, this.#clipBox[0]);
    this.#pendingBBox[1] = Math.max(0, this.#clipBox[1]);
    this.#pendingBBox[2] = Math.min(this.#canvasWidth, this.#clipBox[2]);
    this.#pendingBBox[3] = Math.min(this.#canvasHeight, this.#clipBox[3]);
    return this;
  }
  getSimpleIndex(dependencyName) {
    return this.#simple[dependencyName];
  }
  recordDependencies(idx, dependencyNames) {
    const pendingDependencies = this.#pendingDependencies;
    const simple = this.#simple;
    const incremental = this.#incremental;
    for (const name of dependencyNames) {
      if (name in this.#simple) {
        pendingDependencies.add(simple[name]);
      } else if (name in incremental) {
        incremental[name].forEach(pendingDependencies.add, pendingDependencies);
      }
    }
    return this;
  }
  recordNamedDependency(idx, name) {
    if (this.#namedDependencies.has(name)) {
      this.#pendingDependencies.add(this.#namedDependencies.get(name));
    }
    return this;
  }
  recordOperation(idx, preserve = false) {
    this.recordDependencies(idx, [FORCED_DEPENDENCY_LABEL]);
    if (this.#debugMetadata) {
      const metadata = ensureDebugMetadata(this.#debugMetadata, idx);
      const {
        dependencies
      } = metadata;
      this.#pendingDependencies.forEach(dependencies.add, dependencies);
      this.#savesStack.forEach(dependencies.add, dependencies);
      this.#markedContentStack.forEach(dependencies.add, dependencies);
      dependencies.delete(idx);
      metadata.isRenderingOperation = true;
    }
    if (this.#pendingBBoxIdx === idx) {
      const minX = floor(this.#pendingBBox[0] * 256 / this.#canvasWidth);
      const minY = floor(this.#pendingBBox[1] * 256 / this.#canvasHeight);
      const maxX = ceil(this.#pendingBBox[2] * 256 / this.#canvasWidth);
      const maxY = ceil(this.#pendingBBox[3] * 256 / this.#canvasHeight);
      expandBBox(this.#bboxesCoords, idx, minX, minY, maxX, maxY);
      for (const depIdx of this.#pendingDependencies) {
        if (depIdx !== idx) {
          expandBBox(this.#bboxesCoords, depIdx, minX, minY, maxX, maxY);
        }
      }
      for (const saveIdx of this.#savesStack) {
        if (saveIdx !== idx) {
          expandBBox(this.#bboxesCoords, saveIdx, minX, minY, maxX, maxY);
        }
      }
      for (const saveIdx of this.#markedContentStack) {
        if (saveIdx !== idx) {
          expandBBox(this.#bboxesCoords, saveIdx, minX, minY, maxX, maxY);
        }
      }
      if (!preserve) {
        this.#pendingDependencies.clear();
        this.#pendingBBoxIdx = -1;
      }
    }
    return this;
  }
  recordShowTextOperation(idx, preserve = false) {
    const deps = Array.from(this.#pendingDependencies);
    this.recordOperation(idx, preserve);
    this.recordIncrementalData("sameLineText", idx);
    for (const dep of deps) {
      this.recordIncrementalData("sameLineText", dep);
    }
    return this;
  }
  bboxToClipBoxDropOperation(idx, preserve = false) {
    if (this.#pendingBBoxIdx === idx) {
      this.#pendingBBoxIdx = -1;
      this.#clipBox[0] = Math.max(this.#clipBox[0], this.#pendingBBox[0]);
      this.#clipBox[1] = Math.max(this.#clipBox[1], this.#pendingBBox[1]);
      this.#clipBox[2] = Math.min(this.#clipBox[2], this.#pendingBBox[2]);
      this.#clipBox[3] = Math.min(this.#clipBox[3], this.#pendingBBox[3]);
      if (!preserve) {
        this.#pendingDependencies.clear();
      }
    }
    return this;
  }
  _takePendingDependencies() {
    const pendingDependencies = this.#pendingDependencies;
    this.#pendingDependencies = /* @__PURE__ */ new Set();
    return pendingDependencies;
  }
  _extractOperation(idx) {
    const operation = this.#operations.get(idx);
    this.#operations.delete(idx);
    return operation;
  }
  _pushPendingDependencies(dependencies) {
    for (const dep of dependencies) {
      this.#pendingDependencies.add(dep);
    }
  }
  take() {
    this.#fontBBoxTrustworthy.clear();
    return new BBoxReader(this.#bboxes, this.#bboxesCoords);
  }
  takeDebugMetadata() {
    return this.#debugMetadata;
  }
};
var CanvasNestedDependencyTracker = class _CanvasNestedDependencyTracker {
  #dependencyTracker;
  #opIdx;
  #ignoreBBoxes;
  #nestingLevel = 0;
  #savesLevel = 0;
  constructor(dependencyTracker, opIdx, ignoreBBoxes) {
    if (dependencyTracker instanceof _CanvasNestedDependencyTracker && dependencyTracker.#ignoreBBoxes === !!ignoreBBoxes) {
      return dependencyTracker;
    }
    this.#dependencyTracker = dependencyTracker;
    this.#opIdx = opIdx;
    this.#ignoreBBoxes = !!ignoreBBoxes;
  }
  growOperationsCount() {
    throw new Error("Unreachable");
  }
  save(opIdx) {
    this.#savesLevel++;
    this.#dependencyTracker.save(this.#opIdx);
    return this;
  }
  restore(opIdx) {
    if (this.#savesLevel > 0) {
      this.#dependencyTracker.restore(this.#opIdx);
      this.#savesLevel--;
    }
    return this;
  }
  recordOpenMarker(idx) {
    this.#nestingLevel++;
    return this;
  }
  getOpenMarker() {
    return this.#nestingLevel > 0 ? this.#opIdx : this.#dependencyTracker.getOpenMarker();
  }
  recordCloseMarker(idx) {
    this.#nestingLevel--;
    return this;
  }
  beginMarkedContent(opIdx) {
    return this;
  }
  endMarkedContent(opIdx) {
    return this;
  }
  pushBaseTransform(ctx) {
    this.#dependencyTracker.pushBaseTransform(ctx);
    return this;
  }
  popBaseTransform() {
    this.#dependencyTracker.popBaseTransform();
    return this;
  }
  recordSimpleData(name, idx) {
    this.#dependencyTracker.recordSimpleData(name, this.#opIdx);
    return this;
  }
  recordIncrementalData(name, idx) {
    this.#dependencyTracker.recordIncrementalData(name, this.#opIdx);
    return this;
  }
  resetIncrementalData(name, idx) {
    this.#dependencyTracker.resetIncrementalData(name, this.#opIdx);
    return this;
  }
  recordNamedData(name, idx) {
    return this;
  }
  recordSimpleDataFromNamed(name, depName, fallbackIdx) {
    this.#dependencyTracker.recordSimpleDataFromNamed(name, depName, this.#opIdx);
    return this;
  }
  recordFutureForcedDependency(name, idx) {
    this.#dependencyTracker.recordFutureForcedDependency(name, this.#opIdx);
    return this;
  }
  inheritSimpleDataAsFutureForcedDependencies(names) {
    this.#dependencyTracker.inheritSimpleDataAsFutureForcedDependencies(names);
    return this;
  }
  inheritPendingDependenciesAsFutureForcedDependencies() {
    this.#dependencyTracker.inheritPendingDependenciesAsFutureForcedDependencies();
    return this;
  }
  resetBBox(idx) {
    if (!this.#ignoreBBoxes) {
      this.#dependencyTracker.resetBBox(this.#opIdx);
    }
    return this;
  }
  recordClipBox(idx, ctx, minX, maxX, minY, maxY) {
    if (!this.#ignoreBBoxes) {
      this.#dependencyTracker.recordClipBox(this.#opIdx, ctx, minX, maxX, minY, maxY);
    }
    return this;
  }
  recordBBox(idx, ctx, minX, maxX, minY, maxY) {
    if (!this.#ignoreBBoxes) {
      this.#dependencyTracker.recordBBox(this.#opIdx, ctx, minX, maxX, minY, maxY);
    }
    return this;
  }
  recordCharacterBBox(idx, ctx, font, scale, x2, y4, getMeasure) {
    if (!this.#ignoreBBoxes) {
      this.#dependencyTracker.recordCharacterBBox(this.#opIdx, ctx, font, scale, x2, y4, getMeasure);
    }
    return this;
  }
  recordFullPageBBox(idx) {
    if (!this.#ignoreBBoxes) {
      this.#dependencyTracker.recordFullPageBBox(this.#opIdx);
    }
    return this;
  }
  getSimpleIndex(dependencyName) {
    return this.#dependencyTracker.getSimpleIndex(dependencyName);
  }
  recordDependencies(idx, dependencyNames) {
    this.#dependencyTracker.recordDependencies(this.#opIdx, dependencyNames);
    return this;
  }
  recordNamedDependency(idx, name) {
    this.#dependencyTracker.recordNamedDependency(this.#opIdx, name);
    return this;
  }
  recordOperation(idx) {
    this.#dependencyTracker.recordOperation(this.#opIdx, true);
    return this;
  }
  recordShowTextOperation(idx) {
    this.#dependencyTracker.recordShowTextOperation(this.#opIdx, true);
    return this;
  }
  bboxToClipBoxDropOperation(idx) {
    if (!this.#ignoreBBoxes) {
      this.#dependencyTracker.bboxToClipBoxDropOperation(this.#opIdx, true);
    }
    return this;
  }
  take() {
    throw new Error("Unreachable");
  }
  takeDebugMetadata() {
    throw new Error("Unreachable");
  }
};
var Dependencies = {
  stroke: ["path", "transform", "filter", "strokeColor", "strokeAlpha", "lineWidth", "lineCap", "lineJoin", "miterLimit", "dash"],
  fill: ["path", "transform", "filter", "fillColor", "fillAlpha", "globalCompositeOperation", "SMask"],
  imageXObject: ["transform", "SMask", "filter", "fillAlpha", "strokeAlpha", "globalCompositeOperation"],
  rawFillPath: ["filter", "fillColor", "fillAlpha"],
  showText: ["transform", "leading", "charSpacing", "wordSpacing", "hScale", "textRise", "moveText", "textMatrix", "font", "fontObj", "filter", "fillColor", "textRenderingMode", "SMask", "fillAlpha", "strokeAlpha", "globalCompositeOperation", "sameLineText"],
  transform: ["transform"],
  transformAndFill: ["transform", "fillColor"]
};
var PathType = {
  FILL: "Fill",
  STROKE: "Stroke",
  SHADING: "Shading"
};
function applyBoundingBox(ctx, bbox) {
  if (!bbox) {
    return;
  }
  const width = bbox[2] - bbox[0];
  const height = bbox[3] - bbox[1];
  const region = new Path2D();
  region.rect(bbox[0], bbox[1], width, height);
  ctx.clip(region);
}
var BaseShadingPattern = class {
  isModifyingCurrentTransform() {
    return false;
  }
  getPattern() {
    unreachable("Abstract method `getPattern` called.");
  }
};
var RadialAxialShadingPattern = class extends BaseShadingPattern {
  constructor(IR) {
    super();
    this._type = IR[1];
    this._bbox = IR[2];
    this._colorStops = IR[3];
    this._p0 = IR[4];
    this._p1 = IR[5];
    this._r0 = IR[6];
    this._r1 = IR[7];
    this.matrix = null;
  }
  _createGradient(ctx) {
    let grad;
    if (this._type === "axial") {
      grad = ctx.createLinearGradient(this._p0[0], this._p0[1], this._p1[0], this._p1[1]);
    } else if (this._type === "radial") {
      grad = ctx.createRadialGradient(this._p0[0], this._p0[1], this._r0, this._p1[0], this._p1[1], this._r1);
    }
    for (const colorStop of this._colorStops) {
      grad.addColorStop(colorStop[0], colorStop[1]);
    }
    return grad;
  }
  getPattern(ctx, owner, inverse, pathType) {
    let pattern;
    if (pathType === PathType.STROKE || pathType === PathType.FILL) {
      const ownerBBox = owner.current.getClippedPathBoundingBox(pathType, getCurrentTransform(ctx)) || [0, 0, 0, 0];
      const width = Math.ceil(ownerBBox[2] - ownerBBox[0]) || 1;
      const height = Math.ceil(ownerBBox[3] - ownerBBox[1]) || 1;
      const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", width, height);
      const tmpCtx = tmpCanvas.context;
      tmpCtx.clearRect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
      tmpCtx.beginPath();
      tmpCtx.rect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
      tmpCtx.translate(-ownerBBox[0], -ownerBBox[1]);
      inverse = Util.transform(inverse, [1, 0, 0, 1, ownerBBox[0], ownerBBox[1]]);
      tmpCtx.transform(...owner.baseTransform);
      if (this.matrix) {
        tmpCtx.transform(...this.matrix);
      }
      applyBoundingBox(tmpCtx, this._bbox);
      tmpCtx.fillStyle = this._createGradient(tmpCtx);
      tmpCtx.fill();
      pattern = ctx.createPattern(tmpCanvas.canvas, "no-repeat");
      const domMatrix = new DOMMatrix(inverse);
      pattern.setTransform(domMatrix);
    } else {
      applyBoundingBox(ctx, this._bbox);
      pattern = this._createGradient(ctx);
    }
    return pattern;
  }
};
function drawTriangle(data, context, p1, p22, p32, c1, c22, c32) {
  const coords = context.coords, colors = context.colors;
  const bytes = data.data, rowSize = data.width * 4;
  let tmp;
  if (coords[p1 + 1] > coords[p22 + 1]) {
    tmp = p1;
    p1 = p22;
    p22 = tmp;
    tmp = c1;
    c1 = c22;
    c22 = tmp;
  }
  if (coords[p22 + 1] > coords[p32 + 1]) {
    tmp = p22;
    p22 = p32;
    p32 = tmp;
    tmp = c22;
    c22 = c32;
    c32 = tmp;
  }
  if (coords[p1 + 1] > coords[p22 + 1]) {
    tmp = p1;
    p1 = p22;
    p22 = tmp;
    tmp = c1;
    c1 = c22;
    c22 = tmp;
  }
  const x1 = (coords[p1] + context.offsetX) * context.scaleX;
  const y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
  const x2 = (coords[p22] + context.offsetX) * context.scaleX;
  const y22 = (coords[p22 + 1] + context.offsetY) * context.scaleY;
  const x3 = (coords[p32] + context.offsetX) * context.scaleX;
  const y32 = (coords[p32 + 1] + context.offsetY) * context.scaleY;
  if (y1 >= y32) {
    return;
  }
  const c1r = colors[c1], c1g = colors[c1 + 1], c1b = colors[c1 + 2];
  const c2r = colors[c22], c2g = colors[c22 + 1], c2b = colors[c22 + 2];
  const c3r = colors[c32], c3g = colors[c32 + 1], c3b = colors[c32 + 2];
  const minY = Math.round(y1), maxY = Math.round(y32);
  let xa, car, cag, cab;
  let xb, cbr, cbg, cbb;
  for (let y4 = minY; y4 <= maxY; y4++) {
    if (y4 < y22) {
      const k3 = y4 < y1 ? 0 : (y1 - y4) / (y1 - y22);
      xa = x1 - (x1 - x2) * k3;
      car = c1r - (c1r - c2r) * k3;
      cag = c1g - (c1g - c2g) * k3;
      cab = c1b - (c1b - c2b) * k3;
    } else {
      let k3;
      if (y4 > y32) {
        k3 = 1;
      } else if (y22 === y32) {
        k3 = 0;
      } else {
        k3 = (y22 - y4) / (y22 - y32);
      }
      xa = x2 - (x2 - x3) * k3;
      car = c2r - (c2r - c3r) * k3;
      cag = c2g - (c2g - c3g) * k3;
      cab = c2b - (c2b - c3b) * k3;
    }
    let k2;
    if (y4 < y1) {
      k2 = 0;
    } else if (y4 > y32) {
      k2 = 1;
    } else {
      k2 = (y1 - y4) / (y1 - y32);
    }
    xb = x1 - (x1 - x3) * k2;
    cbr = c1r - (c1r - c3r) * k2;
    cbg = c1g - (c1g - c3g) * k2;
    cbb = c1b - (c1b - c3b) * k2;
    const x1_ = Math.round(Math.min(xa, xb));
    const x2_ = Math.round(Math.max(xa, xb));
    let j3 = rowSize * y4 + x1_ * 4;
    for (let x4 = x1_; x4 <= x2_; x4++) {
      k2 = (xa - x4) / (xa - xb);
      if (k2 < 0) {
        k2 = 0;
      } else if (k2 > 1) {
        k2 = 1;
      }
      bytes[j3++] = car - (car - cbr) * k2 | 0;
      bytes[j3++] = cag - (cag - cbg) * k2 | 0;
      bytes[j3++] = cab - (cab - cbb) * k2 | 0;
      bytes[j3++] = 255;
    }
  }
}
function drawFigure(data, figure, context) {
  const ps = figure.coords;
  const cs = figure.colors;
  let i7, ii;
  switch (figure.type) {
    case MeshFigureType.LATTICE:
      const verticesPerRow = figure.verticesPerRow;
      const rows = Math.floor(ps.length / verticesPerRow) - 1;
      const cols = verticesPerRow - 1;
      for (i7 = 0; i7 < rows; i7++) {
        let q2 = i7 * verticesPerRow;
        for (let j3 = 0; j3 < cols; j3++, q2++) {
          drawTriangle(data, context, ps[q2], ps[q2 + 1], ps[q2 + verticesPerRow], cs[q2], cs[q2 + 1], cs[q2 + verticesPerRow]);
          drawTriangle(data, context, ps[q2 + verticesPerRow + 1], ps[q2 + 1], ps[q2 + verticesPerRow], cs[q2 + verticesPerRow + 1], cs[q2 + 1], cs[q2 + verticesPerRow]);
        }
      }
      break;
    case MeshFigureType.TRIANGLES:
      for (i7 = 0, ii = ps.length; i7 < ii; i7 += 3) {
        drawTriangle(data, context, ps[i7], ps[i7 + 1], ps[i7 + 2], cs[i7], cs[i7 + 1], cs[i7 + 2]);
      }
      break;
    default:
      throw new Error("illegal figure");
  }
}
var MeshShadingPattern = class extends BaseShadingPattern {
  constructor(IR) {
    super();
    this._coords = IR[2];
    this._colors = IR[3];
    this._figures = IR[4];
    this._bounds = IR[5];
    this._bbox = IR[6];
    this._background = IR[7];
    this.matrix = null;
  }
  _createMeshCanvas(combinedScale, backgroundColor, cachedCanvases) {
    const EXPECTED_SCALE = 1.1;
    const MAX_PATTERN_SIZE = 3e3;
    const BORDER_SIZE = 2;
    const offsetX = Math.floor(this._bounds[0]);
    const offsetY = Math.floor(this._bounds[1]);
    const boundsWidth = Math.ceil(this._bounds[2]) - offsetX;
    const boundsHeight = Math.ceil(this._bounds[3]) - offsetY;
    const width = Math.min(Math.ceil(Math.abs(boundsWidth * combinedScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
    const height = Math.min(Math.ceil(Math.abs(boundsHeight * combinedScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
    const scaleX = boundsWidth / width;
    const scaleY = boundsHeight / height;
    const context = {
      coords: this._coords,
      colors: this._colors,
      offsetX: -offsetX,
      offsetY: -offsetY,
      scaleX: 1 / scaleX,
      scaleY: 1 / scaleY
    };
    const paddedWidth = width + BORDER_SIZE * 2;
    const paddedHeight = height + BORDER_SIZE * 2;
    const tmpCanvas = cachedCanvases.getCanvas("mesh", paddedWidth, paddedHeight);
    const tmpCtx = tmpCanvas.context;
    const data = tmpCtx.createImageData(width, height);
    if (backgroundColor) {
      const bytes = data.data;
      for (let i7 = 0, ii = bytes.length; i7 < ii; i7 += 4) {
        bytes[i7] = backgroundColor[0];
        bytes[i7 + 1] = backgroundColor[1];
        bytes[i7 + 2] = backgroundColor[2];
        bytes[i7 + 3] = 255;
      }
    }
    for (const figure of this._figures) {
      drawFigure(data, figure, context);
    }
    tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE);
    const canvas = tmpCanvas.canvas;
    return {
      canvas,
      offsetX: offsetX - BORDER_SIZE * scaleX,
      offsetY: offsetY - BORDER_SIZE * scaleY,
      scaleX,
      scaleY
    };
  }
  isModifyingCurrentTransform() {
    return true;
  }
  getPattern(ctx, owner, inverse, pathType) {
    applyBoundingBox(ctx, this._bbox);
    const scale = new Float32Array(2);
    if (pathType === PathType.SHADING) {
      Util.singularValueDecompose2dScale(getCurrentTransform(ctx), scale);
    } else if (this.matrix) {
      Util.singularValueDecompose2dScale(this.matrix, scale);
      const [matrixScaleX, matrixScaleY] = scale;
      Util.singularValueDecompose2dScale(owner.baseTransform, scale);
      scale[0] *= matrixScaleX;
      scale[1] *= matrixScaleY;
    } else {
      Util.singularValueDecompose2dScale(owner.baseTransform, scale);
    }
    const temporaryPatternCanvas = this._createMeshCanvas(scale, pathType === PathType.SHADING ? null : this._background, owner.cachedCanvases);
    if (pathType !== PathType.SHADING) {
      ctx.setTransform(...owner.baseTransform);
      if (this.matrix) {
        ctx.transform(...this.matrix);
      }
    }
    ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
    ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY);
    return ctx.createPattern(temporaryPatternCanvas.canvas, "no-repeat");
  }
};
var DummyShadingPattern = class extends BaseShadingPattern {
  getPattern() {
    return "hotpink";
  }
};
function getShadingPattern(IR) {
  switch (IR[0]) {
    case "RadialAxial":
      return new RadialAxialShadingPattern(IR);
    case "Mesh":
      return new MeshShadingPattern(IR);
    case "Dummy":
      return new DummyShadingPattern();
  }
  throw new Error(`Unknown IR type: ${IR[0]}`);
}
var PaintType = {
  COLORED: 1,
  UNCOLORED: 2
};
var TilingPattern = class _TilingPattern {
  static MAX_PATTERN_SIZE = 3e3;
  constructor(IR, ctx, canvasGraphicsFactory, baseTransform) {
    this.color = IR[1];
    this.operatorList = IR[2];
    this.matrix = IR[3];
    this.bbox = IR[4];
    this.xstep = IR[5];
    this.ystep = IR[6];
    this.paintType = IR[7];
    this.tilingType = IR[8];
    this.ctx = ctx;
    this.canvasGraphicsFactory = canvasGraphicsFactory;
    this.baseTransform = baseTransform;
  }
  createPatternCanvas(owner, opIdx) {
    const {
      bbox,
      operatorList,
      paintType,
      tilingType,
      color,
      canvasGraphicsFactory
    } = this;
    let {
      xstep,
      ystep
    } = this;
    xstep = Math.abs(xstep);
    ystep = Math.abs(ystep);
    info("TilingType: " + tilingType);
    const x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3];
    const width = x1 - x0;
    const height = y1 - y0;
    const scale = new Float32Array(2);
    Util.singularValueDecompose2dScale(this.matrix, scale);
    const [matrixScaleX, matrixScaleY] = scale;
    Util.singularValueDecompose2dScale(this.baseTransform, scale);
    const combinedScaleX = matrixScaleX * scale[0];
    const combinedScaleY = matrixScaleY * scale[1];
    let canvasWidth = width, canvasHeight = height, redrawHorizontally = false, redrawVertically = false;
    const xScaledStep = Math.ceil(xstep * combinedScaleX);
    const yScaledStep = Math.ceil(ystep * combinedScaleY);
    const xScaledWidth = Math.ceil(width * combinedScaleX);
    const yScaledHeight = Math.ceil(height * combinedScaleY);
    if (xScaledStep >= xScaledWidth) {
      canvasWidth = xstep;
    } else {
      redrawHorizontally = true;
    }
    if (yScaledStep >= yScaledHeight) {
      canvasHeight = ystep;
    } else {
      redrawVertically = true;
    }
    const dimx = this.getSizeAndScale(canvasWidth, this.ctx.canvas.width, combinedScaleX);
    const dimy = this.getSizeAndScale(canvasHeight, this.ctx.canvas.height, combinedScaleY);
    const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", dimx.size, dimy.size);
    const tmpCtx = tmpCanvas.context;
    const graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx, opIdx);
    graphics.groupLevel = owner.groupLevel;
    this.setFillAndStrokeStyleToContext(graphics, paintType, color);
    tmpCtx.translate(-dimx.scale * x0, -dimy.scale * y0);
    graphics.transform(0, dimx.scale, 0, 0, dimy.scale, 0, 0);
    tmpCtx.save();
    graphics.dependencyTracker?.save();
    this.clipBbox(graphics, x0, y0, x1, y1);
    graphics.baseTransform = getCurrentTransform(graphics.ctx);
    graphics.executeOperatorList(operatorList);
    graphics.endDrawing();
    graphics.dependencyTracker?.restore();
    tmpCtx.restore();
    if (redrawHorizontally || redrawVertically) {
      const image = tmpCanvas.canvas;
      if (redrawHorizontally) {
        canvasWidth = xstep;
      }
      if (redrawVertically) {
        canvasHeight = ystep;
      }
      const dimx2 = this.getSizeAndScale(canvasWidth, this.ctx.canvas.width, combinedScaleX);
      const dimy2 = this.getSizeAndScale(canvasHeight, this.ctx.canvas.height, combinedScaleY);
      const xSize = dimx2.size;
      const ySize = dimy2.size;
      const tmpCanvas2 = owner.cachedCanvases.getCanvas("pattern-workaround", xSize, ySize);
      const tmpCtx2 = tmpCanvas2.context;
      const ii = redrawHorizontally ? Math.floor(width / xstep) : 0;
      const jj = redrawVertically ? Math.floor(height / ystep) : 0;
      for (let i7 = 0; i7 <= ii; i7++) {
        for (let j3 = 0; j3 <= jj; j3++) {
          tmpCtx2.drawImage(image, xSize * i7, ySize * j3, xSize, ySize, 0, 0, xSize, ySize);
        }
      }
      return {
        canvas: tmpCanvas2.canvas,
        scaleX: dimx2.scale,
        scaleY: dimy2.scale,
        offsetX: x0,
        offsetY: y0
      };
    }
    return {
      canvas: tmpCanvas.canvas,
      scaleX: dimx.scale,
      scaleY: dimy.scale,
      offsetX: x0,
      offsetY: y0
    };
  }
  getSizeAndScale(step, realOutputSize, scale) {
    const maxSize = Math.max(_TilingPattern.MAX_PATTERN_SIZE, realOutputSize);
    let size = Math.ceil(step * scale);
    if (size >= maxSize) {
      size = maxSize;
    } else {
      scale = size / step;
    }
    return {
      scale,
      size
    };
  }
  clipBbox(graphics, x0, y0, x1, y1) {
    const bboxWidth = x1 - x0;
    const bboxHeight = y1 - y0;
    graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
    Util.axialAlignedBoundingBox([x0, y0, x1, y1], getCurrentTransform(graphics.ctx), graphics.current.minMax);
    graphics.clip();
    graphics.endPath();
  }
  setFillAndStrokeStyleToContext(graphics, paintType, color) {
    const context = graphics.ctx, current2 = graphics.current;
    switch (paintType) {
      case PaintType.COLORED:
        const {
          fillStyle,
          strokeStyle
        } = this.ctx;
        context.fillStyle = current2.fillColor = fillStyle;
        context.strokeStyle = current2.strokeColor = strokeStyle;
        break;
      case PaintType.UNCOLORED:
        context.fillStyle = context.strokeStyle = color;
        current2.fillColor = current2.strokeColor = color;
        break;
      default:
        throw new FormatError(`Unsupported paint type: ${paintType}`);
    }
  }
  isModifyingCurrentTransform() {
    return false;
  }
  getPattern(ctx, owner, inverse, pathType, opIdx) {
    let matrix = inverse;
    if (pathType !== PathType.SHADING) {
      matrix = Util.transform(matrix, owner.baseTransform);
      if (this.matrix) {
        matrix = Util.transform(matrix, this.matrix);
      }
    }
    const temporaryPatternCanvas = this.createPatternCanvas(owner, opIdx);
    let domMatrix = new DOMMatrix(matrix);
    domMatrix = domMatrix.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
    domMatrix = domMatrix.scale(1 / temporaryPatternCanvas.scaleX, 1 / temporaryPatternCanvas.scaleY);
    const pattern = ctx.createPattern(temporaryPatternCanvas.canvas, "repeat");
    pattern.setTransform(domMatrix);
    return pattern;
  }
};
function convertBlackAndWhiteToRGBA({
  src,
  srcPos = 0,
  dest,
  width,
  height,
  nonBlackColor = 4294967295,
  inverseDecode = false
}) {
  const black = util_FeatureTest.isLittleEndian ? 4278190080 : 255;
  const [zeroMapping, oneMapping] = inverseDecode ? [nonBlackColor, black] : [black, nonBlackColor];
  const widthInSource = width >> 3;
  const widthRemainder = width & 7;
  const srcLength = src.length;
  dest = new Uint32Array(dest.buffer);
  let destPos = 0;
  for (let i7 = 0; i7 < height; i7++) {
    for (const max = srcPos + widthInSource; srcPos < max; srcPos++) {
      const elem2 = srcPos < srcLength ? src[srcPos] : 255;
      dest[destPos++] = elem2 & 128 ? oneMapping : zeroMapping;
      dest[destPos++] = elem2 & 64 ? oneMapping : zeroMapping;
      dest[destPos++] = elem2 & 32 ? oneMapping : zeroMapping;
      dest[destPos++] = elem2 & 16 ? oneMapping : zeroMapping;
      dest[destPos++] = elem2 & 8 ? oneMapping : zeroMapping;
      dest[destPos++] = elem2 & 4 ? oneMapping : zeroMapping;
      dest[destPos++] = elem2 & 2 ? oneMapping : zeroMapping;
      dest[destPos++] = elem2 & 1 ? oneMapping : zeroMapping;
    }
    if (widthRemainder === 0) {
      continue;
    }
    const elem = srcPos < srcLength ? src[srcPos++] : 255;
    for (let j3 = 0; j3 < widthRemainder; j3++) {
      dest[destPos++] = elem & 1 << 7 - j3 ? oneMapping : zeroMapping;
    }
  }
  return {
    srcPos,
    destPos
  };
}
var MIN_FONT_SIZE = 16;
var MAX_FONT_SIZE = 100;
var EXECUTION_TIME = 15;
var EXECUTION_STEPS = 10;
var FULL_CHUNK_HEIGHT = 16;
var SCALE_MATRIX = new DOMMatrix();
var XY = new Float32Array(2);
var MIN_MAX_INIT = new Float32Array([Infinity, Infinity, -Infinity, -Infinity]);
function mirrorContextOperations(ctx, destCtx) {
  if (ctx._removeMirroring) {
    throw new Error("Context is already forwarding operations.");
  }
  ctx.__originalSave = ctx.save;
  ctx.__originalRestore = ctx.restore;
  ctx.__originalRotate = ctx.rotate;
  ctx.__originalScale = ctx.scale;
  ctx.__originalTranslate = ctx.translate;
  ctx.__originalTransform = ctx.transform;
  ctx.__originalSetTransform = ctx.setTransform;
  ctx.__originalResetTransform = ctx.resetTransform;
  ctx.__originalClip = ctx.clip;
  ctx.__originalMoveTo = ctx.moveTo;
  ctx.__originalLineTo = ctx.lineTo;
  ctx.__originalBezierCurveTo = ctx.bezierCurveTo;
  ctx.__originalRect = ctx.rect;
  ctx.__originalClosePath = ctx.closePath;
  ctx.__originalBeginPath = ctx.beginPath;
  ctx._removeMirroring = () => {
    ctx.save = ctx.__originalSave;
    ctx.restore = ctx.__originalRestore;
    ctx.rotate = ctx.__originalRotate;
    ctx.scale = ctx.__originalScale;
    ctx.translate = ctx.__originalTranslate;
    ctx.transform = ctx.__originalTransform;
    ctx.setTransform = ctx.__originalSetTransform;
    ctx.resetTransform = ctx.__originalResetTransform;
    ctx.clip = ctx.__originalClip;
    ctx.moveTo = ctx.__originalMoveTo;
    ctx.lineTo = ctx.__originalLineTo;
    ctx.bezierCurveTo = ctx.__originalBezierCurveTo;
    ctx.rect = ctx.__originalRect;
    ctx.closePath = ctx.__originalClosePath;
    ctx.beginPath = ctx.__originalBeginPath;
    delete ctx._removeMirroring;
  };
  ctx.save = function() {
    destCtx.save();
    this.__originalSave();
  };
  ctx.restore = function() {
    destCtx.restore();
    this.__originalRestore();
  };
  ctx.translate = function(x2, y4) {
    destCtx.translate(x2, y4);
    this.__originalTranslate(x2, y4);
  };
  ctx.scale = function(x2, y4) {
    destCtx.scale(x2, y4);
    this.__originalScale(x2, y4);
  };
  ctx.transform = function(a3, b4, c6, d4, e9, f4) {
    destCtx.transform(a3, b4, c6, d4, e9, f4);
    this.__originalTransform(a3, b4, c6, d4, e9, f4);
  };
  ctx.setTransform = function(a3, b4, c6, d4, e9, f4) {
    destCtx.setTransform(a3, b4, c6, d4, e9, f4);
    this.__originalSetTransform(a3, b4, c6, d4, e9, f4);
  };
  ctx.resetTransform = function() {
    destCtx.resetTransform();
    this.__originalResetTransform();
  };
  ctx.rotate = function(angle) {
    destCtx.rotate(angle);
    this.__originalRotate(angle);
  };
  ctx.clip = function(rule) {
    destCtx.clip(rule);
    this.__originalClip(rule);
  };
  ctx.moveTo = function(x2, y4) {
    destCtx.moveTo(x2, y4);
    this.__originalMoveTo(x2, y4);
  };
  ctx.lineTo = function(x2, y4) {
    destCtx.lineTo(x2, y4);
    this.__originalLineTo(x2, y4);
  };
  ctx.bezierCurveTo = function(cp1x, cp1y, cp2x, cp2y, x2, y4) {
    destCtx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x2, y4);
    this.__originalBezierCurveTo(cp1x, cp1y, cp2x, cp2y, x2, y4);
  };
  ctx.rect = function(x2, y4, width, height) {
    destCtx.rect(x2, y4, width, height);
    this.__originalRect(x2, y4, width, height);
  };
  ctx.closePath = function() {
    destCtx.closePath();
    this.__originalClosePath();
  };
  ctx.beginPath = function() {
    destCtx.beginPath();
    this.__originalBeginPath();
  };
}
var CachedCanvases = class {
  constructor(canvasFactory) {
    this.canvasFactory = canvasFactory;
    this.cache = /* @__PURE__ */ Object.create(null);
  }
  getCanvas(id, width, height) {
    let canvasEntry;
    if (this.cache[id] !== void 0) {
      canvasEntry = this.cache[id];
      this.canvasFactory.reset(canvasEntry, width, height);
    } else {
      canvasEntry = this.canvasFactory.create(width, height);
      this.cache[id] = canvasEntry;
    }
    return canvasEntry;
  }
  delete(id) {
    delete this.cache[id];
  }
  clear() {
    for (const id in this.cache) {
      const canvasEntry = this.cache[id];
      this.canvasFactory.destroy(canvasEntry);
      delete this.cache[id];
    }
  }
};
function drawImageAtIntegerCoords(ctx, srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH) {
  const [a3, b4, c6, d4, tx, ty] = getCurrentTransform(ctx);
  if (b4 === 0 && c6 === 0) {
    const tlX = destX * a3 + tx;
    const rTlX = Math.round(tlX);
    const tlY = destY * d4 + ty;
    const rTlY = Math.round(tlY);
    const brX = (destX + destW) * a3 + tx;
    const rWidth = Math.abs(Math.round(brX) - rTlX) || 1;
    const brY = (destY + destH) * d4 + ty;
    const rHeight = Math.abs(Math.round(brY) - rTlY) || 1;
    ctx.setTransform(Math.sign(a3), 0, 0, Math.sign(d4), rTlX, rTlY);
    ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rWidth, rHeight);
    ctx.setTransform(a3, b4, c6, d4, tx, ty);
    return [rWidth, rHeight];
  }
  if (a3 === 0 && d4 === 0) {
    const tlX = destY * c6 + tx;
    const rTlX = Math.round(tlX);
    const tlY = destX * b4 + ty;
    const rTlY = Math.round(tlY);
    const brX = (destY + destH) * c6 + tx;
    const rWidth = Math.abs(Math.round(brX) - rTlX) || 1;
    const brY = (destX + destW) * b4 + ty;
    const rHeight = Math.abs(Math.round(brY) - rTlY) || 1;
    ctx.setTransform(0, Math.sign(b4), Math.sign(c6), 0, rTlX, rTlY);
    ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rHeight, rWidth);
    ctx.setTransform(a3, b4, c6, d4, tx, ty);
    return [rHeight, rWidth];
  }
  ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH);
  const scaleX = Math.hypot(a3, b4);
  const scaleY = Math.hypot(c6, d4);
  return [scaleX * destW, scaleY * destH];
}
var CanvasExtraState = class {
  alphaIsShape = false;
  fontSize = 0;
  fontSizeScale = 1;
  textMatrix = null;
  textMatrixScale = 1;
  fontMatrix = FONT_IDENTITY_MATRIX;
  leading = 0;
  x = 0;
  y = 0;
  lineX = 0;
  lineY = 0;
  charSpacing = 0;
  wordSpacing = 0;
  textHScale = 1;
  textRenderingMode = TextRenderingMode.FILL;
  textRise = 0;
  fillColor = "#000000";
  strokeColor = "#000000";
  patternFill = false;
  patternStroke = false;
  fillAlpha = 1;
  strokeAlpha = 1;
  lineWidth = 1;
  activeSMask = null;
  transferMaps = "none";
  constructor(width, height, preInit) {
    preInit?.(this);
    this.clipBox = new Float32Array([0, 0, width, height]);
    this.minMax = MIN_MAX_INIT.slice();
  }
  clone() {
    const clone = Object.create(this);
    clone.clipBox = this.clipBox.slice();
    clone.minMax = this.minMax.slice();
    return clone;
  }
  getPathBoundingBox(pathType = PathType.FILL, transform = null) {
    const box = this.minMax.slice();
    if (pathType === PathType.STROKE) {
      if (!transform) {
        unreachable("Stroke bounding box must include transform.");
      }
      Util.singularValueDecompose2dScale(transform, XY);
      const xStrokePad = XY[0] * this.lineWidth / 2;
      const yStrokePad = XY[1] * this.lineWidth / 2;
      box[0] -= xStrokePad;
      box[1] -= yStrokePad;
      box[2] += xStrokePad;
      box[3] += yStrokePad;
    }
    return box;
  }
  updateClipFromPath() {
    const intersect = Util.intersect(this.clipBox, this.getPathBoundingBox());
    this.startNewPathAndClipBox(intersect || [0, 0, 0, 0]);
  }
  isEmptyClip() {
    return this.minMax[0] === Infinity;
  }
  startNewPathAndClipBox(box) {
    this.clipBox.set(box, 0);
    this.minMax.set(MIN_MAX_INIT, 0);
  }
  getClippedPathBoundingBox(pathType = PathType.FILL, transform = null) {
    return Util.intersect(this.clipBox, this.getPathBoundingBox(pathType, transform));
  }
};
function putBinaryImageData(ctx, imgData) {
  if (imgData instanceof ImageData) {
    ctx.putImageData(imgData, 0, 0);
    return;
  }
  const height = imgData.height, width = imgData.width;
  const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  let srcPos = 0, destPos;
  const src = imgData.data;
  const dest = chunkImgData.data;
  let i7, j3, thisChunkHeight, elemsInThisChunk;
  if (imgData.kind === util_ImageKind.GRAYSCALE_1BPP) {
    const srcLength = src.byteLength;
    const dest32 = new Uint32Array(dest.buffer, 0, dest.byteLength >> 2);
    const dest32DataLength = dest32.length;
    const fullSrcDiff = width + 7 >> 3;
    const white = 4294967295;
    const black = util_FeatureTest.isLittleEndian ? 4278190080 : 255;
    for (i7 = 0; i7 < totalChunks; i7++) {
      thisChunkHeight = i7 < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
      destPos = 0;
      for (j3 = 0; j3 < thisChunkHeight; j3++) {
        const srcDiff = srcLength - srcPos;
        let k2 = 0;
        const kEnd = srcDiff > fullSrcDiff ? width : srcDiff * 8 - 7;
        const kEndUnrolled = kEnd & ~7;
        let mask = 0;
        let srcByte = 0;
        for (; k2 < kEndUnrolled; k2 += 8) {
          srcByte = src[srcPos++];
          dest32[destPos++] = srcByte & 128 ? white : black;
          dest32[destPos++] = srcByte & 64 ? white : black;
          dest32[destPos++] = srcByte & 32 ? white : black;
          dest32[destPos++] = srcByte & 16 ? white : black;
          dest32[destPos++] = srcByte & 8 ? white : black;
          dest32[destPos++] = srcByte & 4 ? white : black;
          dest32[destPos++] = srcByte & 2 ? white : black;
          dest32[destPos++] = srcByte & 1 ? white : black;
        }
        for (; k2 < kEnd; k2++) {
          if (mask === 0) {
            srcByte = src[srcPos++];
            mask = 128;
          }
          dest32[destPos++] = srcByte & mask ? white : black;
          mask >>= 1;
        }
      }
      while (destPos < dest32DataLength) {
        dest32[destPos++] = 0;
      }
      ctx.putImageData(chunkImgData, 0, i7 * FULL_CHUNK_HEIGHT);
    }
  } else if (imgData.kind === util_ImageKind.RGBA_32BPP) {
    j3 = 0;
    elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
    for (i7 = 0; i7 < fullChunks; i7++) {
      dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
      srcPos += elemsInThisChunk;
      ctx.putImageData(chunkImgData, 0, j3);
      j3 += FULL_CHUNK_HEIGHT;
    }
    if (i7 < totalChunks) {
      elemsInThisChunk = width * partialChunkHeight * 4;
      dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
      ctx.putImageData(chunkImgData, 0, j3);
    }
  } else if (imgData.kind === util_ImageKind.RGB_24BPP) {
    thisChunkHeight = FULL_CHUNK_HEIGHT;
    elemsInThisChunk = width * thisChunkHeight;
    for (i7 = 0; i7 < totalChunks; i7++) {
      if (i7 >= fullChunks) {
        thisChunkHeight = partialChunkHeight;
        elemsInThisChunk = width * thisChunkHeight;
      }
      destPos = 0;
      for (j3 = elemsInThisChunk; j3--; ) {
        dest[destPos++] = src[srcPos++];
        dest[destPos++] = src[srcPos++];
        dest[destPos++] = src[srcPos++];
        dest[destPos++] = 255;
      }
      ctx.putImageData(chunkImgData, 0, i7 * FULL_CHUNK_HEIGHT);
    }
  } else {
    throw new Error(`bad image kind: ${imgData.kind}`);
  }
}
function putBinaryImageMask(ctx, imgData) {
  if (imgData.bitmap) {
    ctx.drawImage(imgData.bitmap, 0, 0);
    return;
  }
  const height = imgData.height, width = imgData.width;
  const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  let srcPos = 0;
  const src = imgData.data;
  const dest = chunkImgData.data;
  for (let i7 = 0; i7 < totalChunks; i7++) {
    const thisChunkHeight = i7 < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
    ({
      srcPos
    } = convertBlackAndWhiteToRGBA({
      src,
      srcPos,
      dest,
      width,
      height: thisChunkHeight,
      nonBlackColor: 0
    }));
    ctx.putImageData(chunkImgData, 0, i7 * FULL_CHUNK_HEIGHT);
  }
}
function copyCtxState(sourceCtx, destCtx) {
  const properties = ["strokeStyle", "fillStyle", "fillRule", "globalAlpha", "lineWidth", "lineCap", "lineJoin", "miterLimit", "globalCompositeOperation", "font", "filter"];
  for (const property of properties) {
    if (sourceCtx[property] !== void 0) {
      destCtx[property] = sourceCtx[property];
    }
  }
  if (sourceCtx.setLineDash !== void 0) {
    destCtx.setLineDash(sourceCtx.getLineDash());
    destCtx.lineDashOffset = sourceCtx.lineDashOffset;
  }
}
function resetCtxToDefault(ctx) {
  ctx.strokeStyle = ctx.fillStyle = "#000000";
  ctx.fillRule = "nonzero";
  ctx.globalAlpha = 1;
  ctx.lineWidth = 1;
  ctx.lineCap = "butt";
  ctx.lineJoin = "miter";
  ctx.miterLimit = 10;
  ctx.globalCompositeOperation = "source-over";
  ctx.font = "10px sans-serif";
  if (ctx.setLineDash !== void 0) {
    ctx.setLineDash([]);
    ctx.lineDashOffset = 0;
  }
  const {
    filter: filter2
  } = ctx;
  if (filter2 !== "none" && filter2 !== "") {
    ctx.filter = "none";
  }
}
function getImageSmoothingEnabled(transform, interpolate) {
  if (interpolate) {
    return true;
  }
  Util.singularValueDecompose2dScale(transform, XY);
  const actualScale = Math.fround(OutputScale.pixelRatio * PixelsPerInch.PDF_TO_CSS_UNITS);
  return XY[0] <= actualScale && XY[1] <= actualScale;
}
var LINE_CAP_STYLES = ["butt", "round", "square"];
var LINE_JOIN_STYLES = ["miter", "round", "bevel"];
var NORMAL_CLIP = {};
var EO_CLIP = {};
var CanvasGraphics = class _CanvasGraphics {
  constructor(canvasCtx, commonObjs, objs, canvasFactory, filterFactory, {
    optionalContentConfig,
    markedContentStack = null
  }, annotationCanvasMap, pageColors, dependencyTracker) {
    this.ctx = canvasCtx;
    this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height);
    this.stateStack = [];
    this.pendingClip = null;
    this.pendingEOFill = false;
    this.res = null;
    this.xobjs = null;
    this.commonObjs = commonObjs;
    this.objs = objs;
    this.canvasFactory = canvasFactory;
    this.filterFactory = filterFactory;
    this.groupStack = [];
    this.baseTransform = null;
    this.baseTransformStack = [];
    this.groupLevel = 0;
    this.smaskStack = [];
    this.smaskCounter = 0;
    this.tempSMask = null;
    this.suspendedCtx = null;
    this.contentVisible = true;
    this.markedContentStack = markedContentStack || [];
    this.optionalContentConfig = optionalContentConfig;
    this.cachedCanvases = new CachedCanvases(this.canvasFactory);
    this.cachedPatterns = /* @__PURE__ */ new Map();
    this.annotationCanvasMap = annotationCanvasMap;
    this.viewportScale = 1;
    this.outputScaleX = 1;
    this.outputScaleY = 1;
    this.pageColors = pageColors;
    this._cachedScaleForStroking = [-1, 0];
    this._cachedGetSinglePixelWidth = null;
    this._cachedBitmapsMap = /* @__PURE__ */ new Map();
    this.dependencyTracker = dependencyTracker ?? null;
  }
  getObject(opIdx, data, fallback = null) {
    if (typeof data === "string") {
      this.dependencyTracker?.recordNamedDependency(opIdx, data);
      return data.startsWith("g_") ? this.commonObjs.get(data) : this.objs.get(data);
    }
    return fallback;
  }
  beginDrawing({
    transform,
    viewport,
    transparency = false,
    background = null
  }) {
    const width = this.ctx.canvas.width;
    const height = this.ctx.canvas.height;
    const savedFillStyle = this.ctx.fillStyle;
    this.ctx.fillStyle = background || "#ffffff";
    this.ctx.fillRect(0, 0, width, height);
    this.ctx.fillStyle = savedFillStyle;
    if (transparency) {
      const transparentCanvas = this.cachedCanvases.getCanvas("transparent", width, height);
      this.compositeCtx = this.ctx;
      this.transparentCanvas = transparentCanvas.canvas;
      this.ctx = transparentCanvas.context;
      this.ctx.save();
      this.ctx.transform(...getCurrentTransform(this.compositeCtx));
    }
    this.ctx.save();
    resetCtxToDefault(this.ctx);
    if (transform) {
      this.ctx.transform(...transform);
      this.outputScaleX = transform[0];
      this.outputScaleY = transform[0];
    }
    this.ctx.transform(...viewport.transform);
    this.viewportScale = viewport.scale;
    this.baseTransform = getCurrentTransform(this.ctx);
  }
  executeOperatorList(operatorList, executionStartIdx, continueCallback, stepper, operationsFilter) {
    const argsArray = operatorList.argsArray;
    const fnArray = operatorList.fnArray;
    let i7 = executionStartIdx || 0;
    const argsArrayLen = argsArray.length;
    if (argsArrayLen === i7) {
      return i7;
    }
    const chunkOperations = argsArrayLen - i7 > EXECUTION_STEPS && typeof continueCallback === "function";
    const endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
    let steps = 0;
    const commonObjs = this.commonObjs;
    const objs = this.objs;
    let fnId, fnArgs;
    while (true) {
      if (stepper !== void 0 && i7 === stepper.nextBreakPoint) {
        stepper.breakIt(i7, continueCallback);
        return i7;
      }
      if (!operationsFilter || operationsFilter(i7)) {
        fnId = fnArray[i7];
        fnArgs = argsArray[i7] ?? null;
        if (fnId !== OPS.dependency) {
          if (fnArgs === null) {
            this[fnId](i7);
          } else {
            this[fnId](i7, ...fnArgs);
          }
        } else {
          for (const depObjId of fnArgs) {
            this.dependencyTracker?.recordNamedData(depObjId, i7);
            const objsPool = depObjId.startsWith("g_") ? commonObjs : objs;
            if (!objsPool.has(depObjId)) {
              objsPool.get(depObjId, continueCallback);
              return i7;
            }
          }
        }
      }
      i7++;
      if (i7 === argsArrayLen) {
        return i7;
      }
      if (chunkOperations && ++steps > EXECUTION_STEPS) {
        if (Date.now() > endTime) {
          continueCallback();
          return i7;
        }
        steps = 0;
      }
    }
  }
  #restoreInitialState() {
    while (this.stateStack.length || this.inSMaskMode) {
      this.restore();
    }
    this.current.activeSMask = null;
    this.ctx.restore();
    if (this.transparentCanvas) {
      this.ctx = this.compositeCtx;
      this.ctx.save();
      this.ctx.setTransform(1, 0, 0, 1, 0, 0);
      this.ctx.drawImage(this.transparentCanvas, 0, 0);
      this.ctx.restore();
      this.transparentCanvas = null;
    }
  }
  endDrawing() {
    this.#restoreInitialState();
    this.cachedCanvases.clear();
    this.cachedPatterns.clear();
    for (const cache of this._cachedBitmapsMap.values()) {
      for (const canvas of cache.values()) {
        if (typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement) {
          canvas.width = canvas.height = 0;
        }
      }
      cache.clear();
    }
    this._cachedBitmapsMap.clear();
    this.#drawFilter();
  }
  #drawFilter() {
    if (this.pageColors) {
      const hcmFilterId = this.filterFactory.addHCMFilter(this.pageColors.foreground, this.pageColors.background);
      if (hcmFilterId !== "none") {
        const savedFilter = this.ctx.filter;
        this.ctx.filter = hcmFilterId;
        this.ctx.drawImage(this.ctx.canvas, 0, 0);
        this.ctx.filter = savedFilter;
      }
    }
  }
  _scaleImage(img, inverseTransform) {
    const width = img.width ?? img.displayWidth;
    const height = img.height ?? img.displayHeight;
    let widthScale = Math.max(Math.hypot(inverseTransform[0], inverseTransform[1]), 1);
    let heightScale = Math.max(Math.hypot(inverseTransform[2], inverseTransform[3]), 1);
    let paintWidth = width, paintHeight = height;
    let tmpCanvasId = "prescale1";
    let tmpCanvas, tmpCtx;
    while (widthScale > 2 && paintWidth > 1 || heightScale > 2 && paintHeight > 1) {
      let newWidth = paintWidth, newHeight = paintHeight;
      if (widthScale > 2 && paintWidth > 1) {
        newWidth = paintWidth >= 16384 ? Math.floor(paintWidth / 2) - 1 || 1 : Math.ceil(paintWidth / 2);
        widthScale /= paintWidth / newWidth;
      }
      if (heightScale > 2 && paintHeight > 1) {
        newHeight = paintHeight >= 16384 ? Math.floor(paintHeight / 2) - 1 || 1 : Math.ceil(paintHeight) / 2;
        heightScale /= paintHeight / newHeight;
      }
      tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);
      tmpCtx = tmpCanvas.context;
      tmpCtx.clearRect(0, 0, newWidth, newHeight);
      tmpCtx.drawImage(img, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight);
      img = tmpCanvas.canvas;
      paintWidth = newWidth;
      paintHeight = newHeight;
      tmpCanvasId = tmpCanvasId === "prescale1" ? "prescale2" : "prescale1";
    }
    return {
      img,
      paintWidth,
      paintHeight
    };
  }
  _createMaskCanvas(opIdx, img) {
    const ctx = this.ctx;
    const {
      width,
      height
    } = img;
    const fillColor = this.current.fillColor;
    const isPatternFill = this.current.patternFill;
    const currentTransform = getCurrentTransform(ctx);
    let cache, cacheKey, scaled, maskCanvas;
    if ((img.bitmap || img.data) && img.count > 1) {
      const mainKey = img.bitmap || img.data.buffer;
      cacheKey = JSON.stringify(isPatternFill ? currentTransform : [currentTransform.slice(0, 4), fillColor]);
      cache = this._cachedBitmapsMap.get(mainKey);
      if (!cache) {
        cache = /* @__PURE__ */ new Map();
        this._cachedBitmapsMap.set(mainKey, cache);
      }
      const cachedImage = cache.get(cacheKey);
      if (cachedImage && !isPatternFill) {
        const offsetX2 = Math.round(Math.min(currentTransform[0], currentTransform[2]) + currentTransform[4]);
        const offsetY2 = Math.round(Math.min(currentTransform[1], currentTransform[3]) + currentTransform[5]);
        this.dependencyTracker?.recordDependencies(opIdx, Dependencies.transformAndFill);
        return {
          canvas: cachedImage,
          offsetX: offsetX2,
          offsetY: offsetY2
        };
      }
      scaled = cachedImage;
    }
    if (!scaled) {
      maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
      putBinaryImageMask(maskCanvas.context, img);
    }
    let maskToCanvas = Util.transform(currentTransform, [1 / width, 0, 0, -1 / height, 0, 0]);
    maskToCanvas = Util.transform(maskToCanvas, [1, 0, 0, 1, 0, -height]);
    const minMax = MIN_MAX_INIT.slice();
    Util.axialAlignedBoundingBox([0, 0, width, height], maskToCanvas, minMax);
    const [minX, minY, maxX, maxY] = minMax;
    const drawnWidth = Math.round(maxX - minX) || 1;
    const drawnHeight = Math.round(maxY - minY) || 1;
    const fillCanvas = this.cachedCanvases.getCanvas("fillCanvas", drawnWidth, drawnHeight);
    const fillCtx = fillCanvas.context;
    const offsetX = minX;
    const offsetY = minY;
    fillCtx.translate(-offsetX, -offsetY);
    fillCtx.transform(...maskToCanvas);
    if (!scaled) {
      scaled = this._scaleImage(maskCanvas.canvas, getCurrentTransformInverse(fillCtx));
      scaled = scaled.img;
      if (cache && isPatternFill) {
        cache.set(cacheKey, scaled);
      }
    }
    fillCtx.imageSmoothingEnabled = getImageSmoothingEnabled(getCurrentTransform(fillCtx), img.interpolate);
    drawImageAtIntegerCoords(fillCtx, scaled, 0, 0, scaled.width, scaled.height, 0, 0, width, height);
    fillCtx.globalCompositeOperation = "source-in";
    const inverse = Util.transform(getCurrentTransformInverse(fillCtx), [1, 0, 0, 1, -offsetX, -offsetY]);
    fillCtx.fillStyle = isPatternFill ? fillColor.getPattern(ctx, this, inverse, PathType.FILL, opIdx) : fillColor;
    fillCtx.fillRect(0, 0, width, height);
    if (cache && !isPatternFill) {
      this.cachedCanvases.delete("fillCanvas");
      cache.set(cacheKey, fillCanvas.canvas);
    }
    this.dependencyTracker?.recordDependencies(opIdx, Dependencies.transformAndFill);
    return {
      canvas: fillCanvas.canvas,
      offsetX: Math.round(offsetX),
      offsetY: Math.round(offsetY)
    };
  }
  setLineWidth(opIdx, width) {
    this.dependencyTracker?.recordSimpleData("lineWidth", opIdx);
    if (width !== this.current.lineWidth) {
      this._cachedScaleForStroking[0] = -1;
    }
    this.current.lineWidth = width;
    this.ctx.lineWidth = width;
  }
  setLineCap(opIdx, style) {
    this.dependencyTracker?.recordSimpleData("lineCap", opIdx);
    this.ctx.lineCap = LINE_CAP_STYLES[style];
  }
  setLineJoin(opIdx, style) {
    this.dependencyTracker?.recordSimpleData("lineJoin", opIdx);
    this.ctx.lineJoin = LINE_JOIN_STYLES[style];
  }
  setMiterLimit(opIdx, limit2) {
    this.dependencyTracker?.recordSimpleData("miterLimit", opIdx);
    this.ctx.miterLimit = limit2;
  }
  setDash(opIdx, dashArray, dashPhase) {
    this.dependencyTracker?.recordSimpleData("dash", opIdx);
    const ctx = this.ctx;
    if (ctx.setLineDash !== void 0) {
      ctx.setLineDash(dashArray);
      ctx.lineDashOffset = dashPhase;
    }
  }
  setRenderingIntent(opIdx, intent) {
  }
  setFlatness(opIdx, flatness) {
  }
  setGState(opIdx, states) {
    for (const [key, value] of states) {
      switch (key) {
        case "LW":
          this.setLineWidth(opIdx, value);
          break;
        case "LC":
          this.setLineCap(opIdx, value);
          break;
        case "LJ":
          this.setLineJoin(opIdx, value);
          break;
        case "ML":
          this.setMiterLimit(opIdx, value);
          break;
        case "D":
          this.setDash(opIdx, value[0], value[1]);
          break;
        case "RI":
          this.setRenderingIntent(opIdx, value);
          break;
        case "FL":
          this.setFlatness(opIdx, value);
          break;
        case "Font":
          this.setFont(opIdx, value[0], value[1]);
          break;
        case "CA":
          this.dependencyTracker?.recordSimpleData("strokeAlpha", opIdx);
          this.current.strokeAlpha = value;
          break;
        case "ca":
          this.dependencyTracker?.recordSimpleData("fillAlpha", opIdx);
          this.ctx.globalAlpha = this.current.fillAlpha = value;
          break;
        case "BM":
          this.dependencyTracker?.recordSimpleData("globalCompositeOperation", opIdx);
          this.ctx.globalCompositeOperation = value;
          break;
        case "SMask":
          this.dependencyTracker?.recordSimpleData("SMask", opIdx);
          this.current.activeSMask = value ? this.tempSMask : null;
          this.tempSMask = null;
          this.checkSMaskState();
          break;
        case "TR":
          this.dependencyTracker?.recordSimpleData("filter", opIdx);
          this.ctx.filter = this.current.transferMaps = this.filterFactory.addFilter(value);
          break;
      }
    }
  }
  get inSMaskMode() {
    return !!this.suspendedCtx;
  }
  checkSMaskState() {
    const inSMaskMode = this.inSMaskMode;
    if (this.current.activeSMask && !inSMaskMode) {
      this.beginSMaskMode();
    } else if (!this.current.activeSMask && inSMaskMode) {
      this.endSMaskMode();
    }
  }
  beginSMaskMode(opIdx) {
    if (this.inSMaskMode) {
      throw new Error("beginSMaskMode called while already in smask mode");
    }
    const drawnWidth = this.ctx.canvas.width;
    const drawnHeight = this.ctx.canvas.height;
    const cacheId = "smaskGroupAt" + this.groupLevel;
    const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight);
    this.suspendedCtx = this.ctx;
    const ctx = this.ctx = scratchCanvas.context;
    ctx.setTransform(this.suspendedCtx.getTransform());
    copyCtxState(this.suspendedCtx, ctx);
    mirrorContextOperations(ctx, this.suspendedCtx);
    this.setGState(opIdx, [["BM", "source-over"]]);
  }
  endSMaskMode() {
    if (!this.inSMaskMode) {
      throw new Error("endSMaskMode called while not in smask mode");
    }
    this.ctx._removeMirroring();
    copyCtxState(this.ctx, this.suspendedCtx);
    this.ctx = this.suspendedCtx;
    this.suspendedCtx = null;
  }
  compose(dirtyBox) {
    if (!this.current.activeSMask) {
      return;
    }
    if (!dirtyBox) {
      dirtyBox = [0, 0, this.ctx.canvas.width, this.ctx.canvas.height];
    } else {
      dirtyBox[0] = Math.floor(dirtyBox[0]);
      dirtyBox[1] = Math.floor(dirtyBox[1]);
      dirtyBox[2] = Math.ceil(dirtyBox[2]);
      dirtyBox[3] = Math.ceil(dirtyBox[3]);
    }
    const smask = this.current.activeSMask;
    const suspendedCtx = this.suspendedCtx;
    this.composeSMask(suspendedCtx, smask, this.ctx, dirtyBox);
    this.ctx.save();
    this.ctx.setTransform(1, 0, 0, 1, 0, 0);
    this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);
    this.ctx.restore();
  }
  composeSMask(ctx, smask, layerCtx, layerBox) {
    const layerOffsetX = layerBox[0];
    const layerOffsetY = layerBox[1];
    const layerWidth = layerBox[2] - layerOffsetX;
    const layerHeight = layerBox[3] - layerOffsetY;
    if (layerWidth === 0 || layerHeight === 0) {
      return;
    }
    this.genericComposeSMask(smask.context, layerCtx, layerWidth, layerHeight, smask.subtype, smask.backdrop, smask.transferMap, layerOffsetX, layerOffsetY, smask.offsetX, smask.offsetY);
    ctx.save();
    ctx.globalAlpha = 1;
    ctx.globalCompositeOperation = "source-over";
    ctx.setTransform(1, 0, 0, 1, 0, 0);
    ctx.drawImage(layerCtx.canvas, 0, 0);
    ctx.restore();
  }
  genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap, layerOffsetX, layerOffsetY, maskOffsetX, maskOffsetY) {
    let maskCanvas = maskCtx.canvas;
    let maskX = layerOffsetX - maskOffsetX;
    let maskY = layerOffsetY - maskOffsetY;
    if (backdrop) {
      if (maskX < 0 || maskY < 0 || maskX + width > maskCanvas.width || maskY + height > maskCanvas.height) {
        const canvas = this.cachedCanvases.getCanvas("maskExtension", width, height);
        const ctx = canvas.context;
        ctx.drawImage(maskCanvas, -maskX, -maskY);
        ctx.globalCompositeOperation = "destination-atop";
        ctx.fillStyle = backdrop;
        ctx.fillRect(0, 0, width, height);
        ctx.globalCompositeOperation = "source-over";
        maskCanvas = canvas.canvas;
        maskX = maskY = 0;
      } else {
        maskCtx.save();
        maskCtx.globalAlpha = 1;
        maskCtx.setTransform(1, 0, 0, 1, 0, 0);
        const clip2 = new Path2D();
        clip2.rect(maskX, maskY, width, height);
        maskCtx.clip(clip2);
        maskCtx.globalCompositeOperation = "destination-atop";
        maskCtx.fillStyle = backdrop;
        maskCtx.fillRect(maskX, maskY, width, height);
        maskCtx.restore();
      }
    }
    layerCtx.save();
    layerCtx.globalAlpha = 1;
    layerCtx.setTransform(1, 0, 0, 1, 0, 0);
    if (subtype === "Alpha" && transferMap) {
      layerCtx.filter = this.filterFactory.addAlphaFilter(transferMap);
    } else if (subtype === "Luminosity") {
      layerCtx.filter = this.filterFactory.addLuminosityFilter(transferMap);
    }
    const clip = new Path2D();
    clip.rect(layerOffsetX, layerOffsetY, width, height);
    layerCtx.clip(clip);
    layerCtx.globalCompositeOperation = "destination-in";
    layerCtx.drawImage(maskCanvas, maskX, maskY, width, height, layerOffsetX, layerOffsetY, width, height);
    layerCtx.restore();
  }
  save(opIdx) {
    if (this.inSMaskMode) {
      copyCtxState(this.ctx, this.suspendedCtx);
    }
    this.ctx.save();
    const old = this.current;
    this.stateStack.push(old);
    this.current = old.clone();
    this.dependencyTracker?.save(opIdx);
  }
  restore(opIdx) {
    this.dependencyTracker?.restore(opIdx);
    if (this.stateStack.length === 0) {
      if (this.inSMaskMode) {
        this.endSMaskMode();
      }
      return;
    }
    this.current = this.stateStack.pop();
    this.ctx.restore();
    if (this.inSMaskMode) {
      copyCtxState(this.suspendedCtx, this.ctx);
    }
    this.checkSMaskState();
    this.pendingClip = null;
    this._cachedScaleForStroking[0] = -1;
    this._cachedGetSinglePixelWidth = null;
  }
  transform(opIdx, a3, b4, c6, d4, e9, f4) {
    this.dependencyTracker?.recordIncrementalData("transform", opIdx);
    this.ctx.transform(a3, b4, c6, d4, e9, f4);
    this._cachedScaleForStroking[0] = -1;
    this._cachedGetSinglePixelWidth = null;
  }
  constructPath(opIdx, op2, data, minMax) {
    let [path6] = data;
    if (!minMax) {
      path6 ||= data[0] = new Path2D();
      this[op2](opIdx, path6);
      return;
    }
    if (this.dependencyTracker !== null) {
      const outerExtraSize = op2 === OPS.stroke ? this.current.lineWidth / 2 : 0;
      this.dependencyTracker.resetBBox(opIdx).recordBBox(opIdx, this.ctx, minMax[0] - outerExtraSize, minMax[2] + outerExtraSize, minMax[1] - outerExtraSize, minMax[3] + outerExtraSize).recordDependencies(opIdx, ["transform"]);
    }
    if (!(path6 instanceof Path2D)) {
      path6 = data[0] = makePathFromDrawOPS(path6);
    }
    Util.axialAlignedBoundingBox(minMax, getCurrentTransform(this.ctx), this.current.minMax);
    this[op2](opIdx, path6);
    this._pathStartIdx = opIdx;
  }
  closePath(opIdx) {
    this.ctx.closePath();
  }
  stroke(opIdx, path6, consumePath = true) {
    const ctx = this.ctx;
    const strokeColor = this.current.strokeColor;
    ctx.globalAlpha = this.current.strokeAlpha;
    if (this.contentVisible) {
      if (typeof strokeColor === "object" && strokeColor?.getPattern) {
        const baseTransform = strokeColor.isModifyingCurrentTransform() ? ctx.getTransform() : null;
        ctx.save();
        ctx.strokeStyle = strokeColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.STROKE, opIdx);
        if (baseTransform) {
          const newPath = new Path2D();
          newPath.addPath(path6, ctx.getTransform().invertSelf().multiplySelf(baseTransform));
          path6 = newPath;
        }
        this.rescaleAndStroke(path6, false);
        ctx.restore();
      } else {
        this.rescaleAndStroke(path6, true);
      }
    }
    this.dependencyTracker?.recordDependencies(opIdx, Dependencies.stroke);
    if (consumePath) {
      this.consumePath(opIdx, path6, this.current.getClippedPathBoundingBox(PathType.STROKE, getCurrentTransform(this.ctx)));
    }
    ctx.globalAlpha = this.current.fillAlpha;
  }
  closeStroke(opIdx, path6) {
    this.stroke(opIdx, path6);
  }
  fill(opIdx, path6, consumePath = true) {
    const ctx = this.ctx;
    const fillColor = this.current.fillColor;
    const isPatternFill = this.current.patternFill;
    let needRestore = false;
    if (isPatternFill) {
      const baseTransform = fillColor.isModifyingCurrentTransform() ? ctx.getTransform() : null;
      this.dependencyTracker?.save(opIdx);
      ctx.save();
      ctx.fillStyle = fillColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.FILL, opIdx);
      if (baseTransform) {
        const newPath = new Path2D();
        newPath.addPath(path6, ctx.getTransform().invertSelf().multiplySelf(baseTransform));
        path6 = newPath;
      }
      needRestore = true;
    }
    const intersect = this.current.getClippedPathBoundingBox();
    if (this.contentVisible && intersect !== null) {
      if (this.pendingEOFill) {
        ctx.fill(path6, "evenodd");
        this.pendingEOFill = false;
      } else {
        ctx.fill(path6);
      }
    }
    this.dependencyTracker?.recordDependencies(opIdx, Dependencies.fill);
    if (needRestore) {
      ctx.restore();
      this.dependencyTracker?.restore(opIdx);
    }
    if (consumePath) {
      this.consumePath(opIdx, path6, intersect);
    }
  }
  eoFill(opIdx, path6) {
    this.pendingEOFill = true;
    this.fill(opIdx, path6);
  }
  fillStroke(opIdx, path6) {
    this.fill(opIdx, path6, false);
    this.stroke(opIdx, path6, false);
    this.consumePath(opIdx, path6);
  }
  eoFillStroke(opIdx, path6) {
    this.pendingEOFill = true;
    this.fillStroke(opIdx, path6);
  }
  closeFillStroke(opIdx, path6) {
    this.fillStroke(opIdx, path6);
  }
  closeEOFillStroke(opIdx, path6) {
    this.pendingEOFill = true;
    this.fillStroke(opIdx, path6);
  }
  endPath(opIdx, path6) {
    this.consumePath(opIdx, path6);
  }
  rawFillPath(opIdx, path6) {
    this.ctx.fill(path6);
    this.dependencyTracker?.recordDependencies(opIdx, Dependencies.rawFillPath).recordOperation(opIdx);
  }
  clip(opIdx) {
    this.dependencyTracker?.recordFutureForcedDependency("clipMode", opIdx);
    this.pendingClip = NORMAL_CLIP;
  }
  eoClip(opIdx) {
    this.dependencyTracker?.recordFutureForcedDependency("clipMode", opIdx);
    this.pendingClip = EO_CLIP;
  }
  beginText(opIdx) {
    this.current.textMatrix = null;
    this.current.textMatrixScale = 1;
    this.current.x = this.current.lineX = 0;
    this.current.y = this.current.lineY = 0;
    this.dependencyTracker?.recordOpenMarker(opIdx).resetIncrementalData("sameLineText").resetIncrementalData("moveText", opIdx);
  }
  endText(opIdx) {
    const paths = this.pendingTextPaths;
    const ctx = this.ctx;
    if (this.dependencyTracker) {
      const {
        dependencyTracker
      } = this;
      if (paths !== void 0) {
        dependencyTracker.recordFutureForcedDependency("textClip", dependencyTracker.getOpenMarker()).recordFutureForcedDependency("textClip", opIdx);
      }
      dependencyTracker.recordCloseMarker(opIdx);
    }
    if (paths !== void 0) {
      const newPath = new Path2D();
      const invTransf = ctx.getTransform().invertSelf();
      for (const {
        transform,
        x: x2,
        y: y4,
        fontSize,
        path: path6
      } of paths) {
        if (!path6) {
          continue;
        }
        newPath.addPath(path6, new DOMMatrix(transform).preMultiplySelf(invTransf).translate(x2, y4).scale(fontSize, -fontSize));
      }
      ctx.clip(newPath);
    }
    delete this.pendingTextPaths;
  }
  setCharSpacing(opIdx, spacing2) {
    this.dependencyTracker?.recordSimpleData("charSpacing", opIdx);
    this.current.charSpacing = spacing2;
  }
  setWordSpacing(opIdx, spacing2) {
    this.dependencyTracker?.recordSimpleData("wordSpacing", opIdx);
    this.current.wordSpacing = spacing2;
  }
  setHScale(opIdx, scale) {
    this.dependencyTracker?.recordSimpleData("hScale", opIdx);
    this.current.textHScale = scale / 100;
  }
  setLeading(opIdx, leading) {
    this.dependencyTracker?.recordSimpleData("leading", opIdx);
    this.current.leading = -leading;
  }
  setFont(opIdx, fontRefName, size) {
    this.dependencyTracker?.recordSimpleData("font", opIdx).recordSimpleDataFromNamed("fontObj", fontRefName, opIdx);
    const fontObj = this.commonObjs.get(fontRefName);
    const current2 = this.current;
    if (!fontObj) {
      throw new Error(`Can't find font for ${fontRefName}`);
    }
    current2.fontMatrix = fontObj.fontMatrix || FONT_IDENTITY_MATRIX;
    if (current2.fontMatrix[0] === 0 || current2.fontMatrix[3] === 0) {
      warn("Invalid font matrix for font " + fontRefName);
    }
    if (size < 0) {
      size = -size;
      current2.fontDirection = -1;
    } else {
      current2.fontDirection = 1;
    }
    this.current.font = fontObj;
    this.current.fontSize = size;
    if (fontObj.isType3Font) {
      return;
    }
    const name = fontObj.loadedName || "sans-serif";
    const typeface = fontObj.systemFontInfo?.css || `"${name}", ${fontObj.fallbackName}`;
    let bold2 = "normal";
    if (fontObj.black) {
      bold2 = "900";
    } else if (fontObj.bold) {
      bold2 = "bold";
    }
    const italic = fontObj.italic ? "italic" : "normal";
    let browserFontSize = size;
    if (size < MIN_FONT_SIZE) {
      browserFontSize = MIN_FONT_SIZE;
    } else if (size > MAX_FONT_SIZE) {
      browserFontSize = MAX_FONT_SIZE;
    }
    this.current.fontSizeScale = size / browserFontSize;
    this.ctx.font = `${italic} ${bold2} ${browserFontSize}px ${typeface}`;
  }
  setTextRenderingMode(opIdx, mode) {
    this.dependencyTracker?.recordSimpleData("textRenderingMode", opIdx);
    this.current.textRenderingMode = mode;
  }
  setTextRise(opIdx, rise) {
    this.dependencyTracker?.recordSimpleData("textRise", opIdx);
    this.current.textRise = rise;
  }
  moveText(opIdx, x2, y4) {
    this.dependencyTracker?.resetIncrementalData("sameLineText").recordIncrementalData("moveText", opIdx);
    this.current.x = this.current.lineX += x2;
    this.current.y = this.current.lineY += y4;
  }
  setLeadingMoveText(opIdx, x2, y4) {
    this.setLeading(opIdx, -y4);
    this.moveText(opIdx, x2, y4);
  }
  setTextMatrix(opIdx, matrix) {
    this.dependencyTracker?.resetIncrementalData("sameLineText").recordSimpleData("textMatrix", opIdx);
    const {
      current: current2
    } = this;
    current2.textMatrix = matrix;
    current2.textMatrixScale = Math.hypot(matrix[0], matrix[1]);
    current2.x = current2.lineX = 0;
    current2.y = current2.lineY = 0;
  }
  nextLine(opIdx) {
    this.moveText(opIdx, 0, this.current.leading);
    this.dependencyTracker?.recordIncrementalData("moveText", this.dependencyTracker.getSimpleIndex("leading") ?? opIdx);
  }
  #getScaledPath(path6, currentTransform, transform) {
    const newPath = new Path2D();
    newPath.addPath(path6, new DOMMatrix(transform).invertSelf().multiplySelf(currentTransform));
    return newPath;
  }
  paintChar(opIdx, character, x2, y4, patternFillTransform, patternStrokeTransform) {
    const ctx = this.ctx;
    const current2 = this.current;
    const font = current2.font;
    const textRenderingMode = current2.textRenderingMode;
    const fontSize = current2.fontSize / current2.fontSizeScale;
    const fillStrokeMode = textRenderingMode & TextRenderingMode.FILL_STROKE_MASK;
    const isAddToPathSet = !!(textRenderingMode & TextRenderingMode.ADD_TO_PATH_FLAG);
    const patternFill = current2.patternFill && !font.missingFile;
    const patternStroke = current2.patternStroke && !font.missingFile;
    let path6;
    if ((font.disableFontFace || isAddToPathSet || patternFill || patternStroke) && !font.missingFile) {
      path6 = font.getPathGenerator(this.commonObjs, character);
    }
    if (path6 && (font.disableFontFace || patternFill || patternStroke)) {
      ctx.save();
      ctx.translate(x2, y4);
      ctx.scale(fontSize, -fontSize);
      this.dependencyTracker?.recordCharacterBBox(opIdx, ctx, font);
      let currentTransform;
      if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
        if (patternFillTransform) {
          currentTransform = ctx.getTransform();
          ctx.setTransform(...patternFillTransform);
          const scaledPath = this.#getScaledPath(path6, currentTransform, patternFillTransform);
          ctx.fill(scaledPath);
        } else {
          ctx.fill(path6);
        }
      }
      if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
        if (patternStrokeTransform) {
          currentTransform ||= ctx.getTransform();
          ctx.setTransform(...patternStrokeTransform);
          const {
            a: a3,
            b: b4,
            c: c6,
            d: d4
          } = currentTransform;
          const invPatternTransform = Util.inverseTransform(patternStrokeTransform);
          const transf = Util.transform([a3, b4, c6, d4, 0, 0], invPatternTransform);
          Util.singularValueDecompose2dScale(transf, XY);
          ctx.lineWidth *= Math.max(XY[0], XY[1]) / fontSize;
          ctx.stroke(this.#getScaledPath(path6, currentTransform, patternStrokeTransform));
        } else {
          ctx.lineWidth /= fontSize;
          ctx.stroke(path6);
        }
      }
      ctx.restore();
    } else {
      if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
        ctx.fillText(character, x2, y4);
        this.dependencyTracker?.recordCharacterBBox(opIdx, ctx, font, fontSize, x2, y4, () => ctx.measureText(character));
      }
      if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
        if (this.dependencyTracker) {
          this.dependencyTracker?.recordCharacterBBox(opIdx, ctx, font, fontSize, x2, y4, () => ctx.measureText(character)).recordDependencies(opIdx, Dependencies.stroke);
        }
        ctx.strokeText(character, x2, y4);
      }
    }
    if (isAddToPathSet) {
      const paths = this.pendingTextPaths ||= [];
      paths.push({
        transform: getCurrentTransform(ctx),
        x: x2,
        y: y4,
        fontSize,
        path: path6
      });
      this.dependencyTracker?.recordCharacterBBox(opIdx, ctx, font, fontSize, x2, y4);
    }
  }
  get isFontSubpixelAAEnabled() {
    const {
      context: ctx
    } = this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled", 10, 10);
    ctx.scale(1.5, 1);
    ctx.fillText("I", 0, 10);
    const data = ctx.getImageData(0, 0, 10, 10).data;
    let enabled = false;
    for (let i7 = 3; i7 < data.length; i7 += 4) {
      if (data[i7] > 0 && data[i7] < 255) {
        enabled = true;
        break;
      }
    }
    return shadow(this, "isFontSubpixelAAEnabled", enabled);
  }
  showText(opIdx, glyphs) {
    if (this.dependencyTracker) {
      this.dependencyTracker.recordDependencies(opIdx, Dependencies.showText).resetBBox(opIdx);
      if (this.current.textRenderingMode & TextRenderingMode.ADD_TO_PATH_FLAG) {
        this.dependencyTracker.recordFutureForcedDependency("textClip", opIdx).inheritPendingDependenciesAsFutureForcedDependencies();
      }
    }
    const current2 = this.current;
    const font = current2.font;
    if (font.isType3Font) {
      this.showType3Text(opIdx, glyphs);
      this.dependencyTracker?.recordShowTextOperation(opIdx);
      return void 0;
    }
    const fontSize = current2.fontSize;
    if (fontSize === 0) {
      this.dependencyTracker?.recordOperation(opIdx);
      return void 0;
    }
    const ctx = this.ctx;
    const fontSizeScale = current2.fontSizeScale;
    const charSpacing = current2.charSpacing;
    const wordSpacing = current2.wordSpacing;
    const fontDirection = current2.fontDirection;
    const textHScale = current2.textHScale * fontDirection;
    const glyphsLength = glyphs.length;
    const vertical = font.vertical;
    const spacingDir = vertical ? 1 : -1;
    const defaultVMetrics = font.defaultVMetrics;
    const widthAdvanceScale = fontSize * current2.fontMatrix[0];
    const simpleFillText = current2.textRenderingMode === TextRenderingMode.FILL && !font.disableFontFace && !current2.patternFill;
    ctx.save();
    if (current2.textMatrix) {
      ctx.transform(...current2.textMatrix);
    }
    ctx.translate(current2.x, current2.y + current2.textRise);
    if (fontDirection > 0) {
      ctx.scale(textHScale, -1);
    } else {
      ctx.scale(textHScale, 1);
    }
    let patternFillTransform, patternStrokeTransform;
    if (current2.patternFill) {
      ctx.save();
      const pattern = current2.fillColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.FILL, opIdx);
      patternFillTransform = getCurrentTransform(ctx);
      ctx.restore();
      ctx.fillStyle = pattern;
    }
    if (current2.patternStroke) {
      ctx.save();
      const pattern = current2.strokeColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.STROKE, opIdx);
      patternStrokeTransform = getCurrentTransform(ctx);
      ctx.restore();
      ctx.strokeStyle = pattern;
    }
    let lineWidth = current2.lineWidth;
    const scale = current2.textMatrixScale;
    if (scale === 0 || lineWidth === 0) {
      const fillStrokeMode = current2.textRenderingMode & TextRenderingMode.FILL_STROKE_MASK;
      if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
        lineWidth = this.getSinglePixelWidth();
      }
    } else {
      lineWidth /= scale;
    }
    if (fontSizeScale !== 1) {
      ctx.scale(fontSizeScale, fontSizeScale);
      lineWidth /= fontSizeScale;
    }
    ctx.lineWidth = lineWidth;
    if (font.isInvalidPDFjsFont) {
      const chars = [];
      let width = 0;
      for (const glyph of glyphs) {
        chars.push(glyph.unicode);
        width += glyph.width;
      }
      const joinedChars = chars.join("");
      ctx.fillText(joinedChars, 0, 0);
      if (this.dependencyTracker !== null) {
        const measure = ctx.measureText(joinedChars);
        this.dependencyTracker.recordBBox(opIdx, this.ctx, -measure.actualBoundingBoxLeft, measure.actualBoundingBoxRight, -measure.actualBoundingBoxAscent, measure.actualBoundingBoxDescent).recordShowTextOperation(opIdx);
      }
      current2.x += width * widthAdvanceScale * textHScale;
      ctx.restore();
      this.compose();
      return void 0;
    }
    let x2 = 0, i7;
    for (i7 = 0; i7 < glyphsLength; ++i7) {
      const glyph = glyphs[i7];
      if (typeof glyph === "number") {
        x2 += spacingDir * glyph * fontSize / 1e3;
        continue;
      }
      let restoreNeeded = false;
      const spacing2 = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
      const character = glyph.fontChar;
      const accent2 = glyph.accent;
      let scaledX, scaledY;
      let width = glyph.width;
      if (vertical) {
        const vmetric = glyph.vmetric || defaultVMetrics;
        const vx = -(glyph.vmetric ? vmetric[1] : width * 0.5) * widthAdvanceScale;
        const vy = vmetric[2] * widthAdvanceScale;
        width = vmetric ? -vmetric[0] : width;
        scaledX = vx / fontSizeScale;
        scaledY = (x2 + vy) / fontSizeScale;
      } else {
        scaledX = x2 / fontSizeScale;
        scaledY = 0;
      }
      let measure;
      if (font.remeasure && width > 0) {
        measure = ctx.measureText(character);
        const measuredWidth = measure.width * 1e3 / fontSize * fontSizeScale;
        if (width < measuredWidth && this.isFontSubpixelAAEnabled) {
          const characterScaleX = width / measuredWidth;
          restoreNeeded = true;
          ctx.save();
          ctx.scale(characterScaleX, 1);
          scaledX /= characterScaleX;
        } else if (width !== measuredWidth) {
          scaledX += (width - measuredWidth) / 2e3 * fontSize / fontSizeScale;
        }
      }
      if (this.contentVisible && (glyph.isInFont || font.missingFile)) {
        if (simpleFillText && !accent2) {
          ctx.fillText(character, scaledX, scaledY);
          this.dependencyTracker?.recordCharacterBBox(opIdx, ctx, measure ? {
            bbox: null
          } : font, fontSize / fontSizeScale, scaledX, scaledY, () => measure ?? ctx.measureText(character));
        } else {
          this.paintChar(opIdx, character, scaledX, scaledY, patternFillTransform, patternStrokeTransform);
          if (accent2) {
            const scaledAccentX = scaledX + fontSize * accent2.offset.x / fontSizeScale;
            const scaledAccentY = scaledY - fontSize * accent2.offset.y / fontSizeScale;
            this.paintChar(opIdx, accent2.fontChar, scaledAccentX, scaledAccentY, patternFillTransform, patternStrokeTransform);
          }
        }
      }
      const charWidth = vertical ? width * widthAdvanceScale - spacing2 * fontDirection : width * widthAdvanceScale + spacing2 * fontDirection;
      x2 += charWidth;
      if (restoreNeeded) {
        ctx.restore();
      }
    }
    if (vertical) {
      current2.y -= x2;
    } else {
      current2.x += x2 * textHScale;
    }
    ctx.restore();
    this.compose();
    this.dependencyTracker?.recordShowTextOperation(opIdx);
    return void 0;
  }
  showType3Text(opIdx, glyphs) {
    const ctx = this.ctx;
    const current2 = this.current;
    const font = current2.font;
    const fontSize = current2.fontSize;
    const fontDirection = current2.fontDirection;
    const spacingDir = font.vertical ? 1 : -1;
    const charSpacing = current2.charSpacing;
    const wordSpacing = current2.wordSpacing;
    const textHScale = current2.textHScale * fontDirection;
    const fontMatrix = current2.fontMatrix || FONT_IDENTITY_MATRIX;
    const glyphsLength = glyphs.length;
    const isTextInvisible = current2.textRenderingMode === TextRenderingMode.INVISIBLE;
    let i7, glyph, width, spacingLength;
    if (isTextInvisible || fontSize === 0) {
      return;
    }
    this._cachedScaleForStroking[0] = -1;
    this._cachedGetSinglePixelWidth = null;
    ctx.save();
    if (current2.textMatrix) {
      ctx.transform(...current2.textMatrix);
    }
    ctx.translate(current2.x, current2.y + current2.textRise);
    ctx.scale(textHScale, fontDirection);
    const dependencyTracker = this.dependencyTracker;
    this.dependencyTracker = dependencyTracker ? new CanvasNestedDependencyTracker(dependencyTracker, opIdx) : null;
    for (i7 = 0; i7 < glyphsLength; ++i7) {
      glyph = glyphs[i7];
      if (typeof glyph === "number") {
        spacingLength = spacingDir * glyph * fontSize / 1e3;
        this.ctx.translate(spacingLength, 0);
        current2.x += spacingLength * textHScale;
        continue;
      }
      const spacing2 = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
      const operatorList = font.charProcOperatorList[glyph.operatorListId];
      if (!operatorList) {
        warn(`Type3 character "${glyph.operatorListId}" is not available.`);
      } else if (this.contentVisible) {
        this.save();
        ctx.scale(fontSize, fontSize);
        ctx.transform(...fontMatrix);
        this.executeOperatorList(operatorList);
        this.restore();
      }
      const p4 = [glyph.width, 0];
      Util.applyTransform(p4, fontMatrix);
      width = p4[0] * fontSize + spacing2;
      ctx.translate(width, 0);
      current2.x += width * textHScale;
    }
    ctx.restore();
    if (dependencyTracker) {
      this.dependencyTracker = dependencyTracker;
    }
  }
  setCharWidth(opIdx, xWidth, yWidth) {
  }
  setCharWidthAndBounds(opIdx, xWidth, yWidth, llx, lly, urx, ury) {
    const clip = new Path2D();
    clip.rect(llx, lly, urx - llx, ury - lly);
    this.ctx.clip(clip);
    this.dependencyTracker?.recordBBox(opIdx, this.ctx, llx, urx, lly, ury).recordClipBox(opIdx, this.ctx, llx, urx, lly, ury);
    this.endPath(opIdx);
  }
  getColorN_Pattern(opIdx, IR) {
    let pattern;
    if (IR[0] === "TilingPattern") {
      const baseTransform = this.baseTransform || getCurrentTransform(this.ctx);
      const canvasGraphicsFactory = {
        createCanvasGraphics: (ctx, renderingOpIdx) => new _CanvasGraphics(ctx, this.commonObjs, this.objs, this.canvasFactory, this.filterFactory, {
          optionalContentConfig: this.optionalContentConfig,
          markedContentStack: this.markedContentStack
        }, void 0, void 0, this.dependencyTracker ? new CanvasNestedDependencyTracker(this.dependencyTracker, renderingOpIdx, true) : null)
      };
      pattern = new TilingPattern(IR, this.ctx, canvasGraphicsFactory, baseTransform);
    } else {
      pattern = this._getPattern(opIdx, IR[1], IR[2]);
    }
    return pattern;
  }
  setStrokeColorN(opIdx, ...args) {
    this.dependencyTracker?.recordSimpleData("strokeColor", opIdx);
    this.current.strokeColor = this.getColorN_Pattern(opIdx, args);
    this.current.patternStroke = true;
  }
  setFillColorN(opIdx, ...args) {
    this.dependencyTracker?.recordSimpleData("fillColor", opIdx);
    this.current.fillColor = this.getColorN_Pattern(opIdx, args);
    this.current.patternFill = true;
  }
  setStrokeRGBColor(opIdx, color) {
    this.dependencyTracker?.recordSimpleData("strokeColor", opIdx);
    this.ctx.strokeStyle = this.current.strokeColor = color;
    this.current.patternStroke = false;
  }
  setStrokeTransparent(opIdx) {
    this.dependencyTracker?.recordSimpleData("strokeColor", opIdx);
    this.ctx.strokeStyle = this.current.strokeColor = "transparent";
    this.current.patternStroke = false;
  }
  setFillRGBColor(opIdx, color) {
    this.dependencyTracker?.recordSimpleData("fillColor", opIdx);
    this.ctx.fillStyle = this.current.fillColor = color;
    this.current.patternFill = false;
  }
  setFillTransparent(opIdx) {
    this.dependencyTracker?.recordSimpleData("fillColor", opIdx);
    this.ctx.fillStyle = this.current.fillColor = "transparent";
    this.current.patternFill = false;
  }
  _getPattern(opIdx, objId, matrix = null) {
    let pattern;
    if (this.cachedPatterns.has(objId)) {
      pattern = this.cachedPatterns.get(objId);
    } else {
      pattern = getShadingPattern(this.getObject(opIdx, objId));
      this.cachedPatterns.set(objId, pattern);
    }
    if (matrix) {
      pattern.matrix = matrix;
    }
    return pattern;
  }
  shadingFill(opIdx, objId) {
    if (!this.contentVisible) {
      return;
    }
    const ctx = this.ctx;
    this.save(opIdx);
    const pattern = this._getPattern(opIdx, objId);
    ctx.fillStyle = pattern.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.SHADING, opIdx);
    const inv = getCurrentTransformInverse(ctx);
    if (inv) {
      const {
        width,
        height
      } = ctx.canvas;
      const minMax = MIN_MAX_INIT.slice();
      Util.axialAlignedBoundingBox([0, 0, width, height], inv, minMax);
      const [x0, y0, x1, y1] = minMax;
      this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
    } else {
      this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
    }
    this.dependencyTracker?.resetBBox(opIdx).recordFullPageBBox(opIdx).recordDependencies(opIdx, Dependencies.transform).recordDependencies(opIdx, Dependencies.fill).recordOperation(opIdx);
    this.compose(this.current.getClippedPathBoundingBox());
    this.restore(opIdx);
  }
  beginInlineImage() {
    unreachable("Should not call beginInlineImage");
  }
  beginImageData() {
    unreachable("Should not call beginImageData");
  }
  paintFormXObjectBegin(opIdx, matrix, bbox) {
    if (!this.contentVisible) {
      return;
    }
    this.save(opIdx);
    this.baseTransformStack.push(this.baseTransform);
    if (matrix) {
      this.transform(opIdx, ...matrix);
    }
    this.baseTransform = getCurrentTransform(this.ctx);
    if (bbox) {
      Util.axialAlignedBoundingBox(bbox, this.baseTransform, this.current.minMax);
      const [x0, y0, x1, y1] = bbox;
      const clip = new Path2D();
      clip.rect(x0, y0, x1 - x0, y1 - y0);
      this.ctx.clip(clip);
      this.dependencyTracker?.recordClipBox(opIdx, this.ctx, x0, x1, y0, y1);
      this.endPath(opIdx);
    }
  }
  paintFormXObjectEnd(opIdx) {
    if (!this.contentVisible) {
      return;
    }
    this.restore(opIdx);
    this.baseTransform = this.baseTransformStack.pop();
  }
  beginGroup(opIdx, group) {
    if (!this.contentVisible) {
      return;
    }
    this.save(opIdx);
    if (this.inSMaskMode) {
      this.endSMaskMode();
      this.current.activeSMask = null;
    }
    const currentCtx = this.ctx;
    if (!group.isolated) {
      info("TODO: Support non-isolated groups.");
    }
    if (group.knockout) {
      warn("Knockout groups not supported.");
    }
    const currentTransform = getCurrentTransform(currentCtx);
    if (group.matrix) {
      currentCtx.transform(...group.matrix);
    }
    if (!group.bbox) {
      throw new Error("Bounding box is required.");
    }
    let bounds = MIN_MAX_INIT.slice();
    Util.axialAlignedBoundingBox(group.bbox, getCurrentTransform(currentCtx), bounds);
    const canvasBounds = [0, 0, currentCtx.canvas.width, currentCtx.canvas.height];
    bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
    const offsetX = Math.floor(bounds[0]);
    const offsetY = Math.floor(bounds[1]);
    const drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
    const drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
    this.current.startNewPathAndClipBox([0, 0, drawnWidth, drawnHeight]);
    let cacheId = "groupAt" + this.groupLevel;
    if (group.smask) {
      cacheId += "_smask_" + this.smaskCounter++ % 2;
    }
    const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight);
    const groupCtx = scratchCanvas.context;
    groupCtx.translate(-offsetX, -offsetY);
    groupCtx.transform(...currentTransform);
    let clip = new Path2D();
    const [x0, y0, x1, y1] = group.bbox;
    clip.rect(x0, y0, x1 - x0, y1 - y0);
    if (group.matrix) {
      const path6 = new Path2D();
      path6.addPath(clip, new DOMMatrix(group.matrix));
      clip = path6;
    }
    groupCtx.clip(clip);
    if (group.smask) {
      this.smaskStack.push({
        canvas: scratchCanvas.canvas,
        context: groupCtx,
        offsetX,
        offsetY,
        subtype: group.smask.subtype,
        backdrop: group.smask.backdrop,
        transferMap: group.smask.transferMap || null,
        startTransformInverse: null
      });
    }
    if (!group.smask || this.dependencyTracker) {
      currentCtx.setTransform(1, 0, 0, 1, 0, 0);
      currentCtx.translate(offsetX, offsetY);
      currentCtx.save();
    }
    copyCtxState(currentCtx, groupCtx);
    this.ctx = groupCtx;
    this.dependencyTracker?.inheritSimpleDataAsFutureForcedDependencies(["fillAlpha", "strokeAlpha", "globalCompositeOperation"]).pushBaseTransform(currentCtx);
    this.setGState(opIdx, [["BM", "source-over"], ["ca", 1], ["CA", 1]]);
    this.groupStack.push(currentCtx);
    this.groupLevel++;
  }
  endGroup(opIdx, group) {
    if (!this.contentVisible) {
      return;
    }
    this.groupLevel--;
    const groupCtx = this.ctx;
    const ctx = this.groupStack.pop();
    this.ctx = ctx;
    this.ctx.imageSmoothingEnabled = false;
    this.dependencyTracker?.popBaseTransform();
    if (group.smask) {
      this.tempSMask = this.smaskStack.pop();
      this.restore(opIdx);
      if (this.dependencyTracker) {
        this.ctx.restore();
      }
    } else {
      this.ctx.restore();
      const currentMtx = getCurrentTransform(this.ctx);
      this.restore(opIdx);
      this.ctx.save();
      this.ctx.setTransform(...currentMtx);
      const dirtyBox = MIN_MAX_INIT.slice();
      Util.axialAlignedBoundingBox([0, 0, groupCtx.canvas.width, groupCtx.canvas.height], currentMtx, dirtyBox);
      this.ctx.drawImage(groupCtx.canvas, 0, 0);
      this.ctx.restore();
      this.compose(dirtyBox);
    }
  }
  beginAnnotation(opIdx, id, rect, transform, matrix, hasOwnCanvas) {
    this.#restoreInitialState();
    resetCtxToDefault(this.ctx);
    this.ctx.save();
    this.save(opIdx);
    if (this.baseTransform) {
      this.ctx.setTransform(...this.baseTransform);
    }
    if (rect) {
      const width = rect[2] - rect[0];
      const height = rect[3] - rect[1];
      if (hasOwnCanvas && this.annotationCanvasMap) {
        transform = transform.slice();
        transform[4] -= rect[0];
        transform[5] -= rect[1];
        rect = rect.slice();
        rect[0] = rect[1] = 0;
        rect[2] = width;
        rect[3] = height;
        Util.singularValueDecompose2dScale(getCurrentTransform(this.ctx), XY);
        const {
          viewportScale
        } = this;
        const canvasWidth = Math.ceil(width * this.outputScaleX * viewportScale);
        const canvasHeight = Math.ceil(height * this.outputScaleY * viewportScale);
        this.annotationCanvas = this.canvasFactory.create(canvasWidth, canvasHeight);
        const {
          canvas,
          context
        } = this.annotationCanvas;
        this.annotationCanvasMap.set(id, canvas);
        this.annotationCanvas.savedCtx = this.ctx;
        this.ctx = context;
        this.ctx.save();
        this.ctx.setTransform(XY[0], 0, 0, -XY[1], 0, height * XY[1]);
        resetCtxToDefault(this.ctx);
      } else {
        resetCtxToDefault(this.ctx);
        this.endPath(opIdx);
        const clip = new Path2D();
        clip.rect(rect[0], rect[1], width, height);
        this.ctx.clip(clip);
      }
    }
    this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height);
    this.transform(opIdx, ...transform);
    this.transform(opIdx, ...matrix);
  }
  endAnnotation(opIdx) {
    if (this.annotationCanvas) {
      this.ctx.restore();
      this.#drawFilter();
      this.ctx = this.annotationCanvas.savedCtx;
      delete this.annotationCanvas.savedCtx;
      delete this.annotationCanvas;
    }
  }
  paintImageMaskXObject(opIdx, img) {
    if (!this.contentVisible) {
      return;
    }
    const count = img.count;
    img = this.getObject(opIdx, img.data, img);
    img.count = count;
    const ctx = this.ctx;
    const mask = this._createMaskCanvas(opIdx, img);
    const maskCanvas = mask.canvas;
    ctx.save();
    ctx.setTransform(1, 0, 0, 1, 0, 0);
    ctx.drawImage(maskCanvas, mask.offsetX, mask.offsetY);
    this.dependencyTracker?.resetBBox(opIdx).recordBBox(opIdx, this.ctx, mask.offsetX, mask.offsetX + maskCanvas.width, mask.offsetY, mask.offsetY + maskCanvas.height).recordOperation(opIdx);
    ctx.restore();
    this.compose();
  }
  paintImageMaskXObjectRepeat(opIdx, img, scaleX, skewX = 0, skewY = 0, scaleY, positions) {
    if (!this.contentVisible) {
      return;
    }
    img = this.getObject(opIdx, img.data, img);
    const ctx = this.ctx;
    ctx.save();
    const currentTransform = getCurrentTransform(ctx);
    ctx.transform(scaleX, skewX, skewY, scaleY, 0, 0);
    const mask = this._createMaskCanvas(opIdx, img);
    ctx.setTransform(1, 0, 0, 1, mask.offsetX - currentTransform[4], mask.offsetY - currentTransform[5]);
    this.dependencyTracker?.resetBBox(opIdx);
    for (let i7 = 0, ii = positions.length; i7 < ii; i7 += 2) {
      const trans = Util.transform(currentTransform, [scaleX, skewX, skewY, scaleY, positions[i7], positions[i7 + 1]]);
      ctx.drawImage(mask.canvas, trans[4], trans[5]);
      this.dependencyTracker?.recordBBox(opIdx, this.ctx, trans[4], trans[4] + mask.canvas.width, trans[5], trans[5] + mask.canvas.height);
    }
    ctx.restore();
    this.compose();
    this.dependencyTracker?.recordOperation(opIdx);
  }
  paintImageMaskXObjectGroup(opIdx, images) {
    if (!this.contentVisible) {
      return;
    }
    const ctx = this.ctx;
    const fillColor = this.current.fillColor;
    const isPatternFill = this.current.patternFill;
    this.dependencyTracker?.resetBBox(opIdx).recordDependencies(opIdx, Dependencies.transformAndFill);
    for (const image of images) {
      const {
        data,
        width,
        height,
        transform
      } = image;
      const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
      const maskCtx = maskCanvas.context;
      maskCtx.save();
      const img = this.getObject(opIdx, data, image);
      putBinaryImageMask(maskCtx, img);
      maskCtx.globalCompositeOperation = "source-in";
      maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this, getCurrentTransformInverse(ctx), PathType.FILL, opIdx) : fillColor;
      maskCtx.fillRect(0, 0, width, height);
      maskCtx.restore();
      ctx.save();
      ctx.transform(...transform);
      ctx.scale(1, -1);
      drawImageAtIntegerCoords(ctx, maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);
      this.dependencyTracker?.recordBBox(opIdx, ctx, 0, width, 0, height);
      ctx.restore();
    }
    this.compose();
    this.dependencyTracker?.recordOperation(opIdx);
  }
  paintImageXObject(opIdx, objId) {
    if (!this.contentVisible) {
      return;
    }
    const imgData = this.getObject(opIdx, objId);
    if (!imgData) {
      warn("Dependent image isn't ready yet");
      return;
    }
    this.paintInlineImageXObject(opIdx, imgData);
  }
  paintImageXObjectRepeat(opIdx, objId, scaleX, scaleY, positions) {
    if (!this.contentVisible) {
      return;
    }
    const imgData = this.getObject(opIdx, objId);
    if (!imgData) {
      warn("Dependent image isn't ready yet");
      return;
    }
    const width = imgData.width;
    const height = imgData.height;
    const map = [];
    for (let i7 = 0, ii = positions.length; i7 < ii; i7 += 2) {
      map.push({
        transform: [scaleX, 0, 0, scaleY, positions[i7], positions[i7 + 1]],
        x: 0,
        y: 0,
        w: width,
        h: height
      });
    }
    this.paintInlineImageXObjectGroup(opIdx, imgData, map);
  }
  applyTransferMapsToCanvas(ctx) {
    if (this.current.transferMaps !== "none") {
      ctx.filter = this.current.transferMaps;
      ctx.drawImage(ctx.canvas, 0, 0);
      ctx.filter = "none";
    }
    return ctx.canvas;
  }
  applyTransferMapsToBitmap(imgData) {
    if (this.current.transferMaps === "none") {
      return imgData.bitmap;
    }
    const {
      bitmap,
      width,
      height
    } = imgData;
    const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height);
    const tmpCtx = tmpCanvas.context;
    tmpCtx.filter = this.current.transferMaps;
    tmpCtx.drawImage(bitmap, 0, 0);
    tmpCtx.filter = "none";
    return tmpCanvas.canvas;
  }
  paintInlineImageXObject(opIdx, imgData) {
    if (!this.contentVisible) {
      return;
    }
    const width = imgData.width;
    const height = imgData.height;
    const ctx = this.ctx;
    this.save(opIdx);
    const {
      filter: filter2
    } = ctx;
    if (filter2 !== "none" && filter2 !== "") {
      ctx.filter = "none";
    }
    ctx.scale(1 / width, -1 / height);
    let imgToPaint;
    if (imgData.bitmap) {
      imgToPaint = this.applyTransferMapsToBitmap(imgData);
    } else if (typeof HTMLElement === "function" && imgData instanceof HTMLElement || !imgData.data) {
      imgToPaint = imgData;
    } else {
      const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height);
      const tmpCtx = tmpCanvas.context;
      putBinaryImageData(tmpCtx, imgData);
      imgToPaint = this.applyTransferMapsToCanvas(tmpCtx);
    }
    const scaled = this._scaleImage(imgToPaint, getCurrentTransformInverse(ctx));
    ctx.imageSmoothingEnabled = getImageSmoothingEnabled(getCurrentTransform(ctx), imgData.interpolate);
    this.dependencyTracker?.resetBBox(opIdx).recordBBox(opIdx, ctx, 0, width, -height, 0).recordDependencies(opIdx, Dependencies.imageXObject).recordOperation(opIdx);
    drawImageAtIntegerCoords(ctx, scaled.img, 0, 0, scaled.paintWidth, scaled.paintHeight, 0, -height, width, height);
    this.compose();
    this.restore(opIdx);
  }
  paintInlineImageXObjectGroup(opIdx, imgData, map) {
    if (!this.contentVisible) {
      return;
    }
    const ctx = this.ctx;
    let imgToPaint;
    if (imgData.bitmap) {
      imgToPaint = imgData.bitmap;
    } else {
      const w3 = imgData.width;
      const h7 = imgData.height;
      const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", w3, h7);
      const tmpCtx = tmpCanvas.context;
      putBinaryImageData(tmpCtx, imgData);
      imgToPaint = this.applyTransferMapsToCanvas(tmpCtx);
    }
    this.dependencyTracker?.resetBBox(opIdx);
    for (const entry of map) {
      ctx.save();
      ctx.transform(...entry.transform);
      ctx.scale(1, -1);
      drawImageAtIntegerCoords(ctx, imgToPaint, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1);
      this.dependencyTracker?.recordBBox(opIdx, ctx, 0, 1, -1, 0);
      ctx.restore();
    }
    this.dependencyTracker?.recordOperation(opIdx);
    this.compose();
  }
  paintSolidColorImageMask(opIdx) {
    if (!this.contentVisible) {
      return;
    }
    this.dependencyTracker?.resetBBox(opIdx).recordBBox(opIdx, this.ctx, 0, 1, 0, 1).recordDependencies(opIdx, Dependencies.fill).recordOperation(opIdx);
    this.ctx.fillRect(0, 0, 1, 1);
    this.compose();
  }
  markPoint(opIdx, tag) {
  }
  markPointProps(opIdx, tag, properties) {
  }
  beginMarkedContent(opIdx, tag) {
    this.dependencyTracker?.beginMarkedContent(opIdx);
    this.markedContentStack.push({
      visible: true
    });
  }
  beginMarkedContentProps(opIdx, tag, properties) {
    this.dependencyTracker?.beginMarkedContent(opIdx);
    if (tag === "OC") {
      this.markedContentStack.push({
        visible: this.optionalContentConfig.isVisible(properties)
      });
    } else {
      this.markedContentStack.push({
        visible: true
      });
    }
    this.contentVisible = this.isContentVisible();
  }
  endMarkedContent(opIdx) {
    this.dependencyTracker?.endMarkedContent(opIdx);
    this.markedContentStack.pop();
    this.contentVisible = this.isContentVisible();
  }
  beginCompat(opIdx) {
  }
  endCompat(opIdx) {
  }
  consumePath(opIdx, path6, clipBox) {
    const isEmpty = this.current.isEmptyClip();
    if (this.pendingClip) {
      this.current.updateClipFromPath();
    }
    if (!this.pendingClip) {
      this.compose(clipBox);
    }
    const ctx = this.ctx;
    if (this.pendingClip) {
      if (!isEmpty) {
        if (this.pendingClip === EO_CLIP) {
          ctx.clip(path6, "evenodd");
        } else {
          ctx.clip(path6);
        }
      }
      this.pendingClip = null;
      this.dependencyTracker?.bboxToClipBoxDropOperation(opIdx).recordFutureForcedDependency("clipPath", opIdx);
    } else {
      this.dependencyTracker?.recordOperation(opIdx);
    }
    this.current.startNewPathAndClipBox(this.current.clipBox);
  }
  getSinglePixelWidth() {
    if (!this._cachedGetSinglePixelWidth) {
      const m4 = getCurrentTransform(this.ctx);
      if (m4[1] === 0 && m4[2] === 0) {
        this._cachedGetSinglePixelWidth = 1 / Math.min(Math.abs(m4[0]), Math.abs(m4[3]));
      } else {
        const absDet = Math.abs(m4[0] * m4[3] - m4[2] * m4[1]);
        const normX = Math.hypot(m4[0], m4[2]);
        const normY = Math.hypot(m4[1], m4[3]);
        this._cachedGetSinglePixelWidth = Math.max(normX, normY) / absDet;
      }
    }
    return this._cachedGetSinglePixelWidth;
  }
  getScaleForStroking() {
    if (this._cachedScaleForStroking[0] === -1) {
      const {
        lineWidth
      } = this.current;
      const {
        a: a3,
        b: b4,
        c: c6,
        d: d4
      } = this.ctx.getTransform();
      let scaleX, scaleY;
      if (b4 === 0 && c6 === 0) {
        const normX = Math.abs(a3);
        const normY = Math.abs(d4);
        if (normX === normY) {
          if (lineWidth === 0) {
            scaleX = scaleY = 1 / normX;
          } else {
            const scaledLineWidth = normX * lineWidth;
            scaleX = scaleY = scaledLineWidth < 1 ? 1 / scaledLineWidth : 1;
          }
        } else if (lineWidth === 0) {
          scaleX = 1 / normX;
          scaleY = 1 / normY;
        } else {
          const scaledXLineWidth = normX * lineWidth;
          const scaledYLineWidth = normY * lineWidth;
          scaleX = scaledXLineWidth < 1 ? 1 / scaledXLineWidth : 1;
          scaleY = scaledYLineWidth < 1 ? 1 / scaledYLineWidth : 1;
        }
      } else {
        const absDet = Math.abs(a3 * d4 - b4 * c6);
        const normX = Math.hypot(a3, b4);
        const normY = Math.hypot(c6, d4);
        if (lineWidth === 0) {
          scaleX = normY / absDet;
          scaleY = normX / absDet;
        } else {
          const baseArea = lineWidth * absDet;
          scaleX = normY > baseArea ? normY / baseArea : 1;
          scaleY = normX > baseArea ? normX / baseArea : 1;
        }
      }
      this._cachedScaleForStroking[0] = scaleX;
      this._cachedScaleForStroking[1] = scaleY;
    }
    return this._cachedScaleForStroking;
  }
  rescaleAndStroke(path6, saveRestore) {
    const {
      ctx,
      current: {
        lineWidth
      }
    } = this;
    const [scaleX, scaleY] = this.getScaleForStroking();
    if (scaleX === scaleY) {
      ctx.lineWidth = (lineWidth || 1) * scaleX;
      ctx.stroke(path6);
      return;
    }
    const dashes = ctx.getLineDash();
    if (saveRestore) {
      ctx.save();
    }
    ctx.scale(scaleX, scaleY);
    SCALE_MATRIX.a = 1 / scaleX;
    SCALE_MATRIX.d = 1 / scaleY;
    const newPath = new Path2D();
    newPath.addPath(path6, SCALE_MATRIX);
    if (dashes.length > 0) {
      const scale = Math.max(scaleX, scaleY);
      ctx.setLineDash(dashes.map((x2) => x2 / scale));
      ctx.lineDashOffset /= scale;
    }
    ctx.lineWidth = lineWidth || 1;
    ctx.stroke(newPath);
    if (saveRestore) {
      ctx.restore();
    }
  }
  isContentVisible() {
    for (let i7 = this.markedContentStack.length - 1; i7 >= 0; i7--) {
      if (!this.markedContentStack[i7].visible) {
        return false;
      }
    }
    return true;
  }
};
for (const op2 in OPS) {
  if (CanvasGraphics.prototype[op2] !== void 0) {
    CanvasGraphics.prototype[OPS[op2]] = CanvasGraphics.prototype[op2];
  }
}
var GlobalWorkerOptions = class {
  static #port = null;
  static #src = "";
  static get workerPort() {
    return this.#port;
  }
  static set workerPort(val2) {
    if (!(typeof Worker !== "undefined" && val2 instanceof Worker) && val2 !== null) {
      throw new Error("Invalid `workerPort` type.");
    }
    this.#port = val2;
  }
  static get workerSrc() {
    return this.#src;
  }
  static set workerSrc(val2) {
    if (typeof val2 !== "string") {
      throw new Error("Invalid `workerSrc` type.");
    }
    this.#src = val2;
  }
};
var Metadata = class {
  #map;
  #data;
  constructor({
    parsedData,
    rawData
  }) {
    this.#map = parsedData;
    this.#data = rawData;
  }
  getRaw() {
    return this.#data;
  }
  get(name) {
    return this.#map.get(name) ?? null;
  }
  [Symbol.iterator]() {
    return this.#map.entries();
  }
};
var INTERNAL = Symbol("INTERNAL");
var OptionalContentGroup = class {
  #isDisplay = false;
  #isPrint = false;
  #userSet = false;
  #visible = true;
  constructor(renderingIntent, {
    name,
    intent,
    usage,
    rbGroups
  }) {
    this.#isDisplay = !!(renderingIntent & RenderingIntentFlag.DISPLAY);
    this.#isPrint = !!(renderingIntent & RenderingIntentFlag.PRINT);
    this.name = name;
    this.intent = intent;
    this.usage = usage;
    this.rbGroups = rbGroups;
  }
  get visible() {
    if (this.#userSet) {
      return this.#visible;
    }
    if (!this.#visible) {
      return false;
    }
    const {
      print,
      view
    } = this.usage;
    if (this.#isDisplay) {
      return view?.viewState !== "OFF";
    } else if (this.#isPrint) {
      return print?.printState !== "OFF";
    }
    return true;
  }
  _setVisible(internal, visible, userSet = false) {
    if (internal !== INTERNAL) {
      unreachable("Internal method `_setVisible` called.");
    }
    this.#userSet = userSet;
    this.#visible = visible;
  }
};
var OptionalContentConfig = class {
  #cachedGetHash = null;
  #groups = /* @__PURE__ */ new Map();
  #initialHash = null;
  #order = null;
  constructor(data, renderingIntent = RenderingIntentFlag.DISPLAY) {
    this.renderingIntent = renderingIntent;
    this.name = null;
    this.creator = null;
    if (data === null) {
      return;
    }
    this.name = data.name;
    this.creator = data.creator;
    this.#order = data.order;
    for (const group of data.groups) {
      this.#groups.set(group.id, new OptionalContentGroup(renderingIntent, group));
    }
    if (data.baseState === "OFF") {
      for (const group of this.#groups.values()) {
        group._setVisible(INTERNAL, false);
      }
    }
    for (const on of data.on) {
      this.#groups.get(on)._setVisible(INTERNAL, true);
    }
    for (const off of data.off) {
      this.#groups.get(off)._setVisible(INTERNAL, false);
    }
    this.#initialHash = this.getHash();
  }
  #evaluateVisibilityExpression(array) {
    const length = array.length;
    if (length < 2) {
      return true;
    }
    const operator = array[0];
    for (let i7 = 1; i7 < length; i7++) {
      const element = array[i7];
      let state;
      if (Array.isArray(element)) {
        state = this.#evaluateVisibilityExpression(element);
      } else if (this.#groups.has(element)) {
        state = this.#groups.get(element).visible;
      } else {
        warn(`Optional content group not found: ${element}`);
        return true;
      }
      switch (operator) {
        case "And":
          if (!state) {
            return false;
          }
          break;
        case "Or":
          if (state) {
            return true;
          }
          break;
        case "Not":
          return !state;
        default:
          return true;
      }
    }
    return operator === "And";
  }
  isVisible(group) {
    if (this.#groups.size === 0) {
      return true;
    }
    if (!group) {
      info("Optional content group not defined.");
      return true;
    }
    if (group.type === "OCG") {
      if (!this.#groups.has(group.id)) {
        warn(`Optional content group not found: ${group.id}`);
        return true;
      }
      return this.#groups.get(group.id).visible;
    } else if (group.type === "OCMD") {
      if (group.expression) {
        return this.#evaluateVisibilityExpression(group.expression);
      }
      if (!group.policy || group.policy === "AnyOn") {
        for (const id of group.ids) {
          if (!this.#groups.has(id)) {
            warn(`Optional content group not found: ${id}`);
            return true;
          }
          if (this.#groups.get(id).visible) {
            return true;
          }
        }
        return false;
      } else if (group.policy === "AllOn") {
        for (const id of group.ids) {
          if (!this.#groups.has(id)) {
            warn(`Optional content group not found: ${id}`);
            return true;
          }
          if (!this.#groups.get(id).visible) {
            return false;
          }
        }
        return true;
      } else if (group.policy === "AnyOff") {
        for (const id of group.ids) {
          if (!this.#groups.has(id)) {
            warn(`Optional content group not found: ${id}`);
            return true;
          }
          if (!this.#groups.get(id).visible) {
            return true;
          }
        }
        return false;
      } else if (group.policy === "AllOff") {
        for (const id of group.ids) {
          if (!this.#groups.has(id)) {
            warn(`Optional content group not found: ${id}`);
            return true;
          }
          if (this.#groups.get(id).visible) {
            return false;
          }
        }
        return true;
      }
      warn(`Unknown optional content policy ${group.policy}.`);
      return true;
    }
    warn(`Unknown group type ${group.type}.`);
    return true;
  }
  setVisibility(id, visible = true, preserveRB = true) {
    const group = this.#groups.get(id);
    if (!group) {
      warn(`Optional content group not found: ${id}`);
      return;
    }
    if (preserveRB && visible && group.rbGroups.length) {
      for (const rbGroup of group.rbGroups) {
        for (const otherId of rbGroup) {
          if (otherId !== id) {
            this.#groups.get(otherId)?._setVisible(INTERNAL, false, true);
          }
        }
      }
    }
    group._setVisible(INTERNAL, !!visible, true);
    this.#cachedGetHash = null;
  }
  setOCGState({
    state,
    preserveRB
  }) {
    let operator;
    for (const elem of state) {
      switch (elem) {
        case "ON":
        case "OFF":
        case "Toggle":
          operator = elem;
          continue;
      }
      const group = this.#groups.get(elem);
      if (!group) {
        continue;
      }
      switch (operator) {
        case "ON":
          this.setVisibility(elem, true, preserveRB);
          break;
        case "OFF":
          this.setVisibility(elem, false, preserveRB);
          break;
        case "Toggle":
          this.setVisibility(elem, !group.visible, preserveRB);
          break;
      }
    }
    this.#cachedGetHash = null;
  }
  get hasInitialVisibility() {
    return this.#initialHash === null || this.getHash() === this.#initialHash;
  }
  getOrder() {
    if (!this.#groups.size) {
      return null;
    }
    if (this.#order) {
      return this.#order.slice();
    }
    return [...this.#groups.keys()];
  }
  getGroup(id) {
    return this.#groups.get(id) || null;
  }
  getHash() {
    if (this.#cachedGetHash !== null) {
      return this.#cachedGetHash;
    }
    const hash = new MurmurHash3_64();
    for (const [id, group] of this.#groups) {
      hash.update(`${id}:${group.visible}`);
    }
    return this.#cachedGetHash = hash.hexdigest();
  }
  [Symbol.iterator]() {
    return this.#groups.entries();
  }
};
var PDFDataTransportStream = class {
  constructor(pdfDataRangeTransport, {
    disableRange = false,
    disableStream = false
  }) {
    assert(pdfDataRangeTransport, 'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');
    const {
      length,
      initialData,
      progressiveDone,
      contentDispositionFilename
    } = pdfDataRangeTransport;
    this._queuedChunks = [];
    this._progressiveDone = progressiveDone;
    this._contentDispositionFilename = contentDispositionFilename;
    if (initialData?.length > 0) {
      const buffer = initialData instanceof Uint8Array && initialData.byteLength === initialData.buffer.byteLength ? initialData.buffer : new Uint8Array(initialData).buffer;
      this._queuedChunks.push(buffer);
    }
    this._pdfDataRangeTransport = pdfDataRangeTransport;
    this._isStreamingSupported = !disableStream;
    this._isRangeSupported = !disableRange;
    this._contentLength = length;
    this._fullRequestReader = null;
    this._rangeReaders = [];
    pdfDataRangeTransport.addRangeListener((begin, chunk) => {
      this._onReceiveData({
        begin,
        chunk
      });
    });
    pdfDataRangeTransport.addProgressListener((loaded, total) => {
      this._onProgress({
        loaded,
        total
      });
    });
    pdfDataRangeTransport.addProgressiveReadListener((chunk) => {
      this._onReceiveData({
        chunk
      });
    });
    pdfDataRangeTransport.addProgressiveDoneListener(() => {
      this._onProgressiveDone();
    });
    pdfDataRangeTransport.transportReady();
  }
  _onReceiveData({
    begin,
    chunk
  }) {
    const buffer = chunk instanceof Uint8Array && chunk.byteLength === chunk.buffer.byteLength ? chunk.buffer : new Uint8Array(chunk).buffer;
    if (begin === void 0) {
      if (this._fullRequestReader) {
        this._fullRequestReader._enqueue(buffer);
      } else {
        this._queuedChunks.push(buffer);
      }
    } else {
      const found = this._rangeReaders.some(function(rangeReader) {
        if (rangeReader._begin !== begin) {
          return false;
        }
        rangeReader._enqueue(buffer);
        return true;
      });
      assert(found, "_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.");
    }
  }
  get _progressiveDataLength() {
    return this._fullRequestReader?._loaded ?? 0;
  }
  _onProgress(evt) {
    if (evt.total === void 0) {
      this._rangeReaders[0]?.onProgress?.({
        loaded: evt.loaded
      });
    } else {
      this._fullRequestReader?.onProgress?.({
        loaded: evt.loaded,
        total: evt.total
      });
    }
  }
  _onProgressiveDone() {
    this._fullRequestReader?.progressiveDone();
    this._progressiveDone = true;
  }
  _removeRangeReader(reader) {
    const i7 = this._rangeReaders.indexOf(reader);
    if (i7 >= 0) {
      this._rangeReaders.splice(i7, 1);
    }
  }
  getFullReader() {
    assert(!this._fullRequestReader, "PDFDataTransportStream.getFullReader can only be called once.");
    const queuedChunks = this._queuedChunks;
    this._queuedChunks = null;
    return new PDFDataTransportStreamReader(this, queuedChunks, this._progressiveDone, this._contentDispositionFilename);
  }
  getRangeReader(begin, end) {
    if (end <= this._progressiveDataLength) {
      return null;
    }
    const reader = new PDFDataTransportStreamRangeReader(this, begin, end);
    this._pdfDataRangeTransport.requestDataRange(begin, end);
    this._rangeReaders.push(reader);
    return reader;
  }
  cancelAllRequests(reason) {
    this._fullRequestReader?.cancel(reason);
    for (const reader of this._rangeReaders.slice(0)) {
      reader.cancel(reason);
    }
    this._pdfDataRangeTransport.abort();
  }
};
var PDFDataTransportStreamReader = class {
  constructor(stream2, queuedChunks, progressiveDone = false, contentDispositionFilename = null) {
    this._stream = stream2;
    this._done = progressiveDone || false;
    this._filename = isPdfFile(contentDispositionFilename) ? contentDispositionFilename : null;
    this._queuedChunks = queuedChunks || [];
    this._loaded = 0;
    for (const chunk of this._queuedChunks) {
      this._loaded += chunk.byteLength;
    }
    this._requests = [];
    this._headersReady = Promise.resolve();
    stream2._fullRequestReader = this;
    this.onProgress = null;
  }
  _enqueue(chunk) {
    if (this._done) {
      return;
    }
    if (this._requests.length > 0) {
      const requestCapability = this._requests.shift();
      requestCapability.resolve({
        value: chunk,
        done: false
      });
    } else {
      this._queuedChunks.push(chunk);
    }
    this._loaded += chunk.byteLength;
  }
  get headersReady() {
    return this._headersReady;
  }
  get filename() {
    return this._filename;
  }
  get isRangeSupported() {
    return this._stream._isRangeSupported;
  }
  get isStreamingSupported() {
    return this._stream._isStreamingSupported;
  }
  get contentLength() {
    return this._stream._contentLength;
  }
  async read() {
    if (this._queuedChunks.length > 0) {
      const chunk = this._queuedChunks.shift();
      return {
        value: chunk,
        done: false
      };
    }
    if (this._done) {
      return {
        value: void 0,
        done: true
      };
    }
    const requestCapability = Promise.withResolvers();
    this._requests.push(requestCapability);
    return requestCapability.promise;
  }
  cancel(reason) {
    this._done = true;
    for (const requestCapability of this._requests) {
      requestCapability.resolve({
        value: void 0,
        done: true
      });
    }
    this._requests.length = 0;
  }
  progressiveDone() {
    if (this._done) {
      return;
    }
    this._done = true;
  }
};
var PDFDataTransportStreamRangeReader = class {
  constructor(stream2, begin, end) {
    this._stream = stream2;
    this._begin = begin;
    this._end = end;
    this._queuedChunk = null;
    this._requests = [];
    this._done = false;
    this.onProgress = null;
  }
  _enqueue(chunk) {
    if (this._done) {
      return;
    }
    if (this._requests.length === 0) {
      this._queuedChunk = chunk;
    } else {
      const requestsCapability = this._requests.shift();
      requestsCapability.resolve({
        value: chunk,
        done: false
      });
      for (const requestCapability of this._requests) {
        requestCapability.resolve({
          value: void 0,
          done: true
        });
      }
      this._requests.length = 0;
    }
    this._done = true;
    this._stream._removeRangeReader(this);
  }
  get isStreamingSupported() {
    return false;
  }
  async read() {
    if (this._queuedChunk) {
      const chunk = this._queuedChunk;
      this._queuedChunk = null;
      return {
        value: chunk,
        done: false
      };
    }
    if (this._done) {
      return {
        value: void 0,
        done: true
      };
    }
    const requestCapability = Promise.withResolvers();
    this._requests.push(requestCapability);
    return requestCapability.promise;
  }
  cancel(reason) {
    this._done = true;
    for (const requestCapability of this._requests) {
      requestCapability.resolve({
        value: void 0,
        done: true
      });
    }
    this._requests.length = 0;
    this._stream._removeRangeReader(this);
  }
};
function getFilenameFromContentDispositionHeader(contentDisposition) {
  let needsEncodingFixup = true;
  let tmp = toParamRegExp("filename\\*", "i").exec(contentDisposition);
  if (tmp) {
    tmp = tmp[1];
    let filename = rfc2616unquote(tmp);
    filename = unescape(filename);
    filename = rfc5987decode(filename);
    filename = rfc2047decode(filename);
    return fixupEncoding(filename);
  }
  tmp = rfc2231getparam(contentDisposition);
  if (tmp) {
    const filename = rfc2047decode(tmp);
    return fixupEncoding(filename);
  }
  tmp = toParamRegExp("filename", "i").exec(contentDisposition);
  if (tmp) {
    tmp = tmp[1];
    let filename = rfc2616unquote(tmp);
    filename = rfc2047decode(filename);
    return fixupEncoding(filename);
  }
  function toParamRegExp(attributePattern, flags) {
    return new RegExp("(?:^|;)\\s*" + attributePattern + '\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)', flags);
  }
  function textdecode(encoding, value) {
    if (encoding) {
      if (!/^[\x00-\xFF]+$/.test(value)) {
        return value;
      }
      try {
        const decoder = new TextDecoder(encoding, {
          fatal: true
        });
        const buffer = stringToBytes(value);
        value = decoder.decode(buffer);
        needsEncodingFixup = false;
      } catch {
      }
    }
    return value;
  }
  function fixupEncoding(value) {
    if (needsEncodingFixup && /[\x80-\xff]/.test(value)) {
      value = textdecode("utf-8", value);
      if (needsEncodingFixup) {
        value = textdecode("iso-8859-1", value);
      }
    }
    return value;
  }
  function rfc2231getparam(contentDispositionStr) {
    const matches = [];
    let match2;
    const iter = toParamRegExp("filename\\*((?!0\\d)\\d+)(\\*?)", "ig");
    while ((match2 = iter.exec(contentDispositionStr)) !== null) {
      let [, n7, quot, part] = match2;
      n7 = parseInt(n7, 10);
      if (n7 in matches) {
        if (n7 === 0) {
          break;
        }
        continue;
      }
      matches[n7] = [quot, part];
    }
    const parts = [];
    for (let n7 = 0; n7 < matches.length; ++n7) {
      if (!(n7 in matches)) {
        break;
      }
      let [quot, part] = matches[n7];
      part = rfc2616unquote(part);
      if (quot) {
        part = unescape(part);
        if (n7 === 0) {
          part = rfc5987decode(part);
        }
      }
      parts.push(part);
    }
    return parts.join("");
  }
  function rfc2616unquote(value) {
    if (value.startsWith('"')) {
      const parts = value.slice(1).split('\\"');
      for (let i7 = 0; i7 < parts.length; ++i7) {
        const quotindex = parts[i7].indexOf('"');
        if (quotindex !== -1) {
          parts[i7] = parts[i7].slice(0, quotindex);
          parts.length = i7 + 1;
        }
        parts[i7] = parts[i7].replaceAll(/\\(.)/g, "$1");
      }
      value = parts.join('"');
    }
    return value;
  }
  function rfc5987decode(extvalue) {
    const encodingend = extvalue.indexOf("'");
    if (encodingend === -1) {
      return extvalue;
    }
    const encoding = extvalue.slice(0, encodingend);
    const langvalue = extvalue.slice(encodingend + 1);
    const value = langvalue.replace(/^[^']*'/, "");
    return textdecode(encoding, value);
  }
  function rfc2047decode(value) {
    if (!value.startsWith("=?") || /[\x00-\x19\x80-\xff]/.test(value)) {
      return value;
    }
    return value.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g, function(matches, charset, encoding, text3) {
      if (encoding === "q" || encoding === "Q") {
        text3 = text3.replaceAll("_", " ");
        text3 = text3.replaceAll(/=([0-9a-fA-F]{2})/g, function(match2, hex) {
          return String.fromCharCode(parseInt(hex, 16));
        });
        return textdecode(charset, text3);
      }
      try {
        text3 = atob(text3);
      } catch {
      }
      return textdecode(charset, text3);
    });
  }
  return "";
}
function createHeaders(isHttp, httpHeaders) {
  const headers = new Headers();
  if (!isHttp || !httpHeaders || typeof httpHeaders !== "object") {
    return headers;
  }
  for (const key in httpHeaders) {
    const val2 = httpHeaders[key];
    if (val2 !== void 0) {
      headers.append(key, val2);
    }
  }
  return headers;
}
function getResponseOrigin(url) {
  return URL.parse(url)?.origin ?? null;
}
function validateRangeRequestCapabilities({
  responseHeaders,
  isHttp,
  rangeChunkSize,
  disableRange
}) {
  const returnValues = {
    allowRangeRequests: false,
    suggestedLength: void 0
  };
  const length = parseInt(responseHeaders.get("Content-Length"), 10);
  if (!Number.isInteger(length)) {
    return returnValues;
  }
  returnValues.suggestedLength = length;
  if (length <= 2 * rangeChunkSize) {
    return returnValues;
  }
  if (disableRange || !isHttp) {
    return returnValues;
  }
  if (responseHeaders.get("Accept-Ranges") !== "bytes") {
    return returnValues;
  }
  const contentEncoding = responseHeaders.get("Content-Encoding") || "identity";
  if (contentEncoding !== "identity") {
    return returnValues;
  }
  returnValues.allowRangeRequests = true;
  return returnValues;
}
function extractFilenameFromHeader(responseHeaders) {
  const contentDisposition = responseHeaders.get("Content-Disposition");
  if (contentDisposition) {
    let filename = getFilenameFromContentDispositionHeader(contentDisposition);
    if (filename.includes("%")) {
      try {
        filename = decodeURIComponent(filename);
      } catch {
      }
    }
    if (isPdfFile(filename)) {
      return filename;
    }
  }
  return null;
}
function createResponseError(status, url) {
  return new ResponseException(`Unexpected server response (${status}) while retrieving PDF "${url}".`, status, status === 404 || status === 0 && url.startsWith("file:"));
}
function validateResponseStatus(status) {
  return status === 200 || status === 206;
}
function createFetchOptions(headers, withCredentials, abortController) {
  return {
    method: "GET",
    headers,
    signal: abortController.signal,
    mode: "cors",
    credentials: withCredentials ? "include" : "same-origin",
    redirect: "follow"
  };
}
function getArrayBuffer(val2) {
  if (val2 instanceof Uint8Array) {
    return val2.buffer;
  }
  if (val2 instanceof ArrayBuffer) {
    return val2;
  }
  warn(`getArrayBuffer - unexpected data format: ${val2}`);
  return new Uint8Array(val2).buffer;
}
var PDFFetchStream = class {
  _responseOrigin = null;
  constructor(source) {
    this.source = source;
    this.isHttp = /^https?:/i.test(source.url);
    this.headers = createHeaders(this.isHttp, source.httpHeaders);
    this._fullRequestReader = null;
    this._rangeRequestReaders = [];
  }
  get _progressiveDataLength() {
    return this._fullRequestReader?._loaded ?? 0;
  }
  getFullReader() {
    assert(!this._fullRequestReader, "PDFFetchStream.getFullReader can only be called once.");
    this._fullRequestReader = new PDFFetchStreamReader(this);
    return this._fullRequestReader;
  }
  getRangeReader(begin, end) {
    if (end <= this._progressiveDataLength) {
      return null;
    }
    const reader = new PDFFetchStreamRangeReader(this, begin, end);
    this._rangeRequestReaders.push(reader);
    return reader;
  }
  cancelAllRequests(reason) {
    this._fullRequestReader?.cancel(reason);
    for (const reader of this._rangeRequestReaders.slice(0)) {
      reader.cancel(reason);
    }
  }
};
var PDFFetchStreamReader = class {
  constructor(stream2) {
    this._stream = stream2;
    this._reader = null;
    this._loaded = 0;
    this._filename = null;
    const source = stream2.source;
    this._withCredentials = source.withCredentials || false;
    this._contentLength = source.length;
    this._headersCapability = Promise.withResolvers();
    this._disableRange = source.disableRange || false;
    this._rangeChunkSize = source.rangeChunkSize;
    if (!this._rangeChunkSize && !this._disableRange) {
      this._disableRange = true;
    }
    this._abortController = new AbortController();
    this._isStreamingSupported = !source.disableStream;
    this._isRangeSupported = !source.disableRange;
    const headers = new Headers(stream2.headers);
    const url = source.url;
    fetch(url, createFetchOptions(headers, this._withCredentials, this._abortController)).then((response) => {
      stream2._responseOrigin = getResponseOrigin(response.url);
      if (!validateResponseStatus(response.status)) {
        throw createResponseError(response.status, url);
      }
      this._reader = response.body.getReader();
      this._headersCapability.resolve();
      const responseHeaders = response.headers;
      const {
        allowRangeRequests,
        suggestedLength
      } = validateRangeRequestCapabilities({
        responseHeaders,
        isHttp: stream2.isHttp,
        rangeChunkSize: this._rangeChunkSize,
        disableRange: this._disableRange
      });
      this._isRangeSupported = allowRangeRequests;
      this._contentLength = suggestedLength || this._contentLength;
      this._filename = extractFilenameFromHeader(responseHeaders);
      if (!this._isStreamingSupported && this._isRangeSupported) {
        this.cancel(new AbortException("Streaming is disabled."));
      }
    }).catch(this._headersCapability.reject);
    this.onProgress = null;
  }
  get headersReady() {
    return this._headersCapability.promise;
  }
  get filename() {
    return this._filename;
  }
  get contentLength() {
    return this._contentLength;
  }
  get isRangeSupported() {
    return this._isRangeSupported;
  }
  get isStreamingSupported() {
    return this._isStreamingSupported;
  }
  async read() {
    await this._headersCapability.promise;
    const {
      value,
      done
    } = await this._reader.read();
    if (done) {
      return {
        value,
        done
      };
    }
    this._loaded += value.byteLength;
    this.onProgress?.({
      loaded: this._loaded,
      total: this._contentLength
    });
    return {
      value: getArrayBuffer(value),
      done: false
    };
  }
  cancel(reason) {
    this._reader?.cancel(reason);
    this._abortController.abort();
  }
};
var PDFFetchStreamRangeReader = class {
  constructor(stream2, begin, end) {
    this._stream = stream2;
    this._reader = null;
    this._loaded = 0;
    const source = stream2.source;
    this._withCredentials = source.withCredentials || false;
    this._readCapability = Promise.withResolvers();
    this._isStreamingSupported = !source.disableStream;
    this._abortController = new AbortController();
    const headers = new Headers(stream2.headers);
    headers.append("Range", `bytes=${begin}-${end - 1}`);
    const url = source.url;
    fetch(url, createFetchOptions(headers, this._withCredentials, this._abortController)).then((response) => {
      const responseOrigin = getResponseOrigin(response.url);
      if (responseOrigin !== stream2._responseOrigin) {
        throw new Error(`Expected range response-origin "${responseOrigin}" to match "${stream2._responseOrigin}".`);
      }
      if (!validateResponseStatus(response.status)) {
        throw createResponseError(response.status, url);
      }
      this._readCapability.resolve();
      this._reader = response.body.getReader();
    }).catch(this._readCapability.reject);
    this.onProgress = null;
  }
  get isStreamingSupported() {
    return this._isStreamingSupported;
  }
  async read() {
    await this._readCapability.promise;
    const {
      value,
      done
    } = await this._reader.read();
    if (done) {
      return {
        value,
        done
      };
    }
    this._loaded += value.byteLength;
    this.onProgress?.({
      loaded: this._loaded
    });
    return {
      value: getArrayBuffer(value),
      done: false
    };
  }
  cancel(reason) {
    this._reader?.cancel(reason);
    this._abortController.abort();
  }
};
var OK_RESPONSE = 200;
var PARTIAL_CONTENT_RESPONSE = 206;
function network_getArrayBuffer(xhr) {
  const data = xhr.response;
  if (typeof data !== "string") {
    return data;
  }
  return stringToBytes(data).buffer;
}
var NetworkManager = class {
  _responseOrigin = null;
  constructor({
    url,
    httpHeaders,
    withCredentials
  }) {
    this.url = url;
    this.isHttp = /^https?:/i.test(url);
    this.headers = createHeaders(this.isHttp, httpHeaders);
    this.withCredentials = withCredentials || false;
    this.currXhrId = 0;
    this.pendingRequests = /* @__PURE__ */ Object.create(null);
  }
  request(args) {
    const xhr = new XMLHttpRequest();
    const xhrId = this.currXhrId++;
    const pendingRequest = this.pendingRequests[xhrId] = {
      xhr
    };
    xhr.open("GET", this.url);
    xhr.withCredentials = this.withCredentials;
    for (const [key, val2] of this.headers) {
      xhr.setRequestHeader(key, val2);
    }
    if (this.isHttp && "begin" in args && "end" in args) {
      xhr.setRequestHeader("Range", `bytes=${args.begin}-${args.end - 1}`);
      pendingRequest.expectedStatus = PARTIAL_CONTENT_RESPONSE;
    } else {
      pendingRequest.expectedStatus = OK_RESPONSE;
    }
    xhr.responseType = "arraybuffer";
    assert(args.onError, "Expected `onError` callback to be provided.");
    xhr.onerror = () => {
      args.onError(xhr.status);
    };
    xhr.onreadystatechange = this.onStateChange.bind(this, xhrId);
    xhr.onprogress = this.onProgress.bind(this, xhrId);
    pendingRequest.onHeadersReceived = args.onHeadersReceived;
    pendingRequest.onDone = args.onDone;
    pendingRequest.onError = args.onError;
    pendingRequest.onProgress = args.onProgress;
    xhr.send(null);
    return xhrId;
  }
  onProgress(xhrId, evt) {
    const pendingRequest = this.pendingRequests[xhrId];
    if (!pendingRequest) {
      return;
    }
    pendingRequest.onProgress?.(evt);
  }
  onStateChange(xhrId, evt) {
    const pendingRequest = this.pendingRequests[xhrId];
    if (!pendingRequest) {
      return;
    }
    const xhr = pendingRequest.xhr;
    if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) {
      pendingRequest.onHeadersReceived();
      delete pendingRequest.onHeadersReceived;
    }
    if (xhr.readyState !== 4) {
      return;
    }
    if (!(xhrId in this.pendingRequests)) {
      return;
    }
    delete this.pendingRequests[xhrId];
    if (xhr.status === 0 && this.isHttp) {
      pendingRequest.onError(xhr.status);
      return;
    }
    const xhrStatus = xhr.status || OK_RESPONSE;
    const ok_response_on_range_request = xhrStatus === OK_RESPONSE && pendingRequest.expectedStatus === PARTIAL_CONTENT_RESPONSE;
    if (!ok_response_on_range_request && xhrStatus !== pendingRequest.expectedStatus) {
      pendingRequest.onError(xhr.status);
      return;
    }
    const chunk = network_getArrayBuffer(xhr);
    if (xhrStatus === PARTIAL_CONTENT_RESPONSE) {
      const rangeHeader = xhr.getResponseHeader("Content-Range");
      const matches = /bytes (\d+)-(\d+)\/(\d+)/.exec(rangeHeader);
      if (matches) {
        pendingRequest.onDone({
          begin: parseInt(matches[1], 10),
          chunk
        });
      } else {
        warn(`Missing or invalid "Content-Range" header.`);
        pendingRequest.onError(0);
      }
    } else if (chunk) {
      pendingRequest.onDone({
        begin: 0,
        chunk
      });
    } else {
      pendingRequest.onError(xhr.status);
    }
  }
  getRequestXhr(xhrId) {
    return this.pendingRequests[xhrId].xhr;
  }
  isPendingRequest(xhrId) {
    return xhrId in this.pendingRequests;
  }
  abortRequest(xhrId) {
    const xhr = this.pendingRequests[xhrId].xhr;
    delete this.pendingRequests[xhrId];
    xhr.abort();
  }
};
var PDFNetworkStream = class {
  constructor(source) {
    this._source = source;
    this._manager = new NetworkManager(source);
    this._rangeChunkSize = source.rangeChunkSize;
    this._fullRequestReader = null;
    this._rangeRequestReaders = [];
  }
  _onRangeRequestReaderClosed(reader) {
    const i7 = this._rangeRequestReaders.indexOf(reader);
    if (i7 >= 0) {
      this._rangeRequestReaders.splice(i7, 1);
    }
  }
  getFullReader() {
    assert(!this._fullRequestReader, "PDFNetworkStream.getFullReader can only be called once.");
    this._fullRequestReader = new PDFNetworkStreamFullRequestReader(this._manager, this._source);
    return this._fullRequestReader;
  }
  getRangeReader(begin, end) {
    const reader = new PDFNetworkStreamRangeRequestReader(this._manager, begin, end);
    reader.onClosed = this._onRangeRequestReaderClosed.bind(this);
    this._rangeRequestReaders.push(reader);
    return reader;
  }
  cancelAllRequests(reason) {
    this._fullRequestReader?.cancel(reason);
    for (const reader of this._rangeRequestReaders.slice(0)) {
      reader.cancel(reason);
    }
  }
};
var PDFNetworkStreamFullRequestReader = class {
  constructor(manager, source) {
    this._manager = manager;
    this._url = source.url;
    this._fullRequestId = manager.request({
      onHeadersReceived: this._onHeadersReceived.bind(this),
      onDone: this._onDone.bind(this),
      onError: this._onError.bind(this),
      onProgress: this._onProgress.bind(this)
    });
    this._headersCapability = Promise.withResolvers();
    this._disableRange = source.disableRange || false;
    this._contentLength = source.length;
    this._rangeChunkSize = source.rangeChunkSize;
    if (!this._rangeChunkSize && !this._disableRange) {
      this._disableRange = true;
    }
    this._isStreamingSupported = false;
    this._isRangeSupported = false;
    this._cachedChunks = [];
    this._requests = [];
    this._done = false;
    this._storedError = void 0;
    this._filename = null;
    this.onProgress = null;
  }
  _onHeadersReceived() {
    const fullRequestXhrId = this._fullRequestId;
    const fullRequestXhr = this._manager.getRequestXhr(fullRequestXhrId);
    this._manager._responseOrigin = getResponseOrigin(fullRequestXhr.responseURL);
    const rawResponseHeaders = fullRequestXhr.getAllResponseHeaders();
    const responseHeaders = new Headers(rawResponseHeaders ? rawResponseHeaders.trimStart().replace(/[^\S ]+$/, "").split(/[\r\n]+/).map((x2) => {
      const [key, ...val2] = x2.split(": ");
      return [key, val2.join(": ")];
    }) : []);
    const {
      allowRangeRequests,
      suggestedLength
    } = validateRangeRequestCapabilities({
      responseHeaders,
      isHttp: this._manager.isHttp,
      rangeChunkSize: this._rangeChunkSize,
      disableRange: this._disableRange
    });
    if (allowRangeRequests) {
      this._isRangeSupported = true;
    }
    this._contentLength = suggestedLength || this._contentLength;
    this._filename = extractFilenameFromHeader(responseHeaders);
    if (this._isRangeSupported) {
      this._manager.abortRequest(fullRequestXhrId);
    }
    this._headersCapability.resolve();
  }
  _onDone(data) {
    if (data) {
      if (this._requests.length > 0) {
        const requestCapability = this._requests.shift();
        requestCapability.resolve({
          value: data.chunk,
          done: false
        });
      } else {
        this._cachedChunks.push(data.chunk);
      }
    }
    this._done = true;
    if (this._cachedChunks.length > 0) {
      return;
    }
    for (const requestCapability of this._requests) {
      requestCapability.resolve({
        value: void 0,
        done: true
      });
    }
    this._requests.length = 0;
  }
  _onError(status) {
    this._storedError = createResponseError(status, this._url);
    this._headersCapability.reject(this._storedError);
    for (const requestCapability of this._requests) {
      requestCapability.reject(this._storedError);
    }
    this._requests.length = 0;
    this._cachedChunks.length = 0;
  }
  _onProgress(evt) {
    this.onProgress?.({
      loaded: evt.loaded,
      total: evt.lengthComputable ? evt.total : this._contentLength
    });
  }
  get filename() {
    return this._filename;
  }
  get isRangeSupported() {
    return this._isRangeSupported;
  }
  get isStreamingSupported() {
    return this._isStreamingSupported;
  }
  get contentLength() {
    return this._contentLength;
  }
  get headersReady() {
    return this._headersCapability.promise;
  }
  async read() {
    await this._headersCapability.promise;
    if (this._storedError) {
      throw this._storedError;
    }
    if (this._cachedChunks.length > 0) {
      const chunk = this._cachedChunks.shift();
      return {
        value: chunk,
        done: false
      };
    }
    if (this._done) {
      return {
        value: void 0,
        done: true
      };
    }
    const requestCapability = Promise.withResolvers();
    this._requests.push(requestCapability);
    return requestCapability.promise;
  }
  cancel(reason) {
    this._done = true;
    this._headersCapability.reject(reason);
    for (const requestCapability of this._requests) {
      requestCapability.resolve({
        value: void 0,
        done: true
      });
    }
    this._requests.length = 0;
    if (this._manager.isPendingRequest(this._fullRequestId)) {
      this._manager.abortRequest(this._fullRequestId);
    }
    this._fullRequestReader = null;
  }
};
var PDFNetworkStreamRangeRequestReader = class {
  constructor(manager, begin, end) {
    this._manager = manager;
    this._url = manager.url;
    this._requestId = manager.request({
      begin,
      end,
      onHeadersReceived: this._onHeadersReceived.bind(this),
      onDone: this._onDone.bind(this),
      onError: this._onError.bind(this),
      onProgress: this._onProgress.bind(this)
    });
    this._requests = [];
    this._queuedChunk = null;
    this._done = false;
    this._storedError = void 0;
    this.onProgress = null;
    this.onClosed = null;
  }
  _onHeadersReceived() {
    const responseOrigin = getResponseOrigin(this._manager.getRequestXhr(this._requestId)?.responseURL);
    if (responseOrigin !== this._manager._responseOrigin) {
      this._storedError = new Error(`Expected range response-origin "${responseOrigin}" to match "${this._manager._responseOrigin}".`);
      this._onError(0);
    }
  }
  _close() {
    this.onClosed?.(this);
  }
  _onDone(data) {
    const chunk = data.chunk;
    if (this._requests.length > 0) {
      const requestCapability = this._requests.shift();
      requestCapability.resolve({
        value: chunk,
        done: false
      });
    } else {
      this._queuedChunk = chunk;
    }
    this._done = true;
    for (const requestCapability of this._requests) {
      requestCapability.resolve({
        value: void 0,
        done: true
      });
    }
    this._requests.length = 0;
    this._close();
  }
  _onError(status) {
    this._storedError ??= createResponseError(status, this._url);
    for (const requestCapability of this._requests) {
      requestCapability.reject(this._storedError);
    }
    this._requests.length = 0;
    this._queuedChunk = null;
  }
  _onProgress(evt) {
    if (!this.isStreamingSupported) {
      this.onProgress?.({
        loaded: evt.loaded
      });
    }
  }
  get isStreamingSupported() {
    return false;
  }
  async read() {
    if (this._storedError) {
      throw this._storedError;
    }
    if (this._queuedChunk !== null) {
      const chunk = this._queuedChunk;
      this._queuedChunk = null;
      return {
        value: chunk,
        done: false
      };
    }
    if (this._done) {
      return {
        value: void 0,
        done: true
      };
    }
    const requestCapability = Promise.withResolvers();
    this._requests.push(requestCapability);
    return requestCapability.promise;
  }
  cancel(reason) {
    this._done = true;
    for (const requestCapability of this._requests) {
      requestCapability.resolve({
        value: void 0,
        done: true
      });
    }
    this._requests.length = 0;
    if (this._manager.isPendingRequest(this._requestId)) {
      this._manager.abortRequest(this._requestId);
    }
    this._close();
  }
};
var urlRegex = /^[a-z][a-z0-9\-+.]+:/i;
function parseUrlOrPath(sourceUrl) {
  if (urlRegex.test(sourceUrl)) {
    return new URL(sourceUrl);
  }
  const url = process.getBuiltinModule("url");
  return new URL(url.pathToFileURL(sourceUrl));
}
var PDFNodeStream = class {
  constructor(source) {
    this.source = source;
    this.url = parseUrlOrPath(source.url);
    assert(this.url.protocol === "file:", "PDFNodeStream only supports file:// URLs.");
    this._fullRequestReader = null;
    this._rangeRequestReaders = [];
  }
  get _progressiveDataLength() {
    return this._fullRequestReader?._loaded ?? 0;
  }
  getFullReader() {
    assert(!this._fullRequestReader, "PDFNodeStream.getFullReader can only be called once.");
    this._fullRequestReader = new PDFNodeStreamFsFullReader(this);
    return this._fullRequestReader;
  }
  getRangeReader(start, end) {
    if (end <= this._progressiveDataLength) {
      return null;
    }
    const rangeReader = new PDFNodeStreamFsRangeReader(this, start, end);
    this._rangeRequestReaders.push(rangeReader);
    return rangeReader;
  }
  cancelAllRequests(reason) {
    this._fullRequestReader?.cancel(reason);
    for (const reader of this._rangeRequestReaders.slice(0)) {
      reader.cancel(reason);
    }
  }
};
var PDFNodeStreamFsFullReader = class {
  constructor(stream2) {
    this._url = stream2.url;
    this._done = false;
    this._storedError = null;
    this.onProgress = null;
    const source = stream2.source;
    this._contentLength = source.length;
    this._loaded = 0;
    this._filename = null;
    this._disableRange = source.disableRange || false;
    this._rangeChunkSize = source.rangeChunkSize;
    if (!this._rangeChunkSize && !this._disableRange) {
      this._disableRange = true;
    }
    this._isStreamingSupported = !source.disableStream;
    this._isRangeSupported = !source.disableRange;
    this._readableStream = null;
    this._readCapability = Promise.withResolvers();
    this._headersCapability = Promise.withResolvers();
    const fs = process.getBuiltinModule("fs");
    fs.promises.lstat(this._url).then((stat) => {
      this._contentLength = stat.size;
      this._setReadableStream(fs.createReadStream(this._url));
      this._headersCapability.resolve();
    }, (error) => {
      if (error.code === "ENOENT") {
        error = createResponseError(0, this._url.href);
      }
      this._storedError = error;
      this._headersCapability.reject(error);
    });
  }
  get headersReady() {
    return this._headersCapability.promise;
  }
  get filename() {
    return this._filename;
  }
  get contentLength() {
    return this._contentLength;
  }
  get isRangeSupported() {
    return this._isRangeSupported;
  }
  get isStreamingSupported() {
    return this._isStreamingSupported;
  }
  async read() {
    await this._readCapability.promise;
    if (this._done) {
      return {
        value: void 0,
        done: true
      };
    }
    if (this._storedError) {
      throw this._storedError;
    }
    const chunk = this._readableStream.read();
    if (chunk === null) {
      this._readCapability = Promise.withResolvers();
      return this.read();
    }
    this._loaded += chunk.length;
    this.onProgress?.({
      loaded: this._loaded,
      total: this._contentLength
    });
    const buffer = new Uint8Array(chunk).buffer;
    return {
      value: buffer,
      done: false
    };
  }
  cancel(reason) {
    if (!this._readableStream) {
      this._error(reason);
      return;
    }
    this._readableStream.destroy(reason);
  }
  _error(reason) {
    this._storedError = reason;
    this._readCapability.resolve();
  }
  _setReadableStream(readableStream) {
    this._readableStream = readableStream;
    readableStream.on("readable", () => {
      this._readCapability.resolve();
    });
    readableStream.on("end", () => {
      readableStream.destroy();
      this._done = true;
      this._readCapability.resolve();
    });
    readableStream.on("error", (reason) => {
      this._error(reason);
    });
    if (!this._isStreamingSupported && this._isRangeSupported) {
      this._error(new AbortException("streaming is disabled"));
    }
    if (this._storedError) {
      this._readableStream.destroy(this._storedError);
    }
  }
};
var PDFNodeStreamFsRangeReader = class {
  constructor(stream2, start, end) {
    this._url = stream2.url;
    this._done = false;
    this._storedError = null;
    this.onProgress = null;
    this._loaded = 0;
    this._readableStream = null;
    this._readCapability = Promise.withResolvers();
    const source = stream2.source;
    this._isStreamingSupported = !source.disableStream;
    const fs = process.getBuiltinModule("fs");
    this._setReadableStream(fs.createReadStream(this._url, {
      start,
      end: end - 1
    }));
  }
  get isStreamingSupported() {
    return this._isStreamingSupported;
  }
  async read() {
    await this._readCapability.promise;
    if (this._done) {
      return {
        value: void 0,
        done: true
      };
    }
    if (this._storedError) {
      throw this._storedError;
    }
    const chunk = this._readableStream.read();
    if (chunk === null) {
      this._readCapability = Promise.withResolvers();
      return this.read();
    }
    this._loaded += chunk.length;
    this.onProgress?.({
      loaded: this._loaded
    });
    const buffer = new Uint8Array(chunk).buffer;
    return {
      value: buffer,
      done: false
    };
  }
  cancel(reason) {
    if (!this._readableStream) {
      this._error(reason);
      return;
    }
    this._readableStream.destroy(reason);
  }
  _error(reason) {
    this._storedError = reason;
    this._readCapability.resolve();
  }
  _setReadableStream(readableStream) {
    this._readableStream = readableStream;
    readableStream.on("readable", () => {
      this._readCapability.resolve();
    });
    readableStream.on("end", () => {
      readableStream.destroy();
      this._done = true;
      this._readCapability.resolve();
    });
    readableStream.on("error", (reason) => {
      this._error(reason);
    });
    if (this._storedError) {
      this._readableStream.destroy(this._storedError);
    }
  }
};
var INITIAL_DATA = Symbol("INITIAL_DATA");
var PDFObjects = class {
  #objs = /* @__PURE__ */ Object.create(null);
  #ensureObj(objId) {
    return this.#objs[objId] ||= {
      ...Promise.withResolvers(),
      data: INITIAL_DATA
    };
  }
  get(objId, callback = null) {
    if (callback) {
      const obj2 = this.#ensureObj(objId);
      obj2.promise.then(() => callback(obj2.data));
      return null;
    }
    const obj = this.#objs[objId];
    if (!obj || obj.data === INITIAL_DATA) {
      throw new Error(`Requesting object that isn't resolved yet ${objId}.`);
    }
    return obj.data;
  }
  has(objId) {
    const obj = this.#objs[objId];
    return !!obj && obj.data !== INITIAL_DATA;
  }
  delete(objId) {
    const obj = this.#objs[objId];
    if (!obj || obj.data === INITIAL_DATA) {
      return false;
    }
    delete this.#objs[objId];
    return true;
  }
  resolve(objId, data = null) {
    const obj = this.#ensureObj(objId);
    obj.data = data;
    obj.resolve();
  }
  clear() {
    for (const objId in this.#objs) {
      const {
        data
      } = this.#objs[objId];
      data?.bitmap?.close();
    }
    this.#objs = /* @__PURE__ */ Object.create(null);
  }
  *[Symbol.iterator]() {
    for (const objId in this.#objs) {
      const {
        data
      } = this.#objs[objId];
      if (data === INITIAL_DATA) {
        continue;
      }
      yield [objId, data];
    }
  }
};
var MAX_TEXT_DIVS_TO_RENDER = 1e5;
var DEFAULT_FONT_SIZE = 30;
var TextLayer = class _TextLayer {
  #capability = Promise.withResolvers();
  #container = null;
  #disableProcessItems = false;
  #fontInspectorEnabled = !!globalThis.FontInspector?.enabled;
  #lang = null;
  #layoutTextParams = null;
  #pageHeight = 0;
  #pageWidth = 0;
  #reader = null;
  #rootContainer = null;
  #rotation = 0;
  #scale = 0;
  #styleCache = /* @__PURE__ */ Object.create(null);
  #textContentItemsStr = [];
  #textContentSource = null;
  #textDivs = [];
  #textDivProperties = /* @__PURE__ */ new WeakMap();
  #transform = null;
  static #ascentCache = /* @__PURE__ */ new Map();
  static #canvasContexts = /* @__PURE__ */ new Map();
  static #canvasCtxFonts = /* @__PURE__ */ new WeakMap();
  static #minFontSize = null;
  static #pendingTextLayers = /* @__PURE__ */ new Set();
  constructor({
    textContentSource,
    container,
    viewport
  }) {
    if (textContentSource instanceof ReadableStream) {
      this.#textContentSource = textContentSource;
    } else if (typeof textContentSource === "object") {
      this.#textContentSource = new ReadableStream({
        start(controller) {
          controller.enqueue(textContentSource);
          controller.close();
        }
      });
    } else {
      throw new Error('No "textContentSource" parameter specified.');
    }
    this.#container = this.#rootContainer = container;
    this.#scale = viewport.scale * OutputScale.pixelRatio;
    this.#rotation = viewport.rotation;
    this.#layoutTextParams = {
      div: null,
      properties: null,
      ctx: null
    };
    const {
      pageWidth,
      pageHeight,
      pageX,
      pageY
    } = viewport.rawDims;
    this.#transform = [1, 0, 0, -1, -pageX, pageY + pageHeight];
    this.#pageWidth = pageWidth;
    this.#pageHeight = pageHeight;
    _TextLayer.#ensureMinFontSizeComputed();
    setLayerDimensions(container, viewport);
    this.#capability.promise.finally(() => {
      _TextLayer.#pendingTextLayers.delete(this);
      this.#layoutTextParams = null;
      this.#styleCache = null;
    }).catch(() => {
    });
  }
  static get fontFamilyMap() {
    const {
      isWindows,
      isFirefox
    } = util_FeatureTest.platform;
    return shadow(this, "fontFamilyMap", /* @__PURE__ */ new Map([["sans-serif", `${isWindows && isFirefox ? "Calibri, " : ""}sans-serif`], ["monospace", `${isWindows && isFirefox ? "Lucida Console, " : ""}monospace`]]));
  }
  render() {
    const pump = () => {
      this.#reader.read().then(({
        value,
        done
      }) => {
        if (done) {
          this.#capability.resolve();
          return;
        }
        this.#lang ??= value.lang;
        Object.assign(this.#styleCache, value.styles);
        this.#processItems(value.items);
        pump();
      }, this.#capability.reject);
    };
    this.#reader = this.#textContentSource.getReader();
    _TextLayer.#pendingTextLayers.add(this);
    pump();
    return this.#capability.promise;
  }
  update({
    viewport,
    onBefore = null
  }) {
    const scale = viewport.scale * OutputScale.pixelRatio;
    const rotation = viewport.rotation;
    if (rotation !== this.#rotation) {
      onBefore?.();
      this.#rotation = rotation;
      setLayerDimensions(this.#rootContainer, {
        rotation
      });
    }
    if (scale !== this.#scale) {
      onBefore?.();
      this.#scale = scale;
      const params = {
        div: null,
        properties: null,
        ctx: _TextLayer.#getCtx(this.#lang)
      };
      for (const div of this.#textDivs) {
        params.properties = this.#textDivProperties.get(div);
        params.div = div;
        this.#layout(params);
      }
    }
  }
  cancel() {
    const abortEx = new AbortException("TextLayer task cancelled.");
    this.#reader?.cancel(abortEx).catch(() => {
    });
    this.#reader = null;
    this.#capability.reject(abortEx);
  }
  get textDivs() {
    return this.#textDivs;
  }
  get textContentItemsStr() {
    return this.#textContentItemsStr;
  }
  #processItems(items) {
    if (this.#disableProcessItems) {
      return;
    }
    this.#layoutTextParams.ctx ??= _TextLayer.#getCtx(this.#lang);
    const textDivs = this.#textDivs, textContentItemsStr = this.#textContentItemsStr;
    for (const item of items) {
      if (textDivs.length > MAX_TEXT_DIVS_TO_RENDER) {
        warn("Ignoring additional textDivs for performance reasons.");
        this.#disableProcessItems = true;
        return;
      }
      if (item.str === void 0) {
        if (item.type === "beginMarkedContentProps" || item.type === "beginMarkedContent") {
          const parent = this.#container;
          this.#container = document.createElement("span");
          this.#container.classList.add("markedContent");
          if (item.id) {
            this.#container.setAttribute("id", `${item.id}`);
          }
          parent.append(this.#container);
        } else if (item.type === "endMarkedContent") {
          this.#container = this.#container.parentNode;
        }
        continue;
      }
      textContentItemsStr.push(item.str);
      this.#appendText(item);
    }
  }
  #appendText(geom) {
    const textDiv = document.createElement("span");
    const textDivProperties = {
      angle: 0,
      canvasWidth: 0,
      hasText: geom.str !== "",
      hasEOL: geom.hasEOL,
      fontSize: 0
    };
    this.#textDivs.push(textDiv);
    const tx = Util.transform(this.#transform, geom.transform);
    let angle = Math.atan2(tx[1], tx[0]);
    const style = this.#styleCache[geom.fontName];
    if (style.vertical) {
      angle += Math.PI / 2;
    }
    let fontFamily = this.#fontInspectorEnabled && style.fontSubstitution || style.fontFamily;
    fontFamily = _TextLayer.fontFamilyMap.get(fontFamily) || fontFamily;
    const fontHeight = Math.hypot(tx[2], tx[3]);
    const fontAscent = fontHeight * _TextLayer.#getAscent(fontFamily, style, this.#lang);
    let left, top;
    if (angle === 0) {
      left = tx[4];
      top = tx[5] - fontAscent;
    } else {
      left = tx[4] + fontAscent * Math.sin(angle);
      top = tx[5] - fontAscent * Math.cos(angle);
    }
    const scaleFactorStr = "calc(var(--total-scale-factor) *";
    const divStyle = textDiv.style;
    if (this.#container === this.#rootContainer) {
      divStyle.left = `${(100 * left / this.#pageWidth).toFixed(2)}%`;
      divStyle.top = `${(100 * top / this.#pageHeight).toFixed(2)}%`;
    } else {
      divStyle.left = `${scaleFactorStr}${left.toFixed(2)}px)`;
      divStyle.top = `${scaleFactorStr}${top.toFixed(2)}px)`;
    }
    divStyle.fontSize = `${scaleFactorStr}${(_TextLayer.#minFontSize * fontHeight).toFixed(2)}px)`;
    divStyle.fontFamily = fontFamily;
    textDivProperties.fontSize = fontHeight;
    textDiv.setAttribute("role", "presentation");
    textDiv.textContent = geom.str;
    textDiv.dir = geom.dir;
    if (this.#fontInspectorEnabled) {
      textDiv.dataset.fontName = style.fontSubstitutionLoadedName || geom.fontName;
    }
    if (angle !== 0) {
      textDivProperties.angle = angle * (180 / Math.PI);
    }
    let shouldScaleText = false;
    if (geom.str.length > 1) {
      shouldScaleText = true;
    } else if (geom.str !== " " && geom.transform[0] !== geom.transform[3]) {
      const absScaleX = Math.abs(geom.transform[0]), absScaleY = Math.abs(geom.transform[3]);
      if (absScaleX !== absScaleY && Math.max(absScaleX, absScaleY) / Math.min(absScaleX, absScaleY) > 1.5) {
        shouldScaleText = true;
      }
    }
    if (shouldScaleText) {
      textDivProperties.canvasWidth = style.vertical ? geom.height : geom.width;
    }
    this.#textDivProperties.set(textDiv, textDivProperties);
    this.#layoutTextParams.div = textDiv;
    this.#layoutTextParams.properties = textDivProperties;
    this.#layout(this.#layoutTextParams);
    if (textDivProperties.hasText) {
      this.#container.append(textDiv);
    }
    if (textDivProperties.hasEOL) {
      const br = document.createElement("br");
      br.setAttribute("role", "presentation");
      this.#container.append(br);
    }
  }
  #layout(params) {
    const {
      div,
      properties,
      ctx
    } = params;
    const {
      style
    } = div;
    let transform = "";
    if (_TextLayer.#minFontSize > 1) {
      transform = `scale(${1 / _TextLayer.#minFontSize})`;
    }
    if (properties.canvasWidth !== 0 && properties.hasText) {
      const {
        fontFamily
      } = style;
      const {
        canvasWidth,
        fontSize
      } = properties;
      _TextLayer.#ensureCtxFont(ctx, fontSize * this.#scale, fontFamily);
      const {
        width
      } = ctx.measureText(div.textContent);
      if (width > 0) {
        transform = `scaleX(${canvasWidth * this.#scale / width}) ${transform}`;
      }
    }
    if (properties.angle !== 0) {
      transform = `rotate(${properties.angle}deg) ${transform}`;
    }
    if (transform.length > 0) {
      style.transform = transform;
    }
  }
  static cleanup() {
    if (this.#pendingTextLayers.size > 0) {
      return;
    }
    this.#ascentCache.clear();
    for (const {
      canvas
    } of this.#canvasContexts.values()) {
      canvas.remove();
    }
    this.#canvasContexts.clear();
  }
  static #getCtx(lang = null) {
    let ctx = this.#canvasContexts.get(lang ||= "");
    if (!ctx) {
      const canvas = document.createElement("canvas");
      canvas.className = "hiddenCanvasElement";
      canvas.lang = lang;
      document.body.append(canvas);
      ctx = canvas.getContext("2d", {
        alpha: false,
        willReadFrequently: true
      });
      this.#canvasContexts.set(lang, ctx);
      this.#canvasCtxFonts.set(ctx, {
        size: 0,
        family: ""
      });
    }
    return ctx;
  }
  static #ensureCtxFont(ctx, size, family) {
    const cached = this.#canvasCtxFonts.get(ctx);
    if (size === cached.size && family === cached.family) {
      return;
    }
    ctx.font = `${size}px ${family}`;
    cached.size = size;
    cached.family = family;
  }
  static #ensureMinFontSizeComputed() {
    if (this.#minFontSize !== null) {
      return;
    }
    const div = document.createElement("div");
    div.style.opacity = 0;
    div.style.lineHeight = 1;
    div.style.fontSize = "1px";
    div.style.position = "absolute";
    div.textContent = "X";
    document.body.append(div);
    this.#minFontSize = div.getBoundingClientRect().height;
    div.remove();
  }
  static #getAscent(fontFamily, style, lang) {
    const cachedAscent = this.#ascentCache.get(fontFamily);
    if (cachedAscent) {
      return cachedAscent;
    }
    const ctx = this.#getCtx(lang);
    ctx.canvas.width = ctx.canvas.height = DEFAULT_FONT_SIZE;
    this.#ensureCtxFont(ctx, DEFAULT_FONT_SIZE, fontFamily);
    const metrics = ctx.measureText("");
    const ascent = metrics.fontBoundingBoxAscent;
    const descent = Math.abs(metrics.fontBoundingBoxDescent);
    ctx.canvas.width = ctx.canvas.height = 0;
    let ratio = 0.8;
    if (ascent) {
      ratio = ascent / (ascent + descent);
    } else {
      if (util_FeatureTest.platform.isFirefox) {
        warn("Enable the `dom.textMetrics.fontBoundingBox.enabled` preference in `about:config` to improve TextLayer rendering.");
      }
      if (style.ascent) {
        ratio = style.ascent;
      } else if (style.descent) {
        ratio = 1 + style.descent;
      }
    }
    this.#ascentCache.set(fontFamily, ratio);
    return ratio;
  }
};
var RENDERING_CANCELLED_TIMEOUT = 100;
function getDocument(src = {}) {
  if (typeof src === "string" || src instanceof URL) {
    src = {
      url: src
    };
  } else if (src instanceof ArrayBuffer || ArrayBuffer.isView(src)) {
    src = {
      data: src
    };
  }
  const task = new PDFDocumentLoadingTask();
  const {
    docId
  } = task;
  const url = src.url ? getUrlProp(src.url) : null;
  const data = src.data ? getDataProp(src.data) : null;
  const httpHeaders = src.httpHeaders || null;
  const withCredentials = src.withCredentials === true;
  const password = src.password ?? null;
  const rangeTransport = src.range instanceof PDFDataRangeTransport ? src.range : null;
  const rangeChunkSize = Number.isInteger(src.rangeChunkSize) && src.rangeChunkSize > 0 ? src.rangeChunkSize : 2 ** 16;
  let worker = src.worker instanceof PDFWorker ? src.worker : null;
  const verbosity2 = src.verbosity;
  const docBaseUrl = typeof src.docBaseUrl === "string" && !isDataScheme(src.docBaseUrl) ? src.docBaseUrl : null;
  const cMapUrl = getFactoryUrlProp(src.cMapUrl);
  const cMapPacked = src.cMapPacked !== false;
  const CMapReaderFactory = src.CMapReaderFactory || (isNodeJS ? NodeCMapReaderFactory : DOMCMapReaderFactory);
  const iccUrl = getFactoryUrlProp(src.iccUrl);
  const standardFontDataUrl = getFactoryUrlProp(src.standardFontDataUrl);
  const StandardFontDataFactory = src.StandardFontDataFactory || (isNodeJS ? NodeStandardFontDataFactory : DOMStandardFontDataFactory);
  const wasmUrl = getFactoryUrlProp(src.wasmUrl);
  const WasmFactory = src.WasmFactory || (isNodeJS ? NodeWasmFactory : DOMWasmFactory);
  const ignoreErrors = src.stopAtErrors !== true;
  const maxImageSize = Number.isInteger(src.maxImageSize) && src.maxImageSize > -1 ? src.maxImageSize : -1;
  const isEvalSupported2 = src.isEvalSupported !== false;
  const isOffscreenCanvasSupported = typeof src.isOffscreenCanvasSupported === "boolean" ? src.isOffscreenCanvasSupported : !isNodeJS;
  const isImageDecoderSupported = typeof src.isImageDecoderSupported === "boolean" ? src.isImageDecoderSupported : !isNodeJS && (util_FeatureTest.platform.isFirefox || !globalThis.chrome);
  const canvasMaxAreaInBytes = Number.isInteger(src.canvasMaxAreaInBytes) ? src.canvasMaxAreaInBytes : -1;
  const disableFontFace = typeof src.disableFontFace === "boolean" ? src.disableFontFace : isNodeJS;
  const fontExtraProperties = src.fontExtraProperties === true;
  const enableXfa = src.enableXfa === true;
  const ownerDocument = src.ownerDocument || globalThis.document;
  const disableRange = src.disableRange === true;
  const disableStream = src.disableStream === true;
  const disableAutoFetch = src.disableAutoFetch === true;
  const pdfBug = src.pdfBug === true;
  const CanvasFactory = src.CanvasFactory || (isNodeJS ? NodeCanvasFactory : DOMCanvasFactory);
  const FilterFactory = src.FilterFactory || (isNodeJS ? NodeFilterFactory : DOMFilterFactory);
  const enableHWA = src.enableHWA === true;
  const useWasm = src.useWasm !== false;
  const length = rangeTransport ? rangeTransport.length : src.length ?? NaN;
  const useSystemFonts = typeof src.useSystemFonts === "boolean" ? src.useSystemFonts : !isNodeJS && !disableFontFace;
  const useWorkerFetch = typeof src.useWorkerFetch === "boolean" ? src.useWorkerFetch : !!(CMapReaderFactory === DOMCMapReaderFactory && StandardFontDataFactory === DOMStandardFontDataFactory && WasmFactory === DOMWasmFactory && cMapUrl && standardFontDataUrl && wasmUrl && isValidFetchUrl(cMapUrl, document.baseURI) && isValidFetchUrl(standardFontDataUrl, document.baseURI) && isValidFetchUrl(wasmUrl, document.baseURI));
  const styleElement = null;
  setVerbosityLevel(verbosity2);
  const transportFactory = {
    canvasFactory: new CanvasFactory({
      ownerDocument,
      enableHWA
    }),
    filterFactory: new FilterFactory({
      docId,
      ownerDocument
    }),
    cMapReaderFactory: useWorkerFetch ? null : new CMapReaderFactory({
      baseUrl: cMapUrl,
      isCompressed: cMapPacked
    }),
    standardFontDataFactory: useWorkerFetch ? null : new StandardFontDataFactory({
      baseUrl: standardFontDataUrl
    }),
    wasmFactory: useWorkerFetch ? null : new WasmFactory({
      baseUrl: wasmUrl
    })
  };
  if (!worker) {
    worker = PDFWorker.create({
      verbosity: verbosity2,
      port: GlobalWorkerOptions.workerPort
    });
    task._worker = worker;
  }
  const docParams = {
    docId,
    apiVersion: "5.4.394",
    data,
    password,
    disableAutoFetch,
    rangeChunkSize,
    length,
    docBaseUrl,
    enableXfa,
    evaluatorOptions: {
      maxImageSize,
      disableFontFace,
      ignoreErrors,
      isEvalSupported: isEvalSupported2,
      isOffscreenCanvasSupported,
      isImageDecoderSupported,
      canvasMaxAreaInBytes,
      fontExtraProperties,
      useSystemFonts,
      useWasm,
      useWorkerFetch,
      cMapUrl,
      iccUrl,
      standardFontDataUrl,
      wasmUrl
    }
  };
  const transportParams = {
    ownerDocument,
    pdfBug,
    styleElement,
    loadingParams: {
      disableAutoFetch,
      enableXfa
    }
  };
  worker.promise.then(function() {
    if (task.destroyed) {
      throw new Error("Loading aborted");
    }
    if (worker.destroyed) {
      throw new Error("Worker was destroyed");
    }
    const workerIdPromise = worker.messageHandler.sendWithPromise("GetDocRequest", docParams, data ? [data.buffer] : null);
    let networkStream;
    if (rangeTransport) {
      networkStream = new PDFDataTransportStream(rangeTransport, {
        disableRange,
        disableStream
      });
    } else if (!data) {
      if (!url) {
        throw new Error("getDocument - no `url` parameter provided.");
      }
      const NetworkStream = isValidFetchUrl(url) ? PDFFetchStream : isNodeJS ? PDFNodeStream : PDFNetworkStream;
      networkStream = new NetworkStream({
        url,
        length,
        httpHeaders,
        withCredentials,
        rangeChunkSize,
        disableRange,
        disableStream
      });
    }
    return workerIdPromise.then((workerId) => {
      if (task.destroyed) {
        throw new Error("Loading aborted");
      }
      if (worker.destroyed) {
        throw new Error("Worker was destroyed");
      }
      const messageHandler = new MessageHandler(docId, workerId, worker.port);
      const transport = new WorkerTransport(messageHandler, task, networkStream, transportParams, transportFactory, enableHWA);
      task._transport = transport;
      messageHandler.send("Ready", null);
    });
  }).catch(task._capability.reject);
  return task;
}
var PDFDocumentLoadingTask = class _PDFDocumentLoadingTask {
  static #docId = 0;
  _capability = Promise.withResolvers();
  _transport = null;
  _worker = null;
  docId = `d${_PDFDocumentLoadingTask.#docId++}`;
  destroyed = false;
  onPassword = null;
  onProgress = null;
  get promise() {
    return this._capability.promise;
  }
  async destroy() {
    this.destroyed = true;
    try {
      if (this._worker?.port) {
        this._worker._pendingDestroy = true;
      }
      await this._transport?.destroy();
    } catch (ex) {
      if (this._worker?.port) {
        delete this._worker._pendingDestroy;
      }
      throw ex;
    }
    this._transport = null;
    this._worker?.destroy();
    this._worker = null;
  }
  async getData() {
    return this._transport.getData();
  }
};
var PDFDataRangeTransport = class {
  #capability = Promise.withResolvers();
  #progressiveDoneListeners = [];
  #progressiveReadListeners = [];
  #progressListeners = [];
  #rangeListeners = [];
  constructor(length, initialData, progressiveDone = false, contentDispositionFilename = null) {
    this.length = length;
    this.initialData = initialData;
    this.progressiveDone = progressiveDone;
    this.contentDispositionFilename = contentDispositionFilename;
  }
  addRangeListener(listener) {
    this.#rangeListeners.push(listener);
  }
  addProgressListener(listener) {
    this.#progressListeners.push(listener);
  }
  addProgressiveReadListener(listener) {
    this.#progressiveReadListeners.push(listener);
  }
  addProgressiveDoneListener(listener) {
    this.#progressiveDoneListeners.push(listener);
  }
  onDataRange(begin, chunk) {
    for (const listener of this.#rangeListeners) {
      listener(begin, chunk);
    }
  }
  onDataProgress(loaded, total) {
    this.#capability.promise.then(() => {
      for (const listener of this.#progressListeners) {
        listener(loaded, total);
      }
    });
  }
  onDataProgressiveRead(chunk) {
    this.#capability.promise.then(() => {
      for (const listener of this.#progressiveReadListeners) {
        listener(chunk);
      }
    });
  }
  onDataProgressiveDone() {
    this.#capability.promise.then(() => {
      for (const listener of this.#progressiveDoneListeners) {
        listener();
      }
    });
  }
  transportReady() {
    this.#capability.resolve();
  }
  requestDataRange(begin, end) {
    unreachable("Abstract method PDFDataRangeTransport.requestDataRange");
  }
  abort() {
  }
};
var PDFDocumentProxy = class {
  constructor(pdfInfo, transport) {
    this._pdfInfo = pdfInfo;
    this._transport = transport;
  }
  get annotationStorage() {
    return this._transport.annotationStorage;
  }
  get canvasFactory() {
    return this._transport.canvasFactory;
  }
  get filterFactory() {
    return this._transport.filterFactory;
  }
  get numPages() {
    return this._pdfInfo.numPages;
  }
  get fingerprints() {
    return this._pdfInfo.fingerprints;
  }
  get isPureXfa() {
    return shadow(this, "isPureXfa", !!this._transport._htmlForXfa);
  }
  get allXfaHtml() {
    return this._transport._htmlForXfa;
  }
  getPage(pageNumber) {
    return this._transport.getPage(pageNumber);
  }
  getPageIndex(ref) {
    return this._transport.getPageIndex(ref);
  }
  getDestinations() {
    return this._transport.getDestinations();
  }
  getDestination(id) {
    return this._transport.getDestination(id);
  }
  getPageLabels() {
    return this._transport.getPageLabels();
  }
  getPageLayout() {
    return this._transport.getPageLayout();
  }
  getPageMode() {
    return this._transport.getPageMode();
  }
  getViewerPreferences() {
    return this._transport.getViewerPreferences();
  }
  getOpenAction() {
    return this._transport.getOpenAction();
  }
  getAttachments() {
    return this._transport.getAttachments();
  }
  getAnnotationsByType(types2, pageIndexesToSkip) {
    return this._transport.getAnnotationsByType(types2, pageIndexesToSkip);
  }
  getJSActions() {
    return this._transport.getDocJSActions();
  }
  getOutline() {
    return this._transport.getOutline();
  }
  getOptionalContentConfig({
    intent = "display"
  } = {}) {
    const {
      renderingIntent
    } = this._transport.getRenderingIntent(intent);
    return this._transport.getOptionalContentConfig(renderingIntent);
  }
  getPermissions() {
    return this._transport.getPermissions();
  }
  getMetadata() {
    return this._transport.getMetadata();
  }
  getMarkInfo() {
    return this._transport.getMarkInfo();
  }
  getData() {
    return this._transport.getData();
  }
  saveDocument() {
    return this._transport.saveDocument();
  }
  getDownloadInfo() {
    return this._transport.downloadInfoCapability.promise;
  }
  cleanup(keepLoadedFonts = false) {
    return this._transport.startCleanup(keepLoadedFonts || this.isPureXfa);
  }
  destroy() {
    return this.loadingTask.destroy();
  }
  cachedPageNumber(ref) {
    return this._transport.cachedPageNumber(ref);
  }
  get loadingParams() {
    return this._transport.loadingParams;
  }
  get loadingTask() {
    return this._transport.loadingTask;
  }
  getFieldObjects() {
    return this._transport.getFieldObjects();
  }
  hasJSActions() {
    return this._transport.hasJSActions();
  }
  getCalculationOrderIds() {
    return this._transport.getCalculationOrderIds();
  }
};
var PDFPageProxy = class {
  #pendingCleanup = false;
  constructor(pageIndex, pageInfo, transport, pdfBug = false) {
    this._pageIndex = pageIndex;
    this._pageInfo = pageInfo;
    this._transport = transport;
    this._stats = pdfBug ? new StatTimer() : null;
    this._pdfBug = pdfBug;
    this.commonObjs = transport.commonObjs;
    this.objs = new PDFObjects();
    this._intentStates = /* @__PURE__ */ new Map();
    this.destroyed = false;
    this.recordedBBoxes = null;
  }
  get pageNumber() {
    return this._pageIndex + 1;
  }
  get rotate() {
    return this._pageInfo.rotate;
  }
  get ref() {
    return this._pageInfo.ref;
  }
  get userUnit() {
    return this._pageInfo.userUnit;
  }
  get view() {
    return this._pageInfo.view;
  }
  getViewport({
    scale,
    rotation = this.rotate,
    offsetX = 0,
    offsetY = 0,
    dontFlip = false
  } = {}) {
    return new PageViewport({
      viewBox: this.view,
      userUnit: this.userUnit,
      scale,
      rotation,
      offsetX,
      offsetY,
      dontFlip
    });
  }
  getAnnotations({
    intent = "display"
  } = {}) {
    const {
      renderingIntent
    } = this._transport.getRenderingIntent(intent);
    return this._transport.getAnnotations(this._pageIndex, renderingIntent);
  }
  getJSActions() {
    return this._transport.getPageJSActions(this._pageIndex);
  }
  get filterFactory() {
    return this._transport.filterFactory;
  }
  get isPureXfa() {
    return shadow(this, "isPureXfa", !!this._transport._htmlForXfa);
  }
  async getXfa() {
    return this._transport._htmlForXfa?.children[this._pageIndex] || null;
  }
  render({
    canvasContext,
    canvas = canvasContext.canvas,
    viewport,
    intent = "display",
    annotationMode = AnnotationMode.ENABLE,
    transform = null,
    background = null,
    optionalContentConfigPromise = null,
    annotationCanvasMap = null,
    pageColors = null,
    printAnnotationStorage = null,
    isEditing = false,
    recordOperations = false,
    operationsFilter = null
  }) {
    this._stats?.time("Overall");
    const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage, isEditing);
    const {
      renderingIntent,
      cacheKey
    } = intentArgs;
    this.#pendingCleanup = false;
    optionalContentConfigPromise ||= this._transport.getOptionalContentConfig(renderingIntent);
    let intentState = this._intentStates.get(cacheKey);
    if (!intentState) {
      intentState = /* @__PURE__ */ Object.create(null);
      this._intentStates.set(cacheKey, intentState);
    }
    if (intentState.streamReaderCancelTimeout) {
      clearTimeout(intentState.streamReaderCancelTimeout);
      intentState.streamReaderCancelTimeout = null;
    }
    const intentPrint = !!(renderingIntent & RenderingIntentFlag.PRINT);
    if (!intentState.displayReadyCapability) {
      intentState.displayReadyCapability = Promise.withResolvers();
      intentState.operatorList = {
        fnArray: [],
        argsArray: [],
        lastChunk: false,
        separateAnnots: null
      };
      this._stats?.time("Page Request");
      this._pumpOperatorList(intentArgs);
    }
    const recordForDebugger = Boolean(this._pdfBug && globalThis.StepperManager?.enabled);
    const shouldRecordOperations = !this.recordedBBoxes && (recordOperations || recordForDebugger);
    const complete2 = (error) => {
      intentState.renderTasks.delete(internalRenderTask);
      if (shouldRecordOperations) {
        const recordedBBoxes = internalRenderTask.gfx?.dependencyTracker.take();
        if (recordedBBoxes) {
          if (internalRenderTask.stepper) {
            internalRenderTask.stepper.setOperatorBBoxes(recordedBBoxes, internalRenderTask.gfx.dependencyTracker.takeDebugMetadata());
          }
          if (recordOperations) {
            this.recordedBBoxes = recordedBBoxes;
          }
        }
      }
      if (intentPrint) {
        this.#pendingCleanup = true;
      }
      this.#tryCleanup();
      if (error) {
        internalRenderTask.capability.reject(error);
        this._abortOperatorList({
          intentState,
          reason: error instanceof Error ? error : new Error(error)
        });
      } else {
        internalRenderTask.capability.resolve();
      }
      if (this._stats) {
        this._stats.timeEnd("Rendering");
        this._stats.timeEnd("Overall");
        if (globalThis.Stats?.enabled) {
          globalThis.Stats.add(this.pageNumber, this._stats);
        }
      }
    };
    const internalRenderTask = new InternalRenderTask({
      callback: complete2,
      params: {
        canvas,
        canvasContext,
        dependencyTracker: shouldRecordOperations ? new CanvasDependencyTracker(canvas, intentState.operatorList.length, recordForDebugger) : null,
        viewport,
        transform,
        background
      },
      objs: this.objs,
      commonObjs: this.commonObjs,
      annotationCanvasMap,
      operatorList: intentState.operatorList,
      pageIndex: this._pageIndex,
      canvasFactory: this._transport.canvasFactory,
      filterFactory: this._transport.filterFactory,
      useRequestAnimationFrame: !intentPrint,
      pdfBug: this._pdfBug,
      pageColors,
      enableHWA: this._transport.enableHWA,
      operationsFilter
    });
    (intentState.renderTasks ||= /* @__PURE__ */ new Set()).add(internalRenderTask);
    const renderTask = internalRenderTask.task;
    Promise.all([intentState.displayReadyCapability.promise, optionalContentConfigPromise]).then(([transparency, optionalContentConfig]) => {
      if (this.destroyed) {
        complete2();
        return;
      }
      this._stats?.time("Rendering");
      if (!(optionalContentConfig.renderingIntent & renderingIntent)) {
        throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");
      }
      internalRenderTask.initializeGraphics({
        transparency,
        optionalContentConfig
      });
      internalRenderTask.operatorListChanged();
    }).catch(complete2);
    return renderTask;
  }
  getOperatorList({
    intent = "display",
    annotationMode = AnnotationMode.ENABLE,
    printAnnotationStorage = null,
    isEditing = false
  } = {}) {
    function operatorListChanged() {
      if (intentState.operatorList.lastChunk) {
        intentState.opListReadCapability.resolve(intentState.operatorList);
        intentState.renderTasks.delete(opListTask);
      }
    }
    const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage, isEditing, true);
    let intentState = this._intentStates.get(intentArgs.cacheKey);
    if (!intentState) {
      intentState = /* @__PURE__ */ Object.create(null);
      this._intentStates.set(intentArgs.cacheKey, intentState);
    }
    let opListTask;
    if (!intentState.opListReadCapability) {
      opListTask = /* @__PURE__ */ Object.create(null);
      opListTask.operatorListChanged = operatorListChanged;
      intentState.opListReadCapability = Promise.withResolvers();
      (intentState.renderTasks ||= /* @__PURE__ */ new Set()).add(opListTask);
      intentState.operatorList = {
        fnArray: [],
        argsArray: [],
        lastChunk: false,
        separateAnnots: null
      };
      this._stats?.time("Page Request");
      this._pumpOperatorList(intentArgs);
    }
    return intentState.opListReadCapability.promise;
  }
  streamTextContent({
    includeMarkedContent = false,
    disableNormalization = false
  } = {}) {
    const TEXT_CONTENT_CHUNK_SIZE = 100;
    return this._transport.messageHandler.sendWithStream("GetTextContent", {
      pageIndex: this._pageIndex,
      includeMarkedContent: includeMarkedContent === true,
      disableNormalization: disableNormalization === true
    }, {
      highWaterMark: TEXT_CONTENT_CHUNK_SIZE,
      size(textContent) {
        return textContent.items.length;
      }
    });
  }
  getTextContent(params = {}) {
    if (this._transport._htmlForXfa) {
      return this.getXfa().then((xfa) => XfaText.textContent(xfa));
    }
    const readableStream = this.streamTextContent(params);
    return new Promise(function(resolve, reject) {
      function pump() {
        reader.read().then(function({
          value,
          done
        }) {
          if (done) {
            resolve(textContent);
            return;
          }
          textContent.lang ??= value.lang;
          Object.assign(textContent.styles, value.styles);
          textContent.items.push(...value.items);
          pump();
        }, reject);
      }
      const reader = readableStream.getReader();
      const textContent = {
        items: [],
        styles: /* @__PURE__ */ Object.create(null),
        lang: null
      };
      pump();
    });
  }
  getStructTree() {
    return this._transport.getStructTree(this._pageIndex);
  }
  _destroy() {
    this.destroyed = true;
    const waitOn = [];
    for (const intentState of this._intentStates.values()) {
      this._abortOperatorList({
        intentState,
        reason: new Error("Page was destroyed."),
        force: true
      });
      if (intentState.opListReadCapability) {
        continue;
      }
      for (const internalRenderTask of intentState.renderTasks) {
        waitOn.push(internalRenderTask.completed);
        internalRenderTask.cancel();
      }
    }
    this.objs.clear();
    this.#pendingCleanup = false;
    return Promise.all(waitOn);
  }
  cleanup(resetStats = false) {
    this.#pendingCleanup = true;
    const success = this.#tryCleanup();
    if (resetStats && success) {
      this._stats &&= new StatTimer();
    }
    return success;
  }
  #tryCleanup() {
    if (!this.#pendingCleanup || this.destroyed) {
      return false;
    }
    for (const {
      renderTasks,
      operatorList
    } of this._intentStates.values()) {
      if (renderTasks.size > 0 || !operatorList.lastChunk) {
        return false;
      }
    }
    this._intentStates.clear();
    this.objs.clear();
    this.#pendingCleanup = false;
    return true;
  }
  _startRenderPage(transparency, cacheKey) {
    const intentState = this._intentStates.get(cacheKey);
    if (!intentState) {
      return;
    }
    this._stats?.timeEnd("Page Request");
    intentState.displayReadyCapability?.resolve(transparency);
  }
  _renderPageChunk(operatorListChunk, intentState) {
    for (let i7 = 0, ii = operatorListChunk.length; i7 < ii; i7++) {
      intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i7]);
      intentState.operatorList.argsArray.push(operatorListChunk.argsArray[i7]);
    }
    intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
    intentState.operatorList.separateAnnots = operatorListChunk.separateAnnots;
    for (const internalRenderTask of intentState.renderTasks) {
      internalRenderTask.operatorListChanged();
    }
    if (operatorListChunk.lastChunk) {
      this.#tryCleanup();
    }
  }
  _pumpOperatorList({
    renderingIntent,
    cacheKey,
    annotationStorageSerializable,
    modifiedIds
  }) {
    const {
      map,
      transfer
    } = annotationStorageSerializable;
    const readableStream = this._transport.messageHandler.sendWithStream("GetOperatorList", {
      pageIndex: this._pageIndex,
      intent: renderingIntent,
      cacheKey,
      annotationStorage: map,
      modifiedIds
    }, transfer);
    const reader = readableStream.getReader();
    const intentState = this._intentStates.get(cacheKey);
    intentState.streamReader = reader;
    const pump = () => {
      reader.read().then(({
        value,
        done
      }) => {
        if (done) {
          intentState.streamReader = null;
          return;
        }
        if (this._transport.destroyed) {
          return;
        }
        this._renderPageChunk(value, intentState);
        pump();
      }, (reason) => {
        intentState.streamReader = null;
        if (this._transport.destroyed) {
          return;
        }
        if (intentState.operatorList) {
          intentState.operatorList.lastChunk = true;
          for (const internalRenderTask of intentState.renderTasks) {
            internalRenderTask.operatorListChanged();
          }
          this.#tryCleanup();
        }
        if (intentState.displayReadyCapability) {
          intentState.displayReadyCapability.reject(reason);
        } else if (intentState.opListReadCapability) {
          intentState.opListReadCapability.reject(reason);
        } else {
          throw reason;
        }
      });
    };
    pump();
  }
  _abortOperatorList({
    intentState,
    reason,
    force = false
  }) {
    if (!intentState.streamReader) {
      return;
    }
    if (intentState.streamReaderCancelTimeout) {
      clearTimeout(intentState.streamReaderCancelTimeout);
      intentState.streamReaderCancelTimeout = null;
    }
    if (!force) {
      if (intentState.renderTasks.size > 0) {
        return;
      }
      if (reason instanceof RenderingCancelledException) {
        let delay = RENDERING_CANCELLED_TIMEOUT;
        if (reason.extraDelay > 0 && reason.extraDelay < 1e3) {
          delay += reason.extraDelay;
        }
        intentState.streamReaderCancelTimeout = setTimeout(() => {
          intentState.streamReaderCancelTimeout = null;
          this._abortOperatorList({
            intentState,
            reason,
            force: true
          });
        }, delay);
        return;
      }
    }
    intentState.streamReader.cancel(new AbortException(reason.message)).catch(() => {
    });
    intentState.streamReader = null;
    if (this._transport.destroyed) {
      return;
    }
    for (const [curCacheKey, curIntentState] of this._intentStates) {
      if (curIntentState === intentState) {
        this._intentStates.delete(curCacheKey);
        break;
      }
    }
    this.cleanup();
  }
  get stats() {
    return this._stats;
  }
};
var PDFWorker = class _PDFWorker {
  #capability = Promise.withResolvers();
  #messageHandler = null;
  #port = null;
  #webWorker = null;
  static #fakeWorkerId = 0;
  static #isWorkerDisabled = false;
  static #workerPorts = /* @__PURE__ */ new WeakMap();
  static {
    if (isNodeJS) {
      this.#isWorkerDisabled = true;
      GlobalWorkerOptions.workerSrc ||= "./pdf.worker.mjs";
    }
    this._isSameOrigin = (baseUrl, otherUrl) => {
      const base = URL.parse(baseUrl);
      if (!base?.origin || base.origin === "null") {
        return false;
      }
      const other = new URL(otherUrl, base);
      return base.origin === other.origin;
    };
    this._createCDNWrapper = (url) => {
      const wrapper = `await import("${url}");`;
      return URL.createObjectURL(new Blob([wrapper], {
        type: "text/javascript"
      }));
    };
    this.fromPort = (params) => {
      deprecated("`PDFWorker.fromPort` - please use `PDFWorker.create` instead.");
      if (!params?.port) {
        throw new Error("PDFWorker.fromPort - invalid method signature.");
      }
      return this.create(params);
    };
  }
  constructor({
    name = null,
    port = null,
    verbosity: verbosity2 = getVerbosityLevel()
  } = {}) {
    this.name = name;
    this.destroyed = false;
    this.verbosity = verbosity2;
    if (port) {
      if (_PDFWorker.#workerPorts.has(port)) {
        throw new Error("Cannot use more than one PDFWorker per port.");
      }
      _PDFWorker.#workerPorts.set(port, this);
      this.#initializeFromPort(port);
    } else {
      this.#initialize();
    }
  }
  get promise() {
    return this.#capability.promise;
  }
  #resolve() {
    this.#capability.resolve();
    this.#messageHandler.send("configure", {
      verbosity: this.verbosity
    });
  }
  get port() {
    return this.#port;
  }
  get messageHandler() {
    return this.#messageHandler;
  }
  #initializeFromPort(port) {
    this.#port = port;
    this.#messageHandler = new MessageHandler("main", "worker", port);
    this.#messageHandler.on("ready", () => {
    });
    this.#resolve();
  }
  #initialize() {
    if (_PDFWorker.#isWorkerDisabled || _PDFWorker.#mainThreadWorkerMessageHandler) {
      this.#setupFakeWorker();
      return;
    }
    let {
      workerSrc
    } = _PDFWorker;
    try {
      if (!_PDFWorker._isSameOrigin(window.location, workerSrc)) {
        workerSrc = _PDFWorker._createCDNWrapper(new URL(workerSrc, window.location).href);
      }
      const worker = new Worker(workerSrc, {
        type: "module"
      });
      const messageHandler = new MessageHandler("main", "worker", worker);
      const terminateEarly = () => {
        ac.abort();
        messageHandler.destroy();
        worker.terminate();
        if (this.destroyed) {
          this.#capability.reject(new Error("Worker was destroyed"));
        } else {
          this.#setupFakeWorker();
        }
      };
      const ac = new AbortController();
      worker.addEventListener("error", () => {
        if (!this.#webWorker) {
          terminateEarly();
        }
      }, {
        signal: ac.signal
      });
      messageHandler.on("test", (data) => {
        ac.abort();
        if (this.destroyed || !data) {
          terminateEarly();
          return;
        }
        this.#messageHandler = messageHandler;
        this.#port = worker;
        this.#webWorker = worker;
        this.#resolve();
      });
      messageHandler.on("ready", (data) => {
        ac.abort();
        if (this.destroyed) {
          terminateEarly();
          return;
        }
        try {
          sendTest();
        } catch {
          this.#setupFakeWorker();
        }
      });
      const sendTest = () => {
        const testObj = new Uint8Array();
        messageHandler.send("test", testObj, [testObj.buffer]);
      };
      sendTest();
      return;
    } catch {
      info("The worker has been disabled.");
    }
    this.#setupFakeWorker();
  }
  #setupFakeWorker() {
    if (!_PDFWorker.#isWorkerDisabled) {
      warn("Setting up fake worker.");
      _PDFWorker.#isWorkerDisabled = true;
    }
    _PDFWorker._setupFakeWorkerGlobal.then((WorkerMessageHandler) => {
      if (this.destroyed) {
        this.#capability.reject(new Error("Worker was destroyed"));
        return;
      }
      const port = new LoopbackPort();
      this.#port = port;
      const id = `fake${_PDFWorker.#fakeWorkerId++}`;
      const workerHandler = new MessageHandler(id + "_worker", id, port);
      WorkerMessageHandler.setup(workerHandler, port);
      this.#messageHandler = new MessageHandler(id, id + "_worker", port);
      this.#resolve();
    }).catch((reason) => {
      this.#capability.reject(new Error(`Setting up fake worker failed: "${reason.message}".`));
    });
  }
  destroy() {
    this.destroyed = true;
    this.#webWorker?.terminate();
    this.#webWorker = null;
    _PDFWorker.#workerPorts.delete(this.#port);
    this.#port = null;
    this.#messageHandler?.destroy();
    this.#messageHandler = null;
  }
  static create(params) {
    const cachedPort = this.#workerPorts.get(params?.port);
    if (cachedPort) {
      if (cachedPort._pendingDestroy) {
        throw new Error("PDFWorker.create - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");
      }
      return cachedPort;
    }
    return new _PDFWorker(params);
  }
  static get workerSrc() {
    if (GlobalWorkerOptions.workerSrc) {
      return GlobalWorkerOptions.workerSrc;
    }
    throw new Error('No "GlobalWorkerOptions.workerSrc" specified.');
  }
  static get #mainThreadWorkerMessageHandler() {
    try {
      return globalThis.pdfjsWorker?.WorkerMessageHandler || null;
    } catch {
      return null;
    }
  }
  static get _setupFakeWorkerGlobal() {
    const loader = async () => {
      if (this.#mainThreadWorkerMessageHandler) {
        return this.#mainThreadWorkerMessageHandler;
      }
      const worker = await import(
        /*webpackIgnore: true*/
        /*@vite-ignore*/
        this.workerSrc
      );
      return worker.WorkerMessageHandler;
    };
    return shadow(this, "_setupFakeWorkerGlobal", loader());
  }
};
var WorkerTransport = class {
  #methodPromises = /* @__PURE__ */ new Map();
  #pageCache = /* @__PURE__ */ new Map();
  #pagePromises = /* @__PURE__ */ new Map();
  #pageRefCache = /* @__PURE__ */ new Map();
  #passwordCapability = null;
  constructor(messageHandler, loadingTask, networkStream, params, factory, enableHWA) {
    this.messageHandler = messageHandler;
    this.loadingTask = loadingTask;
    this.commonObjs = new PDFObjects();
    this.fontLoader = new FontLoader({
      ownerDocument: params.ownerDocument,
      styleElement: params.styleElement
    });
    this.loadingParams = params.loadingParams;
    this._params = params;
    this.canvasFactory = factory.canvasFactory;
    this.filterFactory = factory.filterFactory;
    this.cMapReaderFactory = factory.cMapReaderFactory;
    this.standardFontDataFactory = factory.standardFontDataFactory;
    this.wasmFactory = factory.wasmFactory;
    this.destroyed = false;
    this.destroyCapability = null;
    this._networkStream = networkStream;
    this._fullReader = null;
    this._lastProgress = null;
    this.downloadInfoCapability = Promise.withResolvers();
    this.enableHWA = enableHWA;
    this.setupMessageHandler();
  }
  #cacheSimpleMethod(name, data = null) {
    const cachedPromise = this.#methodPromises.get(name);
    if (cachedPromise) {
      return cachedPromise;
    }
    const promise = this.messageHandler.sendWithPromise(name, data);
    this.#methodPromises.set(name, promise);
    return promise;
  }
  get annotationStorage() {
    return shadow(this, "annotationStorage", new AnnotationStorage());
  }
  getRenderingIntent(intent, annotationMode = AnnotationMode.ENABLE, printAnnotationStorage = null, isEditing = false, isOpList = false) {
    let renderingIntent = RenderingIntentFlag.DISPLAY;
    let annotationStorageSerializable = SerializableEmpty;
    switch (intent) {
      case "any":
        renderingIntent = RenderingIntentFlag.ANY;
        break;
      case "display":
        break;
      case "print":
        renderingIntent = RenderingIntentFlag.PRINT;
        break;
      default:
        warn(`getRenderingIntent - invalid intent: ${intent}`);
    }
    const annotationStorage = renderingIntent & RenderingIntentFlag.PRINT && printAnnotationStorage instanceof PrintAnnotationStorage ? printAnnotationStorage : this.annotationStorage;
    switch (annotationMode) {
      case AnnotationMode.DISABLE:
        renderingIntent += RenderingIntentFlag.ANNOTATIONS_DISABLE;
        break;
      case AnnotationMode.ENABLE:
        break;
      case AnnotationMode.ENABLE_FORMS:
        renderingIntent += RenderingIntentFlag.ANNOTATIONS_FORMS;
        break;
      case AnnotationMode.ENABLE_STORAGE:
        renderingIntent += RenderingIntentFlag.ANNOTATIONS_STORAGE;
        annotationStorageSerializable = annotationStorage.serializable;
        break;
      default:
        warn(`getRenderingIntent - invalid annotationMode: ${annotationMode}`);
    }
    if (isEditing) {
      renderingIntent += RenderingIntentFlag.IS_EDITING;
    }
    if (isOpList) {
      renderingIntent += RenderingIntentFlag.OPLIST;
    }
    const {
      ids: modifiedIds,
      hash: modifiedIdsHash
    } = annotationStorage.modifiedIds;
    const cacheKeyBuf = [renderingIntent, annotationStorageSerializable.hash, modifiedIdsHash];
    return {
      renderingIntent,
      cacheKey: cacheKeyBuf.join("_"),
      annotationStorageSerializable,
      modifiedIds
    };
  }
  destroy() {
    if (this.destroyCapability) {
      return this.destroyCapability.promise;
    }
    this.destroyed = true;
    this.destroyCapability = Promise.withResolvers();
    this.#passwordCapability?.reject(new Error("Worker was destroyed during onPassword callback"));
    const waitOn = [];
    for (const page of this.#pageCache.values()) {
      waitOn.push(page._destroy());
    }
    this.#pageCache.clear();
    this.#pagePromises.clear();
    this.#pageRefCache.clear();
    if (this.hasOwnProperty("annotationStorage")) {
      this.annotationStorage.resetModified();
    }
    const terminated = this.messageHandler.sendWithPromise("Terminate", null);
    waitOn.push(terminated);
    Promise.all(waitOn).then(() => {
      this.commonObjs.clear();
      this.fontLoader.clear();
      this.#methodPromises.clear();
      this.filterFactory.destroy();
      TextLayer.cleanup();
      this._networkStream?.cancelAllRequests(new AbortException("Worker was terminated."));
      this.messageHandler?.destroy();
      this.messageHandler = null;
      this.destroyCapability.resolve();
    }, this.destroyCapability.reject);
    return this.destroyCapability.promise;
  }
  setupMessageHandler() {
    const {
      messageHandler,
      loadingTask
    } = this;
    messageHandler.on("GetReader", (data, sink) => {
      assert(this._networkStream, "GetReader - no `IPDFStream` instance available.");
      this._fullReader = this._networkStream.getFullReader();
      this._fullReader.onProgress = (evt) => {
        this._lastProgress = {
          loaded: evt.loaded,
          total: evt.total
        };
      };
      sink.onPull = () => {
        this._fullReader.read().then(function({
          value,
          done
        }) {
          if (done) {
            sink.close();
            return;
          }
          assert(value instanceof ArrayBuffer, "GetReader - expected an ArrayBuffer.");
          sink.enqueue(new Uint8Array(value), 1, [value]);
        }).catch((reason) => {
          sink.error(reason);
        });
      };
      sink.onCancel = (reason) => {
        this._fullReader.cancel(reason);
        sink.ready.catch((readyReason) => {
          if (this.destroyed) {
            return;
          }
          throw readyReason;
        });
      };
    });
    messageHandler.on("ReaderHeadersReady", async (data) => {
      await this._fullReader.headersReady;
      const {
        isStreamingSupported,
        isRangeSupported,
        contentLength
      } = this._fullReader;
      if (!isStreamingSupported || !isRangeSupported) {
        if (this._lastProgress) {
          loadingTask.onProgress?.(this._lastProgress);
        }
        this._fullReader.onProgress = (evt) => {
          loadingTask.onProgress?.({
            loaded: evt.loaded,
            total: evt.total
          });
        };
      }
      return {
        isStreamingSupported,
        isRangeSupported,
        contentLength
      };
    });
    messageHandler.on("GetRangeReader", (data, sink) => {
      assert(this._networkStream, "GetRangeReader - no `IPDFStream` instance available.");
      const rangeReader = this._networkStream.getRangeReader(data.begin, data.end);
      if (!rangeReader) {
        sink.close();
        return;
      }
      sink.onPull = () => {
        rangeReader.read().then(function({
          value,
          done
        }) {
          if (done) {
            sink.close();
            return;
          }
          assert(value instanceof ArrayBuffer, "GetRangeReader - expected an ArrayBuffer.");
          sink.enqueue(new Uint8Array(value), 1, [value]);
        }).catch((reason) => {
          sink.error(reason);
        });
      };
      sink.onCancel = (reason) => {
        rangeReader.cancel(reason);
        sink.ready.catch((readyReason) => {
          if (this.destroyed) {
            return;
          }
          throw readyReason;
        });
      };
    });
    messageHandler.on("GetDoc", ({
      pdfInfo
    }) => {
      this._numPages = pdfInfo.numPages;
      this._htmlForXfa = pdfInfo.htmlForXfa;
      delete pdfInfo.htmlForXfa;
      loadingTask._capability.resolve(new PDFDocumentProxy(pdfInfo, this));
    });
    messageHandler.on("DocException", (ex) => {
      loadingTask._capability.reject(wrapReason(ex));
    });
    messageHandler.on("PasswordRequest", (ex) => {
      this.#passwordCapability = Promise.withResolvers();
      try {
        if (!loadingTask.onPassword) {
          throw wrapReason(ex);
        }
        const updatePassword = (password) => {
          if (password instanceof Error) {
            this.#passwordCapability.reject(password);
          } else {
            this.#passwordCapability.resolve({
              password
            });
          }
        };
        loadingTask.onPassword(updatePassword, ex.code);
      } catch (err) {
        this.#passwordCapability.reject(err);
      }
      return this.#passwordCapability.promise;
    });
    messageHandler.on("DataLoaded", (data) => {
      loadingTask.onProgress?.({
        loaded: data.length,
        total: data.length
      });
      this.downloadInfoCapability.resolve(data);
    });
    messageHandler.on("StartRenderPage", (data) => {
      if (this.destroyed) {
        return;
      }
      const page = this.#pageCache.get(data.pageIndex);
      page._startRenderPage(data.transparency, data.cacheKey);
    });
    messageHandler.on("commonobj", ([id, type, exportedData]) => {
      if (this.destroyed) {
        return null;
      }
      if (this.commonObjs.has(id)) {
        return null;
      }
      switch (type) {
        case "Font":
          if ("error" in exportedData) {
            const exportedError = exportedData.error;
            warn(`Error during font loading: ${exportedError}`);
            this.commonObjs.resolve(id, exportedError);
            break;
          }
          const fontData = new FontInfo(exportedData);
          const inspectFont = this._params.pdfBug && globalThis.FontInspector?.enabled ? (font2, url) => globalThis.FontInspector.fontAdded(font2, url) : null;
          const font = new FontFaceObject(fontData, inspectFont, exportedData.extra, exportedData.charProcOperatorList);
          this.fontLoader.bind(font).catch(() => messageHandler.sendWithPromise("FontFallback", {
            id
          })).finally(() => {
            if (!font.fontExtraProperties && font.data) {
              font.clearData();
            }
            this.commonObjs.resolve(id, font);
          });
          break;
        case "CopyLocalImage":
          const {
            imageRef
          } = exportedData;
          assert(imageRef, "The imageRef must be defined.");
          for (const pageProxy of this.#pageCache.values()) {
            for (const [, data] of pageProxy.objs) {
              if (data?.ref !== imageRef) {
                continue;
              }
              if (!data.dataLen) {
                return null;
              }
              this.commonObjs.resolve(id, structuredClone(data));
              return data.dataLen;
            }
          }
          break;
        case "FontPath":
        case "Image":
          this.commonObjs.resolve(id, exportedData);
          break;
        case "Pattern":
          const pattern = new PatternInfo(exportedData);
          this.commonObjs.resolve(id, pattern.getIR());
          break;
        default:
          throw new Error(`Got unknown common object type ${type}`);
      }
      return null;
    });
    messageHandler.on("obj", ([id, pageIndex, type, imageData]) => {
      if (this.destroyed) {
        return;
      }
      const pageProxy = this.#pageCache.get(pageIndex);
      if (pageProxy.objs.has(id)) {
        return;
      }
      if (pageProxy._intentStates.size === 0) {
        imageData?.bitmap?.close();
        return;
      }
      switch (type) {
        case "Image":
        case "Pattern":
          pageProxy.objs.resolve(id, imageData);
          break;
        default:
          throw new Error(`Got unknown object type ${type}`);
      }
    });
    messageHandler.on("DocProgress", (data) => {
      if (this.destroyed) {
        return;
      }
      loadingTask.onProgress?.({
        loaded: data.loaded,
        total: data.total
      });
    });
    messageHandler.on("FetchBinaryData", async (data) => {
      if (this.destroyed) {
        throw new Error("Worker was destroyed.");
      }
      const factory = this[data.type];
      if (!factory) {
        throw new Error(`${data.type} not initialized, see the \`useWorkerFetch\` parameter.`);
      }
      return factory.fetch(data);
    });
  }
  getData() {
    return this.messageHandler.sendWithPromise("GetData", null);
  }
  saveDocument() {
    if (this.annotationStorage.size <= 0) {
      warn("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");
    }
    const {
      map,
      transfer
    } = this.annotationStorage.serializable;
    return this.messageHandler.sendWithPromise("SaveDocument", {
      isPureXfa: !!this._htmlForXfa,
      numPages: this._numPages,
      annotationStorage: map,
      filename: this._fullReader?.filename ?? null
    }, transfer).finally(() => {
      this.annotationStorage.resetModified();
    });
  }
  getPage(pageNumber) {
    if (!Number.isInteger(pageNumber) || pageNumber <= 0 || pageNumber > this._numPages) {
      return Promise.reject(new Error("Invalid page request."));
    }
    const pageIndex = pageNumber - 1, cachedPromise = this.#pagePromises.get(pageIndex);
    if (cachedPromise) {
      return cachedPromise;
    }
    const promise = this.messageHandler.sendWithPromise("GetPage", {
      pageIndex
    }).then((pageInfo) => {
      if (this.destroyed) {
        throw new Error("Transport destroyed");
      }
      if (pageInfo.refStr) {
        this.#pageRefCache.set(pageInfo.refStr, pageNumber);
      }
      const page = new PDFPageProxy(pageIndex, pageInfo, this, this._params.pdfBug);
      this.#pageCache.set(pageIndex, page);
      return page;
    });
    this.#pagePromises.set(pageIndex, promise);
    return promise;
  }
  getPageIndex(ref) {
    if (!isRefProxy(ref)) {
      return Promise.reject(new Error("Invalid pageIndex request."));
    }
    return this.messageHandler.sendWithPromise("GetPageIndex", {
      num: ref.num,
      gen: ref.gen
    });
  }
  getAnnotations(pageIndex, intent) {
    return this.messageHandler.sendWithPromise("GetAnnotations", {
      pageIndex,
      intent
    });
  }
  getFieldObjects() {
    return this.#cacheSimpleMethod("GetFieldObjects");
  }
  hasJSActions() {
    return this.#cacheSimpleMethod("HasJSActions");
  }
  getCalculationOrderIds() {
    return this.messageHandler.sendWithPromise("GetCalculationOrderIds", null);
  }
  getDestinations() {
    return this.messageHandler.sendWithPromise("GetDestinations", null);
  }
  getDestination(id) {
    if (typeof id !== "string") {
      return Promise.reject(new Error("Invalid destination request."));
    }
    return this.messageHandler.sendWithPromise("GetDestination", {
      id
    });
  }
  getPageLabels() {
    return this.messageHandler.sendWithPromise("GetPageLabels", null);
  }
  getPageLayout() {
    return this.messageHandler.sendWithPromise("GetPageLayout", null);
  }
  getPageMode() {
    return this.messageHandler.sendWithPromise("GetPageMode", null);
  }
  getViewerPreferences() {
    return this.messageHandler.sendWithPromise("GetViewerPreferences", null);
  }
  getOpenAction() {
    return this.messageHandler.sendWithPromise("GetOpenAction", null);
  }
  getAttachments() {
    return this.messageHandler.sendWithPromise("GetAttachments", null);
  }
  getAnnotationsByType(types2, pageIndexesToSkip) {
    return this.messageHandler.sendWithPromise("GetAnnotationsByType", {
      types: types2,
      pageIndexesToSkip
    });
  }
  getDocJSActions() {
    return this.#cacheSimpleMethod("GetDocJSActions");
  }
  getPageJSActions(pageIndex) {
    return this.messageHandler.sendWithPromise("GetPageJSActions", {
      pageIndex
    });
  }
  getStructTree(pageIndex) {
    return this.messageHandler.sendWithPromise("GetStructTree", {
      pageIndex
    });
  }
  getOutline() {
    return this.messageHandler.sendWithPromise("GetOutline", null);
  }
  getOptionalContentConfig(renderingIntent) {
    return this.#cacheSimpleMethod("GetOptionalContentConfig").then((data) => new OptionalContentConfig(data, renderingIntent));
  }
  getPermissions() {
    return this.messageHandler.sendWithPromise("GetPermissions", null);
  }
  getMetadata() {
    const name = "GetMetadata", cachedPromise = this.#methodPromises.get(name);
    if (cachedPromise) {
      return cachedPromise;
    }
    const promise = this.messageHandler.sendWithPromise(name, null).then((results) => ({
      info: results[0],
      metadata: results[1] ? new Metadata(results[1]) : null,
      contentDispositionFilename: this._fullReader?.filename ?? null,
      contentLength: this._fullReader?.contentLength ?? null
    }));
    this.#methodPromises.set(name, promise);
    return promise;
  }
  getMarkInfo() {
    return this.messageHandler.sendWithPromise("GetMarkInfo", null);
  }
  async startCleanup(keepLoadedFonts = false) {
    if (this.destroyed) {
      return;
    }
    await this.messageHandler.sendWithPromise("Cleanup", null);
    for (const page of this.#pageCache.values()) {
      const cleanupSuccessful = page.cleanup();
      if (!cleanupSuccessful) {
        throw new Error(`startCleanup: Page ${page.pageNumber} is currently rendering.`);
      }
    }
    this.commonObjs.clear();
    if (!keepLoadedFonts) {
      this.fontLoader.clear();
    }
    this.#methodPromises.clear();
    this.filterFactory.destroy(true);
    TextLayer.cleanup();
  }
  cachedPageNumber(ref) {
    if (!isRefProxy(ref)) {
      return null;
    }
    const refStr = ref.gen === 0 ? `${ref.num}R` : `${ref.num}R${ref.gen}`;
    return this.#pageRefCache.get(refStr) ?? null;
  }
};
var RenderTask = class {
  #internalRenderTask = null;
  onContinue = null;
  onError = null;
  constructor(internalRenderTask) {
    this.#internalRenderTask = internalRenderTask;
  }
  get promise() {
    return this.#internalRenderTask.capability.promise;
  }
  cancel(extraDelay = 0) {
    this.#internalRenderTask.cancel(null, extraDelay);
  }
  get separateAnnots() {
    const {
      separateAnnots
    } = this.#internalRenderTask.operatorList;
    if (!separateAnnots) {
      return false;
    }
    const {
      annotationCanvasMap
    } = this.#internalRenderTask;
    return separateAnnots.form || separateAnnots.canvas && annotationCanvasMap?.size > 0;
  }
};
var InternalRenderTask = class _InternalRenderTask {
  #rAF = null;
  static #canvasInUse = /* @__PURE__ */ new WeakSet();
  constructor({
    callback,
    params,
    objs,
    commonObjs,
    annotationCanvasMap,
    operatorList,
    pageIndex,
    canvasFactory,
    filterFactory,
    useRequestAnimationFrame = false,
    pdfBug = false,
    pageColors = null,
    enableHWA = false,
    operationsFilter = null
  }) {
    this.callback = callback;
    this.params = params;
    this.objs = objs;
    this.commonObjs = commonObjs;
    this.annotationCanvasMap = annotationCanvasMap;
    this.operatorListIdx = null;
    this.operatorList = operatorList;
    this._pageIndex = pageIndex;
    this.canvasFactory = canvasFactory;
    this.filterFactory = filterFactory;
    this._pdfBug = pdfBug;
    this.pageColors = pageColors;
    this.running = false;
    this.graphicsReadyCallback = null;
    this.graphicsReady = false;
    this._useRequestAnimationFrame = useRequestAnimationFrame === true && typeof window !== "undefined";
    this.cancelled = false;
    this.capability = Promise.withResolvers();
    this.task = new RenderTask(this);
    this._cancelBound = this.cancel.bind(this);
    this._continueBound = this._continue.bind(this);
    this._scheduleNextBound = this._scheduleNext.bind(this);
    this._nextBound = this._next.bind(this);
    this._canvas = params.canvas;
    this._canvasContext = params.canvas ? null : params.canvasContext;
    this._enableHWA = enableHWA;
    this._dependencyTracker = params.dependencyTracker;
    this._operationsFilter = operationsFilter;
  }
  get completed() {
    return this.capability.promise.catch(function() {
    });
  }
  initializeGraphics({
    transparency = false,
    optionalContentConfig
  }) {
    if (this.cancelled) {
      return;
    }
    if (this._canvas) {
      if (_InternalRenderTask.#canvasInUse.has(this._canvas)) {
        throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");
      }
      _InternalRenderTask.#canvasInUse.add(this._canvas);
    }
    if (this._pdfBug && globalThis.StepperManager?.enabled) {
      this.stepper = globalThis.StepperManager.create(this._pageIndex);
      this.stepper.init(this.operatorList);
      this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
    }
    const {
      viewport,
      transform,
      background,
      dependencyTracker
    } = this.params;
    const canvasContext = this._canvasContext || this._canvas.getContext("2d", {
      alpha: false,
      willReadFrequently: !this._enableHWA
    });
    this.gfx = new CanvasGraphics(canvasContext, this.commonObjs, this.objs, this.canvasFactory, this.filterFactory, {
      optionalContentConfig
    }, this.annotationCanvasMap, this.pageColors, dependencyTracker);
    this.gfx.beginDrawing({
      transform,
      viewport,
      transparency,
      background
    });
    this.operatorListIdx = 0;
    this.graphicsReady = true;
    this.graphicsReadyCallback?.();
  }
  cancel(error = null, extraDelay = 0) {
    this.running = false;
    this.cancelled = true;
    this.gfx?.endDrawing();
    if (this.#rAF) {
      window.cancelAnimationFrame(this.#rAF);
      this.#rAF = null;
    }
    _InternalRenderTask.#canvasInUse.delete(this._canvas);
    error ||= new RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex + 1}`, extraDelay);
    this.callback(error);
    this.task.onError?.(error);
  }
  operatorListChanged() {
    if (!this.graphicsReady) {
      this.graphicsReadyCallback ||= this._continueBound;
      return;
    }
    this.gfx.dependencyTracker?.growOperationsCount(this.operatorList.fnArray.length);
    this.stepper?.updateOperatorList(this.operatorList);
    if (this.running) {
      return;
    }
    this._continue();
  }
  _continue() {
    this.running = true;
    if (this.cancelled) {
      return;
    }
    if (this.task.onContinue) {
      this.task.onContinue(this._scheduleNextBound);
    } else {
      this._scheduleNext();
    }
  }
  _scheduleNext() {
    if (this._useRequestAnimationFrame) {
      this.#rAF = window.requestAnimationFrame(() => {
        this.#rAF = null;
        this._nextBound().catch(this._cancelBound);
      });
    } else {
      Promise.resolve().then(this._nextBound).catch(this._cancelBound);
    }
  }
  async _next() {
    if (this.cancelled) {
      return;
    }
    this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper, this._operationsFilter);
    if (this.operatorListIdx === this.operatorList.argsArray.length) {
      this.running = false;
      if (this.operatorList.lastChunk) {
        this.gfx.endDrawing();
        _InternalRenderTask.#canvasInUse.delete(this._canvas);
        this.callback();
      }
    }
  }
};
var version2 = "5.4.394";
var build = "2cc809ade";
var ColorPicker = class _ColorPicker {
  #button = null;
  #buttonSwatch = null;
  #defaultColor;
  #dropdown = null;
  #dropdownWasFromKeyboard = false;
  #isMainColorPicker = false;
  #editor = null;
  #eventBus;
  #openDropdownAC = null;
  #uiManager = null;
  static #l10nColor = null;
  static get _keyboardManager() {
    return shadow(this, "_keyboardManager", new KeyboardManager([[["Escape", "mac+Escape"], _ColorPicker.prototype._hideDropdownFromKeyboard], [[" ", "mac+ "], _ColorPicker.prototype._colorSelectFromKeyboard], [["ArrowDown", "ArrowRight", "mac+ArrowDown", "mac+ArrowRight"], _ColorPicker.prototype._moveToNext], [["ArrowUp", "ArrowLeft", "mac+ArrowUp", "mac+ArrowLeft"], _ColorPicker.prototype._moveToPrevious], [["Home", "mac+Home"], _ColorPicker.prototype._moveToBeginning], [["End", "mac+End"], _ColorPicker.prototype._moveToEnd]]));
  }
  constructor({
    editor = null,
    uiManager = null
  }) {
    if (editor) {
      this.#isMainColorPicker = false;
      this.#editor = editor;
    } else {
      this.#isMainColorPicker = true;
    }
    this.#uiManager = editor?._uiManager || uiManager;
    this.#eventBus = this.#uiManager._eventBus;
    this.#defaultColor = editor?.color?.toUpperCase() || this.#uiManager?.highlightColors.values().next().value || "#FFFF98";
    _ColorPicker.#l10nColor ||= Object.freeze({
      blue: "pdfjs-editor-colorpicker-blue",
      green: "pdfjs-editor-colorpicker-green",
      pink: "pdfjs-editor-colorpicker-pink",
      red: "pdfjs-editor-colorpicker-red",
      yellow: "pdfjs-editor-colorpicker-yellow"
    });
  }
  renderButton() {
    const button = this.#button = document.createElement("button");
    button.className = "colorPicker";
    button.tabIndex = "0";
    button.setAttribute("data-l10n-id", "pdfjs-editor-colorpicker-button");
    button.ariaHasPopup = "true";
    if (this.#editor) {
      button.ariaControls = `${this.#editor.id}_colorpicker_dropdown`;
    }
    const signal = this.#uiManager._signal;
    button.addEventListener("click", this.#openDropdown.bind(this), {
      signal
    });
    button.addEventListener("keydown", this.#keyDown.bind(this), {
      signal
    });
    const swatch = this.#buttonSwatch = document.createElement("span");
    swatch.className = "swatch";
    swatch.ariaHidden = "true";
    swatch.style.backgroundColor = this.#defaultColor;
    button.append(swatch);
    return button;
  }
  renderMainDropdown() {
    const dropdown = this.#dropdown = this.#getDropdownRoot();
    dropdown.ariaOrientation = "horizontal";
    dropdown.ariaLabelledBy = "highlightColorPickerLabel";
    return dropdown;
  }
  #getDropdownRoot() {
    const div = document.createElement("div");
    const signal = this.#uiManager._signal;
    div.addEventListener("contextmenu", noContextMenu, {
      signal
    });
    div.className = "dropdown";
    div.role = "listbox";
    div.ariaMultiSelectable = "false";
    div.ariaOrientation = "vertical";
    div.setAttribute("data-l10n-id", "pdfjs-editor-colorpicker-dropdown");
    if (this.#editor) {
      div.id = `${this.#editor.id}_colorpicker_dropdown`;
    }
    for (const [name, color] of this.#uiManager.highlightColors) {
      const button = document.createElement("button");
      button.tabIndex = "0";
      button.role = "option";
      button.setAttribute("data-color", color);
      button.title = name;
      button.setAttribute("data-l10n-id", _ColorPicker.#l10nColor[name]);
      const swatch = document.createElement("span");
      button.append(swatch);
      swatch.className = "swatch";
      swatch.style.backgroundColor = color;
      button.ariaSelected = color === this.#defaultColor;
      button.addEventListener("click", this.#colorSelect.bind(this, color), {
        signal
      });
      div.append(button);
    }
    div.addEventListener("keydown", this.#keyDown.bind(this), {
      signal
    });
    return div;
  }
  #colorSelect(color, event) {
    event.stopPropagation();
    this.#eventBus.dispatch("switchannotationeditorparams", {
      source: this,
      type: AnnotationEditorParamsType.HIGHLIGHT_COLOR,
      value: color
    });
    this.updateColor(color);
  }
  _colorSelectFromKeyboard(event) {
    if (event.target === this.#button) {
      this.#openDropdown(event);
      return;
    }
    const color = event.target.getAttribute("data-color");
    if (!color) {
      return;
    }
    this.#colorSelect(color, event);
  }
  _moveToNext(event) {
    if (!this.#isDropdownVisible) {
      this.#openDropdown(event);
      return;
    }
    if (event.target === this.#button) {
      this.#dropdown.firstChild?.focus();
      return;
    }
    event.target.nextSibling?.focus();
  }
  _moveToPrevious(event) {
    if (event.target === this.#dropdown?.firstChild || event.target === this.#button) {
      if (this.#isDropdownVisible) {
        this._hideDropdownFromKeyboard();
      }
      return;
    }
    if (!this.#isDropdownVisible) {
      this.#openDropdown(event);
    }
    event.target.previousSibling?.focus();
  }
  _moveToBeginning(event) {
    if (!this.#isDropdownVisible) {
      this.#openDropdown(event);
      return;
    }
    this.#dropdown.firstChild?.focus();
  }
  _moveToEnd(event) {
    if (!this.#isDropdownVisible) {
      this.#openDropdown(event);
      return;
    }
    this.#dropdown.lastChild?.focus();
  }
  #keyDown(event) {
    _ColorPicker._keyboardManager.exec(this, event);
  }
  #openDropdown(event) {
    if (this.#isDropdownVisible) {
      this.hideDropdown();
      return;
    }
    this.#dropdownWasFromKeyboard = event.detail === 0;
    if (!this.#openDropdownAC) {
      this.#openDropdownAC = new AbortController();
      window.addEventListener("pointerdown", this.#pointerDown.bind(this), {
        signal: this.#uiManager.combinedSignal(this.#openDropdownAC)
      });
    }
    this.#button.ariaExpanded = "true";
    if (this.#dropdown) {
      this.#dropdown.classList.remove("hidden");
      return;
    }
    const root = this.#dropdown = this.#getDropdownRoot();
    this.#button.append(root);
  }
  #pointerDown(event) {
    if (this.#dropdown?.contains(event.target)) {
      return;
    }
    this.hideDropdown();
  }
  hideDropdown() {
    this.#dropdown?.classList.add("hidden");
    this.#button.ariaExpanded = "false";
    this.#openDropdownAC?.abort();
    this.#openDropdownAC = null;
  }
  get #isDropdownVisible() {
    return this.#dropdown && !this.#dropdown.classList.contains("hidden");
  }
  _hideDropdownFromKeyboard() {
    if (this.#isMainColorPicker) {
      return;
    }
    if (!this.#isDropdownVisible) {
      this.#editor?.unselect();
      return;
    }
    this.hideDropdown();
    this.#button.focus({
      preventScroll: true,
      focusVisible: this.#dropdownWasFromKeyboard
    });
  }
  updateColor(color) {
    if (this.#buttonSwatch) {
      this.#buttonSwatch.style.backgroundColor = color;
    }
    if (!this.#dropdown) {
      return;
    }
    const i7 = this.#uiManager.highlightColors.values();
    for (const child of this.#dropdown.children) {
      child.ariaSelected = i7.next().value === color.toUpperCase();
    }
  }
  destroy() {
    this.#button?.remove();
    this.#button = null;
    this.#buttonSwatch = null;
    this.#dropdown?.remove();
    this.#dropdown = null;
  }
};
var BasicColorPicker = class _BasicColorPicker {
  #input = null;
  #editor = null;
  #uiManager = null;
  static #l10nColor = null;
  constructor(editor) {
    this.#editor = editor;
    this.#uiManager = editor._uiManager;
    _BasicColorPicker.#l10nColor ||= Object.freeze({
      freetext: "pdfjs-editor-color-picker-free-text-input",
      ink: "pdfjs-editor-color-picker-ink-input"
    });
  }
  renderButton() {
    if (this.#input) {
      return this.#input;
    }
    const {
      editorType,
      colorType,
      color
    } = this.#editor;
    const input = this.#input = document.createElement("input");
    input.type = "color";
    input.value = color || "#000000";
    input.className = "basicColorPicker";
    input.tabIndex = 0;
    input.setAttribute("data-l10n-id", _BasicColorPicker.#l10nColor[editorType]);
    input.addEventListener("input", () => {
      this.#uiManager.updateParams(colorType, input.value);
    }, {
      signal: this.#uiManager._signal
    });
    return input;
  }
  update(value) {
    if (!this.#input) {
      return;
    }
    this.#input.value = value;
  }
  destroy() {
    this.#input?.remove();
    this.#input = null;
  }
  hideDropdown() {
  }
};
function makeColorComp(n7) {
  return Math.floor(Math.max(0, Math.min(1, n7)) * 255).toString(16).padStart(2, "0");
}
function scaleAndClamp(x2) {
  return Math.max(0, Math.min(255, 255 * x2));
}
var ColorConverters = class {
  static CMYK_G([c6, y4, m4, k2]) {
    return ["G", 1 - Math.min(1, 0.3 * c6 + 0.59 * m4 + 0.11 * y4 + k2)];
  }
  static G_CMYK([g3]) {
    return ["CMYK", 0, 0, 0, 1 - g3];
  }
  static G_RGB([g3]) {
    return ["RGB", g3, g3, g3];
  }
  static G_rgb([g3]) {
    g3 = scaleAndClamp(g3);
    return [g3, g3, g3];
  }
  static G_HTML([g3]) {
    const G2 = makeColorComp(g3);
    return `#${G2}${G2}${G2}`;
  }
  static RGB_G([r8, g3, b4]) {
    return ["G", 0.3 * r8 + 0.59 * g3 + 0.11 * b4];
  }
  static RGB_rgb(color) {
    return color.map(scaleAndClamp);
  }
  static RGB_HTML(color) {
    return `#${color.map(makeColorComp).join("")}`;
  }
  static T_HTML() {
    return "#00000000";
  }
  static T_rgb() {
    return [null];
  }
  static CMYK_RGB([c6, y4, m4, k2]) {
    return ["RGB", 1 - Math.min(1, c6 + k2), 1 - Math.min(1, m4 + k2), 1 - Math.min(1, y4 + k2)];
  }
  static CMYK_rgb([c6, y4, m4, k2]) {
    return [scaleAndClamp(1 - Math.min(1, c6 + k2)), scaleAndClamp(1 - Math.min(1, m4 + k2)), scaleAndClamp(1 - Math.min(1, y4 + k2))];
  }
  static CMYK_HTML(components) {
    const rgb = this.CMYK_RGB(components).slice(1);
    return this.RGB_HTML(rgb);
  }
  static RGB_CMYK([r8, g3, b4]) {
    const c6 = 1 - r8;
    const m4 = 1 - g3;
    const y4 = 1 - b4;
    const k2 = Math.min(c6, m4, y4);
    return ["CMYK", c6, m4, y4, k2];
  }
};
var BaseSVGFactory = class {
  create(width, height, skipDimensions = false) {
    if (width <= 0 || height <= 0) {
      throw new Error("Invalid SVG dimensions");
    }
    const svg = this._createSVG("svg:svg");
    svg.setAttribute("version", "1.1");
    if (!skipDimensions) {
      svg.setAttribute("width", `${width}px`);
      svg.setAttribute("height", `${height}px`);
    }
    svg.setAttribute("preserveAspectRatio", "none");
    svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
    return svg;
  }
  createElement(type) {
    if (typeof type !== "string") {
      throw new Error("Invalid SVG element type");
    }
    return this._createSVG(type);
  }
  _createSVG(type) {
    unreachable("Abstract method `_createSVG` called.");
  }
};
var DOMSVGFactory = class extends BaseSVGFactory {
  _createSVG(type) {
    return document.createElementNS(SVG_NS, type);
  }
};
var annotation_layer_DEFAULT_FONT_SIZE = 9;
var GetElementsByNameSet = /* @__PURE__ */ new WeakSet();
var TIMEZONE_OFFSET = (/* @__PURE__ */ new Date()).getTimezoneOffset() * 60 * 1e3;
var AnnotationElementFactory = class {
  static create(parameters) {
    const subtype = parameters.data.annotationType;
    switch (subtype) {
      case AnnotationType.LINK:
        return new LinkAnnotationElement(parameters);
      case AnnotationType.TEXT:
        return new TextAnnotationElement(parameters);
      case AnnotationType.WIDGET:
        const fieldType = parameters.data.fieldType;
        switch (fieldType) {
          case "Tx":
            return new TextWidgetAnnotationElement(parameters);
          case "Btn":
            if (parameters.data.radioButton) {
              return new RadioButtonWidgetAnnotationElement(parameters);
            } else if (parameters.data.checkBox) {
              return new CheckboxWidgetAnnotationElement(parameters);
            }
            return new PushButtonWidgetAnnotationElement(parameters);
          case "Ch":
            return new ChoiceWidgetAnnotationElement(parameters);
          case "Sig":
            return new SignatureWidgetAnnotationElement(parameters);
        }
        return new WidgetAnnotationElement(parameters);
      case AnnotationType.POPUP:
        return new PopupAnnotationElement(parameters);
      case AnnotationType.FREETEXT:
        return new FreeTextAnnotationElement(parameters);
      case AnnotationType.LINE:
        return new LineAnnotationElement(parameters);
      case AnnotationType.SQUARE:
        return new SquareAnnotationElement(parameters);
      case AnnotationType.CIRCLE:
        return new CircleAnnotationElement(parameters);
      case AnnotationType.POLYLINE:
        return new PolylineAnnotationElement(parameters);
      case AnnotationType.CARET:
        return new CaretAnnotationElement(parameters);
      case AnnotationType.INK:
        return new InkAnnotationElement(parameters);
      case AnnotationType.POLYGON:
        return new PolygonAnnotationElement(parameters);
      case AnnotationType.HIGHLIGHT:
        return new HighlightAnnotationElement(parameters);
      case AnnotationType.UNDERLINE:
        return new UnderlineAnnotationElement(parameters);
      case AnnotationType.SQUIGGLY:
        return new SquigglyAnnotationElement(parameters);
      case AnnotationType.STRIKEOUT:
        return new StrikeOutAnnotationElement(parameters);
      case AnnotationType.STAMP:
        return new StampAnnotationElement(parameters);
      case AnnotationType.FILEATTACHMENT:
        return new FileAttachmentAnnotationElement(parameters);
      default:
        return new AnnotationElement(parameters);
    }
  }
};
var AnnotationElement = class _AnnotationElement {
  #updates = null;
  #hasBorder = false;
  #popupElement = null;
  constructor(parameters, {
    isRenderable = false,
    ignoreBorder = false,
    createQuadrilaterals = false
  } = {}) {
    this.isRenderable = isRenderable;
    this.data = parameters.data;
    this.layer = parameters.layer;
    this.linkService = parameters.linkService;
    this.downloadManager = parameters.downloadManager;
    this.imageResourcesPath = parameters.imageResourcesPath;
    this.renderForms = parameters.renderForms;
    this.svgFactory = parameters.svgFactory;
    this.annotationStorage = parameters.annotationStorage;
    this.enableComment = parameters.enableComment;
    this.enableScripting = parameters.enableScripting;
    this.hasJSActions = parameters.hasJSActions;
    this._fieldObjects = parameters.fieldObjects;
    this.parent = parameters.parent;
    this.hasOwnCommentButton = false;
    if (isRenderable) {
      this.contentElement = this.container = this._createContainer(ignoreBorder);
    }
    if (createQuadrilaterals) {
      this._createQuadrilaterals();
    }
  }
  static _hasPopupData({
    contentsObj,
    richText
  }) {
    return !!(contentsObj?.str || richText?.str);
  }
  get _isEditable() {
    return this.data.isEditable;
  }
  get hasPopupData() {
    return _AnnotationElement._hasPopupData(this.data) || this.enableComment && !!this.commentText;
  }
  get commentData() {
    const {
      data
    } = this;
    const editor = this.annotationStorage?.getEditor(data.id);
    if (editor) {
      return editor.getData();
    }
    return data;
  }
  get hasCommentButton() {
    return this.enableComment && this.hasPopupElement;
  }
  get commentButtonPosition() {
    const editor = this.annotationStorage?.getEditor(this.data.id);
    if (editor) {
      return editor.commentButtonPositionInPage;
    }
    const {
      quadPoints,
      inkLists,
      rect
    } = this.data;
    let maxX = -Infinity;
    let maxY = -Infinity;
    if (quadPoints?.length >= 8) {
      for (let i7 = 0; i7 < quadPoints.length; i7 += 8) {
        if (quadPoints[i7 + 1] > maxY) {
          maxY = quadPoints[i7 + 1];
          maxX = quadPoints[i7 + 2];
        } else if (quadPoints[i7 + 1] === maxY) {
          maxX = Math.max(maxX, quadPoints[i7 + 2]);
        }
      }
      return [maxX, maxY];
    }
    if (inkLists?.length >= 1) {
      for (const inkList of inkLists) {
        for (let i7 = 0, ii = inkList.length; i7 < ii; i7 += 2) {
          if (inkList[i7 + 1] > maxY) {
            maxY = inkList[i7 + 1];
            maxX = inkList[i7];
          } else if (inkList[i7 + 1] === maxY) {
            maxX = Math.max(maxX, inkList[i7]);
          }
        }
      }
      if (maxX !== Infinity) {
        return [maxX, maxY];
      }
    }
    if (rect) {
      return [rect[2], rect[3]];
    }
    return null;
  }
  _normalizePoint(point) {
    const {
      page: {
        view
      },
      viewport: {
        rawDims: {
          pageWidth,
          pageHeight,
          pageX,
          pageY
        }
      }
    } = this.parent;
    point[1] = view[3] - point[1] + view[1];
    point[0] = 100 * (point[0] - pageX) / pageWidth;
    point[1] = 100 * (point[1] - pageY) / pageHeight;
    return point;
  }
  get commentText() {
    const {
      data
    } = this;
    return this.annotationStorage.getRawValue(`${AnnotationEditorPrefix}${data.id}`)?.popup?.contents || data.contentsObj?.str || "";
  }
  set commentText(text3) {
    const {
      data
    } = this;
    const popup = {
      deleted: !text3,
      contents: text3 || ""
    };
    if (!this.annotationStorage.updateEditor(data.id, {
      popup
    })) {
      this.annotationStorage.setValue(`${AnnotationEditorPrefix}${data.id}`, {
        id: data.id,
        annotationType: data.annotationType,
        pageIndex: this.parent.page._pageIndex,
        popup,
        popupRef: data.popupRef,
        modificationDate: /* @__PURE__ */ new Date()
      });
    }
    if (!text3) {
      this.removePopup();
    }
  }
  removePopup() {
    (this.#popupElement?.popup || this.popup)?.remove();
    this.#popupElement = this.popup = null;
  }
  updateEdited(params) {
    if (!this.container) {
      return;
    }
    if (params.rect) {
      this.#updates ||= {
        rect: this.data.rect.slice(0)
      };
    }
    const {
      rect,
      popup: newPopup
    } = params;
    if (rect) {
      this.#setRectEdited(rect);
    }
    let popup = this.#popupElement?.popup || this.popup;
    if (!popup && newPopup?.text) {
      this._createPopup(newPopup);
      popup = this.#popupElement.popup;
    }
    if (!popup) {
      return;
    }
    popup.updateEdited(params);
    if (newPopup?.deleted) {
      popup.remove();
      this.#popupElement = null;
      this.popup = null;
    }
  }
  resetEdited() {
    if (!this.#updates) {
      return;
    }
    this.#setRectEdited(this.#updates.rect);
    this.#popupElement?.popup.resetEdited();
    this.#updates = null;
  }
  #setRectEdited(rect) {
    const {
      container: {
        style
      },
      data: {
        rect: currentRect,
        rotation
      },
      parent: {
        viewport: {
          rawDims: {
            pageWidth,
            pageHeight,
            pageX,
            pageY
          }
        }
      }
    } = this;
    currentRect?.splice(0, 4, ...rect);
    style.left = `${100 * (rect[0] - pageX) / pageWidth}%`;
    style.top = `${100 * (pageHeight - rect[3] + pageY) / pageHeight}%`;
    if (rotation === 0) {
      style.width = `${100 * (rect[2] - rect[0]) / pageWidth}%`;
      style.height = `${100 * (rect[3] - rect[1]) / pageHeight}%`;
    } else {
      this.setRotation(rotation);
    }
  }
  _createContainer(ignoreBorder) {
    const {
      data,
      parent: {
        page,
        viewport
      }
    } = this;
    const container = document.createElement("section");
    container.setAttribute("data-annotation-id", data.id);
    if (!(this instanceof WidgetAnnotationElement) && !(this instanceof LinkAnnotationElement)) {
      container.tabIndex = 0;
    }
    const {
      style
    } = container;
    style.zIndex = this.parent.zIndex;
    this.parent.zIndex += 2;
    if (data.alternativeText) {
      container.title = data.alternativeText;
    }
    if (data.noRotate) {
      container.classList.add("norotate");
    }
    if (!data.rect || this instanceof PopupAnnotationElement) {
      const {
        rotation: rotation2
      } = data;
      if (!data.hasOwnCanvas && rotation2 !== 0) {
        this.setRotation(rotation2, container);
      }
      return container;
    }
    const {
      width,
      height
    } = this;
    if (!ignoreBorder && data.borderStyle.width > 0) {
      style.borderWidth = `${data.borderStyle.width}px`;
      const horizontalRadius = data.borderStyle.horizontalCornerRadius;
      const verticalRadius = data.borderStyle.verticalCornerRadius;
      if (horizontalRadius > 0 || verticalRadius > 0) {
        const radius = `calc(${horizontalRadius}px * var(--total-scale-factor)) / calc(${verticalRadius}px * var(--total-scale-factor))`;
        style.borderRadius = radius;
      } else if (this instanceof RadioButtonWidgetAnnotationElement) {
        const radius = `calc(${width}px * var(--total-scale-factor)) / calc(${height}px * var(--total-scale-factor))`;
        style.borderRadius = radius;
      }
      switch (data.borderStyle.style) {
        case AnnotationBorderStyleType.SOLID:
          style.borderStyle = "solid";
          break;
        case AnnotationBorderStyleType.DASHED:
          style.borderStyle = "dashed";
          break;
        case AnnotationBorderStyleType.BEVELED:
          warn("Unimplemented border style: beveled");
          break;
        case AnnotationBorderStyleType.INSET:
          warn("Unimplemented border style: inset");
          break;
        case AnnotationBorderStyleType.UNDERLINE:
          style.borderBottomStyle = "solid";
          break;
        default:
          break;
      }
      const borderColor = data.borderColor || null;
      if (borderColor) {
        this.#hasBorder = true;
        style.borderColor = Util.makeHexColor(borderColor[0] | 0, borderColor[1] | 0, borderColor[2] | 0);
      } else {
        style.borderWidth = 0;
      }
    }
    const rect = Util.normalizeRect([data.rect[0], page.view[3] - data.rect[1] + page.view[1], data.rect[2], page.view[3] - data.rect[3] + page.view[1]]);
    const {
      pageWidth,
      pageHeight,
      pageX,
      pageY
    } = viewport.rawDims;
    style.left = `${100 * (rect[0] - pageX) / pageWidth}%`;
    style.top = `${100 * (rect[1] - pageY) / pageHeight}%`;
    const {
      rotation
    } = data;
    if (data.hasOwnCanvas || rotation === 0) {
      style.width = `${100 * width / pageWidth}%`;
      style.height = `${100 * height / pageHeight}%`;
    } else {
      this.setRotation(rotation, container);
    }
    return container;
  }
  setRotation(angle, container = this.container) {
    if (!this.data.rect) {
      return;
    }
    const {
      pageWidth,
      pageHeight
    } = this.parent.viewport.rawDims;
    let {
      width,
      height
    } = this;
    if (angle % 180 !== 0) {
      [width, height] = [height, width];
    }
    container.style.width = `${100 * width / pageWidth}%`;
    container.style.height = `${100 * height / pageHeight}%`;
    container.setAttribute("data-main-rotation", (360 - angle) % 360);
  }
  get _commonActions() {
    const setColor = (jsName, styleName, event) => {
      const color = event.detail[jsName];
      const colorType = color[0];
      const colorArray = color.slice(1);
      event.target.style[styleName] = ColorConverters[`${colorType}_HTML`](colorArray);
      this.annotationStorage.setValue(this.data.id, {
        [styleName]: ColorConverters[`${colorType}_rgb`](colorArray)
      });
    };
    return shadow(this, "_commonActions", {
      display: (event) => {
        const {
          display
        } = event.detail;
        const hidden = display % 2 === 1;
        this.container.style.visibility = hidden ? "hidden" : "visible";
        this.annotationStorage.setValue(this.data.id, {
          noView: hidden,
          noPrint: display === 1 || display === 2
        });
      },
      print: (event) => {
        this.annotationStorage.setValue(this.data.id, {
          noPrint: !event.detail.print
        });
      },
      hidden: (event) => {
        const {
          hidden
        } = event.detail;
        this.container.style.visibility = hidden ? "hidden" : "visible";
        this.annotationStorage.setValue(this.data.id, {
          noPrint: hidden,
          noView: hidden
        });
      },
      focus: (event) => {
        setTimeout(() => event.target.focus({
          preventScroll: false
        }), 0);
      },
      userName: (event) => {
        event.target.title = event.detail.userName;
      },
      readonly: (event) => {
        event.target.disabled = event.detail.readonly;
      },
      required: (event) => {
        this._setRequired(event.target, event.detail.required);
      },
      bgColor: (event) => {
        setColor("bgColor", "backgroundColor", event);
      },
      fillColor: (event) => {
        setColor("fillColor", "backgroundColor", event);
      },
      fgColor: (event) => {
        setColor("fgColor", "color", event);
      },
      textColor: (event) => {
        setColor("textColor", "color", event);
      },
      borderColor: (event) => {
        setColor("borderColor", "borderColor", event);
      },
      strokeColor: (event) => {
        setColor("strokeColor", "borderColor", event);
      },
      rotation: (event) => {
        const angle = event.detail.rotation;
        this.setRotation(angle);
        this.annotationStorage.setValue(this.data.id, {
          rotation: angle
        });
      }
    });
  }
  _dispatchEventFromSandbox(actions, jsEvent) {
    const commonActions = this._commonActions;
    for (const name of Object.keys(jsEvent.detail)) {
      const action = actions[name] || commonActions[name];
      action?.(jsEvent);
    }
  }
  _setDefaultPropertiesFromJS(element) {
    if (!this.enableScripting) {
      return;
    }
    const storedData = this.annotationStorage.getRawValue(this.data.id);
    if (!storedData) {
      return;
    }
    const commonActions = this._commonActions;
    for (const [actionName, detail] of Object.entries(storedData)) {
      const action = commonActions[actionName];
      if (action) {
        const eventProxy = {
          detail: {
            [actionName]: detail
          },
          target: element
        };
        action(eventProxy);
        delete storedData[actionName];
      }
    }
  }
  _createQuadrilaterals() {
    if (!this.container) {
      return;
    }
    const {
      quadPoints
    } = this.data;
    if (!quadPoints) {
      return;
    }
    const [rectBlX, rectBlY, rectTrX, rectTrY] = this.data.rect.map((x2) => Math.fround(x2));
    if (quadPoints.length === 8) {
      const [trX, trY, blX, blY] = quadPoints.subarray(2, 6);
      if (rectTrX === trX && rectTrY === trY && rectBlX === blX && rectBlY === blY) {
        return;
      }
    }
    const {
      style
    } = this.container;
    let svgBuffer;
    if (this.#hasBorder) {
      const {
        borderColor,
        borderWidth
      } = style;
      style.borderWidth = 0;
      svgBuffer = ["url('data:image/svg+xml;utf8,", `<svg xmlns="http://www.w3.org/2000/svg"`, ` preserveAspectRatio="none" viewBox="0 0 1 1">`, `<g fill="transparent" stroke="${borderColor}" stroke-width="${borderWidth}">`];
      this.container.classList.add("hasBorder");
    }
    const width = rectTrX - rectBlX;
    const height = rectTrY - rectBlY;
    const {
      svgFactory
    } = this;
    const svg = svgFactory.createElement("svg");
    svg.classList.add("quadrilateralsContainer");
    svg.setAttribute("width", 0);
    svg.setAttribute("height", 0);
    svg.role = "none";
    const defs = svgFactory.createElement("defs");
    svg.append(defs);
    const clipPath = svgFactory.createElement("clipPath");
    const id = `clippath_${this.data.id}`;
    clipPath.setAttribute("id", id);
    clipPath.setAttribute("clipPathUnits", "objectBoundingBox");
    defs.append(clipPath);
    for (let i7 = 2, ii = quadPoints.length; i7 < ii; i7 += 8) {
      const trX = quadPoints[i7];
      const trY = quadPoints[i7 + 1];
      const blX = quadPoints[i7 + 2];
      const blY = quadPoints[i7 + 3];
      const rect = svgFactory.createElement("rect");
      const x2 = (blX - rectBlX) / width;
      const y4 = (rectTrY - trY) / height;
      const rectWidth = (trX - blX) / width;
      const rectHeight = (trY - blY) / height;
      rect.setAttribute("x", x2);
      rect.setAttribute("y", y4);
      rect.setAttribute("width", rectWidth);
      rect.setAttribute("height", rectHeight);
      clipPath.append(rect);
      svgBuffer?.push(`<rect vector-effect="non-scaling-stroke" x="${x2}" y="${y4}" width="${rectWidth}" height="${rectHeight}"/>`);
    }
    if (this.#hasBorder) {
      svgBuffer.push(`</g></svg>')`);
      style.backgroundImage = svgBuffer.join("");
    }
    this.container.append(svg);
    this.container.style.clipPath = `url(#${id})`;
  }
  _createPopup(popupData = null) {
    const {
      data
    } = this;
    let contentsObj, modificationDate;
    if (popupData) {
      contentsObj = {
        str: popupData.text
      };
      modificationDate = popupData.date;
    } else {
      contentsObj = data.contentsObj;
      modificationDate = data.modificationDate;
    }
    this.#popupElement = new PopupAnnotationElement({
      data: {
        color: data.color,
        titleObj: data.titleObj,
        modificationDate,
        contentsObj,
        richText: data.richText,
        parentRect: data.rect,
        borderStyle: 0,
        id: `popup_${data.id}`,
        rotation: data.rotation,
        noRotate: true
      },
      linkService: this.linkService,
      parent: this.parent,
      elements: [this]
    });
  }
  get hasPopupElement() {
    return !!(this.#popupElement || this.popup || this.data.popupRef);
  }
  get extraPopupElement() {
    return this.#popupElement;
  }
  render() {
    unreachable("Abstract method `AnnotationElement.render` called");
  }
  _getElementsByName(name, skipId = null) {
    const fields = [];
    if (this._fieldObjects) {
      const fieldObj = this._fieldObjects[name];
      if (fieldObj) {
        for (const {
          page,
          id,
          exportValues
        } of fieldObj) {
          if (page === -1) {
            continue;
          }
          if (id === skipId) {
            continue;
          }
          const exportValue = typeof exportValues === "string" ? exportValues : null;
          const domElement = document.querySelector(`[data-element-id="${id}"]`);
          if (domElement && !GetElementsByNameSet.has(domElement)) {
            warn(`_getElementsByName - element not allowed: ${id}`);
            continue;
          }
          fields.push({
            id,
            exportValue,
            domElement
          });
        }
      }
      return fields;
    }
    for (const domElement of document.getElementsByName(name)) {
      const {
        exportValue
      } = domElement;
      const id = domElement.getAttribute("data-element-id");
      if (id === skipId) {
        continue;
      }
      if (!GetElementsByNameSet.has(domElement)) {
        continue;
      }
      fields.push({
        id,
        exportValue,
        domElement
      });
    }
    return fields;
  }
  show() {
    if (this.container) {
      this.container.hidden = false;
    }
    this.popup?.maybeShow();
  }
  hide() {
    if (this.container) {
      this.container.hidden = true;
    }
    this.popup?.forceHide();
  }
  getElementsToTriggerPopup() {
    return this.container;
  }
  addHighlightArea() {
    const triggers = this.getElementsToTriggerPopup();
    if (Array.isArray(triggers)) {
      for (const element of triggers) {
        element.classList.add("highlightArea");
      }
    } else {
      triggers.classList.add("highlightArea");
    }
  }
  _editOnDoubleClick() {
    if (!this._isEditable) {
      return;
    }
    const {
      annotationEditorType: mode,
      data: {
        id: editId
      }
    } = this;
    this.container.addEventListener("dblclick", () => {
      this.linkService.eventBus?.dispatch("switchannotationeditormode", {
        source: this,
        mode,
        editId,
        mustEnterInEditMode: true
      });
    });
  }
  get width() {
    return this.data.rect[2] - this.data.rect[0];
  }
  get height() {
    return this.data.rect[3] - this.data.rect[1];
  }
};
var EditorAnnotationElement = class extends AnnotationElement {
  constructor(parameters) {
    super(parameters, {
      isRenderable: true,
      ignoreBorder: true
    });
    this.editor = parameters.editor;
  }
  render() {
    this.container.className = "editorAnnotation";
    return this.container;
  }
  createOrUpdatePopup() {
    const {
      editor
    } = this;
    if (!editor.hasComment) {
      return;
    }
    this._createPopup(editor.comment);
  }
  get hasCommentButton() {
    return this.enableComment && this.editor.hasComment;
  }
  get commentButtonPosition() {
    return this.editor.commentButtonPositionInPage;
  }
  get commentText() {
    return this.editor.comment.text;
  }
  set commentText(text3) {
    this.editor.comment = text3;
    if (!text3) {
      this.removePopup();
    }
  }
  get commentData() {
    return this.editor.getData();
  }
  remove() {
    this.parent.removeAnnotation(this.data.id);
    this.container.remove();
    this.container = null;
    this.removePopup();
  }
};
var LinkAnnotationElement = class extends AnnotationElement {
  constructor(parameters, options = null) {
    super(parameters, {
      isRenderable: true,
      ignoreBorder: !!options?.ignoreBorder,
      createQuadrilaterals: true
    });
    this.isTooltipOnly = parameters.data.isTooltipOnly;
  }
  render() {
    const {
      data,
      linkService
    } = this;
    const link = document.createElement("a");
    link.setAttribute("data-element-id", data.id);
    let isBound = false;
    if (data.url) {
      linkService.addLinkAttributes(link, data.url, data.newWindow);
      isBound = true;
    } else if (data.action) {
      this._bindNamedAction(link, data.action, data.overlaidText);
      isBound = true;
    } else if (data.attachment) {
      this.#bindAttachment(link, data.attachment, data.overlaidText, data.attachmentDest);
      isBound = true;
    } else if (data.setOCGState) {
      this.#bindSetOCGState(link, data.setOCGState, data.overlaidText);
      isBound = true;
    } else if (data.dest) {
      this._bindLink(link, data.dest, data.overlaidText);
      isBound = true;
    } else {
      if (data.actions && (data.actions.Action || data.actions["Mouse Up"] || data.actions["Mouse Down"]) && this.enableScripting && this.hasJSActions) {
        this._bindJSAction(link, data);
        isBound = true;
      }
      if (data.resetForm) {
        this._bindResetFormAction(link, data.resetForm);
        isBound = true;
      } else if (this.isTooltipOnly && !isBound) {
        this._bindLink(link, "");
        isBound = true;
      }
    }
    this.container.classList.add("linkAnnotation");
    if (isBound) {
      this.contentElement = link;
      this.container.append(link);
    }
    return this.container;
  }
  #setInternalLink() {
    this.container.setAttribute("data-internal-link", "");
  }
  _bindLink(link, destination, overlaidText = "") {
    link.href = this.linkService.getDestinationHash(destination);
    link.onclick = () => {
      if (destination) {
        this.linkService.goToDestination(destination);
      }
      return false;
    };
    if (destination || destination === "") {
      this.#setInternalLink();
    }
    if (overlaidText) {
      link.title = overlaidText;
    }
  }
  _bindNamedAction(link, action, overlaidText = "") {
    link.href = this.linkService.getAnchorUrl("");
    link.onclick = () => {
      this.linkService.executeNamedAction(action);
      return false;
    };
    if (overlaidText) {
      link.title = overlaidText;
    }
    this.#setInternalLink();
  }
  #bindAttachment(link, attachment, overlaidText = "", dest = null) {
    link.href = this.linkService.getAnchorUrl("");
    if (attachment.description) {
      link.title = attachment.description;
    } else if (overlaidText) {
      link.title = overlaidText;
    }
    link.onclick = () => {
      this.downloadManager?.openOrDownloadData(attachment.content, attachment.filename, dest);
      return false;
    };
    this.#setInternalLink();
  }
  #bindSetOCGState(link, action, overlaidText = "") {
    link.href = this.linkService.getAnchorUrl("");
    link.onclick = () => {
      this.linkService.executeSetOCGState(action);
      return false;
    };
    if (overlaidText) {
      link.title = overlaidText;
    }
    this.#setInternalLink();
  }
  _bindJSAction(link, data) {
    link.href = this.linkService.getAnchorUrl("");
    const map = /* @__PURE__ */ new Map([["Action", "onclick"], ["Mouse Up", "onmouseup"], ["Mouse Down", "onmousedown"]]);
    for (const name of Object.keys(data.actions)) {
      const jsName = map.get(name);
      if (!jsName) {
        continue;
      }
      link[jsName] = () => {
        this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
          source: this,
          detail: {
            id: data.id,
            name
          }
        });
        return false;
      };
    }
    if (data.overlaidText) {
      link.title = data.overlaidText;
    }
    if (!link.onclick) {
      link.onclick = () => false;
    }
    this.#setInternalLink();
  }
  _bindResetFormAction(link, resetForm) {
    const otherClickAction = link.onclick;
    if (!otherClickAction) {
      link.href = this.linkService.getAnchorUrl("");
    }
    this.#setInternalLink();
    if (!this._fieldObjects) {
      warn(`_bindResetFormAction - "resetForm" action not supported, ensure that the \`fieldObjects\` parameter is provided.`);
      if (!otherClickAction) {
        link.onclick = () => false;
      }
      return;
    }
    link.onclick = () => {
      otherClickAction?.();
      const {
        fields: resetFormFields,
        refs: resetFormRefs,
        include
      } = resetForm;
      const allFields = [];
      if (resetFormFields.length !== 0 || resetFormRefs.length !== 0) {
        const fieldIds = new Set(resetFormRefs);
        for (const fieldName of resetFormFields) {
          const fields = this._fieldObjects[fieldName] || [];
          for (const {
            id
          } of fields) {
            fieldIds.add(id);
          }
        }
        for (const fields of Object.values(this._fieldObjects)) {
          for (const field of fields) {
            if (fieldIds.has(field.id) === include) {
              allFields.push(field);
            }
          }
        }
      } else {
        for (const fields of Object.values(this._fieldObjects)) {
          allFields.push(...fields);
        }
      }
      const storage2 = this.annotationStorage;
      const allIds = [];
      for (const field of allFields) {
        const {
          id
        } = field;
        allIds.push(id);
        switch (field.type) {
          case "text": {
            const value = field.defaultValue || "";
            storage2.setValue(id, {
              value
            });
            break;
          }
          case "checkbox":
          case "radiobutton": {
            const value = field.defaultValue === field.exportValues;
            storage2.setValue(id, {
              value
            });
            break;
          }
          case "combobox":
          case "listbox": {
            const value = field.defaultValue || "";
            storage2.setValue(id, {
              value
            });
            break;
          }
          default:
            continue;
        }
        const domElement = document.querySelector(`[data-element-id="${id}"]`);
        if (!domElement) {
          continue;
        } else if (!GetElementsByNameSet.has(domElement)) {
          warn(`_bindResetFormAction - element not allowed: ${id}`);
          continue;
        }
        domElement.dispatchEvent(new Event("resetform"));
      }
      if (this.enableScripting) {
        this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
          source: this,
          detail: {
            id: "app",
            ids: allIds,
            name: "ResetForm"
          }
        });
      }
      return false;
    };
  }
};
var TextAnnotationElement = class extends AnnotationElement {
  constructor(parameters) {
    super(parameters, {
      isRenderable: true
    });
  }
  render() {
    this.container.classList.add("textAnnotation");
    const image = document.createElement("img");
    image.src = this.imageResourcesPath + "annotation-" + this.data.name.toLowerCase() + ".svg";
    image.setAttribute("data-l10n-id", "pdfjs-text-annotation-type");
    image.setAttribute("data-l10n-args", JSON.stringify({
      type: this.data.name
    }));
    if (!this.data.popupRef && this.hasPopupData) {
      this.hasOwnCommentButton = true;
      this._createPopup();
    }
    this.container.append(image);
    return this.container;
  }
};
var WidgetAnnotationElement = class extends AnnotationElement {
  render() {
    return this.container;
  }
  showElementAndHideCanvas(element) {
    if (this.data.hasOwnCanvas) {
      if (element.previousSibling?.nodeName === "CANVAS") {
        element.previousSibling.hidden = true;
      }
      element.hidden = false;
    }
  }
  _getKeyModifier(event) {
    return util_FeatureTest.platform.isMac ? event.metaKey : event.ctrlKey;
  }
  _setEventListener(element, elementData, baseName, eventName, valueGetter) {
    if (baseName.includes("mouse")) {
      element.addEventListener(baseName, (event) => {
        this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
          source: this,
          detail: {
            id: this.data.id,
            name: eventName,
            value: valueGetter(event),
            shift: event.shiftKey,
            modifier: this._getKeyModifier(event)
          }
        });
      });
    } else {
      element.addEventListener(baseName, (event) => {
        if (baseName === "blur") {
          if (!elementData.focused || !event.relatedTarget) {
            return;
          }
          elementData.focused = false;
        } else if (baseName === "focus") {
          if (elementData.focused) {
            return;
          }
          elementData.focused = true;
        }
        if (!valueGetter) {
          return;
        }
        this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
          source: this,
          detail: {
            id: this.data.id,
            name: eventName,
            value: valueGetter(event)
          }
        });
      });
    }
  }
  _setEventListeners(element, elementData, names, getter) {
    for (const [baseName, eventName] of names) {
      if (eventName === "Action" || this.data.actions?.[eventName]) {
        if (eventName === "Focus" || eventName === "Blur") {
          elementData ||= {
            focused: false
          };
        }
        this._setEventListener(element, elementData, baseName, eventName, getter);
        if (eventName === "Focus" && !this.data.actions?.Blur) {
          this._setEventListener(element, elementData, "blur", "Blur", null);
        } else if (eventName === "Blur" && !this.data.actions?.Focus) {
          this._setEventListener(element, elementData, "focus", "Focus", null);
        }
      }
    }
  }
  _setBackgroundColor(element) {
    const color = this.data.backgroundColor || null;
    element.style.backgroundColor = color === null ? "transparent" : Util.makeHexColor(color[0], color[1], color[2]);
  }
  _setTextStyle(element) {
    const TEXT_ALIGNMENT = ["left", "center", "right"];
    const {
      fontColor
    } = this.data.defaultAppearanceData;
    const fontSize = this.data.defaultAppearanceData.fontSize || annotation_layer_DEFAULT_FONT_SIZE;
    const style = element.style;
    let computedFontSize;
    const BORDER_SIZE = 2;
    const roundToOneDecimal = (x2) => Math.round(10 * x2) / 10;
    if (this.data.multiLine) {
      const height = Math.abs(this.data.rect[3] - this.data.rect[1] - BORDER_SIZE);
      const numberOfLines = Math.round(height / (LINE_FACTOR * fontSize)) || 1;
      const lineHeight = height / numberOfLines;
      computedFontSize = Math.min(fontSize, roundToOneDecimal(lineHeight / LINE_FACTOR));
    } else {
      const height = Math.abs(this.data.rect[3] - this.data.rect[1] - BORDER_SIZE);
      computedFontSize = Math.min(fontSize, roundToOneDecimal(height / LINE_FACTOR));
    }
    style.fontSize = `calc(${computedFontSize}px * var(--total-scale-factor))`;
    style.color = Util.makeHexColor(fontColor[0], fontColor[1], fontColor[2]);
    if (this.data.textAlignment !== null) {
      style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment];
    }
  }
  _setRequired(element, isRequired) {
    if (isRequired) {
      element.setAttribute("required", true);
    } else {
      element.removeAttribute("required");
    }
    element.setAttribute("aria-required", isRequired);
  }
};
var TextWidgetAnnotationElement = class extends WidgetAnnotationElement {
  constructor(parameters) {
    const isRenderable = parameters.renderForms || parameters.data.hasOwnCanvas || !parameters.data.hasAppearance && !!parameters.data.fieldValue;
    super(parameters, {
      isRenderable
    });
  }
  setPropertyOnSiblings(base, key, value, keyInStorage) {
    const storage2 = this.annotationStorage;
    for (const element of this._getElementsByName(base.name, base.id)) {
      if (element.domElement) {
        element.domElement[key] = value;
      }
      storage2.setValue(element.id, {
        [keyInStorage]: value
      });
    }
  }
  render() {
    const storage2 = this.annotationStorage;
    const id = this.data.id;
    this.container.classList.add("textWidgetAnnotation");
    let element = null;
    if (this.renderForms) {
      const storedData = storage2.getValue(id, {
        value: this.data.fieldValue
      });
      let textContent = storedData.value || "";
      const maxLen = storage2.getValue(id, {
        charLimit: this.data.maxLen
      }).charLimit;
      if (maxLen && textContent.length > maxLen) {
        textContent = textContent.slice(0, maxLen);
      }
      let fieldFormattedValues = storedData.formattedValue || this.data.textContent?.join("\n") || null;
      if (fieldFormattedValues && this.data.comb) {
        fieldFormattedValues = fieldFormattedValues.replaceAll(/\s+/g, "");
      }
      const elementData = {
        userValue: textContent,
        formattedValue: fieldFormattedValues,
        lastCommittedValue: null,
        commitKey: 1,
        focused: false
      };
      if (this.data.multiLine) {
        element = document.createElement("textarea");
        element.textContent = fieldFormattedValues ?? textContent;
        if (this.data.doNotScroll) {
          element.style.overflowY = "hidden";
        }
      } else {
        element = document.createElement("input");
        element.type = this.data.password ? "password" : "text";
        element.setAttribute("value", fieldFormattedValues ?? textContent);
        if (this.data.doNotScroll) {
          element.style.overflowX = "hidden";
        }
      }
      if (this.data.hasOwnCanvas) {
        element.hidden = true;
      }
      GetElementsByNameSet.add(element);
      this.contentElement = element;
      element.setAttribute("data-element-id", id);
      element.disabled = this.data.readOnly;
      element.name = this.data.fieldName;
      element.tabIndex = 0;
      const {
        datetimeFormat,
        datetimeType,
        timeStep
      } = this.data;
      const hasDateOrTime = !!datetimeType && this.enableScripting;
      if (datetimeFormat) {
        element.title = datetimeFormat;
      }
      this._setRequired(element, this.data.required);
      if (maxLen) {
        element.maxLength = maxLen;
      }
      element.addEventListener("input", (event) => {
        storage2.setValue(id, {
          value: event.target.value
        });
        this.setPropertyOnSiblings(element, "value", event.target.value, "value");
        elementData.formattedValue = null;
      });
      element.addEventListener("resetform", (event) => {
        const defaultValue = this.data.defaultFieldValue ?? "";
        element.value = elementData.userValue = defaultValue;
        elementData.formattedValue = null;
      });
      let blurListener = (event) => {
        const {
          formattedValue
        } = elementData;
        if (formattedValue !== null && formattedValue !== void 0) {
          event.target.value = formattedValue;
        }
        event.target.scrollLeft = 0;
      };
      if (this.enableScripting && this.hasJSActions) {
        element.addEventListener("focus", (event) => {
          if (elementData.focused) {
            return;
          }
          const {
            target
          } = event;
          if (hasDateOrTime) {
            target.type = datetimeType;
            if (timeStep) {
              target.step = timeStep;
            }
          }
          if (elementData.userValue) {
            const value = elementData.userValue;
            if (hasDateOrTime) {
              if (datetimeType === "time") {
                const date = new Date(value);
                const parts = [date.getHours(), date.getMinutes(), date.getSeconds()];
                target.value = parts.map((v4) => v4.toString().padStart(2, "0")).join(":");
              } else {
                target.value = new Date(value - TIMEZONE_OFFSET).toISOString().split(datetimeType === "date" ? "T" : ".", 1)[0];
              }
            } else {
              target.value = value;
            }
          }
          elementData.lastCommittedValue = target.value;
          elementData.commitKey = 1;
          if (!this.data.actions?.Focus) {
            elementData.focused = true;
          }
        });
        element.addEventListener("updatefromsandbox", (jsEvent) => {
          this.showElementAndHideCanvas(jsEvent.target);
          const actions = {
            value(event) {
              elementData.userValue = event.detail.value ?? "";
              if (!hasDateOrTime) {
                storage2.setValue(id, {
                  value: elementData.userValue.toString()
                });
              }
              event.target.value = elementData.userValue;
            },
            formattedValue(event) {
              const {
                formattedValue
              } = event.detail;
              elementData.formattedValue = formattedValue;
              if (formattedValue !== null && formattedValue !== void 0 && event.target !== document.activeElement) {
                event.target.value = formattedValue;
              }
              const data = {
                formattedValue
              };
              if (hasDateOrTime) {
                data.value = formattedValue;
              }
              storage2.setValue(id, data);
            },
            selRange(event) {
              event.target.setSelectionRange(...event.detail.selRange);
            },
            charLimit: (event) => {
              const {
                charLimit
              } = event.detail;
              const {
                target
              } = event;
              if (charLimit === 0) {
                target.removeAttribute("maxLength");
                return;
              }
              target.setAttribute("maxLength", charLimit);
              let value = elementData.userValue;
              if (!value || value.length <= charLimit) {
                return;
              }
              value = value.slice(0, charLimit);
              target.value = elementData.userValue = value;
              storage2.setValue(id, {
                value
              });
              this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
                source: this,
                detail: {
                  id,
                  name: "Keystroke",
                  value,
                  willCommit: true,
                  commitKey: 1,
                  selStart: target.selectionStart,
                  selEnd: target.selectionEnd
                }
              });
            }
          };
          this._dispatchEventFromSandbox(actions, jsEvent);
        });
        element.addEventListener("keydown", (event) => {
          elementData.commitKey = 1;
          let commitKey = -1;
          if (event.key === "Escape") {
            commitKey = 0;
          } else if (event.key === "Enter" && !this.data.multiLine) {
            commitKey = 2;
          } else if (event.key === "Tab") {
            elementData.commitKey = 3;
          }
          if (commitKey === -1) {
            return;
          }
          const {
            value
          } = event.target;
          if (elementData.lastCommittedValue === value) {
            return;
          }
          elementData.lastCommittedValue = value;
          elementData.userValue = value;
          this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
            source: this,
            detail: {
              id,
              name: "Keystroke",
              value,
              willCommit: true,
              commitKey,
              selStart: event.target.selectionStart,
              selEnd: event.target.selectionEnd
            }
          });
        });
        const _blurListener = blurListener;
        blurListener = null;
        element.addEventListener("blur", (event) => {
          if (!elementData.focused || !event.relatedTarget) {
            return;
          }
          if (!this.data.actions?.Blur) {
            elementData.focused = false;
          }
          const {
            target
          } = event;
          let {
            value
          } = target;
          if (hasDateOrTime) {
            if (value && datetimeType === "time") {
              const parts = value.split(":").map((v4) => parseInt(v4, 10));
              value = new Date(2e3, 0, 1, parts[0], parts[1], parts[2] || 0).valueOf();
              target.step = "";
            } else {
              if (!value.includes("T")) {
                value = `${value}T00:00`;
              }
              value = new Date(value).valueOf();
            }
            target.type = "text";
          }
          elementData.userValue = value;
          if (elementData.lastCommittedValue !== value) {
            this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
              source: this,
              detail: {
                id,
                name: "Keystroke",
                value,
                willCommit: true,
                commitKey: elementData.commitKey,
                selStart: event.target.selectionStart,
                selEnd: event.target.selectionEnd
              }
            });
          }
          _blurListener(event);
        });
        if (this.data.actions?.Keystroke) {
          element.addEventListener("beforeinput", (event) => {
            elementData.lastCommittedValue = null;
            const {
              data,
              target
            } = event;
            const {
              value,
              selectionStart,
              selectionEnd
            } = target;
            let selStart = selectionStart, selEnd = selectionEnd;
            switch (event.inputType) {
              case "deleteWordBackward": {
                const match2 = value.substring(0, selectionStart).match(/\w*[^\w]*$/);
                if (match2) {
                  selStart -= match2[0].length;
                }
                break;
              }
              case "deleteWordForward": {
                const match2 = value.substring(selectionStart).match(/^[^\w]*\w*/);
                if (match2) {
                  selEnd += match2[0].length;
                }
                break;
              }
              case "deleteContentBackward":
                if (selectionStart === selectionEnd) {
                  selStart -= 1;
                }
                break;
              case "deleteContentForward":
                if (selectionStart === selectionEnd) {
                  selEnd += 1;
                }
                break;
            }
            event.preventDefault();
            this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
              source: this,
              detail: {
                id,
                name: "Keystroke",
                value,
                change: data || "",
                willCommit: false,
                selStart,
                selEnd
              }
            });
          });
        }
        this._setEventListeners(element, elementData, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], (event) => event.target.value);
      }
      if (blurListener) {
        element.addEventListener("blur", blurListener);
      }
      if (this.data.comb) {
        const fieldWidth = this.data.rect[2] - this.data.rect[0];
        const combWidth = fieldWidth / maxLen;
        element.classList.add("comb");
        element.style.letterSpacing = `calc(${combWidth}px * var(--total-scale-factor) - 1ch)`;
      }
    } else {
      element = document.createElement("div");
      element.textContent = this.data.fieldValue;
      element.style.verticalAlign = "middle";
      element.style.display = "table-cell";
      if (this.data.hasOwnCanvas) {
        element.hidden = true;
      }
    }
    this._setTextStyle(element);
    this._setBackgroundColor(element);
    this._setDefaultPropertiesFromJS(element);
    this.container.append(element);
    return this.container;
  }
};
var SignatureWidgetAnnotationElement = class extends WidgetAnnotationElement {
  constructor(parameters) {
    super(parameters, {
      isRenderable: !!parameters.data.hasOwnCanvas
    });
  }
};
var CheckboxWidgetAnnotationElement = class extends WidgetAnnotationElement {
  constructor(parameters) {
    super(parameters, {
      isRenderable: parameters.renderForms
    });
  }
  render() {
    const storage2 = this.annotationStorage;
    const data = this.data;
    const id = data.id;
    let value = storage2.getValue(id, {
      value: data.exportValue === data.fieldValue
    }).value;
    if (typeof value === "string") {
      value = value !== "Off";
      storage2.setValue(id, {
        value
      });
    }
    this.container.classList.add("buttonWidgetAnnotation", "checkBox");
    const element = document.createElement("input");
    GetElementsByNameSet.add(element);
    element.setAttribute("data-element-id", id);
    element.disabled = data.readOnly;
    this._setRequired(element, this.data.required);
    element.type = "checkbox";
    element.name = data.fieldName;
    if (value) {
      element.setAttribute("checked", true);
    }
    element.setAttribute("exportValue", data.exportValue);
    element.tabIndex = 0;
    element.addEventListener("change", (event) => {
      const {
        name,
        checked
      } = event.target;
      for (const checkbox of this._getElementsByName(name, id)) {
        const curChecked = checked && checkbox.exportValue === data.exportValue;
        if (checkbox.domElement) {
          checkbox.domElement.checked = curChecked;
        }
        storage2.setValue(checkbox.id, {
          value: curChecked
        });
      }
      storage2.setValue(id, {
        value: checked
      });
    });
    element.addEventListener("resetform", (event) => {
      const defaultValue = data.defaultFieldValue || "Off";
      event.target.checked = defaultValue === data.exportValue;
    });
    if (this.enableScripting && this.hasJSActions) {
      element.addEventListener("updatefromsandbox", (jsEvent) => {
        const actions = {
          value(event) {
            event.target.checked = event.detail.value !== "Off";
            storage2.setValue(id, {
              value: event.target.checked
            });
          }
        };
        this._dispatchEventFromSandbox(actions, jsEvent);
      });
      this._setEventListeners(element, null, [["change", "Validate"], ["change", "Action"], ["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], (event) => event.target.checked);
    }
    this._setBackgroundColor(element);
    this._setDefaultPropertiesFromJS(element);
    this.container.append(element);
    return this.container;
  }
};
var RadioButtonWidgetAnnotationElement = class extends WidgetAnnotationElement {
  constructor(parameters) {
    super(parameters, {
      isRenderable: parameters.renderForms
    });
  }
  render() {
    this.container.classList.add("buttonWidgetAnnotation", "radioButton");
    const storage2 = this.annotationStorage;
    const data = this.data;
    const id = data.id;
    let value = storage2.getValue(id, {
      value: data.fieldValue === data.buttonValue
    }).value;
    if (typeof value === "string") {
      value = value !== data.buttonValue;
      storage2.setValue(id, {
        value
      });
    }
    if (value) {
      for (const radio of this._getElementsByName(data.fieldName, id)) {
        storage2.setValue(radio.id, {
          value: false
        });
      }
    }
    const element = document.createElement("input");
    GetElementsByNameSet.add(element);
    element.setAttribute("data-element-id", id);
    element.disabled = data.readOnly;
    this._setRequired(element, this.data.required);
    element.type = "radio";
    element.name = data.fieldName;
    if (value) {
      element.setAttribute("checked", true);
    }
    element.tabIndex = 0;
    element.addEventListener("change", (event) => {
      const {
        name,
        checked
      } = event.target;
      for (const radio of this._getElementsByName(name, id)) {
        storage2.setValue(radio.id, {
          value: false
        });
      }
      storage2.setValue(id, {
        value: checked
      });
    });
    element.addEventListener("resetform", (event) => {
      const defaultValue = data.defaultFieldValue;
      event.target.checked = defaultValue !== null && defaultValue !== void 0 && defaultValue === data.buttonValue;
    });
    if (this.enableScripting && this.hasJSActions) {
      const pdfButtonValue = data.buttonValue;
      element.addEventListener("updatefromsandbox", (jsEvent) => {
        const actions = {
          value: (event) => {
            const checked = pdfButtonValue === event.detail.value;
            for (const radio of this._getElementsByName(event.target.name)) {
              const curChecked = checked && radio.id === id;
              if (radio.domElement) {
                radio.domElement.checked = curChecked;
              }
              storage2.setValue(radio.id, {
                value: curChecked
              });
            }
          }
        };
        this._dispatchEventFromSandbox(actions, jsEvent);
      });
      this._setEventListeners(element, null, [["change", "Validate"], ["change", "Action"], ["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], (event) => event.target.checked);
    }
    this._setBackgroundColor(element);
    this._setDefaultPropertiesFromJS(element);
    this.container.append(element);
    return this.container;
  }
};
var PushButtonWidgetAnnotationElement = class extends LinkAnnotationElement {
  constructor(parameters) {
    super(parameters, {
      ignoreBorder: parameters.data.hasAppearance
    });
  }
  render() {
    const container = super.render();
    container.classList.add("buttonWidgetAnnotation", "pushButton");
    const linkElement = container.lastChild;
    if (this.enableScripting && this.hasJSActions && linkElement) {
      this._setDefaultPropertiesFromJS(linkElement);
      linkElement.addEventListener("updatefromsandbox", (jsEvent) => {
        this._dispatchEventFromSandbox({}, jsEvent);
      });
    }
    return container;
  }
};
var ChoiceWidgetAnnotationElement = class extends WidgetAnnotationElement {
  constructor(parameters) {
    super(parameters, {
      isRenderable: parameters.renderForms
    });
  }
  render() {
    this.container.classList.add("choiceWidgetAnnotation");
    const storage2 = this.annotationStorage;
    const id = this.data.id;
    const storedData = storage2.getValue(id, {
      value: this.data.fieldValue
    });
    const selectElement = document.createElement("select");
    GetElementsByNameSet.add(selectElement);
    selectElement.setAttribute("data-element-id", id);
    selectElement.disabled = this.data.readOnly;
    this._setRequired(selectElement, this.data.required);
    selectElement.name = this.data.fieldName;
    selectElement.tabIndex = 0;
    let addAnEmptyEntry = this.data.combo && this.data.options.length > 0;
    if (!this.data.combo) {
      selectElement.size = this.data.options.length;
      if (this.data.multiSelect) {
        selectElement.multiple = true;
      }
    }
    selectElement.addEventListener("resetform", (event) => {
      const defaultValue = this.data.defaultFieldValue;
      for (const option of selectElement.options) {
        option.selected = option.value === defaultValue;
      }
    });
    for (const option of this.data.options) {
      const optionElement = document.createElement("option");
      optionElement.textContent = option.displayValue;
      optionElement.value = option.exportValue;
      if (storedData.value.includes(option.exportValue)) {
        optionElement.setAttribute("selected", true);
        addAnEmptyEntry = false;
      }
      selectElement.append(optionElement);
    }
    let removeEmptyEntry = null;
    if (addAnEmptyEntry) {
      const noneOptionElement = document.createElement("option");
      noneOptionElement.value = " ";
      noneOptionElement.setAttribute("hidden", true);
      noneOptionElement.setAttribute("selected", true);
      selectElement.prepend(noneOptionElement);
      removeEmptyEntry = () => {
        noneOptionElement.remove();
        selectElement.removeEventListener("input", removeEmptyEntry);
        removeEmptyEntry = null;
      };
      selectElement.addEventListener("input", removeEmptyEntry);
    }
    const getValue = (isExport) => {
      const name = isExport ? "value" : "textContent";
      const {
        options,
        multiple
      } = selectElement;
      if (!multiple) {
        return options.selectedIndex === -1 ? null : options[options.selectedIndex][name];
      }
      return Array.prototype.filter.call(options, (option) => option.selected).map((option) => option[name]);
    };
    let selectedValues = getValue(false);
    const getItems = (event) => {
      const options = event.target.options;
      return Array.prototype.map.call(options, (option) => ({
        displayValue: option.textContent,
        exportValue: option.value
      }));
    };
    if (this.enableScripting && this.hasJSActions) {
      selectElement.addEventListener("updatefromsandbox", (jsEvent) => {
        const actions = {
          value(event) {
            removeEmptyEntry?.();
            const value = event.detail.value;
            const values2 = new Set(Array.isArray(value) ? value : [value]);
            for (const option of selectElement.options) {
              option.selected = values2.has(option.value);
            }
            storage2.setValue(id, {
              value: getValue(true)
            });
            selectedValues = getValue(false);
          },
          multipleSelection(event) {
            selectElement.multiple = true;
          },
          remove(event) {
            const options = selectElement.options;
            const index = event.detail.remove;
            options[index].selected = false;
            selectElement.remove(index);
            if (options.length > 0) {
              const i7 = Array.prototype.findIndex.call(options, (option) => option.selected);
              if (i7 === -1) {
                options[0].selected = true;
              }
            }
            storage2.setValue(id, {
              value: getValue(true),
              items: getItems(event)
            });
            selectedValues = getValue(false);
          },
          clear(event) {
            while (selectElement.length !== 0) {
              selectElement.remove(0);
            }
            storage2.setValue(id, {
              value: null,
              items: []
            });
            selectedValues = getValue(false);
          },
          insert(event) {
            const {
              index,
              displayValue,
              exportValue
            } = event.detail.insert;
            const selectChild = selectElement.children[index];
            const optionElement = document.createElement("option");
            optionElement.textContent = displayValue;
            optionElement.value = exportValue;
            if (selectChild) {
              selectChild.before(optionElement);
            } else {
              selectElement.append(optionElement);
            }
            storage2.setValue(id, {
              value: getValue(true),
              items: getItems(event)
            });
            selectedValues = getValue(false);
          },
          items(event) {
            const {
              items
            } = event.detail;
            while (selectElement.length !== 0) {
              selectElement.remove(0);
            }
            for (const item of items) {
              const {
                displayValue,
                exportValue
              } = item;
              const optionElement = document.createElement("option");
              optionElement.textContent = displayValue;
              optionElement.value = exportValue;
              selectElement.append(optionElement);
            }
            if (selectElement.options.length > 0) {
              selectElement.options[0].selected = true;
            }
            storage2.setValue(id, {
              value: getValue(true),
              items: getItems(event)
            });
            selectedValues = getValue(false);
          },
          indices(event) {
            const indices = new Set(event.detail.indices);
            for (const option of event.target.options) {
              option.selected = indices.has(option.index);
            }
            storage2.setValue(id, {
              value: getValue(true)
            });
            selectedValues = getValue(false);
          },
          editable(event) {
            event.target.disabled = !event.detail.editable;
          }
        };
        this._dispatchEventFromSandbox(actions, jsEvent);
      });
      selectElement.addEventListener("input", (event) => {
        const exportValue = getValue(true);
        const change = getValue(false);
        storage2.setValue(id, {
          value: exportValue
        });
        event.preventDefault();
        this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
          source: this,
          detail: {
            id,
            name: "Keystroke",
            value: selectedValues,
            change,
            changeEx: exportValue,
            willCommit: false,
            commitKey: 1,
            keyDown: false
          }
        });
      });
      this._setEventListeners(selectElement, null, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"], ["input", "Action"], ["input", "Validate"]], (event) => event.target.value);
    } else {
      selectElement.addEventListener("input", function(event) {
        storage2.setValue(id, {
          value: getValue(true)
        });
      });
    }
    if (this.data.combo) {
      this._setTextStyle(selectElement);
    } else {
    }
    this._setBackgroundColor(selectElement);
    this._setDefaultPropertiesFromJS(selectElement);
    this.container.append(selectElement);
    return this.container;
  }
};
var PopupAnnotationElement = class extends AnnotationElement {
  constructor(parameters) {
    const {
      data,
      elements,
      parent
    } = parameters;
    const hasCommentManager = !!parent._commentManager;
    super(parameters, {
      isRenderable: !hasCommentManager && AnnotationElement._hasPopupData(data)
    });
    this.elements = elements;
    if (hasCommentManager && AnnotationElement._hasPopupData(data)) {
      const popup = this.popup = this.#createPopup();
      for (const element of elements) {
        element.popup = popup;
      }
    } else {
      this.popup = null;
    }
  }
  #createPopup() {
    return new PopupElement({
      container: this.container,
      color: this.data.color,
      titleObj: this.data.titleObj,
      modificationDate: this.data.modificationDate || this.data.creationDate,
      contentsObj: this.data.contentsObj,
      richText: this.data.richText,
      rect: this.data.rect,
      parentRect: this.data.parentRect || null,
      parent: this.parent,
      elements: this.elements,
      open: this.data.open,
      commentManager: this.parent._commentManager
    });
  }
  render() {
    const {
      container
    } = this;
    container.classList.add("popupAnnotation");
    container.role = "comment";
    const popup = this.popup = this.#createPopup();
    const elementIds = [];
    for (const element of this.elements) {
      element.popup = popup;
      element.container.ariaHasPopup = "dialog";
      elementIds.push(element.data.id);
      element.addHighlightArea();
    }
    this.container.setAttribute("aria-controls", elementIds.map((id) => `${AnnotationPrefix}${id}`).join(","));
    return this.container;
  }
};
var PopupElement = class {
  #commentManager = null;
  #boundKeyDown = this.#keyDown.bind(this);
  #boundHide = this.#hide.bind(this);
  #boundShow = this.#show.bind(this);
  #boundToggle = this.#toggle.bind(this);
  #color = null;
  #container = null;
  #contentsObj = null;
  #dateObj = null;
  #elements = null;
  #parent = null;
  #parentRect = null;
  #pinned = false;
  #popup = null;
  #popupAbortController = null;
  #position = null;
  #commentButton = null;
  #commentButtonPosition = null;
  #popupPosition = null;
  #rect = null;
  #richText = null;
  #titleObj = null;
  #updates = null;
  #wasVisible = false;
  #firstElement = null;
  #commentText = null;
  constructor({
    container,
    color,
    elements,
    titleObj,
    modificationDate,
    contentsObj,
    richText,
    parent,
    rect,
    parentRect,
    open: open2,
    commentManager = null
  }) {
    this.#container = container;
    this.#titleObj = titleObj;
    this.#contentsObj = contentsObj;
    this.#richText = richText;
    this.#parent = parent;
    this.#color = color;
    this.#rect = rect;
    this.#parentRect = parentRect;
    this.#elements = elements;
    this.#commentManager = commentManager;
    this.#firstElement = elements[0];
    this.#dateObj = PDFDateString.toDateObject(modificationDate);
    this.trigger = elements.flatMap((e9) => e9.getElementsToTriggerPopup());
    if (!commentManager) {
      this.#addEventListeners();
      this.#container.hidden = true;
      if (open2) {
        this.#toggle();
      }
    }
  }
  #addEventListeners() {
    if (this.#popupAbortController) {
      return;
    }
    this.#popupAbortController = new AbortController();
    const {
      signal
    } = this.#popupAbortController;
    for (const element of this.trigger) {
      element.addEventListener("click", this.#boundToggle, {
        signal
      });
      element.addEventListener("pointerenter", this.#boundShow, {
        signal
      });
      element.addEventListener("pointerleave", this.#boundHide, {
        signal
      });
      element.classList.add("popupTriggerArea");
    }
    for (const element of this.#elements) {
      element.container?.addEventListener("keydown", this.#boundKeyDown, {
        signal
      });
    }
  }
  #setCommentButtonPosition() {
    const element = this.#elements.find((e9) => e9.hasCommentButton);
    if (!element) {
      return;
    }
    this.#commentButtonPosition = element._normalizePoint(element.commentButtonPosition);
  }
  renderCommentButton() {
    if (this.#commentButton) {
      if (!this.#commentButton.parentNode) {
        this.#firstElement.container.after(this.#commentButton);
      }
      return;
    }
    if (!this.#commentButtonPosition) {
      this.#setCommentButtonPosition();
    }
    if (!this.#commentButtonPosition) {
      return;
    }
    const {
      signal
    } = this.#popupAbortController = new AbortController();
    const hasOwnButton = this.#firstElement.hasOwnCommentButton;
    const togglePopup = () => {
      this.#commentManager.toggleCommentPopup(this, true, void 0, !hasOwnButton);
    };
    const showPopup = () => {
      this.#commentManager.toggleCommentPopup(this, false, true, !hasOwnButton);
    };
    const hidePopup = () => {
      this.#commentManager.toggleCommentPopup(this, false, false);
    };
    if (!hasOwnButton) {
      const button = this.#commentButton = document.createElement("button");
      button.className = "annotationCommentButton";
      const parentContainer = this.#firstElement.container;
      button.style.zIndex = parentContainer.style.zIndex + 1;
      button.tabIndex = 0;
      button.ariaHasPopup = "dialog";
      button.ariaControls = "commentPopup";
      button.setAttribute("data-l10n-id", "pdfjs-show-comment-button");
      this.#updateColor();
      this.#updateCommentButtonPosition();
      button.addEventListener("keydown", this.#boundKeyDown, {
        signal
      });
      button.addEventListener("click", togglePopup, {
        signal
      });
      button.addEventListener("pointerenter", showPopup, {
        signal
      });
      button.addEventListener("pointerleave", hidePopup, {
        signal
      });
      parentContainer.after(button);
    } else {
      this.#commentButton = this.#firstElement.container;
      for (const element of this.trigger) {
        element.ariaHasPopup = "dialog";
        element.ariaControls = "commentPopup";
        element.addEventListener("keydown", this.#boundKeyDown, {
          signal
        });
        element.addEventListener("click", togglePopup, {
          signal
        });
        element.addEventListener("pointerenter", showPopup, {
          signal
        });
        element.addEventListener("pointerleave", hidePopup, {
          signal
        });
        element.classList.add("popupTriggerArea");
      }
    }
  }
  #updateCommentButtonPosition() {
    if (this.#firstElement.extraPopupElement && !this.#firstElement.editor) {
      return;
    }
    if (!this.#commentButton) {
      this.renderCommentButton();
    }
    const [x2, y4] = this.#commentButtonPosition;
    const {
      style
    } = this.#commentButton;
    style.left = `calc(${x2}%)`;
    style.top = `calc(${y4}% - var(--comment-button-dim))`;
  }
  #updateColor() {
    if (this.#firstElement.extraPopupElement) {
      return;
    }
    if (!this.#commentButton) {
      this.renderCommentButton();
    }
    this.#commentButton.style.backgroundColor = this.commentButtonColor || "";
  }
  get commentButtonColor() {
    const {
      color,
      opacity
    } = this.#firstElement.commentData;
    if (!color) {
      return null;
    }
    return this.#parent._commentManager.makeCommentColor(color, opacity);
  }
  focusCommentButton() {
    setTimeout(() => {
      this.#commentButton?.focus();
    }, 0);
  }
  getData() {
    const {
      richText,
      color,
      opacity,
      creationDate,
      modificationDate
    } = this.#firstElement.commentData;
    return {
      contentsObj: {
        str: this.comment
      },
      richText,
      color,
      opacity,
      creationDate,
      modificationDate
    };
  }
  get elementBeforePopup() {
    return this.#commentButton;
  }
  get comment() {
    this.#commentText ||= this.#firstElement.commentText;
    return this.#commentText;
  }
  set comment(text3) {
    if (text3 === this.comment) {
      return;
    }
    this.#firstElement.commentText = this.#commentText = text3;
  }
  focus() {
    this.#firstElement.container?.focus();
  }
  get parentBoundingClientRect() {
    return this.#firstElement.layer.getBoundingClientRect();
  }
  setCommentButtonStates({
    selected,
    hasPopup
  }) {
    if (!this.#commentButton) {
      return;
    }
    this.#commentButton.classList.toggle("selected", selected);
    this.#commentButton.ariaExpanded = hasPopup;
  }
  setSelectedCommentButton(selected) {
    this.#commentButton.classList.toggle("selected", selected);
  }
  get commentPopupPosition() {
    if (this.#popupPosition) {
      return this.#popupPosition;
    }
    const {
      x: x2,
      y: y4,
      height
    } = this.#commentButton.getBoundingClientRect();
    const {
      x: parentX,
      y: parentY,
      width: parentWidth,
      height: parentHeight
    } = this.#firstElement.layer.getBoundingClientRect();
    return [(x2 - parentX) / parentWidth, (y4 + height - parentY) / parentHeight];
  }
  set commentPopupPosition(pos) {
    this.#popupPosition = pos;
  }
  hasDefaultPopupPosition() {
    return this.#popupPosition === null;
  }
  get commentButtonPosition() {
    return this.#commentButtonPosition;
  }
  get commentButtonWidth() {
    return this.#commentButton.getBoundingClientRect().width / this.parentBoundingClientRect.width;
  }
  editComment(options) {
    const [posX, posY] = this.#popupPosition || this.commentButtonPosition.map((x2) => x2 / 100);
    const parentDimensions = this.parentBoundingClientRect;
    const {
      x: parentX,
      y: parentY,
      width: parentWidth,
      height: parentHeight
    } = parentDimensions;
    this.#commentManager.showDialog(null, this, parentX + posX * parentWidth, parentY + posY * parentHeight, {
      ...options,
      parentDimensions
    });
  }
  render() {
    if (this.#popup) {
      return;
    }
    const popup = this.#popup = document.createElement("div");
    popup.className = "popup";
    if (this.#color) {
      const baseColor = popup.style.outlineColor = Util.makeHexColor(...this.#color);
      popup.style.backgroundColor = `color-mix(in srgb, ${baseColor} 30%, white)`;
    }
    const header = document.createElement("span");
    header.className = "header";
    if (this.#titleObj?.str) {
      const title = document.createElement("span");
      title.className = "title";
      header.append(title);
      ({
        dir: title.dir,
        str: title.textContent
      } = this.#titleObj);
    }
    popup.append(header);
    if (this.#dateObj) {
      const modificationDate = document.createElement("time");
      modificationDate.className = "popupDate";
      modificationDate.setAttribute("data-l10n-id", "pdfjs-annotation-date-time-string");
      modificationDate.setAttribute("data-l10n-args", JSON.stringify({
        dateObj: this.#dateObj.valueOf()
      }));
      modificationDate.dateTime = this.#dateObj.toISOString();
      header.append(modificationDate);
    }
    renderRichText({
      html: this.#html || this.#contentsObj.str,
      dir: this.#contentsObj?.dir,
      className: "popupContent"
    }, popup);
    this.#container.append(popup);
  }
  get #html() {
    const richText = this.#richText;
    const contentsObj = this.#contentsObj;
    if (richText?.str && (!contentsObj?.str || contentsObj.str === richText.str)) {
      return this.#richText.html || null;
    }
    return null;
  }
  get #fontSize() {
    return this.#html?.attributes?.style?.fontSize || 0;
  }
  get #fontColor() {
    return this.#html?.attributes?.style?.color || null;
  }
  #makePopupContent(text3) {
    const popupLines = [];
    const popupContent = {
      str: text3,
      html: {
        name: "div",
        attributes: {
          dir: "auto"
        },
        children: [{
          name: "p",
          children: popupLines
        }]
      }
    };
    const lineAttributes = {
      style: {
        color: this.#fontColor,
        fontSize: this.#fontSize ? `calc(${this.#fontSize}px * var(--total-scale-factor))` : ""
      }
    };
    for (const line of text3.split("\n")) {
      popupLines.push({
        name: "span",
        value: line,
        attributes: lineAttributes
      });
    }
    return popupContent;
  }
  #keyDown(event) {
    if (event.altKey || event.shiftKey || event.ctrlKey || event.metaKey) {
      return;
    }
    if (event.key === "Enter" || event.key === "Escape" && this.#pinned) {
      this.#toggle();
    }
  }
  updateEdited({
    rect,
    popup,
    deleted
  }) {
    if (this.#commentManager) {
      if (deleted) {
        this.remove();
        this.#commentText = null;
      } else if (popup) {
        if (popup.deleted) {
          this.remove();
        } else {
          this.#updateColor();
          this.#commentText = popup.text;
        }
      }
      if (rect) {
        this.#commentButtonPosition = null;
        this.#setCommentButtonPosition();
        this.#updateCommentButtonPosition();
      }
      return;
    }
    if (deleted || popup?.deleted) {
      this.remove();
      return;
    }
    this.#addEventListeners();
    this.#updates ||= {
      contentsObj: this.#contentsObj,
      richText: this.#richText
    };
    if (rect) {
      this.#position = null;
    }
    if (popup && popup.text) {
      this.#richText = this.#makePopupContent(popup.text);
      this.#dateObj = PDFDateString.toDateObject(popup.date);
      this.#contentsObj = null;
    }
    this.#popup?.remove();
    this.#popup = null;
  }
  resetEdited() {
    if (!this.#updates) {
      return;
    }
    ({
      contentsObj: this.#contentsObj,
      richText: this.#richText
    } = this.#updates);
    this.#updates = null;
    this.#popup?.remove();
    this.#popup = null;
    this.#position = null;
  }
  remove() {
    this.#popupAbortController?.abort();
    this.#popupAbortController = null;
    this.#popup?.remove();
    this.#popup = null;
    this.#wasVisible = false;
    this.#pinned = false;
    this.#commentButton?.remove();
    this.#commentButton = null;
    if (this.trigger) {
      for (const element of this.trigger) {
        element.classList.remove("popupTriggerArea");
      }
    }
  }
  #setPosition() {
    if (this.#position !== null) {
      return;
    }
    const {
      page: {
        view
      },
      viewport: {
        rawDims: {
          pageWidth,
          pageHeight,
          pageX,
          pageY
        }
      }
    } = this.#parent;
    let useParentRect = !!this.#parentRect;
    let rect = useParentRect ? this.#parentRect : this.#rect;
    for (const element of this.#elements) {
      if (!rect || Util.intersect(element.data.rect, rect) !== null) {
        rect = element.data.rect;
        useParentRect = true;
        break;
      }
    }
    const normalizedRect = Util.normalizeRect([rect[0], view[3] - rect[1] + view[1], rect[2], view[3] - rect[3] + view[1]]);
    const HORIZONTAL_SPACE_AFTER_ANNOTATION = 5;
    const parentWidth = useParentRect ? rect[2] - rect[0] + HORIZONTAL_SPACE_AFTER_ANNOTATION : 0;
    const popupLeft = normalizedRect[0] + parentWidth;
    const popupTop = normalizedRect[1];
    this.#position = [100 * (popupLeft - pageX) / pageWidth, 100 * (popupTop - pageY) / pageHeight];
    const {
      style
    } = this.#container;
    style.left = `${this.#position[0]}%`;
    style.top = `${this.#position[1]}%`;
  }
  #toggle() {
    if (this.#commentManager) {
      this.#commentManager.toggleCommentPopup(this, false);
      return;
    }
    this.#pinned = !this.#pinned;
    if (this.#pinned) {
      this.#show();
      this.#container.addEventListener("click", this.#boundToggle);
      this.#container.addEventListener("keydown", this.#boundKeyDown);
    } else {
      this.#hide();
      this.#container.removeEventListener("click", this.#boundToggle);
      this.#container.removeEventListener("keydown", this.#boundKeyDown);
    }
  }
  #show() {
    if (!this.#popup) {
      this.render();
    }
    if (!this.isVisible) {
      this.#setPosition();
      this.#container.hidden = false;
      this.#container.style.zIndex = parseInt(this.#container.style.zIndex) + 1e3;
    } else if (this.#pinned) {
      this.#container.classList.add("focused");
    }
  }
  #hide() {
    this.#container.classList.remove("focused");
    if (this.#pinned || !this.isVisible) {
      return;
    }
    this.#container.hidden = true;
    this.#container.style.zIndex = parseInt(this.#container.style.zIndex) - 1e3;
  }
  forceHide() {
    this.#wasVisible = this.isVisible;
    if (!this.#wasVisible) {
      return;
    }
    this.#container.hidden = true;
  }
  maybeShow() {
    if (this.#commentManager) {
      return;
    }
    this.#addEventListeners();
    if (!this.#wasVisible) {
      return;
    }
    if (!this.#popup) {
      this.#show();
    }
    this.#wasVisible = false;
    this.#container.hidden = false;
  }
  get isVisible() {
    if (this.#commentManager) {
      return false;
    }
    return this.#container.hidden === false;
  }
};
var FreeTextAnnotationElement = class extends AnnotationElement {
  constructor(parameters) {
    super(parameters, {
      isRenderable: true,
      ignoreBorder: true
    });
    this.textContent = parameters.data.textContent;
    this.textPosition = parameters.data.textPosition;
    this.annotationEditorType = AnnotationEditorType.FREETEXT;
  }
  render() {
    this.container.classList.add("freeTextAnnotation");
    if (this.textContent) {
      const content = this.contentElement = document.createElement("div");
      content.classList.add("annotationTextContent");
      content.setAttribute("role", "comment");
      for (const line of this.textContent) {
        const lineSpan = document.createElement("span");
        lineSpan.textContent = line;
        content.append(lineSpan);
      }
      this.container.append(content);
    }
    if (!this.data.popupRef && this.hasPopupData) {
      this.hasOwnCommentButton = true;
      this._createPopup();
    }
    this._editOnDoubleClick();
    return this.container;
  }
};
var LineAnnotationElement = class extends AnnotationElement {
  #line = null;
  constructor(parameters) {
    super(parameters, {
      isRenderable: true,
      ignoreBorder: true
    });
  }
  render() {
    this.container.classList.add("lineAnnotation");
    const {
      data,
      width,
      height
    } = this;
    const svg = this.svgFactory.create(width, height, true);
    const line = this.#line = this.svgFactory.createElement("svg:line");
    line.setAttribute("x1", data.rect[2] - data.lineCoordinates[0]);
    line.setAttribute("y1", data.rect[3] - data.lineCoordinates[1]);
    line.setAttribute("x2", data.rect[2] - data.lineCoordinates[2]);
    line.setAttribute("y2", data.rect[3] - data.lineCoordinates[3]);
    line.setAttribute("stroke-width", data.borderStyle.width || 1);
    line.setAttribute("stroke", "transparent");
    line.setAttribute("fill", "transparent");
    svg.append(line);
    this.container.append(svg);
    if (!data.popupRef && this.hasPopupData) {
      this.hasOwnCommentButton = true;
      this._createPopup();
    }
    return this.container;
  }
  getElementsToTriggerPopup() {
    return this.#line;
  }
  addHighlightArea() {
    this.container.classList.add("highlightArea");
  }
};
var SquareAnnotationElement = class extends AnnotationElement {
  #square = null;
  constructor(parameters) {
    super(parameters, {
      isRenderable: true,
      ignoreBorder: true
    });
  }
  render() {
    this.container.classList.add("squareAnnotation");
    const {
      data,
      width,
      height
    } = this;
    const svg = this.svgFactory.create(width, height, true);
    const borderWidth = data.borderStyle.width;
    const square = this.#square = this.svgFactory.createElement("svg:rect");
    square.setAttribute("x", borderWidth / 2);
    square.setAttribute("y", borderWidth / 2);
    square.setAttribute("width", width - borderWidth);
    square.setAttribute("height", height - borderWidth);
    square.setAttribute("stroke-width", borderWidth || 1);
    square.setAttribute("stroke", "transparent");
    square.setAttribute("fill", "transparent");
    svg.append(square);
    this.container.append(svg);
    if (!data.popupRef && this.hasPopupData) {
      this.hasOwnCommentButton = true;
      this._createPopup();
    }
    return this.container;
  }
  getElementsToTriggerPopup() {
    return this.#square;
  }
  addHighlightArea() {
    this.container.classList.add("highlightArea");
  }
};
var CircleAnnotationElement = class extends AnnotationElement {
  #circle = null;
  constructor(parameters) {
    super(parameters, {
      isRenderable: true,
      ignoreBorder: true
    });
  }
  render() {
    this.container.classList.add("circleAnnotation");
    const {
      data,
      width,
      height
    } = this;
    const svg = this.svgFactory.create(width, height, true);
    const borderWidth = data.borderStyle.width;
    const circle = this.#circle = this.svgFactory.createElement("svg:ellipse");
    circle.setAttribute("cx", width / 2);
    circle.setAttribute("cy", height / 2);
    circle.setAttribute("rx", width / 2 - borderWidth / 2);
    circle.setAttribute("ry", height / 2 - borderWidth / 2);
    circle.setAttribute("stroke-width", borderWidth || 1);
    circle.setAttribute("stroke", "transparent");
    circle.setAttribute("fill", "transparent");
    svg.append(circle);
    this.container.append(svg);
    if (!data.popupRef && this.hasPopupData) {
      this.hasOwnCommentButton = true;
      this._createPopup();
    }
    return this.container;
  }
  getElementsToTriggerPopup() {
    return this.#circle;
  }
  addHighlightArea() {
    this.container.classList.add("highlightArea");
  }
};
var PolylineAnnotationElement = class extends AnnotationElement {
  #polyline = null;
  constructor(parameters) {
    super(parameters, {
      isRenderable: true,
      ignoreBorder: true
    });
    this.containerClassName = "polylineAnnotation";
    this.svgElementName = "svg:polyline";
  }
  render() {
    this.container.classList.add(this.containerClassName);
    const {
      data: {
        rect,
        vertices,
        borderStyle,
        popupRef
      },
      width,
      height
    } = this;
    if (!vertices) {
      return this.container;
    }
    const svg = this.svgFactory.create(width, height, true);
    let points = [];
    for (let i7 = 0, ii = vertices.length; i7 < ii; i7 += 2) {
      const x2 = vertices[i7] - rect[0];
      const y4 = rect[3] - vertices[i7 + 1];
      points.push(`${x2},${y4}`);
    }
    points = points.join(" ");
    const polyline = this.#polyline = this.svgFactory.createElement(this.svgElementName);
    polyline.setAttribute("points", points);
    polyline.setAttribute("stroke-width", borderStyle.width || 1);
    polyline.setAttribute("stroke", "transparent");
    polyline.setAttribute("fill", "transparent");
    svg.append(polyline);
    this.container.append(svg);
    if (!popupRef && this.hasPopupData) {
      this.hasOwnCommentButton = true;
      this._createPopup();
    }
    return this.container;
  }
  getElementsToTriggerPopup() {
    return this.#polyline;
  }
  addHighlightArea() {
    this.container.classList.add("highlightArea");
  }
};
var PolygonAnnotationElement = class extends PolylineAnnotationElement {
  constructor(parameters) {
    super(parameters);
    this.containerClassName = "polygonAnnotation";
    this.svgElementName = "svg:polygon";
  }
};
var CaretAnnotationElement = class extends AnnotationElement {
  constructor(parameters) {
    super(parameters, {
      isRenderable: true,
      ignoreBorder: true
    });
  }
  render() {
    this.container.classList.add("caretAnnotation");
    if (!this.data.popupRef && this.hasPopupData) {
      this.hasOwnCommentButton = true;
      this._createPopup();
    }
    return this.container;
  }
};
var InkAnnotationElement = class extends AnnotationElement {
  #polylinesGroupElement = null;
  #polylines = [];
  constructor(parameters) {
    super(parameters, {
      isRenderable: true,
      ignoreBorder: true
    });
    this.containerClassName = "inkAnnotation";
    this.svgElementName = "svg:polyline";
    this.annotationEditorType = this.data.it === "InkHighlight" ? AnnotationEditorType.HIGHLIGHT : AnnotationEditorType.INK;
  }
  #getTransform(rotation, rect) {
    switch (rotation) {
      case 90:
        return {
          transform: `rotate(90) translate(${-rect[0]},${rect[1]}) scale(1,-1)`,
          width: rect[3] - rect[1],
          height: rect[2] - rect[0]
        };
      case 180:
        return {
          transform: `rotate(180) translate(${-rect[2]},${rect[1]}) scale(1,-1)`,
          width: rect[2] - rect[0],
          height: rect[3] - rect[1]
        };
      case 270:
        return {
          transform: `rotate(270) translate(${-rect[2]},${rect[3]}) scale(1,-1)`,
          width: rect[3] - rect[1],
          height: rect[2] - rect[0]
        };
      default:
        return {
          transform: `translate(${-rect[0]},${rect[3]}) scale(1,-1)`,
          width: rect[2] - rect[0],
          height: rect[3] - rect[1]
        };
    }
  }
  render() {
    this.container.classList.add(this.containerClassName);
    const {
      data: {
        rect,
        rotation,
        inkLists,
        borderStyle,
        popupRef
      }
    } = this;
    const {
      transform,
      width,
      height
    } = this.#getTransform(rotation, rect);
    const svg = this.svgFactory.create(width, height, true);
    const g3 = this.#polylinesGroupElement = this.svgFactory.createElement("svg:g");
    svg.append(g3);
    g3.setAttribute("stroke-width", borderStyle.width || 1);
    g3.setAttribute("stroke-linecap", "round");
    g3.setAttribute("stroke-linejoin", "round");
    g3.setAttribute("stroke-miterlimit", 10);
    g3.setAttribute("stroke", "transparent");
    g3.setAttribute("fill", "transparent");
    g3.setAttribute("transform", transform);
    for (let i7 = 0, ii = inkLists.length; i7 < ii; i7++) {
      const polyline = this.svgFactory.createElement(this.svgElementName);
      this.#polylines.push(polyline);
      polyline.setAttribute("points", inkLists[i7].join(","));
      g3.append(polyline);
    }
    if (!popupRef && this.hasPopupData) {
      this.hasOwnCommentButton = true;
      this._createPopup();
    }
    this.container.append(svg);
    this._editOnDoubleClick();
    return this.container;
  }
  updateEdited(params) {
    super.updateEdited(params);
    const {
      thickness,
      points,
      rect
    } = params;
    const g3 = this.#polylinesGroupElement;
    if (thickness >= 0) {
      g3.setAttribute("stroke-width", thickness || 1);
    }
    if (points) {
      for (let i7 = 0, ii = this.#polylines.length; i7 < ii; i7++) {
        this.#polylines[i7].setAttribute("points", points[i7].join(","));
      }
    }
    if (rect) {
      const {
        transform,
        width,
        height
      } = this.#getTransform(this.data.rotation, rect);
      const root = g3.parentElement;
      root.setAttribute("viewBox", `0 0 ${width} ${height}`);
      g3.setAttribute("transform", transform);
    }
  }
  getElementsToTriggerPopup() {
    return this.#polylines;
  }
  addHighlightArea() {
    this.container.classList.add("highlightArea");
  }
};
var HighlightAnnotationElement = class extends AnnotationElement {
  constructor(parameters) {
    super(parameters, {
      isRenderable: true,
      ignoreBorder: true,
      createQuadrilaterals: true
    });
    this.annotationEditorType = AnnotationEditorType.HIGHLIGHT;
  }
  render() {
    const {
      data: {
        overlaidText,
        popupRef
      }
    } = this;
    if (!popupRef && this.hasPopupData) {
      this.hasOwnCommentButton = true;
      this._createPopup();
    }
    this.container.classList.add("highlightAnnotation");
    this._editOnDoubleClick();
    if (overlaidText) {
      const mark = document.createElement("mark");
      mark.classList.add("overlaidText");
      mark.textContent = overlaidText;
      this.container.append(mark);
    }
    return this.container;
  }
};
var UnderlineAnnotationElement = class extends AnnotationElement {
  constructor(parameters) {
    super(parameters, {
      isRenderable: true,
      ignoreBorder: true,
      createQuadrilaterals: true
    });
  }
  render() {
    const {
      data: {
        overlaidText,
        popupRef
      }
    } = this;
    if (!popupRef && this.hasPopupData) {
      this.hasOwnCommentButton = true;
      this._createPopup();
    }
    this.container.classList.add("underlineAnnotation");
    if (overlaidText) {
      const underline = document.createElement("u");
      underline.classList.add("overlaidText");
      underline.textContent = overlaidText;
      this.container.append(underline);
    }
    return this.container;
  }
};
var SquigglyAnnotationElement = class extends AnnotationElement {
  constructor(parameters) {
    super(parameters, {
      isRenderable: true,
      ignoreBorder: true,
      createQuadrilaterals: true
    });
  }
  render() {
    const {
      data: {
        overlaidText,
        popupRef
      }
    } = this;
    if (!popupRef && this.hasPopupData) {
      this.hasOwnCommentButton = true;
      this._createPopup();
    }
    this.container.classList.add("squigglyAnnotation");
    if (overlaidText) {
      const underline = document.createElement("u");
      underline.classList.add("overlaidText");
      underline.textContent = overlaidText;
      this.container.append(underline);
    }
    return this.container;
  }
};
var StrikeOutAnnotationElement = class extends AnnotationElement {
  constructor(parameters) {
    super(parameters, {
      isRenderable: true,
      ignoreBorder: true,
      createQuadrilaterals: true
    });
  }
  render() {
    const {
      data: {
        overlaidText,
        popupRef
      }
    } = this;
    if (!popupRef && this.hasPopupData) {
      this.hasOwnCommentButton = true;
      this._createPopup();
    }
    this.container.classList.add("strikeoutAnnotation");
    if (overlaidText) {
      const strikeout = document.createElement("s");
      strikeout.classList.add("overlaidText");
      strikeout.textContent = overlaidText;
      this.container.append(strikeout);
    }
    return this.container;
  }
};
var StampAnnotationElement = class extends AnnotationElement {
  constructor(parameters) {
    super(parameters, {
      isRenderable: true,
      ignoreBorder: true
    });
    this.annotationEditorType = AnnotationEditorType.STAMP;
  }
  render() {
    this.container.classList.add("stampAnnotation");
    this.container.setAttribute("role", "img");
    if (!this.data.popupRef && this.hasPopupData) {
      this.hasOwnCommentButton = true;
      this._createPopup();
    }
    this._editOnDoubleClick();
    return this.container;
  }
};
var FileAttachmentAnnotationElement = class extends AnnotationElement {
  #trigger = null;
  constructor(parameters) {
    super(parameters, {
      isRenderable: true
    });
    const {
      file
    } = this.data;
    this.filename = file.filename;
    this.content = file.content;
    this.linkService.eventBus?.dispatch("fileattachmentannotation", {
      source: this,
      ...file
    });
  }
  render() {
    this.container.classList.add("fileAttachmentAnnotation");
    const {
      container,
      data
    } = this;
    let trigger;
    if (data.hasAppearance || data.fillAlpha === 0) {
      trigger = document.createElement("div");
    } else {
      trigger = document.createElement("img");
      trigger.src = `${this.imageResourcesPath}annotation-${/paperclip/i.test(data.name) ? "paperclip" : "pushpin"}.svg`;
      if (data.fillAlpha && data.fillAlpha < 1) {
        trigger.style = `filter: opacity(${Math.round(data.fillAlpha * 100)}%);`;
      }
    }
    trigger.addEventListener("dblclick", this.#download.bind(this));
    this.#trigger = trigger;
    const {
      isMac
    } = util_FeatureTest.platform;
    container.addEventListener("keydown", (evt) => {
      if (evt.key === "Enter" && (isMac ? evt.metaKey : evt.ctrlKey)) {
        this.#download();
      }
    });
    if (!data.popupRef && this.hasPopupData) {
      this.hasOwnCommentButton = true;
      this._createPopup();
    } else {
      trigger.classList.add("popupTriggerArea");
    }
    container.append(trigger);
    return container;
  }
  getElementsToTriggerPopup() {
    return this.#trigger;
  }
  addHighlightArea() {
    this.container.classList.add("highlightArea");
  }
  #download() {
    this.downloadManager?.openOrDownloadData(this.content, this.filename);
  }
};
var AnnotationLayer = class _AnnotationLayer {
  #accessibilityManager = null;
  #annotationCanvasMap = null;
  #annotationStorage = null;
  #editableAnnotations = /* @__PURE__ */ new Map();
  #structTreeLayer = null;
  #linkService = null;
  #elements = [];
  #hasAriaAttributesFromStructTree = false;
  constructor({
    div,
    accessibilityManager,
    annotationCanvasMap,
    annotationEditorUIManager,
    page,
    viewport,
    structTreeLayer,
    commentManager,
    linkService,
    annotationStorage
  }) {
    this.div = div;
    this.#accessibilityManager = accessibilityManager;
    this.#annotationCanvasMap = annotationCanvasMap;
    this.#structTreeLayer = structTreeLayer || null;
    this.#linkService = linkService || null;
    this.#annotationStorage = annotationStorage || new AnnotationStorage();
    this.page = page;
    this.viewport = viewport;
    this.zIndex = 0;
    this._annotationEditorUIManager = annotationEditorUIManager;
    this._commentManager = commentManager || null;
  }
  hasEditableAnnotations() {
    return this.#editableAnnotations.size > 0;
  }
  async render(params) {
    const {
      annotations
    } = params;
    const layer = this.div;
    setLayerDimensions(layer, this.viewport);
    const popupToElements = /* @__PURE__ */ new Map();
    const popupAnnotations = [];
    const elementParams = {
      data: null,
      layer,
      linkService: this.#linkService,
      downloadManager: params.downloadManager,
      imageResourcesPath: params.imageResourcesPath || "",
      renderForms: params.renderForms !== false,
      svgFactory: new DOMSVGFactory(),
      annotationStorage: this.#annotationStorage,
      enableComment: params.enableComment === true,
      enableScripting: params.enableScripting === true,
      hasJSActions: params.hasJSActions,
      fieldObjects: params.fieldObjects,
      parent: this,
      elements: null
    };
    for (const data of annotations) {
      if (data.noHTML) {
        continue;
      }
      const isPopupAnnotation = data.annotationType === AnnotationType.POPUP;
      if (!isPopupAnnotation) {
        if (data.rect[2] === data.rect[0] || data.rect[3] === data.rect[1]) {
          continue;
        }
      } else {
        const elements = popupToElements.get(data.id);
        if (!elements) {
          continue;
        }
        if (!this._commentManager) {
          popupAnnotations.push(data);
          continue;
        }
        elementParams.elements = elements;
      }
      elementParams.data = data;
      const element = AnnotationElementFactory.create(elementParams);
      if (!element.isRenderable) {
        continue;
      }
      if (!isPopupAnnotation) {
        this.#elements.push(element);
        if (data.popupRef) {
          const elements = popupToElements.get(data.popupRef);
          if (!elements) {
            popupToElements.set(data.popupRef, [element]);
          } else {
            elements.push(element);
          }
        }
      }
      const rendered = element.render();
      if (data.hidden) {
        rendered.style.visibility = "hidden";
      }
      if (element._isEditable) {
        this.#editableAnnotations.set(element.data.id, element);
        this._annotationEditorUIManager?.renderAnnotationElement(element);
      }
    }
    await this.#addElementsToDOM();
    for (const data of popupAnnotations) {
      const elements = elementParams.elements = popupToElements.get(data.id);
      elementParams.data = data;
      const element = AnnotationElementFactory.create(elementParams);
      if (!element.isRenderable) {
        continue;
      }
      const rendered = element.render();
      element.contentElement.id = `${AnnotationPrefix}${data.id}`;
      if (data.hidden) {
        rendered.style.visibility = "hidden";
      }
      elements.at(-1).container.after(rendered);
    }
    this.#setAnnotationCanvasMap();
  }
  async #addElementsToDOM() {
    if (this.#elements.length === 0) {
      return;
    }
    this.div.replaceChildren();
    const promises = [];
    if (!this.#hasAriaAttributesFromStructTree) {
      this.#hasAriaAttributesFromStructTree = true;
      for (const {
        contentElement,
        data: {
          id
        }
      } of this.#elements) {
        const annotationId = contentElement.id = `${AnnotationPrefix}${id}`;
        promises.push(this.#structTreeLayer?.getAriaAttributes(annotationId).then((ariaAttributes) => {
          if (ariaAttributes) {
            for (const [key, value] of ariaAttributes) {
              contentElement.setAttribute(key, value);
            }
          }
        }));
      }
    }
    this.#elements.sort(({
      data: {
        rect: [a0, a1, a22, a3]
      }
    }, {
      data: {
        rect: [b0, b1, b22, b32]
      }
    }) => {
      if (a0 === a22 && a1 === a3) {
        return 1;
      }
      if (b0 === b22 && b1 === b32) {
        return -1;
      }
      const top1 = a3;
      const bot1 = a1;
      const mid1 = (a1 + a3) / 2;
      const top2 = b32;
      const bot2 = b1;
      const mid2 = (b1 + b32) / 2;
      if (mid1 >= top2 && mid2 <= bot1) {
        return -1;
      }
      if (mid2 >= top1 && mid1 <= bot2) {
        return 1;
      }
      const centerX1 = (a0 + a22) / 2;
      const centerX2 = (b0 + b22) / 2;
      return centerX1 - centerX2;
    });
    const fragment = document.createDocumentFragment();
    for (const element of this.#elements) {
      fragment.append(element.container);
      if (this._commentManager) {
        (element.extraPopupElement?.popup || element.popup)?.renderCommentButton();
      } else if (element.extraPopupElement) {
        fragment.append(element.extraPopupElement.render());
      }
    }
    this.div.append(fragment);
    await Promise.all(promises);
    if (this.#accessibilityManager) {
      for (const element of this.#elements) {
        this.#accessibilityManager.addPointerInTextLayer(element.contentElement, false);
      }
    }
  }
  async addLinkAnnotations(annotations) {
    const elementParams = {
      data: null,
      layer: this.div,
      linkService: this.#linkService,
      svgFactory: new DOMSVGFactory(),
      parent: this
    };
    for (const data of annotations) {
      data.borderStyle ||= _AnnotationLayer._defaultBorderStyle;
      elementParams.data = data;
      const element = AnnotationElementFactory.create(elementParams);
      if (!element.isRenderable) {
        continue;
      }
      element.render();
      element.contentElement.id = `${AnnotationPrefix}${data.id}`;
      this.#elements.push(element);
    }
    await this.#addElementsToDOM();
  }
  update({
    viewport
  }) {
    const layer = this.div;
    this.viewport = viewport;
    setLayerDimensions(layer, {
      rotation: viewport.rotation
    });
    this.#setAnnotationCanvasMap();
    layer.hidden = false;
  }
  #setAnnotationCanvasMap() {
    if (!this.#annotationCanvasMap) {
      return;
    }
    const layer = this.div;
    for (const [id, canvas] of this.#annotationCanvasMap) {
      const element = layer.querySelector(`[data-annotation-id="${id}"]`);
      if (!element) {
        continue;
      }
      canvas.className = "annotationContent";
      const {
        firstChild
      } = element;
      if (!firstChild) {
        element.append(canvas);
      } else if (firstChild.nodeName === "CANVAS") {
        firstChild.replaceWith(canvas);
      } else if (!firstChild.classList.contains("annotationContent")) {
        firstChild.before(canvas);
      } else {
        firstChild.after(canvas);
      }
      const editableAnnotation = this.#editableAnnotations.get(id);
      if (!editableAnnotation) {
        continue;
      }
      if (editableAnnotation._hasNoCanvas) {
        this._annotationEditorUIManager?.setMissingCanvas(id, element.id, canvas);
        editableAnnotation._hasNoCanvas = false;
      } else {
        editableAnnotation.canvas = canvas;
      }
    }
    this.#annotationCanvasMap.clear();
  }
  getEditableAnnotations() {
    return Array.from(this.#editableAnnotations.values());
  }
  getEditableAnnotation(id) {
    return this.#editableAnnotations.get(id);
  }
  addFakeAnnotation(editor) {
    const {
      div
    } = this;
    const {
      id,
      rotation
    } = editor;
    const element = new EditorAnnotationElement({
      data: {
        id,
        rect: editor.getPDFRect(),
        rotation
      },
      editor,
      layer: div,
      parent: this,
      enableComment: !!this._commentManager,
      linkService: this.#linkService,
      annotationStorage: this.#annotationStorage
    });
    element.render();
    element.contentElement.id = `${AnnotationPrefix}${id}`;
    element.createOrUpdatePopup();
    this.#elements.push(element);
    return element;
  }
  removeAnnotation(id) {
    const index = this.#elements.findIndex((el) => el.data.id === id);
    if (index < 0) {
      return;
    }
    const [element] = this.#elements.splice(index, 1);
    this.#accessibilityManager?.removePointerInTextLayer(element.contentElement);
  }
  updateFakeAnnotations(editors) {
    if (editors.length === 0) {
      return;
    }
    for (const editor of editors) {
      editor.updateFakeAnnotationElement(this);
    }
    this.#addElementsToDOM();
  }
  togglePointerEvents(enabled = false) {
    this.div.classList.toggle("disabled", !enabled);
  }
  static get _defaultBorderStyle() {
    return shadow(this, "_defaultBorderStyle", Object.freeze({
      width: 1,
      rawWidth: 1,
      style: AnnotationBorderStyleType.SOLID,
      dashArray: [3],
      horizontalCornerRadius: 0,
      verticalCornerRadius: 0
    }));
  }
};
var EOL_PATTERN = /\r\n?|\n/g;
var FreeTextEditor = class _FreeTextEditor extends AnnotationEditor {
  #content = "";
  #editorDivId = `${this.id}-editor`;
  #editModeAC = null;
  #fontSize;
  _colorPicker = null;
  static _freeTextDefaultContent = "";
  static _internalPadding = 0;
  static _defaultColor = null;
  static _defaultFontSize = 10;
  static get _keyboardManager() {
    const proto = _FreeTextEditor.prototype;
    const arrowChecker = (self2) => self2.isEmpty();
    const small = AnnotationEditorUIManager.TRANSLATE_SMALL;
    const big = AnnotationEditorUIManager.TRANSLATE_BIG;
    return shadow(this, "_keyboardManager", new KeyboardManager([[["ctrl+s", "mac+meta+s", "ctrl+p", "mac+meta+p"], proto.commitOrRemove, {
      bubbles: true
    }], [["ctrl+Enter", "mac+meta+Enter", "Escape", "mac+Escape"], proto.commitOrRemove], [["ArrowLeft", "mac+ArrowLeft"], proto._translateEmpty, {
      args: [-small, 0],
      checker: arrowChecker
    }], [["ctrl+ArrowLeft", "mac+shift+ArrowLeft"], proto._translateEmpty, {
      args: [-big, 0],
      checker: arrowChecker
    }], [["ArrowRight", "mac+ArrowRight"], proto._translateEmpty, {
      args: [small, 0],
      checker: arrowChecker
    }], [["ctrl+ArrowRight", "mac+shift+ArrowRight"], proto._translateEmpty, {
      args: [big, 0],
      checker: arrowChecker
    }], [["ArrowUp", "mac+ArrowUp"], proto._translateEmpty, {
      args: [0, -small],
      checker: arrowChecker
    }], [["ctrl+ArrowUp", "mac+shift+ArrowUp"], proto._translateEmpty, {
      args: [0, -big],
      checker: arrowChecker
    }], [["ArrowDown", "mac+ArrowDown"], proto._translateEmpty, {
      args: [0, small],
      checker: arrowChecker
    }], [["ctrl+ArrowDown", "mac+shift+ArrowDown"], proto._translateEmpty, {
      args: [0, big],
      checker: arrowChecker
    }]]));
  }
  static _type = "freetext";
  static _editorType = AnnotationEditorType.FREETEXT;
  constructor(params) {
    super({
      ...params,
      name: "freeTextEditor"
    });
    this.color = params.color || _FreeTextEditor._defaultColor || AnnotationEditor._defaultLineColor;
    this.#fontSize = params.fontSize || _FreeTextEditor._defaultFontSize;
    if (!this.annotationElementId) {
      this._uiManager.a11yAlert("pdfjs-editor-freetext-added-alert");
    }
    this.canAddComment = false;
  }
  static initialize(l10n, uiManager) {
    AnnotationEditor.initialize(l10n, uiManager);
    const style = getComputedStyle(document.documentElement);
    this._internalPadding = parseFloat(style.getPropertyValue("--freetext-padding"));
  }
  static updateDefaultParams(type, value) {
    switch (type) {
      case AnnotationEditorParamsType.FREETEXT_SIZE:
        _FreeTextEditor._defaultFontSize = value;
        break;
      case AnnotationEditorParamsType.FREETEXT_COLOR:
        _FreeTextEditor._defaultColor = value;
        break;
    }
  }
  updateParams(type, value) {
    switch (type) {
      case AnnotationEditorParamsType.FREETEXT_SIZE:
        this.#updateFontSize(value);
        break;
      case AnnotationEditorParamsType.FREETEXT_COLOR:
        this.#updateColor(value);
        break;
    }
  }
  static get defaultPropertiesToUpdate() {
    return [[AnnotationEditorParamsType.FREETEXT_SIZE, _FreeTextEditor._defaultFontSize], [AnnotationEditorParamsType.FREETEXT_COLOR, _FreeTextEditor._defaultColor || AnnotationEditor._defaultLineColor]];
  }
  get propertiesToUpdate() {
    return [[AnnotationEditorParamsType.FREETEXT_SIZE, this.#fontSize], [AnnotationEditorParamsType.FREETEXT_COLOR, this.color]];
  }
  get toolbarButtons() {
    this._colorPicker ||= new BasicColorPicker(this);
    return [["colorPicker", this._colorPicker]];
  }
  get colorType() {
    return AnnotationEditorParamsType.FREETEXT_COLOR;
  }
  #updateFontSize(fontSize) {
    const setFontsize = (size) => {
      this.editorDiv.style.fontSize = `calc(${size}px * var(--total-scale-factor))`;
      this.translate(0, -(size - this.#fontSize) * this.parentScale);
      this.#fontSize = size;
      this.#setEditorDimensions();
    };
    const savedFontsize = this.#fontSize;
    this.addCommands({
      cmd: setFontsize.bind(this, fontSize),
      undo: setFontsize.bind(this, savedFontsize),
      post: this._uiManager.updateUI.bind(this._uiManager, this),
      mustExec: true,
      type: AnnotationEditorParamsType.FREETEXT_SIZE,
      overwriteIfSameType: true,
      keepUndo: true
    });
  }
  onUpdatedColor() {
    this.editorDiv.style.color = this.color;
    this._colorPicker?.update(this.color);
    super.onUpdatedColor();
  }
  #updateColor(color) {
    const setColor = (col) => {
      this.color = col;
      this.onUpdatedColor();
    };
    const savedColor = this.color;
    this.addCommands({
      cmd: setColor.bind(this, color),
      undo: setColor.bind(this, savedColor),
      post: this._uiManager.updateUI.bind(this._uiManager, this),
      mustExec: true,
      type: AnnotationEditorParamsType.FREETEXT_COLOR,
      overwriteIfSameType: true,
      keepUndo: true
    });
  }
  _translateEmpty(x2, y4) {
    this._uiManager.translateSelectedEditors(x2, y4, true);
  }
  getInitialTranslation() {
    const scale = this.parentScale;
    return [-_FreeTextEditor._internalPadding * scale, -(_FreeTextEditor._internalPadding + this.#fontSize) * scale];
  }
  rebuild() {
    if (!this.parent) {
      return;
    }
    super.rebuild();
    if (this.div === null) {
      return;
    }
    if (!this.isAttachedToDOM) {
      this.parent.add(this);
    }
  }
  enableEditMode() {
    if (!super.enableEditMode()) {
      return false;
    }
    this.overlayDiv.classList.remove("enabled");
    this.editorDiv.contentEditable = true;
    this._isDraggable = false;
    this.div.removeAttribute("aria-activedescendant");
    this.#editModeAC = new AbortController();
    const signal = this._uiManager.combinedSignal(this.#editModeAC);
    this.editorDiv.addEventListener("keydown", this.editorDivKeydown.bind(this), {
      signal
    });
    this.editorDiv.addEventListener("focus", this.editorDivFocus.bind(this), {
      signal
    });
    this.editorDiv.addEventListener("blur", this.editorDivBlur.bind(this), {
      signal
    });
    this.editorDiv.addEventListener("input", this.editorDivInput.bind(this), {
      signal
    });
    this.editorDiv.addEventListener("paste", this.editorDivPaste.bind(this), {
      signal
    });
    return true;
  }
  disableEditMode() {
    if (!super.disableEditMode()) {
      return false;
    }
    this.overlayDiv.classList.add("enabled");
    this.editorDiv.contentEditable = false;
    this.div.setAttribute("aria-activedescendant", this.#editorDivId);
    this._isDraggable = true;
    this.#editModeAC?.abort();
    this.#editModeAC = null;
    this.div.focus({
      preventScroll: true
    });
    this.isEditing = false;
    this.parent.div.classList.add("freetextEditing");
    return true;
  }
  focusin(event) {
    if (!this._focusEventsAllowed) {
      return;
    }
    super.focusin(event);
    if (event.target !== this.editorDiv) {
      this.editorDiv.focus();
    }
  }
  onceAdded(focus) {
    if (this.width) {
      return;
    }
    this.enableEditMode();
    if (focus) {
      this.editorDiv.focus();
    }
    if (this._initialOptions?.isCentered) {
      this.center();
    }
    this._initialOptions = null;
  }
  isEmpty() {
    return !this.editorDiv || this.editorDiv.innerText.trim() === "";
  }
  remove() {
    this.isEditing = false;
    if (this.parent) {
      this.parent.setEditingState(true);
      this.parent.div.classList.add("freetextEditing");
    }
    super.remove();
  }
  #extractText() {
    const buffer = [];
    this.editorDiv.normalize();
    let prevChild = null;
    for (const child of this.editorDiv.childNodes) {
      if (prevChild?.nodeType === Node.TEXT_NODE && child.nodeName === "BR") {
        continue;
      }
      buffer.push(_FreeTextEditor.#getNodeContent(child));
      prevChild = child;
    }
    return buffer.join("\n");
  }
  #setEditorDimensions() {
    const [parentWidth, parentHeight] = this.parentDimensions;
    let rect;
    if (this.isAttachedToDOM) {
      rect = this.div.getBoundingClientRect();
    } else {
      const {
        currentLayer,
        div
      } = this;
      const savedDisplay = div.style.display;
      const savedVisibility = div.classList.contains("hidden");
      div.classList.remove("hidden");
      div.style.display = "hidden";
      currentLayer.div.append(this.div);
      rect = div.getBoundingClientRect();
      div.remove();
      div.style.display = savedDisplay;
      div.classList.toggle("hidden", savedVisibility);
    }
    if (this.rotation % 180 === this.parentRotation % 180) {
      this.width = rect.width / parentWidth;
      this.height = rect.height / parentHeight;
    } else {
      this.width = rect.height / parentWidth;
      this.height = rect.width / parentHeight;
    }
    this.fixAndSetPosition();
  }
  commit() {
    if (!this.isInEditMode()) {
      return;
    }
    super.commit();
    this.disableEditMode();
    const savedText = this.#content;
    const newText = this.#content = this.#extractText().trimEnd();
    if (savedText === newText) {
      return;
    }
    const setText = (text3) => {
      this.#content = text3;
      if (!text3) {
        this.remove();
        return;
      }
      this.#setContent();
      this._uiManager.rebuild(this);
      this.#setEditorDimensions();
    };
    this.addCommands({
      cmd: () => {
        setText(newText);
      },
      undo: () => {
        setText(savedText);
      },
      mustExec: false
    });
    this.#setEditorDimensions();
  }
  shouldGetKeyboardEvents() {
    return this.isInEditMode();
  }
  enterInEditMode() {
    this.enableEditMode();
    this.editorDiv.focus();
  }
  keydown(event) {
    if (event.target === this.div && event.key === "Enter") {
      this.enterInEditMode();
      event.preventDefault();
    }
  }
  editorDivKeydown(event) {
    _FreeTextEditor._keyboardManager.exec(this, event);
  }
  editorDivFocus(event) {
    this.isEditing = true;
  }
  editorDivBlur(event) {
    this.isEditing = false;
  }
  editorDivInput(event) {
    this.parent.div.classList.toggle("freetextEditing", this.isEmpty());
  }
  disableEditing() {
    this.editorDiv.setAttribute("role", "comment");
    this.editorDiv.removeAttribute("aria-multiline");
  }
  enableEditing() {
    this.editorDiv.setAttribute("role", "textbox");
    this.editorDiv.setAttribute("aria-multiline", true);
  }
  get canChangeContent() {
    return true;
  }
  render() {
    if (this.div) {
      return this.div;
    }
    let baseX, baseY;
    if (this._isCopy || this.annotationElementId) {
      baseX = this.x;
      baseY = this.y;
    }
    super.render();
    this.editorDiv = document.createElement("div");
    this.editorDiv.className = "internal";
    this.editorDiv.setAttribute("id", this.#editorDivId);
    this.editorDiv.setAttribute("data-l10n-id", "pdfjs-free-text2");
    this.editorDiv.setAttribute("data-l10n-attrs", "default-content");
    this.enableEditing();
    this.editorDiv.contentEditable = true;
    const {
      style
    } = this.editorDiv;
    style.fontSize = `calc(${this.#fontSize}px * var(--total-scale-factor))`;
    style.color = this.color;
    this.div.append(this.editorDiv);
    this.overlayDiv = document.createElement("div");
    this.overlayDiv.classList.add("overlay", "enabled");
    this.div.append(this.overlayDiv);
    if (this._isCopy || this.annotationElementId) {
      const [parentWidth, parentHeight] = this.parentDimensions;
      if (this.annotationElementId) {
        const {
          position
        } = this._initialData;
        let [tx, ty] = this.getInitialTranslation();
        [tx, ty] = this.pageTranslationToScreen(tx, ty);
        const [pageWidth, pageHeight] = this.pageDimensions;
        const [pageX, pageY] = this.pageTranslation;
        let posX, posY;
        switch (this.rotation) {
          case 0:
            posX = baseX + (position[0] - pageX) / pageWidth;
            posY = baseY + this.height - (position[1] - pageY) / pageHeight;
            break;
          case 90:
            posX = baseX + (position[0] - pageX) / pageWidth;
            posY = baseY - (position[1] - pageY) / pageHeight;
            [tx, ty] = [ty, -tx];
            break;
          case 180:
            posX = baseX - this.width + (position[0] - pageX) / pageWidth;
            posY = baseY - (position[1] - pageY) / pageHeight;
            [tx, ty] = [-tx, -ty];
            break;
          case 270:
            posX = baseX + (position[0] - pageX - this.height * pageHeight) / pageWidth;
            posY = baseY + (position[1] - pageY - this.width * pageWidth) / pageHeight;
            [tx, ty] = [-ty, tx];
            break;
        }
        this.setAt(posX * parentWidth, posY * parentHeight, tx, ty);
      } else {
        this._moveAfterPaste(baseX, baseY);
      }
      this.#setContent();
      this._isDraggable = true;
      this.editorDiv.contentEditable = false;
    } else {
      this._isDraggable = false;
      this.editorDiv.contentEditable = true;
    }
    return this.div;
  }
  static #getNodeContent(node) {
    return (node.nodeType === Node.TEXT_NODE ? node.nodeValue : node.innerText).replaceAll(EOL_PATTERN, "");
  }
  editorDivPaste(event) {
    const clipboardData = event.clipboardData || window.clipboardData;
    const {
      types: types2
    } = clipboardData;
    if (types2.length === 1 && types2[0] === "text/plain") {
      return;
    }
    event.preventDefault();
    const paste = _FreeTextEditor.#deserializeContent(clipboardData.getData("text") || "").replaceAll(EOL_PATTERN, "\n");
    if (!paste) {
      return;
    }
    const selection = window.getSelection();
    if (!selection.rangeCount) {
      return;
    }
    this.editorDiv.normalize();
    selection.deleteFromDocument();
    const range2 = selection.getRangeAt(0);
    if (!paste.includes("\n")) {
      range2.insertNode(document.createTextNode(paste));
      this.editorDiv.normalize();
      selection.collapseToStart();
      return;
    }
    const {
      startContainer,
      startOffset
    } = range2;
    const bufferBefore = [];
    const bufferAfter = [];
    if (startContainer.nodeType === Node.TEXT_NODE) {
      const parent = startContainer.parentElement;
      bufferAfter.push(startContainer.nodeValue.slice(startOffset).replaceAll(EOL_PATTERN, ""));
      if (parent !== this.editorDiv) {
        let buffer = bufferBefore;
        for (const child of this.editorDiv.childNodes) {
          if (child === parent) {
            buffer = bufferAfter;
            continue;
          }
          buffer.push(_FreeTextEditor.#getNodeContent(child));
        }
      }
      bufferBefore.push(startContainer.nodeValue.slice(0, startOffset).replaceAll(EOL_PATTERN, ""));
    } else if (startContainer === this.editorDiv) {
      let buffer = bufferBefore;
      let i7 = 0;
      for (const child of this.editorDiv.childNodes) {
        if (i7++ === startOffset) {
          buffer = bufferAfter;
        }
        buffer.push(_FreeTextEditor.#getNodeContent(child));
      }
    }
    this.#content = `${bufferBefore.join("\n")}${paste}${bufferAfter.join("\n")}`;
    this.#setContent();
    const newRange = new Range();
    let beforeLength = Math.sumPrecise(bufferBefore.map((line) => line.length));
    for (const {
      firstChild
    } of this.editorDiv.childNodes) {
      if (firstChild.nodeType === Node.TEXT_NODE) {
        const length = firstChild.nodeValue.length;
        if (beforeLength <= length) {
          newRange.setStart(firstChild, beforeLength);
          newRange.setEnd(firstChild, beforeLength);
          break;
        }
        beforeLength -= length;
      }
    }
    selection.removeAllRanges();
    selection.addRange(newRange);
  }
  #setContent() {
    this.editorDiv.replaceChildren();
    if (!this.#content) {
      return;
    }
    for (const line of this.#content.split("\n")) {
      const div = document.createElement("div");
      div.append(line ? document.createTextNode(line) : document.createElement("br"));
      this.editorDiv.append(div);
    }
  }
  #serializeContent() {
    return this.#content.replaceAll("\xA0", " ");
  }
  static #deserializeContent(content) {
    return content.replaceAll(" ", "\xA0");
  }
  get contentDiv() {
    return this.editorDiv;
  }
  getPDFRect() {
    const padding = _FreeTextEditor._internalPadding * this.parentScale;
    return this.getRect(padding, padding);
  }
  static async deserialize(data, parent, uiManager) {
    let initialData = null;
    if (data instanceof FreeTextAnnotationElement) {
      const {
        data: {
          defaultAppearanceData: {
            fontSize,
            fontColor
          },
          rect,
          rotation,
          id,
          popupRef,
          richText,
          contentsObj,
          creationDate,
          modificationDate
        },
        textContent,
        textPosition,
        parent: {
          page: {
            pageNumber
          }
        }
      } = data;
      if (!textContent || textContent.length === 0) {
        return null;
      }
      initialData = data = {
        annotationType: AnnotationEditorType.FREETEXT,
        color: Array.from(fontColor),
        fontSize,
        value: textContent.join("\n"),
        position: textPosition,
        pageIndex: pageNumber - 1,
        rect: rect.slice(0),
        rotation,
        annotationElementId: id,
        id,
        deleted: false,
        popupRef,
        comment: contentsObj?.str || null,
        richText,
        creationDate,
        modificationDate
      };
    }
    const editor = await super.deserialize(data, parent, uiManager);
    editor.#fontSize = data.fontSize;
    editor.color = Util.makeHexColor(...data.color);
    editor.#content = _FreeTextEditor.#deserializeContent(data.value);
    editor._initialData = initialData;
    if (data.comment) {
      editor.setCommentData(data);
    }
    return editor;
  }
  serialize(isForCopying = false) {
    if (this.isEmpty()) {
      return null;
    }
    if (this.deleted) {
      return this.serializeDeleted();
    }
    const color = AnnotationEditor._colorManager.convert(this.isAttachedToDOM ? getComputedStyle(this.editorDiv).color : this.color);
    const serialized = Object.assign(super.serialize(isForCopying), {
      color,
      fontSize: this.#fontSize,
      value: this.#serializeContent()
    });
    this.addComment(serialized);
    if (isForCopying) {
      serialized.isCopy = true;
      return serialized;
    }
    if (this.annotationElementId && !this.#hasElementChanged(serialized)) {
      return null;
    }
    serialized.id = this.annotationElementId;
    return serialized;
  }
  #hasElementChanged(serialized) {
    const {
      value,
      fontSize,
      color,
      pageIndex
    } = this._initialData;
    return this.hasEditedComment || this._hasBeenMoved || serialized.value !== value || serialized.fontSize !== fontSize || serialized.color.some((c6, i7) => c6 !== color[i7]) || serialized.pageIndex !== pageIndex;
  }
  renderAnnotationElement(annotation) {
    const content = super.renderAnnotationElement(annotation);
    if (!content) {
      return null;
    }
    const {
      style
    } = content;
    style.fontSize = `calc(${this.#fontSize}px * var(--total-scale-factor))`;
    style.color = this.color;
    content.replaceChildren();
    for (const line of this.#content.split("\n")) {
      const div = document.createElement("div");
      div.append(line ? document.createTextNode(line) : document.createElement("br"));
      content.append(div);
    }
    annotation.updateEdited({
      rect: this.getPDFRect(),
      popup: this._uiManager.hasCommentManager() || this.hasEditedComment ? this.comment : {
        text: this.#content
      }
    });
    return content;
  }
  resetAnnotationElement(annotation) {
    super.resetAnnotationElement(annotation);
    annotation.resetEdited();
  }
};
var Outline = class {
  static PRECISION = 1e-4;
  toSVGPath() {
    unreachable("Abstract method `toSVGPath` must be implemented.");
  }
  get box() {
    unreachable("Abstract getter `box` must be implemented.");
  }
  serialize(_bbox, _rotation) {
    unreachable("Abstract method `serialize` must be implemented.");
  }
  static _rescale(src, tx, ty, sx, sy, dest) {
    dest ||= new Float32Array(src.length);
    for (let i7 = 0, ii = src.length; i7 < ii; i7 += 2) {
      dest[i7] = tx + src[i7] * sx;
      dest[i7 + 1] = ty + src[i7 + 1] * sy;
    }
    return dest;
  }
  static _rescaleAndSwap(src, tx, ty, sx, sy, dest) {
    dest ||= new Float32Array(src.length);
    for (let i7 = 0, ii = src.length; i7 < ii; i7 += 2) {
      dest[i7] = tx + src[i7 + 1] * sx;
      dest[i7 + 1] = ty + src[i7] * sy;
    }
    return dest;
  }
  static _translate(src, tx, ty, dest) {
    dest ||= new Float32Array(src.length);
    for (let i7 = 0, ii = src.length; i7 < ii; i7 += 2) {
      dest[i7] = tx + src[i7];
      dest[i7 + 1] = ty + src[i7 + 1];
    }
    return dest;
  }
  static svgRound(x2) {
    return Math.round(x2 * 1e4);
  }
  static _normalizePoint(x2, y4, parentWidth, parentHeight, rotation) {
    switch (rotation) {
      case 90:
        return [1 - y4 / parentWidth, x2 / parentHeight];
      case 180:
        return [1 - x2 / parentWidth, 1 - y4 / parentHeight];
      case 270:
        return [y4 / parentWidth, 1 - x2 / parentHeight];
      default:
        return [x2 / parentWidth, y4 / parentHeight];
    }
  }
  static _normalizePagePoint(x2, y4, rotation) {
    switch (rotation) {
      case 90:
        return [1 - y4, x2];
      case 180:
        return [1 - x2, 1 - y4];
      case 270:
        return [y4, 1 - x2];
      default:
        return [x2, y4];
    }
  }
  static createBezierPoints(x1, y1, x2, y22, x3, y32) {
    return [(x1 + 5 * x2) / 6, (y1 + 5 * y22) / 6, (5 * x2 + x3) / 6, (5 * y22 + y32) / 6, (x2 + x3) / 2, (y22 + y32) / 2];
  }
};
var FreeDrawOutliner = class _FreeDrawOutliner {
  #box;
  #bottom = [];
  #innerMargin;
  #isLTR;
  #top = [];
  #last = new Float32Array(18);
  #lastX;
  #lastY;
  #min;
  #min_dist;
  #scaleFactor;
  #thickness;
  #points = [];
  static #MIN_DIST = 8;
  static #MIN_DIFF = 2;
  static #MIN = _FreeDrawOutliner.#MIN_DIST + _FreeDrawOutliner.#MIN_DIFF;
  constructor({
    x: x2,
    y: y4
  }, box, scaleFactor, thickness, isLTR, innerMargin = 0) {
    this.#box = box;
    this.#thickness = thickness * scaleFactor;
    this.#isLTR = isLTR;
    this.#last.set([NaN, NaN, NaN, NaN, x2, y4], 6);
    this.#innerMargin = innerMargin;
    this.#min_dist = _FreeDrawOutliner.#MIN_DIST * scaleFactor;
    this.#min = _FreeDrawOutliner.#MIN * scaleFactor;
    this.#scaleFactor = scaleFactor;
    this.#points.push(x2, y4);
  }
  isEmpty() {
    return isNaN(this.#last[8]);
  }
  #getLastCoords() {
    const lastTop = this.#last.subarray(4, 6);
    const lastBottom = this.#last.subarray(16, 18);
    const [x2, y4, width, height] = this.#box;
    return [(this.#lastX + (lastTop[0] - lastBottom[0]) / 2 - x2) / width, (this.#lastY + (lastTop[1] - lastBottom[1]) / 2 - y4) / height, (this.#lastX + (lastBottom[0] - lastTop[0]) / 2 - x2) / width, (this.#lastY + (lastBottom[1] - lastTop[1]) / 2 - y4) / height];
  }
  add({
    x: x2,
    y: y4
  }) {
    this.#lastX = x2;
    this.#lastY = y4;
    const [layerX, layerY, layerWidth, layerHeight] = this.#box;
    let [x1, y1, x22, y22] = this.#last.subarray(8, 12);
    const diffX = x2 - x22;
    const diffY = y4 - y22;
    const d4 = Math.hypot(diffX, diffY);
    if (d4 < this.#min) {
      return false;
    }
    const diffD = d4 - this.#min_dist;
    const K2 = diffD / d4;
    const shiftX = K2 * diffX;
    const shiftY = K2 * diffY;
    let x0 = x1;
    let y0 = y1;
    x1 = x22;
    y1 = y22;
    x22 += shiftX;
    y22 += shiftY;
    this.#points?.push(x2, y4);
    const nX = -shiftY / diffD;
    const nY = shiftX / diffD;
    const thX = nX * this.#thickness;
    const thY = nY * this.#thickness;
    this.#last.set(this.#last.subarray(2, 8), 0);
    this.#last.set([x22 + thX, y22 + thY], 4);
    this.#last.set(this.#last.subarray(14, 18), 12);
    this.#last.set([x22 - thX, y22 - thY], 16);
    if (isNaN(this.#last[6])) {
      if (this.#top.length === 0) {
        this.#last.set([x1 + thX, y1 + thY], 2);
        this.#top.push(NaN, NaN, NaN, NaN, (x1 + thX - layerX) / layerWidth, (y1 + thY - layerY) / layerHeight);
        this.#last.set([x1 - thX, y1 - thY], 14);
        this.#bottom.push(NaN, NaN, NaN, NaN, (x1 - thX - layerX) / layerWidth, (y1 - thY - layerY) / layerHeight);
      }
      this.#last.set([x0, y0, x1, y1, x22, y22], 6);
      return !this.isEmpty();
    }
    this.#last.set([x0, y0, x1, y1, x22, y22], 6);
    const angle = Math.abs(Math.atan2(y0 - y1, x0 - x1) - Math.atan2(shiftY, shiftX));
    if (angle < Math.PI / 2) {
      [x1, y1, x22, y22] = this.#last.subarray(2, 6);
      this.#top.push(NaN, NaN, NaN, NaN, ((x1 + x22) / 2 - layerX) / layerWidth, ((y1 + y22) / 2 - layerY) / layerHeight);
      [x1, y1, x0, y0] = this.#last.subarray(14, 18);
      this.#bottom.push(NaN, NaN, NaN, NaN, ((x0 + x1) / 2 - layerX) / layerWidth, ((y0 + y1) / 2 - layerY) / layerHeight);
      return true;
    }
    [x0, y0, x1, y1, x22, y22] = this.#last.subarray(0, 6);
    this.#top.push(((x0 + 5 * x1) / 6 - layerX) / layerWidth, ((y0 + 5 * y1) / 6 - layerY) / layerHeight, ((5 * x1 + x22) / 6 - layerX) / layerWidth, ((5 * y1 + y22) / 6 - layerY) / layerHeight, ((x1 + x22) / 2 - layerX) / layerWidth, ((y1 + y22) / 2 - layerY) / layerHeight);
    [x22, y22, x1, y1, x0, y0] = this.#last.subarray(12, 18);
    this.#bottom.push(((x0 + 5 * x1) / 6 - layerX) / layerWidth, ((y0 + 5 * y1) / 6 - layerY) / layerHeight, ((5 * x1 + x22) / 6 - layerX) / layerWidth, ((5 * y1 + y22) / 6 - layerY) / layerHeight, ((x1 + x22) / 2 - layerX) / layerWidth, ((y1 + y22) / 2 - layerY) / layerHeight);
    return true;
  }
  toSVGPath() {
    if (this.isEmpty()) {
      return "";
    }
    const top = this.#top;
    const bottom = this.#bottom;
    if (isNaN(this.#last[6]) && !this.isEmpty()) {
      return this.#toSVGPathTwoPoints();
    }
    const buffer = [];
    buffer.push(`M${top[4]} ${top[5]}`);
    for (let i7 = 6; i7 < top.length; i7 += 6) {
      if (isNaN(top[i7])) {
        buffer.push(`L${top[i7 + 4]} ${top[i7 + 5]}`);
      } else {
        buffer.push(`C${top[i7]} ${top[i7 + 1]} ${top[i7 + 2]} ${top[i7 + 3]} ${top[i7 + 4]} ${top[i7 + 5]}`);
      }
    }
    this.#toSVGPathEnd(buffer);
    for (let i7 = bottom.length - 6; i7 >= 6; i7 -= 6) {
      if (isNaN(bottom[i7])) {
        buffer.push(`L${bottom[i7 + 4]} ${bottom[i7 + 5]}`);
      } else {
        buffer.push(`C${bottom[i7]} ${bottom[i7 + 1]} ${bottom[i7 + 2]} ${bottom[i7 + 3]} ${bottom[i7 + 4]} ${bottom[i7 + 5]}`);
      }
    }
    this.#toSVGPathStart(buffer);
    return buffer.join(" ");
  }
  #toSVGPathTwoPoints() {
    const [x2, y4, width, height] = this.#box;
    const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords();
    return `M${(this.#last[2] - x2) / width} ${(this.#last[3] - y4) / height} L${(this.#last[4] - x2) / width} ${(this.#last[5] - y4) / height} L${lastTopX} ${lastTopY} L${lastBottomX} ${lastBottomY} L${(this.#last[16] - x2) / width} ${(this.#last[17] - y4) / height} L${(this.#last[14] - x2) / width} ${(this.#last[15] - y4) / height} Z`;
  }
  #toSVGPathStart(buffer) {
    const bottom = this.#bottom;
    buffer.push(`L${bottom[4]} ${bottom[5]} Z`);
  }
  #toSVGPathEnd(buffer) {
    const [x2, y4, width, height] = this.#box;
    const lastTop = this.#last.subarray(4, 6);
    const lastBottom = this.#last.subarray(16, 18);
    const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords();
    buffer.push(`L${(lastTop[0] - x2) / width} ${(lastTop[1] - y4) / height} L${lastTopX} ${lastTopY} L${lastBottomX} ${lastBottomY} L${(lastBottom[0] - x2) / width} ${(lastBottom[1] - y4) / height}`);
  }
  newFreeDrawOutline(outline, points, box, scaleFactor, innerMargin, isLTR) {
    return new FreeDrawOutline(outline, points, box, scaleFactor, innerMargin, isLTR);
  }
  getOutlines() {
    const top = this.#top;
    const bottom = this.#bottom;
    const last = this.#last;
    const [layerX, layerY, layerWidth, layerHeight] = this.#box;
    const points = new Float32Array((this.#points?.length ?? 0) + 2);
    for (let i7 = 0, ii = points.length - 2; i7 < ii; i7 += 2) {
      points[i7] = (this.#points[i7] - layerX) / layerWidth;
      points[i7 + 1] = (this.#points[i7 + 1] - layerY) / layerHeight;
    }
    points[points.length - 2] = (this.#lastX - layerX) / layerWidth;
    points[points.length - 1] = (this.#lastY - layerY) / layerHeight;
    if (isNaN(last[6]) && !this.isEmpty()) {
      return this.#getOutlineTwoPoints(points);
    }
    const outline = new Float32Array(this.#top.length + 24 + this.#bottom.length);
    let N3 = top.length;
    for (let i7 = 0; i7 < N3; i7 += 2) {
      if (isNaN(top[i7])) {
        outline[i7] = outline[i7 + 1] = NaN;
        continue;
      }
      outline[i7] = top[i7];
      outline[i7 + 1] = top[i7 + 1];
    }
    N3 = this.#getOutlineEnd(outline, N3);
    for (let i7 = bottom.length - 6; i7 >= 6; i7 -= 6) {
      for (let j3 = 0; j3 < 6; j3 += 2) {
        if (isNaN(bottom[i7 + j3])) {
          outline[N3] = outline[N3 + 1] = NaN;
          N3 += 2;
          continue;
        }
        outline[N3] = bottom[i7 + j3];
        outline[N3 + 1] = bottom[i7 + j3 + 1];
        N3 += 2;
      }
    }
    this.#getOutlineStart(outline, N3);
    return this.newFreeDrawOutline(outline, points, this.#box, this.#scaleFactor, this.#innerMargin, this.#isLTR);
  }
  #getOutlineTwoPoints(points) {
    const last = this.#last;
    const [layerX, layerY, layerWidth, layerHeight] = this.#box;
    const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords();
    const outline = new Float32Array(36);
    outline.set([NaN, NaN, NaN, NaN, (last[2] - layerX) / layerWidth, (last[3] - layerY) / layerHeight, NaN, NaN, NaN, NaN, (last[4] - layerX) / layerWidth, (last[5] - layerY) / layerHeight, NaN, NaN, NaN, NaN, lastTopX, lastTopY, NaN, NaN, NaN, NaN, lastBottomX, lastBottomY, NaN, NaN, NaN, NaN, (last[16] - layerX) / layerWidth, (last[17] - layerY) / layerHeight, NaN, NaN, NaN, NaN, (last[14] - layerX) / layerWidth, (last[15] - layerY) / layerHeight], 0);
    return this.newFreeDrawOutline(outline, points, this.#box, this.#scaleFactor, this.#innerMargin, this.#isLTR);
  }
  #getOutlineStart(outline, pos) {
    const bottom = this.#bottom;
    outline.set([NaN, NaN, NaN, NaN, bottom[4], bottom[5]], pos);
    return pos += 6;
  }
  #getOutlineEnd(outline, pos) {
    const lastTop = this.#last.subarray(4, 6);
    const lastBottom = this.#last.subarray(16, 18);
    const [layerX, layerY, layerWidth, layerHeight] = this.#box;
    const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords();
    outline.set([NaN, NaN, NaN, NaN, (lastTop[0] - layerX) / layerWidth, (lastTop[1] - layerY) / layerHeight, NaN, NaN, NaN, NaN, lastTopX, lastTopY, NaN, NaN, NaN, NaN, lastBottomX, lastBottomY, NaN, NaN, NaN, NaN, (lastBottom[0] - layerX) / layerWidth, (lastBottom[1] - layerY) / layerHeight], pos);
    return pos += 24;
  }
};
var FreeDrawOutline = class extends Outline {
  #box;
  #bbox = new Float32Array(4);
  #innerMargin;
  #isLTR;
  #points;
  #scaleFactor;
  #outline;
  constructor(outline, points, box, scaleFactor, innerMargin, isLTR) {
    super();
    this.#outline = outline;
    this.#points = points;
    this.#box = box;
    this.#scaleFactor = scaleFactor;
    this.#innerMargin = innerMargin;
    this.#isLTR = isLTR;
    this.firstPoint = [NaN, NaN];
    this.lastPoint = [NaN, NaN];
    this.#computeMinMax(isLTR);
    const [x2, y4, width, height] = this.#bbox;
    for (let i7 = 0, ii = outline.length; i7 < ii; i7 += 2) {
      outline[i7] = (outline[i7] - x2) / width;
      outline[i7 + 1] = (outline[i7 + 1] - y4) / height;
    }
    for (let i7 = 0, ii = points.length; i7 < ii; i7 += 2) {
      points[i7] = (points[i7] - x2) / width;
      points[i7 + 1] = (points[i7 + 1] - y4) / height;
    }
  }
  toSVGPath() {
    const buffer = [`M${this.#outline[4]} ${this.#outline[5]}`];
    for (let i7 = 6, ii = this.#outline.length; i7 < ii; i7 += 6) {
      if (isNaN(this.#outline[i7])) {
        buffer.push(`L${this.#outline[i7 + 4]} ${this.#outline[i7 + 5]}`);
        continue;
      }
      buffer.push(`C${this.#outline[i7]} ${this.#outline[i7 + 1]} ${this.#outline[i7 + 2]} ${this.#outline[i7 + 3]} ${this.#outline[i7 + 4]} ${this.#outline[i7 + 5]}`);
    }
    buffer.push("Z");
    return buffer.join(" ");
  }
  serialize([blX, blY, trX, trY], rotation) {
    const width = trX - blX;
    const height = trY - blY;
    let outline;
    let points;
    switch (rotation) {
      case 0:
        outline = Outline._rescale(this.#outline, blX, trY, width, -height);
        points = Outline._rescale(this.#points, blX, trY, width, -height);
        break;
      case 90:
        outline = Outline._rescaleAndSwap(this.#outline, blX, blY, width, height);
        points = Outline._rescaleAndSwap(this.#points, blX, blY, width, height);
        break;
      case 180:
        outline = Outline._rescale(this.#outline, trX, blY, -width, height);
        points = Outline._rescale(this.#points, trX, blY, -width, height);
        break;
      case 270:
        outline = Outline._rescaleAndSwap(this.#outline, trX, trY, -width, -height);
        points = Outline._rescaleAndSwap(this.#points, trX, trY, -width, -height);
        break;
    }
    return {
      outline: Array.from(outline),
      points: [Array.from(points)]
    };
  }
  #computeMinMax(isLTR) {
    const outline = this.#outline;
    let lastX = outline[4];
    let lastY = outline[5];
    const minMax = [lastX, lastY, lastX, lastY];
    let firstPointX = lastX;
    let firstPointY = lastY;
    let lastPointX = lastX;
    let lastPointY = lastY;
    const ltrCallback = isLTR ? Math.max : Math.min;
    const bezierBbox = new Float32Array(4);
    for (let i7 = 6, ii = outline.length; i7 < ii; i7 += 6) {
      const x2 = outline[i7 + 4], y4 = outline[i7 + 5];
      if (isNaN(outline[i7])) {
        Util.pointBoundingBox(x2, y4, minMax);
        if (firstPointY > y4) {
          firstPointX = x2;
          firstPointY = y4;
        } else if (firstPointY === y4) {
          firstPointX = ltrCallback(firstPointX, x2);
        }
        if (lastPointY < y4) {
          lastPointX = x2;
          lastPointY = y4;
        } else if (lastPointY === y4) {
          lastPointX = ltrCallback(lastPointX, x2);
        }
      } else {
        bezierBbox[0] = bezierBbox[1] = Infinity;
        bezierBbox[2] = bezierBbox[3] = -Infinity;
        Util.bezierBoundingBox(lastX, lastY, ...outline.slice(i7, i7 + 6), bezierBbox);
        Util.rectBoundingBox(bezierBbox[0], bezierBbox[1], bezierBbox[2], bezierBbox[3], minMax);
        if (firstPointY > bezierBbox[1]) {
          firstPointX = bezierBbox[0];
          firstPointY = bezierBbox[1];
        } else if (firstPointY === bezierBbox[1]) {
          firstPointX = ltrCallback(firstPointX, bezierBbox[0]);
        }
        if (lastPointY < bezierBbox[3]) {
          lastPointX = bezierBbox[2];
          lastPointY = bezierBbox[3];
        } else if (lastPointY === bezierBbox[3]) {
          lastPointX = ltrCallback(lastPointX, bezierBbox[2]);
        }
      }
      lastX = x2;
      lastY = y4;
    }
    const bbox = this.#bbox;
    bbox[0] = minMax[0] - this.#innerMargin;
    bbox[1] = minMax[1] - this.#innerMargin;
    bbox[2] = minMax[2] - minMax[0] + 2 * this.#innerMargin;
    bbox[3] = minMax[3] - minMax[1] + 2 * this.#innerMargin;
    this.firstPoint = [firstPointX, firstPointY];
    this.lastPoint = [lastPointX, lastPointY];
  }
  get box() {
    return this.#bbox;
  }
  newOutliner(point, box, scaleFactor, thickness, isLTR, innerMargin = 0) {
    return new FreeDrawOutliner(point, box, scaleFactor, thickness, isLTR, innerMargin);
  }
  getNewOutline(thickness, innerMargin) {
    const [x2, y4, width, height] = this.#bbox;
    const [layerX, layerY, layerWidth, layerHeight] = this.#box;
    const sx = width * layerWidth;
    const sy = height * layerHeight;
    const tx = x2 * layerWidth + layerX;
    const ty = y4 * layerHeight + layerY;
    const outliner = this.newOutliner({
      x: this.#points[0] * sx + tx,
      y: this.#points[1] * sy + ty
    }, this.#box, this.#scaleFactor, thickness, this.#isLTR, innerMargin ?? this.#innerMargin);
    for (let i7 = 2; i7 < this.#points.length; i7 += 2) {
      outliner.add({
        x: this.#points[i7] * sx + tx,
        y: this.#points[i7 + 1] * sy + ty
      });
    }
    return outliner.getOutlines();
  }
};
var HighlightOutliner = class {
  #box;
  #firstPoint;
  #lastPoint;
  #verticalEdges = [];
  #intervals = [];
  constructor(boxes, borderWidth = 0, innerMargin = 0, isLTR = true) {
    const minMax = [Infinity, Infinity, -Infinity, -Infinity];
    const NUMBER_OF_DIGITS = 4;
    const EPSILON = 10 ** -NUMBER_OF_DIGITS;
    for (const {
      x: x2,
      y: y4,
      width,
      height
    } of boxes) {
      const x1 = Math.floor((x2 - borderWidth) / EPSILON) * EPSILON;
      const x22 = Math.ceil((x2 + width + borderWidth) / EPSILON) * EPSILON;
      const y1 = Math.floor((y4 - borderWidth) / EPSILON) * EPSILON;
      const y22 = Math.ceil((y4 + height + borderWidth) / EPSILON) * EPSILON;
      const left = [x1, y1, y22, true];
      const right = [x22, y1, y22, false];
      this.#verticalEdges.push(left, right);
      Util.rectBoundingBox(x1, y1, x22, y22, minMax);
    }
    const bboxWidth = minMax[2] - minMax[0] + 2 * innerMargin;
    const bboxHeight = minMax[3] - minMax[1] + 2 * innerMargin;
    const shiftedMinX = minMax[0] - innerMargin;
    const shiftedMinY = minMax[1] - innerMargin;
    let firstPointX = isLTR ? -Infinity : Infinity;
    let firstPointY = Infinity;
    const lastEdge = this.#verticalEdges.at(isLTR ? -1 : -2);
    const lastPoint = [lastEdge[0], lastEdge[2]];
    for (const edge of this.#verticalEdges) {
      const [x2, y1, y22, left] = edge;
      if (!left && isLTR) {
        if (y1 < firstPointY) {
          firstPointY = y1;
          firstPointX = x2;
        } else if (y1 === firstPointY) {
          firstPointX = Math.max(firstPointX, x2);
        }
      } else if (left && !isLTR) {
        if (y1 < firstPointY) {
          firstPointY = y1;
          firstPointX = x2;
        } else if (y1 === firstPointY) {
          firstPointX = Math.min(firstPointX, x2);
        }
      }
      edge[0] = (x2 - shiftedMinX) / bboxWidth;
      edge[1] = (y1 - shiftedMinY) / bboxHeight;
      edge[2] = (y22 - shiftedMinY) / bboxHeight;
    }
    this.#box = new Float32Array([shiftedMinX, shiftedMinY, bboxWidth, bboxHeight]);
    this.#firstPoint = [firstPointX, firstPointY];
    this.#lastPoint = lastPoint;
  }
  getOutlines() {
    this.#verticalEdges.sort((a3, b4) => a3[0] - b4[0] || a3[1] - b4[1] || a3[2] - b4[2]);
    const outlineVerticalEdges = [];
    for (const edge of this.#verticalEdges) {
      if (edge[3]) {
        outlineVerticalEdges.push(...this.#breakEdge(edge));
        this.#insert(edge);
      } else {
        this.#remove(edge);
        outlineVerticalEdges.push(...this.#breakEdge(edge));
      }
    }
    return this.#getOutlines(outlineVerticalEdges);
  }
  #getOutlines(outlineVerticalEdges) {
    const edges = [];
    const allEdges = /* @__PURE__ */ new Set();
    for (const edge of outlineVerticalEdges) {
      const [x2, y1, y22] = edge;
      edges.push([x2, y1, edge], [x2, y22, edge]);
    }
    edges.sort((a3, b4) => a3[1] - b4[1] || a3[0] - b4[0]);
    for (let i7 = 0, ii = edges.length; i7 < ii; i7 += 2) {
      const edge1 = edges[i7][2];
      const edge2 = edges[i7 + 1][2];
      edge1.push(edge2);
      edge2.push(edge1);
      allEdges.add(edge1);
      allEdges.add(edge2);
    }
    const outlines = [];
    let outline;
    while (allEdges.size > 0) {
      const edge = allEdges.values().next().value;
      let [x2, y1, y22, edge1, edge2] = edge;
      allEdges.delete(edge);
      let lastPointX = x2;
      let lastPointY = y1;
      outline = [x2, y22];
      outlines.push(outline);
      while (true) {
        let e9;
        if (allEdges.has(edge1)) {
          e9 = edge1;
        } else if (allEdges.has(edge2)) {
          e9 = edge2;
        } else {
          break;
        }
        allEdges.delete(e9);
        [x2, y1, y22, edge1, edge2] = e9;
        if (lastPointX !== x2) {
          outline.push(lastPointX, lastPointY, x2, lastPointY === y1 ? y1 : y22);
          lastPointX = x2;
        }
        lastPointY = lastPointY === y1 ? y22 : y1;
      }
      outline.push(lastPointX, lastPointY);
    }
    return new HighlightOutline(outlines, this.#box, this.#firstPoint, this.#lastPoint);
  }
  #binarySearch(y4) {
    const array = this.#intervals;
    let start = 0;
    let end = array.length - 1;
    while (start <= end) {
      const middle = start + end >> 1;
      const y1 = array[middle][0];
      if (y1 === y4) {
        return middle;
      }
      if (y1 < y4) {
        start = middle + 1;
      } else {
        end = middle - 1;
      }
    }
    return end + 1;
  }
  #insert([, y1, y22]) {
    const index = this.#binarySearch(y1);
    this.#intervals.splice(index, 0, [y1, y22]);
  }
  #remove([, y1, y22]) {
    const index = this.#binarySearch(y1);
    for (let i7 = index; i7 < this.#intervals.length; i7++) {
      const [start, end] = this.#intervals[i7];
      if (start !== y1) {
        break;
      }
      if (start === y1 && end === y22) {
        this.#intervals.splice(i7, 1);
        return;
      }
    }
    for (let i7 = index - 1; i7 >= 0; i7--) {
      const [start, end] = this.#intervals[i7];
      if (start !== y1) {
        break;
      }
      if (start === y1 && end === y22) {
        this.#intervals.splice(i7, 1);
        return;
      }
    }
  }
  #breakEdge(edge) {
    const [x2, y1, y22] = edge;
    const results = [[x2, y1, y22]];
    const index = this.#binarySearch(y22);
    for (let i7 = 0; i7 < index; i7++) {
      const [start, end] = this.#intervals[i7];
      for (let j3 = 0, jj = results.length; j3 < jj; j3++) {
        const [, y32, y4] = results[j3];
        if (end <= y32 || y4 <= start) {
          continue;
        }
        if (y32 >= start) {
          if (y4 > end) {
            results[j3][1] = end;
          } else {
            if (jj === 1) {
              return [];
            }
            results.splice(j3, 1);
            j3--;
            jj--;
          }
          continue;
        }
        results[j3][2] = start;
        if (y4 > end) {
          results.push([x2, end, y4]);
        }
      }
    }
    return results;
  }
};
var HighlightOutline = class extends Outline {
  #box;
  #outlines;
  constructor(outlines, box, firstPoint, lastPoint) {
    super();
    this.#outlines = outlines;
    this.#box = box;
    this.firstPoint = firstPoint;
    this.lastPoint = lastPoint;
  }
  toSVGPath() {
    const buffer = [];
    for (const polygon of this.#outlines) {
      let [prevX, prevY] = polygon;
      buffer.push(`M${prevX} ${prevY}`);
      for (let i7 = 2; i7 < polygon.length; i7 += 2) {
        const x2 = polygon[i7];
        const y4 = polygon[i7 + 1];
        if (x2 === prevX) {
          buffer.push(`V${y4}`);
          prevY = y4;
        } else if (y4 === prevY) {
          buffer.push(`H${x2}`);
          prevX = x2;
        }
      }
      buffer.push("Z");
    }
    return buffer.join(" ");
  }
  serialize([blX, blY, trX, trY], _rotation) {
    const outlines = [];
    const width = trX - blX;
    const height = trY - blY;
    for (const outline of this.#outlines) {
      const points = new Array(outline.length);
      for (let i7 = 0; i7 < outline.length; i7 += 2) {
        points[i7] = blX + outline[i7] * width;
        points[i7 + 1] = trY - outline[i7 + 1] * height;
      }
      outlines.push(points);
    }
    return outlines;
  }
  get box() {
    return this.#box;
  }
  get classNamesForOutlining() {
    return ["highlightOutline"];
  }
};
var FreeHighlightOutliner = class extends FreeDrawOutliner {
  newFreeDrawOutline(outline, points, box, scaleFactor, innerMargin, isLTR) {
    return new FreeHighlightOutline(outline, points, box, scaleFactor, innerMargin, isLTR);
  }
};
var FreeHighlightOutline = class extends FreeDrawOutline {
  newOutliner(point, box, scaleFactor, thickness, isLTR, innerMargin = 0) {
    return new FreeHighlightOutliner(point, box, scaleFactor, thickness, isLTR, innerMargin);
  }
};
var HighlightEditor = class _HighlightEditor extends AnnotationEditor {
  #anchorNode = null;
  #anchorOffset = 0;
  #boxes;
  #clipPathId = null;
  #colorPicker = null;
  #focusOutlines = null;
  #focusNode = null;
  #focusOffset = 0;
  #highlightDiv = null;
  #highlightOutlines = null;
  #id = null;
  #isFreeHighlight = false;
  #firstPoint = null;
  #lastPoint = null;
  #outlineId = null;
  #text = "";
  #thickness;
  #methodOfCreation = "";
  static _defaultColor = null;
  static _defaultOpacity = 1;
  static _defaultThickness = 12;
  static _type = "highlight";
  static _editorType = AnnotationEditorType.HIGHLIGHT;
  static _freeHighlightId = -1;
  static _freeHighlight = null;
  static _freeHighlightClipId = "";
  static get _keyboardManager() {
    const proto = _HighlightEditor.prototype;
    return shadow(this, "_keyboardManager", new KeyboardManager([[["ArrowLeft", "mac+ArrowLeft"], proto._moveCaret, {
      args: [0]
    }], [["ArrowRight", "mac+ArrowRight"], proto._moveCaret, {
      args: [1]
    }], [["ArrowUp", "mac+ArrowUp"], proto._moveCaret, {
      args: [2]
    }], [["ArrowDown", "mac+ArrowDown"], proto._moveCaret, {
      args: [3]
    }]]));
  }
  constructor(params) {
    super({
      ...params,
      name: "highlightEditor"
    });
    this.color = params.color || _HighlightEditor._defaultColor;
    this.#thickness = params.thickness || _HighlightEditor._defaultThickness;
    this.opacity = params.opacity || _HighlightEditor._defaultOpacity;
    this.#boxes = params.boxes || null;
    this.#methodOfCreation = params.methodOfCreation || "";
    this.#text = params.text || "";
    this._isDraggable = false;
    this.defaultL10nId = "pdfjs-editor-highlight-editor";
    if (params.highlightId > -1) {
      this.#isFreeHighlight = true;
      this.#createFreeOutlines(params);
      this.#addToDrawLayer();
    } else if (this.#boxes) {
      this.#anchorNode = params.anchorNode;
      this.#anchorOffset = params.anchorOffset;
      this.#focusNode = params.focusNode;
      this.#focusOffset = params.focusOffset;
      this.#createOutlines();
      this.#addToDrawLayer();
      this.rotate(this.rotation);
    }
    if (!this.annotationElementId) {
      this._uiManager.a11yAlert("pdfjs-editor-highlight-added-alert");
    }
  }
  get telemetryInitialData() {
    return {
      action: "added",
      type: this.#isFreeHighlight ? "free_highlight" : "highlight",
      color: this._uiManager.getNonHCMColorName(this.color),
      thickness: this.#thickness,
      methodOfCreation: this.#methodOfCreation
    };
  }
  get telemetryFinalData() {
    return {
      type: "highlight",
      color: this._uiManager.getNonHCMColorName(this.color)
    };
  }
  static computeTelemetryFinalData(data) {
    return {
      numberOfColors: data.get("color").size
    };
  }
  #createOutlines() {
    const outliner = new HighlightOutliner(this.#boxes, 1e-3);
    this.#highlightOutlines = outliner.getOutlines();
    [this.x, this.y, this.width, this.height] = this.#highlightOutlines.box;
    const outlinerForOutline = new HighlightOutliner(this.#boxes, 25e-4, 1e-3, this._uiManager.direction === "ltr");
    this.#focusOutlines = outlinerForOutline.getOutlines();
    const {
      firstPoint
    } = this.#highlightOutlines;
    this.#firstPoint = [(firstPoint[0] - this.x) / this.width, (firstPoint[1] - this.y) / this.height];
    const {
      lastPoint
    } = this.#focusOutlines;
    this.#lastPoint = [(lastPoint[0] - this.x) / this.width, (lastPoint[1] - this.y) / this.height];
  }
  #createFreeOutlines({
    highlightOutlines,
    highlightId,
    clipPathId
  }) {
    this.#highlightOutlines = highlightOutlines;
    const extraThickness = 1.5;
    this.#focusOutlines = highlightOutlines.getNewOutline(this.#thickness / 2 + extraThickness, 25e-4);
    if (highlightId >= 0) {
      this.#id = highlightId;
      this.#clipPathId = clipPathId;
      this.parent.drawLayer.finalizeDraw(highlightId, {
        bbox: highlightOutlines.box,
        path: {
          d: highlightOutlines.toSVGPath()
        }
      });
      this.#outlineId = this.parent.drawLayer.drawOutline({
        rootClass: {
          highlightOutline: true,
          free: true
        },
        bbox: this.#focusOutlines.box,
        path: {
          d: this.#focusOutlines.toSVGPath()
        }
      }, true);
    } else if (this.parent) {
      const angle = this.parent.viewport.rotation;
      this.parent.drawLayer.updateProperties(this.#id, {
        bbox: _HighlightEditor.#rotateBbox(this.#highlightOutlines.box, (angle - this.rotation + 360) % 360),
        path: {
          d: highlightOutlines.toSVGPath()
        }
      });
      this.parent.drawLayer.updateProperties(this.#outlineId, {
        bbox: _HighlightEditor.#rotateBbox(this.#focusOutlines.box, angle),
        path: {
          d: this.#focusOutlines.toSVGPath()
        }
      });
    }
    const [x2, y4, width, height] = highlightOutlines.box;
    switch (this.rotation) {
      case 0:
        this.x = x2;
        this.y = y4;
        this.width = width;
        this.height = height;
        break;
      case 90: {
        const [pageWidth, pageHeight] = this.parentDimensions;
        this.x = y4;
        this.y = 1 - x2;
        this.width = width * pageHeight / pageWidth;
        this.height = height * pageWidth / pageHeight;
        break;
      }
      case 180:
        this.x = 1 - x2;
        this.y = 1 - y4;
        this.width = width;
        this.height = height;
        break;
      case 270: {
        const [pageWidth, pageHeight] = this.parentDimensions;
        this.x = 1 - y4;
        this.y = x2;
        this.width = width * pageHeight / pageWidth;
        this.height = height * pageWidth / pageHeight;
        break;
      }
    }
    const {
      firstPoint
    } = highlightOutlines;
    this.#firstPoint = [(firstPoint[0] - x2) / width, (firstPoint[1] - y4) / height];
    const {
      lastPoint
    } = this.#focusOutlines;
    this.#lastPoint = [(lastPoint[0] - x2) / width, (lastPoint[1] - y4) / height];
  }
  static initialize(l10n, uiManager) {
    AnnotationEditor.initialize(l10n, uiManager);
    _HighlightEditor._defaultColor ||= uiManager.highlightColors?.values().next().value || "#fff066";
  }
  static updateDefaultParams(type, value) {
    switch (type) {
      case AnnotationEditorParamsType.HIGHLIGHT_COLOR:
        _HighlightEditor._defaultColor = value;
        break;
      case AnnotationEditorParamsType.HIGHLIGHT_THICKNESS:
        _HighlightEditor._defaultThickness = value;
        break;
    }
  }
  translateInPage(x2, y4) {
  }
  get toolbarPosition() {
    return this.#lastPoint;
  }
  get commentButtonPosition() {
    return this.#firstPoint;
  }
  updateParams(type, value) {
    switch (type) {
      case AnnotationEditorParamsType.HIGHLIGHT_COLOR:
        this.#updateColor(value);
        break;
      case AnnotationEditorParamsType.HIGHLIGHT_THICKNESS:
        this.#updateThickness(value);
        break;
    }
  }
  static get defaultPropertiesToUpdate() {
    return [[AnnotationEditorParamsType.HIGHLIGHT_COLOR, _HighlightEditor._defaultColor], [AnnotationEditorParamsType.HIGHLIGHT_THICKNESS, _HighlightEditor._defaultThickness]];
  }
  get propertiesToUpdate() {
    return [[AnnotationEditorParamsType.HIGHLIGHT_COLOR, this.color || _HighlightEditor._defaultColor], [AnnotationEditorParamsType.HIGHLIGHT_THICKNESS, this.#thickness || _HighlightEditor._defaultThickness], [AnnotationEditorParamsType.HIGHLIGHT_FREE, this.#isFreeHighlight]];
  }
  onUpdatedColor() {
    this.parent?.drawLayer.updateProperties(this.#id, {
      root: {
        fill: this.color,
        "fill-opacity": this.opacity
      }
    });
    this.#colorPicker?.updateColor(this.color);
    super.onUpdatedColor();
  }
  #updateColor(color) {
    const setColorAndOpacity = (col, opa) => {
      this.color = col;
      this.opacity = opa;
      this.onUpdatedColor();
    };
    const savedColor = this.color;
    const savedOpacity = this.opacity;
    this.addCommands({
      cmd: setColorAndOpacity.bind(this, color, _HighlightEditor._defaultOpacity),
      undo: setColorAndOpacity.bind(this, savedColor, savedOpacity),
      post: this._uiManager.updateUI.bind(this._uiManager, this),
      mustExec: true,
      type: AnnotationEditorParamsType.HIGHLIGHT_COLOR,
      overwriteIfSameType: true,
      keepUndo: true
    });
    this._reportTelemetry({
      action: "color_changed",
      color: this._uiManager.getNonHCMColorName(color)
    }, true);
  }
  #updateThickness(thickness) {
    const savedThickness = this.#thickness;
    const setThickness = (th) => {
      this.#thickness = th;
      this.#changeThickness(th);
    };
    this.addCommands({
      cmd: setThickness.bind(this, thickness),
      undo: setThickness.bind(this, savedThickness),
      post: this._uiManager.updateUI.bind(this._uiManager, this),
      mustExec: true,
      type: AnnotationEditorParamsType.INK_THICKNESS,
      overwriteIfSameType: true,
      keepUndo: true
    });
    this._reportTelemetry({
      action: "thickness_changed",
      thickness
    }, true);
  }
  get toolbarButtons() {
    if (this._uiManager.highlightColors) {
      const colorPicker = this.#colorPicker = new ColorPicker({
        editor: this
      });
      return [["colorPicker", colorPicker]];
    }
    return super.toolbarButtons;
  }
  disableEditing() {
    super.disableEditing();
    this.div.classList.toggle("disabled", true);
  }
  enableEditing() {
    super.enableEditing();
    this.div.classList.toggle("disabled", false);
  }
  fixAndSetPosition() {
    return super.fixAndSetPosition(this.#getRotation());
  }
  getBaseTranslation() {
    return [0, 0];
  }
  getRect(tx, ty) {
    return super.getRect(tx, ty, this.#getRotation());
  }
  onceAdded(focus) {
    if (!this.annotationElementId) {
      this.parent.addUndoableEditor(this);
    }
    if (focus) {
      this.div.focus();
    }
  }
  remove() {
    this.#cleanDrawLayer();
    this._reportTelemetry({
      action: "deleted"
    });
    super.remove();
  }
  rebuild() {
    if (!this.parent) {
      return;
    }
    super.rebuild();
    if (this.div === null) {
      return;
    }
    this.#addToDrawLayer();
    if (!this.isAttachedToDOM) {
      this.parent.add(this);
    }
  }
  setParent(parent) {
    let mustBeSelected = false;
    if (this.parent && !parent) {
      this.#cleanDrawLayer();
    } else if (parent) {
      this.#addToDrawLayer(parent);
      mustBeSelected = !this.parent && this.div?.classList.contains("selectedEditor");
    }
    super.setParent(parent);
    this.show(this._isVisible);
    if (mustBeSelected) {
      this.select();
    }
  }
  #changeThickness(thickness) {
    if (!this.#isFreeHighlight) {
      return;
    }
    this.#createFreeOutlines({
      highlightOutlines: this.#highlightOutlines.getNewOutline(thickness / 2)
    });
    this.fixAndSetPosition();
    this.setDims();
  }
  #cleanDrawLayer() {
    if (this.#id === null || !this.parent) {
      return;
    }
    this.parent.drawLayer.remove(this.#id);
    this.#id = null;
    this.parent.drawLayer.remove(this.#outlineId);
    this.#outlineId = null;
  }
  #addToDrawLayer(parent = this.parent) {
    if (this.#id !== null) {
      return;
    }
    ({
      id: this.#id,
      clipPathId: this.#clipPathId
    } = parent.drawLayer.draw({
      bbox: this.#highlightOutlines.box,
      root: {
        viewBox: "0 0 1 1",
        fill: this.color,
        "fill-opacity": this.opacity
      },
      rootClass: {
        highlight: true,
        free: this.#isFreeHighlight
      },
      path: {
        d: this.#highlightOutlines.toSVGPath()
      }
    }, false, true));
    this.#outlineId = parent.drawLayer.drawOutline({
      rootClass: {
        highlightOutline: true,
        free: this.#isFreeHighlight
      },
      bbox: this.#focusOutlines.box,
      path: {
        d: this.#focusOutlines.toSVGPath()
      }
    }, this.#isFreeHighlight);
    if (this.#highlightDiv) {
      this.#highlightDiv.style.clipPath = this.#clipPathId;
    }
  }
  static #rotateBbox([x2, y4, width, height], angle) {
    switch (angle) {
      case 90:
        return [1 - y4 - height, x2, height, width];
      case 180:
        return [1 - x2 - width, 1 - y4 - height, width, height];
      case 270:
        return [y4, 1 - x2 - width, height, width];
    }
    return [x2, y4, width, height];
  }
  rotate(angle) {
    const {
      drawLayer
    } = this.parent;
    let box;
    if (this.#isFreeHighlight) {
      angle = (angle - this.rotation + 360) % 360;
      box = _HighlightEditor.#rotateBbox(this.#highlightOutlines.box, angle);
    } else {
      box = _HighlightEditor.#rotateBbox([this.x, this.y, this.width, this.height], angle);
    }
    drawLayer.updateProperties(this.#id, {
      bbox: box,
      root: {
        "data-main-rotation": angle
      }
    });
    drawLayer.updateProperties(this.#outlineId, {
      bbox: _HighlightEditor.#rotateBbox(this.#focusOutlines.box, angle),
      root: {
        "data-main-rotation": angle
      }
    });
  }
  render() {
    if (this.div) {
      return this.div;
    }
    const div = super.render();
    if (this.#text) {
      div.setAttribute("aria-label", this.#text);
      div.setAttribute("role", "mark");
    }
    if (this.#isFreeHighlight) {
      div.classList.add("free");
    } else {
      this.div.addEventListener("keydown", this.#keydown.bind(this), {
        signal: this._uiManager._signal
      });
    }
    const highlightDiv = this.#highlightDiv = document.createElement("div");
    div.append(highlightDiv);
    highlightDiv.setAttribute("aria-hidden", "true");
    highlightDiv.className = "internal";
    highlightDiv.style.clipPath = this.#clipPathId;
    this.setDims();
    bindEvents(this, this.#highlightDiv, ["pointerover", "pointerleave"]);
    this.enableEditing();
    return div;
  }
  pointerover() {
    if (!this.isSelected) {
      this.parent?.drawLayer.updateProperties(this.#outlineId, {
        rootClass: {
          hovered: true
        }
      });
    }
  }
  pointerleave() {
    if (!this.isSelected) {
      this.parent?.drawLayer.updateProperties(this.#outlineId, {
        rootClass: {
          hovered: false
        }
      });
    }
  }
  #keydown(event) {
    _HighlightEditor._keyboardManager.exec(this, event);
  }
  _moveCaret(direction) {
    this.parent.unselect(this);
    switch (direction) {
      case 0:
      case 2:
        this.#setCaret(true);
        break;
      case 1:
      case 3:
        this.#setCaret(false);
        break;
    }
  }
  #setCaret(start) {
    if (!this.#anchorNode) {
      return;
    }
    const selection = window.getSelection();
    if (start) {
      selection.setPosition(this.#anchorNode, this.#anchorOffset);
    } else {
      selection.setPosition(this.#focusNode, this.#focusOffset);
    }
  }
  select() {
    super.select();
    if (!this.#outlineId) {
      return;
    }
    this.parent?.drawLayer.updateProperties(this.#outlineId, {
      rootClass: {
        hovered: false,
        selected: true
      }
    });
  }
  unselect() {
    super.unselect();
    if (!this.#outlineId) {
      return;
    }
    this.parent?.drawLayer.updateProperties(this.#outlineId, {
      rootClass: {
        selected: false
      }
    });
    if (!this.#isFreeHighlight) {
      this.#setCaret(false);
    }
  }
  get _mustFixPosition() {
    return !this.#isFreeHighlight;
  }
  show(visible = this._isVisible) {
    super.show(visible);
    if (this.parent) {
      this.parent.drawLayer.updateProperties(this.#id, {
        rootClass: {
          hidden: !visible
        }
      });
      this.parent.drawLayer.updateProperties(this.#outlineId, {
        rootClass: {
          hidden: !visible
        }
      });
    }
  }
  #getRotation() {
    return this.#isFreeHighlight ? this.rotation : 0;
  }
  #serializeBoxes() {
    if (this.#isFreeHighlight) {
      return null;
    }
    const [pageWidth, pageHeight] = this.pageDimensions;
    const [pageX, pageY] = this.pageTranslation;
    const boxes = this.#boxes;
    const quadPoints = new Float32Array(boxes.length * 8);
    let i7 = 0;
    for (const {
      x: x2,
      y: y4,
      width,
      height
    } of boxes) {
      const sx = x2 * pageWidth + pageX;
      const sy = (1 - y4) * pageHeight + pageY;
      quadPoints[i7] = quadPoints[i7 + 4] = sx;
      quadPoints[i7 + 1] = quadPoints[i7 + 3] = sy;
      quadPoints[i7 + 2] = quadPoints[i7 + 6] = sx + width * pageWidth;
      quadPoints[i7 + 5] = quadPoints[i7 + 7] = sy - height * pageHeight;
      i7 += 8;
    }
    return quadPoints;
  }
  #serializeOutlines(rect) {
    return this.#highlightOutlines.serialize(rect, this.#getRotation());
  }
  static startHighlighting(parent, isLTR, {
    target: textLayer,
    x: x2,
    y: y4
  }) {
    const {
      x: layerX,
      y: layerY,
      width: parentWidth,
      height: parentHeight
    } = textLayer.getBoundingClientRect();
    const ac = new AbortController();
    const signal = parent.combinedSignal(ac);
    const pointerUpCallback = (e9) => {
      ac.abort();
      this.#endHighlight(parent, e9);
    };
    window.addEventListener("blur", pointerUpCallback, {
      signal
    });
    window.addEventListener("pointerup", pointerUpCallback, {
      signal
    });
    window.addEventListener("pointerdown", stopEvent, {
      capture: true,
      passive: false,
      signal
    });
    window.addEventListener("contextmenu", noContextMenu, {
      signal
    });
    textLayer.addEventListener("pointermove", this.#highlightMove.bind(this, parent), {
      signal
    });
    this._freeHighlight = new FreeHighlightOutliner({
      x: x2,
      y: y4
    }, [layerX, layerY, parentWidth, parentHeight], parent.scale, this._defaultThickness / 2, isLTR, 1e-3);
    ({
      id: this._freeHighlightId,
      clipPathId: this._freeHighlightClipId
    } = parent.drawLayer.draw({
      bbox: [0, 0, 1, 1],
      root: {
        viewBox: "0 0 1 1",
        fill: this._defaultColor,
        "fill-opacity": this._defaultOpacity
      },
      rootClass: {
        highlight: true,
        free: true
      },
      path: {
        d: this._freeHighlight.toSVGPath()
      }
    }, true, true));
  }
  static #highlightMove(parent, event) {
    if (this._freeHighlight.add(event)) {
      parent.drawLayer.updateProperties(this._freeHighlightId, {
        path: {
          d: this._freeHighlight.toSVGPath()
        }
      });
    }
  }
  static #endHighlight(parent, event) {
    if (!this._freeHighlight.isEmpty()) {
      parent.createAndAddNewEditor(event, false, {
        highlightId: this._freeHighlightId,
        highlightOutlines: this._freeHighlight.getOutlines(),
        clipPathId: this._freeHighlightClipId,
        methodOfCreation: "main_toolbar"
      });
    } else {
      parent.drawLayer.remove(this._freeHighlightId);
    }
    this._freeHighlightId = -1;
    this._freeHighlight = null;
    this._freeHighlightClipId = "";
  }
  static async deserialize(data, parent, uiManager) {
    let initialData = null;
    if (data instanceof HighlightAnnotationElement) {
      const {
        data: {
          quadPoints: quadPoints2,
          rect,
          rotation,
          id,
          color: color2,
          opacity: opacity2,
          popupRef,
          richText,
          contentsObj,
          creationDate,
          modificationDate
        },
        parent: {
          page: {
            pageNumber
          }
        }
      } = data;
      initialData = data = {
        annotationType: AnnotationEditorType.HIGHLIGHT,
        color: Array.from(color2),
        opacity: opacity2,
        quadPoints: quadPoints2,
        boxes: null,
        pageIndex: pageNumber - 1,
        rect: rect.slice(0),
        rotation,
        annotationElementId: id,
        id,
        deleted: false,
        popupRef,
        richText,
        comment: contentsObj?.str || null,
        creationDate,
        modificationDate
      };
    } else if (data instanceof InkAnnotationElement) {
      const {
        data: {
          inkLists: inkLists2,
          rect,
          rotation,
          id,
          color: color2,
          borderStyle: {
            rawWidth: thickness
          },
          popupRef,
          richText,
          contentsObj,
          creationDate,
          modificationDate
        },
        parent: {
          page: {
            pageNumber
          }
        }
      } = data;
      initialData = data = {
        annotationType: AnnotationEditorType.HIGHLIGHT,
        color: Array.from(color2),
        thickness,
        inkLists: inkLists2,
        boxes: null,
        pageIndex: pageNumber - 1,
        rect: rect.slice(0),
        rotation,
        annotationElementId: id,
        id,
        deleted: false,
        popupRef,
        richText,
        comment: contentsObj?.str || null,
        creationDate,
        modificationDate
      };
    }
    const {
      color,
      quadPoints,
      inkLists,
      opacity
    } = data;
    const editor = await super.deserialize(data, parent, uiManager);
    editor.color = Util.makeHexColor(...color);
    editor.opacity = opacity || 1;
    if (inkLists) {
      editor.#thickness = data.thickness;
    }
    editor._initialData = initialData;
    if (data.comment) {
      editor.setCommentData(data);
    }
    const [pageWidth, pageHeight] = editor.pageDimensions;
    const [pageX, pageY] = editor.pageTranslation;
    if (quadPoints) {
      const boxes = editor.#boxes = [];
      for (let i7 = 0; i7 < quadPoints.length; i7 += 8) {
        boxes.push({
          x: (quadPoints[i7] - pageX) / pageWidth,
          y: 1 - (quadPoints[i7 + 1] - pageY) / pageHeight,
          width: (quadPoints[i7 + 2] - quadPoints[i7]) / pageWidth,
          height: (quadPoints[i7 + 1] - quadPoints[i7 + 5]) / pageHeight
        });
      }
      editor.#createOutlines();
      editor.#addToDrawLayer();
      editor.rotate(editor.rotation);
    } else if (inkLists) {
      editor.#isFreeHighlight = true;
      const points = inkLists[0];
      const point = {
        x: points[0] - pageX,
        y: pageHeight - (points[1] - pageY)
      };
      const outliner = new FreeHighlightOutliner(point, [0, 0, pageWidth, pageHeight], 1, editor.#thickness / 2, true, 1e-3);
      for (let i7 = 0, ii = points.length; i7 < ii; i7 += 2) {
        point.x = points[i7] - pageX;
        point.y = pageHeight - (points[i7 + 1] - pageY);
        outliner.add(point);
      }
      const {
        id,
        clipPathId
      } = parent.drawLayer.draw({
        bbox: [0, 0, 1, 1],
        root: {
          viewBox: "0 0 1 1",
          fill: editor.color,
          "fill-opacity": editor._defaultOpacity
        },
        rootClass: {
          highlight: true,
          free: true
        },
        path: {
          d: outliner.toSVGPath()
        }
      }, true, true);
      editor.#createFreeOutlines({
        highlightOutlines: outliner.getOutlines(),
        highlightId: id,
        clipPathId
      });
      editor.#addToDrawLayer();
      editor.rotate(editor.parentRotation);
    }
    return editor;
  }
  serialize(isForCopying = false) {
    if (this.isEmpty() || isForCopying) {
      return null;
    }
    if (this.deleted) {
      return this.serializeDeleted();
    }
    const color = AnnotationEditor._colorManager.convert(this._uiManager.getNonHCMColor(this.color));
    const serialized = super.serialize(isForCopying);
    Object.assign(serialized, {
      color,
      opacity: this.opacity,
      thickness: this.#thickness,
      quadPoints: this.#serializeBoxes(),
      outlines: this.#serializeOutlines(serialized.rect)
    });
    this.addComment(serialized);
    if (this.annotationElementId && !this.#hasElementChanged(serialized)) {
      return null;
    }
    serialized.id = this.annotationElementId;
    return serialized;
  }
  #hasElementChanged(serialized) {
    const {
      color
    } = this._initialData;
    return this.hasEditedComment || serialized.color.some((c6, i7) => c6 !== color[i7]);
  }
  renderAnnotationElement(annotation) {
    if (this.deleted) {
      annotation.hide();
      return null;
    }
    annotation.updateEdited({
      rect: this.getPDFRect(),
      popup: this.comment
    });
    return null;
  }
  static canCreateNewEmptyEditor() {
    return false;
  }
};
var DrawingOptions = class {
  #svgProperties = /* @__PURE__ */ Object.create(null);
  updateProperty(name, value) {
    this[name] = value;
    this.updateSVGProperty(name, value);
  }
  updateProperties(properties) {
    if (!properties) {
      return;
    }
    for (const [name, value] of Object.entries(properties)) {
      if (!name.startsWith("_")) {
        this.updateProperty(name, value);
      }
    }
  }
  updateSVGProperty(name, value) {
    this.#svgProperties[name] = value;
  }
  toSVGProperties() {
    const root = this.#svgProperties;
    this.#svgProperties = /* @__PURE__ */ Object.create(null);
    return {
      root
    };
  }
  reset() {
    this.#svgProperties = /* @__PURE__ */ Object.create(null);
  }
  updateAll(options = this) {
    this.updateProperties(options);
  }
  clone() {
    unreachable("Not implemented");
  }
};
var DrawingEditor = class _DrawingEditor extends AnnotationEditor {
  #drawOutlines = null;
  #mustBeCommitted;
  _colorPicker = null;
  _drawId = null;
  static _currentDrawId = -1;
  static _currentParent = null;
  static #currentDraw = null;
  static #currentDrawingAC = null;
  static #currentDrawingOptions = null;
  static _INNER_MARGIN = 3;
  constructor(params) {
    super(params);
    this.#mustBeCommitted = params.mustBeCommitted || false;
    this._addOutlines(params);
  }
  onUpdatedColor() {
    this._colorPicker?.update(this.color);
    super.onUpdatedColor();
  }
  _addOutlines(params) {
    if (params.drawOutlines) {
      this.#createDrawOutlines(params);
      this.#addToDrawLayer();
    }
  }
  #createDrawOutlines({
    drawOutlines,
    drawId,
    drawingOptions
  }) {
    this.#drawOutlines = drawOutlines;
    this._drawingOptions ||= drawingOptions;
    if (!this.annotationElementId) {
      this._uiManager.a11yAlert(`pdfjs-editor-${this.editorType}-added-alert`);
    }
    if (drawId >= 0) {
      this._drawId = drawId;
      this.parent.drawLayer.finalizeDraw(drawId, drawOutlines.defaultProperties);
    } else {
      this._drawId = this.#createDrawing(drawOutlines, this.parent);
    }
    this.#updateBbox(drawOutlines.box);
  }
  #createDrawing(drawOutlines, parent) {
    const {
      id
    } = parent.drawLayer.draw(_DrawingEditor._mergeSVGProperties(this._drawingOptions.toSVGProperties(), drawOutlines.defaultSVGProperties), false, false);
    return id;
  }
  static _mergeSVGProperties(p1, p22) {
    const p1Keys = new Set(Object.keys(p1));
    for (const [key, value] of Object.entries(p22)) {
      if (p1Keys.has(key)) {
        Object.assign(p1[key], value);
      } else {
        p1[key] = value;
      }
    }
    return p1;
  }
  static getDefaultDrawingOptions(_options) {
    unreachable("Not implemented");
  }
  static get typesMap() {
    unreachable("Not implemented");
  }
  static get isDrawer() {
    return true;
  }
  static get supportMultipleDrawings() {
    return false;
  }
  static updateDefaultParams(type, value) {
    const propertyName = this.typesMap.get(type);
    if (propertyName) {
      this._defaultDrawingOptions.updateProperty(propertyName, value);
    }
    if (this._currentParent) {
      _DrawingEditor.#currentDraw.updateProperty(propertyName, value);
      this._currentParent.drawLayer.updateProperties(this._currentDrawId, this._defaultDrawingOptions.toSVGProperties());
    }
  }
  updateParams(type, value) {
    const propertyName = this.constructor.typesMap.get(type);
    if (propertyName) {
      this._updateProperty(type, propertyName, value);
    }
  }
  static get defaultPropertiesToUpdate() {
    const properties = [];
    const options = this._defaultDrawingOptions;
    for (const [type, name] of this.typesMap) {
      properties.push([type, options[name]]);
    }
    return properties;
  }
  get propertiesToUpdate() {
    const properties = [];
    const {
      _drawingOptions
    } = this;
    for (const [type, name] of this.constructor.typesMap) {
      properties.push([type, _drawingOptions[name]]);
    }
    return properties;
  }
  _updateProperty(type, name, value) {
    const options = this._drawingOptions;
    const savedValue = options[name];
    const setter = (val2) => {
      options.updateProperty(name, val2);
      const bbox = this.#drawOutlines.updateProperty(name, val2);
      if (bbox) {
        this.#updateBbox(bbox);
      }
      this.parent?.drawLayer.updateProperties(this._drawId, options.toSVGProperties());
      if (type === this.colorType) {
        this.onUpdatedColor();
      }
    };
    this.addCommands({
      cmd: setter.bind(this, value),
      undo: setter.bind(this, savedValue),
      post: this._uiManager.updateUI.bind(this._uiManager, this),
      mustExec: true,
      type,
      overwriteIfSameType: true,
      keepUndo: true
    });
  }
  _onResizing() {
    this.parent?.drawLayer.updateProperties(this._drawId, _DrawingEditor._mergeSVGProperties(this.#drawOutlines.getPathResizingSVGProperties(this.#convertToDrawSpace()), {
      bbox: this.#rotateBox()
    }));
  }
  _onResized() {
    this.parent?.drawLayer.updateProperties(this._drawId, _DrawingEditor._mergeSVGProperties(this.#drawOutlines.getPathResizedSVGProperties(this.#convertToDrawSpace()), {
      bbox: this.#rotateBox()
    }));
  }
  _onTranslating(_x, _y) {
    this.parent?.drawLayer.updateProperties(this._drawId, {
      bbox: this.#rotateBox()
    });
  }
  _onTranslated() {
    this.parent?.drawLayer.updateProperties(this._drawId, _DrawingEditor._mergeSVGProperties(this.#drawOutlines.getPathTranslatedSVGProperties(this.#convertToDrawSpace(), this.parentDimensions), {
      bbox: this.#rotateBox()
    }));
  }
  _onStartDragging() {
    this.parent?.drawLayer.updateProperties(this._drawId, {
      rootClass: {
        moving: true
      }
    });
  }
  _onStopDragging() {
    this.parent?.drawLayer.updateProperties(this._drawId, {
      rootClass: {
        moving: false
      }
    });
  }
  commit() {
    super.commit();
    this.disableEditMode();
    this.disableEditing();
  }
  disableEditing() {
    super.disableEditing();
    this.div.classList.toggle("disabled", true);
  }
  enableEditing() {
    super.enableEditing();
    this.div.classList.toggle("disabled", false);
  }
  getBaseTranslation() {
    return [0, 0];
  }
  get isResizable() {
    return true;
  }
  onceAdded(focus) {
    if (!this.annotationElementId) {
      this.parent.addUndoableEditor(this);
    }
    this._isDraggable = true;
    if (this.#mustBeCommitted) {
      this.#mustBeCommitted = false;
      this.commit();
      this.parent.setSelected(this);
      if (focus && this.isOnScreen) {
        this.div.focus();
      }
    }
  }
  remove() {
    this.#cleanDrawLayer();
    super.remove();
  }
  rebuild() {
    if (!this.parent) {
      return;
    }
    super.rebuild();
    if (this.div === null) {
      return;
    }
    this.#addToDrawLayer();
    this.#updateBbox(this.#drawOutlines.box);
    if (!this.isAttachedToDOM) {
      this.parent.add(this);
    }
  }
  setParent(parent) {
    let mustBeSelected = false;
    if (this.parent && !parent) {
      this._uiManager.removeShouldRescale(this);
      this.#cleanDrawLayer();
    } else if (parent) {
      this._uiManager.addShouldRescale(this);
      this.#addToDrawLayer(parent);
      mustBeSelected = !this.parent && this.div?.classList.contains("selectedEditor");
    }
    super.setParent(parent);
    if (mustBeSelected) {
      this.select();
    }
  }
  #cleanDrawLayer() {
    if (this._drawId === null || !this.parent) {
      return;
    }
    this.parent.drawLayer.remove(this._drawId);
    this._drawId = null;
    this._drawingOptions.reset();
  }
  #addToDrawLayer(parent = this.parent) {
    if (this._drawId !== null && this.parent === parent) {
      return;
    }
    if (this._drawId !== null) {
      this.parent.drawLayer.updateParent(this._drawId, parent.drawLayer);
      return;
    }
    this._drawingOptions.updateAll();
    this._drawId = this.#createDrawing(this.#drawOutlines, parent);
  }
  #convertToParentSpace([x2, y4, width, height]) {
    const {
      parentDimensions: [pW, pH],
      rotation
    } = this;
    switch (rotation) {
      case 90:
        return [y4, 1 - x2, width * (pH / pW), height * (pW / pH)];
      case 180:
        return [1 - x2, 1 - y4, width, height];
      case 270:
        return [1 - y4, x2, width * (pH / pW), height * (pW / pH)];
      default:
        return [x2, y4, width, height];
    }
  }
  #convertToDrawSpace() {
    const {
      x: x2,
      y: y4,
      width,
      height,
      parentDimensions: [pW, pH],
      rotation
    } = this;
    switch (rotation) {
      case 90:
        return [1 - y4, x2, width * (pW / pH), height * (pH / pW)];
      case 180:
        return [1 - x2, 1 - y4, width, height];
      case 270:
        return [y4, 1 - x2, width * (pW / pH), height * (pH / pW)];
      default:
        return [x2, y4, width, height];
    }
  }
  #updateBbox(bbox) {
    [this.x, this.y, this.width, this.height] = this.#convertToParentSpace(bbox);
    if (this.div) {
      this.fixAndSetPosition();
      this.setDims();
    }
    this._onResized();
  }
  #rotateBox() {
    const {
      x: x2,
      y: y4,
      width,
      height,
      rotation,
      parentRotation,
      parentDimensions: [pW, pH]
    } = this;
    switch ((rotation * 4 + parentRotation) / 90) {
      case 1:
        return [1 - y4 - height, x2, height, width];
      case 2:
        return [1 - x2 - width, 1 - y4 - height, width, height];
      case 3:
        return [y4, 1 - x2 - width, height, width];
      case 4:
        return [x2, y4 - width * (pW / pH), height * (pH / pW), width * (pW / pH)];
      case 5:
        return [1 - y4, x2, width * (pW / pH), height * (pH / pW)];
      case 6:
        return [1 - x2 - height * (pH / pW), 1 - y4, height * (pH / pW), width * (pW / pH)];
      case 7:
        return [y4 - width * (pW / pH), 1 - x2 - height * (pH / pW), width * (pW / pH), height * (pH / pW)];
      case 8:
        return [x2 - width, y4 - height, width, height];
      case 9:
        return [1 - y4, x2 - width, height, width];
      case 10:
        return [1 - x2, 1 - y4, width, height];
      case 11:
        return [y4 - height, 1 - x2, height, width];
      case 12:
        return [x2 - height * (pH / pW), y4, height * (pH / pW), width * (pW / pH)];
      case 13:
        return [1 - y4 - width * (pW / pH), x2 - height * (pH / pW), width * (pW / pH), height * (pH / pW)];
      case 14:
        return [1 - x2, 1 - y4 - width * (pW / pH), height * (pH / pW), width * (pW / pH)];
      case 15:
        return [y4, 1 - x2, width * (pW / pH), height * (pH / pW)];
      default:
        return [x2, y4, width, height];
    }
  }
  rotate() {
    if (!this.parent) {
      return;
    }
    this.parent.drawLayer.updateProperties(this._drawId, _DrawingEditor._mergeSVGProperties({
      bbox: this.#rotateBox()
    }, this.#drawOutlines.updateRotation((this.parentRotation - this.rotation + 360) % 360)));
  }
  onScaleChanging() {
    if (!this.parent) {
      return;
    }
    this.#updateBbox(this.#drawOutlines.updateParentDimensions(this.parentDimensions, this.parent.scale));
  }
  static onScaleChangingWhenDrawing() {
  }
  render() {
    if (this.div) {
      return this.div;
    }
    let baseX, baseY;
    if (this._isCopy) {
      baseX = this.x;
      baseY = this.y;
    }
    const div = super.render();
    div.classList.add("draw");
    const drawDiv = document.createElement("div");
    div.append(drawDiv);
    drawDiv.setAttribute("aria-hidden", "true");
    drawDiv.className = "internal";
    this.setDims();
    this._uiManager.addShouldRescale(this);
    this.disableEditing();
    if (this._isCopy) {
      this._moveAfterPaste(baseX, baseY);
    }
    return div;
  }
  static createDrawerInstance(_x, _y, _parentWidth, _parentHeight, _rotation) {
    unreachable("Not implemented");
  }
  static startDrawing(parent, uiManager, _isLTR, event) {
    const {
      target,
      offsetX: x2,
      offsetY: y4,
      pointerId,
      pointerType
    } = event;
    if (CurrentPointers.isInitializedAndDifferentPointerType(pointerType)) {
      return;
    }
    const {
      viewport: {
        rotation
      }
    } = parent;
    const {
      width: parentWidth,
      height: parentHeight
    } = target.getBoundingClientRect();
    const ac = _DrawingEditor.#currentDrawingAC = new AbortController();
    const signal = parent.combinedSignal(ac);
    CurrentPointers.setPointer(pointerType, pointerId);
    window.addEventListener("pointerup", (e9) => {
      if (CurrentPointers.isSamePointerIdOrRemove(e9.pointerId)) {
        this._endDraw(e9);
      }
    }, {
      signal
    });
    window.addEventListener("pointercancel", (e9) => {
      if (CurrentPointers.isSamePointerIdOrRemove(e9.pointerId)) {
        this._currentParent.endDrawingSession();
      }
    }, {
      signal
    });
    window.addEventListener("pointerdown", (e9) => {
      if (!CurrentPointers.isSamePointerType(e9.pointerType)) {
        return;
      }
      CurrentPointers.initializeAndAddPointerId(e9.pointerId);
      if (_DrawingEditor.#currentDraw.isCancellable()) {
        _DrawingEditor.#currentDraw.removeLastElement();
        if (_DrawingEditor.#currentDraw.isEmpty()) {
          this._currentParent.endDrawingSession(true);
        } else {
          this._endDraw(null);
        }
      }
    }, {
      capture: true,
      passive: false,
      signal
    });
    window.addEventListener("contextmenu", noContextMenu, {
      signal
    });
    target.addEventListener("pointermove", this._drawMove.bind(this), {
      signal
    });
    target.addEventListener("touchmove", (e9) => {
      if (CurrentPointers.isSameTimeStamp(e9.timeStamp)) {
        stopEvent(e9);
      }
    }, {
      signal
    });
    parent.toggleDrawing();
    uiManager._editorUndoBar?.hide();
    if (_DrawingEditor.#currentDraw) {
      parent.drawLayer.updateProperties(this._currentDrawId, _DrawingEditor.#currentDraw.startNew(x2, y4, parentWidth, parentHeight, rotation));
      return;
    }
    uiManager.updateUIForDefaultProperties(this);
    _DrawingEditor.#currentDraw = this.createDrawerInstance(x2, y4, parentWidth, parentHeight, rotation);
    _DrawingEditor.#currentDrawingOptions = this.getDefaultDrawingOptions();
    this._currentParent = parent;
    ({
      id: this._currentDrawId
    } = parent.drawLayer.draw(this._mergeSVGProperties(_DrawingEditor.#currentDrawingOptions.toSVGProperties(), _DrawingEditor.#currentDraw.defaultSVGProperties), true, false));
  }
  static _drawMove(event) {
    CurrentPointers.isSameTimeStamp(event.timeStamp);
    if (!_DrawingEditor.#currentDraw) {
      return;
    }
    const {
      offsetX,
      offsetY,
      pointerId
    } = event;
    if (!CurrentPointers.isSamePointerId(pointerId)) {
      return;
    }
    if (CurrentPointers.isUsingMultiplePointers()) {
      this._endDraw(event);
      return;
    }
    this._currentParent.drawLayer.updateProperties(this._currentDrawId, _DrawingEditor.#currentDraw.add(offsetX, offsetY));
    CurrentPointers.setTimeStamp(event.timeStamp);
    stopEvent(event);
  }
  static _cleanup(all) {
    if (all) {
      this._currentDrawId = -1;
      this._currentParent = null;
      _DrawingEditor.#currentDraw = null;
      _DrawingEditor.#currentDrawingOptions = null;
      CurrentPointers.clearPointerType();
      CurrentPointers.clearTimeStamp();
    }
    if (_DrawingEditor.#currentDrawingAC) {
      _DrawingEditor.#currentDrawingAC.abort();
      _DrawingEditor.#currentDrawingAC = null;
      CurrentPointers.clearPointerIds();
    }
  }
  static _endDraw(event) {
    const parent = this._currentParent;
    if (!parent) {
      return;
    }
    parent.toggleDrawing(true);
    this._cleanup(false);
    if (event?.target === parent.div) {
      parent.drawLayer.updateProperties(this._currentDrawId, _DrawingEditor.#currentDraw.end(event.offsetX, event.offsetY));
    }
    if (this.supportMultipleDrawings) {
      const draw = _DrawingEditor.#currentDraw;
      const drawId = this._currentDrawId;
      const lastElement = draw.getLastElement();
      parent.addCommands({
        cmd: () => {
          parent.drawLayer.updateProperties(drawId, draw.setLastElement(lastElement));
        },
        undo: () => {
          parent.drawLayer.updateProperties(drawId, draw.removeLastElement());
        },
        mustExec: false,
        type: AnnotationEditorParamsType.DRAW_STEP
      });
      return;
    }
    this.endDrawing(false);
  }
  static endDrawing(isAborted3) {
    const parent = this._currentParent;
    if (!parent) {
      return null;
    }
    parent.toggleDrawing(true);
    parent.cleanUndoStack(AnnotationEditorParamsType.DRAW_STEP);
    if (!_DrawingEditor.#currentDraw.isEmpty()) {
      const {
        pageDimensions: [pageWidth, pageHeight],
        scale
      } = parent;
      const editor = parent.createAndAddNewEditor({
        offsetX: 0,
        offsetY: 0
      }, false, {
        drawId: this._currentDrawId,
        drawOutlines: _DrawingEditor.#currentDraw.getOutlines(pageWidth * scale, pageHeight * scale, scale, this._INNER_MARGIN),
        drawingOptions: _DrawingEditor.#currentDrawingOptions,
        mustBeCommitted: !isAborted3
      });
      this._cleanup(true);
      return editor;
    }
    parent.drawLayer.remove(this._currentDrawId);
    this._cleanup(true);
    return null;
  }
  createDrawingOptions(_data) {
  }
  static deserializeDraw(_pageX, _pageY, _pageWidth, _pageHeight, _innerWidth, _data) {
    unreachable("Not implemented");
  }
  static async deserialize(data, parent, uiManager) {
    const {
      rawDims: {
        pageWidth,
        pageHeight,
        pageX,
        pageY
      }
    } = parent.viewport;
    const drawOutlines = this.deserializeDraw(pageX, pageY, pageWidth, pageHeight, this._INNER_MARGIN, data);
    const editor = await super.deserialize(data, parent, uiManager);
    editor.createDrawingOptions(data);
    editor.#createDrawOutlines({
      drawOutlines
    });
    editor.#addToDrawLayer();
    editor.onScaleChanging();
    editor.rotate();
    return editor;
  }
  serializeDraw(isForCopying) {
    const [pageX, pageY] = this.pageTranslation;
    const [pageWidth, pageHeight] = this.pageDimensions;
    return this.#drawOutlines.serialize([pageX, pageY, pageWidth, pageHeight], isForCopying);
  }
  renderAnnotationElement(annotation) {
    annotation.updateEdited({
      rect: this.getPDFRect()
    });
    return null;
  }
  static canCreateNewEmptyEditor() {
    return false;
  }
};
var InkDrawOutliner = class {
  #last = new Float64Array(6);
  #line;
  #lines;
  #rotation;
  #thickness;
  #points;
  #lastSVGPath = "";
  #lastIndex = 0;
  #outlines = new InkDrawOutline();
  #parentWidth;
  #parentHeight;
  constructor(x2, y4, parentWidth, parentHeight, rotation, thickness) {
    this.#parentWidth = parentWidth;
    this.#parentHeight = parentHeight;
    this.#rotation = rotation;
    this.#thickness = thickness;
    [x2, y4] = this.#normalizePoint(x2, y4);
    const line = this.#line = [NaN, NaN, NaN, NaN, x2, y4];
    this.#points = [x2, y4];
    this.#lines = [{
      line,
      points: this.#points
    }];
    this.#last.set(line, 0);
  }
  updateProperty(name, value) {
    if (name === "stroke-width") {
      this.#thickness = value;
    }
  }
  #normalizePoint(x2, y4) {
    return Outline._normalizePoint(x2, y4, this.#parentWidth, this.#parentHeight, this.#rotation);
  }
  isEmpty() {
    return !this.#lines || this.#lines.length === 0;
  }
  isCancellable() {
    return this.#points.length <= 10;
  }
  add(x2, y4) {
    [x2, y4] = this.#normalizePoint(x2, y4);
    const [x1, y1, x22, y22] = this.#last.subarray(2, 6);
    const diffX = x2 - x22;
    const diffY = y4 - y22;
    const d4 = Math.hypot(this.#parentWidth * diffX, this.#parentHeight * diffY);
    if (d4 <= 2) {
      return null;
    }
    this.#points.push(x2, y4);
    if (isNaN(x1)) {
      this.#last.set([x22, y22, x2, y4], 2);
      this.#line.push(NaN, NaN, NaN, NaN, x2, y4);
      return {
        path: {
          d: this.toSVGPath()
        }
      };
    }
    if (isNaN(this.#last[0])) {
      this.#line.splice(6, 6);
    }
    this.#last.set([x1, y1, x22, y22, x2, y4], 0);
    this.#line.push(...Outline.createBezierPoints(x1, y1, x22, y22, x2, y4));
    return {
      path: {
        d: this.toSVGPath()
      }
    };
  }
  end(x2, y4) {
    const change = this.add(x2, y4);
    if (change) {
      return change;
    }
    if (this.#points.length === 2) {
      return {
        path: {
          d: this.toSVGPath()
        }
      };
    }
    return null;
  }
  startNew(x2, y4, parentWidth, parentHeight, rotation) {
    this.#parentWidth = parentWidth;
    this.#parentHeight = parentHeight;
    this.#rotation = rotation;
    [x2, y4] = this.#normalizePoint(x2, y4);
    const line = this.#line = [NaN, NaN, NaN, NaN, x2, y4];
    this.#points = [x2, y4];
    const last = this.#lines.at(-1);
    if (last) {
      last.line = new Float32Array(last.line);
      last.points = new Float32Array(last.points);
    }
    this.#lines.push({
      line,
      points: this.#points
    });
    this.#last.set(line, 0);
    this.#lastIndex = 0;
    this.toSVGPath();
    return null;
  }
  getLastElement() {
    return this.#lines.at(-1);
  }
  setLastElement(element) {
    if (!this.#lines) {
      return this.#outlines.setLastElement(element);
    }
    this.#lines.push(element);
    this.#line = element.line;
    this.#points = element.points;
    this.#lastIndex = 0;
    return {
      path: {
        d: this.toSVGPath()
      }
    };
  }
  removeLastElement() {
    if (!this.#lines) {
      return this.#outlines.removeLastElement();
    }
    this.#lines.pop();
    this.#lastSVGPath = "";
    for (let i7 = 0, ii = this.#lines.length; i7 < ii; i7++) {
      const {
        line,
        points
      } = this.#lines[i7];
      this.#line = line;
      this.#points = points;
      this.#lastIndex = 0;
      this.toSVGPath();
    }
    return {
      path: {
        d: this.#lastSVGPath
      }
    };
  }
  toSVGPath() {
    const firstX = Outline.svgRound(this.#line[4]);
    const firstY = Outline.svgRound(this.#line[5]);
    if (this.#points.length === 2) {
      this.#lastSVGPath = `${this.#lastSVGPath} M ${firstX} ${firstY} Z`;
      return this.#lastSVGPath;
    }
    if (this.#points.length <= 6) {
      const i7 = this.#lastSVGPath.lastIndexOf("M");
      this.#lastSVGPath = `${this.#lastSVGPath.slice(0, i7)} M ${firstX} ${firstY}`;
      this.#lastIndex = 6;
    }
    if (this.#points.length === 4) {
      const secondX = Outline.svgRound(this.#line[10]);
      const secondY = Outline.svgRound(this.#line[11]);
      this.#lastSVGPath = `${this.#lastSVGPath} L ${secondX} ${secondY}`;
      this.#lastIndex = 12;
      return this.#lastSVGPath;
    }
    const buffer = [];
    if (this.#lastIndex === 0) {
      buffer.push(`M ${firstX} ${firstY}`);
      this.#lastIndex = 6;
    }
    for (let i7 = this.#lastIndex, ii = this.#line.length; i7 < ii; i7 += 6) {
      const [c1x, c1y, c2x, c2y, x2, y4] = this.#line.slice(i7, i7 + 6).map(Outline.svgRound);
      buffer.push(`C${c1x} ${c1y} ${c2x} ${c2y} ${x2} ${y4}`);
    }
    this.#lastSVGPath += buffer.join(" ");
    this.#lastIndex = this.#line.length;
    return this.#lastSVGPath;
  }
  getOutlines(parentWidth, parentHeight, scale, innerMargin) {
    const last = this.#lines.at(-1);
    last.line = new Float32Array(last.line);
    last.points = new Float32Array(last.points);
    this.#outlines.build(this.#lines, parentWidth, parentHeight, scale, this.#rotation, this.#thickness, innerMargin);
    this.#last = null;
    this.#line = null;
    this.#lines = null;
    this.#lastSVGPath = null;
    return this.#outlines;
  }
  get defaultSVGProperties() {
    return {
      root: {
        viewBox: "0 0 10000 10000"
      },
      rootClass: {
        draw: true
      },
      bbox: [0, 0, 1, 1]
    };
  }
};
var InkDrawOutline = class extends Outline {
  #bbox;
  #currentRotation = 0;
  #innerMargin;
  #lines;
  #parentWidth;
  #parentHeight;
  #parentScale;
  #rotation;
  #thickness;
  build(lines, parentWidth, parentHeight, parentScale, rotation, thickness, innerMargin) {
    this.#parentWidth = parentWidth;
    this.#parentHeight = parentHeight;
    this.#parentScale = parentScale;
    this.#rotation = rotation;
    this.#thickness = thickness;
    this.#innerMargin = innerMargin ?? 0;
    this.#lines = lines;
    this.#computeBbox();
  }
  get thickness() {
    return this.#thickness;
  }
  setLastElement(element) {
    this.#lines.push(element);
    return {
      path: {
        d: this.toSVGPath()
      }
    };
  }
  removeLastElement() {
    this.#lines.pop();
    return {
      path: {
        d: this.toSVGPath()
      }
    };
  }
  toSVGPath() {
    const buffer = [];
    for (const {
      line
    } of this.#lines) {
      buffer.push(`M${Outline.svgRound(line[4])} ${Outline.svgRound(line[5])}`);
      if (line.length === 6) {
        buffer.push("Z");
        continue;
      }
      if (line.length === 12 && isNaN(line[6])) {
        buffer.push(`L${Outline.svgRound(line[10])} ${Outline.svgRound(line[11])}`);
        continue;
      }
      for (let i7 = 6, ii = line.length; i7 < ii; i7 += 6) {
        const [c1x, c1y, c2x, c2y, x2, y4] = line.subarray(i7, i7 + 6).map(Outline.svgRound);
        buffer.push(`C${c1x} ${c1y} ${c2x} ${c2y} ${x2} ${y4}`);
      }
    }
    return buffer.join("");
  }
  serialize([pageX, pageY, pageWidth, pageHeight], isForCopying) {
    const serializedLines = [];
    const serializedPoints = [];
    const [x2, y4, width, height] = this.#getBBoxWithNoMargin();
    let tx, ty, sx, sy, x1, y1, x22, y22, rescaleFn;
    switch (this.#rotation) {
      case 0:
        rescaleFn = Outline._rescale;
        tx = pageX;
        ty = pageY + pageHeight;
        sx = pageWidth;
        sy = -pageHeight;
        x1 = pageX + x2 * pageWidth;
        y1 = pageY + (1 - y4 - height) * pageHeight;
        x22 = pageX + (x2 + width) * pageWidth;
        y22 = pageY + (1 - y4) * pageHeight;
        break;
      case 90:
        rescaleFn = Outline._rescaleAndSwap;
        tx = pageX;
        ty = pageY;
        sx = pageWidth;
        sy = pageHeight;
        x1 = pageX + y4 * pageWidth;
        y1 = pageY + x2 * pageHeight;
        x22 = pageX + (y4 + height) * pageWidth;
        y22 = pageY + (x2 + width) * pageHeight;
        break;
      case 180:
        rescaleFn = Outline._rescale;
        tx = pageX + pageWidth;
        ty = pageY;
        sx = -pageWidth;
        sy = pageHeight;
        x1 = pageX + (1 - x2 - width) * pageWidth;
        y1 = pageY + y4 * pageHeight;
        x22 = pageX + (1 - x2) * pageWidth;
        y22 = pageY + (y4 + height) * pageHeight;
        break;
      case 270:
        rescaleFn = Outline._rescaleAndSwap;
        tx = pageX + pageWidth;
        ty = pageY + pageHeight;
        sx = -pageWidth;
        sy = -pageHeight;
        x1 = pageX + (1 - y4 - height) * pageWidth;
        y1 = pageY + (1 - x2 - width) * pageHeight;
        x22 = pageX + (1 - y4) * pageWidth;
        y22 = pageY + (1 - x2) * pageHeight;
        break;
    }
    for (const {
      line,
      points
    } of this.#lines) {
      serializedLines.push(rescaleFn(line, tx, ty, sx, sy, isForCopying ? new Array(line.length) : null));
      serializedPoints.push(rescaleFn(points, tx, ty, sx, sy, isForCopying ? new Array(points.length) : null));
    }
    return {
      lines: serializedLines,
      points: serializedPoints,
      rect: [x1, y1, x22, y22]
    };
  }
  static deserialize(pageX, pageY, pageWidth, pageHeight, innerMargin, {
    paths: {
      lines,
      points
    },
    rotation,
    thickness
  }) {
    const newLines = [];
    let tx, ty, sx, sy, rescaleFn;
    switch (rotation) {
      case 0:
        rescaleFn = Outline._rescale;
        tx = -pageX / pageWidth;
        ty = pageY / pageHeight + 1;
        sx = 1 / pageWidth;
        sy = -1 / pageHeight;
        break;
      case 90:
        rescaleFn = Outline._rescaleAndSwap;
        tx = -pageY / pageHeight;
        ty = -pageX / pageWidth;
        sx = 1 / pageHeight;
        sy = 1 / pageWidth;
        break;
      case 180:
        rescaleFn = Outline._rescale;
        tx = pageX / pageWidth + 1;
        ty = -pageY / pageHeight;
        sx = -1 / pageWidth;
        sy = 1 / pageHeight;
        break;
      case 270:
        rescaleFn = Outline._rescaleAndSwap;
        tx = pageY / pageHeight + 1;
        ty = pageX / pageWidth + 1;
        sx = -1 / pageHeight;
        sy = -1 / pageWidth;
        break;
    }
    if (!lines) {
      lines = [];
      for (const point of points) {
        const len = point.length;
        if (len === 2) {
          lines.push(new Float32Array([NaN, NaN, NaN, NaN, point[0], point[1]]));
          continue;
        }
        if (len === 4) {
          lines.push(new Float32Array([NaN, NaN, NaN, NaN, point[0], point[1], NaN, NaN, NaN, NaN, point[2], point[3]]));
          continue;
        }
        const line = new Float32Array(3 * (len - 2));
        lines.push(line);
        let [x1, y1, x2, y22] = point.subarray(0, 4);
        line.set([NaN, NaN, NaN, NaN, x1, y1], 0);
        for (let i7 = 4; i7 < len; i7 += 2) {
          const x3 = point[i7];
          const y4 = point[i7 + 1];
          line.set(Outline.createBezierPoints(x1, y1, x2, y22, x3, y4), (i7 - 2) * 3);
          [x1, y1, x2, y22] = [x2, y22, x3, y4];
        }
      }
    }
    for (let i7 = 0, ii = lines.length; i7 < ii; i7++) {
      newLines.push({
        line: rescaleFn(lines[i7].map((x2) => x2 ?? NaN), tx, ty, sx, sy),
        points: rescaleFn(points[i7].map((x2) => x2 ?? NaN), tx, ty, sx, sy)
      });
    }
    const outlines = new this.prototype.constructor();
    outlines.build(newLines, pageWidth, pageHeight, 1, rotation, thickness, innerMargin);
    return outlines;
  }
  #getMarginComponents(thickness = this.#thickness) {
    const margin = this.#innerMargin + thickness / 2 * this.#parentScale;
    return this.#rotation % 180 === 0 ? [margin / this.#parentWidth, margin / this.#parentHeight] : [margin / this.#parentHeight, margin / this.#parentWidth];
  }
  #getBBoxWithNoMargin() {
    const [x2, y4, width, height] = this.#bbox;
    const [marginX, marginY] = this.#getMarginComponents(0);
    return [x2 + marginX, y4 + marginY, width - 2 * marginX, height - 2 * marginY];
  }
  #computeBbox() {
    const bbox = this.#bbox = new Float32Array([Infinity, Infinity, -Infinity, -Infinity]);
    for (const {
      line
    } of this.#lines) {
      if (line.length <= 12) {
        for (let i7 = 4, ii = line.length; i7 < ii; i7 += 6) {
          Util.pointBoundingBox(line[i7], line[i7 + 1], bbox);
        }
        continue;
      }
      let lastX = line[4], lastY = line[5];
      for (let i7 = 6, ii = line.length; i7 < ii; i7 += 6) {
        const [c1x, c1y, c2x, c2y, x2, y4] = line.subarray(i7, i7 + 6);
        Util.bezierBoundingBox(lastX, lastY, c1x, c1y, c2x, c2y, x2, y4, bbox);
        lastX = x2;
        lastY = y4;
      }
    }
    const [marginX, marginY] = this.#getMarginComponents();
    bbox[0] = MathClamp(bbox[0] - marginX, 0, 1);
    bbox[1] = MathClamp(bbox[1] - marginY, 0, 1);
    bbox[2] = MathClamp(bbox[2] + marginX, 0, 1);
    bbox[3] = MathClamp(bbox[3] + marginY, 0, 1);
    bbox[2] -= bbox[0];
    bbox[3] -= bbox[1];
  }
  get box() {
    return this.#bbox;
  }
  updateProperty(name, value) {
    if (name === "stroke-width") {
      return this.#updateThickness(value);
    }
    return null;
  }
  #updateThickness(thickness) {
    const [oldMarginX, oldMarginY] = this.#getMarginComponents();
    this.#thickness = thickness;
    const [newMarginX, newMarginY] = this.#getMarginComponents();
    const [diffMarginX, diffMarginY] = [newMarginX - oldMarginX, newMarginY - oldMarginY];
    const bbox = this.#bbox;
    bbox[0] -= diffMarginX;
    bbox[1] -= diffMarginY;
    bbox[2] += 2 * diffMarginX;
    bbox[3] += 2 * diffMarginY;
    return bbox;
  }
  updateParentDimensions([width, height], scale) {
    const [oldMarginX, oldMarginY] = this.#getMarginComponents();
    this.#parentWidth = width;
    this.#parentHeight = height;
    this.#parentScale = scale;
    const [newMarginX, newMarginY] = this.#getMarginComponents();
    const diffMarginX = newMarginX - oldMarginX;
    const diffMarginY = newMarginY - oldMarginY;
    const bbox = this.#bbox;
    bbox[0] -= diffMarginX;
    bbox[1] -= diffMarginY;
    bbox[2] += 2 * diffMarginX;
    bbox[3] += 2 * diffMarginY;
    return bbox;
  }
  updateRotation(rotation) {
    this.#currentRotation = rotation;
    return {
      path: {
        transform: this.rotationTransform
      }
    };
  }
  get viewBox() {
    return this.#bbox.map(Outline.svgRound).join(" ");
  }
  get defaultProperties() {
    const [x2, y4] = this.#bbox;
    return {
      root: {
        viewBox: this.viewBox
      },
      path: {
        "transform-origin": `${Outline.svgRound(x2)} ${Outline.svgRound(y4)}`
      }
    };
  }
  get rotationTransform() {
    const [, , width, height] = this.#bbox;
    let a3 = 0, b4 = 0, c6 = 0, d4 = 0, e9 = 0, f4 = 0;
    switch (this.#currentRotation) {
      case 90:
        b4 = height / width;
        c6 = -width / height;
        e9 = width;
        break;
      case 180:
        a3 = -1;
        d4 = -1;
        e9 = width;
        f4 = height;
        break;
      case 270:
        b4 = -height / width;
        c6 = width / height;
        f4 = height;
        break;
      default:
        return "";
    }
    return `matrix(${a3} ${b4} ${c6} ${d4} ${Outline.svgRound(e9)} ${Outline.svgRound(f4)})`;
  }
  getPathResizingSVGProperties([newX, newY, newWidth, newHeight]) {
    const [marginX, marginY] = this.#getMarginComponents();
    const [x2, y4, width, height] = this.#bbox;
    if (Math.abs(width - marginX) <= Outline.PRECISION || Math.abs(height - marginY) <= Outline.PRECISION) {
      const tx = newX + newWidth / 2 - (x2 + width / 2);
      const ty = newY + newHeight / 2 - (y4 + height / 2);
      return {
        path: {
          "transform-origin": `${Outline.svgRound(newX)} ${Outline.svgRound(newY)}`,
          transform: `${this.rotationTransform} translate(${tx} ${ty})`
        }
      };
    }
    const s1x = (newWidth - 2 * marginX) / (width - 2 * marginX);
    const s1y = (newHeight - 2 * marginY) / (height - 2 * marginY);
    const s2x = width / newWidth;
    const s2y = height / newHeight;
    return {
      path: {
        "transform-origin": `${Outline.svgRound(x2)} ${Outline.svgRound(y4)}`,
        transform: `${this.rotationTransform} scale(${s2x} ${s2y}) translate(${Outline.svgRound(marginX)} ${Outline.svgRound(marginY)}) scale(${s1x} ${s1y}) translate(${Outline.svgRound(-marginX)} ${Outline.svgRound(-marginY)})`
      }
    };
  }
  getPathResizedSVGProperties([newX, newY, newWidth, newHeight]) {
    const [marginX, marginY] = this.#getMarginComponents();
    const bbox = this.#bbox;
    const [x2, y4, width, height] = bbox;
    bbox[0] = newX;
    bbox[1] = newY;
    bbox[2] = newWidth;
    bbox[3] = newHeight;
    if (Math.abs(width - marginX) <= Outline.PRECISION || Math.abs(height - marginY) <= Outline.PRECISION) {
      const tx2 = newX + newWidth / 2 - (x2 + width / 2);
      const ty2 = newY + newHeight / 2 - (y4 + height / 2);
      for (const {
        line,
        points
      } of this.#lines) {
        Outline._translate(line, tx2, ty2, line);
        Outline._translate(points, tx2, ty2, points);
      }
      return {
        root: {
          viewBox: this.viewBox
        },
        path: {
          "transform-origin": `${Outline.svgRound(newX)} ${Outline.svgRound(newY)}`,
          transform: this.rotationTransform || null,
          d: this.toSVGPath()
        }
      };
    }
    const s1x = (newWidth - 2 * marginX) / (width - 2 * marginX);
    const s1y = (newHeight - 2 * marginY) / (height - 2 * marginY);
    const tx = -s1x * (x2 + marginX) + newX + marginX;
    const ty = -s1y * (y4 + marginY) + newY + marginY;
    if (s1x !== 1 || s1y !== 1 || tx !== 0 || ty !== 0) {
      for (const {
        line,
        points
      } of this.#lines) {
        Outline._rescale(line, tx, ty, s1x, s1y, line);
        Outline._rescale(points, tx, ty, s1x, s1y, points);
      }
    }
    return {
      root: {
        viewBox: this.viewBox
      },
      path: {
        "transform-origin": `${Outline.svgRound(newX)} ${Outline.svgRound(newY)}`,
        transform: this.rotationTransform || null,
        d: this.toSVGPath()
      }
    };
  }
  getPathTranslatedSVGProperties([newX, newY], parentDimensions) {
    const [newParentWidth, newParentHeight] = parentDimensions;
    const bbox = this.#bbox;
    const tx = newX - bbox[0];
    const ty = newY - bbox[1];
    if (this.#parentWidth === newParentWidth && this.#parentHeight === newParentHeight) {
      for (const {
        line,
        points
      } of this.#lines) {
        Outline._translate(line, tx, ty, line);
        Outline._translate(points, tx, ty, points);
      }
    } else {
      const sx = this.#parentWidth / newParentWidth;
      const sy = this.#parentHeight / newParentHeight;
      this.#parentWidth = newParentWidth;
      this.#parentHeight = newParentHeight;
      for (const {
        line,
        points
      } of this.#lines) {
        Outline._rescale(line, tx, ty, sx, sy, line);
        Outline._rescale(points, tx, ty, sx, sy, points);
      }
      bbox[2] *= sx;
      bbox[3] *= sy;
    }
    bbox[0] = newX;
    bbox[1] = newY;
    return {
      root: {
        viewBox: this.viewBox
      },
      path: {
        d: this.toSVGPath(),
        "transform-origin": `${Outline.svgRound(newX)} ${Outline.svgRound(newY)}`
      }
    };
  }
  get defaultSVGProperties() {
    const bbox = this.#bbox;
    return {
      root: {
        viewBox: this.viewBox
      },
      rootClass: {
        draw: true
      },
      path: {
        d: this.toSVGPath(),
        "transform-origin": `${Outline.svgRound(bbox[0])} ${Outline.svgRound(bbox[1])}`,
        transform: this.rotationTransform || null
      },
      bbox
    };
  }
};
var InkDrawingOptions = class _InkDrawingOptions extends DrawingOptions {
  constructor(viewerParameters) {
    super();
    this._viewParameters = viewerParameters;
    super.updateProperties({
      fill: "none",
      stroke: AnnotationEditor._defaultLineColor,
      "stroke-opacity": 1,
      "stroke-width": 1,
      "stroke-linecap": "round",
      "stroke-linejoin": "round",
      "stroke-miterlimit": 10
    });
  }
  updateSVGProperty(name, value) {
    if (name === "stroke-width") {
      value ??= this["stroke-width"];
      value *= this._viewParameters.realScale;
    }
    super.updateSVGProperty(name, value);
  }
  clone() {
    const clone = new _InkDrawingOptions(this._viewParameters);
    clone.updateAll(this);
    return clone;
  }
};
var InkEditor = class _InkEditor extends DrawingEditor {
  static _type = "ink";
  static _editorType = AnnotationEditorType.INK;
  static _defaultDrawingOptions = null;
  constructor(params) {
    super({
      ...params,
      name: "inkEditor"
    });
    this._willKeepAspectRatio = true;
    this.defaultL10nId = "pdfjs-editor-ink-editor";
  }
  static initialize(l10n, uiManager) {
    AnnotationEditor.initialize(l10n, uiManager);
    this._defaultDrawingOptions = new InkDrawingOptions(uiManager.viewParameters);
  }
  static getDefaultDrawingOptions(options) {
    const clone = this._defaultDrawingOptions.clone();
    clone.updateProperties(options);
    return clone;
  }
  static get supportMultipleDrawings() {
    return true;
  }
  static get typesMap() {
    return shadow(this, "typesMap", /* @__PURE__ */ new Map([[AnnotationEditorParamsType.INK_THICKNESS, "stroke-width"], [AnnotationEditorParamsType.INK_COLOR, "stroke"], [AnnotationEditorParamsType.INK_OPACITY, "stroke-opacity"]]));
  }
  static createDrawerInstance(x2, y4, parentWidth, parentHeight, rotation) {
    return new InkDrawOutliner(x2, y4, parentWidth, parentHeight, rotation, this._defaultDrawingOptions["stroke-width"]);
  }
  static deserializeDraw(pageX, pageY, pageWidth, pageHeight, innerMargin, data) {
    return InkDrawOutline.deserialize(pageX, pageY, pageWidth, pageHeight, innerMargin, data);
  }
  static async deserialize(data, parent, uiManager) {
    let initialData = null;
    if (data instanceof InkAnnotationElement) {
      const {
        data: {
          inkLists,
          rect,
          rotation,
          id,
          color,
          opacity,
          borderStyle: {
            rawWidth: thickness
          },
          popupRef,
          richText,
          contentsObj,
          creationDate,
          modificationDate
        },
        parent: {
          page: {
            pageNumber
          }
        }
      } = data;
      initialData = data = {
        annotationType: AnnotationEditorType.INK,
        color: Array.from(color),
        thickness,
        opacity,
        paths: {
          points: inkLists
        },
        boxes: null,
        pageIndex: pageNumber - 1,
        rect: rect.slice(0),
        rotation,
        annotationElementId: id,
        id,
        deleted: false,
        popupRef,
        richText,
        comment: contentsObj?.str || null,
        creationDate,
        modificationDate
      };
    }
    const editor = await super.deserialize(data, parent, uiManager);
    editor._initialData = initialData;
    if (data.comment) {
      editor.setCommentData(data);
    }
    return editor;
  }
  get toolbarButtons() {
    this._colorPicker ||= new BasicColorPicker(this);
    return [["colorPicker", this._colorPicker]];
  }
  get colorType() {
    return AnnotationEditorParamsType.INK_COLOR;
  }
  get color() {
    return this._drawingOptions.stroke;
  }
  get opacity() {
    return this._drawingOptions["stroke-opacity"];
  }
  onScaleChanging() {
    if (!this.parent) {
      return;
    }
    super.onScaleChanging();
    const {
      _drawId,
      _drawingOptions,
      parent
    } = this;
    _drawingOptions.updateSVGProperty("stroke-width");
    parent.drawLayer.updateProperties(_drawId, _drawingOptions.toSVGProperties());
  }
  static onScaleChangingWhenDrawing() {
    const parent = this._currentParent;
    if (!parent) {
      return;
    }
    super.onScaleChangingWhenDrawing();
    this._defaultDrawingOptions.updateSVGProperty("stroke-width");
    parent.drawLayer.updateProperties(this._currentDrawId, this._defaultDrawingOptions.toSVGProperties());
  }
  createDrawingOptions({
    color,
    thickness,
    opacity
  }) {
    this._drawingOptions = _InkEditor.getDefaultDrawingOptions({
      stroke: Util.makeHexColor(...color),
      "stroke-width": thickness,
      "stroke-opacity": opacity
    });
  }
  serialize(isForCopying = false) {
    if (this.isEmpty()) {
      return null;
    }
    if (this.deleted) {
      return this.serializeDeleted();
    }
    const {
      lines,
      points
    } = this.serializeDraw(isForCopying);
    const {
      _drawingOptions: {
        stroke,
        "stroke-opacity": opacity,
        "stroke-width": thickness
      }
    } = this;
    const serialized = Object.assign(super.serialize(isForCopying), {
      color: AnnotationEditor._colorManager.convert(stroke),
      opacity,
      thickness,
      paths: {
        lines,
        points
      }
    });
    this.addComment(serialized);
    if (isForCopying) {
      serialized.isCopy = true;
      return serialized;
    }
    if (this.annotationElementId && !this.#hasElementChanged(serialized)) {
      return null;
    }
    serialized.id = this.annotationElementId;
    return serialized;
  }
  #hasElementChanged(serialized) {
    const {
      color,
      thickness,
      opacity,
      pageIndex
    } = this._initialData;
    return this.hasEditedComment || this._hasBeenMoved || this._hasBeenResized || serialized.color.some((c6, i7) => c6 !== color[i7]) || serialized.thickness !== thickness || serialized.opacity !== opacity || serialized.pageIndex !== pageIndex;
  }
  renderAnnotationElement(annotation) {
    if (this.deleted) {
      annotation.hide();
      return null;
    }
    const {
      points,
      rect
    } = this.serializeDraw(false);
    annotation.updateEdited({
      rect,
      thickness: this._drawingOptions["stroke-width"],
      points,
      popup: this.comment
    });
    return null;
  }
};
var ContourDrawOutline = class extends InkDrawOutline {
  toSVGPath() {
    let path6 = super.toSVGPath();
    if (!path6.endsWith("Z")) {
      path6 += "Z";
    }
    return path6;
  }
};
var BASE_HEADER_LENGTH = 8;
var POINTS_PROPERTIES_NUMBER = 3;
var SignatureExtractor = class {
  static #PARAMETERS = {
    maxDim: 512,
    sigmaSFactor: 0.02,
    sigmaR: 25,
    kernelSize: 16
  };
  static #neighborIndexToId(i0, j0, i7, j3) {
    i7 -= i0;
    j3 -= j0;
    if (i7 === 0) {
      return j3 > 0 ? 0 : 4;
    }
    if (i7 === 1) {
      return j3 + 6;
    }
    return 2 - j3;
  }
  static #neighborIdToIndex = new Int32Array([0, 1, -1, 1, -1, 0, -1, -1, 0, -1, 1, -1, 1, 0, 1, 1]);
  static #clockwiseNonZero(buf, width, i0, j0, i7, j3, offset) {
    const id = this.#neighborIndexToId(i0, j0, i7, j3);
    for (let k2 = 0; k2 < 8; k2++) {
      const kk = (-k2 + id - offset + 16) % 8;
      const shiftI = this.#neighborIdToIndex[2 * kk];
      const shiftJ = this.#neighborIdToIndex[2 * kk + 1];
      if (buf[(i0 + shiftI) * width + (j0 + shiftJ)] !== 0) {
        return kk;
      }
    }
    return -1;
  }
  static #counterClockwiseNonZero(buf, width, i0, j0, i7, j3, offset) {
    const id = this.#neighborIndexToId(i0, j0, i7, j3);
    for (let k2 = 0; k2 < 8; k2++) {
      const kk = (k2 + id + offset + 16) % 8;
      const shiftI = this.#neighborIdToIndex[2 * kk];
      const shiftJ = this.#neighborIdToIndex[2 * kk + 1];
      if (buf[(i0 + shiftI) * width + (j0 + shiftJ)] !== 0) {
        return kk;
      }
    }
    return -1;
  }
  static #findContours(buf, width, height, threshold) {
    const N3 = buf.length;
    const types2 = new Int32Array(N3);
    for (let i7 = 0; i7 < N3; i7++) {
      types2[i7] = buf[i7] <= threshold ? 1 : 0;
    }
    for (let i7 = 1; i7 < height - 1; i7++) {
      types2[i7 * width] = types2[i7 * width + width - 1] = 0;
    }
    for (let i7 = 0; i7 < width; i7++) {
      types2[i7] = types2[width * height - 1 - i7] = 0;
    }
    let nbd = 1;
    let lnbd;
    const contours = [];
    for (let i7 = 1; i7 < height - 1; i7++) {
      lnbd = 1;
      for (let j3 = 1; j3 < width - 1; j3++) {
        const ij = i7 * width + j3;
        const pix = types2[ij];
        if (pix === 0) {
          continue;
        }
        let i22 = i7;
        let j22 = j3;
        if (pix === 1 && types2[ij - 1] === 0) {
          nbd += 1;
          j22 -= 1;
        } else if (pix >= 1 && types2[ij + 1] === 0) {
          nbd += 1;
          j22 += 1;
          if (pix > 1) {
            lnbd = pix;
          }
        } else {
          if (pix !== 1) {
            lnbd = Math.abs(pix);
          }
          continue;
        }
        const points = [j3, i7];
        const isHole = j22 === j3 + 1;
        const contour = {
          isHole,
          points,
          id: nbd,
          parent: 0
        };
        contours.push(contour);
        let contour0;
        for (const c6 of contours) {
          if (c6.id === lnbd) {
            contour0 = c6;
            break;
          }
        }
        if (!contour0) {
          contour.parent = isHole ? lnbd : 0;
        } else if (contour0.isHole) {
          contour.parent = isHole ? contour0.parent : lnbd;
        } else {
          contour.parent = isHole ? lnbd : contour0.parent;
        }
        const k2 = this.#clockwiseNonZero(types2, width, i7, j3, i22, j22, 0);
        if (k2 === -1) {
          types2[ij] = -nbd;
          if (types2[ij] !== 1) {
            lnbd = Math.abs(types2[ij]);
          }
          continue;
        }
        let shiftI = this.#neighborIdToIndex[2 * k2];
        let shiftJ = this.#neighborIdToIndex[2 * k2 + 1];
        const i1 = i7 + shiftI;
        const j1 = j3 + shiftJ;
        i22 = i1;
        j22 = j1;
        let i32 = i7;
        let j32 = j3;
        while (true) {
          const kk = this.#counterClockwiseNonZero(types2, width, i32, j32, i22, j22, 1);
          shiftI = this.#neighborIdToIndex[2 * kk];
          shiftJ = this.#neighborIdToIndex[2 * kk + 1];
          const i42 = i32 + shiftI;
          const j4 = j32 + shiftJ;
          points.push(j4, i42);
          const ij3 = i32 * width + j32;
          if (types2[ij3 + 1] === 0) {
            types2[ij3] = -nbd;
          } else if (types2[ij3] === 1) {
            types2[ij3] = nbd;
          }
          if (i42 === i7 && j4 === j3 && i32 === i1 && j32 === j1) {
            if (types2[ij] !== 1) {
              lnbd = Math.abs(types2[ij]);
            }
            break;
          } else {
            i22 = i32;
            j22 = j32;
            i32 = i42;
            j32 = j4;
          }
        }
      }
    }
    return contours;
  }
  static #douglasPeuckerHelper(points, start, end, output) {
    if (end - start <= 4) {
      for (let i7 = start; i7 < end - 2; i7 += 2) {
        output.push(points[i7], points[i7 + 1]);
      }
      return;
    }
    const ax = points[start];
    const ay = points[start + 1];
    const abx = points[end - 4] - ax;
    const aby = points[end - 3] - ay;
    const dist = Math.hypot(abx, aby);
    const nabx = abx / dist;
    const naby = aby / dist;
    const aa = nabx * ay - naby * ax;
    const m4 = aby / abx;
    const invS = 1 / dist;
    const phi = Math.atan(m4);
    const cosPhi = Math.cos(phi);
    const sinPhi = Math.sin(phi);
    const tmax = invS * (Math.abs(cosPhi) + Math.abs(sinPhi));
    const poly = invS * (1 - tmax + tmax ** 2);
    const partialPhi = Math.max(Math.atan(Math.abs(sinPhi + cosPhi) * poly), Math.atan(Math.abs(sinPhi - cosPhi) * poly));
    let dmax = 0;
    let index = start;
    for (let i7 = start + 2; i7 < end - 2; i7 += 2) {
      const d4 = Math.abs(aa - nabx * points[i7 + 1] + naby * points[i7]);
      if (d4 > dmax) {
        index = i7;
        dmax = d4;
      }
    }
    if (dmax > (dist * partialPhi) ** 2) {
      this.#douglasPeuckerHelper(points, start, index + 2, output);
      this.#douglasPeuckerHelper(points, index, end, output);
    } else {
      output.push(ax, ay);
    }
  }
  static #douglasPeucker(points) {
    const output = [];
    const len = points.length;
    this.#douglasPeuckerHelper(points, 0, len, output);
    output.push(points[len - 2], points[len - 1]);
    return output.length <= 4 ? null : output;
  }
  static #bilateralFilter(buf, width, height, sigmaS, sigmaR, kernelSize) {
    const kernel = new Float32Array(kernelSize ** 2);
    const sigmaS2 = -2 * sigmaS ** 2;
    const halfSize = kernelSize >> 1;
    for (let i7 = 0; i7 < kernelSize; i7++) {
      const x2 = (i7 - halfSize) ** 2;
      for (let j3 = 0; j3 < kernelSize; j3++) {
        kernel[i7 * kernelSize + j3] = Math.exp((x2 + (j3 - halfSize) ** 2) / sigmaS2);
      }
    }
    const rangeValues = new Float32Array(256);
    const sigmaR2 = -2 * sigmaR ** 2;
    for (let i7 = 0; i7 < 256; i7++) {
      rangeValues[i7] = Math.exp(i7 ** 2 / sigmaR2);
    }
    const N3 = buf.length;
    const out = new Uint8Array(N3);
    const histogram = new Uint32Array(256);
    for (let i7 = 0; i7 < height; i7++) {
      for (let j3 = 0; j3 < width; j3++) {
        const ij = i7 * width + j3;
        const center = buf[ij];
        let sum = 0;
        let norm = 0;
        for (let k2 = 0; k2 < kernelSize; k2++) {
          const y4 = i7 + k2 - halfSize;
          if (y4 < 0 || y4 >= height) {
            continue;
          }
          for (let l5 = 0; l5 < kernelSize; l5++) {
            const x2 = j3 + l5 - halfSize;
            if (x2 < 0 || x2 >= width) {
              continue;
            }
            const neighbour = buf[y4 * width + x2];
            const w3 = kernel[k2 * kernelSize + l5] * rangeValues[Math.abs(neighbour - center)];
            sum += neighbour * w3;
            norm += w3;
          }
        }
        const pix = out[ij] = Math.round(sum / norm);
        histogram[pix]++;
      }
    }
    return [out, histogram];
  }
  static #getHistogram(buf) {
    const histogram = new Uint32Array(256);
    for (const g3 of buf) {
      histogram[g3]++;
    }
    return histogram;
  }
  static #toUint8(buf) {
    const N3 = buf.length;
    const out = new Uint8ClampedArray(N3 >> 2);
    let max = -Infinity;
    let min = Infinity;
    for (let i7 = 0, ii = out.length; i7 < ii; i7++) {
      const pix = out[i7] = buf[i7 << 2];
      max = Math.max(max, pix);
      min = Math.min(min, pix);
    }
    const ratio = 255 / (max - min);
    for (let i7 = 0, ii = out.length; i7 < ii; i7++) {
      out[i7] = (out[i7] - min) * ratio;
    }
    return out;
  }
  static #guessThreshold(histogram) {
    let i7;
    let M4 = -Infinity;
    let L3 = -Infinity;
    const min = histogram.findIndex((v4) => v4 !== 0);
    let pos = min;
    let spos = min;
    for (i7 = min; i7 < 256; i7++) {
      const v4 = histogram[i7];
      if (v4 > M4) {
        if (i7 - pos > L3) {
          L3 = i7 - pos;
          spos = i7 - 1;
        }
        M4 = v4;
        pos = i7;
      }
    }
    for (i7 = spos - 1; i7 >= 0; i7--) {
      if (histogram[i7] > histogram[i7 + 1]) {
        break;
      }
    }
    return i7;
  }
  static #getGrayPixels(bitmap) {
    const originalBitmap = bitmap;
    const {
      width,
      height
    } = bitmap;
    const {
      maxDim
    } = this.#PARAMETERS;
    let newWidth = width;
    let newHeight = height;
    if (width > maxDim || height > maxDim) {
      let prevWidth = width;
      let prevHeight = height;
      let steps = Math.log2(Math.max(width, height) / maxDim);
      const isteps = Math.floor(steps);
      steps = steps === isteps ? isteps - 1 : isteps;
      for (let i7 = 0; i7 < steps; i7++) {
        newWidth = Math.ceil(prevWidth / 2);
        newHeight = Math.ceil(prevHeight / 2);
        const offscreen2 = new OffscreenCanvas(newWidth, newHeight);
        const ctx2 = offscreen2.getContext("2d");
        ctx2.drawImage(bitmap, 0, 0, prevWidth, prevHeight, 0, 0, newWidth, newHeight);
        prevWidth = newWidth;
        prevHeight = newHeight;
        if (bitmap !== originalBitmap) {
          bitmap.close();
        }
        bitmap = offscreen2.transferToImageBitmap();
      }
      const ratio = Math.min(maxDim / newWidth, maxDim / newHeight);
      newWidth = Math.round(newWidth * ratio);
      newHeight = Math.round(newHeight * ratio);
    }
    const offscreen = new OffscreenCanvas(newWidth, newHeight);
    const ctx = offscreen.getContext("2d", {
      willReadFrequently: true
    });
    ctx.fillStyle = "white";
    ctx.fillRect(0, 0, newWidth, newHeight);
    ctx.filter = "grayscale(1)";
    ctx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, newWidth, newHeight);
    const grayImage = ctx.getImageData(0, 0, newWidth, newHeight).data;
    const uint8Buf = this.#toUint8(grayImage);
    return [uint8Buf, newWidth, newHeight];
  }
  static extractContoursFromText(text3, {
    fontFamily,
    fontStyle,
    fontWeight
  }, pageWidth, pageHeight, rotation, innerMargin) {
    let canvas = new OffscreenCanvas(1, 1);
    let ctx = canvas.getContext("2d", {
      alpha: false
    });
    const fontSize = 200;
    const font = ctx.font = `${fontStyle} ${fontWeight} ${fontSize}px ${fontFamily}`;
    const {
      actualBoundingBoxLeft,
      actualBoundingBoxRight,
      actualBoundingBoxAscent,
      actualBoundingBoxDescent,
      fontBoundingBoxAscent,
      fontBoundingBoxDescent,
      width
    } = ctx.measureText(text3);
    const SCALE = 1.5;
    const canvasWidth = Math.ceil(Math.max(Math.abs(actualBoundingBoxLeft) + Math.abs(actualBoundingBoxRight) || 0, width) * SCALE);
    const canvasHeight = Math.ceil(Math.max(Math.abs(actualBoundingBoxAscent) + Math.abs(actualBoundingBoxDescent) || fontSize, Math.abs(fontBoundingBoxAscent) + Math.abs(fontBoundingBoxDescent) || fontSize) * SCALE);
    canvas = new OffscreenCanvas(canvasWidth, canvasHeight);
    ctx = canvas.getContext("2d", {
      alpha: true,
      willReadFrequently: true
    });
    ctx.font = font;
    ctx.filter = "grayscale(1)";
    ctx.fillStyle = "white";
    ctx.fillRect(0, 0, canvasWidth, canvasHeight);
    ctx.fillStyle = "black";
    ctx.fillText(text3, canvasWidth * (SCALE - 1) / 2, canvasHeight * (3 - SCALE) / 2);
    const uint8Buf = this.#toUint8(ctx.getImageData(0, 0, canvasWidth, canvasHeight).data);
    const histogram = this.#getHistogram(uint8Buf);
    const threshold = this.#guessThreshold(histogram);
    const contourList = this.#findContours(uint8Buf, canvasWidth, canvasHeight, threshold);
    return this.processDrawnLines({
      lines: {
        curves: contourList,
        width: canvasWidth,
        height: canvasHeight
      },
      pageWidth,
      pageHeight,
      rotation,
      innerMargin,
      mustSmooth: true,
      areContours: true
    });
  }
  static process(bitmap, pageWidth, pageHeight, rotation, innerMargin) {
    const [uint8Buf, width, height] = this.#getGrayPixels(bitmap);
    const [buffer, histogram] = this.#bilateralFilter(uint8Buf, width, height, Math.hypot(width, height) * this.#PARAMETERS.sigmaSFactor, this.#PARAMETERS.sigmaR, this.#PARAMETERS.kernelSize);
    const threshold = this.#guessThreshold(histogram);
    const contourList = this.#findContours(buffer, width, height, threshold);
    return this.processDrawnLines({
      lines: {
        curves: contourList,
        width,
        height
      },
      pageWidth,
      pageHeight,
      rotation,
      innerMargin,
      mustSmooth: true,
      areContours: true
    });
  }
  static processDrawnLines({
    lines,
    pageWidth,
    pageHeight,
    rotation,
    innerMargin,
    mustSmooth,
    areContours
  }) {
    if (rotation % 180 !== 0) {
      [pageWidth, pageHeight] = [pageHeight, pageWidth];
    }
    const {
      curves,
      width,
      height
    } = lines;
    const thickness = lines.thickness ?? 0;
    const linesAndPoints = [];
    const ratio = Math.min(pageWidth / width, pageHeight / height);
    const xScale = ratio / pageWidth;
    const yScale = ratio / pageHeight;
    const newCurves = [];
    for (const {
      points
    } of curves) {
      const reducedPoints = mustSmooth ? this.#douglasPeucker(points) : points;
      if (!reducedPoints) {
        continue;
      }
      newCurves.push(reducedPoints);
      const len = reducedPoints.length;
      const newPoints = new Float32Array(len);
      const line = new Float32Array(3 * (len === 2 ? 2 : len - 2));
      linesAndPoints.push({
        line,
        points: newPoints
      });
      if (len === 2) {
        newPoints[0] = reducedPoints[0] * xScale;
        newPoints[1] = reducedPoints[1] * yScale;
        line.set([NaN, NaN, NaN, NaN, newPoints[0], newPoints[1]], 0);
        continue;
      }
      let [x1, y1, x2, y22] = reducedPoints;
      x1 *= xScale;
      y1 *= yScale;
      x2 *= xScale;
      y22 *= yScale;
      newPoints.set([x1, y1, x2, y22], 0);
      line.set([NaN, NaN, NaN, NaN, x1, y1], 0);
      for (let i7 = 4; i7 < len; i7 += 2) {
        const x3 = newPoints[i7] = reducedPoints[i7] * xScale;
        const y4 = newPoints[i7 + 1] = reducedPoints[i7 + 1] * yScale;
        line.set(Outline.createBezierPoints(x1, y1, x2, y22, x3, y4), (i7 - 2) * 3);
        [x1, y1, x2, y22] = [x2, y22, x3, y4];
      }
    }
    if (linesAndPoints.length === 0) {
      return null;
    }
    const outline = areContours ? new ContourDrawOutline() : new InkDrawOutline();
    outline.build(linesAndPoints, pageWidth, pageHeight, 1, rotation, areContours ? 0 : thickness, innerMargin);
    return {
      outline,
      newCurves,
      areContours,
      thickness,
      width,
      height
    };
  }
  static async compressSignature({
    outlines,
    areContours,
    thickness,
    width,
    height
  }) {
    let minDiff = Infinity;
    let maxDiff = -Infinity;
    let outlinesLength = 0;
    for (const points of outlines) {
      outlinesLength += points.length;
      for (let i7 = 2, ii = points.length; i7 < ii; i7++) {
        const dx = points[i7] - points[i7 - 2];
        minDiff = Math.min(minDiff, dx);
        maxDiff = Math.max(maxDiff, dx);
      }
    }
    let bufferType;
    if (minDiff >= -128 && maxDiff <= 127) {
      bufferType = Int8Array;
    } else if (minDiff >= -32768 && maxDiff <= 32767) {
      bufferType = Int16Array;
    } else {
      bufferType = Int32Array;
    }
    const len = outlines.length;
    const headerLength = BASE_HEADER_LENGTH + POINTS_PROPERTIES_NUMBER * len;
    const header = new Uint32Array(headerLength);
    let offset = 0;
    header[offset++] = headerLength * Uint32Array.BYTES_PER_ELEMENT + (outlinesLength - 2 * len) * bufferType.BYTES_PER_ELEMENT;
    header[offset++] = 0;
    header[offset++] = width;
    header[offset++] = height;
    header[offset++] = areContours ? 0 : 1;
    header[offset++] = Math.max(0, Math.floor(thickness ?? 0));
    header[offset++] = len;
    header[offset++] = bufferType.BYTES_PER_ELEMENT;
    for (const points of outlines) {
      header[offset++] = points.length - 2;
      header[offset++] = points[0];
      header[offset++] = points[1];
    }
    const cs = new CompressionStream("deflate-raw");
    const writer = cs.writable.getWriter();
    await writer.ready;
    writer.write(header);
    const BufferCtor = bufferType.prototype.constructor;
    for (const points of outlines) {
      const diffs = new BufferCtor(points.length - 2);
      for (let i7 = 2, ii = points.length; i7 < ii; i7++) {
        diffs[i7 - 2] = points[i7] - points[i7 - 2];
      }
      writer.write(diffs);
    }
    writer.close();
    const buf = await new Response(cs.readable).arrayBuffer();
    const bytes = new Uint8Array(buf);
    return toBase64Util(bytes);
  }
  static async decompressSignature(signatureData) {
    try {
      const bytes = fromBase64Util(signatureData);
      const {
        readable,
        writable
      } = new DecompressionStream("deflate-raw");
      const writer = writable.getWriter();
      await writer.ready;
      writer.write(bytes).then(async () => {
        await writer.ready;
        await writer.close();
      }).catch(() => {
      });
      let data = null;
      let offset = 0;
      for await (const chunk of readable) {
        data ||= new Uint8Array(new Uint32Array(chunk.buffer, 0, 4)[0]);
        data.set(chunk, offset);
        offset += chunk.length;
      }
      const header = new Uint32Array(data.buffer, 0, data.length >> 2);
      const version5 = header[1];
      if (version5 !== 0) {
        throw new Error(`Invalid version: ${version5}`);
      }
      const width = header[2];
      const height = header[3];
      const areContours = header[4] === 0;
      const thickness = header[5];
      const numberOfDrawings = header[6];
      const bufferType = header[7];
      const outlines = [];
      const diffsOffset = (BASE_HEADER_LENGTH + POINTS_PROPERTIES_NUMBER * numberOfDrawings) * Uint32Array.BYTES_PER_ELEMENT;
      let diffs;
      switch (bufferType) {
        case Int8Array.BYTES_PER_ELEMENT:
          diffs = new Int8Array(data.buffer, diffsOffset);
          break;
        case Int16Array.BYTES_PER_ELEMENT:
          diffs = new Int16Array(data.buffer, diffsOffset);
          break;
        case Int32Array.BYTES_PER_ELEMENT:
          diffs = new Int32Array(data.buffer, diffsOffset);
          break;
      }
      offset = 0;
      for (let i7 = 0; i7 < numberOfDrawings; i7++) {
        const len = header[POINTS_PROPERTIES_NUMBER * i7 + BASE_HEADER_LENGTH];
        const points = new Float32Array(len + 2);
        outlines.push(points);
        for (let j3 = 0; j3 < POINTS_PROPERTIES_NUMBER - 1; j3++) {
          points[j3] = header[POINTS_PROPERTIES_NUMBER * i7 + BASE_HEADER_LENGTH + j3 + 1];
        }
        for (let j3 = 0; j3 < len; j3++) {
          points[j3 + 2] = points[j3] + diffs[offset++];
        }
      }
      return {
        areContours,
        thickness,
        outlines,
        width,
        height
      };
    } catch (e9) {
      warn(`decompressSignature: ${e9}`);
      return null;
    }
  }
};
var SignatureOptions = class _SignatureOptions extends DrawingOptions {
  constructor() {
    super();
    super.updateProperties({
      fill: AnnotationEditor._defaultLineColor,
      "stroke-width": 0
    });
  }
  clone() {
    const clone = new _SignatureOptions();
    clone.updateAll(this);
    return clone;
  }
};
var DrawnSignatureOptions = class _DrawnSignatureOptions extends InkDrawingOptions {
  constructor(viewerParameters) {
    super(viewerParameters);
    super.updateProperties({
      stroke: AnnotationEditor._defaultLineColor,
      "stroke-width": 1
    });
  }
  clone() {
    const clone = new _DrawnSignatureOptions(this._viewParameters);
    clone.updateAll(this);
    return clone;
  }
};
var SignatureEditor = class _SignatureEditor extends DrawingEditor {
  #isExtracted = false;
  #description = null;
  #signatureData = null;
  #signatureUUID = null;
  static _type = "signature";
  static _editorType = AnnotationEditorType.SIGNATURE;
  static _defaultDrawingOptions = null;
  constructor(params) {
    super({
      ...params,
      mustBeCommitted: true,
      name: "signatureEditor"
    });
    this._willKeepAspectRatio = true;
    this.#signatureData = params.signatureData || null;
    this.#description = null;
    this.defaultL10nId = "pdfjs-editor-signature-editor1";
  }
  static initialize(l10n, uiManager) {
    AnnotationEditor.initialize(l10n, uiManager);
    this._defaultDrawingOptions = new SignatureOptions();
    this._defaultDrawnSignatureOptions = new DrawnSignatureOptions(uiManager.viewParameters);
  }
  static getDefaultDrawingOptions(options) {
    const clone = this._defaultDrawingOptions.clone();
    clone.updateProperties(options);
    return clone;
  }
  static get supportMultipleDrawings() {
    return false;
  }
  static get typesMap() {
    return shadow(this, "typesMap", /* @__PURE__ */ new Map());
  }
  static get isDrawer() {
    return false;
  }
  get telemetryFinalData() {
    return {
      type: "signature",
      hasDescription: !!this.#description
    };
  }
  static computeTelemetryFinalData(data) {
    const hasDescriptionStats = data.get("hasDescription");
    return {
      hasAltText: hasDescriptionStats.get(true) ?? 0,
      hasNoAltText: hasDescriptionStats.get(false) ?? 0
    };
  }
  get isResizable() {
    return true;
  }
  onScaleChanging() {
    if (this._drawId === null) {
      return;
    }
    super.onScaleChanging();
  }
  render() {
    if (this.div) {
      return this.div;
    }
    let baseX, baseY;
    const {
      _isCopy
    } = this;
    if (_isCopy) {
      this._isCopy = false;
      baseX = this.x;
      baseY = this.y;
    }
    super.render();
    if (this._drawId === null) {
      if (this.#signatureData) {
        const {
          lines,
          mustSmooth,
          areContours,
          description,
          uuid,
          heightInPage
        } = this.#signatureData;
        const {
          rawDims: {
            pageWidth,
            pageHeight
          },
          rotation
        } = this.parent.viewport;
        const outline = SignatureExtractor.processDrawnLines({
          lines,
          pageWidth,
          pageHeight,
          rotation,
          innerMargin: _SignatureEditor._INNER_MARGIN,
          mustSmooth,
          areContours
        });
        this.addSignature(outline, heightInPage, description, uuid);
      } else {
        this.div.setAttribute("data-l10n-args", JSON.stringify({
          description: ""
        }));
        this.div.hidden = true;
        this._uiManager.getSignature(this);
      }
    } else {
      this.div.setAttribute("data-l10n-args", JSON.stringify({
        description: this.#description || ""
      }));
    }
    if (_isCopy) {
      this._isCopy = true;
      this._moveAfterPaste(baseX, baseY);
    }
    return this.div;
  }
  setUuid(uuid) {
    this.#signatureUUID = uuid;
    this.addEditToolbar();
  }
  getUuid() {
    return this.#signatureUUID;
  }
  get description() {
    return this.#description;
  }
  set description(description) {
    this.#description = description;
    if (!this.div) {
      return;
    }
    this.div.setAttribute("data-l10n-args", JSON.stringify({
      description
    }));
    super.addEditToolbar().then((toolbar) => {
      toolbar?.updateEditSignatureButton(description);
    });
  }
  getSignaturePreview() {
    const {
      newCurves,
      areContours,
      thickness,
      width,
      height
    } = this.#signatureData;
    const maxDim = Math.max(width, height);
    const outlineData = SignatureExtractor.processDrawnLines({
      lines: {
        curves: newCurves.map((points) => ({
          points
        })),
        thickness,
        width,
        height
      },
      pageWidth: maxDim,
      pageHeight: maxDim,
      rotation: 0,
      innerMargin: 0,
      mustSmooth: false,
      areContours
    });
    return {
      areContours,
      outline: outlineData.outline
    };
  }
  get toolbarButtons() {
    if (this._uiManager.signatureManager) {
      return [["editSignature", this._uiManager.signatureManager]];
    }
    return super.toolbarButtons;
  }
  addSignature(data, heightInPage, description, uuid) {
    const {
      x: savedX,
      y: savedY
    } = this;
    const {
      outline
    } = this.#signatureData = data;
    this.#isExtracted = outline instanceof ContourDrawOutline;
    this.description = description;
    let drawingOptions;
    if (this.#isExtracted) {
      drawingOptions = _SignatureEditor.getDefaultDrawingOptions();
    } else {
      drawingOptions = _SignatureEditor._defaultDrawnSignatureOptions.clone();
      drawingOptions.updateProperties({
        "stroke-width": outline.thickness
      });
    }
    this._addOutlines({
      drawOutlines: outline,
      drawingOptions
    });
    const [, pageHeight] = this.pageDimensions;
    let newHeight = heightInPage / pageHeight;
    newHeight = newHeight >= 1 ? 0.5 : newHeight;
    this.width *= newHeight / this.height;
    if (this.width >= 1) {
      newHeight *= 0.9 / this.width;
      this.width = 0.9;
    }
    this.height = newHeight;
    this.setDims();
    this.x = savedX;
    this.y = savedY;
    this.center();
    this._onResized();
    this.onScaleChanging();
    this.rotate();
    this._uiManager.addToAnnotationStorage(this);
    this.setUuid(uuid);
    this._reportTelemetry({
      action: "pdfjs.signature.inserted",
      data: {
        hasBeenSaved: !!uuid,
        hasDescription: !!description
      }
    });
    this.div.hidden = false;
  }
  getFromImage(bitmap) {
    const {
      rawDims: {
        pageWidth,
        pageHeight
      },
      rotation
    } = this.parent.viewport;
    return SignatureExtractor.process(bitmap, pageWidth, pageHeight, rotation, _SignatureEditor._INNER_MARGIN);
  }
  getFromText(text3, fontInfo) {
    const {
      rawDims: {
        pageWidth,
        pageHeight
      },
      rotation
    } = this.parent.viewport;
    return SignatureExtractor.extractContoursFromText(text3, fontInfo, pageWidth, pageHeight, rotation, _SignatureEditor._INNER_MARGIN);
  }
  getDrawnSignature(curves) {
    const {
      rawDims: {
        pageWidth,
        pageHeight
      },
      rotation
    } = this.parent.viewport;
    return SignatureExtractor.processDrawnLines({
      lines: curves,
      pageWidth,
      pageHeight,
      rotation,
      innerMargin: _SignatureEditor._INNER_MARGIN,
      mustSmooth: false,
      areContours: false
    });
  }
  createDrawingOptions({
    areContours,
    thickness
  }) {
    if (areContours) {
      this._drawingOptions = _SignatureEditor.getDefaultDrawingOptions();
    } else {
      this._drawingOptions = _SignatureEditor._defaultDrawnSignatureOptions.clone();
      this._drawingOptions.updateProperties({
        "stroke-width": thickness
      });
    }
  }
  serialize(isForCopying = false) {
    if (this.isEmpty()) {
      return null;
    }
    const {
      lines,
      points
    } = this.serializeDraw(isForCopying);
    const {
      _drawingOptions: {
        "stroke-width": thickness
      }
    } = this;
    const serialized = Object.assign(super.serialize(isForCopying), {
      isSignature: true,
      areContours: this.#isExtracted,
      color: [0, 0, 0],
      thickness: this.#isExtracted ? 0 : thickness
    });
    this.addComment(serialized);
    if (isForCopying) {
      serialized.paths = {
        lines,
        points
      };
      serialized.uuid = this.#signatureUUID;
      serialized.isCopy = true;
    } else {
      serialized.lines = lines;
    }
    if (this.#description) {
      serialized.accessibilityData = {
        type: "Figure",
        alt: this.#description
      };
    }
    return serialized;
  }
  static deserializeDraw(pageX, pageY, pageWidth, pageHeight, innerMargin, data) {
    if (data.areContours) {
      return ContourDrawOutline.deserialize(pageX, pageY, pageWidth, pageHeight, innerMargin, data);
    }
    return InkDrawOutline.deserialize(pageX, pageY, pageWidth, pageHeight, innerMargin, data);
  }
  static async deserialize(data, parent, uiManager) {
    const editor = await super.deserialize(data, parent, uiManager);
    editor.#isExtracted = data.areContours;
    editor.description = data.accessibilityData?.alt || "";
    editor.#signatureUUID = data.uuid;
    return editor;
  }
};
var StampEditor = class extends AnnotationEditor {
  #bitmap = null;
  #bitmapId = null;
  #bitmapPromise = null;
  #bitmapUrl = null;
  #bitmapFile = null;
  #bitmapFileName = "";
  #canvas = null;
  #missingCanvas = false;
  #resizeTimeoutId = null;
  #isSvg = false;
  #hasBeenAddedInUndoStack = false;
  static _type = "stamp";
  static _editorType = AnnotationEditorType.STAMP;
  constructor(params) {
    super({
      ...params,
      name: "stampEditor"
    });
    this.#bitmapUrl = params.bitmapUrl;
    this.#bitmapFile = params.bitmapFile;
    this.defaultL10nId = "pdfjs-editor-stamp-editor";
  }
  static initialize(l10n, uiManager) {
    AnnotationEditor.initialize(l10n, uiManager);
  }
  static isHandlingMimeForPasting(mime) {
    return SupportedImageMimeTypes.includes(mime);
  }
  static paste(item, parent) {
    parent.pasteEditor({
      mode: AnnotationEditorType.STAMP
    }, {
      bitmapFile: item.getAsFile()
    });
  }
  altTextFinish() {
    if (this._uiManager.useNewAltTextFlow) {
      this.div.hidden = false;
    }
    super.altTextFinish();
  }
  get telemetryFinalData() {
    return {
      type: "stamp",
      hasAltText: !!this.altTextData?.altText
    };
  }
  static computeTelemetryFinalData(data) {
    const hasAltTextStats = data.get("hasAltText");
    return {
      hasAltText: hasAltTextStats.get(true) ?? 0,
      hasNoAltText: hasAltTextStats.get(false) ?? 0
    };
  }
  #getBitmapFetched(data, fromId = false) {
    if (!data) {
      this.remove();
      return;
    }
    this.#bitmap = data.bitmap;
    if (!fromId) {
      this.#bitmapId = data.id;
      this.#isSvg = data.isSvg;
    }
    if (data.file) {
      this.#bitmapFileName = data.file.name;
    }
    this.#createCanvas();
  }
  #getBitmapDone() {
    this.#bitmapPromise = null;
    this._uiManager.enableWaiting(false);
    if (!this.#canvas) {
      return;
    }
    if (this._uiManager.useNewAltTextWhenAddingImage && this._uiManager.useNewAltTextFlow && this.#bitmap) {
      this.addEditToolbar().then(() => {
        this._editToolbar.hide();
        this._uiManager.editAltText(this, true);
      });
      return;
    }
    if (!this._uiManager.useNewAltTextWhenAddingImage && this._uiManager.useNewAltTextFlow && this.#bitmap) {
      this._reportTelemetry({
        action: "pdfjs.image.image_added",
        data: {
          alt_text_modal: false,
          alt_text_type: "empty"
        }
      });
      try {
        this.mlGuessAltText();
      } catch {
      }
    }
    this.div.focus();
  }
  async mlGuessAltText(imageData = null, updateAltTextData = true) {
    if (this.hasAltTextData()) {
      return null;
    }
    const {
      mlManager
    } = this._uiManager;
    if (!mlManager) {
      throw new Error("No ML.");
    }
    if (!await mlManager.isEnabledFor("altText")) {
      throw new Error("ML isn't enabled for alt text.");
    }
    const {
      data,
      width,
      height
    } = imageData || this.copyCanvas(null, null, true).imageData;
    const response = await mlManager.guess({
      name: "altText",
      request: {
        data,
        width,
        height,
        channels: data.length / (width * height)
      }
    });
    if (!response) {
      throw new Error("No response from the AI service.");
    }
    if (response.error) {
      throw new Error("Error from the AI service.");
    }
    if (response.cancel) {
      return null;
    }
    if (!response.output) {
      throw new Error("No valid response from the AI service.");
    }
    const altText = response.output;
    await this.setGuessedAltText(altText);
    if (updateAltTextData && !this.hasAltTextData()) {
      this.altTextData = {
        alt: altText,
        decorative: false
      };
    }
    return altText;
  }
  #getBitmap() {
    if (this.#bitmapId) {
      this._uiManager.enableWaiting(true);
      this._uiManager.imageManager.getFromId(this.#bitmapId).then((data) => this.#getBitmapFetched(data, true)).finally(() => this.#getBitmapDone());
      return;
    }
    if (this.#bitmapUrl) {
      const url = this.#bitmapUrl;
      this.#bitmapUrl = null;
      this._uiManager.enableWaiting(true);
      this.#bitmapPromise = this._uiManager.imageManager.getFromUrl(url).then((data) => this.#getBitmapFetched(data)).finally(() => this.#getBitmapDone());
      return;
    }
    if (this.#bitmapFile) {
      const file = this.#bitmapFile;
      this.#bitmapFile = null;
      this._uiManager.enableWaiting(true);
      this.#bitmapPromise = this._uiManager.imageManager.getFromFile(file).then((data) => this.#getBitmapFetched(data)).finally(() => this.#getBitmapDone());
      return;
    }
    const input = document.createElement("input");
    input.type = "file";
    input.accept = SupportedImageMimeTypes.join(",");
    const signal = this._uiManager._signal;
    this.#bitmapPromise = new Promise((resolve) => {
      input.addEventListener("change", async () => {
        if (!input.files || input.files.length === 0) {
          this.remove();
        } else {
          this._uiManager.enableWaiting(true);
          const data = await this._uiManager.imageManager.getFromFile(input.files[0]);
          this._reportTelemetry({
            action: "pdfjs.image.image_selected",
            data: {
              alt_text_modal: this._uiManager.useNewAltTextFlow
            }
          });
          this.#getBitmapFetched(data);
        }
        resolve();
      }, {
        signal
      });
      input.addEventListener("cancel", () => {
        this.remove();
        resolve();
      }, {
        signal
      });
    }).finally(() => this.#getBitmapDone());
    input.click();
  }
  remove() {
    if (this.#bitmapId) {
      this.#bitmap = null;
      this._uiManager.imageManager.deleteId(this.#bitmapId);
      this.#canvas?.remove();
      this.#canvas = null;
      if (this.#resizeTimeoutId) {
        clearTimeout(this.#resizeTimeoutId);
        this.#resizeTimeoutId = null;
      }
    }
    super.remove();
  }
  rebuild() {
    if (!this.parent) {
      if (this.#bitmapId) {
        this.#getBitmap();
      }
      return;
    }
    super.rebuild();
    if (this.div === null) {
      return;
    }
    if (this.#bitmapId && this.#canvas === null) {
      this.#getBitmap();
    }
    if (!this.isAttachedToDOM) {
      this.parent.add(this);
    }
  }
  onceAdded(focus) {
    this._isDraggable = true;
    if (focus) {
      this.div.focus();
    }
  }
  isEmpty() {
    return !(this.#bitmapPromise || this.#bitmap || this.#bitmapUrl || this.#bitmapFile || this.#bitmapId || this.#missingCanvas);
  }
  get toolbarButtons() {
    return [["altText", this.createAltText()]];
  }
  get isResizable() {
    return true;
  }
  render() {
    if (this.div) {
      return this.div;
    }
    let baseX, baseY;
    if (this._isCopy) {
      baseX = this.x;
      baseY = this.y;
    }
    super.render();
    this.div.hidden = true;
    this.createAltText();
    if (!this.#missingCanvas) {
      if (this.#bitmap) {
        this.#createCanvas();
      } else {
        this.#getBitmap();
      }
    }
    if (this._isCopy) {
      this._moveAfterPaste(baseX, baseY);
    }
    this._uiManager.addShouldRescale(this);
    return this.div;
  }
  setCanvas(annotationElementId, canvas) {
    const {
      id: bitmapId,
      bitmap
    } = this._uiManager.imageManager.getFromCanvas(annotationElementId, canvas);
    canvas.remove();
    if (bitmapId && this._uiManager.imageManager.isValidId(bitmapId)) {
      this.#bitmapId = bitmapId;
      if (bitmap) {
        this.#bitmap = bitmap;
      }
      this.#missingCanvas = false;
      this.#createCanvas();
    }
  }
  _onResized() {
    this.onScaleChanging();
  }
  onScaleChanging() {
    if (!this.parent) {
      return;
    }
    if (this.#resizeTimeoutId !== null) {
      clearTimeout(this.#resizeTimeoutId);
    }
    const TIME_TO_WAIT = 200;
    this.#resizeTimeoutId = setTimeout(() => {
      this.#resizeTimeoutId = null;
      this.#drawBitmap();
    }, TIME_TO_WAIT);
  }
  #createCanvas() {
    const {
      div
    } = this;
    let {
      width,
      height
    } = this.#bitmap;
    const [pageWidth, pageHeight] = this.pageDimensions;
    const MAX_RATIO = 0.75;
    if (this.width) {
      width = this.width * pageWidth;
      height = this.height * pageHeight;
    } else if (width > MAX_RATIO * pageWidth || height > MAX_RATIO * pageHeight) {
      const factor = Math.min(MAX_RATIO * pageWidth / width, MAX_RATIO * pageHeight / height);
      width *= factor;
      height *= factor;
    }
    this._uiManager.enableWaiting(false);
    const canvas = this.#canvas = document.createElement("canvas");
    canvas.setAttribute("role", "img");
    this.addContainer(canvas);
    this.width = width / pageWidth;
    this.height = height / pageHeight;
    this.setDims();
    if (this._initialOptions?.isCentered) {
      this.center();
    } else {
      this.fixAndSetPosition();
    }
    this._initialOptions = null;
    if (!this._uiManager.useNewAltTextWhenAddingImage || !this._uiManager.useNewAltTextFlow || this.annotationElementId) {
      div.hidden = false;
    }
    this.#drawBitmap();
    if (!this.#hasBeenAddedInUndoStack) {
      this.parent.addUndoableEditor(this);
      this.#hasBeenAddedInUndoStack = true;
    }
    this._reportTelemetry({
      action: "inserted_image"
    });
    if (this.#bitmapFileName) {
      this.div.setAttribute("aria-description", this.#bitmapFileName);
    }
    if (!this.annotationElementId) {
      this._uiManager.a11yAlert("pdfjs-editor-stamp-added-alert");
    }
  }
  copyCanvas(maxDataDimension, maxPreviewDimension, createImageData = false) {
    if (!maxDataDimension) {
      maxDataDimension = 224;
    }
    const {
      width: bitmapWidth,
      height: bitmapHeight
    } = this.#bitmap;
    const outputScale = new OutputScale();
    let bitmap = this.#bitmap;
    let width = bitmapWidth, height = bitmapHeight;
    let canvas = null;
    if (maxPreviewDimension) {
      if (bitmapWidth > maxPreviewDimension || bitmapHeight > maxPreviewDimension) {
        const ratio = Math.min(maxPreviewDimension / bitmapWidth, maxPreviewDimension / bitmapHeight);
        width = Math.floor(bitmapWidth * ratio);
        height = Math.floor(bitmapHeight * ratio);
      }
      canvas = document.createElement("canvas");
      const scaledWidth = canvas.width = Math.ceil(width * outputScale.sx);
      const scaledHeight = canvas.height = Math.ceil(height * outputScale.sy);
      if (!this.#isSvg) {
        bitmap = this.#scaleBitmap(scaledWidth, scaledHeight);
      }
      const ctx = canvas.getContext("2d");
      ctx.filter = this._uiManager.hcmFilter;
      let white = "white", black = "#cfcfd8";
      if (this._uiManager.hcmFilter !== "none") {
        black = "black";
      } else if (ColorScheme.isDarkMode) {
        white = "#8f8f9d";
        black = "#42414d";
      }
      const boxDim = 15;
      const boxDimWidth = boxDim * outputScale.sx;
      const boxDimHeight = boxDim * outputScale.sy;
      const pattern = new OffscreenCanvas(boxDimWidth * 2, boxDimHeight * 2);
      const patternCtx = pattern.getContext("2d");
      patternCtx.fillStyle = white;
      patternCtx.fillRect(0, 0, boxDimWidth * 2, boxDimHeight * 2);
      patternCtx.fillStyle = black;
      patternCtx.fillRect(0, 0, boxDimWidth, boxDimHeight);
      patternCtx.fillRect(boxDimWidth, boxDimHeight, boxDimWidth, boxDimHeight);
      ctx.fillStyle = ctx.createPattern(pattern, "repeat");
      ctx.fillRect(0, 0, scaledWidth, scaledHeight);
      ctx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, scaledWidth, scaledHeight);
    }
    let imageData = null;
    if (createImageData) {
      let dataWidth, dataHeight;
      if (outputScale.symmetric && bitmap.width < maxDataDimension && bitmap.height < maxDataDimension) {
        dataWidth = bitmap.width;
        dataHeight = bitmap.height;
      } else {
        bitmap = this.#bitmap;
        if (bitmapWidth > maxDataDimension || bitmapHeight > maxDataDimension) {
          const ratio = Math.min(maxDataDimension / bitmapWidth, maxDataDimension / bitmapHeight);
          dataWidth = Math.floor(bitmapWidth * ratio);
          dataHeight = Math.floor(bitmapHeight * ratio);
          if (!this.#isSvg) {
            bitmap = this.#scaleBitmap(dataWidth, dataHeight);
          }
        }
      }
      const offscreen = new OffscreenCanvas(dataWidth, dataHeight);
      const offscreenCtx = offscreen.getContext("2d", {
        willReadFrequently: true
      });
      offscreenCtx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, dataWidth, dataHeight);
      imageData = {
        width: dataWidth,
        height: dataHeight,
        data: offscreenCtx.getImageData(0, 0, dataWidth, dataHeight).data
      };
    }
    return {
      canvas,
      width,
      height,
      imageData
    };
  }
  #scaleBitmap(width, height) {
    const {
      width: bitmapWidth,
      height: bitmapHeight
    } = this.#bitmap;
    let newWidth = bitmapWidth;
    let newHeight = bitmapHeight;
    let bitmap = this.#bitmap;
    while (newWidth > 2 * width || newHeight > 2 * height) {
      const prevWidth = newWidth;
      const prevHeight = newHeight;
      if (newWidth > 2 * width) {
        newWidth = newWidth >= 16384 ? Math.floor(newWidth / 2) - 1 : Math.ceil(newWidth / 2);
      }
      if (newHeight > 2 * height) {
        newHeight = newHeight >= 16384 ? Math.floor(newHeight / 2) - 1 : Math.ceil(newHeight / 2);
      }
      const offscreen = new OffscreenCanvas(newWidth, newHeight);
      const ctx = offscreen.getContext("2d");
      ctx.drawImage(bitmap, 0, 0, prevWidth, prevHeight, 0, 0, newWidth, newHeight);
      bitmap = offscreen.transferToImageBitmap();
    }
    return bitmap;
  }
  #drawBitmap() {
    const [parentWidth, parentHeight] = this.parentDimensions;
    const {
      width,
      height
    } = this;
    const outputScale = new OutputScale();
    const scaledWidth = Math.ceil(width * parentWidth * outputScale.sx);
    const scaledHeight = Math.ceil(height * parentHeight * outputScale.sy);
    const canvas = this.#canvas;
    if (!canvas || canvas.width === scaledWidth && canvas.height === scaledHeight) {
      return;
    }
    canvas.width = scaledWidth;
    canvas.height = scaledHeight;
    const bitmap = this.#isSvg ? this.#bitmap : this.#scaleBitmap(scaledWidth, scaledHeight);
    const ctx = canvas.getContext("2d");
    ctx.filter = this._uiManager.hcmFilter;
    ctx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, scaledWidth, scaledHeight);
  }
  #serializeBitmap(toUrl) {
    if (toUrl) {
      if (this.#isSvg) {
        const url = this._uiManager.imageManager.getSvgUrl(this.#bitmapId);
        if (url) {
          return url;
        }
      }
      const canvas = document.createElement("canvas");
      ({
        width: canvas.width,
        height: canvas.height
      } = this.#bitmap);
      const ctx = canvas.getContext("2d");
      ctx.drawImage(this.#bitmap, 0, 0);
      return canvas.toDataURL();
    }
    if (this.#isSvg) {
      const [pageWidth, pageHeight] = this.pageDimensions;
      const width = Math.round(this.width * pageWidth * PixelsPerInch.PDF_TO_CSS_UNITS);
      const height = Math.round(this.height * pageHeight * PixelsPerInch.PDF_TO_CSS_UNITS);
      const offscreen = new OffscreenCanvas(width, height);
      const ctx = offscreen.getContext("2d");
      ctx.drawImage(this.#bitmap, 0, 0, this.#bitmap.width, this.#bitmap.height, 0, 0, width, height);
      return offscreen.transferToImageBitmap();
    }
    return structuredClone(this.#bitmap);
  }
  static async deserialize(data, parent, uiManager) {
    let initialData = null;
    let missingCanvas = false;
    if (data instanceof StampAnnotationElement) {
      const {
        data: {
          rect: rect2,
          rotation,
          id,
          structParent,
          popupRef,
          richText,
          contentsObj,
          creationDate,
          modificationDate
        },
        container,
        parent: {
          page: {
            pageNumber
          }
        },
        canvas
      } = data;
      let bitmapId2, bitmap2;
      if (canvas) {
        delete data.canvas;
        ({
          id: bitmapId2,
          bitmap: bitmap2
        } = uiManager.imageManager.getFromCanvas(container.id, canvas));
        canvas.remove();
      } else {
        missingCanvas = true;
        data._hasNoCanvas = true;
      }
      const altText = (await parent._structTree.getAriaAttributes(`${AnnotationPrefix}${id}`))?.get("aria-label") || "";
      initialData = data = {
        annotationType: AnnotationEditorType.STAMP,
        bitmapId: bitmapId2,
        bitmap: bitmap2,
        pageIndex: pageNumber - 1,
        rect: rect2.slice(0),
        rotation,
        annotationElementId: id,
        id,
        deleted: false,
        accessibilityData: {
          decorative: false,
          altText
        },
        isSvg: false,
        structParent,
        popupRef,
        richText,
        comment: contentsObj?.str || null,
        creationDate,
        modificationDate
      };
    }
    const editor = await super.deserialize(data, parent, uiManager);
    const {
      rect,
      bitmap,
      bitmapUrl,
      bitmapId,
      isSvg,
      accessibilityData
    } = data;
    if (missingCanvas) {
      uiManager.addMissingCanvas(data.id, editor);
      editor.#missingCanvas = true;
    } else if (bitmapId && uiManager.imageManager.isValidId(bitmapId)) {
      editor.#bitmapId = bitmapId;
      if (bitmap) {
        editor.#bitmap = bitmap;
      }
    } else {
      editor.#bitmapUrl = bitmapUrl;
    }
    editor.#isSvg = isSvg;
    const [parentWidth, parentHeight] = editor.pageDimensions;
    editor.width = (rect[2] - rect[0]) / parentWidth;
    editor.height = (rect[3] - rect[1]) / parentHeight;
    if (accessibilityData) {
      editor.altTextData = accessibilityData;
    }
    editor._initialData = initialData;
    if (data.comment) {
      editor.setCommentData(data);
    }
    editor.#hasBeenAddedInUndoStack = !!initialData;
    return editor;
  }
  serialize(isForCopying = false, context = null) {
    if (this.isEmpty()) {
      return null;
    }
    if (this.deleted) {
      return this.serializeDeleted();
    }
    const serialized = Object.assign(super.serialize(isForCopying), {
      bitmapId: this.#bitmapId,
      isSvg: this.#isSvg
    });
    this.addComment(serialized);
    if (isForCopying) {
      serialized.bitmapUrl = this.#serializeBitmap(true);
      serialized.accessibilityData = this.serializeAltText(true);
      serialized.isCopy = true;
      return serialized;
    }
    const {
      decorative,
      altText
    } = this.serializeAltText(false);
    if (!decorative && altText) {
      serialized.accessibilityData = {
        type: "Figure",
        alt: altText
      };
    }
    if (this.annotationElementId) {
      const changes = this.#hasElementChanged(serialized);
      if (changes.isSame) {
        return null;
      }
      if (changes.isSameAltText) {
        delete serialized.accessibilityData;
      } else {
        serialized.accessibilityData.structParent = this._initialData.structParent ?? -1;
      }
      serialized.id = this.annotationElementId;
      delete serialized.bitmapId;
      return serialized;
    }
    if (context === null) {
      return serialized;
    }
    context.stamps ||= /* @__PURE__ */ new Map();
    const area = this.#isSvg ? (serialized.rect[2] - serialized.rect[0]) * (serialized.rect[3] - serialized.rect[1]) : null;
    if (!context.stamps.has(this.#bitmapId)) {
      context.stamps.set(this.#bitmapId, {
        area,
        serialized
      });
      serialized.bitmap = this.#serializeBitmap(false);
    } else if (this.#isSvg) {
      const prevData = context.stamps.get(this.#bitmapId);
      if (area > prevData.area) {
        prevData.area = area;
        prevData.serialized.bitmap.close();
        prevData.serialized.bitmap = this.#serializeBitmap(false);
      }
    }
    return serialized;
  }
  #hasElementChanged(serialized) {
    const {
      pageIndex,
      accessibilityData: {
        altText
      }
    } = this._initialData;
    const isSamePageIndex = serialized.pageIndex === pageIndex;
    const isSameAltText = (serialized.accessibilityData?.alt || "") === altText;
    return {
      isSame: !this.hasEditedComment && !this._hasBeenMoved && !this._hasBeenResized && isSamePageIndex && isSameAltText,
      isSameAltText
    };
  }
  renderAnnotationElement(annotation) {
    if (this.deleted) {
      annotation.hide();
      return null;
    }
    annotation.updateEdited({
      rect: this.getPDFRect(),
      popup: this.comment
    });
    return null;
  }
};
var AnnotationEditorLayer = class _AnnotationEditorLayer {
  #accessibilityManager;
  #allowClick = false;
  #annotationLayer = null;
  #clickAC = null;
  #editorFocusTimeoutId = null;
  #editors = /* @__PURE__ */ new Map();
  #hadPointerDown = false;
  #isDisabling = false;
  #isEnabling = false;
  #drawingAC = null;
  #focusedElement = null;
  #textLayer = null;
  #textSelectionAC = null;
  #textLayerDblClickAC = null;
  #lastPointerDownTimestamp = -1;
  #uiManager;
  static _initialized = false;
  static #editorTypes = new Map([FreeTextEditor, InkEditor, StampEditor, HighlightEditor, SignatureEditor].map((type) => [type._editorType, type]));
  constructor({
    uiManager,
    pageIndex,
    div,
    structTreeLayer,
    accessibilityManager,
    annotationLayer,
    drawLayer,
    textLayer,
    viewport,
    l10n
  }) {
    const editorTypes = [..._AnnotationEditorLayer.#editorTypes.values()];
    if (!_AnnotationEditorLayer._initialized) {
      _AnnotationEditorLayer._initialized = true;
      for (const editorType of editorTypes) {
        editorType.initialize(l10n, uiManager);
      }
    }
    uiManager.registerEditorTypes(editorTypes);
    this.#uiManager = uiManager;
    this.pageIndex = pageIndex;
    this.div = div;
    this.#accessibilityManager = accessibilityManager;
    this.#annotationLayer = annotationLayer;
    this.viewport = viewport;
    this.#textLayer = textLayer;
    this.drawLayer = drawLayer;
    this._structTree = structTreeLayer;
    this.#uiManager.addLayer(this);
  }
  get isEmpty() {
    return this.#editors.size === 0;
  }
  get isInvisible() {
    return this.isEmpty && this.#uiManager.getMode() === AnnotationEditorType.NONE;
  }
  updateToolbar(options) {
    this.#uiManager.updateToolbar(options);
  }
  updateMode(mode = this.#uiManager.getMode()) {
    this.#cleanup();
    switch (mode) {
      case AnnotationEditorType.NONE:
        this.div.classList.toggle("nonEditing", true);
        this.disableTextSelection();
        this.togglePointerEvents(false);
        this.toggleAnnotationLayerPointerEvents(true);
        this.disableClick();
        return;
      case AnnotationEditorType.INK:
        this.disableTextSelection();
        this.togglePointerEvents(true);
        this.enableClick();
        break;
      case AnnotationEditorType.HIGHLIGHT:
        this.enableTextSelection();
        this.togglePointerEvents(false);
        this.disableClick();
        break;
      default:
        this.disableTextSelection();
        this.togglePointerEvents(true);
        this.enableClick();
    }
    this.toggleAnnotationLayerPointerEvents(false);
    const {
      classList
    } = this.div;
    classList.toggle("nonEditing", false);
    if (mode === AnnotationEditorType.POPUP) {
      classList.toggle("commentEditing", true);
    } else {
      classList.toggle("commentEditing", false);
      for (const editorType of _AnnotationEditorLayer.#editorTypes.values()) {
        classList.toggle(`${editorType._type}Editing`, mode === editorType._editorType);
      }
    }
    this.div.hidden = false;
  }
  hasTextLayer(textLayer) {
    return textLayer === this.#textLayer?.div;
  }
  setEditingState(isEditing) {
    this.#uiManager.setEditingState(isEditing);
  }
  addCommands(params) {
    this.#uiManager.addCommands(params);
  }
  cleanUndoStack(type) {
    this.#uiManager.cleanUndoStack(type);
  }
  toggleDrawing(enabled = false) {
    this.div.classList.toggle("drawing", !enabled);
  }
  togglePointerEvents(enabled = false) {
    this.div.classList.toggle("disabled", !enabled);
  }
  toggleAnnotationLayerPointerEvents(enabled = false) {
    this.#annotationLayer?.togglePointerEvents(enabled);
  }
  get #allEditorsIterator() {
    return this.#editors.size !== 0 ? this.#editors.values() : this.#uiManager.getEditors(this.pageIndex);
  }
  async enable() {
    this.#isEnabling = true;
    this.div.tabIndex = 0;
    this.togglePointerEvents(true);
    this.div.classList.toggle("nonEditing", false);
    this.#textLayerDblClickAC?.abort();
    this.#textLayerDblClickAC = null;
    const annotationElementIds = /* @__PURE__ */ new Set();
    for (const editor of this.#allEditorsIterator) {
      editor.enableEditing();
      editor.show(true);
      if (editor.annotationElementId) {
        this.#uiManager.removeChangedExistingAnnotation(editor);
        annotationElementIds.add(editor.annotationElementId);
      }
    }
    const annotationLayer = this.#annotationLayer;
    if (annotationLayer) {
      for (const editable of annotationLayer.getEditableAnnotations()) {
        editable.hide();
        if (this.#uiManager.isDeletedAnnotationElement(editable.data.id)) {
          continue;
        }
        if (annotationElementIds.has(editable.data.id)) {
          continue;
        }
        const editor = await this.deserialize(editable);
        if (!editor) {
          continue;
        }
        this.addOrRebuild(editor);
        editor.enableEditing();
      }
    }
    this.#isEnabling = false;
    this.#uiManager._eventBus.dispatch("editorsrendered", {
      source: this,
      pageNumber: this.pageIndex + 1
    });
  }
  disable() {
    this.#isDisabling = true;
    this.div.tabIndex = -1;
    this.togglePointerEvents(false);
    this.div.classList.toggle("nonEditing", true);
    if (this.#textLayer && !this.#textLayerDblClickAC) {
      this.#textLayerDblClickAC = new AbortController();
      const signal = this.#uiManager.combinedSignal(this.#textLayerDblClickAC);
      this.#textLayer.div.addEventListener("pointerdown", (e9) => {
        const DBL_CLICK_THRESHOLD = 500;
        const {
          clientX,
          clientY,
          timeStamp
        } = e9;
        const lastPointerDownTimestamp = this.#lastPointerDownTimestamp;
        if (timeStamp - lastPointerDownTimestamp > DBL_CLICK_THRESHOLD) {
          this.#lastPointerDownTimestamp = timeStamp;
          return;
        }
        this.#lastPointerDownTimestamp = -1;
        const {
          classList: classList2
        } = this.div;
        classList2.toggle("getElements", true);
        const elements = document.elementsFromPoint(clientX, clientY);
        classList2.toggle("getElements", false);
        if (!this.div.contains(elements[0])) {
          return;
        }
        let id;
        const regex = new RegExp(`^${AnnotationEditorPrefix}[0-9]+$`);
        for (const element of elements) {
          if (regex.test(element.id)) {
            id = element.id;
            break;
          }
        }
        if (!id) {
          return;
        }
        const editor = this.#editors.get(id);
        if (editor?.annotationElementId === null) {
          e9.stopPropagation();
          e9.preventDefault();
          editor.dblclick(e9);
        }
      }, {
        signal,
        capture: true
      });
    }
    const annotationLayer = this.#annotationLayer;
    const needFakeAnnotation = [];
    if (annotationLayer) {
      const changedAnnotations = /* @__PURE__ */ new Map();
      const resetAnnotations = /* @__PURE__ */ new Map();
      for (const editor of this.#allEditorsIterator) {
        editor.disableEditing();
        if (!editor.annotationElementId) {
          needFakeAnnotation.push(editor);
          continue;
        }
        if (editor.serialize() !== null) {
          changedAnnotations.set(editor.annotationElementId, editor);
          continue;
        } else {
          resetAnnotations.set(editor.annotationElementId, editor);
        }
        this.getEditableAnnotation(editor.annotationElementId)?.show();
        editor.remove();
      }
      const editables = annotationLayer.getEditableAnnotations();
      for (const editable of editables) {
        const {
          id
        } = editable.data;
        if (this.#uiManager.isDeletedAnnotationElement(id)) {
          editable.updateEdited({
            deleted: true
          });
          continue;
        }
        let editor = resetAnnotations.get(id);
        if (editor) {
          editor.resetAnnotationElement(editable);
          editor.show(false);
          editable.show();
          continue;
        }
        editor = changedAnnotations.get(id);
        if (editor) {
          this.#uiManager.addChangedExistingAnnotation(editor);
          if (editor.renderAnnotationElement(editable)) {
            editor.show(false);
          }
        }
        editable.show();
      }
    }
    this.#cleanup();
    if (this.isEmpty) {
      this.div.hidden = true;
    }
    const {
      classList
    } = this.div;
    for (const editorType of _AnnotationEditorLayer.#editorTypes.values()) {
      classList.remove(`${editorType._type}Editing`);
    }
    this.disableTextSelection();
    this.toggleAnnotationLayerPointerEvents(true);
    annotationLayer?.updateFakeAnnotations(needFakeAnnotation);
    this.#isDisabling = false;
  }
  getEditableAnnotation(id) {
    return this.#annotationLayer?.getEditableAnnotation(id) || null;
  }
  setActiveEditor(editor) {
    const currentActive = this.#uiManager.getActive();
    if (currentActive === editor) {
      return;
    }
    this.#uiManager.setActiveEditor(editor);
  }
  enableTextSelection() {
    this.div.tabIndex = -1;
    if (this.#textLayer?.div && !this.#textSelectionAC) {
      this.#textSelectionAC = new AbortController();
      const signal = this.#uiManager.combinedSignal(this.#textSelectionAC);
      this.#textLayer.div.addEventListener("pointerdown", this.#textLayerPointerDown.bind(this), {
        signal
      });
      this.#textLayer.div.classList.add("highlighting");
    }
  }
  disableTextSelection() {
    this.div.tabIndex = 0;
    if (this.#textLayer?.div && this.#textSelectionAC) {
      this.#textSelectionAC.abort();
      this.#textSelectionAC = null;
      this.#textLayer.div.classList.remove("highlighting");
    }
  }
  #textLayerPointerDown(event) {
    this.#uiManager.unselectAll();
    const {
      target
    } = event;
    if (target === this.#textLayer.div || (target.getAttribute("role") === "img" || target.classList.contains("endOfContent")) && this.#textLayer.div.contains(target)) {
      const {
        isMac
      } = util_FeatureTest.platform;
      if (event.button !== 0 || event.ctrlKey && isMac) {
        return;
      }
      this.#uiManager.showAllEditors("highlight", true, true);
      this.#textLayer.div.classList.add("free");
      this.toggleDrawing();
      HighlightEditor.startHighlighting(this, this.#uiManager.direction === "ltr", {
        target: this.#textLayer.div,
        x: event.x,
        y: event.y
      });
      this.#textLayer.div.addEventListener("pointerup", () => {
        this.#textLayer.div.classList.remove("free");
        this.toggleDrawing(true);
      }, {
        once: true,
        signal: this.#uiManager._signal
      });
      event.preventDefault();
    }
  }
  enableClick() {
    if (this.#clickAC) {
      return;
    }
    this.#clickAC = new AbortController();
    const signal = this.#uiManager.combinedSignal(this.#clickAC);
    this.div.addEventListener("pointerdown", this.pointerdown.bind(this), {
      signal
    });
    const pointerup = this.pointerup.bind(this);
    this.div.addEventListener("pointerup", pointerup, {
      signal
    });
    this.div.addEventListener("pointercancel", pointerup, {
      signal
    });
  }
  disableClick() {
    this.#clickAC?.abort();
    this.#clickAC = null;
  }
  attach(editor) {
    this.#editors.set(editor.id, editor);
    const {
      annotationElementId
    } = editor;
    if (annotationElementId && this.#uiManager.isDeletedAnnotationElement(annotationElementId)) {
      this.#uiManager.removeDeletedAnnotationElement(editor);
    }
  }
  detach(editor) {
    this.#editors.delete(editor.id);
    this.#accessibilityManager?.removePointerInTextLayer(editor.contentDiv);
    if (!this.#isDisabling && editor.annotationElementId) {
      this.#uiManager.addDeletedAnnotationElement(editor);
    }
  }
  remove(editor) {
    this.detach(editor);
    this.#uiManager.removeEditor(editor);
    editor.div.remove();
    editor.isAttachedToDOM = false;
  }
  changeParent(editor) {
    if (editor.parent === this) {
      return;
    }
    if (editor.parent && editor.annotationElementId) {
      this.#uiManager.addDeletedAnnotationElement(editor.annotationElementId);
      AnnotationEditor.deleteAnnotationElement(editor);
      editor.annotationElementId = null;
    }
    this.attach(editor);
    editor.parent?.detach(editor);
    editor.setParent(this);
    if (editor.div && editor.isAttachedToDOM) {
      editor.div.remove();
      this.div.append(editor.div);
    }
  }
  add(editor) {
    if (editor.parent === this && editor.isAttachedToDOM) {
      return;
    }
    this.changeParent(editor);
    this.#uiManager.addEditor(editor);
    this.attach(editor);
    if (!editor.isAttachedToDOM) {
      const div = editor.render();
      this.div.append(div);
      editor.isAttachedToDOM = true;
    }
    editor.fixAndSetPosition();
    editor.onceAdded(!this.#isEnabling);
    this.#uiManager.addToAnnotationStorage(editor);
    editor._reportTelemetry(editor.telemetryInitialData);
  }
  moveEditorInDOM(editor) {
    if (!editor.isAttachedToDOM) {
      return;
    }
    const {
      activeElement
    } = document;
    if (editor.div.contains(activeElement) && !this.#editorFocusTimeoutId) {
      editor._focusEventsAllowed = false;
      this.#editorFocusTimeoutId = setTimeout(() => {
        this.#editorFocusTimeoutId = null;
        if (!editor.div.contains(document.activeElement)) {
          editor.div.addEventListener("focusin", () => {
            editor._focusEventsAllowed = true;
          }, {
            once: true,
            signal: this.#uiManager._signal
          });
          activeElement.focus();
        } else {
          editor._focusEventsAllowed = true;
        }
      }, 0);
    }
    editor._structTreeParentId = this.#accessibilityManager?.moveElementInDOM(this.div, editor.div, editor.contentDiv, true);
  }
  addOrRebuild(editor) {
    if (editor.needsToBeRebuilt()) {
      editor.parent ||= this;
      editor.rebuild();
      editor.show();
    } else {
      this.add(editor);
    }
  }
  addUndoableEditor(editor) {
    const cmd = () => editor._uiManager.rebuild(editor);
    const undo = () => {
      editor.remove();
    };
    this.addCommands({
      cmd,
      undo,
      mustExec: false
    });
  }
  getEditorByUID(uid) {
    for (const editor of this.#editors.values()) {
      if (editor.uid === uid) {
        return editor;
      }
    }
    return null;
  }
  getNextId() {
    return this.#uiManager.getId();
  }
  get #currentEditorType() {
    return _AnnotationEditorLayer.#editorTypes.get(this.#uiManager.getMode());
  }
  combinedSignal(ac) {
    return this.#uiManager.combinedSignal(ac);
  }
  #createNewEditor(params) {
    const editorType = this.#currentEditorType;
    return editorType ? new editorType.prototype.constructor(params) : null;
  }
  canCreateNewEmptyEditor() {
    return this.#currentEditorType?.canCreateNewEmptyEditor();
  }
  async pasteEditor(options, params) {
    this.updateToolbar(options);
    await this.#uiManager.updateMode(options.mode);
    const {
      offsetX,
      offsetY
    } = this.#getCenterPoint();
    const id = this.getNextId();
    const editor = this.#createNewEditor({
      parent: this,
      id,
      x: offsetX,
      y: offsetY,
      uiManager: this.#uiManager,
      isCentered: true,
      ...params
    });
    if (editor) {
      this.add(editor);
    }
  }
  async deserialize(data) {
    return await _AnnotationEditorLayer.#editorTypes.get(data.annotationType ?? data.annotationEditorType)?.deserialize(data, this, this.#uiManager) || null;
  }
  createAndAddNewEditor(event, isCentered, data = {}) {
    const id = this.getNextId();
    const editor = this.#createNewEditor({
      parent: this,
      id,
      x: event.offsetX,
      y: event.offsetY,
      uiManager: this.#uiManager,
      isCentered,
      ...data
    });
    if (editor) {
      this.add(editor);
    }
    return editor;
  }
  get boundingClientRect() {
    return this.div.getBoundingClientRect();
  }
  #getCenterPoint() {
    const {
      x: x2,
      y: y4,
      width,
      height
    } = this.boundingClientRect;
    const tlX = Math.max(0, x2);
    const tlY = Math.max(0, y4);
    const brX = Math.min(window.innerWidth, x2 + width);
    const brY = Math.min(window.innerHeight, y4 + height);
    const centerX = (tlX + brX) / 2 - x2;
    const centerY = (tlY + brY) / 2 - y4;
    const [offsetX, offsetY] = this.viewport.rotation % 180 === 0 ? [centerX, centerY] : [centerY, centerX];
    return {
      offsetX,
      offsetY
    };
  }
  addNewEditor(data = {}) {
    this.createAndAddNewEditor(this.#getCenterPoint(), true, data);
  }
  setSelected(editor) {
    this.#uiManager.setSelected(editor);
  }
  toggleSelected(editor) {
    this.#uiManager.toggleSelected(editor);
  }
  unselect(editor) {
    this.#uiManager.unselect(editor);
  }
  pointerup(event) {
    const {
      isMac
    } = util_FeatureTest.platform;
    if (event.button !== 0 || event.ctrlKey && isMac) {
      return;
    }
    if (event.target !== this.div) {
      return;
    }
    if (!this.#hadPointerDown) {
      return;
    }
    this.#hadPointerDown = false;
    if (this.#currentEditorType?.isDrawer && this.#currentEditorType.supportMultipleDrawings) {
      return;
    }
    if (!this.#allowClick) {
      this.#allowClick = true;
      return;
    }
    const currentMode = this.#uiManager.getMode();
    if (currentMode === AnnotationEditorType.STAMP || currentMode === AnnotationEditorType.SIGNATURE) {
      this.#uiManager.unselectAll();
      return;
    }
    this.createAndAddNewEditor(event, false);
  }
  pointerdown(event) {
    if (this.#uiManager.getMode() === AnnotationEditorType.HIGHLIGHT) {
      this.enableTextSelection();
    }
    if (this.#hadPointerDown) {
      this.#hadPointerDown = false;
      return;
    }
    const {
      isMac
    } = util_FeatureTest.platform;
    if (event.button !== 0 || event.ctrlKey && isMac) {
      return;
    }
    if (event.target !== this.div) {
      return;
    }
    this.#hadPointerDown = true;
    if (this.#currentEditorType?.isDrawer) {
      this.startDrawingSession(event);
      return;
    }
    const editor = this.#uiManager.getActive();
    this.#allowClick = !editor || editor.isEmpty();
  }
  startDrawingSession(event) {
    this.div.focus({
      preventScroll: true
    });
    if (this.#drawingAC) {
      this.#currentEditorType.startDrawing(this, this.#uiManager, false, event);
      return;
    }
    this.#uiManager.setCurrentDrawingSession(this);
    this.#drawingAC = new AbortController();
    const signal = this.#uiManager.combinedSignal(this.#drawingAC);
    this.div.addEventListener("blur", ({
      relatedTarget
    }) => {
      if (relatedTarget && !this.div.contains(relatedTarget)) {
        this.#focusedElement = null;
        this.commitOrRemove();
      }
    }, {
      signal
    });
    this.#currentEditorType.startDrawing(this, this.#uiManager, false, event);
  }
  pause(on) {
    if (on) {
      const {
        activeElement
      } = document;
      if (this.div.contains(activeElement)) {
        this.#focusedElement = activeElement;
      }
      return;
    }
    if (this.#focusedElement) {
      setTimeout(() => {
        this.#focusedElement?.focus();
        this.#focusedElement = null;
      }, 0);
    }
  }
  endDrawingSession(isAborted3 = false) {
    if (!this.#drawingAC) {
      return null;
    }
    this.#uiManager.setCurrentDrawingSession(null);
    this.#drawingAC.abort();
    this.#drawingAC = null;
    this.#focusedElement = null;
    return this.#currentEditorType.endDrawing(isAborted3);
  }
  findNewParent(editor, x2, y4) {
    const layer = this.#uiManager.findParent(x2, y4);
    if (layer === null || layer === this) {
      return false;
    }
    layer.changeParent(editor);
    return true;
  }
  commitOrRemove() {
    if (this.#drawingAC) {
      this.endDrawingSession();
      return true;
    }
    return false;
  }
  onScaleChanging() {
    if (!this.#drawingAC) {
      return;
    }
    this.#currentEditorType.onScaleChangingWhenDrawing(this);
  }
  destroy() {
    this.commitOrRemove();
    if (this.#uiManager.getActive()?.parent === this) {
      this.#uiManager.commitOrRemove();
      this.#uiManager.setActiveEditor(null);
    }
    if (this.#editorFocusTimeoutId) {
      clearTimeout(this.#editorFocusTimeoutId);
      this.#editorFocusTimeoutId = null;
    }
    for (const editor of this.#editors.values()) {
      this.#accessibilityManager?.removePointerInTextLayer(editor.contentDiv);
      editor.setParent(null);
      editor.isAttachedToDOM = false;
      editor.div.remove();
    }
    this.div = null;
    this.#editors.clear();
    this.#uiManager.removeLayer(this);
  }
  #cleanup() {
    for (const editor of this.#editors.values()) {
      if (editor.isEmpty()) {
        editor.remove();
      }
    }
  }
  render({
    viewport
  }) {
    this.viewport = viewport;
    setLayerDimensions(this.div, viewport);
    for (const editor of this.#uiManager.getEditors(this.pageIndex)) {
      this.add(editor);
      editor.rebuild();
    }
    this.updateMode();
  }
  update({
    viewport
  }) {
    this.#uiManager.commitOrRemove();
    this.#cleanup();
    const oldRotation = this.viewport.rotation;
    const rotation = viewport.rotation;
    this.viewport = viewport;
    setLayerDimensions(this.div, {
      rotation
    });
    if (oldRotation !== rotation) {
      for (const editor of this.#editors.values()) {
        editor.rotate(rotation);
      }
    }
  }
  get pageDimensions() {
    const {
      pageWidth,
      pageHeight
    } = this.viewport.rawDims;
    return [pageWidth, pageHeight];
  }
  get scale() {
    return this.#uiManager.viewParameters.realScale;
  }
};
var DrawLayer = class _DrawLayer {
  #parent = null;
  #mapping = /* @__PURE__ */ new Map();
  #toUpdate = /* @__PURE__ */ new Map();
  static #id = 0;
  constructor({
    pageIndex
  }) {
    this.pageIndex = pageIndex;
  }
  setParent(parent) {
    if (!this.#parent) {
      this.#parent = parent;
      return;
    }
    if (this.#parent !== parent) {
      if (this.#mapping.size > 0) {
        for (const root of this.#mapping.values()) {
          root.remove();
          parent.append(root);
        }
      }
      this.#parent = parent;
    }
  }
  static get _svgFactory() {
    return shadow(this, "_svgFactory", new DOMSVGFactory());
  }
  static #setBox(element, [x2, y4, width, height]) {
    const {
      style
    } = element;
    style.top = `${100 * y4}%`;
    style.left = `${100 * x2}%`;
    style.width = `${100 * width}%`;
    style.height = `${100 * height}%`;
  }
  #createSVG() {
    const svg = _DrawLayer._svgFactory.create(1, 1, true);
    this.#parent.append(svg);
    svg.setAttribute("aria-hidden", true);
    return svg;
  }
  #createClipPath(defs, pathId) {
    const clipPath = _DrawLayer._svgFactory.createElement("clipPath");
    defs.append(clipPath);
    const clipPathId = `clip_${pathId}`;
    clipPath.setAttribute("id", clipPathId);
    clipPath.setAttribute("clipPathUnits", "objectBoundingBox");
    const clipPathUse = _DrawLayer._svgFactory.createElement("use");
    clipPath.append(clipPathUse);
    clipPathUse.setAttribute("href", `#${pathId}`);
    clipPathUse.classList.add("clip");
    return clipPathId;
  }
  #updateProperties(element, properties) {
    for (const [key, value] of Object.entries(properties)) {
      if (value === null) {
        element.removeAttribute(key);
      } else {
        element.setAttribute(key, value);
      }
    }
  }
  draw(properties, isPathUpdatable = false, hasClip = false) {
    const id = _DrawLayer.#id++;
    const root = this.#createSVG();
    const defs = _DrawLayer._svgFactory.createElement("defs");
    root.append(defs);
    const path6 = _DrawLayer._svgFactory.createElement("path");
    defs.append(path6);
    const pathId = `path_p${this.pageIndex}_${id}`;
    path6.setAttribute("id", pathId);
    path6.setAttribute("vector-effect", "non-scaling-stroke");
    if (isPathUpdatable) {
      this.#toUpdate.set(id, path6);
    }
    const clipPathId = hasClip ? this.#createClipPath(defs, pathId) : null;
    const use = _DrawLayer._svgFactory.createElement("use");
    root.append(use);
    use.setAttribute("href", `#${pathId}`);
    this.updateProperties(root, properties);
    this.#mapping.set(id, root);
    return {
      id,
      clipPathId: `url(#${clipPathId})`
    };
  }
  drawOutline(properties, mustRemoveSelfIntersections) {
    const id = _DrawLayer.#id++;
    const root = this.#createSVG();
    const defs = _DrawLayer._svgFactory.createElement("defs");
    root.append(defs);
    const path6 = _DrawLayer._svgFactory.createElement("path");
    defs.append(path6);
    const pathId = `path_p${this.pageIndex}_${id}`;
    path6.setAttribute("id", pathId);
    path6.setAttribute("vector-effect", "non-scaling-stroke");
    let maskId;
    if (mustRemoveSelfIntersections) {
      const mask = _DrawLayer._svgFactory.createElement("mask");
      defs.append(mask);
      maskId = `mask_p${this.pageIndex}_${id}`;
      mask.setAttribute("id", maskId);
      mask.setAttribute("maskUnits", "objectBoundingBox");
      const rect = _DrawLayer._svgFactory.createElement("rect");
      mask.append(rect);
      rect.setAttribute("width", "1");
      rect.setAttribute("height", "1");
      rect.setAttribute("fill", "white");
      const use = _DrawLayer._svgFactory.createElement("use");
      mask.append(use);
      use.setAttribute("href", `#${pathId}`);
      use.setAttribute("stroke", "none");
      use.setAttribute("fill", "black");
      use.setAttribute("fill-rule", "nonzero");
      use.classList.add("mask");
    }
    const use1 = _DrawLayer._svgFactory.createElement("use");
    root.append(use1);
    use1.setAttribute("href", `#${pathId}`);
    if (maskId) {
      use1.setAttribute("mask", `url(#${maskId})`);
    }
    const use2 = use1.cloneNode();
    root.append(use2);
    use1.classList.add("mainOutline");
    use2.classList.add("secondaryOutline");
    this.updateProperties(root, properties);
    this.#mapping.set(id, root);
    return id;
  }
  finalizeDraw(id, properties) {
    this.#toUpdate.delete(id);
    this.updateProperties(id, properties);
  }
  updateProperties(elementOrId, properties) {
    if (!properties) {
      return;
    }
    const {
      root,
      bbox,
      rootClass,
      path: path6
    } = properties;
    const element = typeof elementOrId === "number" ? this.#mapping.get(elementOrId) : elementOrId;
    if (!element) {
      return;
    }
    if (root) {
      this.#updateProperties(element, root);
    }
    if (bbox) {
      _DrawLayer.#setBox(element, bbox);
    }
    if (rootClass) {
      const {
        classList
      } = element;
      for (const [className, value] of Object.entries(rootClass)) {
        classList.toggle(className, value);
      }
    }
    if (path6) {
      const defs = element.firstChild;
      const pathElement = defs.firstChild;
      this.#updateProperties(pathElement, path6);
    }
  }
  updateParent(id, layer) {
    if (layer === this) {
      return;
    }
    const root = this.#mapping.get(id);
    if (!root) {
      return;
    }
    layer.#parent.append(root);
    this.#mapping.delete(id);
    layer.#mapping.set(id, root);
  }
  remove(id) {
    this.#toUpdate.delete(id);
    if (this.#parent === null) {
      return;
    }
    this.#mapping.get(id).remove();
    this.#mapping.delete(id);
  }
  destroy() {
    this.#parent = null;
    for (const root of this.#mapping.values()) {
      root.remove();
    }
    this.#mapping.clear();
    this.#toUpdate.clear();
  }
};
{
  globalThis._pdfjsTestingUtils = {
    HighlightOutliner
  };
}
globalThis.pdfjsLib = {
  AbortException,
  AnnotationEditorLayer,
  AnnotationEditorParamsType,
  AnnotationEditorType,
  AnnotationEditorUIManager,
  AnnotationLayer,
  AnnotationMode,
  AnnotationType,
  applyOpacity,
  build,
  ColorPicker,
  createValidAbsoluteUrl,
  CSSConstants,
  DOMSVGFactory,
  DrawLayer,
  FeatureTest: util_FeatureTest,
  fetchData,
  findContrastColor,
  getDocument,
  getFilenameFromUrl,
  getPdfFilenameFromUrl,
  getRGB,
  getUuid,
  getXfaPageViewport,
  GlobalWorkerOptions,
  ImageKind: util_ImageKind,
  InvalidPDFException,
  isDataScheme,
  isPdfFile,
  isValidExplicitDest,
  MathClamp,
  noContextMenu,
  normalizeUnicode,
  OPS,
  OutputScale,
  PasswordResponses,
  PDFDataRangeTransport,
  PDFDateString,
  PDFWorker,
  PermissionFlag,
  PixelsPerInch,
  RenderingCancelledException,
  renderRichText,
  ResponseException,
  setLayerDimensions,
  shadow,
  SignatureExtractor,
  stopEvent,
  SupportedImageMimeTypes,
  TextLayer,
  TouchManager,
  updateUrlHash,
  Util,
  VerbosityLevel,
  version: version2,
  XfaLayer
};

// ../pi-mono/node_modules/xlsx/xlsx.mjs
init_process_shim();
var XLSX = {};
XLSX.version = "0.20.3";
var current_codepage = 1200;
var current_ansi = 1252;
var $cptable;
var VALID_ANSI = [874, 932, 936, 949, 950, 1250, 1251, 1252, 1253, 1254, 1255, 1256, 1257, 1258, 1e4];
var CS2CP = {
  0: 1252,
  /* ANSI */
  1: 65001,
  /* DEFAULT */
  2: 65001,
  /* SYMBOL */
  77: 1e4,
  /* MAC */
  128: 932,
  /* SHIFTJIS */
  129: 949,
  /* HANGUL */
  130: 1361,
  /* JOHAB */
  134: 936,
  /* GB2312 */
  136: 950,
  /* CHINESEBIG5 */
  161: 1253,
  /* GREEK */
  162: 1254,
  /* TURKISH */
  163: 1258,
  /* VIETNAMESE */
  177: 1255,
  /* HEBREW */
  178: 1256,
  /* ARABIC */
  186: 1257,
  /* BALTIC */
  204: 1251,
  /* RUSSIAN */
  222: 874,
  /* THAI */
  238: 1250,
  /* EASTEUROPE */
  255: 1252,
  /* OEM */
  69: 6969
  /* MISC */
};
var set_ansi = function(cp) {
  if (VALID_ANSI.indexOf(cp) == -1) return;
  current_ansi = CS2CP[0] = cp;
};
function reset_ansi() {
  set_ansi(1252);
}
var set_cp = function(cp) {
  current_codepage = cp;
  set_ansi(cp);
};
function reset_cp() {
  set_cp(1200);
  reset_ansi();
}
function char_codes(data) {
  var o9 = [];
  for (var i7 = 0, len = data.length; i7 < len; ++i7) o9[i7] = data.charCodeAt(i7);
  return o9;
}
function utf16leread(data) {
  var o9 = [];
  for (var i7 = 0; i7 < data.length >> 1; ++i7) o9[i7] = String.fromCharCode(data.charCodeAt(2 * i7) + (data.charCodeAt(2 * i7 + 1) << 8));
  return o9.join("");
}
function utf16lereadu(data) {
  var o9 = [];
  for (var i7 = 0; i7 < data.length >> 1; ++i7) o9[i7] = String.fromCharCode(data[2 * i7] + (data[2 * i7 + 1] << 8));
  return o9.join("");
}
function utf16beread(data) {
  var o9 = [];
  for (var i7 = 0; i7 < data.length >> 1; ++i7) o9[i7] = String.fromCharCode(data.charCodeAt(2 * i7 + 1) + (data.charCodeAt(2 * i7) << 8));
  return o9.join("");
}
var debom = function(data) {
  var c1 = data.charCodeAt(0), c22 = data.charCodeAt(1);
  if (c1 == 255 && c22 == 254) return utf16leread(data.slice(2));
  if (c1 == 254 && c22 == 255) return utf16beread(data.slice(2));
  if (c1 == 65279) return data.slice(1);
  return data;
};
var _getchar = function _gc1(x2) {
  return String.fromCharCode(x2);
};
var _getansi = function _ga1(x2) {
  return String.fromCharCode(x2);
};
var DENSE = null;
var DIF_XL = true;
var Base64_map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
function Base64_encode(input) {
  var o9 = "";
  var c1 = 0, c22 = 0, c32 = 0, e1 = 0, e22 = 0, e32 = 0, e42 = 0;
  for (var i7 = 0; i7 < input.length; ) {
    c1 = input.charCodeAt(i7++);
    e1 = c1 >> 2;
    c22 = input.charCodeAt(i7++);
    e22 = (c1 & 3) << 4 | c22 >> 4;
    c32 = input.charCodeAt(i7++);
    e32 = (c22 & 15) << 2 | c32 >> 6;
    e42 = c32 & 63;
    if (isNaN(c22)) {
      e32 = e42 = 64;
    } else if (isNaN(c32)) {
      e42 = 64;
    }
    o9 += Base64_map.charAt(e1) + Base64_map.charAt(e22) + Base64_map.charAt(e32) + Base64_map.charAt(e42);
  }
  return o9;
}
function Base64_decode(input) {
  var o9 = "";
  var c1 = 0, c22 = 0, c32 = 0, e1 = 0, e22 = 0, e32 = 0, e42 = 0;
  if (input.slice(0, 5) == "data:") {
    var i7 = input.slice(0, 1024).indexOf(";base64,");
    if (i7 > -1)
      input = input.slice(i7 + 8);
  }
  input = input.replace(/[^\w\+\/\=]/g, "");
  for (var i7 = 0; i7 < input.length; ) {
    e1 = Base64_map.indexOf(input.charAt(i7++));
    e22 = Base64_map.indexOf(input.charAt(i7++));
    c1 = e1 << 2 | e22 >> 4;
    o9 += String.fromCharCode(c1);
    e32 = Base64_map.indexOf(input.charAt(i7++));
    c22 = (e22 & 15) << 4 | e32 >> 2;
    if (e32 !== 64) {
      o9 += String.fromCharCode(c22);
    }
    e42 = Base64_map.indexOf(input.charAt(i7++));
    c32 = (e32 & 3) << 6 | e42;
    if (e42 !== 64) {
      o9 += String.fromCharCode(c32);
    }
  }
  return o9;
}
var has_buf = /* @__PURE__ */ (function() {
  return typeof Buffer !== "undefined" && typeof process !== "undefined" && typeof process.versions !== "undefined" && !!process.versions.node;
})();
var Buffer_from = /* @__PURE__ */ (function() {
  if (typeof Buffer !== "undefined") {
    var nbfs = !Buffer.from;
    if (!nbfs) try {
      Buffer.from("foo", "utf8");
    } catch (e9) {
      nbfs = true;
    }
    return nbfs ? function(buf, enc) {
      return enc ? new Buffer(buf, enc) : new Buffer(buf);
    } : Buffer.from.bind(Buffer);
  }
  return function() {
  };
})();
var buf_utf16le = /* @__PURE__ */ (function() {
  if (typeof Buffer === "undefined") return false;
  var x2 = Buffer_from([65, 0]);
  if (!x2) return false;
  var o9 = x2.toString("utf16le");
  return o9.length == 1;
})();
function new_raw_buf(len) {
  if (has_buf) return Buffer.alloc ? Buffer.alloc(len) : new Buffer(len);
  return typeof Uint8Array != "undefined" ? new Uint8Array(len) : new Array(len);
}
function new_unsafe_buf(len) {
  if (has_buf) return Buffer.allocUnsafe ? Buffer.allocUnsafe(len) : new Buffer(len);
  return typeof Uint8Array != "undefined" ? new Uint8Array(len) : new Array(len);
}
var s2a = function s2a2(s6) {
  if (has_buf) return Buffer_from(s6, "binary");
  return s6.split("").map(function(x2) {
    return x2.charCodeAt(0) & 255;
  });
};
function a2s(data) {
  if (Array.isArray(data)) return data.map(function(c6) {
    return String.fromCharCode(c6);
  }).join("");
  var o9 = [];
  for (var i7 = 0; i7 < data.length; ++i7) o9[i7] = String.fromCharCode(data[i7]);
  return o9.join("");
}
function ab2a(data) {
  if (typeof ArrayBuffer == "undefined") throw new Error("Unsupported");
  if (data instanceof ArrayBuffer) return ab2a(new Uint8Array(data));
  var o9 = new Array(data.length);
  for (var i7 = 0; i7 < data.length; ++i7) o9[i7] = data[i7];
  return o9;
}
var bconcat = has_buf ? function(bufs) {
  return Buffer.concat(bufs.map(function(buf) {
    return Buffer.isBuffer(buf) ? buf : Buffer_from(buf);
  }));
} : function(bufs) {
  if (typeof Uint8Array !== "undefined") {
    var i7 = 0, maxlen = 0;
    for (i7 = 0; i7 < bufs.length; ++i7) maxlen += bufs[i7].length;
    var o9 = new Uint8Array(maxlen);
    var len = 0;
    for (i7 = 0, maxlen = 0; i7 < bufs.length; maxlen += len, ++i7) {
      len = bufs[i7].length;
      if (bufs[i7] instanceof Uint8Array) o9.set(bufs[i7], maxlen);
      else if (typeof bufs[i7] == "string") o9.set(new Uint8Array(s2a(bufs[i7])), maxlen);
      else o9.set(new Uint8Array(bufs[i7]), maxlen);
    }
    return o9;
  }
  return [].concat.apply([], bufs.map(function(buf) {
    return Array.isArray(buf) ? buf : [].slice.call(buf);
  }));
};
function utf8decode(content) {
  var out = [], widx = 0, L3 = content.length + 250;
  var o9 = new_raw_buf(content.length + 255);
  for (var ridx = 0; ridx < content.length; ++ridx) {
    var c6 = content.charCodeAt(ridx);
    if (c6 < 128) o9[widx++] = c6;
    else if (c6 < 2048) {
      o9[widx++] = 192 | c6 >> 6 & 31;
      o9[widx++] = 128 | c6 & 63;
    } else if (c6 >= 55296 && c6 < 57344) {
      c6 = (c6 & 1023) + 64;
      var d4 = content.charCodeAt(++ridx) & 1023;
      o9[widx++] = 240 | c6 >> 8 & 7;
      o9[widx++] = 128 | c6 >> 2 & 63;
      o9[widx++] = 128 | d4 >> 6 & 15 | (c6 & 3) << 4;
      o9[widx++] = 128 | d4 & 63;
    } else {
      o9[widx++] = 224 | c6 >> 12 & 15;
      o9[widx++] = 128 | c6 >> 6 & 63;
      o9[widx++] = 128 | c6 & 63;
    }
    if (widx > L3) {
      out.push(o9.slice(0, widx));
      widx = 0;
      o9 = new_raw_buf(65535);
      L3 = 65530;
    }
  }
  out.push(o9.slice(0, widx));
  return bconcat(out);
}
var chr0 = /\u0000/g;
var chr1 = /[\u0001-\u0006]/g;
function _strrev(x2) {
  var o9 = "", i7 = x2.length - 1;
  while (i7 >= 0) o9 += x2.charAt(i7--);
  return o9;
}
function pad0(v4, d4) {
  var t6 = "" + v4;
  return t6.length >= d4 ? t6 : fill("0", d4 - t6.length) + t6;
}
function pad_(v4, d4) {
  var t6 = "" + v4;
  return t6.length >= d4 ? t6 : fill(" ", d4 - t6.length) + t6;
}
function rpad_(v4, d4) {
  var t6 = "" + v4;
  return t6.length >= d4 ? t6 : t6 + fill(" ", d4 - t6.length);
}
function pad0r1(v4, d4) {
  var t6 = "" + Math.round(v4);
  return t6.length >= d4 ? t6 : fill("0", d4 - t6.length) + t6;
}
function pad0r2(v4, d4) {
  var t6 = "" + v4;
  return t6.length >= d4 ? t6 : fill("0", d4 - t6.length) + t6;
}
var p2_32 = /* @__PURE__ */ Math.pow(2, 32);
function pad0r(v4, d4) {
  if (v4 > p2_32 || v4 < -p2_32) return pad0r1(v4, d4);
  var i7 = Math.round(v4);
  return pad0r2(i7, d4);
}
function SSF_isgeneral(s6, i7) {
  i7 = i7 || 0;
  return s6.length >= 7 + i7 && (s6.charCodeAt(i7) | 32) === 103 && (s6.charCodeAt(i7 + 1) | 32) === 101 && (s6.charCodeAt(i7 + 2) | 32) === 110 && (s6.charCodeAt(i7 + 3) | 32) === 101 && (s6.charCodeAt(i7 + 4) | 32) === 114 && (s6.charCodeAt(i7 + 5) | 32) === 97 && (s6.charCodeAt(i7 + 6) | 32) === 108;
}
var days = [
  ["Sun", "Sunday"],
  ["Mon", "Monday"],
  ["Tue", "Tuesday"],
  ["Wed", "Wednesday"],
  ["Thu", "Thursday"],
  ["Fri", "Friday"],
  ["Sat", "Saturday"]
];
var months = [
  ["J", "Jan", "January"],
  ["F", "Feb", "February"],
  ["M", "Mar", "March"],
  ["A", "Apr", "April"],
  ["M", "May", "May"],
  ["J", "Jun", "June"],
  ["J", "Jul", "July"],
  ["A", "Aug", "August"],
  ["S", "Sep", "September"],
  ["O", "Oct", "October"],
  ["N", "Nov", "November"],
  ["D", "Dec", "December"]
];
function SSF_init_table(t6) {
  if (!t6) t6 = {};
  t6[0] = "General";
  t6[1] = "0";
  t6[2] = "0.00";
  t6[3] = "#,##0";
  t6[4] = "#,##0.00";
  t6[9] = "0%";
  t6[10] = "0.00%";
  t6[11] = "0.00E+00";
  t6[12] = "# ?/?";
  t6[13] = "# ??/??";
  t6[14] = "m/d/yy";
  t6[15] = "d-mmm-yy";
  t6[16] = "d-mmm";
  t6[17] = "mmm-yy";
  t6[18] = "h:mm AM/PM";
  t6[19] = "h:mm:ss AM/PM";
  t6[20] = "h:mm";
  t6[21] = "h:mm:ss";
  t6[22] = "m/d/yy h:mm";
  t6[37] = "#,##0 ;(#,##0)";
  t6[38] = "#,##0 ;[Red](#,##0)";
  t6[39] = "#,##0.00;(#,##0.00)";
  t6[40] = "#,##0.00;[Red](#,##0.00)";
  t6[45] = "mm:ss";
  t6[46] = "[h]:mm:ss";
  t6[47] = "mmss.0";
  t6[48] = "##0.0E+0";
  t6[49] = "@";
  t6[56] = '"\u4E0A\u5348/\u4E0B\u5348 "hh"\u6642"mm"\u5206"ss"\u79D2 "';
  return t6;
}
var table_fmt = {
  0: "General",
  1: "0",
  2: "0.00",
  3: "#,##0",
  4: "#,##0.00",
  9: "0%",
  10: "0.00%",
  11: "0.00E+00",
  12: "# ?/?",
  13: "# ??/??",
  14: "m/d/yy",
  15: "d-mmm-yy",
  16: "d-mmm",
  17: "mmm-yy",
  18: "h:mm AM/PM",
  19: "h:mm:ss AM/PM",
  20: "h:mm",
  21: "h:mm:ss",
  22: "m/d/yy h:mm",
  37: "#,##0 ;(#,##0)",
  38: "#,##0 ;[Red](#,##0)",
  39: "#,##0.00;(#,##0.00)",
  40: "#,##0.00;[Red](#,##0.00)",
  45: "mm:ss",
  46: "[h]:mm:ss",
  47: "mmss.0",
  48: "##0.0E+0",
  49: "@",
  56: '"\u4E0A\u5348/\u4E0B\u5348 "hh"\u6642"mm"\u5206"ss"\u79D2 "'
};
var SSF_default_map = {
  5: 37,
  6: 38,
  7: 39,
  8: 40,
  //  5 -> 37 ...  8 -> 40
  23: 0,
  24: 0,
  25: 0,
  26: 0,
  // 23 ->  0 ... 26 ->  0
  27: 14,
  28: 14,
  29: 14,
  30: 14,
  31: 14,
  // 27 -> 14 ... 31 -> 14
  50: 14,
  51: 14,
  52: 14,
  53: 14,
  54: 14,
  // 50 -> 14 ... 58 -> 14
  55: 14,
  56: 14,
  57: 14,
  58: 14,
  59: 1,
  60: 2,
  61: 3,
  62: 4,
  // 59 ->  1 ... 62 ->  4
  67: 9,
  68: 10,
  // 67 ->  9 ... 68 -> 10
  69: 12,
  70: 13,
  71: 14,
  // 69 -> 12 ... 71 -> 14
  72: 14,
  73: 15,
  74: 16,
  75: 17,
  // 72 -> 14 ... 75 -> 17
  76: 20,
  77: 21,
  78: 22,
  // 76 -> 20 ... 78 -> 22
  79: 45,
  80: 46,
  81: 47,
  // 79 -> 45 ... 81 -> 47
  82: 0
  // 82 ->  0 ... 65536 -> 0 (omitted)
};
var SSF_default_str = {
  //  5 -- Currency,   0 decimal, black negative
  5: '"$"#,##0_);\\("$"#,##0\\)',
  63: '"$"#,##0_);\\("$"#,##0\\)',
  //  6 -- Currency,   0 decimal, red   negative
  6: '"$"#,##0_);[Red]\\("$"#,##0\\)',
  64: '"$"#,##0_);[Red]\\("$"#,##0\\)',
  //  7 -- Currency,   2 decimal, black negative
  7: '"$"#,##0.00_);\\("$"#,##0.00\\)',
  65: '"$"#,##0.00_);\\("$"#,##0.00\\)',
  //  8 -- Currency,   2 decimal, red   negative
  8: '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)',
  66: '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)',
  // 41 -- Accounting, 0 decimal, No Symbol
  41: '_(* #,##0_);_(* \\(#,##0\\);_(* "-"_);_(@_)',
  // 42 -- Accounting, 0 decimal, $  Symbol
  42: '_("$"* #,##0_);_("$"* \\(#,##0\\);_("$"* "-"_);_(@_)',
  // 43 -- Accounting, 2 decimal, No Symbol
  43: '_(* #,##0.00_);_(* \\(#,##0.00\\);_(* "-"??_);_(@_)',
  // 44 -- Accounting, 2 decimal, $  Symbol
  44: '_("$"* #,##0.00_);_("$"* \\(#,##0.00\\);_("$"* "-"??_);_(@_)'
};
function SSF_frac(x2, D4, mixed) {
  var sgn = x2 < 0 ? -1 : 1;
  var B3 = x2 * sgn;
  var P_2 = 0, P_1 = 1, P3 = 0;
  var Q_2 = 1, Q_1 = 0, Q2 = 0;
  var A2 = Math.floor(B3);
  while (Q_1 < D4) {
    A2 = Math.floor(B3);
    P3 = A2 * P_1 + P_2;
    Q2 = A2 * Q_1 + Q_2;
    if (B3 - A2 < 5e-8) break;
    B3 = 1 / (B3 - A2);
    P_2 = P_1;
    P_1 = P3;
    Q_2 = Q_1;
    Q_1 = Q2;
  }
  if (Q2 > D4) {
    if (Q_1 > D4) {
      Q2 = Q_2;
      P3 = P_2;
    } else {
      Q2 = Q_1;
      P3 = P_1;
    }
  }
  if (!mixed) return [0, sgn * P3, Q2];
  var q2 = Math.floor(sgn * P3 / Q2);
  return [q2, sgn * P3 - q2 * Q2, Q2];
}
function SSF_normalize_xl_unsafe(v4) {
  var s6 = v4.toPrecision(16);
  if (s6.indexOf("e") > -1) {
    var m4 = s6.slice(0, s6.indexOf("e"));
    m4 = m4.indexOf(".") > -1 ? m4.slice(0, m4.slice(0, 2) == "0." ? 17 : 16) : m4.slice(0, 15) + fill("0", m4.length - 15);
    return m4 + s6.slice(s6.indexOf("e"));
  }
  var n7 = s6.indexOf(".") > -1 ? s6.slice(0, s6.slice(0, 2) == "0." ? 17 : 16) : s6.slice(0, 15) + fill("0", s6.length - 15);
  return Number(n7);
}
function SSF_parse_date_code(v4, opts, b22) {
  if (v4 > 2958465 || v4 < 0) return null;
  v4 = SSF_normalize_xl_unsafe(v4);
  var date = v4 | 0, time = Math.floor(86400 * (v4 - date)), dow = 0;
  var dout = [];
  var out = { D: date, T: time, u: 86400 * (v4 - date) - time, y: 0, m: 0, d: 0, H: 0, M: 0, S: 0, q: 0 };
  if (Math.abs(out.u) < 1e-6) out.u = 0;
  if (opts && opts.date1904) date += 1462;
  if (out.u > 0.9999) {
    out.u = 0;
    if (++time == 86400) {
      out.T = time = 0;
      ++date;
      ++out.D;
    }
  }
  if (date === 60) {
    dout = b22 ? [1317, 10, 29] : [1900, 2, 29];
    dow = 3;
  } else if (date === 0) {
    dout = b22 ? [1317, 8, 29] : [1900, 1, 0];
    dow = 6;
  } else {
    if (date > 60) --date;
    var d4 = new Date(1900, 0, 1);
    d4.setDate(d4.getDate() + date - 1);
    dout = [d4.getFullYear(), d4.getMonth() + 1, d4.getDate()];
    dow = d4.getDay();
    if (date < 60) dow = (dow + 6) % 7;
    if (b22) dow = SSF_fix_hijri(d4, dout);
  }
  out.y = dout[0];
  out.m = dout[1];
  out.d = dout[2];
  out.S = time % 60;
  time = Math.floor(time / 60);
  out.M = time % 60;
  time = Math.floor(time / 60);
  out.H = time;
  out.q = dow;
  return out;
}
function SSF_strip_decimal(o9) {
  return o9.indexOf(".") == -1 ? o9 : o9.replace(/(?:\.0*|(\.\d*[1-9])0+)$/, "$1");
}
function SSF_normalize_exp(o9) {
  if (o9.indexOf("E") == -1) return o9;
  return o9.replace(/(?:\.0*|(\.\d*[1-9])0+)[Ee]/, "$1E").replace(/(E[+-])(\d)$/, "$10$2");
}
function SSF_small_exp(v4) {
  var w3 = v4 < 0 ? 12 : 11;
  var o9 = SSF_strip_decimal(v4.toFixed(12));
  if (o9.length <= w3) return o9;
  o9 = v4.toPrecision(10);
  if (o9.length <= w3) return o9;
  return v4.toExponential(5);
}
function SSF_large_exp(v4) {
  var o9 = SSF_strip_decimal(v4.toFixed(11));
  return o9.length > (v4 < 0 ? 12 : 11) || o9 === "0" || o9 === "-0" ? v4.toPrecision(6) : o9;
}
function SSF_general_num(v4) {
  if (!isFinite(v4)) return isNaN(v4) ? "#NUM!" : "#DIV/0!";
  var V3 = Math.floor(Math.log(Math.abs(v4)) * Math.LOG10E), o9;
  if (V3 >= -4 && V3 <= -1) o9 = v4.toPrecision(10 + V3);
  else if (Math.abs(V3) <= 9) o9 = SSF_small_exp(v4);
  else if (V3 === 10) o9 = v4.toFixed(10).substr(0, 12);
  else o9 = SSF_large_exp(v4);
  return SSF_strip_decimal(SSF_normalize_exp(o9.toUpperCase()));
}
function SSF_general(v4, opts) {
  switch (typeof v4) {
    case "string":
      return v4;
    case "boolean":
      return v4 ? "TRUE" : "FALSE";
    case "number":
      return (v4 | 0) === v4 ? v4.toString(10) : SSF_general_num(v4);
    case "undefined":
      return "";
    case "object":
      if (v4 == null) return "";
      if (v4 instanceof Date) return SSF_format(14, datenum(v4, opts && opts.date1904), opts);
  }
  throw new Error("unsupported value in General format: " + v4);
}
function SSF_fix_hijri(date, o9) {
  o9[0] -= 581;
  var dow = date.getDay();
  if (date < 60) dow = (dow + 6) % 7;
  return dow;
}
function SSF_write_date(type, fmt, val2, ss0) {
  var o9 = "", ss = 0, tt = 0, y4 = val2.y, out, outl = 0;
  switch (type) {
    case 98:
      y4 = val2.y + 543;
    /* falls through */
    case 121:
      switch (fmt.length) {
        case 1:
        case 2:
          out = y4 % 100;
          outl = 2;
          break;
        default:
          out = y4 % 1e4;
          outl = 4;
          break;
      }
      break;
    case 109:
      switch (fmt.length) {
        case 1:
        case 2:
          out = val2.m;
          outl = fmt.length;
          break;
        case 3:
          return months[val2.m - 1][1];
        case 5:
          return months[val2.m - 1][0];
        default:
          return months[val2.m - 1][2];
      }
      break;
    case 100:
      switch (fmt.length) {
        case 1:
        case 2:
          out = val2.d;
          outl = fmt.length;
          break;
        case 3:
          return days[val2.q][0];
        default:
          return days[val2.q][1];
      }
      break;
    case 104:
      switch (fmt.length) {
        case 1:
        case 2:
          out = 1 + (val2.H + 11) % 12;
          outl = fmt.length;
          break;
        default:
          throw "bad hour format: " + fmt;
      }
      break;
    case 72:
      switch (fmt.length) {
        case 1:
        case 2:
          out = val2.H;
          outl = fmt.length;
          break;
        default:
          throw "bad hour format: " + fmt;
      }
      break;
    case 77:
      switch (fmt.length) {
        case 1:
        case 2:
          out = val2.M;
          outl = fmt.length;
          break;
        default:
          throw "bad minute format: " + fmt;
      }
      break;
    case 115:
      if (fmt != "s" && fmt != "ss" && fmt != ".0" && fmt != ".00" && fmt != ".000") throw "bad second format: " + fmt;
      if (val2.u === 0 && (fmt == "s" || fmt == "ss")) return pad0(val2.S, fmt.length);
      if (ss0 >= 2) tt = ss0 === 3 ? 1e3 : 100;
      else tt = ss0 === 1 ? 10 : 1;
      ss = Math.round(tt * (val2.S + val2.u));
      if (ss >= 60 * tt) ss = 0;
      if (fmt === "s") return ss === 0 ? "0" : "" + ss / tt;
      o9 = pad0(ss, 2 + ss0);
      if (fmt === "ss") return o9.substr(0, 2);
      return "." + o9.substr(2, fmt.length - 1);
    case 90:
      switch (fmt) {
        case "[h]":
        case "[hh]":
          out = val2.D * 24 + val2.H;
          break;
        case "[m]":
        case "[mm]":
          out = (val2.D * 24 + val2.H) * 60 + val2.M;
          break;
        case "[s]":
        case "[ss]":
          out = ((val2.D * 24 + val2.H) * 60 + val2.M) * 60 + (ss0 == 0 ? Math.round(val2.S + val2.u) : val2.S);
          break;
        default:
          throw "bad abstime format: " + fmt;
      }
      outl = fmt.length === 3 ? 1 : 2;
      break;
    case 101:
      out = y4;
      outl = 1;
      break;
  }
  var outstr = outl > 0 ? pad0(out, outl) : "";
  return outstr;
}
function commaify(s6) {
  var w3 = 3;
  if (s6.length <= w3) return s6;
  var j3 = s6.length % w3, o9 = s6.substr(0, j3);
  for (; j3 != s6.length; j3 += w3) o9 += (o9.length > 0 ? "," : "") + s6.substr(j3, w3);
  return o9;
}
var pct1 = /%/g;
function write_num_pct(type, fmt, val2) {
  var sfmt = fmt.replace(pct1, ""), mul = fmt.length - sfmt.length;
  return write_num(type, sfmt, val2 * Math.pow(10, 2 * mul)) + fill("%", mul);
}
function write_num_cm(type, fmt, val2) {
  var idx = fmt.length - 1;
  while (fmt.charCodeAt(idx - 1) === 44) --idx;
  return write_num(type, fmt.substr(0, idx), val2 / Math.pow(10, 3 * (fmt.length - idx)));
}
function write_num_exp(fmt, val2) {
  var o9;
  var idx = fmt.indexOf("E") - fmt.indexOf(".") - 1;
  if (fmt.match(/^#+0.0E\+0$/)) {
    if (val2 == 0) return "0.0E+0";
    else if (val2 < 0) return "-" + write_num_exp(fmt, -val2);
    var period = fmt.indexOf(".");
    if (period === -1) period = fmt.indexOf("E");
    var ee = Math.floor(Math.log(val2) * Math.LOG10E) % period;
    if (ee < 0) ee += period;
    o9 = (val2 / Math.pow(10, ee)).toPrecision(idx + 1 + (period + ee) % period);
    if (o9.indexOf("e") === -1) {
      var fakee = Math.floor(Math.log(val2) * Math.LOG10E);
      if (o9.indexOf(".") === -1) o9 = o9.charAt(0) + "." + o9.substr(1) + "E+" + (fakee - o9.length + ee);
      else o9 += "E+" + (fakee - ee);
      while (o9.substr(0, 2) === "0.") {
        o9 = o9.charAt(0) + o9.substr(2, period) + "." + o9.substr(2 + period);
        o9 = o9.replace(/^0+([1-9])/, "$1").replace(/^0+\./, "0.");
      }
      o9 = o9.replace(/\+-/, "-");
    }
    o9 = o9.replace(/^([+-]?)(\d*)\.(\d*)[Ee]/, function($$, $1, $22, $32) {
      return $1 + $22 + $32.substr(0, (period + ee) % period) + "." + $32.substr(ee) + "E";
    });
  } else o9 = val2.toExponential(idx);
  if (fmt.match(/E\+00$/) && o9.match(/e[+-]\d$/)) o9 = o9.substr(0, o9.length - 1) + "0" + o9.charAt(o9.length - 1);
  if (fmt.match(/E\-/) && o9.match(/e\+/)) o9 = o9.replace(/e\+/, "e");
  return o9.replace("e", "E");
}
var frac1 = /# (\?+)( ?)\/( ?)(\d+)/;
function write_num_f1(r8, aval, sign) {
  var den = parseInt(r8[4], 10), rr = Math.round(aval * den), base = Math.floor(rr / den);
  var myn = rr - base * den, myd = den;
  return sign + (base === 0 ? "" : "" + base) + " " + (myn === 0 ? fill(" ", r8[1].length + 1 + r8[4].length) : pad_(myn, r8[1].length) + r8[2] + "/" + r8[3] + pad0(myd, r8[4].length));
}
function write_num_f2(r8, aval, sign) {
  return sign + (aval === 0 ? "" : "" + aval) + fill(" ", r8[1].length + 2 + r8[4].length);
}
var dec1 = /^#*0*\.([0#]+)/;
var closeparen = /\)[^)]*[0#]/;
var phone = /\(###\) ###\\?-####/;
function hashq(str2) {
  var o9 = "", cc;
  for (var i7 = 0; i7 != str2.length; ++i7) switch (cc = str2.charCodeAt(i7)) {
    case 35:
      break;
    case 63:
      o9 += " ";
      break;
    case 48:
      o9 += "0";
      break;
    default:
      o9 += String.fromCharCode(cc);
  }
  return o9;
}
function rnd(val2, d4) {
  var dd = Math.pow(10, d4);
  return "" + Math.round(val2 * dd) / dd;
}
function dec(val2, d4) {
  var _frac = val2 - Math.floor(val2), dd = Math.pow(10, d4);
  if (d4 < ("" + Math.round(_frac * dd)).length) return 0;
  return Math.round(_frac * dd);
}
function carry(val2, d4) {
  if (d4 < ("" + Math.round((val2 - Math.floor(val2)) * Math.pow(10, d4))).length) {
    return 1;
  }
  return 0;
}
function flr(val2) {
  if (val2 < 2147483647 && val2 > -2147483648) return "" + (val2 >= 0 ? val2 | 0 : val2 - 1 | 0);
  return "" + Math.floor(val2);
}
function write_num_flt(type, fmt, val2) {
  if (type.charCodeAt(0) === 40 && !fmt.match(closeparen)) {
    var ffmt = fmt.replace(/\( */, "").replace(/ \)/, "").replace(/\)/, "");
    if (val2 >= 0) return write_num_flt("n", ffmt, val2);
    return "(" + write_num_flt("n", ffmt, -val2) + ")";
  }
  if (fmt.charCodeAt(fmt.length - 1) === 44) return write_num_cm(type, fmt, val2);
  if (fmt.indexOf("%") !== -1) return write_num_pct(type, fmt, val2);
  if (fmt.indexOf("E") !== -1) return write_num_exp(fmt, val2);
  if (fmt.charCodeAt(0) === 36) return "$" + write_num_flt(type, fmt.substr(fmt.charAt(1) == " " ? 2 : 1), val2);
  var o9;
  var r8, ri, ff, aval = Math.abs(val2), sign = val2 < 0 ? "-" : "";
  if (fmt.match(/^00+$/)) return sign + pad0r(aval, fmt.length);
  if (fmt.match(/^[#?]+$/)) {
    o9 = pad0r(val2, 0);
    if (o9 === "0") o9 = "";
    return o9.length > fmt.length ? o9 : hashq(fmt.substr(0, fmt.length - o9.length)) + o9;
  }
  if (r8 = fmt.match(frac1)) return write_num_f1(r8, aval, sign);
  if (fmt.match(/^#+0+$/)) return sign + pad0r(aval, fmt.length - fmt.indexOf("0"));
  if (r8 = fmt.match(dec1)) {
    o9 = rnd(val2, r8[1].length).replace(/^([^\.]+)$/, "$1." + hashq(r8[1])).replace(/\.$/, "." + hashq(r8[1])).replace(/\.(\d*)$/, function($$, $1) {
      return "." + $1 + fill("0", hashq(
        /*::(*/
        r8[1]
      ).length - $1.length);
    });
    return fmt.indexOf("0.") !== -1 ? o9 : o9.replace(/^0\./, ".");
  }
  fmt = fmt.replace(/^#+([0.])/, "$1");
  if (r8 = fmt.match(/^(0*)\.(#*)$/)) {
    return sign + rnd(aval, r8[2].length).replace(/\.(\d*[1-9])0*$/, ".$1").replace(/^(-?\d*)$/, "$1.").replace(/^0\./, r8[1].length ? "0." : ".");
  }
  if (r8 = fmt.match(/^#{1,3},##0(\.?)$/)) return sign + commaify(pad0r(aval, 0));
  if (r8 = fmt.match(/^#,##0\.([#0]*0)$/)) {
    return val2 < 0 ? "-" + write_num_flt(type, fmt, -val2) : commaify("" + (Math.floor(val2) + carry(val2, r8[1].length))) + "." + pad0(dec(val2, r8[1].length), r8[1].length);
  }
  if (r8 = fmt.match(/^#,#*,#0/)) return write_num_flt(type, fmt.replace(/^#,#*,/, ""), val2);
  if (r8 = fmt.match(/^([0#]+)(\\?-([0#]+))+$/)) {
    o9 = _strrev(write_num_flt(type, fmt.replace(/[\\-]/g, ""), val2));
    ri = 0;
    return _strrev(_strrev(fmt.replace(/\\/g, "")).replace(/[0#]/g, function(x3) {
      return ri < o9.length ? o9.charAt(ri++) : x3 === "0" ? "0" : "";
    }));
  }
  if (fmt.match(phone)) {
    o9 = write_num_flt(type, "##########", val2);
    return "(" + o9.substr(0, 3) + ") " + o9.substr(3, 3) + "-" + o9.substr(6);
  }
  var oa = "";
  if (r8 = fmt.match(/^([#0?]+)( ?)\/( ?)([#0?]+)/)) {
    ri = Math.min(
      /*::String(*/
      r8[4].length,
      7
    );
    ff = SSF_frac(aval, Math.pow(10, ri) - 1, false);
    o9 = "" + sign;
    oa = write_num(
      "n",
      /*::String(*/
      r8[1],
      ff[1]
    );
    if (oa.charAt(oa.length - 1) == " ") oa = oa.substr(0, oa.length - 1) + "0";
    o9 += oa + /*::String(*/
    r8[2] + "/" + /*::String(*/
    r8[3];
    oa = rpad_(ff[2], ri);
    if (oa.length < r8[4].length) oa = hashq(r8[4].substr(r8[4].length - oa.length)) + oa;
    o9 += oa;
    return o9;
  }
  if (r8 = fmt.match(/^# ([#0?]+)( ?)\/( ?)([#0?]+)/)) {
    ri = Math.min(Math.max(r8[1].length, r8[4].length), 7);
    ff = SSF_frac(aval, Math.pow(10, ri) - 1, true);
    return sign + (ff[0] || (ff[1] ? "" : "0")) + " " + (ff[1] ? pad_(ff[1], ri) + r8[2] + "/" + r8[3] + rpad_(ff[2], ri) : fill(" ", 2 * ri + 1 + r8[2].length + r8[3].length));
  }
  if (r8 = fmt.match(/^[#0?]+$/)) {
    o9 = pad0r(val2, 0);
    if (fmt.length <= o9.length) return o9;
    return hashq(fmt.substr(0, fmt.length - o9.length)) + o9;
  }
  if (r8 = fmt.match(/^([#0?]+)\.([#0]+)$/)) {
    o9 = "" + val2.toFixed(Math.min(r8[2].length, 10)).replace(/([^0])0+$/, "$1");
    ri = o9.indexOf(".");
    var lres = fmt.indexOf(".") - ri, rres = fmt.length - o9.length - lres;
    return hashq(fmt.substr(0, lres) + o9 + fmt.substr(fmt.length - rres));
  }
  if (r8 = fmt.match(/^00,000\.([#0]*0)$/)) {
    ri = dec(val2, r8[1].length);
    return val2 < 0 ? "-" + write_num_flt(type, fmt, -val2) : commaify(flr(val2)).replace(/^\d,\d{3}$/, "0$&").replace(/^\d*$/, function($$) {
      return "00," + ($$.length < 3 ? pad0(0, 3 - $$.length) : "") + $$;
    }) + "." + pad0(ri, r8[1].length);
  }
  switch (fmt) {
    case "###,##0.00":
      return write_num_flt(type, "#,##0.00", val2);
    case "###,###":
    case "##,###":
    case "#,###":
      var x2 = commaify(pad0r(aval, 0));
      return x2 !== "0" ? sign + x2 : "";
    case "###,###.00":
      return write_num_flt(type, "###,##0.00", val2).replace(/^0\./, ".");
    case "#,###.00":
      return write_num_flt(type, "#,##0.00", val2).replace(/^0\./, ".");
    default:
  }
  throw new Error("unsupported format |" + fmt + "|");
}
function write_num_cm2(type, fmt, val2) {
  var idx = fmt.length - 1;
  while (fmt.charCodeAt(idx - 1) === 44) --idx;
  return write_num(type, fmt.substr(0, idx), val2 / Math.pow(10, 3 * (fmt.length - idx)));
}
function write_num_pct2(type, fmt, val2) {
  var sfmt = fmt.replace(pct1, ""), mul = fmt.length - sfmt.length;
  return write_num(type, sfmt, val2 * Math.pow(10, 2 * mul)) + fill("%", mul);
}
function write_num_exp2(fmt, val2) {
  var o9;
  var idx = fmt.indexOf("E") - fmt.indexOf(".") - 1;
  if (fmt.match(/^#+0.0E\+0$/)) {
    if (val2 == 0) return "0.0E+0";
    else if (val2 < 0) return "-" + write_num_exp2(fmt, -val2);
    var period = fmt.indexOf(".");
    if (period === -1) period = fmt.indexOf("E");
    var ee = Math.floor(Math.log(val2) * Math.LOG10E) % period;
    if (ee < 0) ee += period;
    o9 = (val2 / Math.pow(10, ee)).toPrecision(idx + 1 + (period + ee) % period);
    if (!o9.match(/[Ee]/)) {
      var fakee = Math.floor(Math.log(val2) * Math.LOG10E);
      if (o9.indexOf(".") === -1) o9 = o9.charAt(0) + "." + o9.substr(1) + "E+" + (fakee - o9.length + ee);
      else o9 += "E+" + (fakee - ee);
      o9 = o9.replace(/\+-/, "-");
    }
    o9 = o9.replace(/^([+-]?)(\d*)\.(\d*)[Ee]/, function($$, $1, $22, $32) {
      return $1 + $22 + $32.substr(0, (period + ee) % period) + "." + $32.substr(ee) + "E";
    });
  } else o9 = val2.toExponential(idx);
  if (fmt.match(/E\+00$/) && o9.match(/e[+-]\d$/)) o9 = o9.substr(0, o9.length - 1) + "0" + o9.charAt(o9.length - 1);
  if (fmt.match(/E\-/) && o9.match(/e\+/)) o9 = o9.replace(/e\+/, "e");
  return o9.replace("e", "E");
}
function write_num_int(type, fmt, val2) {
  if (type.charCodeAt(0) === 40 && !fmt.match(closeparen)) {
    var ffmt = fmt.replace(/\( */, "").replace(/ \)/, "").replace(/\)/, "");
    if (val2 >= 0) return write_num_int("n", ffmt, val2);
    return "(" + write_num_int("n", ffmt, -val2) + ")";
  }
  if (fmt.charCodeAt(fmt.length - 1) === 44) return write_num_cm2(type, fmt, val2);
  if (fmt.indexOf("%") !== -1) return write_num_pct2(type, fmt, val2);
  if (fmt.indexOf("E") !== -1) return write_num_exp2(fmt, val2);
  if (fmt.charCodeAt(0) === 36) return "$" + write_num_int(type, fmt.substr(fmt.charAt(1) == " " ? 2 : 1), val2);
  var o9;
  var r8, ri, ff, aval = Math.abs(val2), sign = val2 < 0 ? "-" : "";
  if (fmt.match(/^00+$/)) return sign + pad0(aval, fmt.length);
  if (fmt.match(/^[#?]+$/)) {
    o9 = "" + val2;
    if (val2 === 0) o9 = "";
    return o9.length > fmt.length ? o9 : hashq(fmt.substr(0, fmt.length - o9.length)) + o9;
  }
  if (r8 = fmt.match(frac1)) return write_num_f2(r8, aval, sign);
  if (fmt.match(/^#+0+$/)) return sign + pad0(aval, fmt.length - fmt.indexOf("0"));
  if (r8 = fmt.match(dec1)) {
    o9 = ("" + val2).replace(/^([^\.]+)$/, "$1." + hashq(r8[1])).replace(/\.$/, "." + hashq(r8[1]));
    o9 = o9.replace(/\.(\d*)$/, function($$, $1) {
      return "." + $1 + fill("0", hashq(r8[1]).length - $1.length);
    });
    return fmt.indexOf("0.") !== -1 ? o9 : o9.replace(/^0\./, ".");
  }
  fmt = fmt.replace(/^#+([0.])/, "$1");
  if (r8 = fmt.match(/^(0*)\.(#*)$/)) {
    return sign + ("" + aval).replace(/\.(\d*[1-9])0*$/, ".$1").replace(/^(-?\d*)$/, "$1.").replace(/^0\./, r8[1].length ? "0." : ".");
  }
  if (r8 = fmt.match(/^#{1,3},##0(\.?)$/)) return sign + commaify("" + aval);
  if (r8 = fmt.match(/^#,##0\.([#0]*0)$/)) {
    return val2 < 0 ? "-" + write_num_int(type, fmt, -val2) : commaify("" + val2) + "." + fill("0", r8[1].length);
  }
  if (r8 = fmt.match(/^#,#*,#0/)) return write_num_int(type, fmt.replace(/^#,#*,/, ""), val2);
  if (r8 = fmt.match(/^([0#]+)(\\?-([0#]+))+$/)) {
    o9 = _strrev(write_num_int(type, fmt.replace(/[\\-]/g, ""), val2));
    ri = 0;
    return _strrev(_strrev(fmt.replace(/\\/g, "")).replace(/[0#]/g, function(x3) {
      return ri < o9.length ? o9.charAt(ri++) : x3 === "0" ? "0" : "";
    }));
  }
  if (fmt.match(phone)) {
    o9 = write_num_int(type, "##########", val2);
    return "(" + o9.substr(0, 3) + ") " + o9.substr(3, 3) + "-" + o9.substr(6);
  }
  var oa = "";
  if (r8 = fmt.match(/^([#0?]+)( ?)\/( ?)([#0?]+)/)) {
    ri = Math.min(
      /*::String(*/
      r8[4].length,
      7
    );
    ff = SSF_frac(aval, Math.pow(10, ri) - 1, false);
    o9 = "" + sign;
    oa = write_num(
      "n",
      /*::String(*/
      r8[1],
      ff[1]
    );
    if (oa.charAt(oa.length - 1) == " ") oa = oa.substr(0, oa.length - 1) + "0";
    o9 += oa + /*::String(*/
    r8[2] + "/" + /*::String(*/
    r8[3];
    oa = rpad_(ff[2], ri);
    if (oa.length < r8[4].length) oa = hashq(r8[4].substr(r8[4].length - oa.length)) + oa;
    o9 += oa;
    return o9;
  }
  if (r8 = fmt.match(/^# ([#0?]+)( ?)\/( ?)([#0?]+)/)) {
    ri = Math.min(Math.max(r8[1].length, r8[4].length), 7);
    ff = SSF_frac(aval, Math.pow(10, ri) - 1, true);
    return sign + (ff[0] || (ff[1] ? "" : "0")) + " " + (ff[1] ? pad_(ff[1], ri) + r8[2] + "/" + r8[3] + rpad_(ff[2], ri) : fill(" ", 2 * ri + 1 + r8[2].length + r8[3].length));
  }
  if (r8 = fmt.match(/^[#0?]+$/)) {
    o9 = "" + val2;
    if (fmt.length <= o9.length) return o9;
    return hashq(fmt.substr(0, fmt.length - o9.length)) + o9;
  }
  if (r8 = fmt.match(/^([#0]+)\.([#0]+)$/)) {
    o9 = "" + val2.toFixed(Math.min(r8[2].length, 10)).replace(/([^0])0+$/, "$1");
    ri = o9.indexOf(".");
    var lres = fmt.indexOf(".") - ri, rres = fmt.length - o9.length - lres;
    return hashq(fmt.substr(0, lres) + o9 + fmt.substr(fmt.length - rres));
  }
  if (r8 = fmt.match(/^00,000\.([#0]*0)$/)) {
    return val2 < 0 ? "-" + write_num_int(type, fmt, -val2) : commaify("" + val2).replace(/^\d,\d{3}$/, "0$&").replace(/^\d*$/, function($$) {
      return "00," + ($$.length < 3 ? pad0(0, 3 - $$.length) : "") + $$;
    }) + "." + pad0(0, r8[1].length);
  }
  switch (fmt) {
    case "###,###":
    case "##,###":
    case "#,###":
      var x2 = commaify("" + aval);
      return x2 !== "0" ? sign + x2 : "";
    default:
      if (fmt.match(/\.[0#?]*$/)) return write_num_int(type, fmt.slice(0, fmt.lastIndexOf(".")), val2) + hashq(fmt.slice(fmt.lastIndexOf(".")));
  }
  throw new Error("unsupported format |" + fmt + "|");
}
function write_num(type, fmt, val2) {
  return (val2 | 0) === val2 ? write_num_int(type, fmt, val2) : write_num_flt(type, fmt, val2);
}
function SSF_split_fmt(fmt) {
  var out = [];
  var in_str = false;
  for (var i7 = 0, j3 = 0; i7 < fmt.length; ++i7) switch (
    /*cc=*/
    fmt.charCodeAt(i7)
  ) {
    case 34:
      in_str = !in_str;
      break;
    case 95:
    case 42:
    case 92:
      ++i7;
      break;
    case 59:
      out[out.length] = fmt.substr(j3, i7 - j3);
      j3 = i7 + 1;
  }
  out[out.length] = fmt.substr(j3);
  if (in_str === true) throw new Error("Format |" + fmt + "| unterminated string ");
  return out;
}
var SSF_abstime = /\[[HhMmSs\u0E0A\u0E19\u0E17]*\]/;
function fmt_is_date(fmt) {
  var i7 = 0, c6 = "", o9 = "";
  while (i7 < fmt.length) {
    switch (c6 = fmt.charAt(i7)) {
      case "G":
        if (SSF_isgeneral(fmt, i7)) i7 += 6;
        i7++;
        break;
      case '"':
        for (
          ;
          /*cc=*/
          fmt.charCodeAt(++i7) !== 34 && i7 < fmt.length;
        ) {
        }
        ++i7;
        break;
      case "\\":
        i7 += 2;
        break;
      case "_":
        i7 += 2;
        break;
      case "@":
        ++i7;
        break;
      case "B":
      case "b":
        if (fmt.charAt(i7 + 1) === "1" || fmt.charAt(i7 + 1) === "2") return true;
      /* falls through */
      case "M":
      case "D":
      case "Y":
      case "H":
      case "S":
      case "E":
      /* falls through */
      case "m":
      case "d":
      case "y":
      case "h":
      case "s":
      case "e":
      case "g":
        return true;
      case "A":
      case "a":
      case "\u4E0A":
        if (fmt.substr(i7, 3).toUpperCase() === "A/P") return true;
        if (fmt.substr(i7, 5).toUpperCase() === "AM/PM") return true;
        if (fmt.substr(i7, 5).toUpperCase() === "\u4E0A\u5348/\u4E0B\u5348") return true;
        ++i7;
        break;
      case "[":
        o9 = c6;
        while (fmt.charAt(i7++) !== "]" && i7 < fmt.length) o9 += fmt.charAt(i7);
        if (o9.match(SSF_abstime)) return true;
        break;
      case ".":
      /* falls through */
      case "0":
      case "#":
        while (i7 < fmt.length && ("0#?.,E+-%".indexOf(c6 = fmt.charAt(++i7)) > -1 || c6 == "\\" && fmt.charAt(i7 + 1) == "-" && "0#".indexOf(fmt.charAt(i7 + 2)) > -1)) {
        }
        break;
      case "?":
        while (fmt.charAt(++i7) === c6) {
        }
        break;
      case "*":
        ++i7;
        if (fmt.charAt(i7) == " " || fmt.charAt(i7) == "*") ++i7;
        break;
      case "(":
      case ")":
        ++i7;
        break;
      case "1":
      case "2":
      case "3":
      case "4":
      case "5":
      case "6":
      case "7":
      case "8":
      case "9":
        while (i7 < fmt.length && "0123456789".indexOf(fmt.charAt(++i7)) > -1) {
        }
        break;
      case " ":
        ++i7;
        break;
      default:
        ++i7;
        break;
    }
  }
  return false;
}
function eval_fmt(fmt, v4, opts, flen) {
  var out = [], o9 = "", i7 = 0, c6 = "", lst = "t", dt, j3, cc;
  var hr = "H";
  while (i7 < fmt.length) {
    switch (c6 = fmt.charAt(i7)) {
      case "G":
        if (!SSF_isgeneral(fmt, i7)) throw new Error("unrecognized character " + c6 + " in " + fmt);
        out[out.length] = { t: "G", v: "General" };
        i7 += 7;
        break;
      case '"':
        for (o9 = ""; (cc = fmt.charCodeAt(++i7)) !== 34 && i7 < fmt.length; ) o9 += String.fromCharCode(cc);
        out[out.length] = { t: "t", v: o9 };
        ++i7;
        break;
      case "\\":
        var w3 = fmt.charAt(++i7), t6 = w3 === "(" || w3 === ")" ? w3 : "t";
        out[out.length] = { t: t6, v: w3 };
        ++i7;
        break;
      case "_":
        out[out.length] = { t: "t", v: " " };
        i7 += 2;
        break;
      case "@":
        out[out.length] = { t: "T", v: v4 };
        ++i7;
        break;
      case "B":
      case "b":
        if (fmt.charAt(i7 + 1) === "1" || fmt.charAt(i7 + 1) === "2") {
          if (dt == null) {
            dt = SSF_parse_date_code(v4, opts, fmt.charAt(i7 + 1) === "2");
            if (dt == null) return "";
          }
          out[out.length] = { t: "X", v: fmt.substr(i7, 2) };
          lst = c6;
          i7 += 2;
          break;
        }
      /* falls through */
      case "M":
      case "D":
      case "Y":
      case "H":
      case "S":
      case "E":
        c6 = c6.toLowerCase();
      /* falls through */
      case "m":
      case "d":
      case "y":
      case "h":
      case "s":
      case "e":
      case "g":
        if (v4 < 0) return "";
        if (dt == null) {
          dt = SSF_parse_date_code(v4, opts);
          if (dt == null) return "";
        }
        o9 = c6;
        while (++i7 < fmt.length && fmt.charAt(i7).toLowerCase() === c6) o9 += c6;
        if (c6 === "m" && lst.toLowerCase() === "h") c6 = "M";
        if (c6 === "h") c6 = hr;
        out[out.length] = { t: c6, v: o9 };
        lst = c6;
        break;
      case "A":
      case "a":
      case "\u4E0A":
        var q2 = { t: c6, v: c6 };
        if (dt == null) dt = SSF_parse_date_code(v4, opts);
        if (fmt.substr(i7, 3).toUpperCase() === "A/P") {
          if (dt != null) q2.v = dt.H >= 12 ? fmt.charAt(i7 + 2) : c6;
          q2.t = "T";
          hr = "h";
          i7 += 3;
        } else if (fmt.substr(i7, 5).toUpperCase() === "AM/PM") {
          if (dt != null) q2.v = dt.H >= 12 ? "PM" : "AM";
          q2.t = "T";
          i7 += 5;
          hr = "h";
        } else if (fmt.substr(i7, 5).toUpperCase() === "\u4E0A\u5348/\u4E0B\u5348") {
          if (dt != null) q2.v = dt.H >= 12 ? "\u4E0B\u5348" : "\u4E0A\u5348";
          q2.t = "T";
          i7 += 5;
          hr = "h";
        } else {
          q2.t = "t";
          ++i7;
        }
        if (dt == null && q2.t === "T") return "";
        out[out.length] = q2;
        lst = c6;
        break;
      case "[":
        o9 = c6;
        while (fmt.charAt(i7++) !== "]" && i7 < fmt.length) o9 += fmt.charAt(i7);
        if (o9.slice(-1) !== "]") throw 'unterminated "[" block: |' + o9 + "|";
        if (o9.match(SSF_abstime)) {
          if (dt == null) {
            dt = SSF_parse_date_code(v4, opts);
            if (dt == null) return "";
          }
          out[out.length] = { t: "Z", v: o9.toLowerCase() };
          lst = o9.charAt(1);
        } else if (o9.indexOf("$") > -1) {
          o9 = (o9.match(/\$([^-\[\]]*)/) || [])[1] || "$";
          if (!fmt_is_date(fmt)) out[out.length] = { t: "t", v: o9 };
        }
        break;
      /* Numbers */
      case ".":
        if (dt != null) {
          o9 = c6;
          while (++i7 < fmt.length && (c6 = fmt.charAt(i7)) === "0") o9 += c6;
          out[out.length] = { t: "s", v: o9 };
          break;
        }
      /* falls through */
      case "0":
      case "#":
        o9 = c6;
        while (++i7 < fmt.length && "0#?.,E+-%".indexOf(c6 = fmt.charAt(i7)) > -1) o9 += c6;
        out[out.length] = { t: "n", v: o9 };
        break;
      case "?":
        o9 = c6;
        while (fmt.charAt(++i7) === c6) o9 += c6;
        out[out.length] = { t: c6, v: o9 };
        lst = c6;
        break;
      case "*":
        ++i7;
        if (fmt.charAt(i7) == " " || fmt.charAt(i7) == "*") ++i7;
        break;
      // **
      case "(":
      case ")":
        out[out.length] = { t: flen === 1 ? "t" : c6, v: c6 };
        ++i7;
        break;
      case "1":
      case "2":
      case "3":
      case "4":
      case "5":
      case "6":
      case "7":
      case "8":
      case "9":
        o9 = c6;
        while (i7 < fmt.length && "0123456789".indexOf(fmt.charAt(++i7)) > -1) o9 += fmt.charAt(i7);
        out[out.length] = { t: "D", v: o9 };
        break;
      case " ":
        out[out.length] = { t: c6, v: c6 };
        ++i7;
        break;
      case "$":
        out[out.length] = { t: "t", v: "$" };
        ++i7;
        break;
      default:
        if (",$-+/():!^&'~{}<>=\u20ACacfijklopqrtuvwxzP".indexOf(c6) === -1) throw new Error("unrecognized character " + c6 + " in " + fmt);
        out[out.length] = { t: "t", v: c6 };
        ++i7;
        break;
    }
  }
  var bt = 0, ss0 = 0, ssm;
  for (i7 = out.length - 1, lst = "t"; i7 >= 0; --i7) {
    switch (out[i7].t) {
      case "h":
      case "H":
        out[i7].t = hr;
        lst = "h";
        if (bt < 1) bt = 1;
        break;
      case "s":
        if (ssm = out[i7].v.match(/\.0+$/)) {
          ss0 = Math.max(ss0, ssm[0].length - 1);
          bt = 4;
        }
        if (bt < 3) bt = 3;
      /* falls through */
      case "d":
      case "y":
      case "e":
        lst = out[i7].t;
        break;
      case "M":
        lst = out[i7].t;
        if (bt < 2) bt = 2;
        break;
      case "m":
        if (lst === "s") {
          out[i7].t = "M";
          if (bt < 2) bt = 2;
        }
        break;
      case "X":
        break;
      case "Z":
        if (bt < 1 && out[i7].v.match(/[Hh]/)) bt = 1;
        if (bt < 2 && out[i7].v.match(/[Mm]/)) bt = 2;
        if (bt < 3 && out[i7].v.match(/[Ss]/)) bt = 3;
    }
  }
  var _dt;
  switch (bt) {
    case 0:
      break;
    case 1:
    case 2:
    case 3:
      if (dt.u >= 0.5) {
        dt.u = 0;
        ++dt.S;
      }
      if (dt.S >= 60) {
        dt.S = 0;
        ++dt.M;
      }
      if (dt.M >= 60) {
        dt.M = 0;
        ++dt.H;
      }
      if (dt.H >= 24) {
        dt.H = 0;
        ++dt.D;
        _dt = SSF_parse_date_code(dt.D);
        _dt.u = dt.u;
        _dt.S = dt.S;
        _dt.M = dt.M;
        _dt.H = dt.H;
        dt = _dt;
      }
      break;
    case 4:
      switch (ss0) {
        case 1:
          dt.u = Math.round(dt.u * 10) / 10;
          break;
        case 2:
          dt.u = Math.round(dt.u * 100) / 100;
          break;
        case 3:
          dt.u = Math.round(dt.u * 1e3) / 1e3;
          break;
      }
      if (dt.u >= 1) {
        dt.u = 0;
        ++dt.S;
      }
      if (dt.S >= 60) {
        dt.S = 0;
        ++dt.M;
      }
      if (dt.M >= 60) {
        dt.M = 0;
        ++dt.H;
      }
      if (dt.H >= 24) {
        dt.H = 0;
        ++dt.D;
        _dt = SSF_parse_date_code(dt.D);
        _dt.u = dt.u;
        _dt.S = dt.S;
        _dt.M = dt.M;
        _dt.H = dt.H;
        dt = _dt;
      }
      break;
  }
  var nstr = "", jj;
  for (i7 = 0; i7 < out.length; ++i7) {
    switch (out[i7].t) {
      case "t":
      case "T":
      case " ":
      case "D":
        break;
      case "X":
        out[i7].v = "";
        out[i7].t = ";";
        break;
      case "d":
      case "m":
      case "y":
      case "h":
      case "H":
      case "M":
      case "s":
      case "e":
      case "b":
      case "Z":
        out[i7].v = SSF_write_date(out[i7].t.charCodeAt(0), out[i7].v, dt, ss0);
        out[i7].t = "t";
        break;
      case "n":
      case "?":
        jj = i7 + 1;
        while (out[jj] != null && ((c6 = out[jj].t) === "?" || c6 === "D" || (c6 === " " || c6 === "t") && out[jj + 1] != null && (out[jj + 1].t === "?" || out[jj + 1].t === "t" && out[jj + 1].v === "/") || out[i7].t === "(" && (c6 === " " || c6 === "n" || c6 === ")") || c6 === "t" && (out[jj].v === "/" || out[jj].v === " " && out[jj + 1] != null && out[jj + 1].t == "?"))) {
          out[i7].v += out[jj].v;
          out[jj] = { v: "", t: ";" };
          ++jj;
        }
        nstr += out[i7].v;
        i7 = jj - 1;
        break;
      case "G":
        out[i7].t = "t";
        out[i7].v = SSF_general(v4, opts);
        break;
    }
  }
  var vv = "", myv, ostr;
  if (nstr.length > 0) {
    if (nstr.charCodeAt(0) == 40) {
      myv = v4 < 0 && nstr.charCodeAt(0) === 45 ? -v4 : v4;
      ostr = write_num("n", nstr, myv);
    } else {
      myv = v4 < 0 && flen > 1 ? -v4 : v4;
      ostr = write_num("n", nstr, myv);
      if (myv < 0 && out[0] && out[0].t == "t") {
        ostr = ostr.substr(1);
        out[0].v = "-" + out[0].v;
      }
    }
    jj = ostr.length - 1;
    var decpt = out.length;
    for (i7 = 0; i7 < out.length; ++i7) if (out[i7] != null && out[i7].t != "t" && out[i7].v.indexOf(".") > -1) {
      decpt = i7;
      break;
    }
    var lasti = out.length;
    if (decpt === out.length && ostr.indexOf("E") === -1) {
      for (i7 = out.length - 1; i7 >= 0; --i7) {
        if (out[i7] == null || "n?".indexOf(out[i7].t) === -1) continue;
        if (jj >= out[i7].v.length - 1) {
          jj -= out[i7].v.length;
          out[i7].v = ostr.substr(jj + 1, out[i7].v.length);
        } else if (jj < 0) out[i7].v = "";
        else {
          out[i7].v = ostr.substr(0, jj + 1);
          jj = -1;
        }
        out[i7].t = "t";
        lasti = i7;
      }
      if (jj >= 0 && lasti < out.length) out[lasti].v = ostr.substr(0, jj + 1) + out[lasti].v;
    } else if (decpt !== out.length && ostr.indexOf("E") === -1) {
      jj = ostr.indexOf(".") - 1;
      for (i7 = decpt; i7 >= 0; --i7) {
        if (out[i7] == null || "n?".indexOf(out[i7].t) === -1) continue;
        j3 = out[i7].v.indexOf(".") > -1 && i7 === decpt ? out[i7].v.indexOf(".") - 1 : out[i7].v.length - 1;
        vv = out[i7].v.substr(j3 + 1);
        for (; j3 >= 0; --j3) {
          if (jj >= 0 && (out[i7].v.charAt(j3) === "0" || out[i7].v.charAt(j3) === "#")) vv = ostr.charAt(jj--) + vv;
        }
        out[i7].v = vv;
        out[i7].t = "t";
        lasti = i7;
      }
      if (jj >= 0 && lasti < out.length) out[lasti].v = ostr.substr(0, jj + 1) + out[lasti].v;
      jj = ostr.indexOf(".") + 1;
      for (i7 = decpt; i7 < out.length; ++i7) {
        if (out[i7] == null || "n?(".indexOf(out[i7].t) === -1 && i7 !== decpt) continue;
        j3 = out[i7].v.indexOf(".") > -1 && i7 === decpt ? out[i7].v.indexOf(".") + 1 : 0;
        vv = out[i7].v.substr(0, j3);
        for (; j3 < out[i7].v.length; ++j3) {
          if (jj < ostr.length) vv += ostr.charAt(jj++);
        }
        out[i7].v = vv;
        out[i7].t = "t";
        lasti = i7;
      }
    }
  }
  for (i7 = 0; i7 < out.length; ++i7) if (out[i7] != null && "n?".indexOf(out[i7].t) > -1) {
    myv = flen > 1 && v4 < 0 && i7 > 0 && out[i7 - 1].v === "-" ? -v4 : v4;
    out[i7].v = write_num(out[i7].t, out[i7].v, myv);
    out[i7].t = "t";
  }
  var retval = "";
  for (i7 = 0; i7 !== out.length; ++i7) if (out[i7] != null) retval += out[i7].v;
  return retval;
}
var cfregex2 = /\[(=|>[=]?|<[>=]?)(-?\d+(?:\.\d*)?)\]/;
function chkcond(v4, rr) {
  if (rr == null) return false;
  var thresh = parseFloat(rr[2]);
  switch (rr[1]) {
    case "=":
      if (v4 == thresh) return true;
      break;
    case ">":
      if (v4 > thresh) return true;
      break;
    case "<":
      if (v4 < thresh) return true;
      break;
    case "<>":
      if (v4 != thresh) return true;
      break;
    case ">=":
      if (v4 >= thresh) return true;
      break;
    case "<=":
      if (v4 <= thresh) return true;
      break;
  }
  return false;
}
function choose_fmt(f4, v4) {
  var fmt = SSF_split_fmt(f4);
  var l5 = fmt.length, lat = fmt[l5 - 1].indexOf("@");
  if (l5 < 4 && lat > -1) --l5;
  if (fmt.length > 4) throw new Error("cannot find right format for |" + fmt.join("|") + "|");
  if (typeof v4 !== "number") return [4, fmt.length === 4 || lat > -1 ? fmt[fmt.length - 1] : "@"];
  if (typeof v4 === "number" && !isFinite(v4)) v4 = 0;
  switch (fmt.length) {
    case 1:
      fmt = lat > -1 ? ["General", "General", "General", fmt[0]] : [fmt[0], fmt[0], fmt[0], "@"];
      break;
    case 2:
      fmt = lat > -1 ? [fmt[0], fmt[0], fmt[0], fmt[1]] : [fmt[0], fmt[1], fmt[0], "@"];
      break;
    case 3:
      fmt = lat > -1 ? [fmt[0], fmt[1], fmt[0], fmt[2]] : [fmt[0], fmt[1], fmt[2], "@"];
      break;
    case 4:
      break;
  }
  var ff = v4 > 0 ? fmt[0] : v4 < 0 ? fmt[1] : fmt[2];
  if (fmt[0].indexOf("[") === -1 && fmt[1].indexOf("[") === -1) return [l5, ff];
  if (fmt[0].match(/\[[=<>]/) != null || fmt[1].match(/\[[=<>]/) != null) {
    var m1 = fmt[0].match(cfregex2);
    var m22 = fmt[1].match(cfregex2);
    return chkcond(v4, m1) ? [l5, fmt[0]] : chkcond(v4, m22) ? [l5, fmt[1]] : [l5, fmt[m1 != null && m22 != null ? 2 : 1]];
  }
  return [l5, ff];
}
function SSF_format(fmt, v4, o9) {
  if (o9 == null) o9 = {};
  var sfmt = "";
  switch (typeof fmt) {
    case "string":
      if (fmt == "m/d/yy" && o9.dateNF) sfmt = o9.dateNF;
      else sfmt = fmt;
      break;
    case "number":
      if (fmt == 14 && o9.dateNF) sfmt = o9.dateNF;
      else sfmt = (o9.table != null ? o9.table : table_fmt)[fmt];
      if (sfmt == null) sfmt = o9.table && o9.table[SSF_default_map[fmt]] || table_fmt[SSF_default_map[fmt]];
      if (sfmt == null) sfmt = SSF_default_str[fmt] || "General";
      break;
  }
  if (SSF_isgeneral(sfmt, 0)) return SSF_general(v4, o9);
  if (v4 instanceof Date) v4 = datenum(v4, o9.date1904);
  var f4 = choose_fmt(sfmt, v4);
  if (SSF_isgeneral(f4[1])) return SSF_general(v4, o9);
  if (v4 === true) v4 = "TRUE";
  else if (v4 === false) v4 = "FALSE";
  else if (v4 === "" || v4 == null) return "";
  else if (isNaN(v4) && f4[1].indexOf("0") > -1) return "#NUM!";
  else if (!isFinite(v4) && f4[1].indexOf("0") > -1) return "#DIV/0!";
  return eval_fmt(f4[1], v4, o9, f4[0]);
}
function SSF_load(fmt, idx) {
  if (typeof idx != "number") {
    idx = +idx || -1;
    for (var i7 = 0; i7 < 392; ++i7) {
      if (table_fmt[i7] == void 0) {
        if (idx < 0) idx = i7;
        continue;
      }
      if (table_fmt[i7] == fmt) {
        idx = i7;
        break;
      }
    }
    if (idx < 0) idx = 391;
  }
  table_fmt[idx] = fmt;
  return idx;
}
function make_ssf() {
  table_fmt = SSF_init_table();
}
var SSFImplicit = {
  "5": '"$"#,##0_);\\("$"#,##0\\)',
  "6": '"$"#,##0_);[Red]\\("$"#,##0\\)',
  "7": '"$"#,##0.00_);\\("$"#,##0.00\\)',
  "8": '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)',
  "23": "General",
  "24": "General",
  "25": "General",
  "26": "General",
  "27": "m/d/yy",
  "28": "m/d/yy",
  "29": "m/d/yy",
  "30": "m/d/yy",
  "31": "m/d/yy",
  "32": "h:mm:ss",
  "33": "h:mm:ss",
  "34": "h:mm:ss",
  "35": "h:mm:ss",
  "36": "m/d/yy",
  "41": '_(* #,##0_);_(* (#,##0);_(* "-"_);_(@_)',
  "42": '_("$"* #,##0_);_("$"* (#,##0);_("$"* "-"_);_(@_)',
  "43": '_(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(@_)',
  "44": '_("$"* #,##0.00_);_("$"* (#,##0.00);_("$"* "-"??_);_(@_)',
  "50": "m/d/yy",
  "51": "m/d/yy",
  "52": "m/d/yy",
  "53": "m/d/yy",
  "54": "m/d/yy",
  "55": "m/d/yy",
  "56": "m/d/yy",
  "57": "m/d/yy",
  "58": "m/d/yy",
  "59": "0",
  "60": "0.00",
  "61": "#,##0",
  "62": "#,##0.00",
  "63": '"$"#,##0_);\\("$"#,##0\\)',
  "64": '"$"#,##0_);[Red]\\("$"#,##0\\)',
  "65": '"$"#,##0.00_);\\("$"#,##0.00\\)',
  "66": '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)',
  "67": "0%",
  "68": "0.00%",
  "69": "# ?/?",
  "70": "# ??/??",
  "71": "m/d/yy",
  "72": "m/d/yy",
  "73": "d-mmm-yy",
  "74": "d-mmm",
  "75": "mmm-yy",
  "76": "h:mm",
  "77": "h:mm:ss",
  "78": "m/d/yy h:mm",
  "79": "mm:ss",
  "80": "[h]:mm:ss",
  "81": "mmss.0"
};
var dateNFregex = /[dD]+|[mM]+|[yYeE]+|[Hh]+|[Ss]+/g;
function dateNF_regex(dateNF) {
  var fmt = typeof dateNF == "number" ? table_fmt[dateNF] : dateNF;
  fmt = fmt.replace(dateNFregex, "(\\d+)");
  dateNFregex.lastIndex = 0;
  return new RegExp("^" + fmt + "$");
}
function dateNF_fix(str2, dateNF, match2) {
  var Y = -1, m4 = -1, d4 = -1, H2 = -1, M4 = -1, S5 = -1;
  (dateNF.match(dateNFregex) || []).forEach(function(n7, i7) {
    var v4 = parseInt(match2[i7 + 1], 10);
    switch (n7.toLowerCase().charAt(0)) {
      case "y":
        Y = v4;
        break;
      case "d":
        d4 = v4;
        break;
      case "h":
        H2 = v4;
        break;
      case "s":
        S5 = v4;
        break;
      case "m":
        if (H2 >= 0) M4 = v4;
        else m4 = v4;
        break;
    }
  });
  dateNFregex.lastIndex = 0;
  if (S5 >= 0 && M4 == -1 && m4 >= 0) {
    M4 = m4;
    m4 = -1;
  }
  var datestr = ("" + (Y >= 0 ? Y : (/* @__PURE__ */ new Date()).getFullYear())).slice(-4) + "-" + ("00" + (m4 >= 1 ? m4 : 1)).slice(-2) + "-" + ("00" + (d4 >= 1 ? d4 : 1)).slice(-2);
  if (datestr.length == 7) datestr = "0" + datestr;
  if (datestr.length == 8) datestr = "20" + datestr;
  var timestr = ("00" + (H2 >= 0 ? H2 : 0)).slice(-2) + ":" + ("00" + (M4 >= 0 ? M4 : 0)).slice(-2) + ":" + ("00" + (S5 >= 0 ? S5 : 0)).slice(-2);
  if (H2 == -1 && M4 == -1 && S5 == -1) return datestr;
  if (Y == -1 && m4 == -1 && d4 == -1) return timestr;
  return datestr + "T" + timestr;
}
var bad_formats = {
  "d.m": "d\\.m"
  // Issue #2571 Google Sheets writes invalid format 'd.m', correct format is 'd"."m' or 'd\\.m'
};
function SSF__load(fmt, idx) {
  return SSF_load(bad_formats[fmt] || fmt, idx);
}
var CRC32 = /* @__PURE__ */ (function() {
  var CRC322 = {};
  CRC322.version = "1.2.0";
  function signed_crc_table() {
    var c6 = 0, table = new Array(256);
    for (var n7 = 0; n7 != 256; ++n7) {
      c6 = n7;
      c6 = c6 & 1 ? -306674912 ^ c6 >>> 1 : c6 >>> 1;
      c6 = c6 & 1 ? -306674912 ^ c6 >>> 1 : c6 >>> 1;
      c6 = c6 & 1 ? -306674912 ^ c6 >>> 1 : c6 >>> 1;
      c6 = c6 & 1 ? -306674912 ^ c6 >>> 1 : c6 >>> 1;
      c6 = c6 & 1 ? -306674912 ^ c6 >>> 1 : c6 >>> 1;
      c6 = c6 & 1 ? -306674912 ^ c6 >>> 1 : c6 >>> 1;
      c6 = c6 & 1 ? -306674912 ^ c6 >>> 1 : c6 >>> 1;
      c6 = c6 & 1 ? -306674912 ^ c6 >>> 1 : c6 >>> 1;
      table[n7] = c6;
    }
    return typeof Int32Array !== "undefined" ? new Int32Array(table) : table;
  }
  var T0 = signed_crc_table();
  function slice_by_16_tables(T10) {
    var c6 = 0, v4 = 0, n7 = 0, table = typeof Int32Array !== "undefined" ? new Int32Array(4096) : new Array(4096);
    for (n7 = 0; n7 != 256; ++n7) table[n7] = T10[n7];
    for (n7 = 0; n7 != 256; ++n7) {
      v4 = T10[n7];
      for (c6 = 256 + n7; c6 < 4096; c6 += 256) v4 = table[c6] = v4 >>> 8 ^ T10[v4 & 255];
    }
    var out = [];
    for (n7 = 1; n7 != 16; ++n7) out[n7 - 1] = typeof Int32Array !== "undefined" && typeof table.subarray == "function" ? table.subarray(n7 * 256, n7 * 256 + 256) : table.slice(n7 * 256, n7 * 256 + 256);
    return out;
  }
  var TT = slice_by_16_tables(T0);
  var T1 = TT[0], T22 = TT[1], T3 = TT[2], T4 = TT[3], T5 = TT[4];
  var T6 = TT[5], T7 = TT[6], T8 = TT[7], T9 = TT[8], Ta = TT[9];
  var Tb = TT[10], Tc2 = TT[11], Td = TT[12], Te2 = TT[13], Tf = TT[14];
  function crc32_bstr(bstr, seed) {
    var C3 = seed ^ -1;
    for (var i7 = 0, L3 = bstr.length; i7 < L3; ) C3 = C3 >>> 8 ^ T0[(C3 ^ bstr.charCodeAt(i7++)) & 255];
    return ~C3;
  }
  function crc32_buf(B3, seed) {
    var C3 = seed ^ -1, L3 = B3.length - 15, i7 = 0;
    for (; i7 < L3; ) C3 = Tf[B3[i7++] ^ C3 & 255] ^ Te2[B3[i7++] ^ C3 >> 8 & 255] ^ Td[B3[i7++] ^ C3 >> 16 & 255] ^ Tc2[B3[i7++] ^ C3 >>> 24] ^ Tb[B3[i7++]] ^ Ta[B3[i7++]] ^ T9[B3[i7++]] ^ T8[B3[i7++]] ^ T7[B3[i7++]] ^ T6[B3[i7++]] ^ T5[B3[i7++]] ^ T4[B3[i7++]] ^ T3[B3[i7++]] ^ T22[B3[i7++]] ^ T1[B3[i7++]] ^ T0[B3[i7++]];
    L3 += 15;
    while (i7 < L3) C3 = C3 >>> 8 ^ T0[(C3 ^ B3[i7++]) & 255];
    return ~C3;
  }
  function crc32_str(str2, seed) {
    var C3 = seed ^ -1;
    for (var i7 = 0, L3 = str2.length, c6 = 0, d4 = 0; i7 < L3; ) {
      c6 = str2.charCodeAt(i7++);
      if (c6 < 128) {
        C3 = C3 >>> 8 ^ T0[(C3 ^ c6) & 255];
      } else if (c6 < 2048) {
        C3 = C3 >>> 8 ^ T0[(C3 ^ (192 | c6 >> 6 & 31)) & 255];
        C3 = C3 >>> 8 ^ T0[(C3 ^ (128 | c6 & 63)) & 255];
      } else if (c6 >= 55296 && c6 < 57344) {
        c6 = (c6 & 1023) + 64;
        d4 = str2.charCodeAt(i7++) & 1023;
        C3 = C3 >>> 8 ^ T0[(C3 ^ (240 | c6 >> 8 & 7)) & 255];
        C3 = C3 >>> 8 ^ T0[(C3 ^ (128 | c6 >> 2 & 63)) & 255];
        C3 = C3 >>> 8 ^ T0[(C3 ^ (128 | d4 >> 6 & 15 | (c6 & 3) << 4)) & 255];
        C3 = C3 >>> 8 ^ T0[(C3 ^ (128 | d4 & 63)) & 255];
      } else {
        C3 = C3 >>> 8 ^ T0[(C3 ^ (224 | c6 >> 12 & 15)) & 255];
        C3 = C3 >>> 8 ^ T0[(C3 ^ (128 | c6 >> 6 & 63)) & 255];
        C3 = C3 >>> 8 ^ T0[(C3 ^ (128 | c6 & 63)) & 255];
      }
    }
    return ~C3;
  }
  CRC322.table = T0;
  CRC322.bstr = crc32_bstr;
  CRC322.buf = crc32_buf;
  CRC322.str = crc32_str;
  return CRC322;
})();
var CFB = /* @__PURE__ */ (function _CFB() {
  var exports = (
    /*::(*/
    {}
  );
  exports.version = "1.2.2";
  function namecmp(l5, r8) {
    var L3 = l5.split("/"), R3 = r8.split("/");
    for (var i8 = 0, c6 = 0, Z2 = Math.min(L3.length, R3.length); i8 < Z2; ++i8) {
      if (c6 = L3[i8].length - R3[i8].length) return c6;
      if (L3[i8] != R3[i8]) return L3[i8] < R3[i8] ? -1 : 1;
    }
    return L3.length - R3.length;
  }
  function dirname(p4) {
    if (p4.charAt(p4.length - 1) == "/") return p4.slice(0, -1).indexOf("/") === -1 ? p4 : dirname(p4.slice(0, -1));
    var c6 = p4.lastIndexOf("/");
    return c6 === -1 ? p4 : p4.slice(0, c6 + 1);
  }
  function filename(p4) {
    if (p4.charAt(p4.length - 1) == "/") return filename(p4.slice(0, -1));
    var c6 = p4.lastIndexOf("/");
    return c6 === -1 ? p4 : p4.slice(c6 + 1);
  }
  function write_dos_date(buf, date) {
    if (typeof date === "string") date = new Date(date);
    var hms = date.getHours();
    hms = hms << 6 | date.getMinutes();
    hms = hms << 5 | date.getSeconds() >>> 1;
    buf.write_shift(2, hms);
    var ymd = date.getFullYear() - 1980;
    ymd = ymd << 4 | date.getMonth() + 1;
    ymd = ymd << 5 | date.getDate();
    buf.write_shift(2, ymd);
  }
  function parse_dos_date(buf) {
    var hms = buf.read_shift(2) & 65535;
    var ymd = buf.read_shift(2) & 65535;
    var val2 = /* @__PURE__ */ new Date();
    var d4 = ymd & 31;
    ymd >>>= 5;
    var m4 = ymd & 15;
    ymd >>>= 4;
    val2.setMilliseconds(0);
    val2.setFullYear(ymd + 1980);
    val2.setMonth(m4 - 1);
    val2.setDate(d4);
    var S5 = hms & 31;
    hms >>>= 5;
    var M4 = hms & 63;
    hms >>>= 6;
    val2.setHours(hms);
    val2.setMinutes(M4);
    val2.setSeconds(S5 << 1);
    return val2;
  }
  function parse_extra_field(blob) {
    prep_blob(blob, 0);
    var o9 = (
      /*::(*/
      {}
    );
    var flags = 0;
    while (blob.l <= blob.length - 4) {
      var type = blob.read_shift(2);
      var sz = blob.read_shift(2), tgt = blob.l + sz;
      var p4 = {};
      switch (type) {
        /* UNIX-style Timestamps */
        case 21589:
          {
            flags = blob.read_shift(1);
            if (flags & 1) p4.mtime = blob.read_shift(4);
            if (sz > 5) {
              if (flags & 2) p4.atime = blob.read_shift(4);
              if (flags & 4) p4.ctime = blob.read_shift(4);
            }
            if (p4.mtime) p4.mt = new Date(p4.mtime * 1e3);
          }
          break;
        /* ZIP64 Extended Information Field */
        case 1:
          {
            var sz1 = blob.read_shift(4), sz2 = blob.read_shift(4);
            p4.usz = sz2 * Math.pow(2, 32) + sz1;
            sz1 = blob.read_shift(4);
            sz2 = blob.read_shift(4);
            p4.csz = sz2 * Math.pow(2, 32) + sz1;
          }
          break;
      }
      blob.l = tgt;
      o9[type] = p4;
    }
    return o9;
  }
  var fs;
  function get_fs() {
    return fs || (fs = _fs);
  }
  function parse(file, options) {
    if (file[0] == 80 && file[1] == 75) return parse_zip2(file, options);
    if ((file[0] | 32) == 109 && (file[1] | 32) == 105) return parse_mad(file, options);
    if (file.length < 512) throw new Error("CFB file size " + file.length + " < 512");
    var mver = 3;
    var ssz = 512;
    var nmfs = 0;
    var difat_sec_cnt = 0;
    var dir_start = 0;
    var minifat_start = 0;
    var difat_start = 0;
    var fat_addrs = [];
    var blob = (
      /*::(*/
      file.slice(0, 512)
    );
    prep_blob(blob, 0);
    var mv = check_get_mver(blob);
    mver = mv[0];
    switch (mver) {
      case 3:
        ssz = 512;
        break;
      case 4:
        ssz = 4096;
        break;
      case 0:
        if (mv[1] == 0) return parse_zip2(file, options);
      /* falls through */
      default:
        throw new Error("Major Version: Expected 3 or 4 saw " + mver);
    }
    if (ssz !== 512) {
      blob = /*::(*/
      file.slice(0, ssz);
      prep_blob(
        blob,
        28
        /* blob.l */
      );
    }
    var header = file.slice(0, ssz);
    check_shifts(blob, mver);
    var dir_cnt = blob.read_shift(4, "i");
    if (mver === 3 && dir_cnt !== 0) throw new Error("# Directory Sectors: Expected 0 saw " + dir_cnt);
    blob.l += 4;
    dir_start = blob.read_shift(4, "i");
    blob.l += 4;
    blob.chk("00100000", "Mini Stream Cutoff Size: ");
    minifat_start = blob.read_shift(4, "i");
    nmfs = blob.read_shift(4, "i");
    difat_start = blob.read_shift(4, "i");
    difat_sec_cnt = blob.read_shift(4, "i");
    for (var q3 = -1, j3 = 0; j3 < 109; ++j3) {
      q3 = blob.read_shift(4, "i");
      if (q3 < 0) break;
      fat_addrs[j3] = q3;
    }
    var sectors = sectorify(file, ssz);
    sleuth_fat(difat_start, difat_sec_cnt, sectors, ssz, fat_addrs);
    var sector_list = make_sector_list(sectors, dir_start, fat_addrs, ssz);
    if (dir_start < sector_list.length) sector_list[dir_start].name = "!Directory";
    if (nmfs > 0 && minifat_start !== ENDOFCHAIN) sector_list[minifat_start].name = "!MiniFAT";
    sector_list[fat_addrs[0]].name = "!FAT";
    sector_list.fat_addrs = fat_addrs;
    sector_list.ssz = ssz;
    var files = {}, Paths = [], FileIndex = [], FullPaths = [];
    read_directory(dir_start, sector_list, sectors, Paths, nmfs, files, FileIndex, minifat_start);
    build_full_paths(FileIndex, FullPaths, Paths);
    Paths.shift();
    var o9 = {
      FileIndex,
      FullPaths
    };
    if (options && options.raw) o9.raw = { header, sectors };
    return o9;
  }
  function check_get_mver(blob) {
    if (blob[blob.l] == 80 && blob[blob.l + 1] == 75) return [0, 0];
    blob.chk(HEADER_SIGNATURE, "Header Signature: ");
    blob.l += 16;
    var mver = blob.read_shift(2, "u");
    return [blob.read_shift(2, "u"), mver];
  }
  function check_shifts(blob, mver) {
    var shift = 9;
    blob.l += 2;
    switch (shift = blob.read_shift(2)) {
      case 9:
        if (mver != 3) throw new Error("Sector Shift: Expected 9 saw " + shift);
        break;
      case 12:
        if (mver != 4) throw new Error("Sector Shift: Expected 12 saw " + shift);
        break;
      default:
        throw new Error("Sector Shift: Expected 9 or 12 saw " + shift);
    }
    blob.chk("0600", "Mini Sector Shift: ");
    blob.chk("000000000000", "Reserved: ");
  }
  function sectorify(file, ssz) {
    var nsectors = Math.ceil(file.length / ssz) - 1;
    var sectors = [];
    for (var i8 = 1; i8 < nsectors; ++i8) sectors[i8 - 1] = file.slice(i8 * ssz, (i8 + 1) * ssz);
    sectors[nsectors - 1] = file.slice(nsectors * ssz);
    return sectors;
  }
  function build_full_paths(FI, FP, Paths) {
    var i8 = 0, L3 = 0, R3 = 0, C3 = 0, j3 = 0, pl = Paths.length;
    var dad = [], q3 = [];
    for (; i8 < pl; ++i8) {
      dad[i8] = q3[i8] = i8;
      FP[i8] = Paths[i8];
    }
    for (; j3 < q3.length; ++j3) {
      i8 = q3[j3];
      L3 = FI[i8].L;
      R3 = FI[i8].R;
      C3 = FI[i8].C;
      if (dad[i8] === i8) {
        if (L3 !== -1 && dad[L3] !== L3) dad[i8] = dad[L3];
        if (R3 !== -1 && dad[R3] !== R3) dad[i8] = dad[R3];
      }
      if (C3 !== -1) dad[C3] = i8;
      if (L3 !== -1 && i8 != dad[i8]) {
        dad[L3] = dad[i8];
        if (q3.lastIndexOf(L3) < j3) q3.push(L3);
      }
      if (R3 !== -1 && i8 != dad[i8]) {
        dad[R3] = dad[i8];
        if (q3.lastIndexOf(R3) < j3) q3.push(R3);
      }
    }
    for (i8 = 1; i8 < pl; ++i8) if (dad[i8] === i8) {
      if (R3 !== -1 && dad[R3] !== R3) dad[i8] = dad[R3];
      else if (L3 !== -1 && dad[L3] !== L3) dad[i8] = dad[L3];
    }
    for (i8 = 1; i8 < pl; ++i8) {
      if (FI[i8].type === 0) continue;
      j3 = i8;
      if (j3 != dad[j3]) do {
        j3 = dad[j3];
        FP[i8] = FP[j3] + "/" + FP[i8];
      } while (j3 !== 0 && -1 !== dad[j3] && j3 != dad[j3]);
      dad[i8] = -1;
    }
    FP[0] += "/";
    for (i8 = 1; i8 < pl; ++i8) {
      if (FI[i8].type !== 2) FP[i8] += "/";
    }
  }
  function get_mfat_entry(entry, payload, mini) {
    var start = entry.start, size = entry.size;
    var o9 = [];
    var idx = start;
    while (mini && size > 0 && idx >= 0) {
      o9.push(payload.slice(idx * MSSZ, idx * MSSZ + MSSZ));
      size -= MSSZ;
      idx = __readInt32LE(mini, idx * 4);
    }
    if (o9.length === 0) return new_buf(0);
    return bconcat(o9).slice(0, entry.size);
  }
  function sleuth_fat(idx, cnt, sectors, ssz, fat_addrs) {
    var q3 = ENDOFCHAIN;
    if (idx === ENDOFCHAIN) {
      if (cnt !== 0) throw new Error("DIFAT chain shorter than expected");
    } else if (idx !== -1) {
      var sector = sectors[idx], m4 = (ssz >>> 2) - 1;
      if (!sector) return;
      for (var i8 = 0; i8 < m4; ++i8) {
        if ((q3 = __readInt32LE(sector, i8 * 4)) === ENDOFCHAIN) break;
        fat_addrs.push(q3);
      }
      if (cnt >= 1) sleuth_fat(__readInt32LE(sector, ssz - 4), cnt - 1, sectors, ssz, fat_addrs);
    }
  }
  function get_sector_list(sectors, start, fat_addrs, ssz, chkd) {
    var buf = [], buf_chain = [];
    if (!chkd) chkd = [];
    var modulus = ssz - 1, j3 = 0, jj = 0;
    for (j3 = start; j3 >= 0; ) {
      chkd[j3] = true;
      buf[buf.length] = j3;
      buf_chain.push(sectors[j3]);
      var addr = fat_addrs[Math.floor(j3 * 4 / ssz)];
      jj = j3 * 4 & modulus;
      if (ssz < 4 + jj) throw new Error("FAT boundary crossed: " + j3 + " 4 " + ssz);
      if (!sectors[addr]) break;
      j3 = __readInt32LE(sectors[addr], jj);
    }
    return { nodes: buf, data: __toBuffer([buf_chain]) };
  }
  function make_sector_list(sectors, dir_start, fat_addrs, ssz) {
    var sl = sectors.length, sector_list = [];
    var chkd = [], buf = [], buf_chain = [];
    var modulus = ssz - 1, i8 = 0, j3 = 0, k2 = 0, jj = 0;
    for (i8 = 0; i8 < sl; ++i8) {
      buf = [];
      k2 = i8 + dir_start;
      if (k2 >= sl) k2 -= sl;
      if (chkd[k2]) continue;
      buf_chain = [];
      var seen = [];
      for (j3 = k2; j3 >= 0; ) {
        seen[j3] = true;
        chkd[j3] = true;
        buf[buf.length] = j3;
        buf_chain.push(sectors[j3]);
        var addr = fat_addrs[Math.floor(j3 * 4 / ssz)];
        jj = j3 * 4 & modulus;
        if (ssz < 4 + jj) throw new Error("FAT boundary crossed: " + j3 + " 4 " + ssz);
        if (!sectors[addr]) break;
        j3 = __readInt32LE(sectors[addr], jj);
        if (seen[j3]) break;
      }
      sector_list[k2] = { nodes: buf, data: __toBuffer([buf_chain]) };
    }
    return sector_list;
  }
  function read_directory(dir_start, sector_list, sectors, Paths, nmfs, files, FileIndex, mini) {
    var minifat_store = 0, pl = Paths.length ? 2 : 0;
    var sector = sector_list[dir_start].data;
    var i8 = 0, namelen = 0, name;
    for (; i8 < sector.length; i8 += 128) {
      var blob = (
        /*::(*/
        sector.slice(i8, i8 + 128)
      );
      prep_blob(blob, 64);
      namelen = blob.read_shift(2);
      name = __utf16le(blob, 0, namelen - pl);
      Paths.push(name);
      var o9 = {
        name,
        type: blob.read_shift(1),
        color: blob.read_shift(1),
        L: blob.read_shift(4, "i"),
        R: blob.read_shift(4, "i"),
        C: blob.read_shift(4, "i"),
        clsid: blob.read_shift(16),
        state: blob.read_shift(4, "i"),
        start: 0,
        size: 0
      };
      var ctime = blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2);
      if (ctime !== 0) o9.ct = read_date(blob, blob.l - 8);
      var mtime = blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2);
      if (mtime !== 0) o9.mt = read_date(blob, blob.l - 8);
      o9.start = blob.read_shift(4, "i");
      o9.size = blob.read_shift(4, "i");
      if (o9.size < 0 && o9.start < 0) {
        o9.size = o9.type = 0;
        o9.start = ENDOFCHAIN;
        o9.name = "";
      }
      if (o9.type === 5) {
        minifat_store = o9.start;
        if (nmfs > 0 && minifat_store !== ENDOFCHAIN) sector_list[minifat_store].name = "!StreamData";
      } else if (o9.size >= 4096) {
        o9.storage = "fat";
        if (sector_list[o9.start] === void 0) sector_list[o9.start] = get_sector_list(sectors, o9.start, sector_list.fat_addrs, sector_list.ssz);
        sector_list[o9.start].name = o9.name;
        o9.content = sector_list[o9.start].data.slice(0, o9.size);
      } else {
        o9.storage = "minifat";
        if (o9.size < 0) o9.size = 0;
        else if (minifat_store !== ENDOFCHAIN && o9.start !== ENDOFCHAIN && sector_list[minifat_store]) {
          o9.content = get_mfat_entry(o9, sector_list[minifat_store].data, (sector_list[mini] || {}).data);
        }
      }
      if (o9.content) prep_blob(o9.content, 0);
      files[name] = o9;
      FileIndex.push(o9);
    }
  }
  function read_date(blob, offset) {
    return new Date((__readUInt32LE(blob, offset + 4) / 1e7 * Math.pow(2, 32) + __readUInt32LE(blob, offset) / 1e7 - 11644473600) * 1e3);
  }
  function read_file(filename2, options) {
    get_fs();
    return parse(fs.readFileSync(filename2), options);
  }
  function read(blob, options) {
    var type = options && options.type;
    if (!type) {
      if (has_buf && Buffer.isBuffer(blob)) type = "buffer";
    }
    switch (type || "base64") {
      case "file":
        return read_file(blob, options);
      case "base64":
        return parse(s2a(Base64_decode(blob)), options);
      case "binary":
        return parse(s2a(blob), options);
    }
    return parse(
      /*::typeof blob == 'string' ? new Buffer(blob, 'utf-8') : */
      blob,
      options
    );
  }
  function init_cfb(cfb, opts) {
    var o9 = opts || {}, root = o9.root || "Root Entry";
    if (!cfb.FullPaths) cfb.FullPaths = [];
    if (!cfb.FileIndex) cfb.FileIndex = [];
    if (cfb.FullPaths.length !== cfb.FileIndex.length) throw new Error("inconsistent CFB structure");
    if (cfb.FullPaths.length === 0) {
      cfb.FullPaths[0] = root + "/";
      cfb.FileIndex[0] = { name: root, type: 5 };
    }
    if (o9.CLSID) cfb.FileIndex[0].clsid = o9.CLSID;
    seed_cfb(cfb);
  }
  function seed_cfb(cfb) {
    var nm = "Sh33tJ5";
    if (CFB.find(cfb, "/" + nm)) return;
    var p4 = new_buf(4);
    p4[0] = 55;
    p4[1] = p4[3] = 50;
    p4[2] = 54;
    cfb.FileIndex.push({ name: nm, type: 2, content: p4, size: 4, L: 69, R: 69, C: 69 });
    cfb.FullPaths.push(cfb.FullPaths[0] + nm);
    rebuild_cfb(cfb);
  }
  function rebuild_cfb(cfb, f4) {
    init_cfb(cfb);
    var gc = false, s6 = false;
    for (var i8 = cfb.FullPaths.length - 1; i8 >= 0; --i8) {
      var _file = cfb.FileIndex[i8];
      switch (_file.type) {
        case 0:
          if (s6) gc = true;
          else {
            cfb.FileIndex.pop();
            cfb.FullPaths.pop();
          }
          break;
        case 1:
        case 2:
        case 5:
          s6 = true;
          if (isNaN(_file.R * _file.L * _file.C)) gc = true;
          if (_file.R > -1 && _file.L > -1 && _file.R == _file.L) gc = true;
          break;
        default:
          gc = true;
          break;
      }
    }
    if (!gc && !f4) return;
    var now = new Date(1987, 1, 19), j3 = 0;
    var fullPaths = Object.create ? /* @__PURE__ */ Object.create(null) : {};
    var data = [];
    for (i8 = 0; i8 < cfb.FullPaths.length; ++i8) {
      fullPaths[cfb.FullPaths[i8]] = true;
      if (cfb.FileIndex[i8].type === 0) continue;
      data.push([cfb.FullPaths[i8], cfb.FileIndex[i8]]);
    }
    for (i8 = 0; i8 < data.length; ++i8) {
      var dad = dirname(data[i8][0]);
      s6 = fullPaths[dad];
      while (!s6) {
        while (dirname(dad) && !fullPaths[dirname(dad)]) dad = dirname(dad);
        data.push([dad, {
          name: filename(dad).replace("/", ""),
          type: 1,
          clsid: HEADER_CLSID,
          ct: now,
          mt: now,
          content: null
        }]);
        fullPaths[dad] = true;
        dad = dirname(data[i8][0]);
        s6 = fullPaths[dad];
      }
    }
    data.sort(function(x2, y4) {
      return namecmp(x2[0], y4[0]);
    });
    cfb.FullPaths = [];
    cfb.FileIndex = [];
    for (i8 = 0; i8 < data.length; ++i8) {
      cfb.FullPaths[i8] = data[i8][0];
      cfb.FileIndex[i8] = data[i8][1];
    }
    for (i8 = 0; i8 < data.length; ++i8) {
      var elt = cfb.FileIndex[i8];
      var nm = cfb.FullPaths[i8];
      elt.name = filename(nm).replace("/", "");
      elt.L = elt.R = elt.C = -(elt.color = 1);
      elt.size = elt.content ? elt.content.length : 0;
      elt.start = 0;
      elt.clsid = elt.clsid || HEADER_CLSID;
      if (i8 === 0) {
        elt.C = data.length > 1 ? 1 : -1;
        elt.size = 0;
        elt.type = 5;
      } else if (nm.slice(-1) == "/") {
        for (j3 = i8 + 1; j3 < data.length; ++j3) if (dirname(cfb.FullPaths[j3]) == nm) break;
        elt.C = j3 >= data.length ? -1 : j3;
        for (j3 = i8 + 1; j3 < data.length; ++j3) if (dirname(cfb.FullPaths[j3]) == dirname(nm)) break;
        elt.R = j3 >= data.length ? -1 : j3;
        elt.type = 1;
      } else {
        if (dirname(cfb.FullPaths[i8 + 1] || "") == dirname(nm)) elt.R = i8 + 1;
        elt.type = 2;
      }
    }
  }
  function _write(cfb, options) {
    var _opts = options || {};
    if (_opts.fileType == "mad") return write_mad(cfb, _opts);
    rebuild_cfb(cfb);
    switch (_opts.fileType) {
      case "zip":
        return write_zip(cfb, _opts);
    }
    var L3 = (function(cfb2) {
      var mini_size = 0, fat_size = 0;
      for (var i9 = 0; i9 < cfb2.FileIndex.length; ++i9) {
        var file2 = cfb2.FileIndex[i9];
        if (!file2.content) continue;
        var flen2 = file2.content.length;
        if (flen2 > 0) {
          if (flen2 < 4096) mini_size += flen2 + 63 >> 6;
          else fat_size += flen2 + 511 >> 9;
        }
      }
      var dir_cnt = cfb2.FullPaths.length + 3 >> 2;
      var mini_cnt = mini_size + 7 >> 3;
      var mfat_cnt = mini_size + 127 >> 7;
      var fat_base = mini_cnt + fat_size + dir_cnt + mfat_cnt;
      var fat_cnt = fat_base + 127 >> 7;
      var difat_cnt = fat_cnt <= 109 ? 0 : Math.ceil((fat_cnt - 109) / 127);
      while (fat_base + fat_cnt + difat_cnt + 127 >> 7 > fat_cnt) difat_cnt = ++fat_cnt <= 109 ? 0 : Math.ceil((fat_cnt - 109) / 127);
      var L4 = [1, difat_cnt, fat_cnt, mfat_cnt, dir_cnt, fat_size, mini_size, 0];
      cfb2.FileIndex[0].size = mini_size << 6;
      L4[7] = (cfb2.FileIndex[0].start = L4[0] + L4[1] + L4[2] + L4[3] + L4[4] + L4[5]) + (L4[6] + 7 >> 3);
      return L4;
    })(cfb);
    var o9 = new_buf(L3[7] << 9);
    var i8 = 0, T3 = 0;
    {
      for (i8 = 0; i8 < 8; ++i8) o9.write_shift(1, HEADER_SIG[i8]);
      for (i8 = 0; i8 < 8; ++i8) o9.write_shift(2, 0);
      o9.write_shift(2, 62);
      o9.write_shift(2, 3);
      o9.write_shift(2, 65534);
      o9.write_shift(2, 9);
      o9.write_shift(2, 6);
      for (i8 = 0; i8 < 3; ++i8) o9.write_shift(2, 0);
      o9.write_shift(4, 0);
      o9.write_shift(4, L3[2]);
      o9.write_shift(4, L3[0] + L3[1] + L3[2] + L3[3] - 1);
      o9.write_shift(4, 0);
      o9.write_shift(4, 1 << 12);
      o9.write_shift(4, L3[3] ? L3[0] + L3[1] + L3[2] - 1 : ENDOFCHAIN);
      o9.write_shift(4, L3[3]);
      o9.write_shift(-4, L3[1] ? L3[0] - 1 : ENDOFCHAIN);
      o9.write_shift(4, L3[1]);
      for (i8 = 0; i8 < 109; ++i8) o9.write_shift(-4, i8 < L3[2] ? L3[1] + i8 : -1);
    }
    if (L3[1]) {
      for (T3 = 0; T3 < L3[1]; ++T3) {
        for (; i8 < 236 + T3 * 127; ++i8) o9.write_shift(-4, i8 < L3[2] ? L3[1] + i8 : -1);
        o9.write_shift(-4, T3 === L3[1] - 1 ? ENDOFCHAIN : T3 + 1);
      }
    }
    var chainit = function(w3) {
      for (T3 += w3; i8 < T3 - 1; ++i8) o9.write_shift(-4, i8 + 1);
      if (w3) {
        ++i8;
        o9.write_shift(-4, ENDOFCHAIN);
      }
    };
    T3 = i8 = 0;
    for (T3 += L3[1]; i8 < T3; ++i8) o9.write_shift(-4, consts.DIFSECT);
    for (T3 += L3[2]; i8 < T3; ++i8) o9.write_shift(-4, consts.FATSECT);
    chainit(L3[3]);
    chainit(L3[4]);
    var j3 = 0, flen = 0;
    var file = cfb.FileIndex[0];
    for (; j3 < cfb.FileIndex.length; ++j3) {
      file = cfb.FileIndex[j3];
      if (!file.content) continue;
      flen = file.content.length;
      if (flen < 4096) continue;
      file.start = T3;
      chainit(flen + 511 >> 9);
    }
    chainit(L3[6] + 7 >> 3);
    while (o9.l & 511) o9.write_shift(-4, consts.ENDOFCHAIN);
    T3 = i8 = 0;
    for (j3 = 0; j3 < cfb.FileIndex.length; ++j3) {
      file = cfb.FileIndex[j3];
      if (!file.content) continue;
      flen = file.content.length;
      if (!flen || flen >= 4096) continue;
      file.start = T3;
      chainit(flen + 63 >> 6);
    }
    while (o9.l & 511) o9.write_shift(-4, consts.ENDOFCHAIN);
    for (i8 = 0; i8 < L3[4] << 2; ++i8) {
      var nm = cfb.FullPaths[i8];
      if (!nm || nm.length === 0) {
        for (j3 = 0; j3 < 17; ++j3) o9.write_shift(4, 0);
        for (j3 = 0; j3 < 3; ++j3) o9.write_shift(4, -1);
        for (j3 = 0; j3 < 12; ++j3) o9.write_shift(4, 0);
        continue;
      }
      file = cfb.FileIndex[i8];
      if (i8 === 0) file.start = file.size ? file.start - 1 : ENDOFCHAIN;
      var _nm = i8 === 0 && _opts.root || file.name;
      if (_nm.length > 31) {
        console.error("Name " + _nm + " will be truncated to " + _nm.slice(0, 31));
        _nm = _nm.slice(0, 31);
      }
      flen = 2 * (_nm.length + 1);
      o9.write_shift(64, _nm, "utf16le");
      o9.write_shift(2, flen);
      o9.write_shift(1, file.type);
      o9.write_shift(1, file.color);
      o9.write_shift(-4, file.L);
      o9.write_shift(-4, file.R);
      o9.write_shift(-4, file.C);
      if (!file.clsid) for (j3 = 0; j3 < 4; ++j3) o9.write_shift(4, 0);
      else o9.write_shift(16, file.clsid, "hex");
      o9.write_shift(4, file.state || 0);
      o9.write_shift(4, 0);
      o9.write_shift(4, 0);
      o9.write_shift(4, 0);
      o9.write_shift(4, 0);
      o9.write_shift(4, file.start);
      o9.write_shift(4, file.size);
      o9.write_shift(4, 0);
    }
    for (i8 = 1; i8 < cfb.FileIndex.length; ++i8) {
      file = cfb.FileIndex[i8];
      if (file.size >= 4096) {
        o9.l = file.start + 1 << 9;
        if (has_buf && Buffer.isBuffer(file.content)) {
          file.content.copy(o9, o9.l, 0, file.size);
          o9.l += file.size + 511 & -512;
        } else {
          for (j3 = 0; j3 < file.size; ++j3) o9.write_shift(1, file.content[j3]);
          for (; j3 & 511; ++j3) o9.write_shift(1, 0);
        }
      }
    }
    for (i8 = 1; i8 < cfb.FileIndex.length; ++i8) {
      file = cfb.FileIndex[i8];
      if (file.size > 0 && file.size < 4096) {
        if (has_buf && Buffer.isBuffer(file.content)) {
          file.content.copy(o9, o9.l, 0, file.size);
          o9.l += file.size + 63 & -64;
        } else {
          for (j3 = 0; j3 < file.size; ++j3) o9.write_shift(1, file.content[j3]);
          for (; j3 & 63; ++j3) o9.write_shift(1, 0);
        }
      }
    }
    if (has_buf) {
      o9.l = o9.length;
    } else {
      while (o9.l < o9.length) o9.write_shift(1, 0);
    }
    return o9;
  }
  function find2(cfb, path6) {
    var UCFullPaths = cfb.FullPaths.map(function(x2) {
      return x2.toUpperCase();
    });
    var UCPaths = UCFullPaths.map(function(x2) {
      var y4 = x2.split("/");
      return y4[y4.length - (x2.slice(-1) == "/" ? 2 : 1)];
    });
    var k2 = false;
    if (path6.charCodeAt(0) === 47) {
      k2 = true;
      path6 = UCFullPaths[0].slice(0, -1) + path6;
    } else k2 = path6.indexOf("/") !== -1;
    var UCPath = path6.toUpperCase();
    var w3 = k2 === true ? UCFullPaths.indexOf(UCPath) : UCPaths.indexOf(UCPath);
    if (w3 !== -1) return cfb.FileIndex[w3];
    var m4 = !UCPath.match(chr1);
    UCPath = UCPath.replace(chr0, "");
    if (m4) UCPath = UCPath.replace(chr1, "!");
    for (w3 = 0; w3 < UCFullPaths.length; ++w3) {
      if ((m4 ? UCFullPaths[w3].replace(chr1, "!") : UCFullPaths[w3]).replace(chr0, "") == UCPath) return cfb.FileIndex[w3];
      if ((m4 ? UCPaths[w3].replace(chr1, "!") : UCPaths[w3]).replace(chr0, "") == UCPath) return cfb.FileIndex[w3];
    }
    return null;
  }
  var MSSZ = 64;
  var ENDOFCHAIN = -2;
  var HEADER_SIGNATURE = "d0cf11e0a1b11ae1";
  var HEADER_SIG = [208, 207, 17, 224, 161, 177, 26, 225];
  var HEADER_CLSID = "00000000000000000000000000000000";
  var consts = {
    /* 2.1 Compund File Sector Numbers and Types */
    MAXREGSECT: -6,
    DIFSECT: -4,
    FATSECT: -3,
    ENDOFCHAIN,
    FREESECT: -1,
    /* 2.2 Compound File Header */
    HEADER_SIGNATURE,
    HEADER_MINOR_VERSION: "3e00",
    MAXREGSID: -6,
    NOSTREAM: -1,
    HEADER_CLSID,
    /* 2.6.1 Compound File Directory Entry */
    EntryTypes: ["unknown", "storage", "stream", "lockbytes", "property", "root"]
  };
  function write_file(cfb, filename2, options) {
    get_fs();
    var o9 = _write(cfb, options);
    fs.writeFileSync(filename2, o9);
  }
  function a2s2(o9) {
    var out = new Array(o9.length);
    for (var i8 = 0; i8 < o9.length; ++i8) out[i8] = String.fromCharCode(o9[i8]);
    return out.join("");
  }
  function write(cfb, options) {
    var o9 = _write(cfb, options);
    switch (options && options.type || "buffer") {
      case "file":
        get_fs();
        fs.writeFileSync(options.filename, o9);
        return o9;
      case "binary":
        return typeof o9 == "string" ? o9 : a2s2(o9);
      case "base64":
        return Base64_encode(typeof o9 == "string" ? o9 : a2s2(o9));
      case "buffer":
        if (has_buf) return Buffer.isBuffer(o9) ? o9 : Buffer_from(o9);
      /* falls through */
      case "array":
        return typeof o9 == "string" ? s2a(o9) : o9;
    }
    return o9;
  }
  var _zlib;
  function use_zlib(zlib) {
    try {
      var InflateRaw = zlib.InflateRaw;
      var InflRaw = new InflateRaw();
      InflRaw._processChunk(new Uint8Array([3, 0]), InflRaw._finishFlushFlag);
      if (InflRaw.bytesRead) _zlib = zlib;
      else throw new Error("zlib does not expose bytesRead");
    } catch (e9) {
      console.error("cannot use native zlib: " + (e9.message || e9));
    }
  }
  function _inflateRawSync(payload, usz) {
    if (!_zlib) return _inflate(payload, usz);
    var InflateRaw = _zlib.InflateRaw;
    var InflRaw = new InflateRaw();
    var out = InflRaw._processChunk(payload.slice(payload.l), InflRaw._finishFlushFlag);
    payload.l += InflRaw.bytesRead;
    return out;
  }
  function _deflateRawSync(payload) {
    return _zlib ? _zlib.deflateRawSync(payload) : _deflate(payload);
  }
  var CLEN_ORDER = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  var LEN_LN = [3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258];
  var DST_LN = [1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577];
  function bit_swap_8(n7) {
    var t6 = (n7 << 1 | n7 << 11) & 139536 | (n7 << 5 | n7 << 15) & 558144;
    return (t6 >> 16 | t6 >> 8 | t6) & 255;
  }
  var use_typed_arrays = typeof Uint8Array !== "undefined";
  var bitswap8 = use_typed_arrays ? new Uint8Array(1 << 8) : [];
  for (var q2 = 0; q2 < 1 << 8; ++q2) bitswap8[q2] = bit_swap_8(q2);
  function bit_swap_n(n7, b4) {
    var rev = bitswap8[n7 & 255];
    if (b4 <= 8) return rev >>> 8 - b4;
    rev = rev << 8 | bitswap8[n7 >> 8 & 255];
    if (b4 <= 16) return rev >>> 16 - b4;
    rev = rev << 8 | bitswap8[n7 >> 16 & 255];
    return rev >>> 24 - b4;
  }
  function read_bits_2(buf, bl) {
    var w3 = bl & 7, h7 = bl >>> 3;
    return (buf[h7] | (w3 <= 6 ? 0 : buf[h7 + 1] << 8)) >>> w3 & 3;
  }
  function read_bits_3(buf, bl) {
    var w3 = bl & 7, h7 = bl >>> 3;
    return (buf[h7] | (w3 <= 5 ? 0 : buf[h7 + 1] << 8)) >>> w3 & 7;
  }
  function read_bits_4(buf, bl) {
    var w3 = bl & 7, h7 = bl >>> 3;
    return (buf[h7] | (w3 <= 4 ? 0 : buf[h7 + 1] << 8)) >>> w3 & 15;
  }
  function read_bits_5(buf, bl) {
    var w3 = bl & 7, h7 = bl >>> 3;
    return (buf[h7] | (w3 <= 3 ? 0 : buf[h7 + 1] << 8)) >>> w3 & 31;
  }
  function read_bits_7(buf, bl) {
    var w3 = bl & 7, h7 = bl >>> 3;
    return (buf[h7] | (w3 <= 1 ? 0 : buf[h7 + 1] << 8)) >>> w3 & 127;
  }
  function read_bits_n(buf, bl, n7) {
    var w3 = bl & 7, h7 = bl >>> 3, f4 = (1 << n7) - 1;
    var v4 = buf[h7] >>> w3;
    if (n7 < 8 - w3) return v4 & f4;
    v4 |= buf[h7 + 1] << 8 - w3;
    if (n7 < 16 - w3) return v4 & f4;
    v4 |= buf[h7 + 2] << 16 - w3;
    if (n7 < 24 - w3) return v4 & f4;
    v4 |= buf[h7 + 3] << 24 - w3;
    return v4 & f4;
  }
  function write_bits_3(buf, bl, v4) {
    var w3 = bl & 7, h7 = bl >>> 3;
    if (w3 <= 5) buf[h7] |= (v4 & 7) << w3;
    else {
      buf[h7] |= v4 << w3 & 255;
      buf[h7 + 1] = (v4 & 7) >> 8 - w3;
    }
    return bl + 3;
  }
  function write_bits_1(buf, bl, v4) {
    var w3 = bl & 7, h7 = bl >>> 3;
    v4 = (v4 & 1) << w3;
    buf[h7] |= v4;
    return bl + 1;
  }
  function write_bits_8(buf, bl, v4) {
    var w3 = bl & 7, h7 = bl >>> 3;
    v4 <<= w3;
    buf[h7] |= v4 & 255;
    v4 >>>= 8;
    buf[h7 + 1] = v4;
    return bl + 8;
  }
  function write_bits_16(buf, bl, v4) {
    var w3 = bl & 7, h7 = bl >>> 3;
    v4 <<= w3;
    buf[h7] |= v4 & 255;
    v4 >>>= 8;
    buf[h7 + 1] = v4 & 255;
    buf[h7 + 2] = v4 >>> 8;
    return bl + 16;
  }
  function realloc(b4, sz) {
    var L3 = b4.length, M4 = 2 * L3 > sz ? 2 * L3 : sz + 5, i8 = 0;
    if (L3 >= sz) return b4;
    if (has_buf) {
      var o9 = new_unsafe_buf(M4);
      if (b4.copy) b4.copy(o9);
      else for (; i8 < b4.length; ++i8) o9[i8] = b4[i8];
      return o9;
    } else if (use_typed_arrays) {
      var a3 = new Uint8Array(M4);
      if (a3.set) a3.set(b4);
      else for (; i8 < L3; ++i8) a3[i8] = b4[i8];
      return a3;
    }
    b4.length = M4;
    return b4;
  }
  function zero_fill_array(n7) {
    var o9 = new Array(n7);
    for (var i8 = 0; i8 < n7; ++i8) o9[i8] = 0;
    return o9;
  }
  function build_tree(clens, cmap, MAX) {
    var maxlen = 1, w3 = 0, i8 = 0, j3 = 0, ccode = 0, L3 = clens.length;
    var bl_count = use_typed_arrays ? new Uint16Array(32) : zero_fill_array(32);
    for (i8 = 0; i8 < 32; ++i8) bl_count[i8] = 0;
    for (i8 = L3; i8 < MAX; ++i8) clens[i8] = 0;
    L3 = clens.length;
    var ctree = use_typed_arrays ? new Uint16Array(L3) : zero_fill_array(L3);
    for (i8 = 0; i8 < L3; ++i8) {
      bl_count[w3 = clens[i8]]++;
      if (maxlen < w3) maxlen = w3;
      ctree[i8] = 0;
    }
    bl_count[0] = 0;
    for (i8 = 1; i8 <= maxlen; ++i8) bl_count[i8 + 16] = ccode = ccode + bl_count[i8 - 1] << 1;
    for (i8 = 0; i8 < L3; ++i8) {
      ccode = clens[i8];
      if (ccode != 0) ctree[i8] = bl_count[ccode + 16]++;
    }
    var cleni = 0;
    for (i8 = 0; i8 < L3; ++i8) {
      cleni = clens[i8];
      if (cleni != 0) {
        ccode = bit_swap_n(ctree[i8], maxlen) >> maxlen - cleni;
        for (j3 = (1 << maxlen + 4 - cleni) - 1; j3 >= 0; --j3)
          cmap[ccode | j3 << cleni] = cleni & 15 | i8 << 4;
      }
    }
    return maxlen;
  }
  var fix_lmap = use_typed_arrays ? new Uint16Array(512) : zero_fill_array(512);
  var fix_dmap = use_typed_arrays ? new Uint16Array(32) : zero_fill_array(32);
  if (!use_typed_arrays) {
    for (var i7 = 0; i7 < 512; ++i7) fix_lmap[i7] = 0;
    for (i7 = 0; i7 < 32; ++i7) fix_dmap[i7] = 0;
  }
  (function() {
    var dlens = [];
    var i8 = 0;
    for (; i8 < 32; i8++) dlens.push(5);
    build_tree(dlens, fix_dmap, 32);
    var clens = [];
    i8 = 0;
    for (; i8 <= 143; i8++) clens.push(8);
    for (; i8 <= 255; i8++) clens.push(9);
    for (; i8 <= 279; i8++) clens.push(7);
    for (; i8 <= 287; i8++) clens.push(8);
    build_tree(clens, fix_lmap, 288);
  })();
  var _deflateRaw = /* @__PURE__ */ (function _deflateRawIIFE() {
    var DST_LN_RE = use_typed_arrays ? new Uint8Array(32768) : [];
    var j3 = 0, k2 = 0;
    for (; j3 < DST_LN.length - 1; ++j3) {
      for (; k2 < DST_LN[j3 + 1]; ++k2) DST_LN_RE[k2] = j3;
    }
    for (; k2 < 32768; ++k2) DST_LN_RE[k2] = 29;
    var LEN_LN_RE = use_typed_arrays ? new Uint8Array(259) : [];
    for (j3 = 0, k2 = 0; j3 < LEN_LN.length - 1; ++j3) {
      for (; k2 < LEN_LN[j3 + 1]; ++k2) LEN_LN_RE[k2] = j3;
    }
    function write_stored(data, out) {
      var boff = 0;
      while (boff < data.length) {
        var L3 = Math.min(65535, data.length - boff);
        var h7 = boff + L3 == data.length;
        out.write_shift(1, +h7);
        out.write_shift(2, L3);
        out.write_shift(2, ~L3 & 65535);
        while (L3-- > 0) out[out.l++] = data[boff++];
      }
      return out.l;
    }
    function write_huff_fixed(data, out) {
      var bl = 0;
      var boff = 0;
      var addrs = use_typed_arrays ? new Uint16Array(32768) : [];
      while (boff < data.length) {
        var L3 = (
          /* data.length - boff; */
          Math.min(65535, data.length - boff)
        );
        if (L3 < 10) {
          bl = write_bits_3(out, bl, +!!(boff + L3 == data.length));
          if (bl & 7) bl += 8 - (bl & 7);
          out.l = bl / 8 | 0;
          out.write_shift(2, L3);
          out.write_shift(2, ~L3 & 65535);
          while (L3-- > 0) out[out.l++] = data[boff++];
          bl = out.l * 8;
          continue;
        }
        bl = write_bits_3(out, bl, +!!(boff + L3 == data.length) + 2);
        var hash = 0;
        while (L3-- > 0) {
          var d4 = data[boff];
          hash = (hash << 5 ^ d4) & 32767;
          var match2 = -1, mlen = 0;
          if (match2 = addrs[hash]) {
            match2 |= boff & ~32767;
            if (match2 > boff) match2 -= 32768;
            if (match2 < boff) while (data[match2 + mlen] == data[boff + mlen] && mlen < 250) ++mlen;
          }
          if (mlen > 2) {
            d4 = LEN_LN_RE[mlen];
            if (d4 <= 22) bl = write_bits_8(out, bl, bitswap8[d4 + 1] >> 1) - 1;
            else {
              write_bits_8(out, bl, 3);
              bl += 5;
              write_bits_8(out, bl, bitswap8[d4 - 23] >> 5);
              bl += 3;
            }
            var len_eb = d4 < 8 ? 0 : d4 - 4 >> 2;
            if (len_eb > 0) {
              write_bits_16(out, bl, mlen - LEN_LN[d4]);
              bl += len_eb;
            }
            d4 = DST_LN_RE[boff - match2];
            bl = write_bits_8(out, bl, bitswap8[d4] >> 3);
            bl -= 3;
            var dst_eb = d4 < 4 ? 0 : d4 - 2 >> 1;
            if (dst_eb > 0) {
              write_bits_16(out, bl, boff - match2 - DST_LN[d4]);
              bl += dst_eb;
            }
            for (var q3 = 0; q3 < mlen; ++q3) {
              addrs[hash] = boff & 32767;
              hash = (hash << 5 ^ data[boff]) & 32767;
              ++boff;
            }
            L3 -= mlen - 1;
          } else {
            if (d4 <= 143) d4 = d4 + 48;
            else bl = write_bits_1(out, bl, 1);
            bl = write_bits_8(out, bl, bitswap8[d4]);
            addrs[hash] = boff & 32767;
            ++boff;
          }
        }
        bl = write_bits_8(out, bl, 0) - 1;
      }
      out.l = (bl + 7) / 8 | 0;
      return out.l;
    }
    return function _deflateRaw2(data, out) {
      if (data.length < 8) return write_stored(data, out);
      return write_huff_fixed(data, out);
    };
  })();
  function _deflate(data) {
    var buf = new_buf(50 + Math.floor(data.length * 1.1));
    var off = _deflateRaw(data, buf);
    return buf.slice(0, off);
  }
  var dyn_lmap = use_typed_arrays ? new Uint16Array(32768) : zero_fill_array(32768);
  var dyn_dmap = use_typed_arrays ? new Uint16Array(32768) : zero_fill_array(32768);
  var dyn_cmap = use_typed_arrays ? new Uint16Array(128) : zero_fill_array(128);
  var dyn_len_1 = 1, dyn_len_2 = 1;
  function dyn(data, boff) {
    var _HLIT = read_bits_5(data, boff) + 257;
    boff += 5;
    var _HDIST = read_bits_5(data, boff) + 1;
    boff += 5;
    var _HCLEN = read_bits_4(data, boff) + 4;
    boff += 4;
    var w3 = 0;
    var clens = use_typed_arrays ? new Uint8Array(19) : zero_fill_array(19);
    var ctree = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
    var maxlen = 1;
    var bl_count = use_typed_arrays ? new Uint8Array(8) : zero_fill_array(8);
    var next_code = use_typed_arrays ? new Uint8Array(8) : zero_fill_array(8);
    var L3 = clens.length;
    for (var i8 = 0; i8 < _HCLEN; ++i8) {
      clens[CLEN_ORDER[i8]] = w3 = read_bits_3(data, boff);
      if (maxlen < w3) maxlen = w3;
      bl_count[w3]++;
      boff += 3;
    }
    var ccode = 0;
    bl_count[0] = 0;
    for (i8 = 1; i8 <= maxlen; ++i8) next_code[i8] = ccode = ccode + bl_count[i8 - 1] << 1;
    for (i8 = 0; i8 < L3; ++i8) if ((ccode = clens[i8]) != 0) ctree[i8] = next_code[ccode]++;
    var cleni = 0;
    for (i8 = 0; i8 < L3; ++i8) {
      cleni = clens[i8];
      if (cleni != 0) {
        ccode = bitswap8[ctree[i8]] >> 8 - cleni;
        for (var j3 = (1 << 7 - cleni) - 1; j3 >= 0; --j3) dyn_cmap[ccode | j3 << cleni] = cleni & 7 | i8 << 3;
      }
    }
    var hcodes = [];
    maxlen = 1;
    for (; hcodes.length < _HLIT + _HDIST; ) {
      ccode = dyn_cmap[read_bits_7(data, boff)];
      boff += ccode & 7;
      switch (ccode >>>= 3) {
        case 16:
          w3 = 3 + read_bits_2(data, boff);
          boff += 2;
          ccode = hcodes[hcodes.length - 1];
          while (w3-- > 0) hcodes.push(ccode);
          break;
        case 17:
          w3 = 3 + read_bits_3(data, boff);
          boff += 3;
          while (w3-- > 0) hcodes.push(0);
          break;
        case 18:
          w3 = 11 + read_bits_7(data, boff);
          boff += 7;
          while (w3-- > 0) hcodes.push(0);
          break;
        default:
          hcodes.push(ccode);
          if (maxlen < ccode) maxlen = ccode;
          break;
      }
    }
    var h1 = hcodes.slice(0, _HLIT), h22 = hcodes.slice(_HLIT);
    for (i8 = _HLIT; i8 < 286; ++i8) h1[i8] = 0;
    for (i8 = _HDIST; i8 < 30; ++i8) h22[i8] = 0;
    dyn_len_1 = build_tree(h1, dyn_lmap, 286);
    dyn_len_2 = build_tree(h22, dyn_dmap, 30);
    return boff;
  }
  function inflate(data, usz) {
    if (data[0] == 3 && !(data[1] & 3)) {
      return [new_raw_buf(usz), 2];
    }
    var boff = 0;
    var header = 0;
    var outbuf = new_unsafe_buf(usz ? usz : 1 << 18);
    var woff = 0;
    var OL = outbuf.length >>> 0;
    var max_len_1 = 0, max_len_2 = 0;
    while ((header & 1) == 0) {
      header = read_bits_3(data, boff);
      boff += 3;
      if (header >>> 1 == 0) {
        if (boff & 7) boff += 8 - (boff & 7);
        var sz = data[boff >>> 3] | data[(boff >>> 3) + 1] << 8;
        boff += 32;
        if (sz > 0) {
          if (!usz && OL < woff + sz) {
            outbuf = realloc(outbuf, woff + sz);
            OL = outbuf.length;
          }
          while (sz-- > 0) {
            outbuf[woff++] = data[boff >>> 3];
            boff += 8;
          }
        }
        continue;
      } else if (header >> 1 == 1) {
        max_len_1 = 9;
        max_len_2 = 5;
      } else {
        boff = dyn(data, boff);
        max_len_1 = dyn_len_1;
        max_len_2 = dyn_len_2;
      }
      for (; ; ) {
        if (!usz && OL < woff + 32767) {
          outbuf = realloc(outbuf, woff + 32767);
          OL = outbuf.length;
        }
        var bits = read_bits_n(data, boff, max_len_1);
        var code = header >>> 1 == 1 ? fix_lmap[bits] : dyn_lmap[bits];
        boff += code & 15;
        code >>>= 4;
        if ((code >>> 8 & 255) === 0) outbuf[woff++] = code;
        else if (code == 256) break;
        else {
          code -= 257;
          var len_eb = code < 8 ? 0 : code - 4 >> 2;
          if (len_eb > 5) len_eb = 0;
          var tgt = woff + LEN_LN[code];
          if (len_eb > 0) {
            tgt += read_bits_n(data, boff, len_eb);
            boff += len_eb;
          }
          bits = read_bits_n(data, boff, max_len_2);
          code = header >>> 1 == 1 ? fix_dmap[bits] : dyn_dmap[bits];
          boff += code & 15;
          code >>>= 4;
          var dst_eb = code < 4 ? 0 : code - 2 >> 1;
          var dst = DST_LN[code];
          if (dst_eb > 0) {
            dst += read_bits_n(data, boff, dst_eb);
            boff += dst_eb;
          }
          if (!usz && OL < tgt) {
            outbuf = realloc(outbuf, tgt + 100);
            OL = outbuf.length;
          }
          while (woff < tgt) {
            outbuf[woff] = outbuf[woff - dst];
            ++woff;
          }
        }
      }
    }
    if (usz) return [outbuf, boff + 7 >>> 3];
    return [outbuf.slice(0, woff), boff + 7 >>> 3];
  }
  function _inflate(payload, usz) {
    var data = payload.slice(payload.l || 0);
    var out = inflate(data, usz);
    payload.l += out[1];
    return out[0];
  }
  function warn_or_throw(wrn, msg) {
    if (wrn) {
      if (typeof console !== "undefined") console.error(msg);
    } else throw new Error(msg);
  }
  function parse_zip2(file, options) {
    var blob = (
      /*::(*/
      file
    );
    prep_blob(blob, 0);
    var FileIndex = [], FullPaths = [];
    var o9 = {
      FileIndex,
      FullPaths
    };
    init_cfb(o9, { root: options.root });
    var i8 = blob.length - 4;
    while ((blob[i8] != 80 || blob[i8 + 1] != 75 || blob[i8 + 2] != 5 || blob[i8 + 3] != 6) && i8 >= 0) --i8;
    blob.l = i8 + 4;
    blob.l += 4;
    var fcnt = blob.read_shift(2);
    blob.l += 6;
    var start_cd = blob.read_shift(4);
    blob.l = start_cd;
    for (i8 = 0; i8 < fcnt; ++i8) {
      blob.l += 20;
      var csz = blob.read_shift(4);
      var usz = blob.read_shift(4);
      var namelen = blob.read_shift(2);
      var efsz = blob.read_shift(2);
      var fcsz = blob.read_shift(2);
      blob.l += 8;
      var offset = blob.read_shift(4);
      var EF = parse_extra_field(
        /*::(*/
        blob.slice(blob.l + namelen, blob.l + namelen + efsz)
        /*:: :any)*/
      );
      blob.l += namelen + efsz + fcsz;
      var L3 = blob.l;
      blob.l = offset + 4;
      if (EF && EF[1]) {
        if ((EF[1] || {}).usz) usz = EF[1].usz;
        if ((EF[1] || {}).csz) csz = EF[1].csz;
      }
      parse_local_file(blob, csz, usz, o9, EF);
      blob.l = L3;
    }
    return o9;
  }
  function parse_local_file(blob, csz, usz, o9, EF) {
    blob.l += 2;
    var flags = blob.read_shift(2);
    var meth = blob.read_shift(2);
    var date = parse_dos_date(blob);
    if (flags & 8257) throw new Error("Unsupported ZIP encryption");
    var crc32 = blob.read_shift(4);
    var _csz = blob.read_shift(4);
    var _usz = blob.read_shift(4);
    var namelen = blob.read_shift(2);
    var efsz = blob.read_shift(2);
    var name = "";
    for (var i8 = 0; i8 < namelen; ++i8) name += String.fromCharCode(blob[blob.l++]);
    if (efsz) {
      var ef = parse_extra_field(
        /*::(*/
        blob.slice(blob.l, blob.l + efsz)
        /*:: :any)*/
      );
      if ((ef[21589] || {}).mt) date = ef[21589].mt;
      if ((ef[1] || {}).usz) _usz = ef[1].usz;
      if ((ef[1] || {}).csz) _csz = ef[1].csz;
      if (EF) {
        if ((EF[21589] || {}).mt) date = EF[21589].mt;
        if ((EF[1] || {}).usz) _usz = EF[1].usz;
        if ((EF[1] || {}).csz) _csz = EF[1].csz;
      }
    }
    blob.l += efsz;
    var data = blob.slice(blob.l, blob.l + _csz);
    switch (meth) {
      case 8:
        data = _inflateRawSync(blob, _usz);
        break;
      case 0:
        blob.l += _csz;
        break;
      // TODO: scan for magic number
      default:
        throw new Error("Unsupported ZIP Compression method " + meth);
    }
    var wrn = false;
    if (flags & 8) {
      crc32 = blob.read_shift(4);
      if (crc32 == 134695760) {
        crc32 = blob.read_shift(4);
        wrn = true;
      }
      _csz = blob.read_shift(4);
      _usz = blob.read_shift(4);
    }
    if (_csz != csz) warn_or_throw(wrn, "Bad compressed size: " + csz + " != " + _csz);
    if (_usz != usz) warn_or_throw(wrn, "Bad uncompressed size: " + usz + " != " + _usz);
    cfb_add(o9, name, data, { unsafe: true, mt: date });
  }
  function write_zip(cfb, options) {
    var _opts = options || {};
    var out = [], cdirs = [];
    var o9 = new_buf(1);
    var method = _opts.compression ? 8 : 0, flags = 0;
    var desc = false;
    if (desc) flags |= 8;
    var i8 = 0, j3 = 0;
    var start_cd = 0, fcnt = 0;
    var root = cfb.FullPaths[0], fp = root, fi = cfb.FileIndex[0];
    var crcs = [];
    var sz_cd = 0;
    for (i8 = 1; i8 < cfb.FullPaths.length; ++i8) {
      fp = cfb.FullPaths[i8].slice(root.length);
      fi = cfb.FileIndex[i8];
      if (!fi.size || !fi.content || Array.isArray(fi.content) && fi.content.length == 0 || fp == "Sh33tJ5") continue;
      var start = start_cd;
      var namebuf = new_buf(fp.length);
      for (j3 = 0; j3 < fp.length; ++j3) namebuf.write_shift(1, fp.charCodeAt(j3) & 127);
      namebuf = namebuf.slice(0, namebuf.l);
      crcs[fcnt] = typeof fi.content == "string" ? CRC32.bstr(fi.content, 0) : CRC32.buf(
        /*::((*/
        fi.content,
        0
      );
      var outbuf = typeof fi.content == "string" ? s2a(fi.content) : fi.content;
      if (method == 8) outbuf = _deflateRawSync(outbuf);
      o9 = new_buf(30);
      o9.write_shift(4, 67324752);
      o9.write_shift(2, 20);
      o9.write_shift(2, flags);
      o9.write_shift(2, method);
      if (fi.mt) write_dos_date(o9, fi.mt);
      else o9.write_shift(4, 0);
      o9.write_shift(-4, flags & 8 ? 0 : crcs[fcnt]);
      o9.write_shift(4, flags & 8 ? 0 : outbuf.length);
      o9.write_shift(4, flags & 8 ? 0 : (
        /*::(*/
        fi.content.length
      ));
      o9.write_shift(2, namebuf.length);
      o9.write_shift(2, 0);
      start_cd += o9.length;
      out.push(o9);
      start_cd += namebuf.length;
      out.push(namebuf);
      start_cd += outbuf.length;
      out.push(outbuf);
      if (flags & 8) {
        o9 = new_buf(12);
        o9.write_shift(-4, crcs[fcnt]);
        o9.write_shift(4, outbuf.length);
        o9.write_shift(
          4,
          /*::(*/
          fi.content.length
        );
        start_cd += o9.l;
        out.push(o9);
      }
      o9 = new_buf(46);
      o9.write_shift(4, 33639248);
      o9.write_shift(2, 0);
      o9.write_shift(2, 20);
      o9.write_shift(2, flags);
      o9.write_shift(2, method);
      o9.write_shift(4, 0);
      o9.write_shift(-4, crcs[fcnt]);
      o9.write_shift(4, outbuf.length);
      o9.write_shift(
        4,
        /*::(*/
        fi.content.length
      );
      o9.write_shift(2, namebuf.length);
      o9.write_shift(2, 0);
      o9.write_shift(2, 0);
      o9.write_shift(2, 0);
      o9.write_shift(2, 0);
      o9.write_shift(4, 0);
      o9.write_shift(4, start);
      sz_cd += o9.l;
      cdirs.push(o9);
      sz_cd += namebuf.length;
      cdirs.push(namebuf);
      ++fcnt;
    }
    o9 = new_buf(22);
    o9.write_shift(4, 101010256);
    o9.write_shift(2, 0);
    o9.write_shift(2, 0);
    o9.write_shift(2, fcnt);
    o9.write_shift(2, fcnt);
    o9.write_shift(4, sz_cd);
    o9.write_shift(4, start_cd);
    o9.write_shift(2, 0);
    return bconcat([bconcat(out), bconcat(cdirs), o9]);
  }
  var ContentTypeMap = {
    "htm": "text/html",
    "xml": "text/xml",
    "gif": "image/gif",
    "jpg": "image/jpeg",
    "png": "image/png",
    "mso": "application/x-mso",
    "thmx": "application/vnd.ms-officetheme",
    "sh33tj5": "application/octet-stream"
  };
  function get_content_type(fi, fp) {
    if (fi.ctype) return fi.ctype;
    var ext2 = fi.name || "", m4 = ext2.match(/\.([^\.]+)$/);
    if (m4 && ContentTypeMap[m4[1]]) return ContentTypeMap[m4[1]];
    if (fp) {
      m4 = (ext2 = fp).match(/[\.\\]([^\.\\])+$/);
      if (m4 && ContentTypeMap[m4[1]]) return ContentTypeMap[m4[1]];
    }
    return "application/octet-stream";
  }
  function write_base64_76(bstr) {
    var data = Base64_encode(bstr);
    var o9 = [];
    for (var i8 = 0; i8 < data.length; i8 += 76) o9.push(data.slice(i8, i8 + 76));
    return o9.join("\r\n") + "\r\n";
  }
  function write_quoted_printable(text3) {
    var encoded = text3.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7E-\xFF=]/g, function(c6) {
      var w3 = c6.charCodeAt(0).toString(16).toUpperCase();
      return "=" + (w3.length == 1 ? "0" + w3 : w3);
    });
    encoded = encoded.replace(/ $/mg, "=20").replace(/\t$/mg, "=09");
    if (encoded.charAt(0) == "\n") encoded = "=0D" + encoded.slice(1);
    encoded = encoded.replace(/\r(?!\n)/mg, "=0D").replace(/\n\n/mg, "\n=0A").replace(/([^\r\n])\n/mg, "$1=0A");
    var o9 = [], split = encoded.split("\r\n");
    for (var si = 0; si < split.length; ++si) {
      var str2 = split[si];
      if (str2.length == 0) {
        o9.push("");
        continue;
      }
      for (var i8 = 0; i8 < str2.length; ) {
        var end = 76;
        var tmp = str2.slice(i8, i8 + end);
        if (tmp.charAt(end - 1) == "=") end--;
        else if (tmp.charAt(end - 2) == "=") end -= 2;
        else if (tmp.charAt(end - 3) == "=") end -= 3;
        tmp = str2.slice(i8, i8 + end);
        i8 += end;
        if (i8 < str2.length) tmp += "=";
        o9.push(tmp);
      }
    }
    return o9.join("\r\n");
  }
  function parse_quoted_printable(data) {
    var o9 = [];
    for (var di = 0; di < data.length; ++di) {
      var line = data[di];
      while (di <= data.length && line.charAt(line.length - 1) == "=") line = line.slice(0, line.length - 1) + data[++di];
      o9.push(line);
    }
    for (var oi = 0; oi < o9.length; ++oi) o9[oi] = o9[oi].replace(/[=][0-9A-Fa-f]{2}/g, function($$) {
      return String.fromCharCode(parseInt($$.slice(1), 16));
    });
    return s2a(o9.join("\r\n"));
  }
  function parse_mime(cfb, data, root) {
    var fname = "", cte = "", ctype = "", fdata;
    var di = 0;
    for (; di < 10; ++di) {
      var line = data[di];
      if (!line || line.match(/^\s*$/)) break;
      var m4 = line.match(/^([^:]*?):\s*([^\s].*)$/);
      if (m4) switch (m4[1].toLowerCase()) {
        case "content-location":
          fname = m4[2].trim();
          break;
        case "content-type":
          ctype = m4[2].trim();
          break;
        case "content-transfer-encoding":
          cte = m4[2].trim();
          break;
      }
    }
    ++di;
    switch (cte.toLowerCase()) {
      case "base64":
        fdata = s2a(Base64_decode(data.slice(di).join("")));
        break;
      case "quoted-printable":
        fdata = parse_quoted_printable(data.slice(di));
        break;
      default:
        throw new Error("Unsupported Content-Transfer-Encoding " + cte);
    }
    var file = cfb_add(cfb, fname.slice(root.length), fdata, { unsafe: true });
    if (ctype) file.ctype = ctype;
  }
  function parse_mad(file, options) {
    if (a2s2(file.slice(0, 13)).toLowerCase() != "mime-version:") throw new Error("Unsupported MAD header");
    var root = options && options.root || "";
    var data = (has_buf && Buffer.isBuffer(file) ? file.toString("binary") : a2s2(file)).split("\r\n");
    var di = 0, row = "";
    for (di = 0; di < data.length; ++di) {
      row = data[di];
      if (!/^Content-Location:/i.test(row)) continue;
      row = row.slice(row.indexOf("file"));
      if (!root) root = row.slice(0, row.lastIndexOf("/") + 1);
      if (row.slice(0, root.length) == root) continue;
      while (root.length > 0) {
        root = root.slice(0, root.length - 1);
        root = root.slice(0, root.lastIndexOf("/") + 1);
        if (row.slice(0, root.length) == root) break;
      }
    }
    var mboundary = (data[1] || "").match(/boundary="(.*?)"/);
    if (!mboundary) throw new Error("MAD cannot find boundary");
    var boundary = "--" + (mboundary[1] || "");
    var FileIndex = [], FullPaths = [];
    var o9 = {
      FileIndex,
      FullPaths
    };
    init_cfb(o9);
    var start_di, fcnt = 0;
    for (di = 0; di < data.length; ++di) {
      var line = data[di];
      if (line !== boundary && line !== boundary + "--") continue;
      if (fcnt++) parse_mime(o9, data.slice(start_di, di), root);
      start_di = di;
    }
    return o9;
  }
  function write_mad(cfb, options) {
    var opts = options || {};
    var boundary = opts.boundary || "SheetJS";
    boundary = "------=" + boundary;
    var out = [
      "MIME-Version: 1.0",
      'Content-Type: multipart/related; boundary="' + boundary.slice(2) + '"',
      "",
      "",
      ""
    ];
    var root = cfb.FullPaths[0], fp = root, fi = cfb.FileIndex[0];
    for (var i8 = 1; i8 < cfb.FullPaths.length; ++i8) {
      fp = cfb.FullPaths[i8].slice(root.length);
      fi = cfb.FileIndex[i8];
      if (!fi.size || !fi.content || fp == "Sh33tJ5") continue;
      fp = fp.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7E-\xFF]/g, function(c6) {
        return "_x" + c6.charCodeAt(0).toString(16) + "_";
      }).replace(/[\u0080-\uFFFF]/g, function(u5) {
        return "_u" + u5.charCodeAt(0).toString(16) + "_";
      });
      var ca = fi.content;
      var cstr = has_buf && Buffer.isBuffer(ca) ? ca.toString("binary") : a2s2(ca);
      var dispcnt = 0, L3 = Math.min(1024, cstr.length), cc = 0;
      for (var csl = 0; csl <= L3; ++csl) if ((cc = cstr.charCodeAt(csl)) >= 32 && cc < 128) ++dispcnt;
      var qp = dispcnt >= L3 * 4 / 5;
      out.push(boundary);
      out.push("Content-Location: " + (opts.root || "file:///C:/SheetJS/") + fp);
      out.push("Content-Transfer-Encoding: " + (qp ? "quoted-printable" : "base64"));
      out.push("Content-Type: " + get_content_type(fi, fp));
      out.push("");
      out.push(qp ? write_quoted_printable(cstr) : write_base64_76(cstr));
    }
    out.push(boundary + "--\r\n");
    return out.join("\r\n");
  }
  function cfb_new(opts) {
    var o9 = {};
    init_cfb(o9, opts);
    return o9;
  }
  function cfb_add(cfb, name, content, opts) {
    var unsafe = opts && opts.unsafe;
    if (!unsafe) init_cfb(cfb);
    var file = !unsafe && CFB.find(cfb, name);
    if (!file) {
      var fpath = cfb.FullPaths[0];
      if (name.slice(0, fpath.length) == fpath) fpath = name;
      else {
        if (fpath.slice(-1) != "/") fpath += "/";
        fpath = (fpath + name).replace("//", "/");
      }
      file = { name: filename(name), type: 2 };
      cfb.FileIndex.push(file);
      cfb.FullPaths.push(fpath);
      if (!unsafe) CFB.utils.cfb_gc(cfb);
    }
    file.content = content;
    file.size = content ? content.length : 0;
    if (opts) {
      if (opts.CLSID) file.clsid = opts.CLSID;
      if (opts.mt) file.mt = opts.mt;
      if (opts.ct) file.ct = opts.ct;
    }
    return file;
  }
  function cfb_del(cfb, name) {
    init_cfb(cfb);
    var file = CFB.find(cfb, name);
    if (file) {
      for (var j3 = 0; j3 < cfb.FileIndex.length; ++j3) if (cfb.FileIndex[j3] == file) {
        cfb.FileIndex.splice(j3, 1);
        cfb.FullPaths.splice(j3, 1);
        return true;
      }
    }
    return false;
  }
  function cfb_mov(cfb, old_name, new_name) {
    init_cfb(cfb);
    var file = CFB.find(cfb, old_name);
    if (file) {
      for (var j3 = 0; j3 < cfb.FileIndex.length; ++j3) if (cfb.FileIndex[j3] == file) {
        cfb.FileIndex[j3].name = filename(new_name);
        cfb.FullPaths[j3] = new_name;
        return true;
      }
    }
    return false;
  }
  function cfb_gc(cfb) {
    rebuild_cfb(cfb, true);
  }
  exports.find = find2;
  exports.read = read;
  exports.parse = parse;
  exports.write = write;
  exports.writeFile = write_file;
  exports.utils = {
    cfb_new,
    cfb_add,
    cfb_del,
    cfb_mov,
    cfb_gc,
    ReadShift,
    CheckField,
    prep_blob,
    bconcat,
    use_zlib,
    _deflateRaw: _deflate,
    _inflateRaw: _inflate,
    consts
  };
  return exports;
})();
var _fs;
function read_binary(path6) {
  if (typeof _fs !== "undefined") return _fs.readFileSync(path6);
  if (typeof Deno !== "undefined") return Deno.readFileSync(path6);
  if (typeof $ !== "undefined" && typeof File !== "undefined" && typeof Folder !== "undefined") try {
    var infile = File(path6);
    infile.open("r");
    infile.encoding = "binary";
    var data = infile.read();
    infile.close();
    return data;
  } catch (e9) {
    if (!e9.message || e9.message.indexOf("onstruct") == -1) throw e9;
  }
  throw new Error("Cannot access file " + path6);
}
function keys(o9) {
  var ks = Object.keys(o9), o22 = [];
  for (var i7 = 0; i7 < ks.length; ++i7) if (Object.prototype.hasOwnProperty.call(o9, ks[i7])) o22.push(ks[i7]);
  return o22;
}
function evert(obj) {
  var o9 = [], K2 = keys(obj);
  for (var i7 = 0; i7 !== K2.length; ++i7) o9[obj[K2[i7]]] = K2[i7];
  return o9;
}
var dnthresh = /* @__PURE__ */ Date.UTC(1899, 11, 30, 0, 0, 0);
var dnthresh1 = /* @__PURE__ */ Date.UTC(1899, 11, 31, 0, 0, 0);
var dnthresh2 = /* @__PURE__ */ Date.UTC(1904, 0, 1, 0, 0, 0);
function datenum(v4, date1904) {
  var epoch = /* @__PURE__ */ v4.getTime();
  var res = (epoch - dnthresh) / (24 * 60 * 60 * 1e3);
  if (date1904) {
    res -= 1462;
    return res < -1402 ? res - 1 : res;
  }
  return res < 60 ? res - 1 : res;
}
function numdate(v4) {
  if (v4 >= 60 && v4 < 61) return v4;
  var out = /* @__PURE__ */ new Date();
  out.setTime((v4 > 60 ? v4 : v4 + 1) * 24 * 60 * 60 * 1e3 + dnthresh);
  return out;
}
function parse_isodur(s6) {
  var sec = 0, mt = 0, time = false;
  var m4 = s6.match(/P([0-9\.]+Y)?([0-9\.]+M)?([0-9\.]+D)?T([0-9\.]+H)?([0-9\.]+M)?([0-9\.]+S)?/);
  if (!m4) throw new Error("|" + s6 + "| is not an ISO8601 Duration");
  for (var i7 = 1; i7 != m4.length; ++i7) {
    if (!m4[i7]) continue;
    mt = 1;
    if (i7 > 3) time = true;
    switch (m4[i7].slice(m4[i7].length - 1)) {
      case "Y":
        throw new Error("Unsupported ISO Duration Field: " + m4[i7].slice(m4[i7].length - 1));
      case "D":
        mt *= 24;
      /* falls through */
      case "H":
        mt *= 60;
      /* falls through */
      case "M":
        if (!time) throw new Error("Unsupported ISO Duration Field: M");
        else mt *= 60;
      /* falls through */
      case "S":
        break;
    }
    sec += mt * parseInt(m4[i7], 10);
  }
  return sec;
}
var pdre1 = /^(\d+):(\d+)(:\d+)?(\.\d+)?$/;
var pdre2 = /^(\d+)-(\d+)-(\d+)$/;
var pdre3 = /^(\d+)-(\d+)-(\d+)[T ](\d+):(\d+)(:\d+)?(\.\d+)?$/;
function parseDate(str2, date1904) {
  if (str2 instanceof Date) return str2;
  var m4 = str2.match(pdre1);
  if (m4) return new Date((date1904 ? dnthresh2 : dnthresh1) + ((parseInt(m4[1], 10) * 60 + parseInt(m4[2], 10)) * 60 + (m4[3] ? parseInt(m4[3].slice(1), 10) : 0)) * 1e3 + (m4[4] ? parseInt((m4[4] + "000").slice(1, 4), 10) : 0));
  m4 = str2.match(pdre2);
  if (m4) return new Date(Date.UTC(+m4[1], +m4[2] - 1, +m4[3], 0, 0, 0, 0));
  m4 = str2.match(pdre3);
  if (m4) return new Date(Date.UTC(+m4[1], +m4[2] - 1, +m4[3], +m4[4], +m4[5], m4[6] && parseInt(m4[6].slice(1), 10) || 0, m4[7] && parseInt((m4[7] + "0000").slice(1, 4), 10) || 0));
  var d4 = new Date(str2);
  return d4;
}
function cc2str(arr, debomit) {
  if (has_buf && Buffer.isBuffer(arr)) {
    if (debomit && buf_utf16le) {
      if (arr[0] == 255 && arr[1] == 254) return utf8write(arr.slice(2).toString("utf16le"));
      if (arr[1] == 254 && arr[2] == 255) return utf8write(utf16beread(arr.slice(2).toString("binary")));
    }
    return arr.toString("binary");
  }
  if (typeof TextDecoder !== "undefined") try {
    if (debomit) {
      if (arr[0] == 255 && arr[1] == 254) return utf8write(new TextDecoder("utf-16le").decode(arr.slice(2)));
      if (arr[0] == 254 && arr[1] == 255) return utf8write(new TextDecoder("utf-16be").decode(arr.slice(2)));
    }
    var rev = {
      "\u20AC": "\x80",
      "\u201A": "\x82",
      "\u0192": "\x83",
      "\u201E": "\x84",
      "\u2026": "\x85",
      "\u2020": "\x86",
      "\u2021": "\x87",
      "\u02C6": "\x88",
      "\u2030": "\x89",
      "\u0160": "\x8A",
      "\u2039": "\x8B",
      "\u0152": "\x8C",
      "\u017D": "\x8E",
      "\u2018": "\x91",
      "\u2019": "\x92",
      "\u201C": "\x93",
      "\u201D": "\x94",
      "\u2022": "\x95",
      "\u2013": "\x96",
      "\u2014": "\x97",
      "\u02DC": "\x98",
      "\u2122": "\x99",
      "\u0161": "\x9A",
      "\u203A": "\x9B",
      "\u0153": "\x9C",
      "\u017E": "\x9E",
      "\u0178": "\x9F"
    };
    if (Array.isArray(arr)) arr = new Uint8Array(arr);
    return new TextDecoder("latin1").decode(arr).replace(/[€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ]/g, function(c6) {
      return rev[c6] || c6;
    });
  } catch (e9) {
  }
  var o9 = [], i7 = 0;
  try {
    for (i7 = 0; i7 < arr.length - 65536; i7 += 65536) o9.push(String.fromCharCode.apply(0, arr.slice(i7, i7 + 65536)));
    o9.push(String.fromCharCode.apply(0, arr.slice(i7)));
  } catch (e9) {
    try {
      for (; i7 < arr.length - 16384; i7 += 16384) o9.push(String.fromCharCode.apply(0, arr.slice(i7, i7 + 16384)));
      o9.push(String.fromCharCode.apply(0, arr.slice(i7)));
    } catch (e10) {
      for (; i7 != arr.length; ++i7) o9.push(String.fromCharCode(arr[i7]));
    }
  }
  return o9.join("");
}
function dup(o9) {
  if (typeof JSON != "undefined" && !Array.isArray(o9)) return JSON.parse(JSON.stringify(o9));
  if (typeof o9 != "object" || o9 == null) return o9;
  if (o9 instanceof Date) return new Date(o9.getTime());
  var out = {};
  for (var k2 in o9) if (Object.prototype.hasOwnProperty.call(o9, k2)) out[k2] = dup(o9[k2]);
  return out;
}
function fill(c6, l5) {
  var o9 = "";
  while (o9.length < l5) o9 += c6;
  return o9;
}
function fuzzynum(s6) {
  var v4 = Number(s6);
  if (!isNaN(v4)) return isFinite(v4) ? v4 : NaN;
  if (!/\d/.test(s6)) return v4;
  var wt = 1;
  var ss = s6.replace(/([\d]),([\d])/g, "$1$2").replace(/[$]/g, "").replace(/[%]/g, function() {
    wt *= 100;
    return "";
  });
  if (!isNaN(v4 = Number(ss))) return v4 / wt;
  ss = ss.replace(/[(]([^()]*)[)]/, function($$, $1) {
    wt = -wt;
    return $1;
  });
  if (!isNaN(v4 = Number(ss))) return v4 / wt;
  return v4;
}
var FDRE1 = /^(0?\d|1[0-2])(?:|:([0-5]?\d)(?:|(\.\d+)(?:|:([0-5]?\d))|:([0-5]?\d)(|\.\d+)))\s+([ap])m?$/;
var FDRE2 = /^([01]?\d|2[0-3])(?:|:([0-5]?\d)(?:|(\.\d+)(?:|:([0-5]?\d))|:([0-5]?\d)(|\.\d+)))$/;
var FDISO = /^(\d+)-(\d+)-(\d+)[T ](\d+):(\d+)(:\d+)(\.\d+)?[Z]?$/;
var utc_append_works = (/* @__PURE__ */ new Date("6/9/69 00:00 UTC")).valueOf() == -177984e5;
function fuzzytime1(M4) {
  if (!M4[2]) return new Date(Date.UTC(1899, 11, 31, +M4[1] % 12 + (M4[7] == "p" ? 12 : 0), 0, 0, 0));
  if (M4[3]) {
    if (M4[4]) return new Date(Date.UTC(1899, 11, 31, +M4[1] % 12 + (M4[7] == "p" ? 12 : 0), +M4[2], +M4[4], parseFloat(M4[3]) * 1e3));
    else return new Date(Date.UTC(1899, 11, 31, M4[7] == "p" ? 12 : 0, +M4[1], +M4[2], parseFloat(M4[3]) * 1e3));
  } else if (M4[5]) return new Date(Date.UTC(1899, 11, 31, +M4[1] % 12 + (M4[7] == "p" ? 12 : 0), +M4[2], +M4[5], M4[6] ? parseFloat(M4[6]) * 1e3 : 0));
  else return new Date(Date.UTC(1899, 11, 31, +M4[1] % 12 + (M4[7] == "p" ? 12 : 0), +M4[2], 0, 0));
}
function fuzzytime2(M4) {
  if (!M4[2]) return new Date(Date.UTC(1899, 11, 31, +M4[1], 0, 0, 0));
  if (M4[3]) {
    if (M4[4]) return new Date(Date.UTC(1899, 11, 31, +M4[1], +M4[2], +M4[4], parseFloat(M4[3]) * 1e3));
    else return new Date(Date.UTC(1899, 11, 31, 0, +M4[1], +M4[2], parseFloat(M4[3]) * 1e3));
  } else if (M4[5]) return new Date(Date.UTC(1899, 11, 31, +M4[1], +M4[2], +M4[5], M4[6] ? parseFloat(M4[6]) * 1e3 : 0));
  else return new Date(Date.UTC(1899, 11, 31, +M4[1], +M4[2], 0, 0));
}
var lower_months = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];
function fuzzydate(s6) {
  if (FDISO.test(s6)) return s6.indexOf("Z") == -1 ? local_to_utc(new Date(s6)) : new Date(s6);
  var lower = s6.toLowerCase();
  var lnos = lower.replace(/\s+/g, " ").trim();
  var M4 = lnos.match(FDRE1);
  if (M4) return fuzzytime1(M4);
  M4 = lnos.match(FDRE2);
  if (M4) return fuzzytime2(M4);
  M4 = lnos.match(pdre3);
  if (M4) return new Date(Date.UTC(+M4[1], +M4[2] - 1, +M4[3], +M4[4], +M4[5], M4[6] && parseInt(M4[6].slice(1), 10) || 0, M4[7] && parseInt((M4[7] + "0000").slice(1, 4), 10) || 0));
  var o9 = new Date(utc_append_works && s6.indexOf("UTC") == -1 ? s6 + " UTC" : s6), n7 = /* @__PURE__ */ new Date(NaN);
  var y4 = o9.getYear(), m4 = o9.getMonth(), d4 = o9.getDate();
  if (isNaN(d4)) return n7;
  if (lower.match(/jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec/)) {
    lower = lower.replace(/[^a-z]/g, "").replace(/([^a-z]|^)[ap]m?([^a-z]|$)/, "");
    if (lower.length > 3 && lower_months.indexOf(lower) == -1) return n7;
  } else if (lower.replace(/[ap]m?/, "").match(/[a-z]/)) return n7;
  if (y4 < 0 || y4 > 8099 || s6.match(/[^-0-9:,\/\\\ ]/)) return n7;
  return o9;
}
var split_regex = /* @__PURE__ */ (function() {
  var safe_split_regex = "abacaba".split(/(:?b)/i).length == 5;
  return function split_regex2(str2, re2, def) {
    if (safe_split_regex || typeof re2 == "string") return str2.split(re2);
    var p4 = str2.split(re2), o9 = [p4[0]];
    for (var i7 = 1; i7 < p4.length; ++i7) {
      o9.push(def);
      o9.push(p4[i7]);
    }
    return o9;
  };
})();
function utc_to_local(utc) {
  return new Date(utc.getUTCFullYear(), utc.getUTCMonth(), utc.getUTCDate(), utc.getUTCHours(), utc.getUTCMinutes(), utc.getUTCSeconds(), utc.getUTCMilliseconds());
}
function local_to_utc(local) {
  return new Date(Date.UTC(local.getFullYear(), local.getMonth(), local.getDate(), local.getHours(), local.getMinutes(), local.getSeconds(), local.getMilliseconds()));
}
function remove_doctype(str2) {
  var preamble = str2.slice(0, 1024);
  var si = preamble.indexOf("<!DOCTYPE");
  if (si == -1) return str2;
  var m4 = str2.match(/<[\w]/);
  if (!m4) return str2;
  return str2.slice(0, si) + str2.slice(m4.index);
}
function str_match_ng(str2, s6, e9) {
  var out = [];
  var si = str2.indexOf(s6);
  while (si > -1) {
    var ei = str2.indexOf(e9, si + s6.length);
    if (ei == -1) break;
    out.push(str2.slice(si, ei + e9.length));
    si = str2.indexOf(s6, ei + e9.length);
  }
  return out.length > 0 ? out : null;
}
function str_remove_ng(str2, s6, e9) {
  var out = [], last = 0;
  var si = str2.indexOf(s6);
  if (si == -1) return str2;
  while (si > -1) {
    out.push(str2.slice(last, si));
    var ei = str2.indexOf(e9, si + s6.length);
    if (ei == -1) break;
    if ((si = str2.indexOf(s6, last = ei + e9.length)) == -1) out.push(str2.slice(last));
  }
  return out.join("");
}
var xml_boundary = { " ": 1, "	": 1, "\r": 1, "\n": 1, ">": 1 };
function str_match_xml(str2, tag) {
  var si = str2.indexOf("<" + tag), w3 = tag.length + 1, L3 = str2.length;
  while (si >= 0 && si <= L3 - w3 && !xml_boundary[str2.charAt(si + w3)]) si = str2.indexOf("<" + tag, si + 1);
  if (si === -1) return null;
  var sf = str2.indexOf(">", si + tag.length);
  if (sf === -1) return null;
  var et = "</" + tag + ">";
  var ei = str2.indexOf(et, sf);
  if (ei == -1) return null;
  return [str2.slice(si, ei + et.length), str2.slice(sf + 1, ei)];
}
var str_match_xml_ns = /* @__PURE__ */ (function() {
  var str_match_xml_ns_cache = {};
  return function str_match_xml_ns2(str2, tag) {
    var res = str_match_xml_ns_cache[tag];
    if (!res) str_match_xml_ns_cache[tag] = res = [
      new RegExp("<(?:\\w+:)?" + tag + "\\b[^<>]*>", "g"),
      new RegExp("</(?:\\w+:)?" + tag + ">", "g")
    ];
    res[0].lastIndex = res[1].lastIndex = 0;
    var m4 = res[0].exec(str2);
    if (!m4) return null;
    var si = m4.index;
    var sf = res[0].lastIndex;
    res[1].lastIndex = res[0].lastIndex;
    m4 = res[1].exec(str2);
    if (!m4) return null;
    var ei = m4.index;
    var ef = res[1].lastIndex;
    return [str2.slice(si, ef), str2.slice(sf, ei)];
  };
})();
var str_match_xml_ns_g = /* @__PURE__ */ (function() {
  var str_match_xml_ns_cache = {};
  return function str_match_xml_ns2(str2, tag) {
    var out = [];
    var res = str_match_xml_ns_cache[tag];
    if (!res) str_match_xml_ns_cache[tag] = res = [
      new RegExp("<(?:\\w+:)?" + tag + "\\b[^<>]*>", "g"),
      new RegExp("</(?:\\w+:)?" + tag + ">", "g")
    ];
    res[0].lastIndex = res[1].lastIndex = 0;
    var m4;
    while (m4 = res[0].exec(str2)) {
      var si = m4.index;
      res[1].lastIndex = res[0].lastIndex;
      m4 = res[1].exec(str2);
      if (!m4) return null;
      var ef = res[1].lastIndex;
      out.push(str2.slice(si, ef));
      res[0].lastIndex = res[1].lastIndex;
    }
    return out.length == 0 ? null : out;
  };
})();
var str_remove_xml_ns_g = /* @__PURE__ */ (function() {
  var str_remove_xml_ns_cache = {};
  return function str_remove_xml_ns_g2(str2, tag) {
    var out = [];
    var res = str_remove_xml_ns_cache[tag];
    if (!res) str_remove_xml_ns_cache[tag] = res = [
      new RegExp("<(?:\\w+:)?" + tag + "\\b[^<>]*>", "g"),
      new RegExp("</(?:\\w+:)?" + tag + ">", "g")
    ];
    res[0].lastIndex = res[1].lastIndex = 0;
    var m4;
    var si = 0, ef = 0;
    while (m4 = res[0].exec(str2)) {
      si = m4.index;
      out.push(str2.slice(ef, si));
      ef = si;
      res[1].lastIndex = res[0].lastIndex;
      m4 = res[1].exec(str2);
      if (!m4) return null;
      ef = res[1].lastIndex;
      res[0].lastIndex = res[1].lastIndex;
    }
    out.push(str2.slice(ef));
    return out.length == 0 ? "" : out.join("");
  };
})();
var str_match_xml_ig = /* @__PURE__ */ (function() {
  var str_match_xml_ns_cache = {};
  return function str_match_xml_ns2(str2, tag) {
    var out = [];
    var res = str_match_xml_ns_cache[tag];
    if (!res) str_match_xml_ns_cache[tag] = res = [
      new RegExp("<" + tag + "\\b[^<>]*>", "ig"),
      new RegExp("</" + tag + ">", "ig")
    ];
    res[0].lastIndex = res[1].lastIndex = 0;
    var m4;
    while (m4 = res[0].exec(str2)) {
      var si = m4.index;
      res[1].lastIndex = res[0].lastIndex;
      m4 = res[1].exec(str2);
      if (!m4) return null;
      var ef = res[1].lastIndex;
      out.push(str2.slice(si, ef));
      res[0].lastIndex = res[1].lastIndex;
    }
    return out.length == 0 ? null : out;
  };
})();
function getdatastr(data) {
  if (!data) return null;
  if (data.content && data.type) return cc2str(data.content, true);
  if (data.data) return debom(data.data);
  if (data.asNodeBuffer && has_buf) return debom(data.asNodeBuffer().toString("binary"));
  if (data.asBinary) return debom(data.asBinary());
  if (data._data && data._data.getContent) return debom(cc2str(Array.prototype.slice.call(data._data.getContent(), 0)));
  return null;
}
function getdatabin(data) {
  if (!data) return null;
  if (data.data) return char_codes(data.data);
  if (data.asNodeBuffer && has_buf) return data.asNodeBuffer();
  if (data._data && data._data.getContent) {
    var o9 = data._data.getContent();
    if (typeof o9 == "string") return char_codes(o9);
    return Array.prototype.slice.call(o9);
  }
  if (data.content && data.type) return data.content;
  return null;
}
function getdata(data) {
  return data && data.name.slice(-4) === ".bin" ? getdatabin(data) : getdatastr(data);
}
function safegetzipfile(zip, file) {
  var k2 = zip.FullPaths || keys(zip.files);
  var f4 = file.toLowerCase().replace(/[\/]/g, "\\"), g3 = f4.replace(/\\/g, "/");
  for (var i7 = 0; i7 < k2.length; ++i7) {
    var n7 = k2[i7].replace(/^Root Entry[\/]/, "").toLowerCase();
    if (f4 == n7 || g3 == n7) return zip.files ? zip.files[k2[i7]] : zip.FileIndex[i7];
  }
  return null;
}
function getzipfile(zip, file) {
  var o9 = safegetzipfile(zip, file);
  if (o9 == null) throw new Error("Cannot find file " + file + " in zip");
  return o9;
}
function getzipdata(zip, file, safe) {
  if (!safe) return getdata(getzipfile(zip, file));
  if (!file) return null;
  try {
    return getzipdata(zip, file);
  } catch (e9) {
    return null;
  }
}
function getzipstr(zip, file, safe) {
  if (!safe) return getdatastr(getzipfile(zip, file));
  if (!file) return null;
  try {
    return getzipstr(zip, file);
  } catch (e9) {
    return null;
  }
}
function getzipbin(zip, file, safe) {
  if (!safe) return getdatabin(getzipfile(zip, file));
  if (!file) return null;
  try {
    return getzipbin(zip, file);
  } catch (e9) {
    return null;
  }
}
function zipentries(zip) {
  var k2 = zip.FullPaths || keys(zip.files), o9 = [];
  for (var i7 = 0; i7 < k2.length; ++i7) if (k2[i7].slice(-1) != "/") o9.push(k2[i7].replace(/^Root Entry[\/]/, ""));
  return o9.sort();
}
function zip_add_file(zip, path6, content) {
  if (zip.FullPaths) {
    if (Array.isArray(content) && typeof content[0] == "string") {
      content = content.join("");
    }
    if (typeof content == "string") {
      var res;
      if (has_buf) res = Buffer_from(content);
      else res = utf8decode(content);
      return CFB.utils.cfb_add(zip, path6, res);
    }
    CFB.utils.cfb_add(zip, path6, content);
  } else zip.file(path6, content);
}
function zip_read(d4, o9) {
  switch (o9.type) {
    case "base64":
      return CFB.read(d4, { type: "base64" });
    case "binary":
      return CFB.read(d4, { type: "binary" });
    case "buffer":
    case "array":
      return CFB.read(d4, { type: "buffer" });
  }
  throw new Error("Unrecognized type " + o9.type);
}
function resolve_path(path6, base) {
  if (path6.charAt(0) == "/") return path6.slice(1);
  var result = base.split("/");
  if (base.slice(-1) != "/") result.pop();
  var target = path6.split("/");
  while (target.length !== 0) {
    var step = target.shift();
    if (step === "..") result.pop();
    else if (step !== ".") result.push(step);
  }
  return result.join("/");
}
var XML_HEADER = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n';
var attregexg = /\s([^"\s?>\/]+)\s*=\s*((?:")([^"]*)(?:")|(?:')([^']*)(?:')|([^'">\s]+))/g;
var tagregex1 = /<[\/\?]?[a-zA-Z0-9:_-]+(?:\s+[^"\s?<>\/]+\s*=\s*(?:"[^"]*"|'[^']*'|[^'"<>\s=]+))*\s*[\/\?]?>/mg;
var tagregex2 = /<[^<>]*>/g;
var tagregex = /* @__PURE__ */ XML_HEADER.match(tagregex1) ? tagregex1 : tagregex2;
var nsregex = /<\w*:/;
var nsregex2 = /<(\/?)\w+:/;
function parsexmltag(tag, skip_root, skip_LC) {
  var z3 = {};
  var eq = 0, c6 = 0;
  for (; eq !== tag.length; ++eq) if ((c6 = tag.charCodeAt(eq)) === 32 || c6 === 10 || c6 === 13) break;
  if (!skip_root) z3[0] = tag.slice(0, eq);
  if (eq === tag.length) return z3;
  var m4 = tag.match(attregexg), j3 = 0, v4 = "", i7 = 0, q2 = "", cc = "", quot = 1;
  if (m4) for (i7 = 0; i7 != m4.length; ++i7) {
    cc = m4[i7].slice(1);
    for (c6 = 0; c6 != cc.length; ++c6) if (cc.charCodeAt(c6) === 61) break;
    q2 = cc.slice(0, c6).trim();
    while (cc.charCodeAt(c6 + 1) == 32) ++c6;
    quot = (eq = cc.charCodeAt(c6 + 1)) == 34 || eq == 39 ? 1 : 0;
    v4 = cc.slice(c6 + 1 + quot, cc.length - quot);
    for (j3 = 0; j3 != q2.length; ++j3) if (q2.charCodeAt(j3) === 58) break;
    if (j3 === q2.length) {
      if (q2.indexOf("_") > 0) q2 = q2.slice(0, q2.indexOf("_"));
      z3[q2] = v4;
      if (!skip_LC) z3[q2.toLowerCase()] = v4;
    } else {
      var k2 = (j3 === 5 && q2.slice(0, 5) === "xmlns" ? "xmlns" : "") + q2.slice(j3 + 1);
      if (z3[k2] && q2.slice(j3 - 3, j3) == "ext") continue;
      z3[k2] = v4;
      if (!skip_LC) z3[k2.toLowerCase()] = v4;
    }
  }
  return z3;
}
function parsexmltagraw(tag, skip_root, skip_LC) {
  var z3 = {};
  var eq = 0, c6 = 0;
  for (; eq !== tag.length; ++eq) if ((c6 = tag.charCodeAt(eq)) === 32 || c6 === 10 || c6 === 13) break;
  if (!skip_root) z3[0] = tag.slice(0, eq);
  if (eq === tag.length) return z3;
  var m4 = tag.match(attregexg), j3 = 0, v4 = "", i7 = 0, q2 = "", cc = "", quot = 1;
  if (m4) for (i7 = 0; i7 != m4.length; ++i7) {
    cc = m4[i7].slice(1);
    for (c6 = 0; c6 != cc.length; ++c6) if (cc.charCodeAt(c6) === 61) break;
    q2 = cc.slice(0, c6).trim();
    while (cc.charCodeAt(c6 + 1) == 32) ++c6;
    quot = (eq = cc.charCodeAt(c6 + 1)) == 34 || eq == 39 ? 1 : 0;
    v4 = cc.slice(c6 + 1 + quot, cc.length - quot);
    if (q2.indexOf("_") > 0) q2 = q2.slice(0, q2.indexOf("_"));
    z3[q2] = v4;
    if (!skip_LC) z3[q2.toLowerCase()] = v4;
  }
  return z3;
}
function strip_ns(x2) {
  return x2.replace(nsregex2, "<$1");
}
var encodings = {
  "&quot;": '"',
  "&apos;": "'",
  "&gt;": ">",
  "&lt;": "<",
  "&amp;": "&"
};
var rencoding = /* @__PURE__ */ evert(encodings);
var unescapexml = /* @__PURE__ */ (function() {
  var encregex = /&(?:quot|apos|gt|lt|amp|#x?([\da-fA-F]+));/ig, coderegex = /_x([\da-fA-F]{4})_/ig;
  function raw_unescapexml(text3) {
    var s6 = text3 + "", i7 = s6.indexOf("<![CDATA[");
    if (i7 == -1) return s6.replace(encregex, function($$, $1) {
      return encodings[$$] || String.fromCharCode(parseInt($1, $$.indexOf("x") > -1 ? 16 : 10)) || $$;
    }).replace(coderegex, function(m4, c6) {
      return String.fromCharCode(parseInt(c6, 16));
    });
    var j3 = s6.indexOf("]]>");
    return raw_unescapexml(s6.slice(0, i7)) + s6.slice(i7 + 9, j3) + raw_unescapexml(s6.slice(j3 + 3));
  }
  return function unescapexml2(text3, xlsx) {
    var out = raw_unescapexml(text3);
    return xlsx ? out.replace(/\r\n/g, "\n") : out;
  };
})();
var decregex = /[&<>'"]/g;
var htmlcharegex = /[\u0000-\u001f]/g;
function escapehtml(text3) {
  var s6 = text3 + "";
  return s6.replace(decregex, function(y4) {
    return rencoding[y4];
  }).replace(/\n/g, "<br/>").replace(htmlcharegex, function(s7) {
    return "&#x" + ("000" + s7.charCodeAt(0).toString(16)).slice(-4) + ";";
  });
}
var xlml_fixstr = /* @__PURE__ */ (function() {
  var entregex = /&#(\d+);/g;
  function entrepl($$, $1) {
    return String.fromCharCode(parseInt($1, 10));
  }
  return function xlml_fixstr2(str2) {
    return str2.replace(entregex, entrepl);
  };
})();
function parsexmlbool(value) {
  switch (value) {
    case 1:
    case true:
    case "1":
    case "true":
      return true;
    case 0:
    case false:
    case "0":
    case "false":
      return false;
  }
  return false;
}
function utf8reada(orig) {
  var out = "", i7 = 0, c6 = 0, d4 = 0, e9 = 0, f4 = 0, w3 = 0;
  while (i7 < orig.length) {
    c6 = orig.charCodeAt(i7++);
    if (c6 < 128) {
      out += String.fromCharCode(c6);
      continue;
    }
    d4 = orig.charCodeAt(i7++);
    if (c6 > 191 && c6 < 224) {
      f4 = (c6 & 31) << 6;
      f4 |= d4 & 63;
      out += String.fromCharCode(f4);
      continue;
    }
    e9 = orig.charCodeAt(i7++);
    if (c6 < 240) {
      out += String.fromCharCode((c6 & 15) << 12 | (d4 & 63) << 6 | e9 & 63);
      continue;
    }
    f4 = orig.charCodeAt(i7++);
    w3 = ((c6 & 7) << 18 | (d4 & 63) << 12 | (e9 & 63) << 6 | f4 & 63) - 65536;
    out += String.fromCharCode(55296 + (w3 >>> 10 & 1023));
    out += String.fromCharCode(56320 + (w3 & 1023));
  }
  return out;
}
function utf8readb(data) {
  var out = new_raw_buf(2 * data.length), w3, i7, j3 = 1, k2 = 0, ww = 0, c6;
  for (i7 = 0; i7 < data.length; i7 += j3) {
    j3 = 1;
    if ((c6 = data.charCodeAt(i7)) < 128) w3 = c6;
    else if (c6 < 224) {
      w3 = (c6 & 31) * 64 + (data.charCodeAt(i7 + 1) & 63);
      j3 = 2;
    } else if (c6 < 240) {
      w3 = (c6 & 15) * 4096 + (data.charCodeAt(i7 + 1) & 63) * 64 + (data.charCodeAt(i7 + 2) & 63);
      j3 = 3;
    } else {
      j3 = 4;
      w3 = (c6 & 7) * 262144 + (data.charCodeAt(i7 + 1) & 63) * 4096 + (data.charCodeAt(i7 + 2) & 63) * 64 + (data.charCodeAt(i7 + 3) & 63);
      w3 -= 65536;
      ww = 55296 + (w3 >>> 10 & 1023);
      w3 = 56320 + (w3 & 1023);
    }
    if (ww !== 0) {
      out[k2++] = ww & 255;
      out[k2++] = ww >>> 8;
      ww = 0;
    }
    out[k2++] = w3 % 256;
    out[k2++] = w3 >>> 8;
  }
  return out.slice(0, k2).toString("ucs2");
}
function utf8readc(data) {
  return Buffer_from(data, "binary").toString("utf8");
}
var utf8corpus = "foo bar baz\xE2\x98\x83\xF0\x9F\x8D\xA3";
var utf8read = has_buf && (/* @__PURE__ */ utf8readc(utf8corpus) == /* @__PURE__ */ utf8reada(utf8corpus) && utf8readc || /* @__PURE__ */ utf8readb(utf8corpus) == /* @__PURE__ */ utf8reada(utf8corpus) && utf8readb) || utf8reada;
var utf8write = has_buf ? function(data) {
  return Buffer_from(data, "utf8").toString("binary");
} : function(orig) {
  var out = [], i7 = 0, c6 = 0, d4 = 0;
  while (i7 < orig.length) {
    c6 = orig.charCodeAt(i7++);
    switch (true) {
      case c6 < 128:
        out.push(String.fromCharCode(c6));
        break;
      case c6 < 2048:
        out.push(String.fromCharCode(192 + (c6 >> 6)));
        out.push(String.fromCharCode(128 + (c6 & 63)));
        break;
      case (c6 >= 55296 && c6 < 57344):
        c6 -= 55296;
        d4 = orig.charCodeAt(i7++) - 56320 + (c6 << 10);
        out.push(String.fromCharCode(240 + (d4 >> 18 & 7)));
        out.push(String.fromCharCode(144 + (d4 >> 12 & 63)));
        out.push(String.fromCharCode(128 + (d4 >> 6 & 63)));
        out.push(String.fromCharCode(128 + (d4 & 63)));
        break;
      default:
        out.push(String.fromCharCode(224 + (c6 >> 12)));
        out.push(String.fromCharCode(128 + (c6 >> 6 & 63)));
        out.push(String.fromCharCode(128 + (c6 & 63)));
    }
  }
  return out.join("");
};
var htmldecode = /* @__PURE__ */ (function() {
  var entities = [
    ["nbsp", " "],
    ["middot", "\xB7"],
    ["quot", '"'],
    ["apos", "'"],
    ["gt", ">"],
    ["lt", "<"],
    ["amp", "&"]
  ].map(function(x2) {
    return [new RegExp("&" + x2[0] + ";", "ig"), x2[1]];
  });
  return function htmldecode2(str2) {
    var o9 = str2.replace(/^[\t\n\r ]+/, "").replace(/(^|[^\t\n\r ])[\t\n\r ]+$/, "$1").replace(/>\s+/g, ">").replace(/\b\s+</g, "<").replace(/[\t\n\r ]+/g, " ").replace(/<\s*[bB][rR]\s*\/?>/g, "\n").replace(/<[^<>]*>/g, "");
    for (var i7 = 0; i7 < entities.length; ++i7) o9 = o9.replace(entities[i7][0], entities[i7][1]);
    return o9;
  };
})();
var vtvregex = /<\/?(?:vt:)?variant>/g;
var vtmregex = /<(?:vt:)([^<"'>]*)>([\s\S]*)</;
function parseVector(data, opts) {
  var h7 = parsexmltag(data);
  var matches = str_match_xml_ns_g(data, h7.baseType) || [];
  var res = [];
  if (matches.length != h7.size) {
    if (opts.WTF) throw new Error("unexpected vector length " + matches.length + " != " + h7.size);
    return res;
  }
  matches.forEach(function(x2) {
    var v4 = x2.replace(vtvregex, "").match(vtmregex);
    if (v4) res.push({ v: utf8read(v4[2]), t: v4[1] });
  });
  return res;
}
var wtregex = /(^\s|\s$|\n)/;
function wxt_helper(h7) {
  return keys(h7).map(function(k2) {
    return " " + k2 + '="' + h7[k2] + '"';
  }).join("");
}
function writextag(f4, g3, h7) {
  return "<" + f4 + (h7 != null ? wxt_helper(h7) : "") + (g3 != null ? (g3.match(wtregex) ? ' xml:space="preserve"' : "") + ">" + g3 + "</" + f4 : "/") + ">";
}
function xlml_normalize(d4) {
  if (has_buf && /*::typeof Buffer !== "undefined" && d != null && d instanceof Buffer &&*/
  Buffer.isBuffer(d4)) return d4.toString("utf8");
  if (typeof d4 === "string") return d4;
  if (typeof Uint8Array !== "undefined" && d4 instanceof Uint8Array) return utf8read(a2s(ab2a(d4)));
  throw new Error("Bad input format: expected Buffer or string");
}
var xlmlregex = /<([\/]?)([^\s?><!\/:"]*:|)([^\s?<>:\/"]+)(?:\s+[^<>=?"'\s]+="[^"]*?")*\s*[\/]?>/mg;
var XMLNS = {
  CORE_PROPS: "http://schemas.openxmlformats.org/package/2006/metadata/core-properties",
  CUST_PROPS: "http://schemas.openxmlformats.org/officeDocument/2006/custom-properties",
  EXT_PROPS: "http://schemas.openxmlformats.org/officeDocument/2006/extended-properties",
  CT: "http://schemas.openxmlformats.org/package/2006/content-types",
  RELS: "http://schemas.openxmlformats.org/package/2006/relationships",
  TCMNT: "http://schemas.microsoft.com/office/spreadsheetml/2018/threadedcomments",
  "dc": "http://purl.org/dc/elements/1.1/",
  "dcterms": "http://purl.org/dc/terms/",
  "dcmitype": "http://purl.org/dc/dcmitype/",
  "mx": "http://schemas.microsoft.com/office/mac/excel/2008/main",
  "r": "http://schemas.openxmlformats.org/officeDocument/2006/relationships",
  "sjs": "http://schemas.openxmlformats.org/package/2006/sheetjs/core-properties",
  "vt": "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes",
  "xsi": "http://www.w3.org/2001/XMLSchema-instance",
  "xsd": "http://www.w3.org/2001/XMLSchema"
};
var XMLNS_main = [
  "http://schemas.openxmlformats.org/spreadsheetml/2006/main",
  "http://purl.oclc.org/ooxml/spreadsheetml/main",
  "http://schemas.microsoft.com/office/excel/2006/main",
  "http://schemas.microsoft.com/office/excel/2006/2"
];
function read_double_le(b4, idx) {
  var s6 = 1 - 2 * (b4[idx + 7] >>> 7);
  var e9 = ((b4[idx + 7] & 127) << 4) + (b4[idx + 6] >>> 4 & 15);
  var m4 = b4[idx + 6] & 15;
  for (var i7 = 5; i7 >= 0; --i7) m4 = m4 * 256 + b4[idx + i7];
  if (e9 == 2047) return m4 == 0 ? s6 * Infinity : NaN;
  if (e9 == 0) e9 = -1022;
  else {
    e9 -= 1023;
    m4 += Math.pow(2, 52);
  }
  return s6 * Math.pow(2, e9 - 52) * m4;
}
function write_double_le(b4, v4, idx) {
  var bs = (v4 < 0 || 1 / v4 == -Infinity ? 1 : 0) << 7, e9 = 0, m4 = 0;
  var av = bs ? -v4 : v4;
  if (!isFinite(av)) {
    e9 = 2047;
    m4 = isNaN(v4) ? 26985 : 0;
  } else if (av == 0) e9 = m4 = 0;
  else {
    e9 = Math.floor(Math.log(av) / Math.LN2);
    m4 = av * Math.pow(2, 52 - e9);
    if (e9 <= -1023 && (!isFinite(m4) || m4 < Math.pow(2, 52))) {
      e9 = -1022;
    } else {
      m4 -= Math.pow(2, 52);
      e9 += 1023;
    }
  }
  for (var i7 = 0; i7 <= 5; ++i7, m4 /= 256) b4[idx + i7] = m4 & 255;
  b4[idx + 6] = (e9 & 15) << 4 | m4 & 15;
  b4[idx + 7] = e9 >> 4 | bs;
}
var ___toBuffer = function(bufs) {
  var x2 = [], w3 = 10240;
  for (var i7 = 0; i7 < bufs[0].length; ++i7) if (bufs[0][i7]) for (var j3 = 0, L3 = bufs[0][i7].length; j3 < L3; j3 += w3) x2.push.apply(x2, bufs[0][i7].slice(j3, j3 + w3));
  return x2;
};
var __toBuffer = has_buf ? function(bufs) {
  return bufs[0].length > 0 && Buffer.isBuffer(bufs[0][0]) ? Buffer.concat(bufs[0].map(function(x2) {
    return Buffer.isBuffer(x2) ? x2 : Buffer_from(x2);
  })) : ___toBuffer(bufs);
} : ___toBuffer;
var ___utf16le = function(b4, s6, e9) {
  var ss = [];
  for (var i7 = s6; i7 < e9; i7 += 2) ss.push(String.fromCharCode(__readUInt16LE(b4, i7)));
  return ss.join("").replace(chr0, "");
};
var __utf16le = has_buf ? function(b4, s6, e9) {
  if (!Buffer.isBuffer(b4) || !buf_utf16le) return ___utf16le(b4, s6, e9);
  return b4.toString("utf16le", s6, e9).replace(chr0, "");
} : ___utf16le;
var ___hexlify = function(b4, s6, l5) {
  var ss = [];
  for (var i7 = s6; i7 < s6 + l5; ++i7) ss.push(("0" + b4[i7].toString(16)).slice(-2));
  return ss.join("");
};
var __hexlify = has_buf ? function(b4, s6, l5) {
  return Buffer.isBuffer(b4) ? b4.toString("hex", s6, s6 + l5) : ___hexlify(b4, s6, l5);
} : ___hexlify;
var ___utf8 = function(b4, s6, e9) {
  var ss = [];
  for (var i7 = s6; i7 < e9; i7++) ss.push(String.fromCharCode(__readUInt8(b4, i7)));
  return ss.join("");
};
var __utf8 = has_buf ? function utf8_b(b4, s6, e9) {
  return Buffer.isBuffer(b4) ? b4.toString("utf8", s6, e9) : ___utf8(b4, s6, e9);
} : ___utf8;
var ___lpstr = function(b4, i7) {
  var len = __readUInt32LE(b4, i7);
  return len > 0 ? __utf8(b4, i7 + 4, i7 + 4 + len - 1) : "";
};
var __lpstr = ___lpstr;
var ___cpstr = function(b4, i7) {
  var len = __readUInt32LE(b4, i7);
  return len > 0 ? __utf8(b4, i7 + 4, i7 + 4 + len - 1) : "";
};
var __cpstr = ___cpstr;
var ___lpwstr = function(b4, i7) {
  var len = 2 * __readUInt32LE(b4, i7);
  return len > 0 ? __utf8(b4, i7 + 4, i7 + 4 + len - 1) : "";
};
var __lpwstr = ___lpwstr;
var ___lpp4 = function lpp4_(b4, i7) {
  var len = __readUInt32LE(b4, i7);
  return len > 0 ? __utf16le(b4, i7 + 4, i7 + 4 + len) : "";
};
var __lpp4 = ___lpp4;
var ___8lpp4 = function(b4, i7) {
  var len = __readUInt32LE(b4, i7);
  return len > 0 ? __utf8(b4, i7 + 4, i7 + 4 + len) : "";
};
var __8lpp4 = ___8lpp4;
var ___double = function(b4, idx) {
  return read_double_le(b4, idx);
};
var __double = ___double;
var is_buf = function is_buf_a(a3) {
  return Array.isArray(a3) || typeof Uint8Array !== "undefined" && a3 instanceof Uint8Array;
};
if (has_buf) {
  __lpstr = function lpstr_b(b4, i7) {
    if (!Buffer.isBuffer(b4)) return ___lpstr(b4, i7);
    var len = b4.readUInt32LE(i7);
    return len > 0 ? b4.toString("utf8", i7 + 4, i7 + 4 + len - 1) : "";
  };
  __cpstr = function cpstr_b(b4, i7) {
    if (!Buffer.isBuffer(b4)) return ___cpstr(b4, i7);
    var len = b4.readUInt32LE(i7);
    return len > 0 ? b4.toString("utf8", i7 + 4, i7 + 4 + len - 1) : "";
  };
  __lpwstr = function lpwstr_b(b4, i7) {
    if (!Buffer.isBuffer(b4) || !buf_utf16le) return ___lpwstr(b4, i7);
    var len = 2 * b4.readUInt32LE(i7);
    return b4.toString("utf16le", i7 + 4, i7 + 4 + len - 1);
  };
  __lpp4 = function lpp4_b(b4, i7) {
    if (!Buffer.isBuffer(b4) || !buf_utf16le) return ___lpp4(b4, i7);
    var len = b4.readUInt32LE(i7);
    return b4.toString("utf16le", i7 + 4, i7 + 4 + len);
  };
  __8lpp4 = function lpp4_8b(b4, i7) {
    if (!Buffer.isBuffer(b4)) return ___8lpp4(b4, i7);
    var len = b4.readUInt32LE(i7);
    return b4.toString("utf8", i7 + 4, i7 + 4 + len);
  };
  __double = function double_(b4, i7) {
    if (Buffer.isBuffer(b4)) return b4.readDoubleLE(i7);
    return ___double(b4, i7);
  };
  is_buf = function is_buf_b(a3) {
    return Buffer.isBuffer(a3) || Array.isArray(a3) || typeof Uint8Array !== "undefined" && a3 instanceof Uint8Array;
  };
}
function cpdoit() {
  __utf16le = function(b4, s6, e9) {
    return $cptable.utils.decode(1200, b4.slice(s6, e9)).replace(chr0, "");
  };
  __utf8 = function(b4, s6, e9) {
    return $cptable.utils.decode(65001, b4.slice(s6, e9));
  };
  __lpstr = function(b4, i7) {
    var len = __readUInt32LE(b4, i7);
    return len > 0 ? $cptable.utils.decode(current_ansi, b4.slice(i7 + 4, i7 + 4 + len - 1)) : "";
  };
  __cpstr = function(b4, i7) {
    var len = __readUInt32LE(b4, i7);
    return len > 0 ? $cptable.utils.decode(current_codepage, b4.slice(i7 + 4, i7 + 4 + len - 1)) : "";
  };
  __lpwstr = function(b4, i7) {
    var len = 2 * __readUInt32LE(b4, i7);
    return len > 0 ? $cptable.utils.decode(1200, b4.slice(i7 + 4, i7 + 4 + len - 1)) : "";
  };
  __lpp4 = function(b4, i7) {
    var len = __readUInt32LE(b4, i7);
    return len > 0 ? $cptable.utils.decode(1200, b4.slice(i7 + 4, i7 + 4 + len)) : "";
  };
  __8lpp4 = function(b4, i7) {
    var len = __readUInt32LE(b4, i7);
    return len > 0 ? $cptable.utils.decode(65001, b4.slice(i7 + 4, i7 + 4 + len)) : "";
  };
}
if (typeof $cptable !== "undefined") cpdoit();
var __readUInt8 = function(b4, idx) {
  return b4[idx];
};
var __readUInt16LE = function(b4, idx) {
  return b4[idx + 1] * (1 << 8) + b4[idx];
};
var __readInt16LE = function(b4, idx) {
  var u5 = b4[idx + 1] * (1 << 8) + b4[idx];
  return u5 < 32768 ? u5 : (65535 - u5 + 1) * -1;
};
var __readUInt32LE = function(b4, idx) {
  return b4[idx + 3] * (1 << 24) + (b4[idx + 2] << 16) + (b4[idx + 1] << 8) + b4[idx];
};
var __readInt32LE = function(b4, idx) {
  return b4[idx + 3] << 24 | b4[idx + 2] << 16 | b4[idx + 1] << 8 | b4[idx];
};
var __readInt32BE = function(b4, idx) {
  return b4[idx] << 24 | b4[idx + 1] << 16 | b4[idx + 2] << 8 | b4[idx + 3];
};
function ReadShift(size, t6) {
  var o9 = "", oI, oR, oo = [], w3, vv, i7, loc;
  switch (t6) {
    case "dbcs":
      loc = this.l;
      if (has_buf && Buffer.isBuffer(this) && buf_utf16le) o9 = this.slice(this.l, this.l + 2 * size).toString("utf16le");
      else for (i7 = 0; i7 < size; ++i7) {
        o9 += String.fromCharCode(__readUInt16LE(this, loc));
        loc += 2;
      }
      size *= 2;
      break;
    case "utf8":
      o9 = __utf8(this, this.l, this.l + size);
      break;
    case "utf16le":
      size *= 2;
      o9 = __utf16le(this, this.l, this.l + size);
      break;
    case "wstr":
      if (typeof $cptable !== "undefined") o9 = $cptable.utils.decode(current_codepage, this.slice(this.l, this.l + 2 * size));
      else return ReadShift.call(this, size, "dbcs");
      size = 2 * size;
      break;
    /* [MS-OLEDS] 2.1.4 LengthPrefixedAnsiString */
    case "lpstr-ansi":
      o9 = __lpstr(this, this.l);
      size = 4 + __readUInt32LE(this, this.l);
      break;
    case "lpstr-cp":
      o9 = __cpstr(this, this.l);
      size = 4 + __readUInt32LE(this, this.l);
      break;
    /* [MS-OLEDS] 2.1.5 LengthPrefixedUnicodeString */
    case "lpwstr":
      o9 = __lpwstr(this, this.l);
      size = 4 + 2 * __readUInt32LE(this, this.l);
      break;
    /* [MS-OFFCRYPTO] 2.1.2 Length-Prefixed Padded Unicode String (UNICODE-LP-P4) */
    case "lpp4":
      size = 4 + __readUInt32LE(this, this.l);
      o9 = __lpp4(this, this.l);
      if (size & 2) size += 2;
      break;
    /* [MS-OFFCRYPTO] 2.1.3 Length-Prefixed UTF-8 String (UTF-8-LP-P4) */
    case "8lpp4":
      size = 4 + __readUInt32LE(this, this.l);
      o9 = __8lpp4(this, this.l);
      if (size & 3) size += 4 - (size & 3);
      break;
    case "cstr":
      size = 0;
      o9 = "";
      while ((w3 = __readUInt8(this, this.l + size++)) !== 0) oo.push(_getchar(w3));
      o9 = oo.join("");
      break;
    case "_wstr":
      size = 0;
      o9 = "";
      while ((w3 = __readUInt16LE(this, this.l + size)) !== 0) {
        oo.push(_getchar(w3));
        size += 2;
      }
      size += 2;
      o9 = oo.join("");
      break;
    /* sbcs and dbcs support continue records in the SST way TODO codepages */
    case "dbcs-cont":
      o9 = "";
      loc = this.l;
      for (i7 = 0; i7 < size; ++i7) {
        if (this.lens && this.lens.indexOf(loc) !== -1) {
          w3 = __readUInt8(this, loc);
          this.l = loc + 1;
          vv = ReadShift.call(this, size - i7, w3 ? "dbcs-cont" : "sbcs-cont");
          return oo.join("") + vv;
        }
        oo.push(_getchar(__readUInt16LE(this, loc)));
        loc += 2;
      }
      o9 = oo.join("");
      size *= 2;
      break;
    case "cpstr":
      if (typeof $cptable !== "undefined") {
        o9 = $cptable.utils.decode(current_codepage, this.slice(this.l, this.l + size));
        break;
      }
    /* falls through */
    case "sbcs-cont":
      o9 = "";
      loc = this.l;
      for (i7 = 0; i7 != size; ++i7) {
        if (this.lens && this.lens.indexOf(loc) !== -1) {
          w3 = __readUInt8(this, loc);
          this.l = loc + 1;
          vv = ReadShift.call(this, size - i7, w3 ? "dbcs-cont" : "sbcs-cont");
          return oo.join("") + vv;
        }
        oo.push(_getchar(__readUInt8(this, loc)));
        loc += 1;
      }
      o9 = oo.join("");
      break;
    default:
      switch (size) {
        case 1:
          oI = __readUInt8(this, this.l);
          this.l++;
          return oI;
        case 2:
          oI = (t6 === "i" ? __readInt16LE : __readUInt16LE)(this, this.l);
          this.l += 2;
          return oI;
        case 4:
        case -4:
          if (t6 === "i" || (this[this.l + 3] & 128) === 0) {
            oI = (size > 0 ? __readInt32LE : __readInt32BE)(this, this.l);
            this.l += 4;
            return oI;
          } else {
            oR = __readUInt32LE(this, this.l);
            this.l += 4;
          }
          return oR;
        case 8:
        case -8:
          if (t6 === "f") {
            if (size == 8) oR = __double(this, this.l);
            else oR = __double([this[this.l + 7], this[this.l + 6], this[this.l + 5], this[this.l + 4], this[this.l + 3], this[this.l + 2], this[this.l + 1], this[this.l + 0]], 0);
            this.l += 8;
            return oR;
          } else size = 8;
        /* falls through */
        case 16:
          o9 = __hexlify(this, this.l, size);
          break;
      }
  }
  this.l += size;
  return o9;
}
var __writeUInt32LE = function(b4, val2, idx) {
  b4[idx] = val2 & 255;
  b4[idx + 1] = val2 >>> 8 & 255;
  b4[idx + 2] = val2 >>> 16 & 255;
  b4[idx + 3] = val2 >>> 24 & 255;
};
var __writeInt32LE = function(b4, val2, idx) {
  b4[idx] = val2 & 255;
  b4[idx + 1] = val2 >> 8 & 255;
  b4[idx + 2] = val2 >> 16 & 255;
  b4[idx + 3] = val2 >> 24 & 255;
};
var __writeUInt16LE = function(b4, val2, idx) {
  b4[idx] = val2 & 255;
  b4[idx + 1] = val2 >>> 8 & 255;
};
function WriteShift(t6, val2, f4) {
  var size = 0, i7 = 0;
  if (f4 === "dbcs") {
    for (i7 = 0; i7 != val2.length; ++i7) __writeUInt16LE(this, val2.charCodeAt(i7), this.l + 2 * i7);
    size = 2 * val2.length;
  } else if (f4 === "sbcs" || f4 == "cpstr") {
    if (typeof $cptable !== "undefined" && current_ansi == 874) {
      for (i7 = 0; i7 != val2.length; ++i7) {
        var cpp = $cptable.utils.encode(current_ansi, val2.charAt(i7));
        this[this.l + i7] = cpp[0];
      }
      size = val2.length;
    } else if (typeof $cptable !== "undefined" && f4 == "cpstr") {
      cpp = $cptable.utils.encode(current_codepage, val2);
      if (cpp.length == val2.length) {
        for (i7 = 0; i7 < val2.length; ++i7) if (cpp[i7] == 0 && val2.charCodeAt(i7) != 0) cpp[i7] = 95;
      }
      if (cpp.length == 2 * val2.length) {
        for (i7 = 0; i7 < val2.length; ++i7) if (cpp[2 * i7] == 0 && cpp[2 * i7 + 1] == 0 && val2.charCodeAt(i7) != 0) cpp[2 * i7] = 95;
      }
      for (i7 = 0; i7 < cpp.length; ++i7) this[this.l + i7] = cpp[i7];
      size = cpp.length;
    } else {
      val2 = val2.replace(/[^\x00-\x7F]/g, "_");
      for (i7 = 0; i7 != val2.length; ++i7) this[this.l + i7] = val2.charCodeAt(i7) & 255;
      size = val2.length;
    }
  } else if (f4 === "hex") {
    for (; i7 < t6; ++i7) {
      this[this.l++] = parseInt(val2.slice(2 * i7, 2 * i7 + 2), 16) || 0;
    }
    return this;
  } else if (f4 === "utf16le") {
    var end = Math.min(this.l + t6, this.length);
    for (i7 = 0; i7 < Math.min(val2.length, t6); ++i7) {
      var cc = val2.charCodeAt(i7);
      this[this.l++] = cc & 255;
      this[this.l++] = cc >> 8;
    }
    while (this.l < end) this[this.l++] = 0;
    return this;
  } else switch (t6) {
    case 1:
      size = 1;
      this[this.l] = val2 & 255;
      break;
    case 2:
      size = 2;
      this[this.l] = val2 & 255;
      val2 >>>= 8;
      this[this.l + 1] = val2 & 255;
      break;
    case 3:
      size = 3;
      this[this.l] = val2 & 255;
      val2 >>>= 8;
      this[this.l + 1] = val2 & 255;
      val2 >>>= 8;
      this[this.l + 2] = val2 & 255;
      break;
    case 4:
      size = 4;
      __writeUInt32LE(this, val2, this.l);
      break;
    case 8:
      size = 8;
      if (f4 === "f") {
        write_double_le(this, val2, this.l);
        break;
      }
    /* falls through */
    case 16:
      break;
    case -4:
      size = 4;
      __writeInt32LE(this, val2, this.l);
      break;
  }
  this.l += size;
  return this;
}
function CheckField(hexstr, fld) {
  var m4 = __hexlify(this, this.l, hexstr.length >> 1);
  if (m4 !== hexstr) throw new Error(fld + "Expected " + hexstr + " saw " + m4);
  this.l += hexstr.length >> 1;
}
function prep_blob(blob, pos) {
  blob.l = pos;
  blob.read_shift = /*::(*/
  ReadShift;
  blob.chk = CheckField;
  blob.write_shift = WriteShift;
}
function parsenoop(blob, length) {
  blob.l += length;
}
function new_buf(sz) {
  var o9 = new_raw_buf(sz);
  prep_blob(o9, 0);
  return o9;
}
function recordhopper(data, cb, opts) {
  if (!data) return;
  var tmpbyte, cntbyte, length;
  prep_blob(data, data.l || 0);
  var L3 = data.length, RT = 0, tgt = 0;
  while (data.l < L3) {
    RT = data.read_shift(1);
    if (RT & 128) RT = (RT & 127) + ((data.read_shift(1) & 127) << 7);
    var R3 = XLSBRecordEnum[RT] || XLSBRecordEnum[65535];
    tmpbyte = data.read_shift(1);
    length = tmpbyte & 127;
    for (cntbyte = 1; cntbyte < 4 && tmpbyte & 128; ++cntbyte) length += ((tmpbyte = data.read_shift(1)) & 127) << 7 * cntbyte;
    tgt = data.l + length;
    var d4 = R3.f && R3.f(data, length, opts);
    data.l = tgt;
    if (cb(d4, R3, RT)) return;
  }
}
function buf_array() {
  var bufs = [], blksz = has_buf ? 16384 : 2048;
  var has_buf_copy = has_buf && typeof new_buf(blksz).copy == "function";
  var newblk = function ba_newblk(sz) {
    var o9 = new_buf(sz);
    prep_blob(o9, 0);
    return o9;
  };
  var curbuf = newblk(blksz);
  var endbuf = function ba_endbuf() {
    if (!curbuf) return;
    if (curbuf.l) {
      if (curbuf.length > curbuf.l) {
        curbuf = curbuf.slice(0, curbuf.l);
        curbuf.l = curbuf.length;
      }
      if (curbuf.length > 0) bufs.push(curbuf);
    }
    curbuf = null;
  };
  var next = function ba_next(sz) {
    if (curbuf && sz < curbuf.length - curbuf.l) return curbuf;
    endbuf();
    return curbuf = newblk(Math.max(sz + 1, blksz));
  };
  var end = function ba_end() {
    endbuf();
    return bconcat(bufs);
  };
  var end2 = function() {
    endbuf();
    return bufs;
  };
  var push = function ba_push(buf) {
    endbuf();
    curbuf = buf;
    if (curbuf.l == null) curbuf.l = curbuf.length;
    next(blksz);
  };
  return { next, push, end, _bufs: bufs, end2 };
}
function shift_cell_xls(cell, tgt, opts) {
  var out = dup(cell);
  if (tgt.s) {
    if (out.cRel) out.c += tgt.s.c;
    if (out.rRel) out.r += tgt.s.r;
  } else {
    if (out.cRel) out.c += tgt.c;
    if (out.rRel) out.r += tgt.r;
  }
  if (!opts || opts.biff < 12) {
    while (out.c >= 256) out.c -= 256;
    while (out.r >= 65536) out.r -= 65536;
  }
  return out;
}
function shift_range_xls(cell, range2, opts) {
  var out = dup(cell);
  out.s = shift_cell_xls(out.s, range2.s, opts);
  out.e = shift_cell_xls(out.e, range2.s, opts);
  return out;
}
function encode_cell_xls(c6, biff) {
  if (c6.cRel && c6.c < 0) {
    c6 = dup(c6);
    while (c6.c < 0) c6.c += biff > 8 ? 16384 : 256;
  }
  if (c6.rRel && c6.r < 0) {
    c6 = dup(c6);
    while (c6.r < 0) c6.r += biff > 8 ? 1048576 : biff > 5 ? 65536 : 16384;
  }
  var s6 = encode_cell(c6);
  if (!c6.cRel && c6.cRel != null) s6 = fix_col(s6);
  if (!c6.rRel && c6.rRel != null) s6 = fix_row(s6);
  return s6;
}
function encode_range_xls(r8, opts) {
  if (r8.s.r == 0 && !r8.s.rRel) {
    if (r8.e.r == (opts.biff >= 12 ? 1048575 : opts.biff >= 8 ? 65536 : 16384) && !r8.e.rRel) {
      return (r8.s.cRel ? "" : "$") + encode_col(r8.s.c) + ":" + (r8.e.cRel ? "" : "$") + encode_col(r8.e.c);
    }
  }
  if (r8.s.c == 0 && !r8.s.cRel) {
    if (r8.e.c == (opts.biff >= 12 ? 16383 : 255) && !r8.e.cRel) {
      return (r8.s.rRel ? "" : "$") + encode_row(r8.s.r) + ":" + (r8.e.rRel ? "" : "$") + encode_row(r8.e.r);
    }
  }
  return encode_cell_xls(r8.s, opts.biff) + ":" + encode_cell_xls(r8.e, opts.biff);
}
function decode_row(rowstr) {
  return parseInt(unfix_row(rowstr), 10) - 1;
}
function encode_row(row) {
  return "" + (row + 1);
}
function fix_row(cstr) {
  return cstr.replace(/([A-Z]|^)(\d+)$/, "$1$$$2");
}
function unfix_row(cstr) {
  return cstr.replace(/\$(\d+)$/, "$1");
}
function decode_col(colstr) {
  var c6 = unfix_col(colstr), d4 = 0, i7 = 0;
  for (; i7 !== c6.length; ++i7) d4 = 26 * d4 + c6.charCodeAt(i7) - 64;
  return d4 - 1;
}
function encode_col(col) {
  if (col < 0) throw new Error("invalid column " + col);
  var s6 = "";
  for (++col; col; col = Math.floor((col - 1) / 26)) s6 = String.fromCharCode((col - 1) % 26 + 65) + s6;
  return s6;
}
function fix_col(cstr) {
  return cstr.replace(/^([A-Z])/, "$$$1");
}
function unfix_col(cstr) {
  return cstr.replace(/^\$([A-Z])/, "$1");
}
function split_cell(cstr) {
  return cstr.replace(/(\$?[A-Z]*)(\$?\d*)/, "$1,$2").split(",");
}
function decode_cell(cstr) {
  var R3 = 0, C3 = 0;
  for (var i7 = 0; i7 < cstr.length; ++i7) {
    var cc = cstr.charCodeAt(i7);
    if (cc >= 48 && cc <= 57) R3 = 10 * R3 + (cc - 48);
    else if (cc >= 65 && cc <= 90) C3 = 26 * C3 + (cc - 64);
  }
  return { c: C3 - 1, r: R3 - 1 };
}
function encode_cell(cell) {
  var col = cell.c + 1;
  var s6 = "";
  for (; col; col = (col - 1) / 26 | 0) s6 = String.fromCharCode((col - 1) % 26 + 65) + s6;
  return s6 + (cell.r + 1);
}
function decode_range(range2) {
  var idx = range2.indexOf(":");
  if (idx == -1) return { s: decode_cell(range2), e: decode_cell(range2) };
  return { s: decode_cell(range2.slice(0, idx)), e: decode_cell(range2.slice(idx + 1)) };
}
function encode_range(cs, ce2) {
  if (typeof ce2 === "undefined" || typeof ce2 === "number") {
    return encode_range(cs.s, cs.e);
  }
  if (typeof cs !== "string") cs = encode_cell(cs);
  if (typeof ce2 !== "string") ce2 = encode_cell(ce2);
  return cs == ce2 ? cs : cs + ":" + ce2;
}
function formula_quote_sheet_name(sname, opts) {
  if (!sname && !(opts && opts.biff <= 5 && opts.biff >= 2)) throw new Error("empty sheet name");
  if (/[^\w\u4E00-\u9FFF\u3040-\u30FF]/.test(sname)) return "'" + sname.replace(/'/g, "''") + "'";
  return sname;
}
function safe_decode_range(range2) {
  var o9 = { s: { c: 0, r: 0 }, e: { c: 0, r: 0 } };
  var idx = 0, i7 = 0, cc = 0;
  var len = range2.length;
  for (idx = 0; i7 < len; ++i7) {
    if ((cc = range2.charCodeAt(i7) - 64) < 1 || cc > 26) break;
    idx = 26 * idx + cc;
  }
  o9.s.c = --idx;
  for (idx = 0; i7 < len; ++i7) {
    if ((cc = range2.charCodeAt(i7) - 48) < 0 || cc > 9) break;
    idx = 10 * idx + cc;
  }
  o9.s.r = --idx;
  if (i7 === len || cc != 10) {
    o9.e.c = o9.s.c;
    o9.e.r = o9.s.r;
    return o9;
  }
  ++i7;
  for (idx = 0; i7 != len; ++i7) {
    if ((cc = range2.charCodeAt(i7) - 64) < 1 || cc > 26) break;
    idx = 26 * idx + cc;
  }
  o9.e.c = --idx;
  for (idx = 0; i7 != len; ++i7) {
    if ((cc = range2.charCodeAt(i7) - 48) < 0 || cc > 9) break;
    idx = 10 * idx + cc;
  }
  o9.e.r = --idx;
  return o9;
}
function safe_format_cell(cell, v4) {
  var q2 = cell.t == "d" && v4 instanceof Date;
  if (cell.z != null) try {
    return cell.w = SSF_format(cell.z, q2 ? datenum(v4) : v4);
  } catch (e9) {
  }
  try {
    return cell.w = SSF_format((cell.XF || {}).numFmtId || (q2 ? 14 : 0), q2 ? datenum(v4) : v4);
  } catch (e9) {
    return "" + v4;
  }
}
function format_cell(cell, v4, o9) {
  if (cell == null || cell.t == null || cell.t == "z") return "";
  if (cell.w !== void 0) return cell.w;
  if (cell.t == "d" && !cell.z && o9 && o9.dateNF) cell.z = o9.dateNF;
  if (cell.t == "e") return BErr[cell.v] || cell.v;
  if (v4 == void 0) return safe_format_cell(cell, cell.v);
  return safe_format_cell(cell, v4);
}
function sheet_to_workbook(sheet, opts) {
  var n7 = opts && opts.sheet ? opts.sheet : "Sheet1";
  var sheets = {};
  sheets[n7] = sheet;
  return { SheetNames: [n7], Sheets: sheets };
}
function sheet_new(opts) {
  var out = {};
  var o9 = opts || {};
  if (o9.dense) out["!data"] = [];
  return out;
}
function sheet_add_aoa(_ws, data, opts) {
  var o9 = opts || {};
  var dense = _ws ? _ws["!data"] != null : o9.dense;
  if (DENSE != null && dense == null) dense = DENSE;
  var ws = _ws || (dense ? { "!data": [] } : {});
  if (dense && !ws["!data"]) ws["!data"] = [];
  var _R = 0, _C = 0;
  if (ws && o9.origin != null) {
    if (typeof o9.origin == "number") _R = o9.origin;
    else {
      var _origin = typeof o9.origin == "string" ? decode_cell(o9.origin) : o9.origin;
      _R = _origin.r;
      _C = _origin.c;
    }
  }
  var range2 = { s: { c: 1e7, r: 1e7 }, e: { c: 0, r: 0 } };
  if (ws["!ref"]) {
    var _range = safe_decode_range(ws["!ref"]);
    range2.s.c = _range.s.c;
    range2.s.r = _range.s.r;
    range2.e.c = Math.max(range2.e.c, _range.e.c);
    range2.e.r = Math.max(range2.e.r, _range.e.r);
    if (_R == -1) range2.e.r = _R = ws["!ref"] ? _range.e.r + 1 : 0;
  } else {
    range2.s.c = range2.e.c = range2.s.r = range2.e.r = 0;
  }
  var row = [], seen = false;
  for (var R3 = 0; R3 != data.length; ++R3) {
    if (!data[R3]) continue;
    if (!Array.isArray(data[R3])) throw new Error("aoa_to_sheet expects an array of arrays");
    var __R = _R + R3;
    if (dense) {
      if (!ws["!data"][__R]) ws["!data"][__R] = [];
      row = ws["!data"][__R];
    }
    var data_R = data[R3];
    for (var C3 = 0; C3 != data_R.length; ++C3) {
      if (typeof data_R[C3] === "undefined") continue;
      var cell = { v: data_R[C3], t: "" };
      var __C = _C + C3;
      if (range2.s.r > __R) range2.s.r = __R;
      if (range2.s.c > __C) range2.s.c = __C;
      if (range2.e.r < __R) range2.e.r = __R;
      if (range2.e.c < __C) range2.e.c = __C;
      seen = true;
      if (data_R[C3] && typeof data_R[C3] === "object" && !Array.isArray(data_R[C3]) && !(data_R[C3] instanceof Date)) cell = data_R[C3];
      else {
        if (Array.isArray(cell.v)) {
          cell.f = data_R[C3][1];
          cell.v = cell.v[0];
        }
        if (cell.v === null) {
          if (cell.f) cell.t = "n";
          else if (o9.nullError) {
            cell.t = "e";
            cell.v = 0;
          } else if (!o9.sheetStubs) continue;
          else cell.t = "z";
        } else if (typeof cell.v === "number") {
          if (isFinite(cell.v)) cell.t = "n";
          else if (isNaN(cell.v)) {
            cell.t = "e";
            cell.v = 15;
          } else {
            cell.t = "e";
            cell.v = 7;
          }
        } else if (typeof cell.v === "boolean") cell.t = "b";
        else if (cell.v instanceof Date) {
          cell.z = o9.dateNF || table_fmt[14];
          if (!o9.UTC) cell.v = local_to_utc(cell.v);
          if (o9.cellDates) {
            cell.t = "d";
            cell.w = SSF_format(cell.z, datenum(cell.v, o9.date1904));
          } else {
            cell.t = "n";
            cell.v = datenum(cell.v, o9.date1904);
            cell.w = SSF_format(cell.z, cell.v);
          }
        } else cell.t = "s";
      }
      if (dense) {
        if (row[__C] && row[__C].z) cell.z = row[__C].z;
        row[__C] = cell;
      } else {
        var cell_ref = encode_col(__C) + (__R + 1);
        if (ws[cell_ref] && ws[cell_ref].z) cell.z = ws[cell_ref].z;
        ws[cell_ref] = cell;
      }
    }
  }
  if (seen && range2.s.c < 104e5) ws["!ref"] = encode_range(range2);
  return ws;
}
function aoa_to_sheet(data, opts) {
  return sheet_add_aoa(null, data, opts);
}
function parse_Int32LE(data) {
  return data.read_shift(4, "i");
}
function parse_XLWideString(data) {
  var cchCharacters = data.read_shift(4);
  return cchCharacters === 0 ? "" : data.read_shift(cchCharacters, "dbcs");
}
function parse_StrRun(data) {
  return { ich: data.read_shift(2), ifnt: data.read_shift(2) };
}
function parse_RichStr(data, length) {
  var start = data.l;
  var flags = data.read_shift(1);
  var str2 = parse_XLWideString(data);
  var rgsStrRun = [];
  var z3 = { t: str2, h: str2 };
  if ((flags & 1) !== 0) {
    var dwSizeStrRun = data.read_shift(4);
    for (var i7 = 0; i7 != dwSizeStrRun; ++i7) rgsStrRun.push(parse_StrRun(data));
    z3.r = rgsStrRun;
  } else z3.r = [{ ich: 0, ifnt: 0 }];
  data.l = start + length;
  return z3;
}
var parse_BrtCommentText = parse_RichStr;
function parse_XLSBCell(data) {
  var col = data.read_shift(4);
  var iStyleRef = data.read_shift(2);
  iStyleRef += data.read_shift(1) << 16;
  data.l++;
  return { c: col, iStyleRef };
}
function parse_XLSBShortCell(data) {
  var iStyleRef = data.read_shift(2);
  iStyleRef += data.read_shift(1) << 16;
  data.l++;
  return { c: -1, iStyleRef };
}
var parse_XLSBCodeName = parse_XLWideString;
function parse_XLNullableWideString(data) {
  var cchCharacters = data.read_shift(4);
  return cchCharacters === 0 || cchCharacters === 4294967295 ? "" : data.read_shift(cchCharacters, "dbcs");
}
var parse_XLNameWideString = parse_XLWideString;
var parse_RelID = parse_XLNullableWideString;
function parse_RkNumber(data) {
  var b4 = data.slice(data.l, data.l + 4);
  var fX100 = b4[0] & 1, fInt = b4[0] & 2;
  data.l += 4;
  var RK = fInt === 0 ? __double([0, 0, 0, 0, b4[0] & 252, b4[1], b4[2], b4[3]], 0) : __readInt32LE(b4, 0) >> 2;
  return fX100 ? RK / 100 : RK;
}
function parse_RfX(data) {
  var cell = { s: {}, e: {} };
  cell.s.r = data.read_shift(4);
  cell.e.r = data.read_shift(4);
  cell.s.c = data.read_shift(4);
  cell.e.c = data.read_shift(4);
  return cell;
}
var parse_UncheckedRfX = parse_RfX;
function parse_Xnum(data) {
  if (data.length - data.l < 8) throw "XLS Xnum Buffer underflow";
  return data.read_shift(8, "f");
}
function parse_BrtColor(data) {
  var out = {};
  var d4 = data.read_shift(1);
  var xColorType = d4 >>> 1;
  var index = data.read_shift(1);
  var nTS = data.read_shift(2, "i");
  var bR = data.read_shift(1);
  var bG = data.read_shift(1);
  var bB = data.read_shift(1);
  data.l++;
  switch (xColorType) {
    case 0:
      out.auto = 1;
      break;
    case 1:
      out.index = index;
      var icv = XLSIcv[index];
      if (icv) out.rgb = rgb2Hex(icv);
      break;
    case 2:
      out.rgb = rgb2Hex([bR, bG, bB]);
      break;
    case 3:
      out.theme = index;
      break;
  }
  if (nTS != 0) out.tint = nTS > 0 ? nTS / 32767 : nTS / 32768;
  return out;
}
function parse_FontFlags(data) {
  var d4 = data.read_shift(1);
  data.l++;
  var out = {
    fBold: d4 & 1,
    fItalic: d4 & 2,
    fUnderline: d4 & 4,
    fStrikeout: d4 & 8,
    fOutline: d4 & 16,
    fShadow: d4 & 32,
    fCondense: d4 & 64,
    fExtend: d4 & 128
  };
  return out;
}
function parse_ClipboardFormatOrString(o9, w3) {
  var ClipFmt = { 2: "BITMAP", 3: "METAFILEPICT", 8: "DIB", 14: "ENHMETAFILE" };
  var m4 = o9.read_shift(4);
  switch (m4) {
    case 0:
      return "";
    case 4294967295:
    case 4294967294:
      return ClipFmt[o9.read_shift(4)] || "";
  }
  if (m4 > 400) throw new Error("Unsupported Clipboard: " + m4.toString(16));
  o9.l -= 4;
  return o9.read_shift(0, w3 == 1 ? "lpstr" : "lpwstr");
}
function parse_ClipboardFormatOrAnsiString(o9) {
  return parse_ClipboardFormatOrString(o9, 1);
}
function parse_ClipboardFormatOrUnicodeString(o9) {
  return parse_ClipboardFormatOrString(o9, 2);
}
var VT_I2 = 2;
var VT_I4 = 3;
var VT_BOOL = 11;
var VT_VARIANT = 12;
var VT_UI4 = 19;
var VT_FILETIME = 64;
var VT_BLOB = 65;
var VT_CF = 71;
var VT_VECTOR_VARIANT = 4108;
var VT_VECTOR_LPSTR = 4126;
var VT_STRING = 80;
var VT_USTR = 81;
var VT_CUSTOM = [VT_STRING, VT_USTR];
var DocSummaryPIDDSI = {
  1: { n: "CodePage", t: VT_I2 },
  2: { n: "Category", t: VT_STRING },
  3: { n: "PresentationFormat", t: VT_STRING },
  4: { n: "ByteCount", t: VT_I4 },
  5: { n: "LineCount", t: VT_I4 },
  6: { n: "ParagraphCount", t: VT_I4 },
  7: { n: "SlideCount", t: VT_I4 },
  8: { n: "NoteCount", t: VT_I4 },
  9: { n: "HiddenCount", t: VT_I4 },
  10: { n: "MultimediaClipCount", t: VT_I4 },
  11: { n: "ScaleCrop", t: VT_BOOL },
  12: {
    n: "HeadingPairs",
    t: VT_VECTOR_VARIANT
    /* VT_VECTOR | VT_VARIANT */
  },
  13: {
    n: "TitlesOfParts",
    t: VT_VECTOR_LPSTR
    /* VT_VECTOR | VT_LPSTR */
  },
  14: { n: "Manager", t: VT_STRING },
  15: { n: "Company", t: VT_STRING },
  16: { n: "LinksUpToDate", t: VT_BOOL },
  17: { n: "CharacterCount", t: VT_I4 },
  19: { n: "SharedDoc", t: VT_BOOL },
  22: { n: "HyperlinksChanged", t: VT_BOOL },
  23: { n: "AppVersion", t: VT_I4, p: "version" },
  24: { n: "DigSig", t: VT_BLOB },
  26: { n: "ContentType", t: VT_STRING },
  27: { n: "ContentStatus", t: VT_STRING },
  28: { n: "Language", t: VT_STRING },
  29: { n: "Version", t: VT_STRING },
  255: {},
  /* [MS-OLEPS] 2.18 */
  2147483648: { n: "Locale", t: VT_UI4 },
  2147483651: { n: "Behavior", t: VT_UI4 },
  1919054434: {}
};
var SummaryPIDSI = {
  1: { n: "CodePage", t: VT_I2 },
  2: { n: "Title", t: VT_STRING },
  3: { n: "Subject", t: VT_STRING },
  4: { n: "Author", t: VT_STRING },
  5: { n: "Keywords", t: VT_STRING },
  6: { n: "Comments", t: VT_STRING },
  7: { n: "Template", t: VT_STRING },
  8: { n: "LastAuthor", t: VT_STRING },
  9: { n: "RevNumber", t: VT_STRING },
  10: { n: "EditTime", t: VT_FILETIME },
  11: { n: "LastPrinted", t: VT_FILETIME },
  12: { n: "CreatedDate", t: VT_FILETIME },
  13: { n: "ModifiedDate", t: VT_FILETIME },
  14: { n: "PageCount", t: VT_I4 },
  15: { n: "WordCount", t: VT_I4 },
  16: { n: "CharCount", t: VT_I4 },
  17: { n: "Thumbnail", t: VT_CF },
  18: { n: "Application", t: VT_STRING },
  19: { n: "DocSecurity", t: VT_I4 },
  255: {},
  /* [MS-OLEPS] 2.18 */
  2147483648: { n: "Locale", t: VT_UI4 },
  2147483651: { n: "Behavior", t: VT_UI4 },
  1919054434: {}
};
var CountryEnum = {
  1: "US",
  // United States
  2: "CA",
  // Canada
  3: "",
  // Latin America (except Brazil)
  7: "RU",
  // Russia
  20: "EG",
  // Egypt
  30: "GR",
  // Greece
  31: "NL",
  // Netherlands
  32: "BE",
  // Belgium
  33: "FR",
  // France
  34: "ES",
  // Spain
  36: "HU",
  // Hungary
  39: "IT",
  // Italy
  41: "CH",
  // Switzerland
  43: "AT",
  // Austria
  44: "GB",
  // United Kingdom
  45: "DK",
  // Denmark
  46: "SE",
  // Sweden
  47: "NO",
  // Norway
  48: "PL",
  // Poland
  49: "DE",
  // Germany
  52: "MX",
  // Mexico
  55: "BR",
  // Brazil
  61: "AU",
  // Australia
  64: "NZ",
  // New Zealand
  66: "TH",
  // Thailand
  81: "JP",
  // Japan
  82: "KR",
  // Korea
  84: "VN",
  // Viet Nam
  86: "CN",
  // China
  90: "TR",
  // Turkey
  105: "JS",
  // Ramastan
  213: "DZ",
  // Algeria
  216: "MA",
  // Morocco
  218: "LY",
  // Libya
  351: "PT",
  // Portugal
  354: "IS",
  // Iceland
  358: "FI",
  // Finland
  420: "CZ",
  // Czech Republic
  886: "TW",
  // Taiwan
  961: "LB",
  // Lebanon
  962: "JO",
  // Jordan
  963: "SY",
  // Syria
  964: "IQ",
  // Iraq
  965: "KW",
  // Kuwait
  966: "SA",
  // Saudi Arabia
  971: "AE",
  // United Arab Emirates
  972: "IL",
  // Israel
  974: "QA",
  // Qatar
  981: "IR",
  // Iran
  65535: "US"
  // United States
};
var XLSFillPattern = [
  null,
  "solid",
  "mediumGray",
  "darkGray",
  "lightGray",
  "darkHorizontal",
  "darkVertical",
  "darkDown",
  "darkUp",
  "darkGrid",
  "darkTrellis",
  "lightHorizontal",
  "lightVertical",
  "lightDown",
  "lightUp",
  "lightGrid",
  "lightTrellis",
  "gray125",
  "gray0625"
];
function rgbify(arr) {
  return arr.map(function(x2) {
    return [x2 >> 16 & 255, x2 >> 8 & 255, x2 & 255];
  });
}
var _XLSIcv = /* @__PURE__ */ rgbify([
  /* Color Constants */
  0,
  16777215,
  16711680,
  65280,
  255,
  16776960,
  16711935,
  65535,
  /* Overridable Defaults */
  0,
  16777215,
  16711680,
  65280,
  255,
  16776960,
  16711935,
  65535,
  8388608,
  32768,
  128,
  8421376,
  8388736,
  32896,
  12632256,
  8421504,
  10066431,
  10040166,
  16777164,
  13434879,
  6684774,
  16744576,
  26316,
  13421823,
  128,
  16711935,
  16776960,
  65535,
  8388736,
  8388608,
  32896,
  255,
  52479,
  13434879,
  13434828,
  16777113,
  10079487,
  16751052,
  13408767,
  16764057,
  3368703,
  3394764,
  10079232,
  16763904,
  16750848,
  16737792,
  6710937,
  9868950,
  13158,
  3381606,
  13056,
  3355392,
  10040064,
  10040166,
  3355545,
  3355443,
  /* Other entries to appease BIFF8/12 */
  0,
  /* 0x40 icvForeground ?? */
  16777215,
  /* 0x41 icvBackground ?? */
  0,
  /* 0x42 icvFrame ?? */
  0,
  /* 0x43 icv3D ?? */
  0,
  /* 0x44 icv3DText ?? */
  0,
  /* 0x45 icv3DHilite ?? */
  0,
  /* 0x46 icv3DShadow ?? */
  0,
  /* 0x47 icvHilite ?? */
  0,
  /* 0x48 icvCtlText ?? */
  0,
  /* 0x49 icvCtlScrl ?? */
  0,
  /* 0x4A icvCtlInv ?? */
  0,
  /* 0x4B icvCtlBody ?? */
  0,
  /* 0x4C icvCtlFrame ?? */
  0,
  /* 0x4D icvCtlFore ?? */
  0,
  /* 0x4E icvCtlBack ?? */
  0,
  /* 0x4F icvCtlNeutral */
  0,
  /* 0x50 icvInfoBk ?? */
  0
  /* 0x51 icvInfoText ?? */
]);
var XLSIcv = /* @__PURE__ */ dup(_XLSIcv);
var BErr = {
  0: "#NULL!",
  7: "#DIV/0!",
  15: "#VALUE!",
  23: "#REF!",
  29: "#NAME?",
  36: "#NUM!",
  42: "#N/A",
  43: "#GETTING_DATA",
  255: "#WTF?"
};
var RBErr = {
  "#NULL!": 0,
  "#DIV/0!": 7,
  "#VALUE!": 15,
  "#REF!": 23,
  "#NAME?": 29,
  "#NUM!": 36,
  "#N/A": 42,
  "#GETTING_DATA": 43,
  "#WTF?": 255
};
var XLSLblBuiltIn = [
  "_xlnm.Consolidate_Area",
  "_xlnm.Auto_Open",
  "_xlnm.Auto_Close",
  "_xlnm.Extract",
  "_xlnm.Database",
  "_xlnm.Criteria",
  "_xlnm.Print_Area",
  "_xlnm.Print_Titles",
  "_xlnm.Recorder",
  "_xlnm.Data_Form",
  "_xlnm.Auto_Activate",
  "_xlnm.Auto_Deactivate",
  "_xlnm.Sheet_Title",
  "_xlnm._FilterDatabase"
];
var ct2type = {
  /* Workbook */
  "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": "workbooks",
  "application/vnd.ms-excel.sheet.macroEnabled.main+xml": "workbooks",
  "application/vnd.ms-excel.sheet.binary.macroEnabled.main": "workbooks",
  "application/vnd.ms-excel.addin.macroEnabled.main+xml": "workbooks",
  "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": "workbooks",
  /* Worksheet */
  "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": "sheets",
  "application/vnd.ms-excel.worksheet": "sheets",
  "application/vnd.ms-excel.binIndexWs": "TODO",
  /* Binary Index */
  /* Chartsheet */
  "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": "charts",
  "application/vnd.ms-excel.chartsheet": "charts",
  /* Macrosheet */
  "application/vnd.ms-excel.macrosheet+xml": "macros",
  "application/vnd.ms-excel.macrosheet": "macros",
  "application/vnd.ms-excel.intlmacrosheet": "TODO",
  "application/vnd.ms-excel.binIndexMs": "TODO",
  /* Binary Index */
  /* Dialogsheet */
  "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": "dialogs",
  "application/vnd.ms-excel.dialogsheet": "dialogs",
  /* Shared Strings */
  "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml": "strs",
  "application/vnd.ms-excel.sharedStrings": "strs",
  /* Styles */
  "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": "styles",
  "application/vnd.ms-excel.styles": "styles",
  /* File Properties */
  "application/vnd.openxmlformats-package.core-properties+xml": "coreprops",
  "application/vnd.openxmlformats-officedocument.custom-properties+xml": "custprops",
  "application/vnd.openxmlformats-officedocument.extended-properties+xml": "extprops",
  /* Custom Data Properties */
  "application/vnd.openxmlformats-officedocument.customXmlProperties+xml": "TODO",
  "application/vnd.openxmlformats-officedocument.spreadsheetml.customProperty": "TODO",
  /* Comments */
  "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": "comments",
  "application/vnd.ms-excel.comments": "comments",
  "application/vnd.ms-excel.threadedcomments+xml": "threadedcomments",
  "application/vnd.ms-excel.person+xml": "people",
  /* Metadata (Stock/Geography and Dynamic Array) */
  "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetMetadata+xml": "metadata",
  "application/vnd.ms-excel.sheetMetadata": "metadata",
  /* PivotTable */
  "application/vnd.ms-excel.pivotTable": "TODO",
  "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml": "TODO",
  /* Chart Objects */
  "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": "TODO",
  /* Chart Colors */
  "application/vnd.ms-office.chartcolorstyle+xml": "TODO",
  /* Chart Style */
  "application/vnd.ms-office.chartstyle+xml": "TODO",
  /* Chart Advanced */
  "application/vnd.ms-office.chartex+xml": "TODO",
  /* Calculation Chain */
  "application/vnd.ms-excel.calcChain": "calcchains",
  "application/vnd.openxmlformats-officedocument.spreadsheetml.calcChain+xml": "calcchains",
  /* Printer Settings */
  "application/vnd.openxmlformats-officedocument.spreadsheetml.printerSettings": "TODO",
  /* ActiveX */
  "application/vnd.ms-office.activeX": "TODO",
  "application/vnd.ms-office.activeX+xml": "TODO",
  /* Custom Toolbars */
  "application/vnd.ms-excel.attachedToolbars": "TODO",
  /* External Data Connections */
  "application/vnd.ms-excel.connections": "TODO",
  "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": "TODO",
  /* External Links */
  "application/vnd.ms-excel.externalLink": "links",
  "application/vnd.openxmlformats-officedocument.spreadsheetml.externalLink+xml": "links",
  /* PivotCache */
  "application/vnd.ms-excel.pivotCacheDefinition": "TODO",
  "application/vnd.ms-excel.pivotCacheRecords": "TODO",
  "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheDefinition+xml": "TODO",
  "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheRecords+xml": "TODO",
  /* Query Table */
  "application/vnd.ms-excel.queryTable": "TODO",
  "application/vnd.openxmlformats-officedocument.spreadsheetml.queryTable+xml": "TODO",
  /* Shared Workbook */
  "application/vnd.ms-excel.userNames": "TODO",
  "application/vnd.ms-excel.revisionHeaders": "TODO",
  "application/vnd.ms-excel.revisionLog": "TODO",
  "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionHeaders+xml": "TODO",
  "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionLog+xml": "TODO",
  "application/vnd.openxmlformats-officedocument.spreadsheetml.userNames+xml": "TODO",
  /* Single Cell Table */
  "application/vnd.ms-excel.tableSingleCells": "TODO",
  "application/vnd.openxmlformats-officedocument.spreadsheetml.tableSingleCells+xml": "TODO",
  /* Slicer */
  "application/vnd.ms-excel.slicer": "TODO",
  "application/vnd.ms-excel.slicerCache": "TODO",
  "application/vnd.ms-excel.slicer+xml": "TODO",
  "application/vnd.ms-excel.slicerCache+xml": "TODO",
  /* Sort Map */
  "application/vnd.ms-excel.wsSortMap": "TODO",
  /* Table */
  "application/vnd.ms-excel.table": "TODO",
  "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": "TODO",
  /* Themes */
  "application/vnd.openxmlformats-officedocument.theme+xml": "themes",
  /* Theme Override */
  "application/vnd.openxmlformats-officedocument.themeOverride+xml": "TODO",
  /* Timeline */
  "application/vnd.ms-excel.Timeline+xml": "TODO",
  /* verify */
  "application/vnd.ms-excel.TimelineCache+xml": "TODO",
  /* verify */
  /* VBA */
  "application/vnd.ms-office.vbaProject": "vba",
  "application/vnd.ms-office.vbaProjectSignature": "TODO",
  /* Volatile Dependencies */
  "application/vnd.ms-office.volatileDependencies": "TODO",
  "application/vnd.openxmlformats-officedocument.spreadsheetml.volatileDependencies+xml": "TODO",
  /* Control Properties */
  "application/vnd.ms-excel.controlproperties+xml": "TODO",
  /* Data Model */
  "application/vnd.openxmlformats-officedocument.model+data": "TODO",
  /* Survey */
  "application/vnd.ms-excel.Survey+xml": "TODO",
  /* Drawing */
  "application/vnd.openxmlformats-officedocument.drawing+xml": "drawings",
  "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": "TODO",
  "application/vnd.openxmlformats-officedocument.drawingml.diagramColors+xml": "TODO",
  "application/vnd.openxmlformats-officedocument.drawingml.diagramData+xml": "TODO",
  "application/vnd.openxmlformats-officedocument.drawingml.diagramLayout+xml": "TODO",
  "application/vnd.openxmlformats-officedocument.drawingml.diagramStyle+xml": "TODO",
  /* VML */
  "application/vnd.openxmlformats-officedocument.vmlDrawing": "TODO",
  "application/vnd.openxmlformats-package.relationships+xml": "rels",
  "application/vnd.openxmlformats-officedocument.oleObject": "TODO",
  /* Image */
  "image/png": "TODO",
  "sheet": "js"
};
function new_ct() {
  return {
    workbooks: [],
    sheets: [],
    charts: [],
    dialogs: [],
    macros: [],
    rels: [],
    strs: [],
    comments: [],
    threadedcomments: [],
    links: [],
    coreprops: [],
    extprops: [],
    custprops: [],
    themes: [],
    styles: [],
    calcchains: [],
    vba: [],
    drawings: [],
    metadata: [],
    people: [],
    TODO: [],
    xmlns: ""
  };
}
function parse_ct(data) {
  var ct = new_ct();
  if (!data || !data.match) return ct;
  var ctext = {};
  (data.match(tagregex) || []).forEach(function(x2) {
    var y4 = parsexmltag(x2);
    switch (y4[0].replace(nsregex, "<")) {
      case "<?xml":
        break;
      case "<Types":
        ct.xmlns = y4["xmlns" + (y4[0].match(/<(\w+):/) || ["", ""])[1]];
        break;
      case "<Default":
        ctext[y4.Extension.toLowerCase()] = y4.ContentType;
        break;
      case "<Override":
        if (ct[ct2type[y4.ContentType]] !== void 0) ct[ct2type[y4.ContentType]].push(y4.PartName);
        break;
    }
  });
  if (ct.xmlns !== XMLNS.CT) throw new Error("Unknown Namespace: " + ct.xmlns);
  ct.calcchain = ct.calcchains.length > 0 ? ct.calcchains[0] : "";
  ct.sst = ct.strs.length > 0 ? ct.strs[0] : "";
  ct.style = ct.styles.length > 0 ? ct.styles[0] : "";
  ct.defaults = ctext;
  delete ct.calcchains;
  return ct;
}
var RELS = {
  WB: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",
  SHEET: "http://sheetjs.openxmlformats.org/officeDocument/2006/relationships/officeDocument",
  HLINK: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink",
  VML: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing",
  XPATH: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/externalLinkPath",
  XMISS: "http://schemas.microsoft.com/office/2006/relationships/xlExternalLinkPath/xlPathMissing",
  XLINK: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/externalLink",
  CXML: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXml",
  CXMLP: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXmlProps",
  CMNT: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments",
  CORE_PROPS: "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties",
  EXT_PROPS: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties",
  CUST_PROPS: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties",
  SST: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings",
  STY: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles",
  THEME: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme",
  CHART: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart",
  CHARTEX: "http://schemas.microsoft.com/office/2014/relationships/chartEx",
  CS: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chartsheet",
  WS: [
    "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet",
    "http://purl.oclc.org/ooxml/officeDocument/relationships/worksheet"
  ],
  DS: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/dialogsheet",
  MS: "http://schemas.microsoft.com/office/2006/relationships/xlMacrosheet",
  IMG: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
  DRAW: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing",
  XLMETA: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/sheetMetadata",
  TCMNT: "http://schemas.microsoft.com/office/2017/10/relationships/threadedComment",
  PEOPLE: "http://schemas.microsoft.com/office/2017/10/relationships/person",
  CONN: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/connections",
  VBA: "http://schemas.microsoft.com/office/2006/relationships/vbaProject"
};
function get_rels_path(file) {
  var n7 = file.lastIndexOf("/");
  return file.slice(0, n7 + 1) + "_rels/" + file.slice(n7 + 1) + ".rels";
}
function parse_rels(data, currentFilePath) {
  var rels = { "!id": {} };
  if (!data) return rels;
  if (currentFilePath.charAt(0) !== "/") {
    currentFilePath = "/" + currentFilePath;
  }
  var hash = {};
  (data.match(tagregex) || []).forEach(function(x2) {
    var y4 = parsexmltag(x2);
    if (y4[0] === "<Relationship") {
      var rel2 = {};
      rel2.Type = y4.Type;
      rel2.Target = unescapexml(y4.Target);
      rel2.Id = y4.Id;
      if (y4.TargetMode) rel2.TargetMode = y4.TargetMode;
      var canonictarget = y4.TargetMode === "External" ? y4.Target : resolve_path(y4.Target, currentFilePath);
      rels[canonictarget] = rel2;
      hash[y4.Id] = rel2;
    }
  });
  rels["!id"] = hash;
  return rels;
}
var CT_ODS = "application/vnd.oasis.opendocument.spreadsheet";
function parse_manifest(d4, opts) {
  var str2 = xlml_normalize(d4);
  var Rn;
  var FEtag;
  while (Rn = xlmlregex.exec(str2))
    switch (Rn[3]) {
      case "manifest":
        break;
      case "file-entry":
        FEtag = parsexmltag(Rn[0], false);
        if (FEtag.path == "/" && FEtag.type !== CT_ODS)
          throw new Error("This OpenDocument is not a spreadsheet");
        break;
      case "encryption-data":
      case "algorithm":
      case "start-key-generation":
      case "key-derivation":
        throw new Error("Unsupported ODS Encryption");
      default:
        if (opts && opts.WTF)
          throw Rn;
    }
}
var CORE_PROPS = [
  ["cp:category", "Category"],
  ["cp:contentStatus", "ContentStatus"],
  ["cp:keywords", "Keywords"],
  ["cp:lastModifiedBy", "LastAuthor"],
  ["cp:lastPrinted", "LastPrinted"],
  ["cp:revision", "RevNumber"],
  ["cp:version", "Version"],
  ["dc:creator", "Author"],
  ["dc:description", "Comments"],
  ["dc:identifier", "Identifier"],
  ["dc:language", "Language"],
  ["dc:subject", "Subject"],
  ["dc:title", "Title"],
  ["dcterms:created", "CreatedDate", "date"],
  ["dcterms:modified", "ModifiedDate", "date"]
];
function parse_core_props(data) {
  var p4 = {};
  data = utf8read(data);
  for (var i7 = 0; i7 < CORE_PROPS.length; ++i7) {
    var f4 = CORE_PROPS[i7], cur = str_match_xml(data, f4[0]);
    if (cur != null && cur.length > 0) p4[f4[1]] = unescapexml(cur[1]);
    if (f4[2] === "date" && p4[f4[1]]) p4[f4[1]] = parseDate(p4[f4[1]]);
  }
  return p4;
}
var EXT_PROPS = [
  ["Application", "Application", "string"],
  ["AppVersion", "AppVersion", "string"],
  ["Company", "Company", "string"],
  ["DocSecurity", "DocSecurity", "string"],
  ["Manager", "Manager", "string"],
  ["HyperlinksChanged", "HyperlinksChanged", "bool"],
  ["SharedDoc", "SharedDoc", "bool"],
  ["LinksUpToDate", "LinksUpToDate", "bool"],
  ["ScaleCrop", "ScaleCrop", "bool"],
  ["HeadingPairs", "HeadingPairs", "raw"],
  ["TitlesOfParts", "TitlesOfParts", "raw"]
];
function load_props_pairs(HP, TOP, props, opts) {
  var v4 = [];
  if (typeof HP == "string") v4 = parseVector(HP, opts);
  else for (var j3 = 0; j3 < HP.length; ++j3) v4 = v4.concat(HP[j3].map(function(hp) {
    return { v: hp };
  }));
  var parts = typeof TOP == "string" ? parseVector(TOP, opts).map(function(x2) {
    return x2.v;
  }) : TOP;
  var idx = 0, len = 0;
  if (parts.length > 0) for (var i7 = 0; i7 !== v4.length; i7 += 2) {
    len = +v4[i7 + 1].v;
    switch (v4[i7].v) {
      case "Worksheets":
      case "\u5DE5\u4F5C\u8868":
      case "\u041B\u0438\u0441\u0442\u044B":
      case "\u0623\u0648\u0631\u0627\u0642 \u0627\u0644\u0639\u0645\u0644":
      case "\u30EF\u30FC\u30AF\u30B7\u30FC\u30C8":
      case "\u05D2\u05DC\u05D9\u05D5\u05E0\u05D5\u05EA \u05E2\u05D1\u05D5\u05D3\u05D4":
      case "Arbeitsbl\xE4tter":
      case "\xC7al\u0131\u015Fma Sayfalar\u0131":
      case "Feuilles de calcul":
      case "Fogli di lavoro":
      case "Folhas de c\xE1lculo":
      case "Planilhas":
      case "Regneark":
      case "Hojas de c\xE1lculo":
      case "Werkbladen":
        props.Worksheets = len;
        props.SheetNames = parts.slice(idx, idx + len);
        break;
      case "Named Ranges":
      case "Rangos con nombre":
      case "\u540D\u524D\u4ED8\u304D\u4E00\u89A7":
      case "Benannte Bereiche":
      case "Navngivne omr\xE5der":
        props.NamedRanges = len;
        props.DefinedNames = parts.slice(idx, idx + len);
        break;
      case "Charts":
      case "Diagramme":
        props.Chartsheets = len;
        props.ChartNames = parts.slice(idx, idx + len);
        break;
    }
    idx += len;
  }
}
function parse_ext_props(data, p4, opts) {
  var q2 = {};
  if (!p4) p4 = {};
  data = utf8read(data);
  EXT_PROPS.forEach(function(f4) {
    var xml2 = (str_match_xml_ns(data, f4[0]) || [])[1];
    switch (f4[2]) {
      case "string":
        if (xml2) p4[f4[1]] = unescapexml(xml2);
        break;
      case "bool":
        p4[f4[1]] = xml2 === "true";
        break;
      case "raw":
        var cur = str_match_xml(data, f4[0]);
        if (cur && cur.length > 0) q2[f4[1]] = cur[1];
        break;
    }
  });
  if (q2.HeadingPairs && q2.TitlesOfParts) load_props_pairs(q2.HeadingPairs, q2.TitlesOfParts, p4, opts);
  return p4;
}
var custregex = /<[^<>]+>[^<]*/g;
function parse_cust_props(data, opts) {
  var p4 = {}, name = "";
  var m4 = data.match(custregex);
  if (m4) for (var i7 = 0; i7 != m4.length; ++i7) {
    var x2 = m4[i7], y4 = parsexmltag(x2);
    switch (strip_ns(y4[0])) {
      case "<?xml":
        break;
      case "<Properties":
        break;
      case "<property":
        name = unescapexml(y4.name);
        break;
      case "</property>":
        name = null;
        break;
      default:
        if (x2.indexOf("<vt:") === 0) {
          var toks = x2.split(">");
          var type = toks[0].slice(4), text3 = toks[1];
          switch (type) {
            case "lpstr":
            case "bstr":
            case "lpwstr":
              p4[name] = unescapexml(text3);
              break;
            case "bool":
              p4[name] = parsexmlbool(text3);
              break;
            case "i1":
            case "i2":
            case "i4":
            case "i8":
            case "int":
            case "uint":
              p4[name] = parseInt(text3, 10);
              break;
            case "r4":
            case "r8":
            case "decimal":
              p4[name] = parseFloat(text3);
              break;
            case "filetime":
            case "date":
              p4[name] = parseDate(text3);
              break;
            case "cy":
            case "error":
              p4[name] = unescapexml(text3);
              break;
            default:
              if (type.slice(-1) == "/") break;
              if (opts.WTF && typeof console !== "undefined") console.warn("Unexpected", x2, type, toks);
          }
        } else if (x2.slice(0, 2) === "</") {
        } else if (opts.WTF) throw new Error(x2);
    }
  }
  return p4;
}
var XLMLDocPropsMap = {
  Title: "Title",
  Subject: "Subject",
  Author: "Author",
  Keywords: "Keywords",
  Comments: "Description",
  LastAuthor: "LastAuthor",
  RevNumber: "Revision",
  Application: "AppName",
  /* TotalTime: 'TotalTime', */
  LastPrinted: "LastPrinted",
  CreatedDate: "Created",
  ModifiedDate: "LastSaved",
  /* Pages */
  /* Words */
  /* Characters */
  Category: "Category",
  /* PresentationFormat */
  Manager: "Manager",
  Company: "Company",
  /* Guid */
  /* HyperlinkBase */
  /* Bytes */
  /* Lines */
  /* Paragraphs */
  /* CharactersWithSpaces */
  AppVersion: "Version",
  ContentStatus: "ContentStatus",
  /* NOTE: missing from schema */
  Identifier: "Identifier",
  /* NOTE: missing from schema */
  Language: "Language"
  /* NOTE: missing from schema */
};
var evert_XLMLDPM;
function xlml_set_prop(Props, tag, val2) {
  if (!evert_XLMLDPM) evert_XLMLDPM = evert(XLMLDocPropsMap);
  tag = evert_XLMLDPM[tag] || tag;
  Props[tag] = val2;
}
function parse_FILETIME(blob) {
  var dwLowDateTime = blob.read_shift(4), dwHighDateTime = blob.read_shift(4);
  return new Date((dwHighDateTime / 1e7 * Math.pow(2, 32) + dwLowDateTime / 1e7 - 11644473600) * 1e3).toISOString().replace(/\.000/, "");
}
function parse_lpstr(blob, type, pad2) {
  var start = blob.l;
  var str2 = blob.read_shift(0, "lpstr-cp");
  if (pad2) while (blob.l - start & 3) ++blob.l;
  return str2;
}
function parse_lpwstr(blob, type, pad2) {
  var str2 = blob.read_shift(0, "lpwstr");
  if (pad2) blob.l += 4 - (str2.length + 1 & 3) & 3;
  return str2;
}
function parse_VtStringBase(blob, stringType3, pad2) {
  if (stringType3 === 31) return parse_lpwstr(blob);
  return parse_lpstr(blob, stringType3, pad2);
}
function parse_VtString(blob, t6, pad2) {
  return parse_VtStringBase(blob, t6, pad2 === false ? 0 : 4);
}
function parse_VtUnalignedString(blob, t6) {
  if (!t6) throw new Error("VtUnalignedString must have positive length");
  return parse_VtStringBase(blob, t6, 0);
}
function parse_VtVecLpwstrValue(blob) {
  var length = blob.read_shift(4);
  var ret = [];
  for (var i7 = 0; i7 != length; ++i7) {
    var start = blob.l;
    ret[i7] = blob.read_shift(0, "lpwstr").replace(chr0, "");
    if (blob.l - start & 2) blob.l += 2;
  }
  return ret;
}
function parse_VtVecUnalignedLpstrValue(blob) {
  var length = blob.read_shift(4);
  var ret = [];
  for (var i7 = 0; i7 != length; ++i7) ret[i7] = blob.read_shift(0, "lpstr-cp").replace(chr0, "");
  return ret;
}
function parse_VtHeadingPair(blob) {
  var start = blob.l;
  var headingString = parse_TypedPropertyValue(blob, VT_USTR);
  if (blob[blob.l] == 0 && blob[blob.l + 1] == 0 && blob.l - start & 2) blob.l += 2;
  var headerParts = parse_TypedPropertyValue(blob, VT_I4);
  return [headingString, headerParts];
}
function parse_VtVecHeadingPairValue(blob) {
  var cElements = blob.read_shift(4);
  var out = [];
  for (var i7 = 0; i7 < cElements / 2; ++i7) out.push(parse_VtHeadingPair(blob));
  return out;
}
function parse_dictionary(blob, CodePage) {
  var cnt = blob.read_shift(4);
  var dict = {};
  for (var j3 = 0; j3 != cnt; ++j3) {
    var pid = blob.read_shift(4);
    var len = blob.read_shift(4);
    dict[pid] = blob.read_shift(len, CodePage === 1200 ? "utf16le" : "utf8").replace(chr0, "").replace(chr1, "!");
    if (CodePage === 1200 && len % 2) blob.l += 2;
  }
  if (blob.l & 3) blob.l = blob.l >> 2 + 1 << 2;
  return dict;
}
function parse_BLOB(blob) {
  var size = blob.read_shift(4);
  var bytes = blob.slice(blob.l, blob.l + size);
  blob.l += size;
  if ((size & 3) > 0) blob.l += 4 - (size & 3) & 3;
  return bytes;
}
function parse_ClipboardData(blob) {
  var o9 = {};
  o9.Size = blob.read_shift(4);
  blob.l += o9.Size + 3 - (o9.Size - 1) % 4;
  return o9;
}
function parse_TypedPropertyValue(blob, type, _opts) {
  var t6 = blob.read_shift(2), ret, opts = _opts || {};
  blob.l += 2;
  if (type !== VT_VARIANT) {
    if (t6 !== type && VT_CUSTOM.indexOf(type) === -1 && !((type & 65534) == 4126 && (t6 & 65534) == 4126)) throw new Error("Expected type " + type + " saw " + t6);
  }
  switch (type === VT_VARIANT ? t6 : type) {
    case 2:
      ret = blob.read_shift(2, "i");
      if (!opts.raw) blob.l += 2;
      return ret;
    case 3:
      ret = blob.read_shift(4, "i");
      return ret;
    case 11:
      return blob.read_shift(4) !== 0;
    case 19:
      ret = blob.read_shift(4);
      return ret;
    case 30:
      blob.l += 4;
      val = parse_VtString(blob, blob[blob.l - 4]).replace(/(^|[^\u0000])\u0000+$/, "$1");
      break;
    case 31:
      blob.l += 4;
      val = parse_VtString(blob, blob[blob.l - 4]).replace(/(^|[^\u0000])\u0000+$/, "$1");
      break;
    case 64:
      return parse_FILETIME(blob);
    case 65:
      return parse_BLOB(blob);
    case 71:
      return parse_ClipboardData(blob);
    case 80:
      return parse_VtString(blob, t6, !opts.raw).replace(chr0, "");
    case 81:
      return parse_VtUnalignedString(
        blob,
        t6
        /*, 4*/
      ).replace(chr0, "");
    case 4108:
      return parse_VtVecHeadingPairValue(blob);
    case 4126:
    case 4127:
      return t6 == 4127 ? parse_VtVecLpwstrValue(blob) : parse_VtVecUnalignedLpstrValue(blob);
    default:
      throw new Error("TypedPropertyValue unrecognized type " + type + " " + t6);
  }
}
function parse_PropertySet(blob, PIDSI) {
  var start_addr = blob.l;
  var size = blob.read_shift(4);
  var NumProps = blob.read_shift(4);
  var Props = [], i7 = 0;
  var CodePage = 0;
  var Dictionary = -1, DictObj = {};
  for (i7 = 0; i7 != NumProps; ++i7) {
    var PropID = blob.read_shift(4);
    var Offset = blob.read_shift(4);
    Props[i7] = [PropID, Offset + start_addr];
  }
  Props.sort(function(x2, y4) {
    return x2[1] - y4[1];
  });
  var PropH = {};
  for (i7 = 0; i7 != NumProps; ++i7) {
    if (blob.l !== Props[i7][1]) {
      var fail = true;
      if (i7 > 0 && PIDSI) switch (PIDSI[Props[i7 - 1][0]].t) {
        case 2:
          if (blob.l + 2 === Props[i7][1]) {
            blob.l += 2;
            fail = false;
          }
          break;
        case 80:
          if (blob.l <= Props[i7][1]) {
            blob.l = Props[i7][1];
            fail = false;
          }
          break;
        case 4108:
          if (blob.l <= Props[i7][1]) {
            blob.l = Props[i7][1];
            fail = false;
          }
          break;
      }
      if ((!PIDSI || i7 == 0) && blob.l <= Props[i7][1]) {
        fail = false;
        blob.l = Props[i7][1];
      }
      if (fail) throw new Error("Read Error: Expected address " + Props[i7][1] + " at " + blob.l + " :" + i7);
    }
    if (PIDSI) {
      if (Props[i7][0] == 0 && Props.length > i7 + 1 && Props[i7][1] == Props[i7 + 1][1]) continue;
      var piddsi = PIDSI[Props[i7][0]];
      PropH[piddsi.n] = parse_TypedPropertyValue(blob, piddsi.t, { raw: true });
      if (piddsi.p === "version") PropH[piddsi.n] = String(PropH[piddsi.n] >> 16) + "." + ("0000" + String(PropH[piddsi.n] & 65535)).slice(-4);
      if (piddsi.n == "CodePage") switch (PropH[piddsi.n]) {
        case 0:
          PropH[piddsi.n] = 1252;
        /* falls through */
        case 874:
        case 932:
        case 936:
        case 949:
        case 950:
        case 1250:
        case 1251:
        case 1253:
        case 1254:
        case 1255:
        case 1256:
        case 1257:
        case 1258:
        case 1e4:
        case 1200:
        case 1201:
        case 1252:
        case 65e3:
        case -536:
        case 65001:
        case -535:
          set_cp(CodePage = PropH[piddsi.n] >>> 0 & 65535);
          break;
        default:
          throw new Error("Unsupported CodePage: " + PropH[piddsi.n]);
      }
    } else {
      if (Props[i7][0] === 1) {
        CodePage = PropH.CodePage = parse_TypedPropertyValue(blob, VT_I2);
        set_cp(CodePage);
        if (Dictionary !== -1) {
          var oldpos = blob.l;
          blob.l = Props[Dictionary][1];
          DictObj = parse_dictionary(blob, CodePage);
          blob.l = oldpos;
        }
      } else if (Props[i7][0] === 0) {
        if (CodePage === 0) {
          Dictionary = i7;
          blob.l = Props[i7 + 1][1];
          continue;
        }
        DictObj = parse_dictionary(blob, CodePage);
      } else {
        var name = DictObj[Props[i7][0]];
        var val2;
        switch (blob[blob.l]) {
          case 65:
            blob.l += 4;
            val2 = parse_BLOB(blob);
            break;
          case 30:
            blob.l += 4;
            val2 = parse_VtString(blob, blob[blob.l - 4]).replace(/(^|[^\u0000])\u0000+$/, "$1");
            break;
          case 31:
            blob.l += 4;
            val2 = parse_VtString(blob, blob[blob.l - 4]).replace(/(^|[^\u0000])\u0000+$/, "$1");
            break;
          case 3:
            blob.l += 4;
            val2 = blob.read_shift(4, "i");
            break;
          case 19:
            blob.l += 4;
            val2 = blob.read_shift(4);
            break;
          case 5:
            blob.l += 4;
            val2 = blob.read_shift(8, "f");
            break;
          case 11:
            blob.l += 4;
            val2 = parsebool(blob, 4);
            break;
          case 64:
            blob.l += 4;
            val2 = parseDate(parse_FILETIME(blob));
            break;
          default:
            throw new Error("unparsed value: " + blob[blob.l]);
        }
        PropH[name] = val2;
      }
    }
  }
  blob.l = start_addr + size;
  return PropH;
}
function parse_PropertySetStream(file, PIDSI, clsid) {
  var blob = file.content;
  if (!blob) return {};
  prep_blob(blob, 0);
  var NumSets, FMTID0, FMTID1, Offset0, Offset1 = 0;
  blob.chk("feff", "Byte Order: ");
  blob.read_shift(2);
  var SystemIdentifier = blob.read_shift(4);
  var CLSID = blob.read_shift(16);
  if (CLSID !== CFB.utils.consts.HEADER_CLSID && CLSID !== clsid) throw new Error("Bad PropertySet CLSID " + CLSID);
  NumSets = blob.read_shift(4);
  if (NumSets !== 1 && NumSets !== 2) throw new Error("Unrecognized #Sets: " + NumSets);
  FMTID0 = blob.read_shift(16);
  Offset0 = blob.read_shift(4);
  if (NumSets === 1 && Offset0 !== blob.l) throw new Error("Length mismatch: " + Offset0 + " !== " + blob.l);
  else if (NumSets === 2) {
    FMTID1 = blob.read_shift(16);
    Offset1 = blob.read_shift(4);
  }
  var PSet0 = parse_PropertySet(blob, PIDSI);
  var rval = { SystemIdentifier };
  for (var y4 in PSet0) rval[y4] = PSet0[y4];
  rval.FMTID = FMTID0;
  if (NumSets === 1) return rval;
  if (Offset1 - blob.l == 2) blob.l += 2;
  if (blob.l !== Offset1) throw new Error("Length mismatch 2: " + blob.l + " !== " + Offset1);
  var PSet1;
  try {
    PSet1 = parse_PropertySet(blob, null);
  } catch (e9) {
  }
  for (y4 in PSet1) rval[y4] = PSet1[y4];
  rval.FMTID = [FMTID0, FMTID1];
  return rval;
}
function parsenoop2(blob, length) {
  blob.read_shift(length);
  return null;
}
function parslurp(blob, length, cb) {
  var arr = [], target = blob.l + length;
  while (blob.l < target) arr.push(cb(blob, target - blob.l));
  if (target !== blob.l) throw new Error("Slurp error");
  return arr;
}
function parsebool(blob, length) {
  return blob.read_shift(length) === 1;
}
function parseuint16(blob) {
  return blob.read_shift(2, "u");
}
function parseuint16a(blob, length) {
  return parslurp(blob, length, parseuint16);
}
function parse_Bes(blob) {
  var v4 = blob.read_shift(1), t6 = blob.read_shift(1);
  return t6 === 1 ? v4 : v4 === 1;
}
function parse_ShortXLUnicodeString(blob, length, opts) {
  var cch = blob.read_shift(opts && opts.biff >= 12 ? 2 : 1);
  var encoding = "sbcs-cont";
  var cp = current_codepage;
  if (opts && opts.biff >= 8) current_codepage = 1200;
  if (!opts || opts.biff == 8) {
    var fHighByte = blob.read_shift(1);
    if (fHighByte) {
      encoding = "dbcs-cont";
    }
  } else if (opts.biff == 12) {
    encoding = "wstr";
  }
  if (opts.biff >= 2 && opts.biff <= 5) encoding = "cpstr";
  var o9 = cch ? blob.read_shift(cch, encoding) : "";
  current_codepage = cp;
  return o9;
}
function parse_XLUnicodeRichExtendedString(blob) {
  var cp = current_codepage;
  current_codepage = 1200;
  var cch = blob.read_shift(2), flags = blob.read_shift(1);
  var fExtSt = flags & 4, fRichSt = flags & 8;
  var width = 1 + (flags & 1);
  var cRun = 0, cbExtRst;
  var z3 = {};
  if (fRichSt) cRun = blob.read_shift(2);
  if (fExtSt) cbExtRst = blob.read_shift(4);
  var encoding = width == 2 ? "dbcs-cont" : "sbcs-cont";
  var msg = cch === 0 ? "" : blob.read_shift(cch, encoding);
  if (fRichSt) blob.l += 4 * cRun;
  if (fExtSt) blob.l += cbExtRst;
  z3.t = msg;
  if (!fRichSt) {
    z3.raw = "<t>" + z3.t + "</t>";
    z3.r = z3.t;
  }
  current_codepage = cp;
  return z3;
}
function parse_XLUnicodeStringNoCch(blob, cch, opts) {
  var retval;
  if (opts) {
    if (opts.biff >= 2 && opts.biff <= 5) return blob.read_shift(cch, "cpstr");
    if (opts.biff >= 12) return blob.read_shift(cch, "dbcs-cont");
  }
  var fHighByte = blob.read_shift(1);
  if (fHighByte === 0) {
    retval = blob.read_shift(cch, "sbcs-cont");
  } else {
    retval = blob.read_shift(cch, "dbcs-cont");
  }
  return retval;
}
function parse_XLUnicodeString(blob, length, opts) {
  var cch = blob.read_shift(opts && opts.biff == 2 ? 1 : 2);
  if (cch === 0) {
    blob.l++;
    return "";
  }
  return parse_XLUnicodeStringNoCch(blob, cch, opts);
}
function parse_XLUnicodeString2(blob, length, opts) {
  if (opts.biff > 5) return parse_XLUnicodeString(blob, length, opts);
  var cch = blob.read_shift(1);
  if (cch === 0) {
    blob.l++;
    return "";
  }
  return blob.read_shift(cch, opts.biff <= 4 || !blob.lens ? "cpstr" : "sbcs-cont");
}
function parse_ControlInfo(blob) {
  var flags = blob.read_shift(1);
  blob.l++;
  var accel = blob.read_shift(2);
  blob.l += 2;
  return [flags, accel];
}
function parse_URLMoniker(blob) {
  var len = blob.read_shift(4), start = blob.l;
  var extra = false;
  if (len > 24) {
    blob.l += len - 24;
    if (blob.read_shift(16) === "795881f43b1d7f48af2c825dc4852763") extra = true;
    blob.l = start;
  }
  var url = blob.read_shift((extra ? len - 24 : len) >> 1, "utf16le").replace(chr0, "");
  if (extra) blob.l += 24;
  return url;
}
function parse_FileMoniker(blob) {
  var cAnti = blob.read_shift(2);
  var preamble = "";
  while (cAnti-- > 0) preamble += "../";
  var ansiPath = blob.read_shift(0, "lpstr-ansi");
  blob.l += 2;
  if (blob.read_shift(2) != 57005) throw new Error("Bad FileMoniker");
  var sz = blob.read_shift(4);
  if (sz === 0) return preamble + ansiPath.replace(/\\/g, "/");
  var bytes = blob.read_shift(4);
  if (blob.read_shift(2) != 3) throw new Error("Bad FileMoniker");
  var unicodePath = blob.read_shift(bytes >> 1, "utf16le").replace(chr0, "");
  return preamble + unicodePath;
}
function parse_HyperlinkMoniker(blob, length) {
  var clsid = blob.read_shift(16);
  length -= 16;
  switch (clsid) {
    case "e0c9ea79f9bace118c8200aa004ba90b":
      return parse_URLMoniker(blob, length);
    case "0303000000000000c000000000000046":
      return parse_FileMoniker(blob, length);
    default:
      throw new Error("Unsupported Moniker " + clsid);
  }
}
function parse_HyperlinkString(blob) {
  var len = blob.read_shift(4);
  var o9 = len > 0 ? blob.read_shift(len, "utf16le").replace(chr0, "") : "";
  return o9;
}
function parse_Hyperlink(blob, length) {
  var end = blob.l + length;
  var sVer = blob.read_shift(4);
  if (sVer !== 2) throw new Error("Unrecognized streamVersion: " + sVer);
  var flags = blob.read_shift(2);
  blob.l += 2;
  var displayName, targetFrameName, moniker, oleMoniker, Loc = "", guid, fileTime;
  if (flags & 16) displayName = parse_HyperlinkString(blob, end - blob.l);
  if (flags & 128) targetFrameName = parse_HyperlinkString(blob, end - blob.l);
  if ((flags & 257) === 257) moniker = parse_HyperlinkString(blob, end - blob.l);
  if ((flags & 257) === 1) oleMoniker = parse_HyperlinkMoniker(blob, end - blob.l);
  if (flags & 8) Loc = parse_HyperlinkString(blob, end - blob.l);
  if (flags & 32) guid = blob.read_shift(16);
  if (flags & 64) fileTime = parse_FILETIME(
    blob
    /*, 8*/
  );
  blob.l = end;
  var target = targetFrameName || moniker || oleMoniker || "";
  if (target && Loc) target += "#" + Loc;
  if (!target) target = "#" + Loc;
  if (flags & 2 && target.charAt(0) == "/" && target.charAt(1) != "/") target = "file://" + target;
  var out = { Target: target };
  if (guid) out.guid = guid;
  if (fileTime) out.time = fileTime;
  if (displayName) out.Tooltip = displayName;
  return out;
}
function parse_LongRGBA(blob) {
  var r8 = blob.read_shift(1), g3 = blob.read_shift(1), b4 = blob.read_shift(1), a3 = blob.read_shift(1);
  return [r8, g3, b4, a3];
}
function parse_LongRGB(blob, length) {
  var x2 = parse_LongRGBA(blob, length);
  x2[3] = 0;
  return x2;
}
function parse_XLSCell(blob, length, opts) {
  var rw = blob.read_shift(2);
  var col = blob.read_shift(2);
  var ret = { r: rw, c: col, ixfe: 0 };
  if (opts && opts.biff == 2 || length == 7) {
    var flags = blob.read_shift(1);
    ret.ixfe = flags & 63;
    blob.l += 2;
  } else ret.ixfe = blob.read_shift(2);
  return ret;
}
function parse_frtHeader(blob) {
  var rt = blob.read_shift(2);
  var flags = blob.read_shift(2);
  blob.l += 8;
  return { type: rt, flags };
}
function parse_OptXLUnicodeString(blob, length, opts) {
  return length === 0 ? "" : parse_XLUnicodeString2(blob, length, opts);
}
function parse_XTI(blob, length, opts) {
  var w3 = opts.biff > 8 ? 4 : 2;
  var iSupBook = blob.read_shift(w3), itabFirst = blob.read_shift(w3, "i"), itabLast = blob.read_shift(w3, "i");
  return [iSupBook, itabFirst, itabLast];
}
function parse_RkRec(blob) {
  var ixfe = blob.read_shift(2);
  var RK = parse_RkNumber(blob);
  return [ixfe, RK];
}
function parse_AddinUdf(blob, length, opts) {
  blob.l += 4;
  length -= 4;
  var l5 = blob.l + length;
  var udfName = parse_ShortXLUnicodeString(blob, length, opts);
  var cb = blob.read_shift(2);
  l5 -= blob.l;
  if (cb !== l5) throw new Error("Malformed AddinUdf: padding = " + l5 + " != " + cb);
  blob.l += cb;
  return udfName;
}
function parse_Ref8U(blob) {
  var rwFirst = blob.read_shift(2);
  var rwLast = blob.read_shift(2);
  var colFirst = blob.read_shift(2);
  var colLast = blob.read_shift(2);
  return { s: { c: colFirst, r: rwFirst }, e: { c: colLast, r: rwLast } };
}
function parse_RefU(blob) {
  var rwFirst = blob.read_shift(2);
  var rwLast = blob.read_shift(2);
  var colFirst = blob.read_shift(1);
  var colLast = blob.read_shift(1);
  return { s: { c: colFirst, r: rwFirst }, e: { c: colLast, r: rwLast } };
}
var parse_Ref = parse_RefU;
function parse_FtCmo(blob) {
  blob.l += 4;
  var ot = blob.read_shift(2);
  var id = blob.read_shift(2);
  var flags = blob.read_shift(2);
  blob.l += 12;
  return [id, ot, flags];
}
function parse_FtNts(blob) {
  var out = {};
  blob.l += 4;
  blob.l += 16;
  out.fSharedNote = blob.read_shift(2);
  blob.l += 4;
  return out;
}
function parse_FtCf(blob) {
  var out = {};
  blob.l += 4;
  blob.cf = blob.read_shift(2);
  return out;
}
function parse_FtSkip(blob) {
  blob.l += 2;
  blob.l += blob.read_shift(2);
}
var FtTab = {
  0: parse_FtSkip,
  /* FtEnd */
  4: parse_FtSkip,
  /* FtMacro */
  5: parse_FtSkip,
  /* FtButton */
  6: parse_FtSkip,
  /* FtGmo */
  7: parse_FtCf,
  /* FtCf */
  8: parse_FtSkip,
  /* FtPioGrbit */
  9: parse_FtSkip,
  /* FtPictFmla */
  10: parse_FtSkip,
  /* FtCbls */
  11: parse_FtSkip,
  /* FtRbo */
  12: parse_FtSkip,
  /* FtSbs */
  13: parse_FtNts,
  /* FtNts */
  14: parse_FtSkip,
  /* FtSbsFmla */
  15: parse_FtSkip,
  /* FtGboData */
  16: parse_FtSkip,
  /* FtEdoData */
  17: parse_FtSkip,
  /* FtRboData */
  18: parse_FtSkip,
  /* FtCblsData */
  19: parse_FtSkip,
  /* FtLbsData */
  20: parse_FtSkip,
  /* FtCblsFmla */
  21: parse_FtCmo
};
function parse_FtArray(blob, length) {
  var tgt = blob.l + length;
  var fts = [];
  while (blob.l < tgt) {
    var ft = blob.read_shift(2);
    blob.l -= 2;
    try {
      fts[ft] = FtTab[ft](blob, tgt - blob.l);
    } catch (e9) {
      blob.l = tgt;
      return fts;
    }
  }
  if (blob.l != tgt) blob.l = tgt;
  return fts;
}
function parse_BOF(blob, length) {
  var o9 = { BIFFVer: 0, dt: 0 };
  o9.BIFFVer = blob.read_shift(2);
  length -= 2;
  if (length >= 2) {
    o9.dt = blob.read_shift(2);
    blob.l -= 2;
  }
  switch (o9.BIFFVer) {
    case 1536:
    /* BIFF8 */
    case 1280:
    /* BIFF5 */
    case 1024:
    /* BIFF4 */
    case 768:
    /* BIFF3 */
    case 512:
    /* BIFF2 */
    case 2:
    case 7:
      break;
    default:
      if (length > 6) throw new Error("Unexpected BIFF Ver " + o9.BIFFVer);
  }
  blob.read_shift(length);
  return o9;
}
function parse_InterfaceHdr(blob, length) {
  if (length === 0) return 1200;
  if (blob.read_shift(2) !== 1200) {
  }
  return 1200;
}
function parse_WriteAccess(blob, length, opts) {
  if (opts.enc) {
    blob.l += length;
    return "";
  }
  var l5 = blob.l;
  var UserName = parse_XLUnicodeString2(blob, 0, opts);
  blob.read_shift(length + l5 - blob.l);
  return UserName;
}
function parse_WsBool(blob, length, opts) {
  var flags = opts && opts.biff == 8 || length == 2 ? blob.read_shift(2) : (blob.l += length, 0);
  return { fDialog: flags & 16, fBelow: flags & 64, fRight: flags & 128 };
}
function parse_BoundSheet8(blob, length, opts) {
  var name = "";
  if (opts.biff == 4) {
    name = parse_ShortXLUnicodeString(blob, 0, opts);
    if (name.length === 0) name = "Sheet1";
    return { name };
  }
  var pos = blob.read_shift(4);
  var hidden = blob.read_shift(1) & 3;
  var dt = blob.read_shift(1);
  switch (dt) {
    case 0:
      dt = "Worksheet";
      break;
    case 1:
      dt = "Macrosheet";
      break;
    case 2:
      dt = "Chartsheet";
      break;
    case 6:
      dt = "VBAModule";
      break;
  }
  name = parse_ShortXLUnicodeString(blob, 0, opts);
  if (name.length === 0) name = "Sheet1";
  return { pos, hs: hidden, dt, name };
}
function parse_SST(blob, length) {
  var end = blob.l + length;
  var cnt = blob.read_shift(4);
  var ucnt = blob.read_shift(4);
  var strs2 = [];
  for (var i7 = 0; i7 != ucnt && blob.l < end; ++i7) {
    strs2.push(parse_XLUnicodeRichExtendedString(blob));
  }
  strs2.Count = cnt;
  strs2.Unique = ucnt;
  return strs2;
}
function parse_ExtSST(blob, length) {
  var extsst = {};
  extsst.dsst = blob.read_shift(2);
  blob.l += length - 2;
  return extsst;
}
function parse_Row(blob) {
  var z3 = {};
  z3.r = blob.read_shift(2);
  z3.c = blob.read_shift(2);
  z3.cnt = blob.read_shift(2) - z3.c;
  var miyRw = blob.read_shift(2);
  blob.l += 4;
  var flags = blob.read_shift(1);
  blob.l += 3;
  if (flags & 7) z3.level = flags & 7;
  if (flags & 32) z3.hidden = true;
  if (flags & 64) z3.hpt = miyRw / 20;
  return z3;
}
function parse_ForceFullCalculation(blob) {
  var header = parse_frtHeader(blob);
  if (header.type != 2211) throw new Error("Invalid Future Record " + header.type);
  var fullcalc = blob.read_shift(4);
  return fullcalc !== 0;
}
function parse_RecalcId(blob) {
  blob.read_shift(2);
  return blob.read_shift(4);
}
function parse_DefaultRowHeight(blob, length, opts) {
  var f4 = 0;
  if (!(opts && opts.biff == 2)) {
    f4 = blob.read_shift(2);
  }
  var miyRw = blob.read_shift(2);
  if (opts && opts.biff == 2) {
    f4 = 1 - (miyRw >> 15);
    miyRw &= 32767;
  }
  var fl = { Unsynced: f4 & 1, DyZero: (f4 & 2) >> 1, ExAsc: (f4 & 4) >> 2, ExDsc: (f4 & 8) >> 3 };
  return [fl, miyRw];
}
function parse_Window1(blob) {
  var xWn = blob.read_shift(2), yWn = blob.read_shift(2), dxWn = blob.read_shift(2), dyWn = blob.read_shift(2);
  var flags = blob.read_shift(2), iTabCur = blob.read_shift(2), iTabFirst = blob.read_shift(2);
  var ctabSel = blob.read_shift(2), wTabRatio = blob.read_shift(2);
  return {
    Pos: [xWn, yWn],
    Dim: [dxWn, dyWn],
    Flags: flags,
    CurTab: iTabCur,
    FirstTab: iTabFirst,
    Selected: ctabSel,
    TabRatio: wTabRatio
  };
}
function parse_Window2(blob, length, opts) {
  if (opts && opts.biff >= 2 && opts.biff < 5) return {};
  var f4 = blob.read_shift(2);
  return { RTL: f4 & 64 };
}
function parse_Pane() {
}
function parse_Font(blob, length, opts) {
  var o9 = {
    dyHeight: blob.read_shift(2),
    fl: blob.read_shift(2)
  };
  switch (opts && opts.biff || 8) {
    case 2:
      break;
    case 3:
    case 4:
      blob.l += 2;
      break;
    default:
      blob.l += 10;
      break;
  }
  o9.name = parse_ShortXLUnicodeString(blob, 0, opts);
  return o9;
}
function parse_LabelSst(blob, length, opts) {
  var cell = parse_XLSCell(blob, length, opts);
  cell.isst = blob.read_shift(4);
  return cell;
}
function parse_Label(blob, length, opts) {
  if (opts.biffguess && opts.biff == 2) opts.biff = 5;
  var target = blob.l + length;
  var cell = parse_XLSCell(blob, length, opts);
  var str2 = parse_XLUnicodeString(blob, target - blob.l, opts);
  cell.val = str2;
  return cell;
}
function parse_Format(blob, length, opts) {
  var numFmtId = blob.read_shift(2);
  var fmtstr = parse_XLUnicodeString2(blob, 0, opts);
  return [numFmtId, fmtstr];
}
var parse_BIFF2Format = parse_XLUnicodeString2;
function parse_Dimensions(blob, length, opts) {
  var end = blob.l + length;
  var w3 = opts.biff == 8 || !opts.biff ? 4 : 2;
  var r8 = blob.read_shift(w3), R3 = blob.read_shift(w3);
  var c6 = blob.read_shift(2), C3 = blob.read_shift(2);
  blob.l = end;
  return { s: { r: r8, c: c6 }, e: { r: R3, c: C3 } };
}
function parse_RK(blob) {
  var rw = blob.read_shift(2), col = blob.read_shift(2);
  var rkrec = parse_RkRec(blob);
  return { r: rw, c: col, ixfe: rkrec[0], rknum: rkrec[1] };
}
function parse_MulRk(blob, length) {
  var target = blob.l + length - 2;
  var rw = blob.read_shift(2), col = blob.read_shift(2);
  var rkrecs = [];
  while (blob.l < target) rkrecs.push(parse_RkRec(blob));
  if (blob.l !== target) throw new Error("MulRK read error");
  var lastcol = blob.read_shift(2);
  if (rkrecs.length != lastcol - col + 1) throw new Error("MulRK length mismatch");
  return { r: rw, c: col, C: lastcol, rkrec: rkrecs };
}
function parse_MulBlank(blob, length) {
  var target = blob.l + length - 2;
  var rw = blob.read_shift(2), col = blob.read_shift(2);
  var ixfes = [];
  while (blob.l < target) ixfes.push(blob.read_shift(2));
  if (blob.l !== target) throw new Error("MulBlank read error");
  var lastcol = blob.read_shift(2);
  if (ixfes.length != lastcol - col + 1) throw new Error("MulBlank length mismatch");
  return { r: rw, c: col, C: lastcol, ixfe: ixfes };
}
function parse_CellStyleXF(blob, length, style, opts) {
  var o9 = {};
  var a3 = blob.read_shift(4), b4 = blob.read_shift(4);
  var c6 = blob.read_shift(4), d4 = blob.read_shift(2);
  o9.patternType = XLSFillPattern[c6 >> 26];
  if (!opts.cellStyles) return o9;
  o9.alc = a3 & 7;
  o9.fWrap = a3 >> 3 & 1;
  o9.alcV = a3 >> 4 & 7;
  o9.fJustLast = a3 >> 7 & 1;
  o9.trot = a3 >> 8 & 255;
  o9.cIndent = a3 >> 16 & 15;
  o9.fShrinkToFit = a3 >> 20 & 1;
  o9.iReadOrder = a3 >> 22 & 2;
  o9.fAtrNum = a3 >> 26 & 1;
  o9.fAtrFnt = a3 >> 27 & 1;
  o9.fAtrAlc = a3 >> 28 & 1;
  o9.fAtrBdr = a3 >> 29 & 1;
  o9.fAtrPat = a3 >> 30 & 1;
  o9.fAtrProt = a3 >> 31 & 1;
  o9.dgLeft = b4 & 15;
  o9.dgRight = b4 >> 4 & 15;
  o9.dgTop = b4 >> 8 & 15;
  o9.dgBottom = b4 >> 12 & 15;
  o9.icvLeft = b4 >> 16 & 127;
  o9.icvRight = b4 >> 23 & 127;
  o9.grbitDiag = b4 >> 30 & 3;
  o9.icvTop = c6 & 127;
  o9.icvBottom = c6 >> 7 & 127;
  o9.icvDiag = c6 >> 14 & 127;
  o9.dgDiag = c6 >> 21 & 15;
  o9.icvFore = d4 & 127;
  o9.icvBack = d4 >> 7 & 127;
  o9.fsxButton = d4 >> 14 & 1;
  return o9;
}
function parse_XF(blob, length, opts) {
  var o9 = {};
  o9.ifnt = blob.read_shift(2);
  o9.numFmtId = blob.read_shift(2);
  o9.flags = blob.read_shift(2);
  o9.fStyle = o9.flags >> 2 & 1;
  length -= 6;
  o9.data = parse_CellStyleXF(blob, length, o9.fStyle, opts);
  return o9;
}
function parse_BIFF2XF(blob) {
  var o9 = {};
  o9.ifnt = blob.read_shift(1);
  blob.l++;
  o9.flags = blob.read_shift(1);
  o9.numFmtId = o9.flags & 63;
  o9.flags >>= 6;
  o9.fStyle = 0;
  o9.data = {};
  return o9;
}
function parse_BIFF3XF(blob) {
  var o9 = {};
  o9.ifnt = blob.read_shift(1);
  o9.numFmtId = blob.read_shift(1);
  o9.flags = blob.read_shift(2);
  o9.fStyle = o9.flags >> 2 & 1;
  o9.data = {};
  return o9;
}
function parse_BIFF4XF(blob) {
  var o9 = {};
  o9.ifnt = blob.read_shift(1);
  o9.numFmtId = blob.read_shift(1);
  o9.flags = blob.read_shift(2);
  o9.fStyle = o9.flags >> 2 & 1;
  o9.data = {};
  return o9;
}
function parse_Guts(blob) {
  blob.l += 4;
  var out = [blob.read_shift(2), blob.read_shift(2)];
  if (out[0] !== 0) out[0]--;
  if (out[1] !== 0) out[1]--;
  if (out[0] > 7 || out[1] > 7) throw new Error("Bad Gutters: " + out.join("|"));
  return out;
}
function parse_BoolErr(blob, length, opts) {
  var cell = parse_XLSCell(blob, 6, opts);
  var val2 = parse_Bes(blob, 2);
  cell.val = val2;
  cell.t = val2 === true || val2 === false ? "b" : "e";
  return cell;
}
function parse_Number(blob, length, opts) {
  if (opts.biffguess && opts.biff == 2) opts.biff = 5;
  var cell = parse_XLSCell(blob, 6, opts);
  var xnum = parse_Xnum(blob, 8);
  cell.val = xnum;
  return cell;
}
var parse_XLHeaderFooter = parse_OptXLUnicodeString;
function parse_SupBook(blob, length, opts) {
  var end = blob.l + length;
  var ctab = blob.read_shift(2);
  var cch = blob.read_shift(2);
  opts.sbcch = cch;
  if (cch == 1025 || cch == 14849) return [cch, ctab];
  if (cch < 1 || cch > 255) throw new Error("Unexpected SupBook type: " + cch);
  var virtPath = parse_XLUnicodeStringNoCch(blob, cch);
  var rgst = [];
  while (end > blob.l) rgst.push(parse_XLUnicodeString(blob));
  return [cch, ctab, virtPath, rgst];
}
function parse_ExternName(blob, length, opts) {
  var flags = blob.read_shift(2);
  var body;
  var o9 = {
    fBuiltIn: flags & 1,
    fWantAdvise: flags >>> 1 & 1,
    fWantPict: flags >>> 2 & 1,
    fOle: flags >>> 3 & 1,
    fOleLink: flags >>> 4 & 1,
    cf: flags >>> 5 & 1023,
    fIcon: flags >>> 15 & 1
  };
  if (opts.sbcch === 14849) body = parse_AddinUdf(blob, length - 2, opts);
  o9.body = body || blob.read_shift(length - 2);
  if (typeof body === "string") o9.Name = body;
  return o9;
}
function parse_Lbl(blob, length, opts) {
  var target = blob.l + length;
  var flags = blob.read_shift(2);
  var chKey = blob.read_shift(1);
  var cch = blob.read_shift(1);
  var cce = blob.read_shift(opts && opts.biff == 2 ? 1 : 2);
  var itab = 0;
  if (!opts || opts.biff >= 5) {
    if (opts.biff != 5) blob.l += 2;
    itab = blob.read_shift(2);
    if (opts.biff == 5) blob.l += 2;
    blob.l += 4;
  }
  var name = parse_XLUnicodeStringNoCch(blob, cch, opts);
  if (flags & 32) name = XLSLblBuiltIn[name.charCodeAt(0)];
  var npflen = target - blob.l;
  if (opts && opts.biff == 2) --npflen;
  var rgce = target == blob.l || cce === 0 || !(npflen > 0) ? [] : parse_NameParsedFormula(blob, npflen, opts, cce);
  return {
    chKey,
    Name: name,
    itab,
    rgce
  };
}
function parse_ExternSheet(blob, length, opts) {
  if (opts.biff < 8) return parse_BIFF5ExternSheet(blob, length, opts);
  if (!(opts.biff > 8) && length == blob[blob.l] + (blob[blob.l + 1] == 3 ? 1 : 0) + 1) return parse_BIFF5ExternSheet(blob, length, opts);
  var o9 = [], target = blob.l + length, len = blob.read_shift(opts.biff > 8 ? 4 : 2);
  while (len-- !== 0) o9.push(parse_XTI(blob, opts.biff > 8 ? 12 : 6, opts));
  if (blob.l != target) throw new Error("Bad ExternSheet: " + blob.l + " != " + target);
  return o9;
}
function parse_BIFF5ExternSheet(blob, length, opts) {
  if (blob[blob.l + 1] == 3) blob[blob.l]++;
  var o9 = parse_ShortXLUnicodeString(blob, length, opts);
  return o9.charCodeAt(0) == 3 ? o9.slice(1) : o9;
}
function parse_NameCmt(blob, length, opts) {
  if (opts.biff < 8) {
    blob.l += length;
    return;
  }
  var cchName = blob.read_shift(2);
  var cchComment = blob.read_shift(2);
  var name = parse_XLUnicodeStringNoCch(blob, cchName, opts);
  var comment = parse_XLUnicodeStringNoCch(blob, cchComment, opts);
  return [name, comment];
}
function parse_ShrFmla(blob, length, opts) {
  var ref = parse_RefU(blob, 6);
  blob.l++;
  var cUse = blob.read_shift(1);
  length -= 8;
  return [parse_SharedParsedFormula(blob, length, opts), cUse, ref];
}
function parse_Array(blob, length, opts) {
  var ref = parse_Ref(blob, 6);
  switch (opts.biff) {
    case 2:
      blob.l++;
      length -= 7;
      break;
    case 3:
    case 4:
      blob.l += 2;
      length -= 8;
      break;
    default:
      blob.l += 6;
      length -= 12;
  }
  return [ref, parse_ArrayParsedFormula(blob, length, opts, ref)];
}
function parse_MTRSettings(blob) {
  var fMTREnabled = blob.read_shift(4) !== 0;
  var fUserSetThreadCount = blob.read_shift(4) !== 0;
  var cUserThreadCount = blob.read_shift(4);
  return [fMTREnabled, fUserSetThreadCount, cUserThreadCount];
}
function parse_NoteSh(blob, length, opts) {
  var row = blob.read_shift(2), col = blob.read_shift(2);
  var flags = blob.read_shift(2), idObj = blob.read_shift(2);
  var stAuthor = parse_XLUnicodeString2(blob, 0, opts);
  return [{ r: row, c: col }, stAuthor, idObj, flags];
}
function parse_Note(blob, length, opts) {
  if (opts && opts.biff < 8) {
    var row = blob.read_shift(2), col = blob.read_shift(2);
    if (row == 65535 || row == -1) return;
    var cch = blob.read_shift(2);
    var cmnt = blob.read_shift(Math.min(cch, 2048), "cpstr");
    return [{ r: row, c: col }, cmnt];
  }
  return parse_NoteSh(blob, length, opts);
}
function parse_MergeCells(blob, length) {
  var merges = [];
  var cmcs = blob.read_shift(2);
  while (cmcs--) merges.push(parse_Ref8U(blob, length));
  return merges;
}
function parse_Obj(blob, length, opts) {
  if (opts && opts.biff < 8) return parse_BIFF5Obj(blob, length, opts);
  var cmo = parse_FtCmo(blob, 22);
  var fts = parse_FtArray(blob, length - 22, cmo[1]);
  return { cmo, ft: fts };
}
var parse_BIFF5OT = {
  8: function(blob, length) {
    var tgt = blob.l + length;
    blob.l += 10;
    var cf = blob.read_shift(2);
    blob.l += 4;
    blob.l += 2;
    blob.l += 2;
    blob.l += 2;
    blob.l += 4;
    var cchName = blob.read_shift(1);
    blob.l += cchName;
    blob.l = tgt;
    return { fmt: cf };
  }
};
function parse_BIFF5Obj(blob, length, opts) {
  blob.l += 4;
  var ot = blob.read_shift(2);
  var id = blob.read_shift(2);
  var grbit = blob.read_shift(2);
  blob.l += 2;
  blob.l += 2;
  blob.l += 2;
  blob.l += 2;
  blob.l += 2;
  blob.l += 2;
  blob.l += 2;
  blob.l += 2;
  blob.l += 2;
  blob.l += 6;
  length -= 36;
  var fts = [];
  fts.push((parse_BIFF5OT[ot] || parsenoop)(blob, length, opts));
  return { cmo: [id, ot, grbit], ft: fts };
}
function parse_TxO(blob, length, opts) {
  var s6 = blob.l;
  var texts = "";
  try {
    blob.l += 4;
    var ot = (opts.lastobj || { cmo: [0, 0] }).cmo[1];
    var controlInfo;
    if ([0, 5, 7, 11, 12, 14].indexOf(ot) == -1) blob.l += 6;
    else controlInfo = parse_ControlInfo(blob, 6, opts);
    var cchText = blob.read_shift(2);
    blob.read_shift(2);
    parseuint16(blob, 2);
    var len = blob.read_shift(2);
    blob.l += len;
    for (var i7 = 1; i7 < blob.lens.length - 1; ++i7) {
      if (blob.l - s6 != blob.lens[i7]) throw new Error("TxO: bad continue record");
      var hdr = blob[blob.l];
      var t6 = parse_XLUnicodeStringNoCch(blob, blob.lens[i7 + 1] - blob.lens[i7] - 1);
      texts += t6;
      if (texts.length >= (hdr ? cchText : 2 * cchText)) break;
    }
    if (texts.length !== cchText && texts.length !== cchText * 2) {
      throw new Error("cchText: " + cchText + " != " + texts.length);
    }
    blob.l = s6 + length;
    return { t: texts };
  } catch (e9) {
    blob.l = s6 + length;
    return { t: texts };
  }
}
function parse_HLink(blob, length) {
  var ref = parse_Ref8U(blob, 8);
  blob.l += 16;
  var hlink = parse_Hyperlink(blob, length - 24);
  return [ref, hlink];
}
function parse_HLinkTooltip(blob, length) {
  blob.read_shift(2);
  var ref = parse_Ref8U(blob, 8);
  var wzTooltip = blob.read_shift((length - 10) / 2, "dbcs-cont");
  wzTooltip = wzTooltip.replace(chr0, "");
  return [ref, wzTooltip];
}
function parse_Country(blob) {
  var o9 = [0, 0], d4;
  d4 = blob.read_shift(2);
  o9[0] = CountryEnum[d4] || d4;
  d4 = blob.read_shift(2);
  o9[1] = CountryEnum[d4] || d4;
  return o9;
}
function parse_ClrtClient(blob) {
  var ccv = blob.read_shift(2);
  var o9 = [];
  while (ccv-- > 0) o9.push(parse_LongRGB(blob, 8));
  return o9;
}
function parse_Palette(blob) {
  var ccv = blob.read_shift(2);
  var o9 = [];
  while (ccv-- > 0) o9.push(parse_LongRGB(blob, 8));
  return o9;
}
function parse_XFCRC(blob) {
  blob.l += 2;
  var o9 = { cxfs: 0, crc: 0 };
  o9.cxfs = blob.read_shift(2);
  o9.crc = blob.read_shift(4);
  return o9;
}
function parse_ColInfo(blob, length, opts) {
  if (!opts.cellStyles) return parsenoop(blob, length);
  var w3 = opts && opts.biff >= 12 ? 4 : 2;
  var colFirst = blob.read_shift(w3);
  var colLast = blob.read_shift(w3);
  var coldx = blob.read_shift(w3);
  var ixfe = blob.read_shift(w3);
  var flags = blob.read_shift(2);
  if (w3 == 2) blob.l += 2;
  var o9 = { s: colFirst, e: colLast, w: coldx, ixfe, flags };
  if (opts.biff >= 5 || !opts.biff) o9.level = flags >> 8 & 7;
  return o9;
}
function parse_Setup(blob, length) {
  var o9 = {};
  if (length < 32) return o9;
  blob.l += 16;
  o9.header = parse_Xnum(blob, 8);
  o9.footer = parse_Xnum(blob, 8);
  blob.l += 2;
  return o9;
}
function parse_ShtProps(blob, length, opts) {
  var def = { area: false };
  if (opts.biff != 5) {
    blob.l += length;
    return def;
  }
  var d4 = blob.read_shift(1);
  blob.l += 3;
  if (d4 & 16) def.area = true;
  return def;
}
var parse_Blank = parse_XLSCell;
var parse_Scl = parseuint16a;
var parse_String = parse_XLUnicodeString;
function parse_ImData(blob) {
  var cf = blob.read_shift(2);
  var env = blob.read_shift(2);
  var lcb = blob.read_shift(4);
  var o9 = { fmt: cf, env, len: lcb, data: blob.slice(blob.l, blob.l + lcb) };
  blob.l += lcb;
  return o9;
}
function parse_BIFF2STR(blob, length, opts) {
  if (opts.biffguess && opts.biff == 5) opts.biff = 2;
  var cell = parse_XLSCell(blob, 7, opts);
  var str2 = parse_XLUnicodeString2(blob, length - 7, opts);
  cell.t = "str";
  cell.val = str2;
  return cell;
}
function parse_BIFF2NUM(blob, length, opts) {
  var cell = parse_XLSCell(blob, 7, opts);
  var num = parse_Xnum(blob, 8);
  cell.t = "n";
  cell.val = num;
  return cell;
}
function parse_BIFF2INT(blob, length, opts) {
  var cell = parse_XLSCell(blob, 7, opts);
  var num = blob.read_shift(2);
  cell.t = "n";
  cell.val = num;
  return cell;
}
function parse_BIFF2STRING(blob) {
  var cch = blob.read_shift(1);
  if (cch === 0) {
    blob.l++;
    return "";
  }
  return blob.read_shift(cch, "sbcs-cont");
}
function parse_BIFF2BOOLERR(blob, length, opts) {
  var bestart = blob.l + 7;
  var cell = parse_XLSCell(blob, 6, opts);
  blob.l = bestart;
  var val2 = parse_Bes(blob, 2);
  cell.val = val2;
  cell.t = val2 === true || val2 === false ? "b" : "e";
  return cell;
}
function parse_BIFF2FONTXTRA(blob, length) {
  blob.l += 6;
  blob.l += 2;
  blob.l += 1;
  blob.l += 3;
  blob.l += 1;
  blob.l += length - 13;
}
function parse_RString(blob, length, opts) {
  var end = blob.l + length;
  var cell = parse_XLSCell(blob, 6, opts);
  var cch = blob.read_shift(2);
  var str2 = parse_XLUnicodeStringNoCch(blob, cch, opts);
  blob.l = end;
  cell.t = "str";
  cell.val = str2;
  return cell;
}
function parse_BIFF4SheetInfo(blob) {
  var flags = blob.read_shift(4);
  var cch = blob.read_shift(1), name = blob.read_shift(cch, "sbcs");
  if (name.length === 0) name = "Sheet1";
  return { flags, name };
}
var DBF_SUPPORTED_VERSIONS = [2, 3, 48, 49, 131, 139, 140, 245];
var DBF = /* @__PURE__ */ (function() {
  var dbf_codepage_map = {
    /* Code Pages Supported by Visual FoxPro */
    1: 437,
    2: 850,
    3: 1252,
    4: 1e4,
    100: 852,
    101: 866,
    102: 865,
    103: 861,
    104: 895,
    105: 620,
    106: 737,
    107: 857,
    120: 950,
    121: 949,
    122: 936,
    123: 932,
    124: 874,
    125: 1255,
    126: 1256,
    150: 10007,
    151: 10029,
    152: 10006,
    200: 1250,
    201: 1251,
    202: 1254,
    203: 1253,
    /* shapefile DBF extension */
    0: 20127,
    8: 865,
    9: 437,
    10: 850,
    11: 437,
    13: 437,
    14: 850,
    15: 437,
    16: 850,
    17: 437,
    18: 850,
    19: 932,
    20: 850,
    21: 437,
    22: 850,
    23: 865,
    24: 437,
    25: 437,
    26: 850,
    27: 437,
    28: 863,
    29: 850,
    31: 852,
    34: 852,
    35: 852,
    36: 860,
    37: 850,
    38: 866,
    55: 850,
    64: 852,
    77: 936,
    78: 949,
    79: 950,
    80: 874,
    87: 1252,
    88: 1252,
    89: 1252,
    108: 863,
    134: 737,
    135: 852,
    136: 857,
    204: 1257,
    255: 16969
  };
  var dbf_reverse_map = evert({
    1: 437,
    2: 850,
    3: 1252,
    4: 1e4,
    100: 852,
    101: 866,
    102: 865,
    103: 861,
    104: 895,
    105: 620,
    106: 737,
    107: 857,
    120: 950,
    121: 949,
    122: 936,
    123: 932,
    124: 874,
    125: 1255,
    126: 1256,
    150: 10007,
    151: 10029,
    152: 10006,
    200: 1250,
    201: 1251,
    202: 1254,
    203: 1253,
    0: 20127
  });
  function dbf_to_aoa(buf, opts) {
    var out = [];
    var d4 = new_raw_buf(1);
    switch (opts.type) {
      case "base64":
        d4 = s2a(Base64_decode(buf));
        break;
      case "binary":
        d4 = s2a(buf);
        break;
      case "buffer":
      case "array":
        d4 = buf;
        break;
    }
    prep_blob(d4, 0);
    var ft = d4.read_shift(1);
    var memo = !!(ft & 136);
    var vfp = false, l7 = false;
    switch (ft) {
      case 2:
        break;
      // dBASE II
      case 3:
        break;
      // dBASE III
      case 48:
        vfp = true;
        memo = true;
        break;
      // VFP
      case 49:
        vfp = true;
        memo = true;
        break;
      // VFP with autoincrement
      // 0x43 dBASE IV SQL table files
      // 0x63 dBASE IV SQL system files
      case 131:
        break;
      // dBASE III with memo
      case 139:
        break;
      // dBASE IV with memo
      case 140:
        l7 = true;
        break;
      // dBASE Level 7 with memo
      // case 0xCB dBASE IV SQL table files with memo
      case 245:
        break;
      // FoxPro 2.x with memo
      // case 0xFB FoxBASE
      default:
        throw new Error("DBF Unsupported Version: " + ft.toString(16));
    }
    var nrow = 0, fpos = 521;
    if (ft == 2) nrow = d4.read_shift(2);
    d4.l += 3;
    if (ft != 2) nrow = d4.read_shift(4);
    if (nrow > 1048576) nrow = 1e6;
    if (ft != 2) fpos = d4.read_shift(2);
    var rlen = d4.read_shift(2);
    var current_cp = opts.codepage || 1252;
    if (ft != 2) {
      d4.l += 16;
      d4.read_shift(1);
      if (d4[d4.l] !== 0) current_cp = dbf_codepage_map[d4[d4.l]];
      d4.l += 1;
      d4.l += 2;
    }
    if (l7) d4.l += 36;
    var fields = [], field = {};
    var hend = Math.min(d4.length, ft == 2 ? 521 : fpos - 10 - (vfp ? 264 : 0));
    var ww = l7 ? 32 : 11;
    while (d4.l < hend && d4[d4.l] != 13) {
      field = {};
      field.name = (typeof $cptable !== "undefined" ? $cptable.utils.decode(current_cp, d4.slice(d4.l, d4.l + ww)) : a2s(d4.slice(d4.l, d4.l + ww))).replace(/[\u0000\r\n][\S\s]*$/g, "");
      d4.l += ww;
      field.type = String.fromCharCode(d4.read_shift(1));
      if (ft != 2 && !l7) field.offset = d4.read_shift(4);
      field.len = d4.read_shift(1);
      if (ft == 2) field.offset = d4.read_shift(2);
      field.dec = d4.read_shift(1);
      if (field.name.length) fields.push(field);
      if (ft != 2) d4.l += l7 ? 13 : 14;
      switch (field.type) {
        case "B":
          if ((!vfp || field.len != 8) && opts.WTF) console.log("Skipping " + field.name + ":" + field.type);
          break;
        case "G":
        // General (FoxPro and dBASE L7)
        case "P":
          if (opts.WTF) console.log("Skipping " + field.name + ":" + field.type);
          break;
        case "+":
        // Autoincrement (dBASE L7 only)
        case "0":
        // _NullFlags (VFP only)
        case "@":
        // Timestamp (dBASE L7 only)
        case "C":
        // Character (dBASE II)
        case "D":
        // Date (dBASE III)
        case "F":
        // Float (dBASE IV)
        case "I":
        // Long (VFP and dBASE L7)
        case "L":
        // Logical (dBASE II)
        case "M":
        // Memo (dBASE III)
        case "N":
        // Number (dBASE II)
        case "O":
        // Double (dBASE L7 only)
        case "T":
        // Datetime (VFP only)
        case "Y":
          break;
        default:
          throw new Error("Unknown Field Type: " + field.type);
      }
    }
    if (d4[d4.l] !== 13) d4.l = fpos - 1;
    if (d4.read_shift(1) !== 13) throw new Error("DBF Terminator not found " + d4.l + " " + d4[d4.l]);
    d4.l = fpos;
    var R3 = 0, C3 = 0;
    out[0] = [];
    for (C3 = 0; C3 != fields.length; ++C3) out[0][C3] = fields[C3].name;
    while (nrow-- > 0) {
      if (d4[d4.l] === 42) {
        d4.l += rlen;
        continue;
      }
      ++d4.l;
      out[++R3] = [];
      C3 = 0;
      for (C3 = 0; C3 != fields.length; ++C3) {
        var dd = d4.slice(d4.l, d4.l + fields[C3].len);
        d4.l += fields[C3].len;
        prep_blob(dd, 0);
        var s6 = typeof $cptable !== "undefined" ? $cptable.utils.decode(current_cp, dd) : a2s(dd);
        switch (fields[C3].type) {
          case "C":
            if (s6.trim().length) out[R3][C3] = s6.replace(/([^\s])\s+$/, "$1");
            break;
          case "D":
            if (s6.length === 8) {
              out[R3][C3] = new Date(Date.UTC(+s6.slice(0, 4), +s6.slice(4, 6) - 1, +s6.slice(6, 8), 0, 0, 0, 0));
              if (!(opts && opts.UTC)) {
                out[R3][C3] = utc_to_local(out[R3][C3]);
              }
            } else out[R3][C3] = s6;
            break;
          case "F":
            out[R3][C3] = parseFloat(s6.trim());
            break;
          case "+":
          case "I":
            out[R3][C3] = l7 ? dd.read_shift(-4, "i") ^ 2147483648 : dd.read_shift(4, "i");
            break;
          case "L":
            switch (s6.trim().toUpperCase()) {
              case "Y":
              case "T":
                out[R3][C3] = true;
                break;
              case "N":
              case "F":
                out[R3][C3] = false;
                break;
              case "":
              case "\0":
              case "?":
                break;
              default:
                throw new Error("DBF Unrecognized L:|" + s6 + "|");
            }
            break;
          case "M":
            if (!memo) throw new Error("DBF Unexpected MEMO for type " + ft.toString(16));
            out[R3][C3] = "##MEMO##" + (l7 ? parseInt(s6.trim(), 10) : dd.read_shift(4));
            break;
          case "N":
            s6 = s6.replace(/\u0000/g, "").trim();
            if (s6 && s6 != ".") out[R3][C3] = +s6 || 0;
            break;
          case "@":
            out[R3][C3] = new Date(dd.read_shift(-8, "f") - 621356832e5);
            break;
          case "T":
            {
              var hi = dd.read_shift(4), lo = dd.read_shift(4);
              if (hi == 0 && lo == 0) break;
              out[R3][C3] = new Date((hi - 2440588) * 864e5 + lo);
              if (!(opts && opts.UTC)) out[R3][C3] = utc_to_local(out[R3][C3]);
            }
            break;
          case "Y":
            out[R3][C3] = dd.read_shift(4, "i") / 1e4 + dd.read_shift(4, "i") / 1e4 * Math.pow(2, 32);
            break;
          case "O":
            out[R3][C3] = -dd.read_shift(-8, "f");
            break;
          case "B":
            if (vfp && fields[C3].len == 8) {
              out[R3][C3] = dd.read_shift(8, "f");
              break;
            }
          /* falls through */
          case "G":
          case "P":
            dd.l += fields[C3].len;
            break;
          case "0":
            if (fields[C3].name === "_NullFlags") break;
          /* falls through */
          default:
            throw new Error("DBF Unsupported data type " + fields[C3].type);
        }
      }
    }
    if (ft != 2) {
      if (d4.l < d4.length && d4[d4.l++] != 26) throw new Error("DBF EOF Marker missing " + (d4.l - 1) + " of " + d4.length + " " + d4[d4.l - 1].toString(16));
    }
    if (opts && opts.sheetRows) out = out.slice(0, opts.sheetRows);
    opts.DBF = fields;
    return out;
  }
  function dbf_to_sheet(buf, opts) {
    var o9 = opts || {};
    if (!o9.dateNF) o9.dateNF = "yyyymmdd";
    var ws = aoa_to_sheet(dbf_to_aoa(buf, o9), o9);
    ws["!cols"] = o9.DBF.map(function(field) {
      return {
        wch: field.len,
        DBF: field
      };
    });
    delete o9.DBF;
    return ws;
  }
  function dbf_to_workbook(buf, opts) {
    try {
      var o9 = sheet_to_workbook(dbf_to_sheet(buf, opts), opts);
      o9.bookType = "dbf";
      return o9;
    } catch (e9) {
      if (opts && opts.WTF) throw e9;
    }
    return { SheetNames: [], Sheets: {} };
  }
  var _RLEN = { "B": 8, "C": 250, "L": 1, "D": 8, "?": 0, "": 0 };
  function sheet_to_dbf(ws, opts) {
    if (!ws["!ref"]) throw new Error("Cannot export empty sheet to DBF");
    var o9 = opts || {};
    var old_cp = current_codepage;
    if (+o9.codepage >= 0) set_cp(+o9.codepage);
    if (o9.type == "string") throw new Error("Cannot write DBF to JS string");
    var ba = buf_array();
    var aoa = sheet_to_json(ws, { header: 1, raw: true, cellDates: true });
    var headers = aoa[0], data = aoa.slice(1), cols = ws["!cols"] || [];
    var i7 = 0, j3 = 0, hcnt = 0, rlen = 1;
    for (i7 = 0; i7 < headers.length; ++i7) {
      if (((cols[i7] || {}).DBF || {}).name) {
        headers[i7] = cols[i7].DBF.name;
        ++hcnt;
        continue;
      }
      if (headers[i7] == null) continue;
      ++hcnt;
      if (typeof headers[i7] === "number") headers[i7] = headers[i7].toString(10);
      if (typeof headers[i7] !== "string") throw new Error("DBF Invalid column name " + headers[i7] + " |" + typeof headers[i7] + "|");
      if (headers.indexOf(headers[i7]) !== i7) {
        for (j3 = 0; j3 < 1024; ++j3)
          if (headers.indexOf(headers[i7] + "_" + j3) == -1) {
            headers[i7] += "_" + j3;
            break;
          }
      }
    }
    var range2 = safe_decode_range(ws["!ref"]);
    var coltypes = [];
    var colwidths = [];
    var coldecimals = [];
    for (i7 = 0; i7 <= range2.e.c - range2.s.c; ++i7) {
      var guess = "", _guess = "", maxlen = 0;
      var col = [];
      for (j3 = 0; j3 < data.length; ++j3) {
        if (data[j3][i7] != null) col.push(data[j3][i7]);
      }
      if (col.length == 0 || headers[i7] == null) {
        coltypes[i7] = "?";
        continue;
      }
      for (j3 = 0; j3 < col.length; ++j3) {
        switch (typeof col[j3]) {
          /* TODO: check if L2 compat is desired */
          case "number":
            _guess = "B";
            break;
          case "string":
            _guess = "C";
            break;
          case "boolean":
            _guess = "L";
            break;
          case "object":
            _guess = col[j3] instanceof Date ? "D" : "C";
            break;
          default:
            _guess = "C";
        }
        maxlen = Math.max(maxlen, (typeof $cptable !== "undefined" && typeof col[j3] == "string" ? $cptable.utils.encode(current_ansi, col[j3]) : String(col[j3])).length);
        guess = guess && guess != _guess ? "C" : _guess;
      }
      if (maxlen > 250) maxlen = 250;
      _guess = ((cols[i7] || {}).DBF || {}).type;
      if (_guess == "C") {
        if (cols[i7].DBF.len > maxlen) maxlen = cols[i7].DBF.len;
      }
      if (guess == "B" && _guess == "N") {
        guess = "N";
        coldecimals[i7] = cols[i7].DBF.dec;
        maxlen = cols[i7].DBF.len;
      }
      colwidths[i7] = guess == "C" || _guess == "N" ? maxlen : _RLEN[guess] || 0;
      rlen += colwidths[i7];
      coltypes[i7] = guess;
    }
    var h7 = ba.next(32);
    h7.write_shift(4, 318902576);
    h7.write_shift(4, data.length);
    h7.write_shift(2, 296 + 32 * hcnt);
    h7.write_shift(2, rlen);
    for (i7 = 0; i7 < 4; ++i7) h7.write_shift(4, 0);
    var cp = +dbf_reverse_map[
      /*::String(*/
      current_codepage
      /*::)*/
    ] || 3;
    h7.write_shift(4, 0 | cp << 8);
    if (dbf_codepage_map[cp] != +o9.codepage) {
      if (o9.codepage) console.error("DBF Unsupported codepage " + current_codepage + ", using 1252");
      current_codepage = 1252;
    }
    for (i7 = 0, j3 = 0; i7 < headers.length; ++i7) {
      if (headers[i7] == null) continue;
      var hf = ba.next(32);
      var _f = (headers[i7].slice(-10) + "\0\0\0\0\0\0\0\0\0\0\0").slice(0, 11);
      hf.write_shift(1, _f, "sbcs");
      hf.write_shift(1, coltypes[i7] == "?" ? "C" : coltypes[i7], "sbcs");
      hf.write_shift(4, j3);
      hf.write_shift(1, colwidths[i7] || _RLEN[coltypes[i7]] || 0);
      hf.write_shift(1, coldecimals[i7] || 0);
      hf.write_shift(1, 2);
      hf.write_shift(4, 0);
      hf.write_shift(1, 0);
      hf.write_shift(4, 0);
      hf.write_shift(4, 0);
      j3 += colwidths[i7] || _RLEN[coltypes[i7]] || 0;
    }
    var hb = ba.next(264);
    hb.write_shift(4, 13);
    for (i7 = 0; i7 < 65; ++i7) hb.write_shift(4, 0);
    for (i7 = 0; i7 < data.length; ++i7) {
      var rout = ba.next(rlen);
      rout.write_shift(1, 0);
      for (j3 = 0; j3 < headers.length; ++j3) {
        if (headers[j3] == null) continue;
        switch (coltypes[j3]) {
          case "L":
            rout.write_shift(1, data[i7][j3] == null ? 63 : data[i7][j3] ? 84 : 70);
            break;
          case "B":
            rout.write_shift(8, data[i7][j3] || 0, "f");
            break;
          case "N":
            var _n = "0";
            if (typeof data[i7][j3] == "number") _n = data[i7][j3].toFixed(coldecimals[j3] || 0);
            if (_n.length > colwidths[j3]) _n = _n.slice(0, colwidths[j3]);
            for (hcnt = 0; hcnt < colwidths[j3] - _n.length; ++hcnt) rout.write_shift(1, 32);
            rout.write_shift(1, _n, "sbcs");
            break;
          case "D":
            if (!data[i7][j3]) rout.write_shift(8, "00000000", "sbcs");
            else {
              rout.write_shift(4, ("0000" + data[i7][j3].getFullYear()).slice(-4), "sbcs");
              rout.write_shift(2, ("00" + (data[i7][j3].getMonth() + 1)).slice(-2), "sbcs");
              rout.write_shift(2, ("00" + data[i7][j3].getDate()).slice(-2), "sbcs");
            }
            break;
          case "C":
            var _l = rout.l;
            var _s = String(data[i7][j3] != null ? data[i7][j3] : "").slice(0, colwidths[j3]);
            rout.write_shift(1, _s, "cpstr");
            _l += colwidths[j3] - rout.l;
            for (hcnt = 0; hcnt < _l; ++hcnt) rout.write_shift(1, 32);
            break;
        }
      }
    }
    current_codepage = old_cp;
    ba.next(1).write_shift(1, 26);
    return ba.end();
  }
  return {
    to_workbook: dbf_to_workbook,
    to_sheet: dbf_to_sheet,
    from_sheet: sheet_to_dbf
  };
})();
var SYLK = /* @__PURE__ */ (function() {
  var sylk_escapes = {
    AA: "\xC0",
    BA: "\xC1",
    CA: "\xC2",
    DA: 195,
    HA: "\xC4",
    JA: 197,
    AE: "\xC8",
    BE: "\xC9",
    CE: "\xCA",
    HE: "\xCB",
    AI: "\xCC",
    BI: "\xCD",
    CI: "\xCE",
    HI: "\xCF",
    AO: "\xD2",
    BO: "\xD3",
    CO: "\xD4",
    DO: 213,
    HO: "\xD6",
    AU: "\xD9",
    BU: "\xDA",
    CU: "\xDB",
    HU: "\xDC",
    Aa: "\xE0",
    Ba: "\xE1",
    Ca: "\xE2",
    Da: 227,
    Ha: "\xE4",
    Ja: 229,
    Ae: "\xE8",
    Be: "\xE9",
    Ce: "\xEA",
    He: "\xEB",
    Ai: "\xEC",
    Bi: "\xED",
    Ci: "\xEE",
    Hi: "\xEF",
    Ao: "\xF2",
    Bo: "\xF3",
    Co: "\xF4",
    Do: 245,
    Ho: "\xF6",
    Au: "\xF9",
    Bu: "\xFA",
    Cu: "\xFB",
    Hu: "\xFC",
    KC: "\xC7",
    Kc: "\xE7",
    q: "\xE6",
    z: "\u0153",
    a: "\xC6",
    j: "\u0152",
    DN: 209,
    Dn: 241,
    Hy: 255,
    S: 169,
    c: 170,
    R: 174,
    "B ": 180,
    0: 176,
    1: 177,
    2: 178,
    3: 179,
    5: 181,
    6: 182,
    7: 183,
    Q: 185,
    k: 186,
    b: 208,
    i: 216,
    l: 222,
    s: 240,
    y: 248,
    "!": 161,
    '"': 162,
    "#": 163,
    "(": 164,
    "%": 165,
    "'": 167,
    "H ": 168,
    "+": 171,
    ";": 187,
    "<": 188,
    "=": 189,
    ">": 190,
    "?": 191,
    "{": 223
  };
  var sylk_char_regex = new RegExp("\x1BN(" + keys(sylk_escapes).join("|").replace(/\|\|\|/, "|\\||").replace(/([?()+])/g, "\\$1").replace("{", "\\{") + "|\\|)", "gm");
  try {
    sylk_char_regex = new RegExp("\x1BN(" + keys(sylk_escapes).join("|").replace(/\|\|\|/, "|\\||").replace(/([?()+])/g, "\\$1") + "|\\|)", "gm");
  } catch (e9) {
  }
  var sylk_char_fn = function(_3, $1) {
    var o9 = sylk_escapes[$1];
    return typeof o9 == "number" ? _getansi(o9) : o9;
  };
  var decode_sylk_char = function($$, $1, $22) {
    var newcc = $1.charCodeAt(0) - 32 << 4 | $22.charCodeAt(0) - 48;
    return newcc == 59 ? $$ : _getansi(newcc);
  };
  sylk_escapes["|"] = 254;
  var encode_sylk_str = function($$) {
    return $$.replace(/\n/g, "\x1B :").replace(/\r/g, "\x1B =");
  };
  function sylk_to_aoa(d4, opts) {
    switch (opts.type) {
      case "base64":
        return sylk_to_aoa_str(Base64_decode(d4), opts);
      case "binary":
        return sylk_to_aoa_str(d4, opts);
      case "buffer":
        return sylk_to_aoa_str(has_buf && Buffer.isBuffer(d4) ? d4.toString("binary") : a2s(d4), opts);
      case "array":
        return sylk_to_aoa_str(cc2str(d4), opts);
    }
    throw new Error("Unrecognized type " + opts.type);
  }
  function sylk_to_aoa_str(str2, opts) {
    var records = str2.split(/[\n\r]+/), R3 = -1, C3 = -1, ri = 0, rj = 0, arr = [];
    var formats = [];
    var next_cell_format = null;
    var sht = {}, rowinfo = [], colinfo = [], cw = [];
    var Mval = 0, j3;
    var wb = { Workbook: { WBProps: {}, Names: [] } };
    if (+opts.codepage >= 0) set_cp(+opts.codepage);
    for (; ri !== records.length; ++ri) {
      Mval = 0;
      var rstr = records[ri].trim().replace(/\x1B([\x20-\x2F])([\x30-\x3F])/g, decode_sylk_char).replace(sylk_char_regex, sylk_char_fn);
      var record = rstr.replace(/;;/g, "\0").split(";").map(function(x2) {
        return x2.replace(/\u0000/g, ";");
      });
      var RT = record[0], val2;
      if (rstr.length > 0) switch (RT) {
        case "ID":
          break;
        /* header */
        case "E":
          break;
        /* EOF */
        case "B":
          break;
        /* dimensions */
        case "O":
          for (rj = 1; rj < record.length; ++rj) switch (record[rj].charAt(0)) {
            case "V":
              {
                var d1904 = parseInt(record[rj].slice(1), 10);
                if (d1904 >= 1 && d1904 <= 4) wb.Workbook.WBProps.date1904 = true;
              }
              break;
          }
          break;
        case "W":
          break;
        /* window */
        case "P":
          switch (record[1].charAt(0)) {
            case "P":
              formats.push(rstr.slice(3).replace(/;;/g, ";"));
              break;
          }
          break;
        case "NN":
          {
            var nn = { Sheet: 0 };
            for (rj = 1; rj < record.length; ++rj) switch (record[rj].charAt(0)) {
              case "N":
                nn.Name = record[rj].slice(1);
                break;
              case "E":
                nn.Ref = (opts && opts.sheet || "Sheet1") + "!" + rc_to_a1(record[rj].slice(1));
                break;
            }
            wb.Workbook.Names.push(nn);
          }
          break;
        // case 'NE': // ??
        // case 'NU': // ??
        case "C":
          var C_seen_K = false, C_seen_X = false, C_seen_S = false, C_seen_E = false, _R = -1, _C = -1, formula = "", cell_t = "z";
          var cmnt = "";
          for (rj = 1; rj < record.length; ++rj) switch (record[rj].charAt(0)) {
            case "A":
              cmnt = record[rj].slice(1);
              break;
            // TODO: comment
            case "X":
              C3 = parseInt(record[rj].slice(1), 10) - 1;
              C_seen_X = true;
              break;
            case "Y":
              R3 = parseInt(record[rj].slice(1), 10) - 1;
              if (!C_seen_X) C3 = 0;
              for (j3 = arr.length; j3 <= R3; ++j3) arr[j3] = [];
              break;
            case "K":
              val2 = record[rj].slice(1);
              if (val2.charAt(0) === '"') {
                val2 = val2.slice(1, val2.length - 1);
                cell_t = "s";
              } else if (val2 === "TRUE" || val2 === "FALSE") {
                val2 = val2 === "TRUE";
                cell_t = "b";
              } else if (val2.charAt(0) == "#" && RBErr[val2] != null) {
                cell_t = "e";
                val2 = RBErr[val2];
              } else if (!isNaN(fuzzynum(val2))) {
                val2 = fuzzynum(val2);
                cell_t = "n";
                if (next_cell_format !== null && fmt_is_date(next_cell_format) && opts.cellDates) {
                  val2 = numdate(wb.Workbook.WBProps.date1904 ? val2 + 1462 : val2);
                  cell_t = typeof val2 == "number" ? "n" : "d";
                }
              }
              if (typeof $cptable !== "undefined" && typeof val2 == "string" && (opts || {}).type != "string" && (opts || {}).codepage) val2 = $cptable.utils.decode(opts.codepage, val2);
              C_seen_K = true;
              break;
            case "E":
              C_seen_E = true;
              formula = rc_to_a1(record[rj].slice(1), { r: R3, c: C3 });
              break;
            case "S":
              C_seen_S = true;
              break;
            case "G":
              break;
            // unknown
            case "R":
              _R = parseInt(record[rj].slice(1), 10) - 1;
              break;
            case "C":
              _C = parseInt(record[rj].slice(1), 10) - 1;
              break;
            // case 'P': // ??
            // case 'D': // ??
            default:
              if (opts && opts.WTF) throw new Error("SYLK bad record " + rstr);
          }
          if (C_seen_K) {
            if (!arr[R3][C3]) arr[R3][C3] = { t: cell_t, v: val2 };
            else {
              arr[R3][C3].t = cell_t;
              arr[R3][C3].v = val2;
            }
            if (next_cell_format) arr[R3][C3].z = next_cell_format;
            if (opts.cellText !== false && next_cell_format) arr[R3][C3].w = SSF_format(arr[R3][C3].z, arr[R3][C3].v, { date1904: wb.Workbook.WBProps.date1904 });
            next_cell_format = null;
          }
          if (C_seen_S) {
            if (C_seen_E) throw new Error("SYLK shared formula cannot have own formula");
            var shrbase = _R > -1 && arr[_R][_C];
            if (!shrbase || !shrbase[1]) throw new Error("SYLK shared formula cannot find base");
            formula = shift_formula_str(shrbase[1], { r: R3 - _R, c: C3 - _C });
          }
          if (formula) {
            if (!arr[R3][C3]) arr[R3][C3] = { t: "n", f: formula };
            else arr[R3][C3].f = formula;
          }
          if (cmnt) {
            if (!arr[R3][C3]) arr[R3][C3] = { t: "z" };
            arr[R3][C3].c = [{ a: "SheetJSYLK", t: cmnt }];
          }
          break;
        case "F":
          var F_seen = 0;
          for (rj = 1; rj < record.length; ++rj) switch (record[rj].charAt(0)) {
            case "X":
              C3 = parseInt(record[rj].slice(1), 10) - 1;
              ++F_seen;
              break;
            case "Y":
              R3 = parseInt(record[rj].slice(1), 10) - 1;
              for (j3 = arr.length; j3 <= R3; ++j3) arr[j3] = [];
              break;
            case "M":
              Mval = parseInt(record[rj].slice(1), 10) / 20;
              break;
            case "F":
              break;
            /* ??? */
            case "G":
              break;
            /* hide grid */
            case "P":
              next_cell_format = formats[parseInt(record[rj].slice(1), 10)];
              break;
            case "S":
              break;
            /* cell style */
            case "D":
              break;
            /* column */
            case "N":
              break;
            /* font */
            case "W":
              cw = record[rj].slice(1).split(" ");
              for (j3 = parseInt(cw[0], 10); j3 <= parseInt(cw[1], 10); ++j3) {
                Mval = parseInt(cw[2], 10);
                colinfo[j3 - 1] = Mval === 0 ? { hidden: true } : { wch: Mval };
              }
              break;
            case "C":
              C3 = parseInt(record[rj].slice(1), 10) - 1;
              if (!colinfo[C3]) colinfo[C3] = {};
              break;
            case "R":
              R3 = parseInt(record[rj].slice(1), 10) - 1;
              if (!rowinfo[R3]) rowinfo[R3] = {};
              if (Mval > 0) {
                rowinfo[R3].hpt = Mval;
                rowinfo[R3].hpx = pt2px(Mval);
              } else if (Mval === 0) rowinfo[R3].hidden = true;
              break;
            // case 'K': // ??
            // case 'E': // ??
            default:
              if (opts && opts.WTF) throw new Error("SYLK bad record " + rstr);
          }
          if (F_seen < 1) next_cell_format = null;
          break;
        default:
          if (opts && opts.WTF) throw new Error("SYLK bad record " + rstr);
      }
    }
    if (rowinfo.length > 0) sht["!rows"] = rowinfo;
    if (colinfo.length > 0) sht["!cols"] = colinfo;
    colinfo.forEach(function(col) {
      process_col(col);
    });
    if (opts && opts.sheetRows) arr = arr.slice(0, opts.sheetRows);
    return [arr, sht, wb];
  }
  function sylk_to_workbook(d4, opts) {
    var aoasht = sylk_to_aoa(d4, opts);
    var aoa = aoasht[0], ws = aoasht[1], wb = aoasht[2];
    var _opts = dup(opts);
    _opts.date1904 = (((wb || {}).Workbook || {}).WBProps || {}).date1904;
    var o9 = aoa_to_sheet(aoa, _opts);
    keys(ws).forEach(function(k2) {
      o9[k2] = ws[k2];
    });
    var outwb = sheet_to_workbook(o9, opts);
    keys(wb).forEach(function(k2) {
      outwb[k2] = wb[k2];
    });
    outwb.bookType = "sylk";
    return outwb;
  }
  function write_ws_cell_sylk(cell, ws, R3, C3, opts, date1904) {
    var o9 = "C;Y" + (R3 + 1) + ";X" + (C3 + 1) + ";K";
    switch (cell.t) {
      case "n":
        o9 += isFinite(cell.v) ? cell.v || 0 : BErr[isNaN(cell.v) ? 36 : 7];
        if (cell.f && !cell.F) o9 += ";E" + a1_to_rc(cell.f, { r: R3, c: C3 });
        break;
      case "b":
        o9 += cell.v ? "TRUE" : "FALSE";
        break;
      case "e":
        o9 += cell.w || BErr[cell.v] || cell.v;
        break;
      case "d":
        o9 += datenum(parseDate(cell.v, date1904), date1904);
        break;
      case "s":
        o9 += '"' + (cell.v == null ? "" : String(cell.v)).replace(/"/g, "").replace(/;/g, ";;") + '"';
        break;
    }
    return o9;
  }
  function write_ws_cmnt_sylk(cmnt, R3, C3) {
    var o9 = "C;Y" + (R3 + 1) + ";X" + (C3 + 1) + ";A";
    o9 += encode_sylk_str(cmnt.map(function(c6) {
      return c6.t;
    }).join(""));
    return o9;
  }
  function write_ws_cols_sylk(out, cols) {
    cols.forEach(function(col, i7) {
      var rec = "F;W" + (i7 + 1) + " " + (i7 + 1) + " ";
      if (col.hidden) rec += "0";
      else {
        if (typeof col.width == "number" && !col.wpx) col.wpx = width2px(col.width);
        if (typeof col.wpx == "number" && !col.wch) col.wch = px2char(col.wpx);
        if (typeof col.wch == "number") rec += Math.round(col.wch);
      }
      if (rec.charAt(rec.length - 1) != " ") out.push(rec);
    });
  }
  function write_ws_rows_sylk(out, rows) {
    rows.forEach(function(row, i7) {
      var rec = "F;";
      if (row.hidden) rec += "M0;";
      else if (row.hpt) rec += "M" + 20 * row.hpt + ";";
      else if (row.hpx) rec += "M" + 20 * px2pt(row.hpx) + ";";
      if (rec.length > 2) out.push(rec + "R" + (i7 + 1));
    });
  }
  function sheet_to_sylk(ws, opts, wb) {
    if (!opts) opts = {};
    opts._formats = ["General"];
    var preamble = ["ID;PSheetJS;N;E"], o9 = [];
    var r8 = safe_decode_range(ws["!ref"] || "A1"), cell;
    var dense = ws["!data"] != null;
    var RS = "\r\n";
    var d1904 = (((wb || {}).Workbook || {}).WBProps || {}).date1904;
    var _lastfmt = "General";
    preamble.push("P;PGeneral");
    var R3 = r8.s.r, C3 = r8.s.c, p4 = [];
    if (ws["!ref"]) for (R3 = r8.s.r; R3 <= r8.e.r; ++R3) {
      if (dense && !ws["!data"][R3]) continue;
      p4 = [];
      for (C3 = r8.s.c; C3 <= r8.e.c; ++C3) {
        cell = dense ? ws["!data"][R3][C3] : ws[encode_col(C3) + encode_row(R3)];
        if (!cell || !cell.c) continue;
        p4.push(write_ws_cmnt_sylk(cell.c, R3, C3));
      }
      if (p4.length) o9.push(p4.join(RS));
    }
    if (ws["!ref"]) for (R3 = r8.s.r; R3 <= r8.e.r; ++R3) {
      if (dense && !ws["!data"][R3]) continue;
      p4 = [];
      for (C3 = r8.s.c; C3 <= r8.e.c; ++C3) {
        cell = dense ? ws["!data"][R3][C3] : ws[encode_col(C3) + encode_row(R3)];
        if (!cell || cell.v == null && (!cell.f || cell.F)) continue;
        if ((cell.z || (cell.t == "d" ? table_fmt[14] : "General")) != _lastfmt) {
          var ifmt = opts._formats.indexOf(cell.z);
          if (ifmt == -1) {
            opts._formats.push(cell.z);
            ifmt = opts._formats.length - 1;
            preamble.push("P;P" + cell.z.replace(/;/g, ";;"));
          }
          p4.push("F;P" + ifmt + ";Y" + (R3 + 1) + ";X" + (C3 + 1));
        }
        p4.push(write_ws_cell_sylk(cell, ws, R3, C3, opts, d1904));
      }
      o9.push(p4.join(RS));
    }
    preamble.push("F;P0;DG0G8;M255");
    if (ws["!cols"]) write_ws_cols_sylk(preamble, ws["!cols"]);
    if (ws["!rows"]) write_ws_rows_sylk(preamble, ws["!rows"]);
    if (ws["!ref"]) preamble.push("B;Y" + (r8.e.r - r8.s.r + 1) + ";X" + (r8.e.c - r8.s.c + 1) + ";D" + [r8.s.c, r8.s.r, r8.e.c, r8.e.r].join(" "));
    preamble.push("O;L;D;B" + (d1904 ? ";V4" : "") + ";K47;G100 0.001");
    delete opts._formats;
    return preamble.join(RS) + RS + o9.join(RS) + RS + "E" + RS;
  }
  return {
    to_workbook: sylk_to_workbook,
    from_sheet: sheet_to_sylk
  };
})();
var DIF = /* @__PURE__ */ (function() {
  function dif_to_aoa(d4, opts) {
    switch (opts.type) {
      case "base64":
        return dif_to_aoa_str(Base64_decode(d4), opts);
      case "binary":
        return dif_to_aoa_str(d4, opts);
      case "buffer":
        return dif_to_aoa_str(has_buf && Buffer.isBuffer(d4) ? d4.toString("binary") : a2s(d4), opts);
      case "array":
        return dif_to_aoa_str(cc2str(d4), opts);
    }
    throw new Error("Unrecognized type " + opts.type);
  }
  function dif_to_aoa_str(str2, opts) {
    var records = str2.split("\n"), R3 = -1, C3 = -1, ri = 0, arr = [];
    for (; ri !== records.length; ++ri) {
      if (records[ri].trim() === "BOT") {
        arr[++R3] = [];
        C3 = 0;
        continue;
      }
      if (R3 < 0) continue;
      var metadata = records[ri].trim().split(",");
      var type = metadata[0], value = metadata[1];
      ++ri;
      var data = records[ri] || "";
      while ((data.match(/["]/g) || []).length & 1 && ri < records.length - 1) data += "\n" + records[++ri];
      data = data.trim();
      switch (+type) {
        case -1:
          if (data === "BOT") {
            arr[++R3] = [];
            C3 = 0;
            continue;
          } else if (data !== "EOD") throw new Error("Unrecognized DIF special command " + data);
          break;
        case 0:
          if (data === "TRUE") arr[R3][C3] = true;
          else if (data === "FALSE") arr[R3][C3] = false;
          else if (!isNaN(fuzzynum(value))) arr[R3][C3] = fuzzynum(value);
          else if (!isNaN(fuzzydate(value).getDate())) {
            arr[R3][C3] = parseDate(value);
            if (!(opts && opts.UTC)) {
              arr[R3][C3] = utc_to_local(arr[R3][C3]);
            }
          } else arr[R3][C3] = value;
          ++C3;
          break;
        case 1:
          data = data.slice(1, data.length - 1);
          data = data.replace(/""/g, '"');
          if (DIF_XL && data && data.match(/^=".*"$/)) data = data.slice(2, -1);
          arr[R3][C3++] = data !== "" ? data : null;
          break;
      }
      if (data === "EOD") break;
    }
    if (opts && opts.sheetRows) arr = arr.slice(0, opts.sheetRows);
    return arr;
  }
  function dif_to_sheet(str2, opts) {
    return aoa_to_sheet(dif_to_aoa(str2, opts), opts);
  }
  function dif_to_workbook(str2, opts) {
    var o9 = sheet_to_workbook(dif_to_sheet(str2, opts), opts);
    o9.bookType = "dif";
    return o9;
  }
  function make_value(v4, s6) {
    return "0," + String(v4) + "\r\n" + s6;
  }
  function make_value_str(s6) {
    return '1,0\r\n"' + s6.replace(/"/g, '""') + '"';
  }
  function sheet_to_dif(ws) {
    var _DIF_XL = DIF_XL;
    if (!ws["!ref"]) throw new Error("Cannot export empty sheet to DIF");
    var r8 = safe_decode_range(ws["!ref"]);
    var dense = ws["!data"] != null;
    var o9 = [
      'TABLE\r\n0,1\r\n"sheetjs"\r\n',
      "VECTORS\r\n0," + (r8.e.r - r8.s.r + 1) + '\r\n""\r\n',
      "TUPLES\r\n0," + (r8.e.c - r8.s.c + 1) + '\r\n""\r\n',
      'DATA\r\n0,0\r\n""\r\n'
    ];
    for (var R3 = r8.s.r; R3 <= r8.e.r; ++R3) {
      var row = dense ? ws["!data"][R3] : [];
      var p4 = "-1,0\r\nBOT\r\n";
      for (var C3 = r8.s.c; C3 <= r8.e.c; ++C3) {
        var cell = dense ? row && row[C3] : ws[encode_cell({ r: R3, c: C3 })];
        if (cell == null) {
          p4 += '1,0\r\n""\r\n';
          continue;
        }
        switch (cell.t) {
          case "n":
            if (_DIF_XL) {
              if (cell.w != null) p4 += "0," + cell.w + "\r\nV";
              else if (cell.v != null) p4 += make_value(cell.v, "V");
              else if (cell.f != null && !cell.F) p4 += make_value_str("=" + cell.f);
              else p4 += '1,0\r\n""';
            } else {
              if (cell.v == null) p4 += '1,0\r\n""';
              else p4 += make_value(cell.v, "V");
            }
            break;
          case "b":
            p4 += cell.v ? make_value(1, "TRUE") : make_value(0, "FALSE");
            break;
          case "s":
            p4 += make_value_str(!_DIF_XL || isNaN(+cell.v) ? cell.v : '="' + cell.v + '"');
            break;
          case "d":
            if (!cell.w) cell.w = SSF_format(cell.z || table_fmt[14], datenum(parseDate(cell.v)));
            if (_DIF_XL) p4 += make_value(cell.w, "V");
            else p4 += make_value_str(cell.w);
            break;
          default:
            p4 += '1,0\r\n""';
        }
        p4 += "\r\n";
      }
      o9.push(p4);
    }
    return o9.join("") + "-1,0\r\nEOD";
  }
  return {
    to_workbook: dif_to_workbook,
    to_sheet: dif_to_sheet,
    from_sheet: sheet_to_dif
  };
})();
var ETH = /* @__PURE__ */ (function() {
  function decode2(s6) {
    return s6.replace(/\\b/g, "\\").replace(/\\c/g, ":").replace(/\\n/g, "\n");
  }
  function encode2(s6) {
    return s6.replace(/\\/g, "\\b").replace(/:/g, "\\c").replace(/\n/g, "\\n");
  }
  function eth_to_aoa(str2, opts) {
    var records = str2.split("\n"), R3 = -1, C3 = -1, ri = 0, arr = [];
    for (; ri !== records.length; ++ri) {
      var record = records[ri].trim().split(":");
      if (record[0] !== "cell") continue;
      var addr = decode_cell(record[1]);
      if (arr.length <= addr.r) {
        for (R3 = arr.length; R3 <= addr.r; ++R3) if (!arr[R3]) arr[R3] = [];
      }
      R3 = addr.r;
      C3 = addr.c;
      switch (record[2]) {
        case "t":
          arr[R3][C3] = decode2(record[3]);
          break;
        case "v":
          arr[R3][C3] = +record[3];
          break;
        case "vtf":
          var _f = record[record.length - 1];
        /* falls through */
        case "vtc":
          switch (record[3]) {
            case "nl":
              arr[R3][C3] = +record[4] ? true : false;
              break;
            default:
              arr[R3][C3] = record[record.length - 1].charAt(0) == "#" ? { t: "e", v: RBErr[record[record.length - 1]] } : +record[4];
              break;
          }
          if (record[2] == "vtf") arr[R3][C3] = [arr[R3][C3], _f];
      }
    }
    if (opts && opts.sheetRows) arr = arr.slice(0, opts.sheetRows);
    return arr;
  }
  function eth_to_sheet(d4, opts) {
    return aoa_to_sheet(eth_to_aoa(d4, opts), opts);
  }
  function eth_to_workbook(d4, opts) {
    return sheet_to_workbook(eth_to_sheet(d4, opts), opts);
  }
  var header = [
    "socialcalc:version:1.5",
    "MIME-Version: 1.0",
    "Content-Type: multipart/mixed; boundary=SocialCalcSpreadsheetControlSave"
  ].join("\n");
  var sep2 = [
    "--SocialCalcSpreadsheetControlSave",
    "Content-type: text/plain; charset=UTF-8"
  ].join("\n") + "\n";
  var meta = [
    "# SocialCalc Spreadsheet Control Save",
    "part:sheet"
  ].join("\n");
  var end = "--SocialCalcSpreadsheetControlSave--";
  function sheet_to_eth_data(ws) {
    if (!ws || !ws["!ref"]) return "";
    var o9 = [], oo = [], cell, coord = "";
    var r8 = decode_range(ws["!ref"]);
    var dense = ws["!data"] != null;
    for (var R3 = r8.s.r; R3 <= r8.e.r; ++R3) {
      for (var C3 = r8.s.c; C3 <= r8.e.c; ++C3) {
        coord = encode_cell({ r: R3, c: C3 });
        cell = dense ? (ws["!data"][R3] || [])[C3] : ws[coord];
        if (!cell || cell.v == null || cell.t === "z") continue;
        oo = ["cell", coord, "t"];
        switch (cell.t) {
          case "s":
            oo.push(encode2(cell.v));
            break;
          case "b":
            oo[2] = "vt" + (cell.f ? "f" : "c");
            oo[3] = "nl";
            oo[4] = cell.v ? "1" : "0";
            oo[5] = encode2(cell.f || (cell.v ? "TRUE" : "FALSE"));
            break;
          case "d":
            var t6 = datenum(parseDate(cell.v));
            oo[2] = "vtc";
            oo[3] = "nd";
            oo[4] = "" + t6;
            oo[5] = cell.w || SSF_format(cell.z || table_fmt[14], t6);
            break;
          case "n":
            if (isFinite(cell.v)) {
              if (!cell.f) {
                oo[2] = "v";
                oo[3] = cell.v;
              } else {
                oo[2] = "vtf";
                oo[3] = "n";
                oo[4] = cell.v;
                oo[5] = encode2(cell.f);
              }
            } else {
              oo[2] = "vt" + (cell.f ? "f" : "c");
              oo[3] = "e" + BErr[isNaN(cell.v) ? 36 : 7];
              oo[4] = "0";
              oo[5] = cell.f || oo[3].slice(1);
              oo[6] = "e";
              oo[7] = oo[3].slice(1);
            }
            break;
          case "e":
            continue;
        }
        o9.push(oo.join(":"));
      }
    }
    o9.push("sheet:c:" + (r8.e.c - r8.s.c + 1) + ":r:" + (r8.e.r - r8.s.r + 1) + ":tvf:1");
    o9.push("valueformat:1:text-wiki");
    return o9.join("\n");
  }
  function sheet_to_eth(ws) {
    return [header, sep2, meta, sep2, sheet_to_eth_data(ws), end].join("\n");
  }
  return {
    to_workbook: eth_to_workbook,
    to_sheet: eth_to_sheet,
    from_sheet: sheet_to_eth
  };
})();
var PRN = /* @__PURE__ */ (function() {
  function set_text_arr(data, arr, R3, C3, o9) {
    if (o9.raw) arr[R3][C3] = data;
    else if (data === "") {
    } else if (data === "TRUE") arr[R3][C3] = true;
    else if (data === "FALSE") arr[R3][C3] = false;
    else if (!isNaN(fuzzynum(data))) arr[R3][C3] = fuzzynum(data);
    else if (!isNaN(fuzzydate(data).getDate())) arr[R3][C3] = parseDate(data);
    else if (data.charCodeAt(0) == 35 && RBErr[data] != null) arr[R3][C3] = { t: "e", v: RBErr[data], w: data };
    else arr[R3][C3] = data;
  }
  function prn_to_aoa_str(f4, opts) {
    var o9 = opts || {};
    var arr = [];
    if (!f4 || f4.length === 0) return arr;
    var lines = f4.split(/[\r\n]/);
    var L3 = lines.length - 1;
    while (L3 >= 0 && lines[L3].length === 0) --L3;
    var start = 10, idx = 0;
    var R3 = 0;
    for (; R3 <= L3; ++R3) {
      idx = lines[R3].indexOf(" ");
      if (idx == -1) idx = lines[R3].length;
      else idx++;
      start = Math.max(start, idx);
    }
    for (R3 = 0; R3 <= L3; ++R3) {
      arr[R3] = [];
      var C3 = 0;
      set_text_arr(lines[R3].slice(0, start).trim(), arr, R3, C3, o9);
      for (C3 = 1; C3 <= (lines[R3].length - start) / 10 + 1; ++C3)
        set_text_arr(lines[R3].slice(start + (C3 - 1) * 10, start + C3 * 10).trim(), arr, R3, C3, o9);
    }
    if (o9.sheetRows) arr = arr.slice(0, o9.sheetRows);
    return arr;
  }
  var guess_seps = {
    44: ",",
    9: "	",
    59: ";",
    124: "|"
  };
  var guess_sep_weights = {
    44: 3,
    9: 2,
    59: 1,
    124: 0
  };
  function guess_sep(str2) {
    var cnt = {}, instr = false, end = 0, cc = 0;
    for (; end < str2.length; ++end) {
      if ((cc = str2.charCodeAt(end)) == 34) instr = !instr;
      else if (!instr && cc in guess_seps) cnt[cc] = (cnt[cc] || 0) + 1;
    }
    cc = [];
    for (end in cnt) if (Object.prototype.hasOwnProperty.call(cnt, end)) {
      cc.push([cnt[end], end]);
    }
    if (!cc.length) {
      cnt = guess_sep_weights;
      for (end in cnt) if (Object.prototype.hasOwnProperty.call(cnt, end)) {
        cc.push([cnt[end], end]);
      }
    }
    cc.sort(function(a3, b4) {
      return a3[0] - b4[0] || guess_sep_weights[a3[1]] - guess_sep_weights[b4[1]];
    });
    return guess_seps[cc.pop()[1]] || 44;
  }
  function dsv_to_sheet_str(str2, opts) {
    var o9 = opts || {};
    var sep2 = "";
    if (DENSE != null && o9.dense == null) o9.dense = DENSE;
    var ws = {};
    if (o9.dense) ws["!data"] = [];
    var range2 = { s: { c: 0, r: 0 }, e: { c: 0, r: 0 } };
    if (str2.slice(0, 4) == "sep=") {
      if (str2.charCodeAt(5) == 13 && str2.charCodeAt(6) == 10) {
        sep2 = str2.charAt(4);
        str2 = str2.slice(7);
      } else if (str2.charCodeAt(5) == 13 || str2.charCodeAt(5) == 10) {
        sep2 = str2.charAt(4);
        str2 = str2.slice(6);
      } else sep2 = guess_sep(str2.slice(0, 1024));
    } else if (o9 && o9.FS) sep2 = o9.FS;
    else sep2 = guess_sep(str2.slice(0, 1024));
    var R3 = 0, C3 = 0, v4 = 0;
    var start = 0, end = 0, sepcc = sep2.charCodeAt(0), instr = false, cc = 0, startcc = str2.charCodeAt(0);
    var _re = o9.dateNF != null ? dateNF_regex(o9.dateNF) : null;
    function finish_cell() {
      var s6 = str2.slice(start, end);
      if (s6.slice(-1) == "\r") s6 = s6.slice(0, -1);
      var cell = {};
      if (s6.charAt(0) == '"' && s6.charAt(s6.length - 1) == '"') s6 = s6.slice(1, -1).replace(/""/g, '"');
      if (o9.cellText !== false) cell.w = s6;
      if (s6.length === 0) cell.t = "z";
      else if (o9.raw) {
        cell.t = "s";
        cell.v = s6;
      } else if (s6.trim().length === 0) {
        cell.t = "s";
        cell.v = s6;
      } else if (s6.charCodeAt(0) == 61) {
        if (s6.charCodeAt(1) == 34 && s6.charCodeAt(s6.length - 1) == 34) {
          cell.t = "s";
          cell.v = s6.slice(2, -1).replace(/""/g, '"');
        } else if (fuzzyfmla(s6)) {
          cell.t = "s";
          cell.f = s6.slice(1);
          cell.v = s6;
        } else {
          cell.t = "s";
          cell.v = s6;
        }
      } else if (s6 == "TRUE") {
        cell.t = "b";
        cell.v = true;
      } else if (s6 == "FALSE") {
        cell.t = "b";
        cell.v = false;
      } else if (!isNaN(v4 = fuzzynum(s6))) {
        cell.t = "n";
        cell.v = v4;
      } else if (!isNaN((v4 = fuzzydate(s6)).getDate()) || _re && s6.match(_re)) {
        cell.z = o9.dateNF || table_fmt[14];
        if (_re && s6.match(_re)) {
          var news = dateNF_fix(s6, o9.dateNF, s6.match(_re) || []);
          v4 = parseDate(news);
          if (o9 && o9.UTC === false) v4 = utc_to_local(v4);
        } else if (o9 && o9.UTC === false) v4 = utc_to_local(v4);
        else if (o9.cellText !== false && o9.dateNF) cell.w = SSF_format(cell.z, v4);
        if (o9.cellDates) {
          cell.t = "d";
          cell.v = v4;
        } else {
          cell.t = "n";
          cell.v = datenum(v4);
        }
        if (!o9.cellNF) delete cell.z;
      } else if (s6.charCodeAt(0) == 35 && RBErr[s6] != null) {
        cell.t = "e";
        cell.w = s6;
        cell.v = RBErr[s6];
      } else {
        cell.t = "s";
        cell.v = s6;
      }
      if (cell.t == "z") {
      } else if (o9.dense) {
        if (!ws["!data"][R3]) ws["!data"][R3] = [];
        ws["!data"][R3][C3] = cell;
      } else ws[encode_cell({ c: C3, r: R3 })] = cell;
      start = end + 1;
      startcc = str2.charCodeAt(start);
      if (range2.e.c < C3) range2.e.c = C3;
      if (range2.e.r < R3) range2.e.r = R3;
      if (cc == sepcc) ++C3;
      else {
        C3 = 0;
        ++R3;
        if (o9.sheetRows && o9.sheetRows <= R3) return true;
      }
    }
    outer: for (; end < str2.length; ++end) switch (cc = str2.charCodeAt(end)) {
      case 34:
        if (startcc === 34) instr = !instr;
        break;
      case 13:
        if (instr) break;
        if (str2.charCodeAt(end + 1) == 10) ++end;
      /* falls through */
      case sepcc:
      case 10:
        if (!instr && finish_cell()) break outer;
        break;
      default:
        break;
    }
    if (end - start > 0) finish_cell();
    ws["!ref"] = encode_range(range2);
    return ws;
  }
  function prn_to_sheet_str(str2, opts) {
    if (!(opts && opts.PRN)) return dsv_to_sheet_str(str2, opts);
    if (opts.FS) return dsv_to_sheet_str(str2, opts);
    if (str2.slice(0, 4) == "sep=") return dsv_to_sheet_str(str2, opts);
    if (str2.indexOf("	") >= 0 || str2.indexOf(",") >= 0 || str2.indexOf(";") >= 0) return dsv_to_sheet_str(str2, opts);
    return aoa_to_sheet(prn_to_aoa_str(str2, opts), opts);
  }
  function prn_to_sheet(d4, opts) {
    var str2 = "", bytes = opts.type == "string" ? [0, 0, 0, 0] : firstbyte(d4, opts);
    switch (opts.type) {
      case "base64":
        str2 = Base64_decode(d4);
        break;
      case "binary":
        str2 = d4;
        break;
      case "buffer":
        if (opts.codepage == 65001) str2 = d4.toString("utf8");
        else if (opts.codepage && typeof $cptable !== "undefined") str2 = $cptable.utils.decode(opts.codepage, d4);
        else str2 = has_buf && Buffer.isBuffer(d4) ? d4.toString("binary") : a2s(d4);
        break;
      case "array":
        str2 = cc2str(d4);
        break;
      case "string":
        str2 = d4;
        break;
      default:
        throw new Error("Unrecognized type " + opts.type);
    }
    if (bytes[0] == 239 && bytes[1] == 187 && bytes[2] == 191) str2 = utf8read(str2.slice(3));
    else if (opts.type != "string" && opts.type != "buffer" && opts.codepage == 65001) str2 = utf8read(str2);
    else if (opts.type == "binary" && typeof $cptable !== "undefined" && opts.codepage) str2 = $cptable.utils.decode(opts.codepage, $cptable.utils.encode(28591, str2));
    if (str2.slice(0, 19) == "socialcalc:version:") return ETH.to_sheet(opts.type == "string" ? str2 : utf8read(str2), opts);
    return prn_to_sheet_str(str2, opts);
  }
  function prn_to_workbook(d4, opts) {
    return sheet_to_workbook(prn_to_sheet(d4, opts), opts);
  }
  function sheet_to_prn(ws) {
    var o9 = [];
    if (!ws["!ref"]) return "";
    var r8 = safe_decode_range(ws["!ref"]), cell;
    var dense = ws["!data"] != null;
    for (var R3 = r8.s.r; R3 <= r8.e.r; ++R3) {
      var oo = [];
      for (var C3 = r8.s.c; C3 <= r8.e.c; ++C3) {
        var coord = encode_cell({ r: R3, c: C3 });
        cell = dense ? (ws["!data"][R3] || [])[C3] : ws[coord];
        if (!cell || cell.v == null) {
          oo.push("          ");
          continue;
        }
        var w3 = (cell.w || (format_cell(cell), cell.w) || "").slice(0, 10);
        while (w3.length < 10) w3 += " ";
        oo.push(w3 + (C3 === 0 ? " " : ""));
      }
      o9.push(oo.join(""));
    }
    return o9.join("\n");
  }
  return {
    to_workbook: prn_to_workbook,
    to_sheet: prn_to_sheet,
    from_sheet: sheet_to_prn
  };
})();
function read_wb_ID(d4, opts) {
  var o9 = opts || {}, OLD_WTF = !!o9.WTF;
  o9.WTF = true;
  try {
    var out = SYLK.to_workbook(d4, o9);
    o9.WTF = OLD_WTF;
    return out;
  } catch (e9) {
    o9.WTF = OLD_WTF;
    if (e9.message.indexOf("SYLK bad record ID") == -1 && OLD_WTF) throw e9;
    return PRN.to_workbook(d4, opts);
  }
}
var WK_ = /* @__PURE__ */ (function() {
  function lotushopper(data, cb, opts) {
    if (!data) return;
    prep_blob(data, data.l || 0);
    var Enum3 = opts.Enum || WK1Enum;
    while (data.l < data.length) {
      var RT = data.read_shift(2);
      var R3 = Enum3[RT] || Enum3[65535];
      var length = data.read_shift(2);
      var tgt = data.l + length;
      var d4 = R3.f && R3.f(data, length, opts);
      data.l = tgt;
      if (cb(d4, R3, RT)) return;
    }
  }
  function lotus_to_workbook(d4, opts) {
    switch (opts.type) {
      case "base64":
        return lotus_to_workbook_buf(s2a(Base64_decode(d4)), opts);
      case "binary":
        return lotus_to_workbook_buf(s2a(d4), opts);
      case "buffer":
      case "array":
        return lotus_to_workbook_buf(d4, opts);
    }
    throw "Unsupported type " + opts.type;
  }
  var LOTUS_DATE_FMTS = [
    "mmmm",
    "dd-mmm-yyyy",
    "dd-mmm",
    "mmm-yyyy",
    "@",
    // "text"?
    "mm/dd",
    "hh:mm:ss AM/PM",
    // 7
    "hh:mm AM/PM",
    "mm/dd/yyyy",
    "mm/dd",
    "hh:mm:ss",
    "hh:mm"
    // 12
  ];
  function lotus_to_workbook_buf(d4, opts) {
    if (!d4) return d4;
    var o9 = opts || {};
    if (DENSE != null && o9.dense == null) o9.dense = DENSE;
    var s6 = {}, n7 = "Sheet1", next_n = "", sidx = 0;
    var sheets = {}, snames = [], realnames = [], sdata = [];
    if (o9.dense) sdata = s6["!data"] = [];
    var refguess = { s: { r: 0, c: 0 }, e: { r: 0, c: 0 } };
    var sheetRows = o9.sheetRows || 0;
    var lastcell = {};
    if (d4[4] == 81 && d4[5] == 80 && d4[6] == 87) return qpw_to_workbook_buf(d4, opts);
    if (d4[2] == 0) {
      if (d4[3] == 8 || d4[3] == 9) {
        if (d4.length >= 16 && d4[14] == 5 && d4[15] === 108) throw new Error("Unsupported Works 3 for Mac file");
      }
    }
    if (d4[2] == 2) {
      o9.Enum = WK1Enum;
      lotushopper(d4, function(val2, R3, RT) {
        switch (RT) {
          case 0:
            o9.vers = val2;
            if (val2 >= 4096) o9.qpro = true;
            break;
          case 255:
            o9.vers = val2;
            o9.works = true;
            break;
          case 6:
            refguess = val2;
            break;
          /* RANGE */
          case 204:
            if (val2) next_n = val2;
            break;
          /* SHEETNAMECS */
          case 222:
            next_n = val2;
            break;
          /* SHEETNAMELP */
          case 15:
          /* LABEL */
          case 51:
            if ((!o9.qpro && !o9.works || RT == 51) && val2[1].v.charCodeAt(0) < 48) val2[1].v = val2[1].v.slice(1);
            if (o9.works || o9.works2) val2[1].v = val2[1].v.replace(/\r\n/g, "\n");
          /* falls through */
          case 13:
          /* INTEGER */
          case 14:
          /* NUMBER */
          case 16:
            if ((val2[2] & 112) == 112 && (val2[2] & 15) > 1 && (val2[2] & 15) < 15) {
              val2[1].z = o9.dateNF || LOTUS_DATE_FMTS[(val2[2] & 15) - 1] || table_fmt[14];
              if (o9.cellDates) {
                val2[1].v = numdate(val2[1].v);
                val2[1].t = typeof val2[1].v == "number" ? "n" : "d";
              }
            }
            if (o9.qpro) {
              if (val2[3] > sidx) {
                s6["!ref"] = encode_range(refguess);
                sheets[n7] = s6;
                snames.push(n7);
                s6 = {};
                if (o9.dense) sdata = s6["!data"] = [];
                refguess = { s: { r: 0, c: 0 }, e: { r: 0, c: 0 } };
                sidx = val2[3];
                n7 = next_n || "Sheet" + (sidx + 1);
                next_n = "";
              }
            }
            var tmpcell = o9.dense ? (sdata[val2[0].r] || [])[val2[0].c] : s6[encode_cell(val2[0])];
            if (tmpcell) {
              tmpcell.t = val2[1].t;
              tmpcell.v = val2[1].v;
              if (val2[1].z != null) tmpcell.z = val2[1].z;
              if (val2[1].f != null) tmpcell.f = val2[1].f;
              lastcell = tmpcell;
              break;
            }
            if (o9.dense) {
              if (!sdata[val2[0].r]) sdata[val2[0].r] = [];
              sdata[val2[0].r][val2[0].c] = val2[1];
            } else s6[encode_cell(val2[0])] = val2[1];
            lastcell = val2[1];
            break;
          case 21509:
            o9.works2 = true;
            break;
          case 21506:
            {
              if (val2 == 5281) {
                lastcell.z = "hh:mm:ss";
                if (o9.cellDates && lastcell.t == "n") {
                  lastcell.v = numdate(lastcell.v);
                  lastcell.t = typeof lastcell.v == "number" ? "n" : "d";
                }
              }
            }
            break;
        }
      }, o9);
    } else if (d4[2] == 26 || d4[2] == 14) {
      o9.Enum = WK3Enum;
      if (d4[2] == 14) {
        o9.qpro = true;
        d4.l = 0;
      }
      lotushopper(d4, function(val2, R3, RT) {
        switch (RT) {
          case 204:
            n7 = val2;
            break;
          /* SHEETNAMECS */
          case 22:
            if (val2[1].v.charCodeAt(0) < 48) val2[1].v = val2[1].v.slice(1);
            val2[1].v = val2[1].v.replace(/\x0F./g, function($$) {
              return String.fromCharCode($$.charCodeAt(1) - 32);
            }).replace(/\r\n/g, "\n");
          /* falls through */
          case 23:
          /* NUMBER17 */
          case 24:
          /* NUMBER18 */
          case 25:
          /* FORMULA19 */
          case 37:
          /* NUMBER25 */
          case 39:
          /* NUMBER27 */
          case 40:
            if (val2[3] > sidx) {
              s6["!ref"] = encode_range(refguess);
              sheets[n7] = s6;
              snames.push(n7);
              s6 = {};
              if (o9.dense) sdata = s6["!data"] = [];
              refguess = { s: { r: 0, c: 0 }, e: { r: 0, c: 0 } };
              sidx = val2[3];
              n7 = "Sheet" + (sidx + 1);
            }
            if (sheetRows > 0 && val2[0].r >= sheetRows) break;
            if (o9.dense) {
              if (!sdata[val2[0].r]) sdata[val2[0].r] = [];
              sdata[val2[0].r][val2[0].c] = val2[1];
            } else s6[encode_cell(val2[0])] = val2[1];
            if (refguess.e.c < val2[0].c) refguess.e.c = val2[0].c;
            if (refguess.e.r < val2[0].r) refguess.e.r = val2[0].r;
            break;
          case 27:
            if (val2[14e3]) realnames[val2[14e3][0]] = val2[14e3][1];
            break;
          case 1537:
            realnames[val2[0]] = val2[1];
            if (val2[0] == sidx) n7 = val2[1];
            break;
          default:
            break;
        }
      }, o9);
    } else throw new Error("Unrecognized LOTUS BOF " + d4[2]);
    s6["!ref"] = encode_range(refguess);
    sheets[next_n || n7] = s6;
    snames.push(next_n || n7);
    if (!realnames.length) return { SheetNames: snames, Sheets: sheets };
    var osheets = {}, rnames = [];
    for (var i7 = 0; i7 < realnames.length; ++i7) if (sheets[snames[i7]]) {
      rnames.push(realnames[i7] || snames[i7]);
      osheets[realnames[i7]] = sheets[realnames[i7]] || sheets[snames[i7]];
    } else {
      rnames.push(realnames[i7]);
      osheets[realnames[i7]] = { "!ref": "A1" };
    }
    return { SheetNames: rnames, Sheets: osheets };
  }
  function sheet_to_wk1(ws, opts) {
    var o9 = opts || {};
    if (+o9.codepage >= 0) set_cp(+o9.codepage);
    if (o9.type == "string") throw new Error("Cannot write WK1 to JS string");
    var ba = buf_array();
    if (!ws["!ref"]) throw new Error("Cannot export empty sheet to WK1");
    var range2 = safe_decode_range(ws["!ref"]);
    var dense = ws["!data"] != null;
    var cols = [];
    write_biff_rec(ba, 0, write_BOF_WK1(1030));
    write_biff_rec(ba, 6, write_RANGE(range2));
    var max_R = Math.min(range2.e.r, 8191);
    for (var C3 = range2.s.c; C3 <= range2.e.c; ++C3) cols[C3] = encode_col(C3);
    for (var R3 = range2.s.r; R3 <= max_R; ++R3) {
      var rr = encode_row(R3);
      for (C3 = range2.s.c; C3 <= range2.e.c; ++C3) {
        var cell = dense ? (ws["!data"][R3] || [])[C3] : ws[cols[C3] + rr];
        if (!cell || cell.t == "z") continue;
        switch (cell.t) {
          case "n":
            if ((cell.v | 0) == cell.v && cell.v >= -32768 && cell.v <= 32767) write_biff_rec(ba, 13, write_INTEGER(R3, C3, cell));
            else write_biff_rec(ba, 14, write_NUMBER(R3, C3, cell));
            break;
          case "d":
            var dc = datenum(cell.v);
            if ((dc | 0) == dc && dc >= -32768 && dc <= 32767) write_biff_rec(ba, 13, write_INTEGER(R3, C3, { t: "n", v: dc, z: cell.z || table_fmt[14] }));
            else write_biff_rec(ba, 14, write_NUMBER(R3, C3, { t: "n", v: dc, z: cell.z || table_fmt[14] }));
            break;
          default:
            var str2 = format_cell(cell);
            write_biff_rec(ba, 15, write_LABEL(R3, C3, str2.slice(0, 239)));
        }
      }
    }
    write_biff_rec(ba, 1);
    return ba.end();
  }
  function book_to_wk3(wb, opts) {
    var o9 = opts || {};
    if (+o9.codepage >= 0) set_cp(+o9.codepage);
    if (o9.type == "string") throw new Error("Cannot write WK3 to JS string");
    var ba = buf_array();
    write_biff_rec(ba, 0, write_BOF_WK3(wb));
    for (var i7 = 0, cnt = 0; i7 < wb.SheetNames.length; ++i7) if ((wb.Sheets[wb.SheetNames[i7]] || {})["!ref"]) write_biff_rec(ba, 27, write_XFORMAT_SHEETNAME(wb.SheetNames[i7], cnt++));
    var wsidx = 0;
    for (i7 = 0; i7 < wb.SheetNames.length; ++i7) {
      var ws = wb.Sheets[wb.SheetNames[i7]];
      if (!ws || !ws["!ref"]) continue;
      var range2 = safe_decode_range(ws["!ref"]);
      var dense = ws["!data"] != null;
      var cols = [];
      var max_R = Math.min(range2.e.r, 8191);
      for (var R3 = range2.s.r; R3 <= max_R; ++R3) {
        var rr = encode_row(R3);
        for (var C3 = range2.s.c; C3 <= range2.e.c; ++C3) {
          if (R3 === range2.s.r) cols[C3] = encode_col(C3);
          var ref = cols[C3] + rr;
          var cell = dense ? (ws["!data"][R3] || [])[C3] : ws[ref];
          if (!cell || cell.t == "z") continue;
          if (cell.t == "n") {
            write_biff_rec(ba, 23, write_NUMBER_17(R3, C3, wsidx, cell.v));
          } else {
            var str2 = format_cell(cell);
            write_biff_rec(ba, 22, write_LABEL_16(R3, C3, wsidx, str2.slice(0, 239)));
          }
        }
      }
      ++wsidx;
    }
    write_biff_rec(ba, 1);
    return ba.end();
  }
  function write_BOF_WK1(v4) {
    var out = new_buf(2);
    out.write_shift(2, v4);
    return out;
  }
  function write_BOF_WK3(wb) {
    var out = new_buf(26);
    out.write_shift(2, 4096);
    out.write_shift(2, 4);
    out.write_shift(4, 0);
    var rows = 0, cols = 0, wscnt = 0;
    for (var i7 = 0; i7 < wb.SheetNames.length; ++i7) {
      var name = wb.SheetNames[i7];
      var ws = wb.Sheets[name];
      if (!ws || !ws["!ref"]) continue;
      ++wscnt;
      var range2 = decode_range(ws["!ref"]);
      if (rows < range2.e.r) rows = range2.e.r;
      if (cols < range2.e.c) cols = range2.e.c;
    }
    if (rows > 8191) rows = 8191;
    out.write_shift(2, rows);
    out.write_shift(1, wscnt);
    out.write_shift(1, cols);
    out.write_shift(2, 0);
    out.write_shift(2, 0);
    out.write_shift(1, 1);
    out.write_shift(1, 2);
    out.write_shift(4, 0);
    out.write_shift(4, 0);
    return out;
  }
  function parse_RANGE(blob, length, opts) {
    var o9 = { s: { c: 0, r: 0 }, e: { c: 0, r: 0 } };
    if (length == 8 && opts.qpro) {
      o9.s.c = blob.read_shift(1);
      blob.l++;
      o9.s.r = blob.read_shift(2);
      o9.e.c = blob.read_shift(1);
      blob.l++;
      o9.e.r = blob.read_shift(2);
      return o9;
    }
    o9.s.c = blob.read_shift(2);
    o9.s.r = blob.read_shift(2);
    if (length == 12 && opts.qpro) blob.l += 2;
    o9.e.c = blob.read_shift(2);
    o9.e.r = blob.read_shift(2);
    if (length == 12 && opts.qpro) blob.l += 2;
    if (o9.s.c == 65535) o9.s.c = o9.e.c = o9.s.r = o9.e.r = 0;
    return o9;
  }
  function write_RANGE(range2) {
    var out = new_buf(8);
    out.write_shift(2, range2.s.c);
    out.write_shift(2, range2.s.r);
    out.write_shift(2, range2.e.c);
    out.write_shift(2, range2.e.r);
    return out;
  }
  function parse_cell(blob, length, opts) {
    var o9 = [{ c: 0, r: 0 }, { t: "n", v: 0 }, 0, 0];
    if (opts.qpro && opts.vers != 20768) {
      o9[0].c = blob.read_shift(1);
      o9[3] = blob.read_shift(1);
      o9[0].r = blob.read_shift(2);
      blob.l += 2;
    } else if (opts.works) {
      o9[0].c = blob.read_shift(2);
      o9[0].r = blob.read_shift(2);
      o9[2] = blob.read_shift(2);
    } else {
      o9[2] = blob.read_shift(1);
      o9[0].c = blob.read_shift(2);
      o9[0].r = blob.read_shift(2);
    }
    return o9;
  }
  function get_wk1_fmt(cell) {
    if (cell.z && fmt_is_date(cell.z)) {
      return 240 | (LOTUS_DATE_FMTS.indexOf(cell.z) + 1 || 2);
    }
    return 255;
  }
  function parse_LABEL(blob, length, opts) {
    var tgt = blob.l + length;
    var o9 = parse_cell(blob, length, opts);
    o9[1].t = "s";
    if ((opts.vers & 65534) == 20768) {
      blob.l++;
      var len = blob.read_shift(1);
      o9[1].v = blob.read_shift(len, "utf8");
      return o9;
    }
    if (opts.qpro) blob.l++;
    o9[1].v = blob.read_shift(tgt - blob.l, "cstr");
    return o9;
  }
  function write_LABEL(R3, C3, s6) {
    var o9 = new_buf(7 + s6.length);
    o9.write_shift(1, 255);
    o9.write_shift(2, C3);
    o9.write_shift(2, R3);
    o9.write_shift(1, 39);
    for (var i7 = 0; i7 < o9.length; ++i7) {
      var cc = s6.charCodeAt(i7);
      o9.write_shift(1, cc >= 128 ? 95 : cc);
    }
    o9.write_shift(1, 0);
    return o9;
  }
  function parse_STRING(blob, length, opts) {
    var tgt = blob.l + length;
    var o9 = parse_cell(blob, length, opts);
    o9[1].t = "s";
    if (opts.vers == 20768) {
      var len = blob.read_shift(1);
      o9[1].v = blob.read_shift(len, "utf8");
      return o9;
    }
    o9[1].v = blob.read_shift(tgt - blob.l, "cstr");
    return o9;
  }
  function parse_INTEGER(blob, length, opts) {
    var o9 = parse_cell(blob, length, opts);
    o9[1].v = blob.read_shift(2, "i");
    return o9;
  }
  function write_INTEGER(R3, C3, cell) {
    var o9 = new_buf(7);
    o9.write_shift(1, get_wk1_fmt(cell));
    o9.write_shift(2, C3);
    o9.write_shift(2, R3);
    o9.write_shift(2, cell.v, "i");
    return o9;
  }
  function parse_NUMBER(blob, length, opts) {
    var o9 = parse_cell(blob, length, opts);
    o9[1].v = blob.read_shift(8, "f");
    return o9;
  }
  function write_NUMBER(R3, C3, cell) {
    var o9 = new_buf(13);
    o9.write_shift(1, get_wk1_fmt(cell));
    o9.write_shift(2, C3);
    o9.write_shift(2, R3);
    o9.write_shift(8, cell.v, "f");
    return o9;
  }
  function parse_FORMULA(blob, length, opts) {
    var tgt = blob.l + length;
    var o9 = parse_cell(blob, length, opts);
    o9[1].v = blob.read_shift(8, "f");
    if (opts.qpro) blob.l = tgt;
    else {
      var flen = blob.read_shift(2);
      wk1_fmla_to_csf(blob.slice(blob.l, blob.l + flen), o9);
      blob.l += flen;
    }
    return o9;
  }
  function wk1_parse_rc(B3, V3, col) {
    var rel2 = V3 & 32768;
    V3 &= ~32768;
    V3 = (rel2 ? B3 : 0) + (V3 >= 8192 ? V3 - 16384 : V3);
    return (rel2 ? "" : "$") + (col ? encode_col(V3) : encode_row(V3));
  }
  var FuncTab = {
    31: ["NA", 0],
    // 0x20: ["ERR", 0],
    33: ["ABS", 1],
    34: ["TRUNC", 1],
    35: ["SQRT", 1],
    36: ["LOG", 1],
    37: ["LN", 1],
    38: ["PI", 0],
    39: ["SIN", 1],
    40: ["COS", 1],
    41: ["TAN", 1],
    42: ["ATAN2", 2],
    43: ["ATAN", 1],
    44: ["ASIN", 1],
    45: ["ACOS", 1],
    46: ["EXP", 1],
    47: ["MOD", 2],
    // 0x30
    49: ["ISNA", 1],
    50: ["ISERR", 1],
    51: ["FALSE", 0],
    52: ["TRUE", 0],
    53: ["RAND", 0],
    54: ["DATE", 3],
    // 0x37 NOW
    // 0x38 PMT
    // 0x39 PV
    // 0x3A FV
    // 0x3B IF
    // 0x3C DAY
    // 0x3D MONTH
    // 0x3E YEAR
    63: ["ROUND", 2],
    64: ["TIME", 3],
    // 0x41 HOUR
    // 0x42 MINUTE
    // 0x43 SECOND
    68: ["ISNUMBER", 1],
    69: ["ISTEXT", 1],
    70: ["LEN", 1],
    71: ["VALUE", 1],
    // 0x48: ["FIXED", ?? 1],
    73: ["MID", 3],
    74: ["CHAR", 1],
    // 0x4B
    // 0x4C FIND
    // 0x4D DATEVALUE
    // 0x4E TIMEVALUE
    // 0x4F CELL
    80: ["SUM", 69],
    81: ["AVERAGEA", 69],
    82: ["COUNTA", 69],
    83: ["MINA", 69],
    84: ["MAXA", 69],
    // 0x55 VLOOKUP
    // 0x56 NPV
    // 0x57 VAR
    // 0x58 STD
    // 0x59 IRR
    // 0x5A HLOOKUP
    // 0x5B DSUM
    // 0x5C DAVERAGE
    // 0x5D DCOUNTA
    // 0x5E DMIN
    // 0x5F DMAX
    // 0x60 DVARP
    // 0x61 DSTDEVP
    // 0x62 INDEX
    // 0x63 COLS
    // 0x64 ROWS
    // 0x65 REPEAT
    102: ["UPPER", 1],
    103: ["LOWER", 1],
    // 0x68 LEFT
    // 0x69 RIGHT
    // 0x6A REPLACE
    107: ["PROPER", 1],
    // 0x6C CELL
    109: ["TRIM", 1],
    // 0x6E CLEAN
    111: ["T", 1]
    // 0x70 V
  };
  var BinOpTab = [
    "",
    "",
    "",
    "",
    "",
    "",
    "",
    "",
    // eslint-disable-line no-mixed-spaces-and-tabs
    "",
    "+",
    "-",
    "*",
    "/",
    "^",
    "=",
    "<>",
    // eslint-disable-line no-mixed-spaces-and-tabs
    "<=",
    ">=",
    "<",
    ">",
    "",
    "",
    "",
    "",
    // eslint-disable-line no-mixed-spaces-and-tabs
    "&",
    "",
    "",
    "",
    "",
    "",
    "",
    ""
    // eslint-disable-line no-mixed-spaces-and-tabs
  ];
  function wk1_fmla_to_csf(blob, o9) {
    prep_blob(blob, 0);
    var out = [], argc = 0, R3 = "", C3 = "", argL = "", argR = "";
    while (blob.l < blob.length) {
      var cc = blob[blob.l++];
      switch (cc) {
        case 0:
          out.push(blob.read_shift(8, "f"));
          break;
        case 1:
          {
            C3 = wk1_parse_rc(o9[0].c, blob.read_shift(2), true);
            R3 = wk1_parse_rc(o9[0].r, blob.read_shift(2), false);
            out.push(C3 + R3);
          }
          break;
        case 2:
          {
            var c6 = wk1_parse_rc(o9[0].c, blob.read_shift(2), true);
            var r8 = wk1_parse_rc(o9[0].r, blob.read_shift(2), false);
            C3 = wk1_parse_rc(o9[0].c, blob.read_shift(2), true);
            R3 = wk1_parse_rc(o9[0].r, blob.read_shift(2), false);
            out.push(c6 + r8 + ":" + C3 + R3);
          }
          break;
        case 3:
          if (blob.l < blob.length) {
            console.error("WK1 premature formula end");
            return;
          }
          break;
        case 4:
          out.push("(" + out.pop() + ")");
          break;
        case 5:
          out.push(blob.read_shift(2));
          break;
        case 6:
          {
            var Z2 = "";
            while (cc = blob[blob.l++]) Z2 += String.fromCharCode(cc);
            out.push('"' + Z2.replace(/"/g, '""') + '"');
          }
          break;
        case 8:
          out.push("-" + out.pop());
          break;
        case 23:
          out.push("+" + out.pop());
          break;
        case 22:
          out.push("NOT(" + out.pop() + ")");
          break;
        case 20:
        case 21:
          {
            argR = out.pop();
            argL = out.pop();
            out.push(["AND", "OR"][cc - 20] + "(" + argL + "," + argR + ")");
          }
          break;
        default:
          if (cc < 32 && BinOpTab[cc]) {
            argR = out.pop();
            argL = out.pop();
            out.push(argL + BinOpTab[cc] + argR);
          } else if (FuncTab[cc]) {
            argc = FuncTab[cc][1];
            if (argc == 69) argc = blob[blob.l++];
            if (argc > out.length) {
              console.error("WK1 bad formula parse 0x" + cc.toString(16) + ":|" + out.join("|") + "|");
              return;
            }
            var args = out.slice(-argc);
            out.length -= argc;
            out.push(FuncTab[cc][0] + "(" + args.join(",") + ")");
          } else if (cc <= 7) return console.error("WK1 invalid opcode " + cc.toString(16));
          else if (cc <= 24) return console.error("WK1 unsupported op " + cc.toString(16));
          else if (cc <= 30) return console.error("WK1 invalid opcode " + cc.toString(16));
          else if (cc <= 115) return console.error("WK1 unsupported function opcode " + cc.toString(16));
          else return console.error("WK1 unrecognized opcode " + cc.toString(16));
      }
    }
    if (out.length == 1) o9[1].f = "" + out[0];
    else console.error("WK1 bad formula parse |" + out.join("|") + "|");
  }
  function parse_cell_3(blob) {
    var o9 = [{ c: 0, r: 0 }, { t: "n", v: 0 }, 0];
    o9[0].r = blob.read_shift(2);
    o9[3] = blob[blob.l++];
    o9[0].c = blob[blob.l++];
    return o9;
  }
  function parse_LABEL_16(blob, length) {
    var o9 = parse_cell_3(blob, length);
    o9[1].t = "s";
    o9[1].v = blob.read_shift(length - 4, "cstr");
    return o9;
  }
  function write_LABEL_16(R3, C3, wsidx, s6) {
    var o9 = new_buf(6 + s6.length);
    o9.write_shift(2, R3);
    o9.write_shift(1, wsidx);
    o9.write_shift(1, C3);
    o9.write_shift(1, 39);
    for (var i7 = 0; i7 < s6.length; ++i7) {
      var cc = s6.charCodeAt(i7);
      o9.write_shift(1, cc >= 128 ? 95 : cc);
    }
    o9.write_shift(1, 0);
    return o9;
  }
  function parse_NUMBER_18(blob, length) {
    var o9 = parse_cell_3(blob, length);
    o9[1].v = blob.read_shift(2);
    var v4 = o9[1].v >> 1;
    if (o9[1].v & 1) {
      switch (v4 & 7) {
        case 0:
          v4 = (v4 >> 3) * 5e3;
          break;
        case 1:
          v4 = (v4 >> 3) * 500;
          break;
        case 2:
          v4 = (v4 >> 3) / 20;
          break;
        case 3:
          v4 = (v4 >> 3) / 200;
          break;
        case 4:
          v4 = (v4 >> 3) / 2e3;
          break;
        case 5:
          v4 = (v4 >> 3) / 2e4;
          break;
        case 6:
          v4 = (v4 >> 3) / 16;
          break;
        case 7:
          v4 = (v4 >> 3) / 64;
          break;
      }
    }
    o9[1].v = v4;
    return o9;
  }
  function parse_NUMBER_17(blob, length) {
    var o9 = parse_cell_3(blob, length);
    var v1 = blob.read_shift(4);
    var v22 = blob.read_shift(4);
    var e9 = blob.read_shift(2);
    if (e9 == 65535) {
      if (v1 === 0 && v22 === 3221225472) {
        o9[1].t = "e";
        o9[1].v = 15;
      } else if (v1 === 0 && v22 === 3489660928) {
        o9[1].t = "e";
        o9[1].v = 42;
      } else o9[1].v = 0;
      return o9;
    }
    var s6 = e9 & 32768;
    e9 = (e9 & 32767) - 16446;
    o9[1].v = (1 - s6 * 2) * (v22 * Math.pow(2, e9 + 32) + v1 * Math.pow(2, e9));
    return o9;
  }
  function write_NUMBER_17(R3, C3, wsidx, v4) {
    var o9 = new_buf(14);
    o9.write_shift(2, R3);
    o9.write_shift(1, wsidx);
    o9.write_shift(1, C3);
    if (v4 == 0) {
      o9.write_shift(4, 0);
      o9.write_shift(4, 0);
      o9.write_shift(2, 65535);
      return o9;
    }
    var s6 = 0, e9 = 0, v1 = 0, v22 = 0;
    if (v4 < 0) {
      s6 = 1;
      v4 = -v4;
    }
    e9 = Math.log2(v4) | 0;
    v4 /= Math.pow(2, e9 - 31);
    v22 = v4 >>> 0;
    if ((v22 & 2147483648) == 0) {
      v4 /= 2;
      ++e9;
      v22 = v4 >>> 0;
    }
    v4 -= v22;
    v22 |= 2147483648;
    v22 >>>= 0;
    v4 *= Math.pow(2, 32);
    v1 = v4 >>> 0;
    o9.write_shift(4, v1);
    o9.write_shift(4, v22);
    e9 += 16383 + (s6 ? 32768 : 0);
    o9.write_shift(2, e9);
    return o9;
  }
  function parse_FORMULA_19(blob, length) {
    var o9 = parse_NUMBER_17(blob, 14);
    blob.l += length - 14;
    return o9;
  }
  function parse_NUMBER_25(blob, length) {
    var o9 = parse_cell_3(blob, length);
    var v1 = blob.read_shift(4);
    o9[1].v = v1 >> 6;
    return o9;
  }
  function parse_NUMBER_27(blob, length) {
    var o9 = parse_cell_3(blob, length);
    var v1 = blob.read_shift(8, "f");
    o9[1].v = v1;
    return o9;
  }
  function parse_FORMULA_28(blob, length) {
    var o9 = parse_NUMBER_27(blob, 12);
    blob.l += length - 12;
    return o9;
  }
  function parse_SHEETNAMECS(blob, length) {
    return blob[blob.l + length - 1] == 0 ? blob.read_shift(length, "cstr") : "";
  }
  function parse_SHEETNAMELP(blob, length) {
    var len = blob[blob.l++];
    if (len > length - 1) len = length - 1;
    var o9 = "";
    while (o9.length < len) o9 += String.fromCharCode(blob[blob.l++]);
    return o9;
  }
  function parse_SHEETINFOQP(blob, length, opts) {
    if (!opts.qpro || length < 21) return;
    var id = blob.read_shift(1);
    blob.l += 17;
    blob.l += 1;
    blob.l += 2;
    var nm = blob.read_shift(length - 21, "cstr");
    return [id, nm];
  }
  function parse_XFORMAT(blob, length) {
    var o9 = {}, tgt = blob.l + length;
    while (blob.l < tgt) {
      var dt = blob.read_shift(2);
      if (dt == 14e3) {
        o9[dt] = [0, ""];
        o9[dt][0] = blob.read_shift(2);
        while (blob[blob.l]) {
          o9[dt][1] += String.fromCharCode(blob[blob.l]);
          blob.l++;
        }
        blob.l++;
      }
    }
    return o9;
  }
  function write_XFORMAT_SHEETNAME(name, wsidx) {
    var out = new_buf(5 + name.length);
    out.write_shift(2, 14e3);
    out.write_shift(2, wsidx);
    for (var i7 = 0; i7 < name.length; ++i7) {
      var cc = name.charCodeAt(i7);
      out[out.l++] = cc > 127 ? 95 : cc;
    }
    out[out.l++] = 0;
    return out;
  }
  var WK1Enum = {
    0: { n: "BOF", f: parseuint16 },
    1: { n: "EOF" },
    2: { n: "CALCMODE" },
    3: { n: "CALCORDER" },
    4: { n: "SPLIT" },
    5: { n: "SYNC" },
    6: { n: "RANGE", f: parse_RANGE },
    7: { n: "WINDOW1" },
    8: { n: "COLW1" },
    9: { n: "WINTWO" },
    10: { n: "COLW2" },
    11: { n: "NAME" },
    12: { n: "BLANK" },
    13: { n: "INTEGER", f: parse_INTEGER },
    14: { n: "NUMBER", f: parse_NUMBER },
    15: { n: "LABEL", f: parse_LABEL },
    16: { n: "FORMULA", f: parse_FORMULA },
    24: { n: "TABLE" },
    25: { n: "ORANGE" },
    26: { n: "PRANGE" },
    27: { n: "SRANGE" },
    28: { n: "FRANGE" },
    29: { n: "KRANGE1" },
    32: { n: "HRANGE" },
    35: { n: "KRANGE2" },
    36: { n: "PROTEC" },
    37: { n: "FOOTER" },
    38: { n: "HEADER" },
    39: { n: "SETUP" },
    40: { n: "MARGINS" },
    41: { n: "LABELFMT" },
    42: { n: "TITLES" },
    43: { n: "SHEETJS" },
    45: { n: "GRAPH" },
    46: { n: "NGRAPH" },
    47: { n: "CALCCOUNT" },
    48: { n: "UNFORMATTED" },
    49: { n: "CURSORW12" },
    50: { n: "WINDOW" },
    51: { n: "STRING", f: parse_STRING },
    55: { n: "PASSWORD" },
    56: { n: "LOCKED" },
    60: { n: "QUERY" },
    61: { n: "QUERYNAME" },
    62: { n: "PRINT" },
    63: { n: "PRINTNAME" },
    64: { n: "GRAPH2" },
    65: { n: "GRAPHNAME" },
    66: { n: "ZOOM" },
    67: { n: "SYMSPLIT" },
    68: { n: "NSROWS" },
    69: { n: "NSCOLS" },
    70: { n: "RULER" },
    71: { n: "NNAME" },
    72: { n: "ACOMM" },
    73: { n: "AMACRO" },
    74: { n: "PARSE" },
    // 0x0064
    102: { n: "PRANGES??" },
    103: { n: "RRANGES??" },
    104: { n: "FNAME??" },
    105: { n: "MRANGES??" },
    // 0x0096
    // 0x0099
    // 0x009A
    // 0x009B
    // 0x009C
    // 0x00C0
    // 0x00C7
    // 0x00C9
    204: { n: "SHEETNAMECS", f: parse_SHEETNAMECS },
    // 0x00CD
    222: { n: "SHEETNAMELP", f: parse_SHEETNAMELP },
    255: { n: "BOF", f: parseuint16 },
    21506: { n: "WKSNF", f: parseuint16 },
    65535: { n: "" }
  };
  var WK3Enum = {
    0: { n: "BOF" },
    1: { n: "EOF" },
    2: { n: "PASSWORD" },
    3: { n: "CALCSET" },
    4: { n: "WINDOWSET" },
    5: { n: "SHEETCELLPTR" },
    6: { n: "SHEETLAYOUT" },
    7: { n: "COLUMNWIDTH" },
    8: { n: "HIDDENCOLUMN" },
    9: { n: "USERRANGE" },
    10: { n: "SYSTEMRANGE" },
    11: { n: "ZEROFORCE" },
    12: { n: "SORTKEYDIR" },
    13: { n: "FILESEAL" },
    14: { n: "DATAFILLNUMS" },
    15: { n: "PRINTMAIN" },
    16: { n: "PRINTSTRING" },
    17: { n: "GRAPHMAIN" },
    18: { n: "GRAPHSTRING" },
    19: { n: "??" },
    20: { n: "ERRCELL" },
    21: { n: "NACELL" },
    22: { n: "LABEL16", f: parse_LABEL_16 },
    23: { n: "NUMBER17", f: parse_NUMBER_17 },
    24: { n: "NUMBER18", f: parse_NUMBER_18 },
    25: { n: "FORMULA19", f: parse_FORMULA_19 },
    26: { n: "FORMULA1A" },
    27: { n: "XFORMAT", f: parse_XFORMAT },
    28: { n: "DTLABELMISC" },
    29: { n: "DTLABELCELL" },
    30: { n: "GRAPHWINDOW" },
    31: { n: "CPA" },
    32: { n: "LPLAUTO" },
    33: { n: "QUERY" },
    34: { n: "HIDDENSHEET" },
    35: { n: "??" },
    37: { n: "NUMBER25", f: parse_NUMBER_25 },
    38: { n: "??" },
    39: { n: "NUMBER27", f: parse_NUMBER_27 },
    40: { n: "FORMULA28", f: parse_FORMULA_28 },
    142: { n: "??" },
    147: { n: "??" },
    150: { n: "??" },
    151: { n: "??" },
    152: { n: "??" },
    153: { n: "??" },
    154: { n: "??" },
    155: { n: "??" },
    156: { n: "??" },
    163: { n: "??" },
    174: { n: "??" },
    175: { n: "??" },
    176: { n: "??" },
    177: { n: "??" },
    184: { n: "??" },
    185: { n: "??" },
    186: { n: "??" },
    187: { n: "??" },
    188: { n: "??" },
    195: { n: "??" },
    201: { n: "??" },
    204: { n: "SHEETNAMECS", f: parse_SHEETNAMECS },
    205: { n: "??" },
    206: { n: "??" },
    207: { n: "??" },
    208: { n: "??" },
    256: { n: "??" },
    259: { n: "??" },
    260: { n: "??" },
    261: { n: "??" },
    262: { n: "??" },
    263: { n: "??" },
    265: { n: "??" },
    266: { n: "??" },
    267: { n: "??" },
    268: { n: "??" },
    270: { n: "??" },
    271: { n: "??" },
    384: { n: "??" },
    389: { n: "??" },
    390: { n: "??" },
    393: { n: "??" },
    396: { n: "??" },
    512: { n: "??" },
    514: { n: "??" },
    513: { n: "??" },
    516: { n: "??" },
    517: { n: "??" },
    640: { n: "??" },
    641: { n: "??" },
    642: { n: "??" },
    643: { n: "??" },
    644: { n: "??" },
    645: { n: "??" },
    646: { n: "??" },
    647: { n: "??" },
    648: { n: "??" },
    658: { n: "??" },
    659: { n: "??" },
    660: { n: "??" },
    661: { n: "??" },
    662: { n: "??" },
    665: { n: "??" },
    666: { n: "??" },
    768: { n: "??" },
    772: { n: "??" },
    1537: { n: "SHEETINFOQP", f: parse_SHEETINFOQP },
    1600: { n: "??" },
    1602: { n: "??" },
    1793: { n: "??" },
    1794: { n: "??" },
    1795: { n: "??" },
    1796: { n: "??" },
    1920: { n: "??" },
    2048: { n: "??" },
    2049: { n: "??" },
    2052: { n: "??" },
    2688: { n: "??" },
    10998: { n: "??" },
    12849: { n: "??" },
    28233: { n: "??" },
    28484: { n: "??" },
    65535: { n: "" }
  };
  var QPWNFTable = {
    5: "dd-mmm-yy",
    6: "dd-mmm",
    7: "mmm-yy",
    8: "mm/dd/yy",
    // Long Date Intl
    10: "hh:mm:ss AM/PM",
    11: "hh:mm AM/PM",
    14: "dd-mmm-yyyy",
    15: "mmm-yyyy",
    /* It is suspected that the the low nybble specifies decimal places */
    34: "0.00",
    50: "0.00;[Red]0.00",
    66: "0.00;(0.00)",
    82: "0.00;[Red](0.00)",
    162: '"$"#,##0.00;\\("$"#,##0.00\\)',
    288: "0%",
    304: "0E+00",
    320: "# ?/?"
  };
  function parse_qpw_str(p4) {
    var cch = p4.read_shift(2);
    var flags = p4.read_shift(1);
    if (flags != 0) throw "unsupported QPW string type " + flags.toString(16);
    return p4.read_shift(cch, "sbcs-cont");
  }
  function qpw_to_workbook_buf(d4, opts) {
    prep_blob(d4, 0);
    var o9 = opts || {};
    if (DENSE != null && o9.dense == null) o9.dense = DENSE;
    var s6 = {};
    if (o9.dense) s6["!data"] = [];
    var SST = [], sname = "", formulae = [];
    var range2 = { s: { r: -1, c: -1 }, e: { r: -1, c: -1 } };
    var cnt = 0, type = 0, C3 = 0, R3 = 0;
    var wb = { SheetNames: [], Sheets: {} };
    var FMTS = [];
    outer: while (d4.l < d4.length) {
      var RT = d4.read_shift(2), length = d4.read_shift(2);
      var p4 = d4.slice(d4.l, d4.l + length);
      prep_blob(p4, 0);
      switch (RT) {
        case 1:
          if (p4.read_shift(4) != 962023505) throw "Bad QPW9 BOF!";
          break;
        case 2:
          break outer;
        case 8:
          break;
        // TODO: this is tied to custom number formats
        case 10:
          {
            var fcnt = p4.read_shift(4);
            var step = (p4.length - p4.l) / fcnt | 0;
            for (var ifmt = 0; ifmt < fcnt; ++ifmt) {
              var end = p4.l + step;
              var fmt = {};
              p4.l += 2;
              fmt.numFmtId = p4.read_shift(2);
              if (QPWNFTable[fmt.numFmtId]) fmt.z = QPWNFTable[fmt.numFmtId];
              p4.l = end;
              FMTS.push(fmt);
            }
          }
          break;
        /* TODO: The behavior here should be consistent with Numbers: QP Notebook ~ .TN.SheetArchive, QP Sheet ~ .TST.TableModelArchive */
        case 1025:
          break;
        case 1026:
          break;
        case 1031:
          {
            p4.l += 12;
            while (p4.l < p4.length) {
              cnt = p4.read_shift(2);
              type = p4.read_shift(1);
              SST.push(p4.read_shift(cnt, "cstr"));
            }
          }
          break;
        case 1032:
          {
          }
          break;
        case 1537:
          {
            var sidx = p4.read_shift(2);
            s6 = {};
            if (o9.dense) s6["!data"] = [];
            range2.s.c = p4.read_shift(2);
            range2.e.c = p4.read_shift(2);
            range2.s.r = p4.read_shift(4);
            range2.e.r = p4.read_shift(4);
            p4.l += 4;
            if (p4.l + 2 < p4.length) {
              cnt = p4.read_shift(2);
              type = p4.read_shift(1);
              sname = cnt == 0 ? "" : p4.read_shift(cnt, "cstr");
            }
            if (!sname) sname = encode_col(sidx);
          }
          break;
        case 1538:
          {
            if (range2.s.c > 255 || range2.s.r > 999999) break;
            if (range2.e.c < range2.s.c) range2.e.c = range2.s.c;
            if (range2.e.r < range2.s.r) range2.e.r = range2.s.r;
            s6["!ref"] = encode_range(range2);
            book_append_sheet(wb, s6, sname);
          }
          break;
        case 2561:
          {
            C3 = p4.read_shift(2);
            if (range2.e.c < C3) range2.e.c = C3;
            if (range2.s.c > C3) range2.s.c = C3;
            R3 = p4.read_shift(4);
            if (range2.s.r > R3) range2.s.r = R3;
            R3 = p4.read_shift(4);
            if (range2.e.r < R3) range2.e.r = R3;
          }
          break;
        case 3073:
          {
            R3 = p4.read_shift(4), cnt = p4.read_shift(4);
            if (range2.s.r > R3) range2.s.r = R3;
            if (range2.e.r < R3 + cnt - 1) range2.e.r = R3 + cnt - 1;
            var CC = encode_col(C3);
            while (p4.l < p4.length) {
              var cell = { t: "z" };
              var flags = p4.read_shift(1), fmtidx = -1;
              if (flags & 128) fmtidx = p4.read_shift(2);
              var mul = flags & 64 ? p4.read_shift(2) - 1 : 0;
              switch (flags & 31) {
                case 0:
                  break;
                case 1:
                  break;
                case 2:
                  cell = { t: "n", v: p4.read_shift(2) };
                  break;
                case 3:
                  cell = { t: "n", v: p4.read_shift(2, "i") };
                  break;
                case 4:
                  cell = { t: "n", v: parse_RkNumber(p4) };
                  break;
                case 5:
                  cell = { t: "n", v: p4.read_shift(8, "f") };
                  break;
                case 7:
                  cell = { t: "s", v: SST[type = p4.read_shift(4) - 1] };
                  break;
                case 8:
                  cell = { t: "n", v: p4.read_shift(8, "f") };
                  p4.l += 2;
                  p4.l += 4;
                  if (isNaN(cell.v)) cell = { t: "e", v: 15 };
                  break;
                default:
                  throw "Unrecognized QPW cell type " + (flags & 31);
              }
              if (fmtidx != -1 && (FMTS[fmtidx - 1] || {}).z) cell.z = FMTS[fmtidx - 1].z;
              var delta = 0;
              if (flags & 32) switch (flags & 31) {
                case 2:
                  delta = p4.read_shift(2);
                  break;
                case 3:
                  delta = p4.read_shift(2, "i");
                  break;
                case 7:
                  delta = p4.read_shift(2);
                  break;
                default:
                  throw "Unsupported delta for QPW cell type " + (flags & 31);
              }
              if (!(!o9.sheetStubs && cell.t == "z")) {
                var newcell = dup(cell);
                if (cell.t == "n" && cell.z && fmt_is_date(cell.z) && o9.cellDates) {
                  newcell.v = numdate(cell.v);
                  newcell.t = typeof newcell.v == "number" ? "n" : "d";
                }
                if (s6["!data"] != null) {
                  if (!s6["!data"][R3]) s6["!data"][R3] = [];
                  s6["!data"][R3][C3] = newcell;
                } else s6[CC + encode_row(R3)] = newcell;
              }
              ++R3;
              --cnt;
              while (mul-- > 0 && cnt >= 0) {
                if (flags & 32) switch (flags & 31) {
                  case 2:
                    cell = { t: "n", v: cell.v + delta & 65535 };
                    break;
                  case 3:
                    cell = { t: "n", v: cell.v + delta & 65535 };
                    if (cell.v > 32767) cell.v -= 65536;
                    break;
                  case 7:
                    cell = { t: "s", v: SST[type = type + delta >>> 0] };
                    break;
                  default:
                    throw "Cannot apply delta for QPW cell type " + (flags & 31);
                }
                else switch (flags & 31) {
                  case 1:
                    cell = { t: "z" };
                    break;
                  case 2:
                    cell = { t: "n", v: p4.read_shift(2) };
                    break;
                  case 7:
                    cell = { t: "s", v: SST[type = p4.read_shift(4) - 1] };
                    break;
                  default:
                    throw "Cannot apply repeat for QPW cell type " + (flags & 31);
                }
                if (fmtidx != -1) ;
                if (!(!o9.sheetStubs && cell.t == "z")) {
                  if (s6["!data"] != null) {
                    if (!s6["!data"][R3]) s6["!data"][R3] = [];
                    s6["!data"][R3][C3] = cell;
                  } else s6[CC + encode_row(R3)] = cell;
                }
                ++R3;
                --cnt;
              }
            }
          }
          break;
        case 3074:
          {
            C3 = p4.read_shift(2);
            R3 = p4.read_shift(4);
            var str2 = parse_qpw_str(p4);
            if (s6["!data"] != null) {
              if (!s6["!data"][R3]) s6["!data"][R3] = [];
              s6["!data"][R3][C3] = { t: "s", v: str2 };
            } else s6[encode_col(C3) + encode_row(R3)] = { t: "s", v: str2 };
          }
          break;
        default:
          break;
      }
      d4.l += length;
    }
    return wb;
  }
  return {
    sheet_to_wk1,
    book_to_wk3,
    to_workbook: lotus_to_workbook
  };
})();
function parse_rpr(rpr) {
  var font = {}, m4 = rpr.match(tagregex), i7 = 0;
  var pass = false;
  if (m4) for (; i7 != m4.length; ++i7) {
    var y4 = parsexmltag(m4[i7]);
    switch (y4[0].replace(/<\w*:/g, "<")) {
      /* 18.8.12 condense CT_BooleanProperty */
      /* ** not required . */
      case "<condense":
        break;
      /* 18.8.17 extend CT_BooleanProperty */
      /* ** not required . */
      case "<extend":
        break;
      /* 18.8.36 shadow CT_BooleanProperty */
      /* ** not required . */
      case "<shadow":
        if (!y4.val) break;
      /* falls through */
      case "<shadow>":
      case "<shadow/>":
        font.shadow = 1;
        break;
      case "</shadow>":
        break;
      /* 18.4.1 charset CT_IntProperty TODO */
      case "<charset":
        if (y4.val == "1") break;
        font.cp = CS2CP[parseInt(y4.val, 10)];
        break;
      /* 18.4.2 outline CT_BooleanProperty TODO */
      case "<outline":
        if (!y4.val) break;
      /* falls through */
      case "<outline>":
      case "<outline/>":
        font.outline = 1;
        break;
      case "</outline>":
        break;
      /* 18.4.5 rFont CT_FontName */
      case "<rFont":
        font.name = y4.val;
        break;
      /* 18.4.11 sz CT_FontSize */
      case "<sz":
        font.sz = y4.val;
        break;
      /* 18.4.10 strike CT_BooleanProperty */
      case "<strike":
        if (!y4.val) break;
      /* falls through */
      case "<strike>":
      case "<strike/>":
        font.strike = 1;
        break;
      case "</strike>":
        break;
      /* 18.4.13 u CT_UnderlineProperty */
      case "<u":
        if (!y4.val) break;
        switch (y4.val) {
          case "double":
            font.uval = "double";
            break;
          case "singleAccounting":
            font.uval = "single-accounting";
            break;
          case "doubleAccounting":
            font.uval = "double-accounting";
            break;
        }
      /* falls through */
      case "<u>":
      case "<u/>":
        font.u = 1;
        break;
      case "</u>":
        break;
      /* 18.8.2 b */
      case "<b":
        if (y4.val == "0") break;
      /* falls through */
      case "<b>":
      case "<b/>":
        font.b = 1;
        break;
      case "</b>":
        break;
      /* 18.8.26 i */
      case "<i":
        if (y4.val == "0") break;
      /* falls through */
      case "<i>":
      case "<i/>":
        font.i = 1;
        break;
      case "</i>":
        break;
      /* 18.3.1.15 color CT_Color TODO: tint, theme, auto, indexed */
      case "<color":
        if (y4.rgb) font.color = y4.rgb.slice(2, 8);
        break;
      case "<color>":
      case "<color/>":
      case "</color>":
        break;
      /* 18.8.18 family ST_FontFamily */
      case "<family":
        font.family = y4.val;
        break;
      case "<family>":
      case "<family/>":
      case "</family>":
        break;
      /* 18.4.14 vertAlign CT_VerticalAlignFontProperty TODO */
      case "<vertAlign":
        font.valign = y4.val;
        break;
      case "<vertAlign>":
      case "<vertAlign/>":
      case "</vertAlign>":
        break;
      /* 18.8.35 scheme CT_FontScheme TODO */
      case "<scheme":
        break;
      case "<scheme>":
      case "<scheme/>":
      case "</scheme>":
        break;
      /* 18.2.10 extLst CT_ExtensionList ? */
      case "<extLst":
      case "<extLst>":
      case "</extLst>":
        break;
      case "<ext":
        pass = true;
        break;
      case "</ext>":
        pass = false;
        break;
      default:
        if (y4[0].charCodeAt(1) !== 47 && !pass) throw new Error("Unrecognized rich format " + y4[0]);
    }
  }
  return font;
}
var parse_rs = /* @__PURE__ */ (function() {
  function parse_r(r8) {
    var t6 = str_match_xml_ns(r8, "t");
    if (!t6) return { t: "s", v: "" };
    var o9 = { t: "s", v: unescapexml(t6[1]) };
    var rpr = str_match_xml_ns(r8, "rPr");
    if (rpr) o9.s = parse_rpr(rpr[1]);
    return o9;
  }
  var rregex = /<(?:\w+:)?r>/g, rend = /<\/(?:\w+:)?r>/;
  return function parse_rs2(rs) {
    return rs.replace(rregex, "").split(rend).map(parse_r).filter(function(r8) {
      return r8.v;
    });
  };
})();
var rs_to_html = /* @__PURE__ */ (function parse_rs_factory() {
  var nlregex = /(\r\n|\n)/g;
  function parse_rpr2(font, intro, outro) {
    var style = [];
    if (font.u) style.push("text-decoration: underline;");
    if (font.uval) style.push("text-underline-style:" + font.uval + ";");
    if (font.sz) style.push("font-size:" + font.sz + "pt;");
    if (font.outline) style.push("text-effect: outline;");
    if (font.shadow) style.push("text-shadow: auto;");
    intro.push('<span style="' + style.join("") + '">');
    if (font.b) {
      intro.push("<b>");
      outro.push("</b>");
    }
    if (font.i) {
      intro.push("<i>");
      outro.push("</i>");
    }
    if (font.strike) {
      intro.push("<s>");
      outro.push("</s>");
    }
    var align = font.valign || "";
    if (align == "superscript" || align == "super") align = "sup";
    else if (align == "subscript") align = "sub";
    if (align != "") {
      intro.push("<" + align + ">");
      outro.push("</" + align + ">");
    }
    outro.push("</span>");
    return font;
  }
  function r_to_html(r8) {
    var terms = [[], r8.v, []];
    if (!r8.v) return "";
    if (r8.s) parse_rpr2(r8.s, terms[0], terms[2]);
    return terms[0].join("") + terms[1].replace(nlregex, "<br/>") + terms[2].join("");
  }
  return function parse_rs2(rs) {
    return rs.map(r_to_html).join("");
  };
})();
var sitregex = /<(?:\w+:)?t\b[^<>]*>([^<]*)<\/(?:\w+:)?t>/g;
var sirregex = /<(?:\w+:)?r\b[^<>]*>/;
function parse_si(x2, opts) {
  var html = opts ? opts.cellHTML : true;
  var z3 = {};
  if (!x2) return { t: "" };
  if (x2.match(/^\s*<(?:\w+:)?t[^>]*>/)) {
    z3.t = unescapexml(utf8read(x2.slice(x2.indexOf(">") + 1).split(/<\/(?:\w+:)?t>/)[0] || ""), true);
    z3.r = utf8read(x2);
    if (html) z3.h = escapehtml(z3.t);
  } else if (
    /*y = */
    x2.match(sirregex)
  ) {
    z3.r = utf8read(x2);
    z3.t = unescapexml(utf8read((str_remove_xml_ns_g(x2, "rPh").match(sitregex) || []).join("").replace(tagregex, "")), true);
    if (html) z3.h = rs_to_html(parse_rs(z3.r));
  }
  return z3;
}
var sstr1 = /<(?:\w+:)?(?:si|sstItem)>/g;
var sstr2 = /<\/(?:\w+:)?(?:si|sstItem)>/;
function parse_sst_xml(data, opts) {
  var s6 = [], ss = "";
  if (!data) return s6;
  var sst = str_match_xml_ns(data, "sst");
  if (sst) {
    ss = sst[1].replace(sstr1, "").split(sstr2);
    for (var i7 = 0; i7 != ss.length; ++i7) {
      var o9 = parse_si(ss[i7].trim(), opts);
      if (o9 != null) s6[s6.length] = o9;
    }
    sst = parsexmltag(sst[0].slice(0, sst[0].indexOf(">")));
    s6.Count = sst.count;
    s6.Unique = sst.uniqueCount;
  }
  return s6;
}
function parse_BrtBeginSst(data) {
  return [data.read_shift(4), data.read_shift(4)];
}
function parse_sst_bin(data, opts) {
  var s6 = [];
  var pass = false;
  recordhopper(data, function hopper_sst(val2, R3, RT) {
    switch (RT) {
      case 159:
        s6.Count = val2[0];
        s6.Unique = val2[1];
        break;
      case 19:
        s6.push(val2);
        break;
      case 160:
        return true;
      case 35:
        pass = true;
        break;
      case 36:
        pass = false;
        break;
      default:
        if (R3.T) {
        }
        if (!pass || opts.WTF) throw new Error("Unexpected record 0x" + RT.toString(16));
    }
  });
  return s6;
}
function _JS2ANSI(str2) {
  if (typeof $cptable !== "undefined") return $cptable.utils.encode(current_ansi, str2);
  var o9 = [], oo = str2.split("");
  for (var i7 = 0; i7 < oo.length; ++i7) o9[i7] = oo[i7].charCodeAt(0);
  return o9;
}
function parse_CRYPTOVersion(blob, length) {
  var o9 = {};
  o9.Major = blob.read_shift(2);
  o9.Minor = blob.read_shift(2);
  if (length >= 4) blob.l += length - 4;
  return o9;
}
function parse_DataSpaceVersionInfo(blob) {
  var o9 = {};
  o9.id = blob.read_shift(0, "lpp4");
  o9.R = parse_CRYPTOVersion(blob, 4);
  o9.U = parse_CRYPTOVersion(blob, 4);
  o9.W = parse_CRYPTOVersion(blob, 4);
  return o9;
}
function parse_DataSpaceMapEntry(blob) {
  var len = blob.read_shift(4);
  var end = blob.l + len - 4;
  var o9 = {};
  var cnt = blob.read_shift(4);
  var comps = [];
  while (cnt-- > 0) comps.push({ t: blob.read_shift(4), v: blob.read_shift(0, "lpp4") });
  o9.name = blob.read_shift(0, "lpp4");
  o9.comps = comps;
  if (blob.l != end) throw new Error("Bad DataSpaceMapEntry: " + blob.l + " != " + end);
  return o9;
}
function parse_DataSpaceMap(blob) {
  var o9 = [];
  blob.l += 4;
  var cnt = blob.read_shift(4);
  while (cnt-- > 0) o9.push(parse_DataSpaceMapEntry(blob));
  return o9;
}
function parse_DataSpaceDefinition(blob) {
  var o9 = [];
  blob.l += 4;
  var cnt = blob.read_shift(4);
  while (cnt-- > 0) o9.push(blob.read_shift(0, "lpp4"));
  return o9;
}
function parse_TransformInfoHeader(blob) {
  var o9 = {};
  blob.read_shift(4);
  blob.l += 4;
  o9.id = blob.read_shift(0, "lpp4");
  o9.name = blob.read_shift(0, "lpp4");
  o9.R = parse_CRYPTOVersion(blob, 4);
  o9.U = parse_CRYPTOVersion(blob, 4);
  o9.W = parse_CRYPTOVersion(blob, 4);
  return o9;
}
function parse_Primary(blob) {
  var hdr = parse_TransformInfoHeader(blob);
  hdr.ename = blob.read_shift(0, "8lpp4");
  hdr.blksz = blob.read_shift(4);
  hdr.cmode = blob.read_shift(4);
  if (blob.read_shift(4) != 4) throw new Error("Bad !Primary record");
  return hdr;
}
function parse_EncryptionHeader(blob, length) {
  var tgt = blob.l + length;
  var o9 = {};
  o9.Flags = blob.read_shift(4) & 63;
  blob.l += 4;
  o9.AlgID = blob.read_shift(4);
  var valid = false;
  switch (o9.AlgID) {
    case 26126:
    case 26127:
    case 26128:
      valid = o9.Flags == 36;
      break;
    case 26625:
      valid = o9.Flags == 4;
      break;
    case 0:
      valid = o9.Flags == 16 || o9.Flags == 4 || o9.Flags == 36;
      break;
    default:
      throw "Unrecognized encryption algorithm: " + o9.AlgID;
  }
  if (!valid) throw new Error("Encryption Flags/AlgID mismatch");
  o9.AlgIDHash = blob.read_shift(4);
  o9.KeySize = blob.read_shift(4);
  o9.ProviderType = blob.read_shift(4);
  blob.l += 8;
  o9.CSPName = blob.read_shift(tgt - blob.l >> 1, "utf16le");
  blob.l = tgt;
  return o9;
}
function parse_EncryptionVerifier(blob, length) {
  var o9 = {}, tgt = blob.l + length;
  blob.l += 4;
  o9.Salt = blob.slice(blob.l, blob.l + 16);
  blob.l += 16;
  o9.Verifier = blob.slice(blob.l, blob.l + 16);
  blob.l += 16;
  blob.read_shift(4);
  o9.VerifierHash = blob.slice(blob.l, tgt);
  blob.l = tgt;
  return o9;
}
function parse_EncryptionInfo(blob) {
  var vers = parse_CRYPTOVersion(blob);
  switch (vers.Minor) {
    case 2:
      return [vers.Minor, parse_EncInfoStd(blob, vers)];
    case 3:
      return [vers.Minor, parse_EncInfoExt(blob, vers)];
    case 4:
      return [vers.Minor, parse_EncInfoAgl(blob, vers)];
  }
  throw new Error("ECMA-376 Encrypted file unrecognized Version: " + vers.Minor);
}
function parse_EncInfoStd(blob) {
  var flags = blob.read_shift(4);
  if ((flags & 63) != 36) throw new Error("EncryptionInfo mismatch");
  var sz = blob.read_shift(4);
  var hdr = parse_EncryptionHeader(blob, sz);
  var verifier = parse_EncryptionVerifier(blob, blob.length - blob.l);
  return { t: "Std", h: hdr, v: verifier };
}
function parse_EncInfoExt() {
  throw new Error("File is password-protected: ECMA-376 Extensible");
}
function parse_EncInfoAgl(blob) {
  var KeyData = ["saltSize", "blockSize", "keyBits", "hashSize", "cipherAlgorithm", "cipherChaining", "hashAlgorithm", "saltValue"];
  blob.l += 4;
  var xml2 = blob.read_shift(blob.length - blob.l, "utf8");
  var o9 = {};
  xml2.replace(tagregex, function xml_agile(x2) {
    var y4 = parsexmltag(x2);
    switch (strip_ns(y4[0])) {
      case "<?xml":
        break;
      case "<encryption":
      case "</encryption>":
        break;
      case "<keyData":
        KeyData.forEach(function(k2) {
          o9[k2] = y4[k2];
        });
        break;
      case "<dataIntegrity":
        o9.encryptedHmacKey = y4.encryptedHmacKey;
        o9.encryptedHmacValue = y4.encryptedHmacValue;
        break;
      case "<keyEncryptors>":
      case "<keyEncryptors":
        o9.encs = [];
        break;
      case "</keyEncryptors>":
        break;
      case "<keyEncryptor":
        o9.uri = y4.uri;
        break;
      case "</keyEncryptor>":
        break;
      case "<encryptedKey":
        o9.encs.push(y4);
        break;
      default:
        throw y4[0];
    }
  });
  return o9;
}
function parse_RC4CryptoHeader(blob, length) {
  var o9 = {};
  var vers = o9.EncryptionVersionInfo = parse_CRYPTOVersion(blob, 4);
  length -= 4;
  if (vers.Minor != 2) throw new Error("unrecognized minor version code: " + vers.Minor);
  if (vers.Major > 4 || vers.Major < 2) throw new Error("unrecognized major version code: " + vers.Major);
  o9.Flags = blob.read_shift(4);
  length -= 4;
  var sz = blob.read_shift(4);
  length -= 4;
  o9.EncryptionHeader = parse_EncryptionHeader(blob, sz);
  length -= sz;
  o9.EncryptionVerifier = parse_EncryptionVerifier(blob, length);
  return o9;
}
function parse_RC4Header(blob) {
  var o9 = {};
  var vers = o9.EncryptionVersionInfo = parse_CRYPTOVersion(blob, 4);
  if (vers.Major != 1 || vers.Minor != 1) throw "unrecognized version code " + vers.Major + " : " + vers.Minor;
  o9.Salt = blob.read_shift(16);
  o9.EncryptedVerifier = blob.read_shift(16);
  o9.EncryptedVerifierHash = blob.read_shift(16);
  return o9;
}
function crypto_CreatePasswordVerifier_Method1(Password) {
  var Verifier = 0, PasswordArray;
  var PasswordDecoded = _JS2ANSI(Password);
  var len = PasswordDecoded.length + 1, i7, PasswordByte;
  var Intermediate1, Intermediate2, Intermediate3;
  PasswordArray = new_raw_buf(len);
  PasswordArray[0] = PasswordDecoded.length;
  for (i7 = 1; i7 != len; ++i7) PasswordArray[i7] = PasswordDecoded[i7 - 1];
  for (i7 = len - 1; i7 >= 0; --i7) {
    PasswordByte = PasswordArray[i7];
    Intermediate1 = (Verifier & 16384) === 0 ? 0 : 1;
    Intermediate2 = Verifier << 1 & 32767;
    Intermediate3 = Intermediate1 | Intermediate2;
    Verifier = Intermediate3 ^ PasswordByte;
  }
  return Verifier ^ 52811;
}
var crypto_CreateXorArray_Method1 = /* @__PURE__ */ (function() {
  var PadArray = [187, 255, 255, 186, 255, 255, 185, 128, 0, 190, 15, 0, 191, 15, 0];
  var InitialCode = [57840, 7439, 52380, 33984, 4364, 3600, 61902, 12606, 6258, 57657, 54287, 34041, 10252, 43370, 20163];
  var XorMatrix = [44796, 19929, 39858, 10053, 20106, 40212, 10761, 31585, 63170, 64933, 60267, 50935, 40399, 11199, 17763, 35526, 1453, 2906, 5812, 11624, 23248, 885, 1770, 3540, 7080, 14160, 28320, 56640, 55369, 41139, 20807, 41614, 21821, 43642, 17621, 28485, 56970, 44341, 19019, 38038, 14605, 29210, 60195, 50791, 40175, 10751, 21502, 43004, 24537, 18387, 36774, 3949, 7898, 15796, 31592, 63184, 47201, 24803, 49606, 37805, 14203, 28406, 56812, 17824, 35648, 1697, 3394, 6788, 13576, 27152, 43601, 17539, 35078, 557, 1114, 2228, 4456, 30388, 60776, 51953, 34243, 7079, 14158, 28316, 14128, 28256, 56512, 43425, 17251, 34502, 7597, 13105, 26210, 52420, 35241, 883, 1766, 3532, 4129, 8258, 16516, 33032, 4657, 9314, 18628];
  var Ror = function(Byte) {
    return (Byte / 2 | Byte * 128) & 255;
  };
  var XorRor = function(byte1, byte2) {
    return Ror(byte1 ^ byte2);
  };
  var CreateXorKey_Method1 = function(Password) {
    var XorKey = InitialCode[Password.length - 1];
    var CurrentElement = 104;
    for (var i7 = Password.length - 1; i7 >= 0; --i7) {
      var Char = Password[i7];
      for (var j3 = 0; j3 != 7; ++j3) {
        if (Char & 64) XorKey ^= XorMatrix[CurrentElement];
        Char *= 2;
        --CurrentElement;
      }
    }
    return XorKey;
  };
  return function(password) {
    var Password = _JS2ANSI(password);
    var XorKey = CreateXorKey_Method1(Password);
    var Index3 = Password.length;
    var ObfuscationArray = new_raw_buf(16);
    for (var i7 = 0; i7 != 16; ++i7) ObfuscationArray[i7] = 0;
    var Temp, PasswordLastChar, PadIndex;
    if ((Index3 & 1) === 1) {
      Temp = XorKey >> 8;
      ObfuscationArray[Index3] = XorRor(PadArray[0], Temp);
      --Index3;
      Temp = XorKey & 255;
      PasswordLastChar = Password[Password.length - 1];
      ObfuscationArray[Index3] = XorRor(PasswordLastChar, Temp);
    }
    while (Index3 > 0) {
      --Index3;
      Temp = XorKey >> 8;
      ObfuscationArray[Index3] = XorRor(Password[Index3], Temp);
      --Index3;
      Temp = XorKey & 255;
      ObfuscationArray[Index3] = XorRor(Password[Index3], Temp);
    }
    Index3 = 15;
    PadIndex = 15 - Password.length;
    while (PadIndex > 0) {
      Temp = XorKey >> 8;
      ObfuscationArray[Index3] = XorRor(PadArray[PadIndex], Temp);
      --Index3;
      --PadIndex;
      Temp = XorKey & 255;
      ObfuscationArray[Index3] = XorRor(Password[Index3], Temp);
      --Index3;
      --PadIndex;
    }
    return ObfuscationArray;
  };
})();
var crypto_DecryptData_Method1 = function(password, Data, XorArrayIndex, XorArray, O2) {
  if (!O2) O2 = Data;
  if (!XorArray) XorArray = crypto_CreateXorArray_Method1(password);
  var Index3, Value;
  for (Index3 = 0; Index3 != Data.length; ++Index3) {
    Value = Data[Index3];
    Value ^= XorArray[XorArrayIndex];
    Value = (Value >> 5 | Value << 3) & 255;
    O2[Index3] = Value;
    ++XorArrayIndex;
  }
  return [O2, XorArrayIndex, XorArray];
};
var crypto_MakeXorDecryptor = function(password) {
  var XorArrayIndex = 0, XorArray = crypto_CreateXorArray_Method1(password);
  return function(Data) {
    var O2 = crypto_DecryptData_Method1("", Data, XorArrayIndex, XorArray);
    XorArrayIndex = O2[1];
    return O2[0];
  };
};
function parse_XORObfuscation(blob, length, opts, out) {
  var o9 = { key: parseuint16(blob), verificationBytes: parseuint16(blob) };
  if (opts.password) o9.verifier = crypto_CreatePasswordVerifier_Method1(opts.password);
  out.valid = o9.verificationBytes === o9.verifier;
  if (out.valid) out.insitu = crypto_MakeXorDecryptor(opts.password);
  return o9;
}
function parse_FilePassHeader(blob, length, oo) {
  var o9 = oo || {};
  o9.Info = blob.read_shift(2);
  blob.l -= 2;
  if (o9.Info === 1) o9.Data = parse_RC4Header(blob, length);
  else o9.Data = parse_RC4CryptoHeader(blob, length);
  return o9;
}
function parse_FilePass(blob, length, opts) {
  var o9 = { Type: opts.biff >= 8 ? blob.read_shift(2) : 0 };
  if (o9.Type) parse_FilePassHeader(blob, length - 2, o9);
  else parse_XORObfuscation(blob, opts.biff >= 8 ? length : length - 2, opts, o9);
  return o9;
}
function rtf_to_sheet(d4, opts) {
  switch (opts.type) {
    case "base64":
      return rtf_to_sheet_str(Base64_decode(d4), opts);
    case "binary":
      return rtf_to_sheet_str(d4, opts);
    case "buffer":
      return rtf_to_sheet_str(has_buf && Buffer.isBuffer(d4) ? d4.toString("binary") : a2s(d4), opts);
    case "array":
      return rtf_to_sheet_str(cc2str(d4), opts);
  }
  throw new Error("Unrecognized type " + opts.type);
}
function rtf_to_sheet_str(str2, opts) {
  var o9 = opts || {};
  var ws = {};
  var dense = o9.dense;
  if (dense)
    ws["!data"] = [];
  var rows = str_match_ng(str2, "\\trowd", "\\row");
  if (!rows)
    throw new Error("RTF missing table");
  var range2 = { s: { c: 0, r: 0 }, e: { c: 0, r: rows.length - 1 } };
  var row = [];
  rows.forEach(function(rowtf, R3) {
    if (dense)
      row = ws["!data"][R3] = [];
    var rtfre = /\\[\w\-]+\b/g;
    var last_index = 0;
    var res;
    var C3 = -1;
    var payload = [];
    while ((res = rtfre.exec(rowtf)) != null) {
      var data = rowtf.slice(last_index, rtfre.lastIndex - res[0].length);
      if (data.charCodeAt(0) == 32)
        data = data.slice(1);
      if (data.length)
        payload.push(data);
      switch (res[0]) {
        case "\\cell":
          ++C3;
          if (payload.length) {
            var cell = { v: payload.join(""), t: "s" };
            if (cell.v == "TRUE" || cell.v == "FALSE") {
              cell.v = cell.v == "TRUE";
              cell.t = "b";
            } else if (!isNaN(fuzzynum(cell.v))) {
              cell.t = "n";
              if (o9.cellText !== false)
                cell.w = cell.v;
              cell.v = fuzzynum(cell.v);
            } else if (RBErr[cell.v] != null) {
              cell.t = "e";
              cell.w = cell.v;
              cell.v = RBErr[cell.v];
            }
            if (dense)
              row[C3] = cell;
            else
              ws[encode_cell({ r: R3, c: C3 })] = cell;
          }
          payload = [];
          break;
        case "\\par":
          payload.push("\n");
          break;
      }
      last_index = rtfre.lastIndex;
    }
    if (C3 > range2.e.c)
      range2.e.c = C3;
  });
  ws["!ref"] = encode_range(range2);
  return ws;
}
function rtf_to_workbook(d4, opts) {
  var wb = sheet_to_workbook(rtf_to_sheet(d4, opts), opts);
  wb.bookType = "rtf";
  return wb;
}
function hex2RGB(h7) {
  var o9 = h7.slice(h7[0] === "#" ? 1 : 0).slice(0, 6);
  return [parseInt(o9.slice(0, 2), 16), parseInt(o9.slice(2, 4), 16), parseInt(o9.slice(4, 6), 16)];
}
function rgb2Hex(rgb) {
  for (var i7 = 0, o9 = 1; i7 != 3; ++i7) o9 = o9 * 256 + (rgb[i7] > 255 ? 255 : rgb[i7] < 0 ? 0 : rgb[i7]);
  return o9.toString(16).toUpperCase().slice(1);
}
function rgb2HSL(rgb) {
  var R3 = rgb[0] / 255, G2 = rgb[1] / 255, B3 = rgb[2] / 255;
  var M4 = Math.max(R3, G2, B3), m4 = Math.min(R3, G2, B3), C3 = M4 - m4;
  if (C3 === 0) return [0, 0, R3];
  var H6 = 0, S5 = 0, L22 = M4 + m4;
  S5 = C3 / (L22 > 1 ? 2 - L22 : L22);
  switch (M4) {
    case R3:
      H6 = ((G2 - B3) / C3 + 6) % 6;
      break;
    case G2:
      H6 = (B3 - R3) / C3 + 2;
      break;
    case B3:
      H6 = (R3 - G2) / C3 + 4;
      break;
  }
  return [H6 / 6, S5, L22 / 2];
}
function hsl2RGB(hsl) {
  var H2 = hsl[0], S5 = hsl[1], L3 = hsl[2];
  var C3 = S5 * 2 * (L3 < 0.5 ? L3 : 1 - L3), m4 = L3 - C3 / 2;
  var rgb = [m4, m4, m4], h62 = 6 * H2;
  var X3;
  if (S5 !== 0) switch (h62 | 0) {
    case 0:
    case 6:
      X3 = C3 * h62;
      rgb[0] += C3;
      rgb[1] += X3;
      break;
    case 1:
      X3 = C3 * (2 - h62);
      rgb[0] += X3;
      rgb[1] += C3;
      break;
    case 2:
      X3 = C3 * (h62 - 2);
      rgb[1] += C3;
      rgb[2] += X3;
      break;
    case 3:
      X3 = C3 * (4 - h62);
      rgb[1] += X3;
      rgb[2] += C3;
      break;
    case 4:
      X3 = C3 * (h62 - 4);
      rgb[2] += C3;
      rgb[0] += X3;
      break;
    case 5:
      X3 = C3 * (6 - h62);
      rgb[2] += X3;
      rgb[0] += C3;
      break;
  }
  for (var i7 = 0; i7 != 3; ++i7) rgb[i7] = Math.round(rgb[i7] * 255);
  return rgb;
}
function rgb_tint(hex, tint) {
  if (tint === 0) return hex;
  var hsl = rgb2HSL(hex2RGB(hex));
  if (tint < 0) hsl[2] = hsl[2] * (1 + tint);
  else hsl[2] = 1 - (1 - hsl[2]) * (1 - tint);
  return rgb2Hex(hsl2RGB(hsl));
}
var DEF_MDW = 6;
var MAX_MDW = 15;
var MIN_MDW = 1;
var MDW = DEF_MDW;
function width2px(width) {
  return Math.floor((width + Math.round(128 / MDW) / 256) * MDW);
}
function px2char(px) {
  return Math.floor((px - 5) / MDW * 100 + 0.5) / 100;
}
function char2width(chr) {
  return Math.round((chr * MDW + 5) / MDW * 256) / 256;
}
function cycle_width(collw) {
  return char2width(px2char(width2px(collw)));
}
function find_mdw_colw(collw) {
  var delta = Math.abs(collw - cycle_width(collw)), _MDW = MDW;
  if (delta > 5e-3) {
    for (MDW = MIN_MDW; MDW < MAX_MDW; ++MDW) if (Math.abs(collw - cycle_width(collw)) <= delta) {
      delta = Math.abs(collw - cycle_width(collw));
      _MDW = MDW;
    }
  }
  MDW = _MDW;
}
function process_col(coll) {
  if (coll.width) {
    coll.wpx = width2px(coll.width);
    coll.wch = px2char(coll.wpx);
    coll.MDW = MDW;
  } else if (coll.wpx) {
    coll.wch = px2char(coll.wpx);
    coll.width = char2width(coll.wch);
    coll.MDW = MDW;
  } else if (typeof coll.wch == "number") {
    coll.width = char2width(coll.wch);
    coll.wpx = width2px(coll.width);
    coll.MDW = MDW;
  }
  if (coll.customWidth) delete coll.customWidth;
}
var DEF_PPI = 96;
var PPI = DEF_PPI;
function px2pt(px) {
  return px * 96 / PPI;
}
function pt2px(pt) {
  return pt * PPI / 96;
}
var XLMLPatternTypeMap = {
  "None": "none",
  "Solid": "solid",
  "Gray50": "mediumGray",
  "Gray75": "darkGray",
  "Gray25": "lightGray",
  "HorzStripe": "darkHorizontal",
  "VertStripe": "darkVertical",
  "ReverseDiagStripe": "darkDown",
  "DiagStripe": "darkUp",
  "DiagCross": "darkGrid",
  "ThickDiagCross": "darkTrellis",
  "ThinHorzStripe": "lightHorizontal",
  "ThinVertStripe": "lightVertical",
  "ThinReverseDiagStripe": "lightDown",
  "ThinHorzCross": "lightGrid"
};
function parse_borders(t6, styles2, themes, opts) {
  styles2.Borders = [];
  var border = {};
  var pass = false;
  (t6.match(tagregex) || []).forEach(function(x2) {
    var y4 = parsexmltag(x2);
    switch (strip_ns(y4[0])) {
      case "<borders":
      case "<borders>":
      case "</borders>":
        break;
      /* 18.8.4 border CT_Border */
      case "<border":
      case "<border>":
      case "<border/>":
        border = /*::(*/
        {};
        if (y4.diagonalUp) border.diagonalUp = parsexmlbool(y4.diagonalUp);
        if (y4.diagonalDown) border.diagonalDown = parsexmlbool(y4.diagonalDown);
        styles2.Borders.push(border);
        break;
      case "</border>":
        break;
      /* note: not in spec, appears to be CT_BorderPr */
      case "<left/>":
        break;
      case "<left":
      case "<left>":
        break;
      case "</left>":
        break;
      /* note: not in spec, appears to be CT_BorderPr */
      case "<right/>":
        break;
      case "<right":
      case "<right>":
        break;
      case "</right>":
        break;
      /* 18.8.43 top CT_BorderPr */
      case "<top/>":
        break;
      case "<top":
      case "<top>":
        break;
      case "</top>":
        break;
      /* 18.8.6 bottom CT_BorderPr */
      case "<bottom/>":
        break;
      case "<bottom":
      case "<bottom>":
        break;
      case "</bottom>":
        break;
      /* 18.8.13 diagonal CT_BorderPr */
      case "<diagonal":
      case "<diagonal>":
      case "<diagonal/>":
        break;
      case "</diagonal>":
        break;
      /* 18.8.25 horizontal CT_BorderPr */
      case "<horizontal":
      case "<horizontal>":
      case "<horizontal/>":
        break;
      case "</horizontal>":
        break;
      /* 18.8.44 vertical CT_BorderPr */
      case "<vertical":
      case "<vertical>":
      case "<vertical/>":
        break;
      case "</vertical>":
        break;
      /* 18.8.37 start CT_BorderPr */
      case "<start":
      case "<start>":
      case "<start/>":
        break;
      case "</start>":
        break;
      /* 18.8.16 end CT_BorderPr */
      case "<end":
      case "<end>":
      case "<end/>":
        break;
      case "</end>":
        break;
      /* 18.8.? color CT_Color */
      case "<color":
      case "<color>":
        break;
      case "<color/>":
      case "</color>":
        break;
      /* 18.2.10 extLst CT_ExtensionList ? */
      case "<extLst":
      case "<extLst>":
      case "</extLst>":
        break;
      case "<ext":
        pass = true;
        break;
      case "</ext>":
        pass = false;
        break;
      default:
        if (opts && opts.WTF) {
          if (!pass) throw new Error("unrecognized " + y4[0] + " in borders");
        }
    }
  });
}
function parse_fills(t6, styles2, themes, opts) {
  styles2.Fills = [];
  var fill2 = {};
  var pass = false;
  (t6.match(tagregex) || []).forEach(function(x2) {
    var y4 = parsexmltag(x2);
    switch (strip_ns(y4[0])) {
      case "<fills":
      case "<fills>":
      case "</fills>":
        break;
      /* 18.8.20 fill CT_Fill */
      case "<fill>":
      case "<fill":
      case "<fill/>":
        fill2 = {};
        styles2.Fills.push(fill2);
        break;
      case "</fill>":
        break;
      /* 18.8.24 gradientFill CT_GradientFill */
      case "<gradientFill>":
        break;
      case "<gradientFill":
      case "</gradientFill>":
        styles2.Fills.push(fill2);
        fill2 = {};
        break;
      /* 18.8.32 patternFill CT_PatternFill */
      case "<patternFill":
      case "<patternFill>":
        if (y4.patternType) fill2.patternType = y4.patternType;
        break;
      case "<patternFill/>":
      case "</patternFill>":
        break;
      /* 18.8.3 bgColor CT_Color */
      case "<bgColor":
        if (!fill2.bgColor) fill2.bgColor = {};
        if (y4.indexed) fill2.bgColor.indexed = parseInt(y4.indexed, 10);
        if (y4.theme) fill2.bgColor.theme = parseInt(y4.theme, 10);
        if (y4.tint) fill2.bgColor.tint = parseFloat(y4.tint);
        if (y4.rgb) fill2.bgColor.rgb = y4.rgb.slice(-6);
        break;
      case "<bgColor/>":
      case "</bgColor>":
        break;
      /* 18.8.19 fgColor CT_Color */
      case "<fgColor":
        if (!fill2.fgColor) fill2.fgColor = {};
        if (y4.theme) fill2.fgColor.theme = parseInt(y4.theme, 10);
        if (y4.tint) fill2.fgColor.tint = parseFloat(y4.tint);
        if (y4.rgb != null) fill2.fgColor.rgb = y4.rgb.slice(-6);
        break;
      case "<fgColor/>":
      case "</fgColor>":
        break;
      /* 18.8.38 stop CT_GradientStop */
      case "<stop":
      case "<stop/>":
        break;
      case "</stop>":
        break;
      /* 18.8.? color CT_Color */
      case "<color":
      case "<color/>":
        break;
      case "</color>":
        break;
      /* 18.2.10 extLst CT_ExtensionList ? */
      case "<extLst":
      case "<extLst>":
      case "</extLst>":
        break;
      case "<ext":
        pass = true;
        break;
      case "</ext>":
        pass = false;
        break;
      default:
        if (opts && opts.WTF) {
          if (!pass) throw new Error("unrecognized " + y4[0] + " in fills");
        }
    }
  });
}
function parse_fonts(t6, styles2, themes, opts) {
  styles2.Fonts = [];
  var font = {};
  var pass = false;
  (t6.match(tagregex) || []).forEach(function(x2) {
    var y4 = parsexmltag(x2);
    switch (strip_ns(y4[0])) {
      case "<fonts":
      case "<fonts>":
      case "</fonts>":
        break;
      /* 18.8.22 font CT_Font */
      case "<font":
      case "<font>":
        break;
      case "</font>":
      case "<font/>":
        styles2.Fonts.push(font);
        font = {};
        break;
      /* 18.8.29 name CT_FontName */
      case "<name":
        if (y4.val) font.name = utf8read(y4.val);
        break;
      case "<name/>":
      case "</name>":
        break;
      /* 18.8.2  b CT_BooleanProperty */
      case "<b":
        font.bold = y4.val ? parsexmlbool(y4.val) : 1;
        break;
      case "<b/>":
        font.bold = 1;
        break;
      case "</b>":
      case "</b":
        break;
      /* 18.8.26 i CT_BooleanProperty */
      case "<i":
        font.italic = y4.val ? parsexmlbool(y4.val) : 1;
        break;
      case "<i/>":
        font.italic = 1;
        break;
      case "</i>":
      case "</i":
        break;
      /* 18.4.13 u CT_UnderlineProperty */
      case "<u":
        switch (y4.val) {
          case "none":
            font.underline = 0;
            break;
          case "single":
            font.underline = 1;
            break;
          case "double":
            font.underline = 2;
            break;
          case "singleAccounting":
            font.underline = 33;
            break;
          case "doubleAccounting":
            font.underline = 34;
            break;
        }
        break;
      case "<u/>":
        font.underline = 1;
        break;
      case "</u>":
      case "</u":
        break;
      /* 18.4.10 strike CT_BooleanProperty */
      case "<strike":
        font.strike = y4.val ? parsexmlbool(y4.val) : 1;
        break;
      case "<strike/>":
        font.strike = 1;
        break;
      case "</strike>":
      case "</strike":
        break;
      /* 18.4.2  outline CT_BooleanProperty */
      case "<outline":
        font.outline = y4.val ? parsexmlbool(y4.val) : 1;
        break;
      case "<outline/>":
        font.outline = 1;
        break;
      case "</outline>":
      case "</outline":
        break;
      /* 18.8.36 shadow CT_BooleanProperty */
      case "<shadow":
        font.shadow = y4.val ? parsexmlbool(y4.val) : 1;
        break;
      case "<shadow/>":
        font.shadow = 1;
        break;
      case "</shadow>":
      case "</shadow":
        break;
      /* 18.8.12 condense CT_BooleanProperty */
      case "<condense":
        font.condense = y4.val ? parsexmlbool(y4.val) : 1;
        break;
      case "<condense/>":
        font.condense = 1;
        break;
      case "</condense>":
      case "</condense":
        break;
      /* 18.8.17 extend CT_BooleanProperty */
      case "<extend":
        font.extend = y4.val ? parsexmlbool(y4.val) : 1;
        break;
      case "<extend/>":
        font.extend = 1;
        break;
      case "</extend>":
      case "</extend":
        break;
      /* 18.4.11 sz CT_FontSize */
      case "<sz":
        if (y4.val) font.sz = +y4.val;
        break;
      case "<sz/>":
      case "</sz>":
      case "</sz":
        break;
      /* 18.4.14 vertAlign CT_VerticalAlignFontProperty */
      case "<vertAlign":
        if (y4.val) font.vertAlign = y4.val;
        break;
      case "<vertAlign/>":
      case "</vertAlign>":
      case "</vertAlign":
        break;
      /* 18.8.18 family CT_FontFamily */
      case "<family":
        if (y4.val) font.family = parseInt(y4.val, 10);
        break;
      case "<family/>":
      case "</family>":
      case "</family":
        break;
      /* 18.8.35 scheme CT_FontScheme */
      case "<scheme":
        if (y4.val) font.scheme = y4.val;
        break;
      case "<scheme/>":
      case "</scheme>":
      case "</scheme":
        break;
      /* 18.4.1 charset CT_IntProperty */
      case "<charset":
        if (y4.val == "1") break;
        y4.codepage = CS2CP[parseInt(y4.val, 10)];
        break;
      case "<charset/>":
      case "</charset>":
      case "</charset":
        break;
      /* 18.?.? color CT_Color */
      case "<color":
        if (!font.color) font.color = {};
        if (y4.auto) font.color.auto = parsexmlbool(y4.auto);
        if (y4.rgb) font.color.rgb = y4.rgb.slice(-6);
        else if (y4.indexed) {
          font.color.index = parseInt(y4.indexed, 10);
          var icv = XLSIcv[font.color.index];
          if (font.color.index == 81) icv = XLSIcv[1];
          if (!icv) icv = XLSIcv[1];
          font.color.rgb = icv[0].toString(16) + icv[1].toString(16) + icv[2].toString(16);
        } else if (y4.theme) {
          font.color.theme = parseInt(y4.theme, 10);
          if (y4.tint) font.color.tint = parseFloat(y4.tint);
          if (y4.theme && themes.themeElements && themes.themeElements.clrScheme) {
            font.color.rgb = rgb_tint(themes.themeElements.clrScheme[font.color.theme].rgb, font.color.tint || 0);
          }
        }
        break;
      case "<color/>":
      case "</color>":
      case "</color":
        break;
      /* note: sometimes mc:AlternateContent appears bare */
      case "<AlternateContent":
        pass = true;
        break;
      case "</AlternateContent>":
      case "</AlternateContent":
        pass = false;
        break;
      /* 18.2.10 extLst CT_ExtensionList ? */
      case "<extLst":
      case "<extLst>":
      case "</extLst>":
        break;
      case "<ext":
        pass = true;
        break;
      case "</ext>":
        pass = false;
        break;
      default:
        if (opts && opts.WTF) {
          if (!pass) throw new Error("unrecognized " + y4[0] + " in fonts");
        }
    }
  });
}
function parse_numFmts(t6, styles2, opts) {
  styles2.NumberFmt = [];
  var k2 = keys(table_fmt);
  for (var i7 = 0; i7 < k2.length; ++i7) styles2.NumberFmt[k2[i7]] = table_fmt[k2[i7]];
  var m4 = t6.match(tagregex);
  if (!m4) return;
  for (i7 = 0; i7 < m4.length; ++i7) {
    var y4 = parsexmltag(m4[i7]);
    switch (strip_ns(y4[0])) {
      case "<numFmts":
      case "</numFmts>":
      case "<numFmts/>":
      case "<numFmts>":
        break;
      case "<numFmt":
        {
          var f4 = unescapexml(utf8read(y4.formatCode)), j3 = parseInt(y4.numFmtId, 10);
          styles2.NumberFmt[j3] = f4;
          if (j3 > 0) {
            if (j3 > 392) {
              for (j3 = 392; j3 > 60; --j3) if (styles2.NumberFmt[j3] == null) break;
              styles2.NumberFmt[j3] = f4;
            }
            SSF__load(f4, j3);
          }
        }
        break;
      case "</numFmt>":
        break;
      default:
        if (opts.WTF) throw new Error("unrecognized " + y4[0] + " in numFmts");
    }
  }
}
var cellXF_uint = ["numFmtId", "fillId", "fontId", "borderId", "xfId"];
var cellXF_bool = ["applyAlignment", "applyBorder", "applyFill", "applyFont", "applyNumberFormat", "applyProtection", "pivotButton", "quotePrefix"];
function parse_cellXfs(t6, styles2, opts) {
  styles2.CellXf = [];
  var xf;
  var pass = false;
  (t6.match(tagregex) || []).forEach(function(x2) {
    var y4 = parsexmltag(x2), i7 = 0;
    switch (strip_ns(y4[0])) {
      case "<cellXfs":
      case "<cellXfs>":
      case "<cellXfs/>":
      case "</cellXfs>":
        break;
      /* 18.8.45 xf CT_Xf */
      case "<xf":
      case "<xf/>":
      case "<xf>":
        xf = y4;
        delete xf[0];
        for (i7 = 0; i7 < cellXF_uint.length; ++i7) if (xf[cellXF_uint[i7]])
          xf[cellXF_uint[i7]] = parseInt(xf[cellXF_uint[i7]], 10);
        for (i7 = 0; i7 < cellXF_bool.length; ++i7) if (xf[cellXF_bool[i7]])
          xf[cellXF_bool[i7]] = parsexmlbool(xf[cellXF_bool[i7]]);
        if (styles2.NumberFmt && xf.numFmtId > 392) {
          for (i7 = 392; i7 > 60; --i7) if (styles2.NumberFmt[xf.numFmtId] == styles2.NumberFmt[i7]) {
            xf.numFmtId = i7;
            break;
          }
        }
        styles2.CellXf.push(xf);
        break;
      case "</xf>":
        break;
      /* 18.8.1 alignment CT_CellAlignment */
      case "<alignment":
      case "<alignment/>":
      case "<alignment>":
        var alignment = {};
        if (y4.vertical) alignment.vertical = y4.vertical;
        if (y4.horizontal) alignment.horizontal = y4.horizontal;
        if (y4.textRotation != null) alignment.textRotation = y4.textRotation;
        if (y4.indent) alignment.indent = y4.indent;
        if (y4.wrapText) alignment.wrapText = parsexmlbool(y4.wrapText);
        xf.alignment = alignment;
        break;
      case "</alignment>":
        break;
      /* 18.8.33 protection CT_CellProtection */
      case "<protection":
      case "<protection>":
        break;
      case "</protection>":
      case "<protection/>":
        break;
      /* note: sometimes mc:AlternateContent appears bare */
      case "<AlternateContent":
      case "<AlternateContent>":
        pass = true;
        break;
      case "</AlternateContent>":
        pass = false;
        break;
      /* 18.2.10 extLst CT_ExtensionList ? */
      case "<extLst":
      case "<extLst>":
      case "</extLst>":
        break;
      case "<ext":
        pass = true;
        break;
      case "</ext>":
        pass = false;
        break;
      default:
        if (opts && opts.WTF) {
          if (!pass) throw new Error("unrecognized " + y4[0] + " in cellXfs");
        }
    }
  });
}
var parse_sty_xml = /* @__PURE__ */ (function make_pstyx() {
  return function parse_sty_xml2(data, themes, opts) {
    var styles2 = {};
    if (!data) return styles2;
    data = remove_doctype(str_remove_ng(data, "<!--", "-->"));
    var t6;
    if (t6 = str_match_xml_ns(data, "numFmts")) parse_numFmts(t6[0], styles2, opts);
    if (t6 = str_match_xml_ns(data, "fonts")) parse_fonts(t6[0], styles2, themes, opts);
    if (t6 = str_match_xml_ns(data, "fills")) parse_fills(t6[0], styles2, themes, opts);
    if (t6 = str_match_xml_ns(data, "borders")) parse_borders(t6[0], styles2, themes, opts);
    if (t6 = str_match_xml_ns(data, "cellXfs")) parse_cellXfs(t6[0], styles2, opts);
    return styles2;
  };
})();
function parse_BrtFmt(data, length) {
  var numFmtId = data.read_shift(2);
  var stFmtCode = parse_XLWideString(data, length - 2);
  return [numFmtId, stFmtCode];
}
function parse_BrtFont(data, length, opts) {
  var out = {};
  out.sz = data.read_shift(2) / 20;
  var grbit = parse_FontFlags(data, 2, opts);
  if (grbit.fItalic) out.italic = 1;
  if (grbit.fCondense) out.condense = 1;
  if (grbit.fExtend) out.extend = 1;
  if (grbit.fShadow) out.shadow = 1;
  if (grbit.fOutline) out.outline = 1;
  if (grbit.fStrikeout) out.strike = 1;
  var bls = data.read_shift(2);
  if (bls === 700) out.bold = 1;
  switch (data.read_shift(2)) {
    /* case 0: out.vertAlign = "baseline"; break; */
    case 1:
      out.vertAlign = "superscript";
      break;
    case 2:
      out.vertAlign = "subscript";
      break;
  }
  var underline = data.read_shift(1);
  if (underline != 0) out.underline = underline;
  var family = data.read_shift(1);
  if (family > 0) out.family = family;
  var bCharSet = data.read_shift(1);
  if (bCharSet > 0) out.charset = bCharSet;
  data.l++;
  out.color = parse_BrtColor(data, 8);
  switch (data.read_shift(1)) {
    /* case 0: out.scheme = "none": break; */
    case 1:
      out.scheme = "major";
      break;
    case 2:
      out.scheme = "minor";
      break;
  }
  out.name = parse_XLWideString(data, length - 21);
  return out;
}
var parse_BrtFill = parsenoop;
function parse_BrtXF(data, length) {
  var tgt = data.l + length;
  var ixfeParent = data.read_shift(2);
  var ifmt = data.read_shift(2);
  data.l = tgt;
  return { ixfe: ixfeParent, numFmtId: ifmt };
}
var parse_BrtBorder = parsenoop;
function parse_sty_bin(data, themes, opts) {
  var styles2 = {};
  styles2.NumberFmt = [];
  for (var y4 in table_fmt) styles2.NumberFmt[y4] = table_fmt[y4];
  styles2.CellXf = [];
  styles2.Fonts = [];
  var state = [];
  var pass = false;
  recordhopper(data, function hopper_sty(val2, R3, RT) {
    switch (RT) {
      case 44:
        styles2.NumberFmt[val2[0]] = val2[1];
        SSF__load(val2[1], val2[0]);
        break;
      case 43:
        styles2.Fonts.push(val2);
        if (val2.color.theme != null && themes && themes.themeElements && themes.themeElements.clrScheme) {
          val2.color.rgb = rgb_tint(themes.themeElements.clrScheme[val2.color.theme].rgb, val2.color.tint || 0);
        }
        break;
      case 1025:
        break;
      case 45:
        break;
      case 46:
        break;
      case 47:
        if (state[state.length - 1] == 617) {
          styles2.CellXf.push(val2);
        }
        break;
      case 48:
      /* BrtStyle */
      case 507:
      /* BrtDXF */
      case 572:
      /* BrtMRUColor */
      case 475:
        break;
      case 1171:
      /* BrtDXF14 */
      case 2102:
      /* BrtDXF15 */
      case 1130:
      /* BrtSlicerStyleElement */
      case 512:
      /* BrtTableStyleElement */
      case 2095:
      /* BrtTimelineStyleElement */
      case 3072:
        break;
      case 35:
        pass = true;
        break;
      case 36:
        pass = false;
        break;
      case 37:
        state.push(RT);
        pass = true;
        break;
      case 38:
        state.pop();
        pass = false;
        break;
      default:
        if (R3.T > 0) state.push(RT);
        else if (R3.T < 0) state.pop();
        else if (!pass || opts.WTF && state[state.length - 1] != 37) throw new Error("Unexpected record 0x" + RT.toString(16));
    }
  });
  return styles2;
}
var XLSXThemeClrScheme = [
  "</a:lt1>",
  "</a:dk1>",
  "</a:lt2>",
  "</a:dk2>",
  "</a:accent1>",
  "</a:accent2>",
  "</a:accent3>",
  "</a:accent4>",
  "</a:accent5>",
  "</a:accent6>",
  "</a:hlink>",
  "</a:folHlink>"
];
function parse_clrScheme(t6, themes, opts) {
  themes.themeElements.clrScheme = [];
  var color = {};
  (t6[0].match(tagregex) || []).forEach(function(x2) {
    var y4 = parsexmltag(x2);
    switch (y4[0]) {
      /* 20.1.6.2 clrScheme (Color Scheme) CT_ColorScheme */
      case "<a:clrScheme":
      case "</a:clrScheme>":
        break;
      /* 20.1.2.3.32 srgbClr CT_SRgbColor */
      case "<a:srgbClr":
        color.rgb = y4.val;
        break;
      case "</a:srgbClr>":
        break;
      /* 20.1.2.3.33 sysClr CT_SystemColor */
      case "<a:sysClr":
        color.rgb = y4.lastClr;
        break;
      case "</a:sysClr>":
        break;
      /* 20.1.4.1.1 accent1 (Accent 1) */
      /* 20.1.4.1.2 accent2 (Accent 2) */
      /* 20.1.4.1.3 accent3 (Accent 3) */
      /* 20.1.4.1.4 accent4 (Accent 4) */
      /* 20.1.4.1.5 accent5 (Accent 5) */
      /* 20.1.4.1.6 accent6 (Accent 6) */
      /* 20.1.4.1.9 dk1 (Dark 1) */
      /* 20.1.4.1.10 dk2 (Dark 2) */
      /* 20.1.4.1.15 folHlink (Followed Hyperlink) */
      /* 20.1.4.1.19 hlink (Hyperlink) */
      /* 20.1.4.1.22 lt1 (Light 1) */
      /* 20.1.4.1.23 lt2 (Light 2) */
      case "</a:dk1>":
      case "</a:lt1>":
      case "<a:dk1>":
      case "<a:lt1>":
      case "<a:dk2>":
      case "</a:dk2>":
      case "<a:lt2>":
      case "</a:lt2>":
      case "<a:accent1>":
      case "</a:accent1>":
      case "<a:accent2>":
      case "</a:accent2>":
      case "<a:accent3>":
      case "</a:accent3>":
      case "<a:accent4>":
      case "</a:accent4>":
      case "<a:accent5>":
      case "</a:accent5>":
      case "<a:accent6>":
      case "</a:accent6>":
      case "<a:hlink>":
      case "</a:hlink>":
      case "<a:folHlink>":
      case "</a:folHlink>":
        if (y4[0].charAt(1) === "/") {
          themes.themeElements.clrScheme[XLSXThemeClrScheme.indexOf(y4[0])] = color;
          color = {};
        } else {
          color.name = y4[0].slice(3, y4[0].length - 1);
        }
        break;
      default:
        if (opts && opts.WTF) throw new Error("Unrecognized " + y4[0] + " in clrScheme");
    }
  });
}
function parse_fontScheme() {
}
function parse_fmtScheme() {
}
function parse_themeElements(data, themes, opts) {
  themes.themeElements = {};
  var t6;
  if (!(t6 = str_match_xml(data, "a:clrScheme"))) throw new Error("clrScheme not found in themeElements");
  parse_clrScheme(t6, themes, opts);
  if (!(t6 = str_match_xml(data, "a:fontScheme"))) throw new Error("fontScheme not found in themeElements");
  parse_fontScheme(t6, themes, opts);
  if (!(t6 = str_match_xml(data, "a:fmtScheme"))) throw new Error("fmtScheme not found in themeElements");
  parse_fmtScheme(t6, themes, opts);
}
function parse_theme_xml(data, opts) {
  if (!data || data.length === 0) data = write_theme();
  var t6;
  var themes = {};
  if (!(t6 = str_match_xml(data, "a:themeElements"))) throw new Error("themeElements not found in theme");
  parse_themeElements(t6[0], themes, opts);
  themes.raw = data;
  return themes;
}
function write_theme(Themes, opts) {
  if (opts && opts.themeXLSX) return opts.themeXLSX;
  if (Themes && typeof Themes.raw == "string") return Themes.raw;
  var o9 = [XML_HEADER];
  o9[o9.length] = '<a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="Office Theme">';
  o9[o9.length] = "<a:themeElements>";
  o9[o9.length] = '<a:clrScheme name="Office">';
  o9[o9.length] = '<a:dk1><a:sysClr val="windowText" lastClr="000000"/></a:dk1>';
  o9[o9.length] = '<a:lt1><a:sysClr val="window" lastClr="FFFFFF"/></a:lt1>';
  o9[o9.length] = '<a:dk2><a:srgbClr val="1F497D"/></a:dk2>';
  o9[o9.length] = '<a:lt2><a:srgbClr val="EEECE1"/></a:lt2>';
  o9[o9.length] = '<a:accent1><a:srgbClr val="4F81BD"/></a:accent1>';
  o9[o9.length] = '<a:accent2><a:srgbClr val="C0504D"/></a:accent2>';
  o9[o9.length] = '<a:accent3><a:srgbClr val="9BBB59"/></a:accent3>';
  o9[o9.length] = '<a:accent4><a:srgbClr val="8064A2"/></a:accent4>';
  o9[o9.length] = '<a:accent5><a:srgbClr val="4BACC6"/></a:accent5>';
  o9[o9.length] = '<a:accent6><a:srgbClr val="F79646"/></a:accent6>';
  o9[o9.length] = '<a:hlink><a:srgbClr val="0000FF"/></a:hlink>';
  o9[o9.length] = '<a:folHlink><a:srgbClr val="800080"/></a:folHlink>';
  o9[o9.length] = "</a:clrScheme>";
  o9[o9.length] = '<a:fontScheme name="Office">';
  o9[o9.length] = "<a:majorFont>";
  o9[o9.length] = '<a:latin typeface="Cambria"/>';
  o9[o9.length] = '<a:ea typeface=""/>';
  o9[o9.length] = '<a:cs typeface=""/>';
  o9[o9.length] = '<a:font script="Jpan" typeface="\uFF2D\uFF33 \uFF30\u30B4\u30B7\u30C3\u30AF"/>';
  o9[o9.length] = '<a:font script="Hang" typeface="\uB9D1\uC740 \uACE0\uB515"/>';
  o9[o9.length] = '<a:font script="Hans" typeface="\u5B8B\u4F53"/>';
  o9[o9.length] = '<a:font script="Hant" typeface="\u65B0\u7D30\u660E\u9AD4"/>';
  o9[o9.length] = '<a:font script="Arab" typeface="Times New Roman"/>';
  o9[o9.length] = '<a:font script="Hebr" typeface="Times New Roman"/>';
  o9[o9.length] = '<a:font script="Thai" typeface="Tahoma"/>';
  o9[o9.length] = '<a:font script="Ethi" typeface="Nyala"/>';
  o9[o9.length] = '<a:font script="Beng" typeface="Vrinda"/>';
  o9[o9.length] = '<a:font script="Gujr" typeface="Shruti"/>';
  o9[o9.length] = '<a:font script="Khmr" typeface="MoolBoran"/>';
  o9[o9.length] = '<a:font script="Knda" typeface="Tunga"/>';
  o9[o9.length] = '<a:font script="Guru" typeface="Raavi"/>';
  o9[o9.length] = '<a:font script="Cans" typeface="Euphemia"/>';
  o9[o9.length] = '<a:font script="Cher" typeface="Plantagenet Cherokee"/>';
  o9[o9.length] = '<a:font script="Yiii" typeface="Microsoft Yi Baiti"/>';
  o9[o9.length] = '<a:font script="Tibt" typeface="Microsoft Himalaya"/>';
  o9[o9.length] = '<a:font script="Thaa" typeface="MV Boli"/>';
  o9[o9.length] = '<a:font script="Deva" typeface="Mangal"/>';
  o9[o9.length] = '<a:font script="Telu" typeface="Gautami"/>';
  o9[o9.length] = '<a:font script="Taml" typeface="Latha"/>';
  o9[o9.length] = '<a:font script="Syrc" typeface="Estrangelo Edessa"/>';
  o9[o9.length] = '<a:font script="Orya" typeface="Kalinga"/>';
  o9[o9.length] = '<a:font script="Mlym" typeface="Kartika"/>';
  o9[o9.length] = '<a:font script="Laoo" typeface="DokChampa"/>';
  o9[o9.length] = '<a:font script="Sinh" typeface="Iskoola Pota"/>';
  o9[o9.length] = '<a:font script="Mong" typeface="Mongolian Baiti"/>';
  o9[o9.length] = '<a:font script="Viet" typeface="Times New Roman"/>';
  o9[o9.length] = '<a:font script="Uigh" typeface="Microsoft Uighur"/>';
  o9[o9.length] = '<a:font script="Geor" typeface="Sylfaen"/>';
  o9[o9.length] = "</a:majorFont>";
  o9[o9.length] = "<a:minorFont>";
  o9[o9.length] = '<a:latin typeface="Calibri"/>';
  o9[o9.length] = '<a:ea typeface=""/>';
  o9[o9.length] = '<a:cs typeface=""/>';
  o9[o9.length] = '<a:font script="Jpan" typeface="\uFF2D\uFF33 \uFF30\u30B4\u30B7\u30C3\u30AF"/>';
  o9[o9.length] = '<a:font script="Hang" typeface="\uB9D1\uC740 \uACE0\uB515"/>';
  o9[o9.length] = '<a:font script="Hans" typeface="\u5B8B\u4F53"/>';
  o9[o9.length] = '<a:font script="Hant" typeface="\u65B0\u7D30\u660E\u9AD4"/>';
  o9[o9.length] = '<a:font script="Arab" typeface="Arial"/>';
  o9[o9.length] = '<a:font script="Hebr" typeface="Arial"/>';
  o9[o9.length] = '<a:font script="Thai" typeface="Tahoma"/>';
  o9[o9.length] = '<a:font script="Ethi" typeface="Nyala"/>';
  o9[o9.length] = '<a:font script="Beng" typeface="Vrinda"/>';
  o9[o9.length] = '<a:font script="Gujr" typeface="Shruti"/>';
  o9[o9.length] = '<a:font script="Khmr" typeface="DaunPenh"/>';
  o9[o9.length] = '<a:font script="Knda" typeface="Tunga"/>';
  o9[o9.length] = '<a:font script="Guru" typeface="Raavi"/>';
  o9[o9.length] = '<a:font script="Cans" typeface="Euphemia"/>';
  o9[o9.length] = '<a:font script="Cher" typeface="Plantagenet Cherokee"/>';
  o9[o9.length] = '<a:font script="Yiii" typeface="Microsoft Yi Baiti"/>';
  o9[o9.length] = '<a:font script="Tibt" typeface="Microsoft Himalaya"/>';
  o9[o9.length] = '<a:font script="Thaa" typeface="MV Boli"/>';
  o9[o9.length] = '<a:font script="Deva" typeface="Mangal"/>';
  o9[o9.length] = '<a:font script="Telu" typeface="Gautami"/>';
  o9[o9.length] = '<a:font script="Taml" typeface="Latha"/>';
  o9[o9.length] = '<a:font script="Syrc" typeface="Estrangelo Edessa"/>';
  o9[o9.length] = '<a:font script="Orya" typeface="Kalinga"/>';
  o9[o9.length] = '<a:font script="Mlym" typeface="Kartika"/>';
  o9[o9.length] = '<a:font script="Laoo" typeface="DokChampa"/>';
  o9[o9.length] = '<a:font script="Sinh" typeface="Iskoola Pota"/>';
  o9[o9.length] = '<a:font script="Mong" typeface="Mongolian Baiti"/>';
  o9[o9.length] = '<a:font script="Viet" typeface="Arial"/>';
  o9[o9.length] = '<a:font script="Uigh" typeface="Microsoft Uighur"/>';
  o9[o9.length] = '<a:font script="Geor" typeface="Sylfaen"/>';
  o9[o9.length] = "</a:minorFont>";
  o9[o9.length] = "</a:fontScheme>";
  o9[o9.length] = '<a:fmtScheme name="Office">';
  o9[o9.length] = "<a:fillStyleLst>";
  o9[o9.length] = '<a:solidFill><a:schemeClr val="phClr"/></a:solidFill>';
  o9[o9.length] = '<a:gradFill rotWithShape="1">';
  o9[o9.length] = "<a:gsLst>";
  o9[o9.length] = '<a:gs pos="0"><a:schemeClr val="phClr"><a:tint val="50000"/><a:satMod val="300000"/></a:schemeClr></a:gs>';
  o9[o9.length] = '<a:gs pos="35000"><a:schemeClr val="phClr"><a:tint val="37000"/><a:satMod val="300000"/></a:schemeClr></a:gs>';
  o9[o9.length] = '<a:gs pos="100000"><a:schemeClr val="phClr"><a:tint val="15000"/><a:satMod val="350000"/></a:schemeClr></a:gs>';
  o9[o9.length] = "</a:gsLst>";
  o9[o9.length] = '<a:lin ang="16200000" scaled="1"/>';
  o9[o9.length] = "</a:gradFill>";
  o9[o9.length] = '<a:gradFill rotWithShape="1">';
  o9[o9.length] = "<a:gsLst>";
  o9[o9.length] = '<a:gs pos="0"><a:schemeClr val="phClr"><a:tint val="100000"/><a:shade val="100000"/><a:satMod val="130000"/></a:schemeClr></a:gs>';
  o9[o9.length] = '<a:gs pos="100000"><a:schemeClr val="phClr"><a:tint val="50000"/><a:shade val="100000"/><a:satMod val="350000"/></a:schemeClr></a:gs>';
  o9[o9.length] = "</a:gsLst>";
  o9[o9.length] = '<a:lin ang="16200000" scaled="0"/>';
  o9[o9.length] = "</a:gradFill>";
  o9[o9.length] = "</a:fillStyleLst>";
  o9[o9.length] = "<a:lnStyleLst>";
  o9[o9.length] = '<a:ln w="9525" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="phClr"><a:shade val="95000"/><a:satMod val="105000"/></a:schemeClr></a:solidFill><a:prstDash val="solid"/></a:ln>';
  o9[o9.length] = '<a:ln w="25400" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:prstDash val="solid"/></a:ln>';
  o9[o9.length] = '<a:ln w="38100" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:prstDash val="solid"/></a:ln>';
  o9[o9.length] = "</a:lnStyleLst>";
  o9[o9.length] = "<a:effectStyleLst>";
  o9[o9.length] = "<a:effectStyle>";
  o9[o9.length] = "<a:effectLst>";
  o9[o9.length] = '<a:outerShdw blurRad="40000" dist="20000" dir="5400000" rotWithShape="0"><a:srgbClr val="000000"><a:alpha val="38000"/></a:srgbClr></a:outerShdw>';
  o9[o9.length] = "</a:effectLst>";
  o9[o9.length] = "</a:effectStyle>";
  o9[o9.length] = "<a:effectStyle>";
  o9[o9.length] = "<a:effectLst>";
  o9[o9.length] = '<a:outerShdw blurRad="40000" dist="23000" dir="5400000" rotWithShape="0"><a:srgbClr val="000000"><a:alpha val="35000"/></a:srgbClr></a:outerShdw>';
  o9[o9.length] = "</a:effectLst>";
  o9[o9.length] = "</a:effectStyle>";
  o9[o9.length] = "<a:effectStyle>";
  o9[o9.length] = "<a:effectLst>";
  o9[o9.length] = '<a:outerShdw blurRad="40000" dist="23000" dir="5400000" rotWithShape="0"><a:srgbClr val="000000"><a:alpha val="35000"/></a:srgbClr></a:outerShdw>';
  o9[o9.length] = "</a:effectLst>";
  o9[o9.length] = '<a:scene3d><a:camera prst="orthographicFront"><a:rot lat="0" lon="0" rev="0"/></a:camera><a:lightRig rig="threePt" dir="t"><a:rot lat="0" lon="0" rev="1200000"/></a:lightRig></a:scene3d>';
  o9[o9.length] = '<a:sp3d><a:bevelT w="63500" h="25400"/></a:sp3d>';
  o9[o9.length] = "</a:effectStyle>";
  o9[o9.length] = "</a:effectStyleLst>";
  o9[o9.length] = "<a:bgFillStyleLst>";
  o9[o9.length] = '<a:solidFill><a:schemeClr val="phClr"/></a:solidFill>';
  o9[o9.length] = '<a:gradFill rotWithShape="1">';
  o9[o9.length] = "<a:gsLst>";
  o9[o9.length] = '<a:gs pos="0"><a:schemeClr val="phClr"><a:tint val="40000"/><a:satMod val="350000"/></a:schemeClr></a:gs>';
  o9[o9.length] = '<a:gs pos="40000"><a:schemeClr val="phClr"><a:tint val="45000"/><a:shade val="99000"/><a:satMod val="350000"/></a:schemeClr></a:gs>';
  o9[o9.length] = '<a:gs pos="100000"><a:schemeClr val="phClr"><a:shade val="20000"/><a:satMod val="255000"/></a:schemeClr></a:gs>';
  o9[o9.length] = "</a:gsLst>";
  o9[o9.length] = '<a:path path="circle"><a:fillToRect l="50000" t="-80000" r="50000" b="180000"/></a:path>';
  o9[o9.length] = "</a:gradFill>";
  o9[o9.length] = '<a:gradFill rotWithShape="1">';
  o9[o9.length] = "<a:gsLst>";
  o9[o9.length] = '<a:gs pos="0"><a:schemeClr val="phClr"><a:tint val="80000"/><a:satMod val="300000"/></a:schemeClr></a:gs>';
  o9[o9.length] = '<a:gs pos="100000"><a:schemeClr val="phClr"><a:shade val="30000"/><a:satMod val="200000"/></a:schemeClr></a:gs>';
  o9[o9.length] = "</a:gsLst>";
  o9[o9.length] = '<a:path path="circle"><a:fillToRect l="50000" t="50000" r="50000" b="50000"/></a:path>';
  o9[o9.length] = "</a:gradFill>";
  o9[o9.length] = "</a:bgFillStyleLst>";
  o9[o9.length] = "</a:fmtScheme>";
  o9[o9.length] = "</a:themeElements>";
  o9[o9.length] = "<a:objectDefaults>";
  o9[o9.length] = "<a:spDef>";
  o9[o9.length] = '<a:spPr/><a:bodyPr/><a:lstStyle/><a:style><a:lnRef idx="1"><a:schemeClr val="accent1"/></a:lnRef><a:fillRef idx="3"><a:schemeClr val="accent1"/></a:fillRef><a:effectRef idx="2"><a:schemeClr val="accent1"/></a:effectRef><a:fontRef idx="minor"><a:schemeClr val="lt1"/></a:fontRef></a:style>';
  o9[o9.length] = "</a:spDef>";
  o9[o9.length] = "<a:lnDef>";
  o9[o9.length] = '<a:spPr/><a:bodyPr/><a:lstStyle/><a:style><a:lnRef idx="2"><a:schemeClr val="accent1"/></a:lnRef><a:fillRef idx="0"><a:schemeClr val="accent1"/></a:fillRef><a:effectRef idx="1"><a:schemeClr val="accent1"/></a:effectRef><a:fontRef idx="minor"><a:schemeClr val="tx1"/></a:fontRef></a:style>';
  o9[o9.length] = "</a:lnDef>";
  o9[o9.length] = "</a:objectDefaults>";
  o9[o9.length] = "<a:extraClrSchemeLst/>";
  o9[o9.length] = "</a:theme>";
  return o9.join("");
}
function parse_Theme(blob, length, opts) {
  var end = blob.l + length;
  var dwThemeVersion = blob.read_shift(4);
  if (dwThemeVersion === 124226) return;
  if (!opts.cellStyles) {
    blob.l = end;
    return;
  }
  var data = blob.slice(blob.l);
  blob.l = end;
  var zip;
  try {
    zip = zip_read(data, { type: "array" });
  } catch (e9) {
    return;
  }
  var themeXML = getzipstr(zip, "theme/theme/theme1.xml", true);
  if (!themeXML) return;
  return parse_theme_xml(themeXML, opts);
}
function parse_ColorTheme(blob) {
  return blob.read_shift(4);
}
function parse_FullColorExt(blob) {
  var o9 = {};
  o9.xclrType = blob.read_shift(2);
  o9.nTintShade = blob.read_shift(2);
  switch (o9.xclrType) {
    case 0:
      blob.l += 4;
      break;
    case 1:
      o9.xclrValue = parse_IcvXF(blob, 4);
      break;
    case 2:
      o9.xclrValue = parse_LongRGBA(blob, 4);
      break;
    case 3:
      o9.xclrValue = parse_ColorTheme(blob, 4);
      break;
    case 4:
      blob.l += 4;
      break;
  }
  blob.l += 8;
  return o9;
}
function parse_IcvXF(blob, length) {
  return parsenoop(blob, length);
}
function parse_XFExtGradient(blob, length) {
  return parsenoop(blob, length);
}
function parse_ExtProp(blob) {
  var extType = blob.read_shift(2);
  var cb = blob.read_shift(2) - 4;
  var o9 = [extType];
  switch (extType) {
    case 4:
    case 5:
    case 7:
    case 8:
    case 9:
    case 10:
    case 11:
    case 13:
      o9[1] = parse_FullColorExt(blob, cb);
      break;
    case 6:
      o9[1] = parse_XFExtGradient(blob, cb);
      break;
    case 14:
    case 15:
      o9[1] = blob.read_shift(cb === 1 ? 1 : 2);
      break;
    default:
      throw new Error("Unrecognized ExtProp type: " + extType + " " + cb);
  }
  return o9;
}
function parse_XFExt(blob, length) {
  var end = blob.l + length;
  blob.l += 2;
  var ixfe = blob.read_shift(2);
  blob.l += 2;
  var cexts = blob.read_shift(2);
  var ext2 = [];
  while (cexts-- > 0) ext2.push(parse_ExtProp(blob, end - blob.l));
  return { ixfe, ext: ext2 };
}
function update_xfext(xf, xfext) {
  xfext.forEach(function(xfe) {
    switch (xfe[0]) {
      /* 2.5.108 extPropData */
      case 4:
        break;
      /* foreground color */
      case 5:
        break;
      /* background color */
      case 6:
        break;
      /* gradient fill */
      case 7:
        break;
      /* top cell border color */
      case 8:
        break;
      /* bottom cell border color */
      case 9:
        break;
      /* left cell border color */
      case 10:
        break;
      /* right cell border color */
      case 11:
        break;
      /* diagonal cell border color */
      case 13:
        break;
      case 14:
        break;
      /* font scheme */
      case 15:
        break;
    }
  });
}
function parse_BrtMdtinfo(data, length) {
  return {
    flags: data.read_shift(4),
    version: data.read_shift(4),
    name: parse_XLWideString(data, length - 8)
  };
}
function parse_BrtMdb(data) {
  var out = [];
  var cnt = data.read_shift(4);
  while (cnt-- > 0)
    out.push([data.read_shift(4), data.read_shift(4)]);
  return out;
}
function parse_BrtBeginEsmdb(data) {
  data.l += 4;
  return data.read_shift(4) != 0;
}
function parse_xlmeta_bin(data, name, _opts) {
  var out = { Types: [], Cell: [], Value: [] };
  var opts = _opts || {};
  var state = [];
  var pass = false;
  var metatype = 2;
  recordhopper(data, function(val2, R3, RT) {
    switch (RT) {
      case 335:
        out.Types.push({ name: val2.name });
        break;
      case 51:
        val2.forEach(function(r8) {
          if (metatype == 1)
            out.Cell.push({ type: out.Types[r8[0] - 1].name, index: r8[1] });
          else if (metatype == 0)
            out.Value.push({ type: out.Types[r8[0] - 1].name, index: r8[1] });
        });
        break;
      case 337:
        metatype = val2 ? 1 : 0;
        break;
      case 338:
        metatype = 2;
        break;
      case 35:
        state.push(RT);
        pass = true;
        break;
      case 36:
        state.pop();
        pass = false;
        break;
      default:
        if (R3.T) {
        } else if (!pass || opts.WTF && state[state.length - 1] != 35)
          throw new Error("Unexpected record 0x" + RT.toString(16));
    }
  });
  return out;
}
function parse_xlmeta_xml(data, name, opts) {
  var out = { Types: [], Cell: [], Value: [] };
  if (!data)
    return out;
  var pass = false;
  var metatype = 2;
  var lastmeta;
  data.replace(tagregex, function(x2) {
    var y4 = parsexmltag(x2);
    switch (strip_ns(y4[0])) {
      case "<?xml":
        break;
      case "<metadata":
      case "</metadata>":
        break;
      case "<metadataTypes":
      case "</metadataTypes>":
        break;
      case "<metadataType":
        out.Types.push({ name: y4.name });
        break;
      case "</metadataType>":
        break;
      case "<futureMetadata":
        for (var j3 = 0; j3 < out.Types.length; ++j3)
          if (out.Types[j3].name == y4.name)
            lastmeta = out.Types[j3];
        break;
      case "</futureMetadata>":
        break;
      case "<bk>":
        break;
      case "</bk>":
        break;
      case "<rc":
        if (metatype == 1)
          out.Cell.push({ type: out.Types[y4.t - 1].name, index: +y4.v });
        else if (metatype == 0)
          out.Value.push({ type: out.Types[y4.t - 1].name, index: +y4.v });
        break;
      case "</rc>":
        break;
      case "<cellMetadata":
        metatype = 1;
        break;
      case "</cellMetadata>":
        metatype = 2;
        break;
      case "<valueMetadata":
        metatype = 0;
        break;
      case "</valueMetadata>":
        metatype = 2;
        break;
      case "<extLst":
      case "<extLst>":
      case "</extLst>":
      case "<extLst/>":
        break;
      case "<ext":
        pass = true;
        break;
      case "</ext>":
        pass = false;
        break;
      case "<rvb":
        if (!lastmeta)
          break;
        if (!lastmeta.offsets)
          lastmeta.offsets = [];
        lastmeta.offsets.push(+y4.i);
        break;
      default:
        if (!pass && (opts == null ? void 0 : opts.WTF))
          throw new Error("unrecognized " + y4[0] + " in metadata");
    }
    return x2;
  });
  return out;
}
function parse_cc_xml(data) {
  var d4 = [];
  if (!data) return d4;
  var i7 = 1;
  (data.match(tagregex) || []).forEach(function(x2) {
    var y4 = parsexmltag(x2);
    switch (y4[0]) {
      case "<?xml":
        break;
      /* 18.6.2  calcChain CT_CalcChain 1 */
      case "<calcChain":
      case "<calcChain>":
      case "</calcChain>":
        break;
      /* 18.6.1  c CT_CalcCell 1 */
      case "<c":
        delete y4[0];
        if (y4.i) i7 = y4.i;
        else y4.i = i7;
        d4.push(y4);
        break;
    }
  });
  return d4;
}
function parse_BrtCalcChainItem$(data) {
  var out = {};
  out.i = data.read_shift(4);
  var cell = {};
  cell.r = data.read_shift(4);
  cell.c = data.read_shift(4);
  out.r = encode_cell(cell);
  var flags = data.read_shift(1);
  if (flags & 2) out.l = "1";
  if (flags & 8) out.a = "1";
  return out;
}
function parse_cc_bin(data, name, opts) {
  var out = [];
  var pass = false;
  recordhopper(data, function hopper_cc(val2, R3, RT) {
    switch (RT) {
      case 63:
        out.push(val2);
        break;
      default:
        if (R3.T) {
        } else if (!pass || opts.WTF) throw new Error("Unexpected record 0x" + RT.toString(16));
    }
  });
  return out;
}
function parse_xlink_xml() {
}
function parse_xlink_bin(data, rel2, name, _opts) {
  if (!data) return data;
  var opts = _opts || {};
  var pass = false, end = false;
  recordhopper(data, function xlink_parse(val2, R3, RT) {
    if (end) return;
    switch (RT) {
      case 359:
      /* 'BrtSupTabs' */
      case 363:
      /* 'BrtExternTableStart' */
      case 364:
      /* 'BrtExternTableEnd' */
      case 366:
      /* 'BrtExternRowHdr' */
      case 367:
      /* 'BrtExternCellBlank' */
      case 368:
      /* 'BrtExternCellReal' */
      case 369:
      /* 'BrtExternCellBool' */
      case 370:
      /* 'BrtExternCellError' */
      case 371:
      /* 'BrtExternCellString' */
      case 472:
      /* 'BrtExternValueMeta' */
      case 577:
      /* 'BrtSupNameStart' */
      case 578:
      /* 'BrtSupNameValueStart' */
      case 579:
      /* 'BrtSupNameValueEnd' */
      case 580:
      /* 'BrtSupNameNum' */
      case 581:
      /* 'BrtSupNameErr' */
      case 582:
      /* 'BrtSupNameSt' */
      case 583:
      /* 'BrtSupNameNil' */
      case 584:
      /* 'BrtSupNameBool' */
      case 585:
      /* 'BrtSupNameFmla' */
      case 586:
      /* 'BrtSupNameBits' */
      case 587:
        break;
      case 35:
        pass = true;
        break;
      case 36:
        pass = false;
        break;
      default:
        if (R3.T) {
        } else if (!pass || opts.WTF) throw new Error("Unexpected record 0x" + RT.toString(16));
    }
  }, opts);
}
function parse_drawing(data, rels) {
  if (!data) return "??";
  var id = (data.match(/<c:chart [^<>]*r:id="([^<>"]*)"/) || ["", ""])[1];
  return rels["!id"][id].Target;
}
function parse_vml(data, sheet, comments) {
  var cidx = 0;
  (str_match_xml_ns_g(data, "shape") || []).forEach(function(m4) {
    var type = "";
    var hidden = true;
    var aidx = -1;
    var R3 = -1, C3 = -1;
    m4.replace(tagregex, function(x2, idx) {
      var y4 = parsexmltag(x2);
      switch (strip_ns(y4[0])) {
        case "<ClientData":
          if (y4.ObjectType) type = y4.ObjectType;
          break;
        case "<Visible":
        case "<Visible/>":
          hidden = false;
          break;
        case "<Row":
        case "<Row>":
          aidx = idx + x2.length;
          break;
        case "</Row>":
          R3 = +m4.slice(aidx, idx).trim();
          break;
        case "<Column":
        case "<Column>":
          aidx = idx + x2.length;
          break;
        case "</Column>":
          C3 = +m4.slice(aidx, idx).trim();
          break;
      }
      return "";
    });
    switch (type) {
      case "Note":
        var cell = ws_get_cell_stub(sheet, R3 >= 0 && C3 >= 0 ? encode_cell({ r: R3, c: C3 }) : comments[cidx].ref);
        if (cell.c) {
          cell.c.hidden = hidden;
        }
        ++cidx;
        break;
    }
  });
}
function sheet_insert_comments(sheet, comments, threaded, people) {
  var dense = sheet["!data"] != null;
  var cell;
  comments.forEach(function(comment) {
    var r8 = decode_cell(comment.ref);
    if (r8.r < 0 || r8.c < 0) return;
    if (dense) {
      if (!sheet["!data"][r8.r]) sheet["!data"][r8.r] = [];
      cell = sheet["!data"][r8.r][r8.c];
    } else cell = sheet[comment.ref];
    if (!cell) {
      cell = { t: "z" };
      if (dense) sheet["!data"][r8.r][r8.c] = cell;
      else sheet[comment.ref] = cell;
      var range2 = safe_decode_range(sheet["!ref"] || "BDWGO1000001:A1");
      if (range2.s.r > r8.r) range2.s.r = r8.r;
      if (range2.e.r < r8.r) range2.e.r = r8.r;
      if (range2.s.c > r8.c) range2.s.c = r8.c;
      if (range2.e.c < r8.c) range2.e.c = r8.c;
      var encoded = encode_range(range2);
      sheet["!ref"] = encoded;
    }
    if (!cell.c) cell.c = [];
    var o9 = { a: comment.author, t: comment.t, r: comment.r, T: threaded };
    if (comment.h) o9.h = comment.h;
    for (var i7 = cell.c.length - 1; i7 >= 0; --i7) {
      if (!threaded && cell.c[i7].T) return;
      if (threaded && !cell.c[i7].T) cell.c.splice(i7, 1);
    }
    if (threaded && people) for (i7 = 0; i7 < people.length; ++i7) {
      if (o9.a == people[i7].id) {
        o9.a = people[i7].name || o9.a;
        break;
      }
    }
    cell.c.push(o9);
  });
}
function parse_comments_xml(data, opts) {
  if (data.match(/<(?:\w+:)?comments *\/>/)) return [];
  var authors = [];
  var commentList = [];
  var authtag = str_match_xml_ns(data, "authors");
  if (authtag && authtag[1]) authtag[1].split(/<\/\w*:?author>/).forEach(function(x2) {
    if (x2 === "" || x2.trim() === "") return;
    var a3 = x2.match(/<(?:\w+:)?author[^<>]*>(.*)/);
    if (a3) authors.push(a3[1]);
  });
  var cmnttag = str_match_xml_ns(data, "commentList");
  if (cmnttag && cmnttag[1]) cmnttag[1].split(/<\/\w*:?comment>/).forEach(function(x2) {
    if (x2 === "" || x2.trim() === "") return;
    var cm = x2.match(/<(?:\w+:)?comment[^<>]*>/);
    if (!cm) return;
    var y4 = parsexmltag(cm[0]);
    var comment = { author: y4.authorId && authors[y4.authorId] || "sheetjsghost", ref: y4.ref, guid: y4.guid };
    var cell = decode_cell(y4.ref);
    if (opts.sheetRows && opts.sheetRows <= cell.r) return;
    var textMatch = str_match_xml_ns(x2, "text");
    var rt = !!textMatch && !!textMatch[1] && parse_si(textMatch[1]) || { r: "", t: "", h: "" };
    comment.r = rt.r;
    if (rt.r == "<t></t>") rt.t = rt.h = "";
    comment.t = (rt.t || "").replace(/\r\n/g, "\n").replace(/\r/g, "\n");
    if (opts.cellHTML) comment.h = rt.h;
    commentList.push(comment);
  });
  return commentList;
}
function parse_tcmnt_xml(data, opts) {
  var out = [];
  var pass = false, comment = {}, tidx = 0;
  data.replace(tagregex, function xml_tcmnt(x2, idx) {
    var y4 = parsexmltag(x2);
    switch (strip_ns(y4[0])) {
      case "<?xml":
        break;
      /* 2.6.207 ThreadedComments CT_ThreadedComments */
      case "<ThreadedComments":
        break;
      case "</ThreadedComments>":
        break;
      /* 2.6.205 threadedComment CT_ThreadedComment */
      case "<threadedComment":
        comment = { author: y4.personId, guid: y4.id, ref: y4.ref, T: 1 };
        break;
      case "</threadedComment>":
        if (comment.t != null) out.push(comment);
        break;
      case "<text>":
      case "<text":
        tidx = idx + x2.length;
        break;
      case "</text>":
        comment.t = data.slice(tidx, idx).replace(/\r\n/g, "\n").replace(/\r/g, "\n");
        break;
      /* 2.6.206 mentions CT_ThreadedCommentMentions TODO */
      case "<mentions":
      case "<mentions>":
        pass = true;
        break;
      case "</mentions>":
        pass = false;
        break;
      /* 2.6.202 mention CT_Mention TODO */
      /* 18.2.10 extLst CT_ExtensionList ? */
      case "<extLst":
      case "<extLst>":
      case "</extLst>":
      case "<extLst/>":
        break;
      /* 18.2.7  ext CT_Extension + */
      case "<ext":
        pass = true;
        break;
      case "</ext>":
        pass = false;
        break;
      default:
        if (!pass && opts.WTF) throw new Error("unrecognized " + y4[0] + " in threaded comments");
    }
    return x2;
  });
  return out;
}
function parse_people_xml(data, opts) {
  var out = [];
  var pass = false;
  data.replace(tagregex, function xml_tcmnt(x2) {
    var y4 = parsexmltag(x2);
    switch (strip_ns(y4[0])) {
      case "<?xml":
        break;
      /* 2.4.85 personList CT_PersonList */
      case "<personList":
        break;
      case "</personList>":
        break;
      /* 2.6.203 person CT_Person TODO: providers */
      case "<person":
        out.push({ name: y4.displayname, id: y4.id });
        break;
      case "</person>":
        break;
      /* 18.2.10 extLst CT_ExtensionList ? */
      case "<extLst":
      case "<extLst>":
      case "</extLst>":
      case "<extLst/>":
        break;
      /* 18.2.7  ext CT_Extension + */
      case "<ext":
        pass = true;
        break;
      case "</ext>":
        pass = false;
        break;
      default:
        if (!pass && opts.WTF) throw new Error("unrecognized " + y4[0] + " in threaded comments");
    }
    return x2;
  });
  return out;
}
function parse_BrtBeginComment(data) {
  var out = {};
  out.iauthor = data.read_shift(4);
  var rfx = parse_UncheckedRfX(data, 16);
  out.rfx = rfx.s;
  out.ref = encode_cell(rfx.s);
  data.l += 16;
  return out;
}
var parse_BrtCommentAuthor = parse_XLWideString;
function parse_comments_bin(data, opts) {
  var out = [];
  var authors = [];
  var c6 = {};
  var pass = false;
  recordhopper(data, function hopper_cmnt(val2, R3, RT) {
    switch (RT) {
      case 632:
        authors.push(val2);
        break;
      case 635:
        c6 = val2;
        break;
      case 637:
        c6.t = val2.t;
        c6.h = val2.h;
        c6.r = val2.r;
        break;
      case 636:
        c6.author = authors[c6.iauthor];
        delete c6.iauthor;
        if (opts.sheetRows && c6.rfx && opts.sheetRows <= c6.rfx.r) break;
        if (!c6.t) c6.t = "";
        delete c6.rfx;
        out.push(c6);
        break;
      case 3072:
        break;
      case 35:
        pass = true;
        break;
      case 36:
        pass = false;
        break;
      case 37:
        break;
      case 38:
        break;
      default:
        if (R3.T) {
        } else if (!pass || opts.WTF) throw new Error("Unexpected record 0x" + RT.toString(16));
    }
  });
  return out;
}
var CT_VBA = "application/vnd.ms-office.vbaProject";
function make_vba_xls(cfb) {
  var newcfb = CFB.utils.cfb_new({ root: "R" });
  cfb.FullPaths.forEach(function(p4, i7) {
    if (p4.slice(-1) === "/" || !p4.match(/_VBA_PROJECT_CUR/))
      return;
    var newpath = p4.replace(/^[^\/]*/, "R").replace(/\/_VBA_PROJECT_CUR\u0000*/, "");
    CFB.utils.cfb_add(newcfb, newpath, cfb.FileIndex[i7].content);
  });
  return CFB.write(newcfb);
}
function parse_ds_bin() {
  return { "!type": "dialog" };
}
function parse_ds_xml() {
  return { "!type": "dialog" };
}
function parse_ms_bin() {
  return { "!type": "macro" };
}
function parse_ms_xml() {
  return { "!type": "macro" };
}
var rc_to_a1 = /* @__PURE__ */ (function() {
  var rcregex = /(^|[^A-Za-z_])R(\[?-?\d+\]|[1-9]\d*|)C(\[?-?\d+\]|[1-9]\d*|)(?![A-Za-z0-9_])/g;
  var rcbase = { r: 0, c: 0 };
  function rcfunc($$, $1, $22, $32) {
    var cRel = false, rRel = false;
    if ($22.length == 0) rRel = true;
    else if ($22.charAt(0) == "[") {
      rRel = true;
      $22 = $22.slice(1, -1);
    }
    if ($32.length == 0) cRel = true;
    else if ($32.charAt(0) == "[") {
      cRel = true;
      $32 = $32.slice(1, -1);
    }
    var R3 = $22.length > 0 ? parseInt($22, 10) | 0 : 0, C3 = $32.length > 0 ? parseInt($32, 10) | 0 : 0;
    if (cRel) C3 += rcbase.c;
    else --C3;
    if (rRel) R3 += rcbase.r;
    else --R3;
    return $1 + (cRel ? "" : "$") + encode_col(C3) + (rRel ? "" : "$") + encode_row(R3);
  }
  return function rc_to_a12(fstr, base) {
    rcbase = base;
    return fstr.replace(rcregex, rcfunc);
  };
})();
var crefregex = /(^|[^._A-Z0-9])(\$?)([A-Z]{1,2}|[A-W][A-Z]{2}|X[A-E][A-Z]|XF[A-D])(\$?)(\d{1,7})(?![_.\(A-Za-z0-9])/g;
try {
  crefregex = /(^|[^._A-Z0-9])([$]?)([A-Z]{1,2}|[A-W][A-Z]{2}|X[A-E][A-Z]|XF[A-D])([$]?)(10[0-3]\d{4}|104[0-7]\d{3}|1048[0-4]\d{2}|10485[0-6]\d|104857[0-6]|[1-9]\d{0,5})(?![_.\(A-Za-z0-9])/g;
} catch (e9) {
}
var a1_to_rc = /* @__PURE__ */ (function() {
  return function a1_to_rc2(fstr, base) {
    return fstr.replace(crefregex, function($0, $1, $22, $32, $4, $5) {
      var c6 = decode_col($32) - ($22 ? 0 : base.c);
      var r8 = decode_row($5) - ($4 ? 0 : base.r);
      var R3 = $4 == "$" ? r8 + 1 : r8 == 0 ? "" : "[" + r8 + "]";
      var C3 = $22 == "$" ? c6 + 1 : c6 == 0 ? "" : "[" + c6 + "]";
      return $1 + "R" + R3 + "C" + C3;
    });
  };
})();
function shift_formula_str(f4, delta) {
  return f4.replace(crefregex, function($0, $1, $22, $32, $4, $5) {
    return $1 + ($22 == "$" ? $22 + $32 : encode_col(decode_col($32) + delta.c)) + ($4 == "$" ? $4 + $5 : encode_row(decode_row($5) + delta.r));
  });
}
function shift_formula_xlsx(f4, range2, cell) {
  var r8 = decode_range(range2), s6 = r8.s, c6 = decode_cell(cell);
  var delta = { r: c6.r - s6.r, c: c6.c - s6.c };
  return shift_formula_str(f4, delta);
}
function fuzzyfmla(f4) {
  if (f4.length == 1) return false;
  return true;
}
function _xlfn(f4) {
  return f4.replace(/_xlfn\./g, "");
}
function parseread1(blob) {
  blob.l += 1;
  return;
}
function parse_ColRelU(blob, length) {
  var c6 = blob.read_shift(length == 1 ? 1 : 2);
  return [c6 & 16383, c6 >> 14 & 1, c6 >> 15 & 1];
}
function parse_RgceArea(blob, length, opts) {
  var w3 = 2;
  if (opts) {
    if (opts.biff >= 2 && opts.biff <= 5) return parse_RgceArea_BIFF2(blob, length, opts);
    else if (opts.biff == 12) w3 = 4;
  }
  var r8 = blob.read_shift(w3), R3 = blob.read_shift(w3);
  var c6 = parse_ColRelU(blob, 2);
  var C3 = parse_ColRelU(blob, 2);
  return { s: { r: r8, c: c6[0], cRel: c6[1], rRel: c6[2] }, e: { r: R3, c: C3[0], cRel: C3[1], rRel: C3[2] } };
}
function parse_RgceArea_BIFF2(blob) {
  var r8 = parse_ColRelU(blob, 2), R3 = parse_ColRelU(blob, 2);
  var c6 = blob.read_shift(1);
  var C3 = blob.read_shift(1);
  return { s: { r: r8[0], c: c6, cRel: r8[1], rRel: r8[2] }, e: { r: R3[0], c: C3, cRel: R3[1], rRel: R3[2] } };
}
function parse_RgceAreaRel(blob, length, opts) {
  if (opts.biff < 8) return parse_RgceArea_BIFF2(blob, length, opts);
  var r8 = blob.read_shift(opts.biff == 12 ? 4 : 2), R3 = blob.read_shift(opts.biff == 12 ? 4 : 2);
  var c6 = parse_ColRelU(blob, 2);
  var C3 = parse_ColRelU(blob, 2);
  return { s: { r: r8, c: c6[0], cRel: c6[1], rRel: c6[2] }, e: { r: R3, c: C3[0], cRel: C3[1], rRel: C3[2] } };
}
function parse_RgceLoc(blob, length, opts) {
  if (opts && opts.biff >= 2 && opts.biff <= 5) return parse_RgceLoc_BIFF2(blob, length, opts);
  var r8 = blob.read_shift(opts && opts.biff == 12 ? 4 : 2);
  var c6 = parse_ColRelU(blob, 2);
  return { r: r8, c: c6[0], cRel: c6[1], rRel: c6[2] };
}
function parse_RgceLoc_BIFF2(blob) {
  var r8 = parse_ColRelU(blob, 2);
  var c6 = blob.read_shift(1);
  return { r: r8[0], c: c6, cRel: r8[1], rRel: r8[2] };
}
function parse_RgceElfLoc(blob) {
  var r8 = blob.read_shift(2);
  var c6 = blob.read_shift(2);
  return { r: r8, c: c6 & 255, fQuoted: !!(c6 & 16384), cRel: c6 >> 15, rRel: c6 >> 15 };
}
function parse_RgceLocRel(blob, length, opts) {
  var biff = opts && opts.biff ? opts.biff : 8;
  if (biff >= 2 && biff <= 5) return parse_RgceLocRel_BIFF2(blob, length, opts);
  var r8 = blob.read_shift(biff >= 12 ? 4 : 2);
  var cl = blob.read_shift(2);
  var cRel = (cl & 16384) >> 14, rRel = (cl & 32768) >> 15;
  cl &= 16383;
  if (rRel == 1) while (r8 > 524287) r8 -= 1048576;
  if (cRel == 1) while (cl > 8191) cl = cl - 16384;
  return { r: r8, c: cl, cRel, rRel };
}
function parse_RgceLocRel_BIFF2(blob) {
  var rl = blob.read_shift(2);
  var c6 = blob.read_shift(1);
  var rRel = (rl & 32768) >> 15, cRel = (rl & 16384) >> 14;
  rl &= 16383;
  if (rRel == 1 && rl >= 8192) rl = rl - 16384;
  if (cRel == 1 && c6 >= 128) c6 = c6 - 256;
  return { r: rl, c: c6, cRel, rRel };
}
function parse_PtgArea(blob, length, opts) {
  var type = (blob[blob.l++] & 96) >> 5;
  var area = parse_RgceArea(blob, opts.biff >= 2 && opts.biff <= 5 ? 6 : 8, opts);
  return [type, area];
}
function parse_PtgArea3d(blob, length, opts) {
  var type = (blob[blob.l++] & 96) >> 5;
  var ixti = blob.read_shift(2, "i");
  var w3 = 8;
  if (opts) switch (opts.biff) {
    case 5:
      blob.l += 12;
      w3 = 6;
      break;
    case 12:
      w3 = 12;
      break;
  }
  var area = parse_RgceArea(blob, w3, opts);
  return [type, ixti, area];
}
function parse_PtgAreaErr(blob, length, opts) {
  var type = (blob[blob.l++] & 96) >> 5;
  blob.l += opts && opts.biff > 8 ? 12 : opts.biff < 8 ? 6 : 8;
  return [type];
}
function parse_PtgAreaErr3d(blob, length, opts) {
  var type = (blob[blob.l++] & 96) >> 5;
  var ixti = blob.read_shift(2);
  var w3 = 8;
  if (opts) switch (opts.biff) {
    case 5:
      blob.l += 12;
      w3 = 6;
      break;
    case 12:
      w3 = 12;
      break;
  }
  blob.l += w3;
  return [type, ixti];
}
function parse_PtgAreaN(blob, length, opts) {
  var type = (blob[blob.l++] & 96) >> 5;
  var area = parse_RgceAreaRel(blob, length - 1, opts);
  return [type, area];
}
function parse_PtgArray(blob, length, opts) {
  var type = (blob[blob.l++] & 96) >> 5;
  blob.l += opts.biff == 2 ? 6 : opts.biff == 12 ? 14 : 7;
  return [type];
}
function parse_PtgAttrBaxcel(blob) {
  var bitSemi = blob[blob.l + 1] & 1;
  var bitBaxcel = 1;
  blob.l += 4;
  return [bitSemi, bitBaxcel];
}
function parse_PtgAttrChoose(blob, length, opts) {
  blob.l += 2;
  var offset = blob.read_shift(opts && opts.biff == 2 ? 1 : 2);
  var o9 = [];
  for (var i7 = 0; i7 <= offset; ++i7) o9.push(blob.read_shift(opts && opts.biff == 2 ? 1 : 2));
  return o9;
}
function parse_PtgAttrGoto(blob, length, opts) {
  var bitGoto = blob[blob.l + 1] & 255 ? 1 : 0;
  blob.l += 2;
  return [bitGoto, blob.read_shift(opts && opts.biff == 2 ? 1 : 2)];
}
function parse_PtgAttrIf(blob, length, opts) {
  var bitIf = blob[blob.l + 1] & 255 ? 1 : 0;
  blob.l += 2;
  return [bitIf, blob.read_shift(opts && opts.biff == 2 ? 1 : 2)];
}
function parse_PtgAttrIfError(blob) {
  var bitIf = blob[blob.l + 1] & 255 ? 1 : 0;
  blob.l += 2;
  return [bitIf, blob.read_shift(2)];
}
function parse_PtgAttrSemi(blob, length, opts) {
  var bitSemi = blob[blob.l + 1] & 255 ? 1 : 0;
  blob.l += opts && opts.biff == 2 ? 3 : 4;
  return [bitSemi];
}
function parse_PtgAttrSpaceType(blob) {
  var type = blob.read_shift(1), cch = blob.read_shift(1);
  return [type, cch];
}
function parse_PtgAttrSpace(blob) {
  blob.read_shift(2);
  return parse_PtgAttrSpaceType(blob, 2);
}
function parse_PtgAttrSpaceSemi(blob) {
  blob.read_shift(2);
  return parse_PtgAttrSpaceType(blob, 2);
}
function parse_PtgRef(blob, length, opts) {
  var type = (blob[blob.l] & 96) >> 5;
  blob.l += 1;
  var loc = parse_RgceLoc(blob, 0, opts);
  return [type, loc];
}
function parse_PtgRefN(blob, length, opts) {
  var type = (blob[blob.l] & 96) >> 5;
  blob.l += 1;
  var loc = parse_RgceLocRel(blob, 0, opts);
  return [type, loc];
}
function parse_PtgRef3d(blob, length, opts) {
  var type = (blob[blob.l] & 96) >> 5;
  blob.l += 1;
  var ixti = blob.read_shift(2);
  if (opts && opts.biff == 5) blob.l += 12;
  var loc = parse_RgceLoc(blob, 0, opts);
  return [type, ixti, loc];
}
function parse_PtgFunc(blob, length, opts) {
  var type = (blob[blob.l] & 96) >> 5;
  blob.l += 1;
  var iftab = blob.read_shift(opts && opts.biff <= 3 ? 1 : 2);
  return [FtabArgc[iftab], Ftab[iftab], type];
}
function parse_PtgFuncVar(blob, length, opts) {
  var type = blob[blob.l++];
  var cparams = blob.read_shift(1), tab = opts && opts.biff <= 3 ? [type == 88 ? -1 : 0, blob.read_shift(1)] : parsetab(blob);
  return [cparams, (tab[0] === 0 ? Ftab : Cetab)[tab[1]]];
}
function parsetab(blob) {
  return [blob[blob.l + 1] >> 7, blob.read_shift(2) & 32767];
}
function parse_PtgAttrSum(blob, length, opts) {
  blob.l += opts && opts.biff == 2 ? 3 : 4;
  return;
}
function parse_PtgExp(blob, length, opts) {
  blob.l++;
  if (opts && opts.biff == 12) return [blob.read_shift(4, "i"), 0];
  var row = blob.read_shift(2);
  var col = blob.read_shift(opts && opts.biff == 2 ? 1 : 2);
  return [row, col];
}
function parse_PtgErr(blob) {
  blob.l++;
  return BErr[blob.read_shift(1)];
}
function parse_PtgInt(blob) {
  blob.l++;
  return blob.read_shift(2);
}
function parse_PtgBool(blob) {
  blob.l++;
  return blob.read_shift(1) !== 0;
}
function parse_PtgNum(blob) {
  blob.l++;
  return parse_Xnum(blob, 8);
}
function parse_PtgStr(blob, length, opts) {
  blob.l++;
  return parse_ShortXLUnicodeString(blob, length - 1, opts);
}
function parse_SerAr(blob, biff) {
  var val2 = [blob.read_shift(1)];
  if (biff == 12) switch (val2[0]) {
    case 2:
      val2[0] = 4;
      break;
    /* SerBool */
    case 4:
      val2[0] = 16;
      break;
    /* SerErr */
    case 0:
      val2[0] = 1;
      break;
    /* SerNum */
    case 1:
      val2[0] = 2;
      break;
  }
  switch (val2[0]) {
    case 4:
      val2[1] = parsebool(blob, 1) ? "TRUE" : "FALSE";
      if (biff != 12) blob.l += 7;
      break;
    case 37:
    /* appears to be an alias */
    case 16:
      val2[1] = BErr[blob[blob.l]];
      blob.l += biff == 12 ? 4 : 8;
      break;
    case 0:
      blob.l += 8;
      break;
    case 1:
      val2[1] = parse_Xnum(blob, 8);
      break;
    case 2:
      val2[1] = parse_XLUnicodeString2(blob, 0, { biff: biff > 0 && biff < 8 ? 2 : biff });
      break;
    default:
      throw new Error("Bad SerAr: " + val2[0]);
  }
  return val2;
}
function parse_PtgExtraMem(blob, cce, opts) {
  var count = blob.read_shift(opts.biff == 12 ? 4 : 2);
  var out = [];
  for (var i7 = 0; i7 != count; ++i7) out.push((opts.biff == 12 ? parse_UncheckedRfX : parse_Ref8U)(blob, 8));
  return out;
}
function parse_PtgExtraArray(blob, length, opts) {
  var rows = 0, cols = 0;
  if (opts.biff == 12) {
    rows = blob.read_shift(4);
    cols = blob.read_shift(4);
  } else {
    cols = 1 + blob.read_shift(1);
    rows = 1 + blob.read_shift(2);
  }
  if (opts.biff >= 2 && opts.biff < 8) {
    --rows;
    if (--cols == 0) cols = 256;
  }
  for (var i7 = 0, o9 = []; i7 != rows && (o9[i7] = []); ++i7)
    for (var j3 = 0; j3 != cols; ++j3) o9[i7][j3] = parse_SerAr(blob, opts.biff);
  return o9;
}
function parse_PtgName(blob, length, opts) {
  var type = blob.read_shift(1) >>> 5 & 3;
  var w3 = !opts || opts.biff >= 8 ? 4 : 2;
  var nameindex = blob.read_shift(w3);
  switch (opts.biff) {
    case 2:
      blob.l += 5;
      break;
    case 3:
    case 4:
      blob.l += 8;
      break;
    case 5:
      blob.l += 12;
      break;
  }
  return [type, 0, nameindex];
}
function parse_PtgNameX(blob, length, opts) {
  if (opts.biff == 5) return parse_PtgNameX_BIFF5(blob, length, opts);
  var type = blob.read_shift(1) >>> 5 & 3;
  var ixti = blob.read_shift(2);
  var nameindex = blob.read_shift(4);
  return [type, ixti, nameindex];
}
function parse_PtgNameX_BIFF5(blob) {
  var type = blob.read_shift(1) >>> 5 & 3;
  var ixti = blob.read_shift(2, "i");
  blob.l += 8;
  var nameindex = blob.read_shift(2);
  blob.l += 12;
  return [type, ixti, nameindex];
}
function parse_PtgMemArea(blob, length, opts) {
  var type = blob.read_shift(1) >>> 5 & 3;
  blob.l += opts && opts.biff == 2 ? 3 : 4;
  var cce = blob.read_shift(opts && opts.biff == 2 ? 1 : 2);
  return [type, cce];
}
function parse_PtgMemFunc(blob, length, opts) {
  var type = blob.read_shift(1) >>> 5 & 3;
  var cce = blob.read_shift(opts && opts.biff == 2 ? 1 : 2);
  return [type, cce];
}
function parse_PtgRefErr(blob, length, opts) {
  var type = blob.read_shift(1) >>> 5 & 3;
  blob.l += 4;
  if (opts.biff < 8) blob.l--;
  if (opts.biff == 12) blob.l += 2;
  return [type];
}
function parse_PtgRefErr3d(blob, length, opts) {
  var type = (blob[blob.l++] & 96) >> 5;
  var ixti = blob.read_shift(2);
  var w3 = 4;
  if (opts) switch (opts.biff) {
    case 5:
      w3 = 15;
      break;
    case 12:
      w3 = 6;
      break;
  }
  blob.l += w3;
  return [type, ixti];
}
var parse_PtgMemErr = parsenoop;
var parse_PtgMemNoMem = parsenoop;
var parse_PtgTbl = parsenoop;
function parse_PtgElfLoc(blob, length, opts) {
  blob.l += 2;
  return [parse_RgceElfLoc(blob, 4, opts)];
}
function parse_PtgElfNoop(blob) {
  blob.l += 6;
  return [];
}
var parse_PtgElfCol = parse_PtgElfLoc;
var parse_PtgElfColS = parse_PtgElfNoop;
var parse_PtgElfColSV = parse_PtgElfNoop;
var parse_PtgElfColV = parse_PtgElfLoc;
function parse_PtgElfLel(blob) {
  blob.l += 2;
  return [parseuint16(blob), blob.read_shift(2) & 1];
}
var parse_PtgElfRadical = parse_PtgElfLoc;
var parse_PtgElfRadicalLel = parse_PtgElfLel;
var parse_PtgElfRadicalS = parse_PtgElfNoop;
var parse_PtgElfRw = parse_PtgElfLoc;
var parse_PtgElfRwV = parse_PtgElfLoc;
var PtgListRT = [
  "Data",
  "All",
  "Headers",
  "??",
  "?Data2",
  "??",
  "?DataHeaders",
  "??",
  "Totals",
  "??",
  "??",
  "??",
  "?DataTotals",
  "??",
  "??",
  "??",
  "?Current"
];
function parse_PtgList(blob) {
  blob.l += 2;
  var ixti = blob.read_shift(2);
  var flags = blob.read_shift(2);
  var idx = blob.read_shift(4);
  var c6 = blob.read_shift(2);
  var C3 = blob.read_shift(2);
  var rt = PtgListRT[flags >> 2 & 31];
  return { ixti, coltype: flags & 3, rt, idx, c: c6, C: C3 };
}
function parse_PtgSxName(blob) {
  blob.l += 2;
  return [blob.read_shift(4)];
}
function parse_PtgSheet(blob, length, opts) {
  blob.l += 5;
  blob.l += 2;
  blob.l += opts.biff == 2 ? 1 : 4;
  return ["PTGSHEET"];
}
function parse_PtgEndSheet(blob, length, opts) {
  blob.l += opts.biff == 2 ? 4 : 5;
  return ["PTGENDSHEET"];
}
function parse_PtgMemAreaN(blob) {
  var type = blob.read_shift(1) >>> 5 & 3;
  var cce = blob.read_shift(2);
  return [type, cce];
}
function parse_PtgMemNoMemN(blob) {
  var type = blob.read_shift(1) >>> 5 & 3;
  var cce = blob.read_shift(2);
  return [type, cce];
}
function parse_PtgAttrNoop(blob) {
  blob.l += 4;
  return [0, 0];
}
var PtgTypes = {
  1: { n: "PtgExp", f: parse_PtgExp },
  2: { n: "PtgTbl", f: parse_PtgTbl },
  3: { n: "PtgAdd", f: parseread1 },
  4: { n: "PtgSub", f: parseread1 },
  5: { n: "PtgMul", f: parseread1 },
  6: { n: "PtgDiv", f: parseread1 },
  7: { n: "PtgPower", f: parseread1 },
  8: { n: "PtgConcat", f: parseread1 },
  9: { n: "PtgLt", f: parseread1 },
  10: { n: "PtgLe", f: parseread1 },
  11: { n: "PtgEq", f: parseread1 },
  12: { n: "PtgGe", f: parseread1 },
  13: { n: "PtgGt", f: parseread1 },
  14: { n: "PtgNe", f: parseread1 },
  15: { n: "PtgIsect", f: parseread1 },
  16: { n: "PtgUnion", f: parseread1 },
  17: { n: "PtgRange", f: parseread1 },
  18: { n: "PtgUplus", f: parseread1 },
  19: { n: "PtgUminus", f: parseread1 },
  20: { n: "PtgPercent", f: parseread1 },
  21: { n: "PtgParen", f: parseread1 },
  22: { n: "PtgMissArg", f: parseread1 },
  23: { n: "PtgStr", f: parse_PtgStr },
  26: { n: "PtgSheet", f: parse_PtgSheet },
  27: { n: "PtgEndSheet", f: parse_PtgEndSheet },
  28: { n: "PtgErr", f: parse_PtgErr },
  29: { n: "PtgBool", f: parse_PtgBool },
  30: { n: "PtgInt", f: parse_PtgInt },
  31: { n: "PtgNum", f: parse_PtgNum },
  32: { n: "PtgArray", f: parse_PtgArray },
  33: { n: "PtgFunc", f: parse_PtgFunc },
  34: { n: "PtgFuncVar", f: parse_PtgFuncVar },
  35: { n: "PtgName", f: parse_PtgName },
  36: { n: "PtgRef", f: parse_PtgRef },
  37: { n: "PtgArea", f: parse_PtgArea },
  38: { n: "PtgMemArea", f: parse_PtgMemArea },
  39: { n: "PtgMemErr", f: parse_PtgMemErr },
  40: { n: "PtgMemNoMem", f: parse_PtgMemNoMem },
  41: { n: "PtgMemFunc", f: parse_PtgMemFunc },
  42: { n: "PtgRefErr", f: parse_PtgRefErr },
  43: { n: "PtgAreaErr", f: parse_PtgAreaErr },
  44: { n: "PtgRefN", f: parse_PtgRefN },
  45: { n: "PtgAreaN", f: parse_PtgAreaN },
  46: { n: "PtgMemAreaN", f: parse_PtgMemAreaN },
  47: { n: "PtgMemNoMemN", f: parse_PtgMemNoMemN },
  57: { n: "PtgNameX", f: parse_PtgNameX },
  58: { n: "PtgRef3d", f: parse_PtgRef3d },
  59: { n: "PtgArea3d", f: parse_PtgArea3d },
  60: { n: "PtgRefErr3d", f: parse_PtgRefErr3d },
  61: { n: "PtgAreaErr3d", f: parse_PtgAreaErr3d },
  255: {}
};
var PtgDupes = {
  64: 32,
  96: 32,
  65: 33,
  97: 33,
  66: 34,
  98: 34,
  67: 35,
  99: 35,
  68: 36,
  100: 36,
  69: 37,
  101: 37,
  70: 38,
  102: 38,
  71: 39,
  103: 39,
  72: 40,
  104: 40,
  73: 41,
  105: 41,
  74: 42,
  106: 42,
  75: 43,
  107: 43,
  76: 44,
  108: 44,
  77: 45,
  109: 45,
  78: 46,
  110: 46,
  79: 47,
  111: 47,
  88: 34,
  120: 34,
  89: 57,
  121: 57,
  90: 58,
  122: 58,
  91: 59,
  123: 59,
  92: 60,
  124: 60,
  93: 61,
  125: 61
};
var Ptg18 = {
  1: { n: "PtgElfLel", f: parse_PtgElfLel },
  2: { n: "PtgElfRw", f: parse_PtgElfRw },
  3: { n: "PtgElfCol", f: parse_PtgElfCol },
  6: { n: "PtgElfRwV", f: parse_PtgElfRwV },
  7: { n: "PtgElfColV", f: parse_PtgElfColV },
  10: { n: "PtgElfRadical", f: parse_PtgElfRadical },
  11: { n: "PtgElfRadicalS", f: parse_PtgElfRadicalS },
  13: { n: "PtgElfColS", f: parse_PtgElfColS },
  15: { n: "PtgElfColSV", f: parse_PtgElfColSV },
  16: { n: "PtgElfRadicalLel", f: parse_PtgElfRadicalLel },
  25: { n: "PtgList", f: parse_PtgList },
  29: { n: "PtgSxName", f: parse_PtgSxName },
  255: {}
};
var Ptg19 = {
  0: { n: "PtgAttrNoop", f: parse_PtgAttrNoop },
  1: { n: "PtgAttrSemi", f: parse_PtgAttrSemi },
  2: { n: "PtgAttrIf", f: parse_PtgAttrIf },
  4: { n: "PtgAttrChoose", f: parse_PtgAttrChoose },
  8: { n: "PtgAttrGoto", f: parse_PtgAttrGoto },
  16: { n: "PtgAttrSum", f: parse_PtgAttrSum },
  32: { n: "PtgAttrBaxcel", f: parse_PtgAttrBaxcel },
  33: { n: "PtgAttrBaxcel", f: parse_PtgAttrBaxcel },
  64: { n: "PtgAttrSpace", f: parse_PtgAttrSpace },
  65: { n: "PtgAttrSpaceSemi", f: parse_PtgAttrSpaceSemi },
  128: { n: "PtgAttrIfError", f: parse_PtgAttrIfError },
  255: {}
};
function parse_RgbExtra(blob, length, rgce, opts) {
  if (opts.biff < 8) return parsenoop(blob, length);
  var target = blob.l + length;
  var o9 = [];
  for (var i7 = 0; i7 !== rgce.length; ++i7) {
    switch (rgce[i7][0]) {
      case "PtgArray":
        rgce[i7][1] = parse_PtgExtraArray(blob, 0, opts);
        o9.push(rgce[i7][1]);
        break;
      case "PtgMemArea":
        rgce[i7][2] = parse_PtgExtraMem(blob, rgce[i7][1], opts);
        o9.push(rgce[i7][2]);
        break;
      case "PtgExp":
        if (opts && opts.biff == 12) {
          rgce[i7][1][1] = blob.read_shift(4);
          o9.push(rgce[i7][1]);
        }
        break;
      case "PtgList":
      /* TODO: PtgList -> PtgExtraList */
      case "PtgElfRadicalS":
      /* TODO: PtgElfRadicalS -> PtgExtraElf */
      case "PtgElfColS":
      /* TODO: PtgElfColS -> PtgExtraElf */
      case "PtgElfColSV":
        throw "Unsupported " + rgce[i7][0];
      default:
        break;
    }
  }
  length = target - blob.l;
  if (length !== 0) o9.push(parsenoop(blob, length));
  return o9;
}
function parse_Rgce(blob, length, opts) {
  var target = blob.l + length;
  var R3, id, ptgs = [];
  while (target != blob.l) {
    length = target - blob.l;
    id = blob[blob.l];
    R3 = PtgTypes[id] || PtgTypes[PtgDupes[id]];
    if (id === 24 || id === 25) R3 = (id === 24 ? Ptg18 : Ptg19)[blob[blob.l + 1]];
    if (!R3 || !R3.f) {
      parsenoop(blob, length);
    } else {
      ptgs.push([R3.n, R3.f(blob, length, opts)]);
    }
  }
  return ptgs;
}
function stringify_array(f4) {
  var o9 = [];
  for (var i7 = 0; i7 < f4.length; ++i7) {
    var x2 = f4[i7], r8 = [];
    for (var j3 = 0; j3 < x2.length; ++j3) {
      var y4 = x2[j3];
      if (y4) switch (y4[0]) {
        // TODO: handle embedded quotes
        case 2:
          r8.push('"' + y4[1].replace(/"/g, '""') + '"');
          break;
        default:
          r8.push(y4[1]);
      }
      else r8.push("");
    }
    o9.push(r8.join(","));
  }
  return o9.join(";");
}
var PtgBinOp = {
  PtgAdd: "+",
  PtgConcat: "&",
  PtgDiv: "/",
  PtgEq: "=",
  PtgGe: ">=",
  PtgGt: ">",
  PtgLe: "<=",
  PtgLt: "<",
  PtgMul: "*",
  PtgNe: "<>",
  PtgPower: "^",
  PtgSub: "-"
};
function make_3d_range(start, end) {
  var s6 = start.lastIndexOf("!"), e9 = end.lastIndexOf("!");
  if (s6 == -1 && e9 == -1) return start + ":" + end;
  if (s6 > 0 && e9 > 0 && start.slice(0, s6).toLowerCase() == end.slice(0, e9).toLowerCase()) return start + ":" + end.slice(e9 + 1);
  console.error("Cannot hydrate range", start, end);
  return start + ":" + end;
}
function get_ixti_raw(supbooks, ixti, opts) {
  if (!supbooks) return "SH33TJSERR0";
  if (opts.biff > 8 && (!supbooks.XTI || !supbooks.XTI[ixti])) return supbooks.SheetNames[ixti];
  if (!supbooks.XTI) return "SH33TJSERR6";
  var XTI = supbooks.XTI[ixti];
  if (opts.biff < 8) {
    if (ixti > 1e4) ixti -= 65536;
    if (ixti < 0) ixti = -ixti;
    return ixti == 0 ? "" : supbooks.XTI[ixti - 1];
  }
  if (!XTI) return "SH33TJSERR1";
  var o9 = "";
  if (opts.biff > 8) switch (supbooks[XTI[0]][0]) {
    case 357:
      o9 = XTI[1] == -1 ? "#REF" : supbooks.SheetNames[XTI[1]];
      return XTI[1] == XTI[2] ? o9 : o9 + ":" + supbooks.SheetNames[XTI[2]];
    case 358:
      if (opts.SID != null) return supbooks.SheetNames[opts.SID];
      return "SH33TJSSAME" + supbooks[XTI[0]][0];
    case 355:
    /* 'BrtSupBookSrc' */
    /* falls through */
    default:
      return "SH33TJSSRC" + supbooks[XTI[0]][0];
  }
  switch (supbooks[XTI[0]][0][0]) {
    case 1025:
      o9 = XTI[1] == -1 ? "#REF" : supbooks.SheetNames[XTI[1]] || "SH33TJSERR3";
      return XTI[1] == XTI[2] ? o9 : o9 + ":" + supbooks.SheetNames[XTI[2]];
    case 14849:
      return supbooks[XTI[0]].slice(1).map(function(name) {
        return name.Name;
      }).join(";;");
    //return "SH33TJSERR8";
    default:
      if (!supbooks[XTI[0]][0][3]) return "SH33TJSERR2";
      o9 = XTI[1] == -1 ? "#REF" : supbooks[XTI[0]][0][3][XTI[1]] || "SH33TJSERR4";
      return XTI[1] == XTI[2] ? o9 : o9 + ":" + supbooks[XTI[0]][0][3][XTI[2]];
  }
}
function get_ixti(supbooks, ixti, opts) {
  var ixtiraw = get_ixti_raw(supbooks, ixti, opts);
  return ixtiraw == "#REF" ? ixtiraw : formula_quote_sheet_name(ixtiraw, opts);
}
function stringify_formula(formula, range2, cell, supbooks, opts) {
  var biff = opts && opts.biff || 8;
  var _range = (
    /*range != null ? range :*/
    { s: { c: 0, r: 0 }, e: { c: 0, r: 0 } }
  );
  var stack = [], e1, e22, c6, ixti = 0, nameidx = 0, r8, sname = "";
  if (!formula[0] || !formula[0][0]) return "";
  var last_sp = -1, sp = "";
  for (var ff = 0, fflen = formula[0].length; ff < fflen; ++ff) {
    var f4 = formula[0][ff];
    switch (f4[0]) {
      case "PtgUminus":
        stack.push("-" + stack.pop());
        break;
      case "PtgUplus":
        stack.push("+" + stack.pop());
        break;
      case "PtgPercent":
        stack.push(stack.pop() + "%");
        break;
      case "PtgAdd":
      /* [MS-XLS] 2.5.198.26 */
      case "PtgConcat":
      /* [MS-XLS] 2.5.198.43 */
      case "PtgDiv":
      /* [MS-XLS] 2.5.198.45 */
      case "PtgEq":
      /* [MS-XLS] 2.5.198.56 */
      case "PtgGe":
      /* [MS-XLS] 2.5.198.64 */
      case "PtgGt":
      /* [MS-XLS] 2.5.198.65 */
      case "PtgLe":
      /* [MS-XLS] 2.5.198.68 */
      case "PtgLt":
      /* [MS-XLS] 2.5.198.69 */
      case "PtgMul":
      /* [MS-XLS] 2.5.198.75 */
      case "PtgNe":
      /* [MS-XLS] 2.5.198.78 */
      case "PtgPower":
      /* [MS-XLS] 2.5.198.82 */
      case "PtgSub":
        e1 = stack.pop();
        e22 = stack.pop();
        if (last_sp >= 0) {
          switch (formula[0][last_sp][1][0]) {
            case 0:
              sp = fill(" ", formula[0][last_sp][1][1]);
              break;
            case 1:
              sp = fill("\r", formula[0][last_sp][1][1]);
              break;
            default:
              sp = "";
              if (opts.WTF) throw new Error("Unexpected PtgAttrSpaceType " + formula[0][last_sp][1][0]);
          }
          e22 = e22 + sp;
          last_sp = -1;
        }
        stack.push(e22 + PtgBinOp[f4[0]] + e1);
        break;
      case "PtgIsect":
        e1 = stack.pop();
        e22 = stack.pop();
        stack.push(e22 + " " + e1);
        break;
      case "PtgUnion":
        e1 = stack.pop();
        e22 = stack.pop();
        stack.push(e22 + "," + e1);
        break;
      case "PtgRange":
        e1 = stack.pop();
        e22 = stack.pop();
        stack.push(make_3d_range(e22, e1));
        break;
      case "PtgAttrChoose":
        break;
      case "PtgAttrGoto":
        break;
      case "PtgAttrIf":
        break;
      case "PtgAttrIfError":
        break;
      case "PtgRef":
        c6 = shift_cell_xls(f4[1][1], _range, opts);
        stack.push(encode_cell_xls(c6, biff));
        break;
      case "PtgRefN":
        c6 = cell ? shift_cell_xls(f4[1][1], cell, opts) : f4[1][1];
        stack.push(encode_cell_xls(c6, biff));
        break;
      case "PtgRef3d":
        ixti = /*::Number(*/
        f4[1][1];
        c6 = shift_cell_xls(f4[1][2], _range, opts);
        sname = get_ixti(supbooks, ixti, opts);
        var w3 = sname;
        stack.push(sname + "!" + encode_cell_xls(c6, biff));
        break;
      case "PtgFunc":
      /* [MS-XLS] 2.5.198.62 */
      case "PtgFuncVar":
        var argc = f4[1][0], func = f4[1][1];
        if (!argc) argc = 0;
        argc &= 127;
        var args = argc == 0 ? [] : stack.slice(-argc);
        stack.length -= argc;
        if (func === "User") func = args.shift();
        stack.push(func + "(" + args.join(",") + ")");
        break;
      case "PtgBool":
        stack.push(f4[1] ? "TRUE" : "FALSE");
        break;
      case "PtgInt":
        stack.push(
          /*::String(*/
          f4[1]
          /*::)*/
        );
        break;
      case "PtgNum":
        stack.push(String(f4[1]));
        break;
      case "PtgStr":
        stack.push('"' + f4[1].replace(/"/g, '""') + '"');
        break;
      case "PtgErr":
        stack.push(
          /*::String(*/
          f4[1]
          /*::)*/
        );
        break;
      case "PtgAreaN":
        r8 = shift_range_xls(f4[1][1], cell ? { s: cell } : _range, opts);
        stack.push(encode_range_xls(r8, opts));
        break;
      case "PtgArea":
        r8 = shift_range_xls(f4[1][1], _range, opts);
        stack.push(encode_range_xls(r8, opts));
        break;
      case "PtgArea3d":
        ixti = /*::Number(*/
        f4[1][1];
        r8 = f4[1][2];
        sname = get_ixti(supbooks, ixti, opts);
        stack.push(sname + "!" + encode_range_xls(r8, opts));
        break;
      case "PtgAttrSum":
        stack.push("SUM(" + stack.pop() + ")");
        break;
      case "PtgAttrBaxcel":
      /* [MS-XLS] 2.5.198.33 */
      case "PtgAttrSemi":
        break;
      case "PtgName":
        nameidx = f4[1][2];
        var lbl = (supbooks.names || [])[nameidx - 1] || (supbooks[0] || [])[nameidx];
        var name = lbl ? lbl.Name : "SH33TJSNAME" + String(nameidx);
        if (name && name.slice(0, 6) == "_xlfn." && !opts.xlfn) name = name.slice(6);
        stack.push(name);
        break;
      case "PtgNameX":
        var bookidx = f4[1][1];
        nameidx = f4[1][2];
        var externbook;
        if (opts.biff <= 5) {
          if (bookidx < 0) bookidx = -bookidx;
          if (supbooks[bookidx]) externbook = supbooks[bookidx][nameidx];
        } else {
          var o9 = "";
          if (((supbooks[bookidx] || [])[0] || [])[0] == 14849) {
          } else if (((supbooks[bookidx] || [])[0] || [])[0] == 1025) {
            if (supbooks[bookidx][nameidx] && supbooks[bookidx][nameidx].itab > 0) {
              o9 = supbooks.SheetNames[supbooks[bookidx][nameidx].itab - 1] + "!";
            }
          } else o9 = supbooks.SheetNames[nameidx - 1] + "!";
          if (supbooks[bookidx] && supbooks[bookidx][nameidx]) o9 += supbooks[bookidx][nameidx].Name;
          else if (supbooks[0] && supbooks[0][nameidx]) o9 += supbooks[0][nameidx].Name;
          else {
            var ixtidata = (get_ixti_raw(supbooks, bookidx, opts) || "").split(";;");
            if (ixtidata[nameidx - 1]) o9 = ixtidata[nameidx - 1];
            else o9 += "SH33TJSERRX";
          }
          stack.push(o9);
          break;
        }
        if (!externbook) externbook = { Name: "SH33TJSERRY" };
        stack.push(externbook.Name);
        break;
      case "PtgParen":
        var lp = "(", rp = ")";
        if (last_sp >= 0) {
          sp = "";
          switch (formula[0][last_sp][1][0]) {
            // $FlowIgnore
            case 2:
              lp = fill(" ", formula[0][last_sp][1][1]) + lp;
              break;
            // $FlowIgnore
            case 3:
              lp = fill("\r", formula[0][last_sp][1][1]) + lp;
              break;
            // $FlowIgnore
            case 4:
              rp = fill(" ", formula[0][last_sp][1][1]) + rp;
              break;
            // $FlowIgnore
            case 5:
              rp = fill("\r", formula[0][last_sp][1][1]) + rp;
              break;
            default:
              if (opts.WTF) throw new Error("Unexpected PtgAttrSpaceType " + formula[0][last_sp][1][0]);
          }
          last_sp = -1;
        }
        stack.push(lp + stack.pop() + rp);
        break;
      case "PtgRefErr":
        stack.push("#REF!");
        break;
      case "PtgRefErr3d":
        stack.push("#REF!");
        break;
      case "PtgExp":
        c6 = { c: f4[1][1], r: f4[1][0] };
        var q2 = { c: cell.c, r: cell.r };
        if (supbooks.sharedf[encode_cell(c6)]) {
          var parsedf = supbooks.sharedf[encode_cell(c6)];
          stack.push(stringify_formula(parsedf, _range, q2, supbooks, opts));
        } else {
          var fnd = false;
          for (e1 = 0; e1 != supbooks.arrayf.length; ++e1) {
            e22 = supbooks.arrayf[e1];
            if (c6.c < e22[0].s.c || c6.c > e22[0].e.c) continue;
            if (c6.r < e22[0].s.r || c6.r > e22[0].e.r) continue;
            stack.push(stringify_formula(e22[1], _range, q2, supbooks, opts));
            fnd = true;
            break;
          }
          if (!fnd) stack.push(
            /*::String(*/
            f4[1]
            /*::)*/
          );
        }
        break;
      case "PtgArray":
        stack.push("{" + stringify_array(
          /*::(*/
          f4[1]
          /*:: :any)*/
        ) + "}");
        break;
      case "PtgMemArea":
        break;
      case "PtgAttrSpace":
      /* [MS-XLS] 2.5.198.38 */
      case "PtgAttrSpaceSemi":
        last_sp = ff;
        break;
      case "PtgTbl":
        break;
      case "PtgMemErr":
        break;
      case "PtgMissArg":
        stack.push("");
        break;
      case "PtgAreaErr":
        stack.push("#REF!");
        break;
      case "PtgAreaErr3d":
        stack.push("#REF!");
        break;
      case "PtgList":
        stack.push("Table" + f4[1].idx + "[#" + f4[1].rt + "]");
        break;
      case "PtgMemAreaN":
      case "PtgMemNoMemN":
      case "PtgAttrNoop":
      case "PtgSheet":
      case "PtgEndSheet":
        break;
      case "PtgMemFunc":
        break;
      case "PtgMemNoMem":
        break;
      case "PtgElfCol":
      /* [MS-XLS] 2.5.198.46 */
      case "PtgElfColS":
      /* [MS-XLS] 2.5.198.47 */
      case "PtgElfColSV":
      /* [MS-XLS] 2.5.198.48 */
      case "PtgElfColV":
      /* [MS-XLS] 2.5.198.49 */
      case "PtgElfLel":
      /* [MS-XLS] 2.5.198.50 */
      case "PtgElfRadical":
      /* [MS-XLS] 2.5.198.51 */
      case "PtgElfRadicalLel":
      /* [MS-XLS] 2.5.198.52 */
      case "PtgElfRadicalS":
      /* [MS-XLS] 2.5.198.53 */
      case "PtgElfRw":
      /* [MS-XLS] 2.5.198.54 */
      case "PtgElfRwV":
        throw new Error("Unsupported ELFs");
      case "PtgSxName":
        throw new Error("Unrecognized Formula Token: " + String(f4));
      default:
        throw new Error("Unrecognized Formula Token: " + String(f4));
    }
    var PtgNonDisp = ["PtgAttrSpace", "PtgAttrSpaceSemi", "PtgAttrGoto"];
    if (opts.biff != 3) {
      if (last_sp >= 0 && PtgNonDisp.indexOf(formula[0][ff][0]) == -1) {
        f4 = formula[0][last_sp];
        var _left = true;
        switch (f4[1][0]) {
          /* note: some bad XLSB files omit the PtgParen */
          case 4:
            _left = false;
          /* falls through */
          case 0:
            sp = fill(" ", f4[1][1]);
            break;
          case 5:
            _left = false;
          /* falls through */
          case 1:
            sp = fill("\r", f4[1][1]);
            break;
          default:
            sp = "";
            if (opts.WTF) throw new Error("Unexpected PtgAttrSpaceType " + f4[1][0]);
        }
        stack.push((_left ? sp : "") + stack.pop() + (_left ? "" : sp));
        last_sp = -1;
      }
    }
  }
  if (stack.length > 1 && opts.WTF) throw new Error("bad formula stack");
  if (stack[0] == "TRUE") return true;
  if (stack[0] == "FALSE") return false;
  return stack[0];
}
function parse_ArrayParsedFormula(blob, length, opts) {
  var target = blob.l + length, len = opts.biff == 2 ? 1 : 2;
  var rgcb, cce = blob.read_shift(len);
  if (cce == 65535) return [[], parsenoop(blob, length - 2)];
  var rgce = parse_Rgce(blob, cce, opts);
  if (length !== cce + len) rgcb = parse_RgbExtra(blob, length - cce - len, rgce, opts);
  blob.l = target;
  return [rgce, rgcb];
}
function parse_XLSCellParsedFormula(blob, length, opts) {
  var target = blob.l + length, len = opts.biff == 2 ? 1 : 2;
  var rgcb, cce = blob.read_shift(len);
  if (cce == 65535) return [[], parsenoop(blob, length - 2)];
  var rgce = parse_Rgce(blob, cce, opts);
  if (length !== cce + len) rgcb = parse_RgbExtra(blob, length - cce - len, rgce, opts);
  blob.l = target;
  return [rgce, rgcb];
}
function parse_NameParsedFormula(blob, length, opts, cce) {
  var target = blob.l + length;
  var rgce = parse_Rgce(blob, cce, opts);
  var rgcb;
  if (target !== blob.l) rgcb = parse_RgbExtra(blob, target - blob.l, rgce, opts);
  return [rgce, rgcb];
}
function parse_SharedParsedFormula(blob, length, opts) {
  var target = blob.l + length;
  var rgcb, cce = blob.read_shift(2);
  var rgce = parse_Rgce(blob, cce, opts);
  if (cce == 65535) return [[], parsenoop(blob, length - 2)];
  if (length !== cce + 2) rgcb = parse_RgbExtra(blob, target - cce - 2, rgce, opts);
  return [rgce, rgcb];
}
function parse_FormulaValue(blob) {
  var b4;
  if (__readUInt16LE(blob, blob.l + 6) !== 65535) return [parse_Xnum(blob), "n"];
  switch (blob[blob.l]) {
    case 0:
      blob.l += 8;
      return ["String", "s"];
    case 1:
      b4 = blob[blob.l + 2] === 1;
      blob.l += 8;
      return [b4, "b"];
    case 2:
      b4 = blob[blob.l + 2];
      blob.l += 8;
      return [b4, "e"];
    case 3:
      blob.l += 8;
      return ["", "s"];
  }
  return [];
}
function parse_Formula(blob, length, opts) {
  var end = blob.l + length;
  var cell = parse_XLSCell(blob, 6, opts);
  var val2 = parse_FormulaValue(blob, 8);
  var flags = blob.read_shift(1);
  if (opts.biff != 2) {
    blob.read_shift(1);
    if (opts.biff >= 5) {
      blob.read_shift(4);
    }
  }
  var cbf = parse_XLSCellParsedFormula(blob, end - blob.l, opts);
  return { cell, val: val2[0], formula: cbf, shared: flags >> 3 & 1, tt: val2[1] };
}
function parse_XLSBParsedFormula(data, length, opts) {
  var cce = data.read_shift(4);
  var rgce = parse_Rgce(data, cce, opts);
  var cb = data.read_shift(4);
  var rgcb = cb > 0 ? parse_RgbExtra(data, cb, rgce, opts) : null;
  return [rgce, rgcb];
}
var parse_XLSBArrayParsedFormula = parse_XLSBParsedFormula;
var parse_XLSBCellParsedFormula = parse_XLSBParsedFormula;
var parse_XLSBNameParsedFormula = parse_XLSBParsedFormula;
var parse_XLSBSharedParsedFormula = parse_XLSBParsedFormula;
var Cetab = {
  0: "BEEP",
  1: "OPEN",
  2: "OPEN.LINKS",
  3: "CLOSE.ALL",
  4: "SAVE",
  5: "SAVE.AS",
  6: "FILE.DELETE",
  7: "PAGE.SETUP",
  8: "PRINT",
  9: "PRINTER.SETUP",
  10: "QUIT",
  11: "NEW.WINDOW",
  12: "ARRANGE.ALL",
  13: "WINDOW.SIZE",
  14: "WINDOW.MOVE",
  15: "FULL",
  16: "CLOSE",
  17: "RUN",
  22: "SET.PRINT.AREA",
  23: "SET.PRINT.TITLES",
  24: "SET.PAGE.BREAK",
  25: "REMOVE.PAGE.BREAK",
  26: "FONT",
  27: "DISPLAY",
  28: "PROTECT.DOCUMENT",
  29: "PRECISION",
  30: "A1.R1C1",
  31: "CALCULATE.NOW",
  32: "CALCULATION",
  34: "DATA.FIND",
  35: "EXTRACT",
  36: "DATA.DELETE",
  37: "SET.DATABASE",
  38: "SET.CRITERIA",
  39: "SORT",
  40: "DATA.SERIES",
  41: "TABLE",
  42: "FORMAT.NUMBER",
  43: "ALIGNMENT",
  44: "STYLE",
  45: "BORDER",
  46: "CELL.PROTECTION",
  47: "COLUMN.WIDTH",
  48: "UNDO",
  49: "CUT",
  50: "COPY",
  51: "PASTE",
  52: "CLEAR",
  53: "PASTE.SPECIAL",
  54: "EDIT.DELETE",
  55: "INSERT",
  56: "FILL.RIGHT",
  57: "FILL.DOWN",
  61: "DEFINE.NAME",
  62: "CREATE.NAMES",
  63: "FORMULA.GOTO",
  64: "FORMULA.FIND",
  65: "SELECT.LAST.CELL",
  66: "SHOW.ACTIVE.CELL",
  67: "GALLERY.AREA",
  68: "GALLERY.BAR",
  69: "GALLERY.COLUMN",
  70: "GALLERY.LINE",
  71: "GALLERY.PIE",
  72: "GALLERY.SCATTER",
  73: "COMBINATION",
  74: "PREFERRED",
  75: "ADD.OVERLAY",
  76: "GRIDLINES",
  77: "SET.PREFERRED",
  78: "AXES",
  79: "LEGEND",
  80: "ATTACH.TEXT",
  81: "ADD.ARROW",
  82: "SELECT.CHART",
  83: "SELECT.PLOT.AREA",
  84: "PATTERNS",
  85: "MAIN.CHART",
  86: "OVERLAY",
  87: "SCALE",
  88: "FORMAT.LEGEND",
  89: "FORMAT.TEXT",
  90: "EDIT.REPEAT",
  91: "PARSE",
  92: "JUSTIFY",
  93: "HIDE",
  94: "UNHIDE",
  95: "WORKSPACE",
  96: "FORMULA",
  97: "FORMULA.FILL",
  98: "FORMULA.ARRAY",
  99: "DATA.FIND.NEXT",
  100: "DATA.FIND.PREV",
  101: "FORMULA.FIND.NEXT",
  102: "FORMULA.FIND.PREV",
  103: "ACTIVATE",
  104: "ACTIVATE.NEXT",
  105: "ACTIVATE.PREV",
  106: "UNLOCKED.NEXT",
  107: "UNLOCKED.PREV",
  108: "COPY.PICTURE",
  109: "SELECT",
  110: "DELETE.NAME",
  111: "DELETE.FORMAT",
  112: "VLINE",
  113: "HLINE",
  114: "VPAGE",
  115: "HPAGE",
  116: "VSCROLL",
  117: "HSCROLL",
  118: "ALERT",
  119: "NEW",
  120: "CANCEL.COPY",
  121: "SHOW.CLIPBOARD",
  122: "MESSAGE",
  124: "PASTE.LINK",
  125: "APP.ACTIVATE",
  126: "DELETE.ARROW",
  127: "ROW.HEIGHT",
  128: "FORMAT.MOVE",
  129: "FORMAT.SIZE",
  130: "FORMULA.REPLACE",
  131: "SEND.KEYS",
  132: "SELECT.SPECIAL",
  133: "APPLY.NAMES",
  134: "REPLACE.FONT",
  135: "FREEZE.PANES",
  136: "SHOW.INFO",
  137: "SPLIT",
  138: "ON.WINDOW",
  139: "ON.DATA",
  140: "DISABLE.INPUT",
  142: "OUTLINE",
  143: "LIST.NAMES",
  144: "FILE.CLOSE",
  145: "SAVE.WORKBOOK",
  146: "DATA.FORM",
  147: "COPY.CHART",
  148: "ON.TIME",
  149: "WAIT",
  150: "FORMAT.FONT",
  151: "FILL.UP",
  152: "FILL.LEFT",
  153: "DELETE.OVERLAY",
  155: "SHORT.MENUS",
  159: "SET.UPDATE.STATUS",
  161: "COLOR.PALETTE",
  162: "DELETE.STYLE",
  163: "WINDOW.RESTORE",
  164: "WINDOW.MAXIMIZE",
  166: "CHANGE.LINK",
  167: "CALCULATE.DOCUMENT",
  168: "ON.KEY",
  169: "APP.RESTORE",
  170: "APP.MOVE",
  171: "APP.SIZE",
  172: "APP.MINIMIZE",
  173: "APP.MAXIMIZE",
  174: "BRING.TO.FRONT",
  175: "SEND.TO.BACK",
  185: "MAIN.CHART.TYPE",
  186: "OVERLAY.CHART.TYPE",
  187: "SELECT.END",
  188: "OPEN.MAIL",
  189: "SEND.MAIL",
  190: "STANDARD.FONT",
  191: "CONSOLIDATE",
  192: "SORT.SPECIAL",
  193: "GALLERY.3D.AREA",
  194: "GALLERY.3D.COLUMN",
  195: "GALLERY.3D.LINE",
  196: "GALLERY.3D.PIE",
  197: "VIEW.3D",
  198: "GOAL.SEEK",
  199: "WORKGROUP",
  200: "FILL.GROUP",
  201: "UPDATE.LINK",
  202: "PROMOTE",
  203: "DEMOTE",
  204: "SHOW.DETAIL",
  206: "UNGROUP",
  207: "OBJECT.PROPERTIES",
  208: "SAVE.NEW.OBJECT",
  209: "SHARE",
  210: "SHARE.NAME",
  211: "DUPLICATE",
  212: "APPLY.STYLE",
  213: "ASSIGN.TO.OBJECT",
  214: "OBJECT.PROTECTION",
  215: "HIDE.OBJECT",
  216: "SET.EXTRACT",
  217: "CREATE.PUBLISHER",
  218: "SUBSCRIBE.TO",
  219: "ATTRIBUTES",
  220: "SHOW.TOOLBAR",
  222: "PRINT.PREVIEW",
  223: "EDIT.COLOR",
  224: "SHOW.LEVELS",
  225: "FORMAT.MAIN",
  226: "FORMAT.OVERLAY",
  227: "ON.RECALC",
  228: "EDIT.SERIES",
  229: "DEFINE.STYLE",
  240: "LINE.PRINT",
  243: "ENTER.DATA",
  249: "GALLERY.RADAR",
  250: "MERGE.STYLES",
  251: "EDITION.OPTIONS",
  252: "PASTE.PICTURE",
  253: "PASTE.PICTURE.LINK",
  254: "SPELLING",
  256: "ZOOM",
  259: "INSERT.OBJECT",
  260: "WINDOW.MINIMIZE",
  265: "SOUND.NOTE",
  266: "SOUND.PLAY",
  267: "FORMAT.SHAPE",
  268: "EXTEND.POLYGON",
  269: "FORMAT.AUTO",
  272: "GALLERY.3D.BAR",
  273: "GALLERY.3D.SURFACE",
  274: "FILL.AUTO",
  276: "CUSTOMIZE.TOOLBAR",
  277: "ADD.TOOL",
  278: "EDIT.OBJECT",
  279: "ON.DOUBLECLICK",
  280: "ON.ENTRY",
  281: "WORKBOOK.ADD",
  282: "WORKBOOK.MOVE",
  283: "WORKBOOK.COPY",
  284: "WORKBOOK.OPTIONS",
  285: "SAVE.WORKSPACE",
  288: "CHART.WIZARD",
  289: "DELETE.TOOL",
  290: "MOVE.TOOL",
  291: "WORKBOOK.SELECT",
  292: "WORKBOOK.ACTIVATE",
  293: "ASSIGN.TO.TOOL",
  295: "COPY.TOOL",
  296: "RESET.TOOL",
  297: "CONSTRAIN.NUMERIC",
  298: "PASTE.TOOL",
  302: "WORKBOOK.NEW",
  305: "SCENARIO.CELLS",
  306: "SCENARIO.DELETE",
  307: "SCENARIO.ADD",
  308: "SCENARIO.EDIT",
  309: "SCENARIO.SHOW",
  310: "SCENARIO.SHOW.NEXT",
  311: "SCENARIO.SUMMARY",
  312: "PIVOT.TABLE.WIZARD",
  313: "PIVOT.FIELD.PROPERTIES",
  314: "PIVOT.FIELD",
  315: "PIVOT.ITEM",
  316: "PIVOT.ADD.FIELDS",
  318: "OPTIONS.CALCULATION",
  319: "OPTIONS.EDIT",
  320: "OPTIONS.VIEW",
  321: "ADDIN.MANAGER",
  322: "MENU.EDITOR",
  323: "ATTACH.TOOLBARS",
  324: "VBAActivate",
  325: "OPTIONS.CHART",
  328: "VBA.INSERT.FILE",
  330: "VBA.PROCEDURE.DEFINITION",
  336: "ROUTING.SLIP",
  338: "ROUTE.DOCUMENT",
  339: "MAIL.LOGON",
  342: "INSERT.PICTURE",
  343: "EDIT.TOOL",
  344: "GALLERY.DOUGHNUT",
  350: "CHART.TREND",
  352: "PIVOT.ITEM.PROPERTIES",
  354: "WORKBOOK.INSERT",
  355: "OPTIONS.TRANSITION",
  356: "OPTIONS.GENERAL",
  370: "FILTER.ADVANCED",
  373: "MAIL.ADD.MAILER",
  374: "MAIL.DELETE.MAILER",
  375: "MAIL.REPLY",
  376: "MAIL.REPLY.ALL",
  377: "MAIL.FORWARD",
  378: "MAIL.NEXT.LETTER",
  379: "DATA.LABEL",
  380: "INSERT.TITLE",
  381: "FONT.PROPERTIES",
  382: "MACRO.OPTIONS",
  383: "WORKBOOK.HIDE",
  384: "WORKBOOK.UNHIDE",
  385: "WORKBOOK.DELETE",
  386: "WORKBOOK.NAME",
  388: "GALLERY.CUSTOM",
  390: "ADD.CHART.AUTOFORMAT",
  391: "DELETE.CHART.AUTOFORMAT",
  392: "CHART.ADD.DATA",
  393: "AUTO.OUTLINE",
  394: "TAB.ORDER",
  395: "SHOW.DIALOG",
  396: "SELECT.ALL",
  397: "UNGROUP.SHEETS",
  398: "SUBTOTAL.CREATE",
  399: "SUBTOTAL.REMOVE",
  400: "RENAME.OBJECT",
  412: "WORKBOOK.SCROLL",
  413: "WORKBOOK.NEXT",
  414: "WORKBOOK.PREV",
  415: "WORKBOOK.TAB.SPLIT",
  416: "FULL.SCREEN",
  417: "WORKBOOK.PROTECT",
  420: "SCROLLBAR.PROPERTIES",
  421: "PIVOT.SHOW.PAGES",
  422: "TEXT.TO.COLUMNS",
  423: "FORMAT.CHARTTYPE",
  424: "LINK.FORMAT",
  425: "TRACER.DISPLAY",
  430: "TRACER.NAVIGATE",
  431: "TRACER.CLEAR",
  432: "TRACER.ERROR",
  433: "PIVOT.FIELD.GROUP",
  434: "PIVOT.FIELD.UNGROUP",
  435: "CHECKBOX.PROPERTIES",
  436: "LABEL.PROPERTIES",
  437: "LISTBOX.PROPERTIES",
  438: "EDITBOX.PROPERTIES",
  439: "PIVOT.REFRESH",
  440: "LINK.COMBO",
  441: "OPEN.TEXT",
  442: "HIDE.DIALOG",
  443: "SET.DIALOG.FOCUS",
  444: "ENABLE.OBJECT",
  445: "PUSHBUTTON.PROPERTIES",
  446: "SET.DIALOG.DEFAULT",
  447: "FILTER",
  448: "FILTER.SHOW.ALL",
  449: "CLEAR.OUTLINE",
  450: "FUNCTION.WIZARD",
  451: "ADD.LIST.ITEM",
  452: "SET.LIST.ITEM",
  453: "REMOVE.LIST.ITEM",
  454: "SELECT.LIST.ITEM",
  455: "SET.CONTROL.VALUE",
  456: "SAVE.COPY.AS",
  458: "OPTIONS.LISTS.ADD",
  459: "OPTIONS.LISTS.DELETE",
  460: "SERIES.AXES",
  461: "SERIES.X",
  462: "SERIES.Y",
  463: "ERRORBAR.X",
  464: "ERRORBAR.Y",
  465: "FORMAT.CHART",
  466: "SERIES.ORDER",
  467: "MAIL.LOGOFF",
  468: "CLEAR.ROUTING.SLIP",
  469: "APP.ACTIVATE.MICROSOFT",
  470: "MAIL.EDIT.MAILER",
  471: "ON.SHEET",
  472: "STANDARD.WIDTH",
  473: "SCENARIO.MERGE",
  474: "SUMMARY.INFO",
  475: "FIND.FILE",
  476: "ACTIVE.CELL.FONT",
  477: "ENABLE.TIPWIZARD",
  478: "VBA.MAKE.ADDIN",
  480: "INSERTDATATABLE",
  481: "WORKGROUP.OPTIONS",
  482: "MAIL.SEND.MAILER",
  485: "AUTOCORRECT",
  489: "POST.DOCUMENT",
  491: "PICKLIST",
  493: "VIEW.SHOW",
  494: "VIEW.DEFINE",
  495: "VIEW.DELETE",
  509: "SHEET.BACKGROUND",
  510: "INSERT.MAP.OBJECT",
  511: "OPTIONS.MENONO",
  517: "MSOCHECKS",
  518: "NORMAL",
  519: "LAYOUT",
  520: "RM.PRINT.AREA",
  521: "CLEAR.PRINT.AREA",
  522: "ADD.PRINT.AREA",
  523: "MOVE.BRK",
  545: "HIDECURR.NOTE",
  546: "HIDEALL.NOTES",
  547: "DELETE.NOTE",
  548: "TRAVERSE.NOTES",
  549: "ACTIVATE.NOTES",
  620: "PROTECT.REVISIONS",
  621: "UNPROTECT.REVISIONS",
  647: "OPTIONS.ME",
  653: "WEB.PUBLISH",
  667: "NEWWEBQUERY",
  673: "PIVOT.TABLE.CHART",
  753: "OPTIONS.SAVE",
  755: "OPTIONS.SPELL",
  808: "HIDEALL.INKANNOTS"
};
var Ftab = {
  0: "COUNT",
  1: "IF",
  2: "ISNA",
  3: "ISERROR",
  4: "SUM",
  5: "AVERAGE",
  6: "MIN",
  7: "MAX",
  8: "ROW",
  9: "COLUMN",
  10: "NA",
  11: "NPV",
  12: "STDEV",
  13: "DOLLAR",
  14: "FIXED",
  15: "SIN",
  16: "COS",
  17: "TAN",
  18: "ATAN",
  19: "PI",
  20: "SQRT",
  21: "EXP",
  22: "LN",
  23: "LOG10",
  24: "ABS",
  25: "INT",
  26: "SIGN",
  27: "ROUND",
  28: "LOOKUP",
  29: "INDEX",
  30: "REPT",
  31: "MID",
  32: "LEN",
  33: "VALUE",
  34: "TRUE",
  35: "FALSE",
  36: "AND",
  37: "OR",
  38: "NOT",
  39: "MOD",
  40: "DCOUNT",
  41: "DSUM",
  42: "DAVERAGE",
  43: "DMIN",
  44: "DMAX",
  45: "DSTDEV",
  46: "VAR",
  47: "DVAR",
  48: "TEXT",
  49: "LINEST",
  50: "TREND",
  51: "LOGEST",
  52: "GROWTH",
  53: "GOTO",
  54: "HALT",
  55: "RETURN",
  56: "PV",
  57: "FV",
  58: "NPER",
  59: "PMT",
  60: "RATE",
  61: "MIRR",
  62: "IRR",
  63: "RAND",
  64: "MATCH",
  65: "DATE",
  66: "TIME",
  67: "DAY",
  68: "MONTH",
  69: "YEAR",
  70: "WEEKDAY",
  71: "HOUR",
  72: "MINUTE",
  73: "SECOND",
  74: "NOW",
  75: "AREAS",
  76: "ROWS",
  77: "COLUMNS",
  78: "OFFSET",
  79: "ABSREF",
  80: "RELREF",
  81: "ARGUMENT",
  82: "SEARCH",
  83: "TRANSPOSE",
  84: "ERROR",
  85: "STEP",
  86: "TYPE",
  87: "ECHO",
  88: "SET.NAME",
  89: "CALLER",
  90: "DEREF",
  91: "WINDOWS",
  92: "SERIES",
  93: "DOCUMENTS",
  94: "ACTIVE.CELL",
  95: "SELECTION",
  96: "RESULT",
  97: "ATAN2",
  98: "ASIN",
  99: "ACOS",
  100: "CHOOSE",
  101: "HLOOKUP",
  102: "VLOOKUP",
  103: "LINKS",
  104: "INPUT",
  105: "ISREF",
  106: "GET.FORMULA",
  107: "GET.NAME",
  108: "SET.VALUE",
  109: "LOG",
  110: "EXEC",
  111: "CHAR",
  112: "LOWER",
  113: "UPPER",
  114: "PROPER",
  115: "LEFT",
  116: "RIGHT",
  117: "EXACT",
  118: "TRIM",
  119: "REPLACE",
  120: "SUBSTITUTE",
  121: "CODE",
  122: "NAMES",
  123: "DIRECTORY",
  124: "FIND",
  125: "CELL",
  126: "ISERR",
  127: "ISTEXT",
  128: "ISNUMBER",
  129: "ISBLANK",
  130: "T",
  131: "N",
  132: "FOPEN",
  133: "FCLOSE",
  134: "FSIZE",
  135: "FREADLN",
  136: "FREAD",
  137: "FWRITELN",
  138: "FWRITE",
  139: "FPOS",
  140: "DATEVALUE",
  141: "TIMEVALUE",
  142: "SLN",
  143: "SYD",
  144: "DDB",
  145: "GET.DEF",
  146: "REFTEXT",
  147: "TEXTREF",
  148: "INDIRECT",
  149: "REGISTER",
  150: "CALL",
  151: "ADD.BAR",
  152: "ADD.MENU",
  153: "ADD.COMMAND",
  154: "ENABLE.COMMAND",
  155: "CHECK.COMMAND",
  156: "RENAME.COMMAND",
  157: "SHOW.BAR",
  158: "DELETE.MENU",
  159: "DELETE.COMMAND",
  160: "GET.CHART.ITEM",
  161: "DIALOG.BOX",
  162: "CLEAN",
  163: "MDETERM",
  164: "MINVERSE",
  165: "MMULT",
  166: "FILES",
  167: "IPMT",
  168: "PPMT",
  169: "COUNTA",
  170: "CANCEL.KEY",
  171: "FOR",
  172: "WHILE",
  173: "BREAK",
  174: "NEXT",
  175: "INITIATE",
  176: "REQUEST",
  177: "POKE",
  178: "EXECUTE",
  179: "TERMINATE",
  180: "RESTART",
  181: "HELP",
  182: "GET.BAR",
  183: "PRODUCT",
  184: "FACT",
  185: "GET.CELL",
  186: "GET.WORKSPACE",
  187: "GET.WINDOW",
  188: "GET.DOCUMENT",
  189: "DPRODUCT",
  190: "ISNONTEXT",
  191: "GET.NOTE",
  192: "NOTE",
  193: "STDEVP",
  194: "VARP",
  195: "DSTDEVP",
  196: "DVARP",
  197: "TRUNC",
  198: "ISLOGICAL",
  199: "DCOUNTA",
  200: "DELETE.BAR",
  201: "UNREGISTER",
  204: "USDOLLAR",
  205: "FINDB",
  206: "SEARCHB",
  207: "REPLACEB",
  208: "LEFTB",
  209: "RIGHTB",
  210: "MIDB",
  211: "LENB",
  212: "ROUNDUP",
  213: "ROUNDDOWN",
  214: "ASC",
  215: "DBCS",
  216: "RANK",
  219: "ADDRESS",
  220: "DAYS360",
  221: "TODAY",
  222: "VDB",
  223: "ELSE",
  224: "ELSE.IF",
  225: "END.IF",
  226: "FOR.CELL",
  227: "MEDIAN",
  228: "SUMPRODUCT",
  229: "SINH",
  230: "COSH",
  231: "TANH",
  232: "ASINH",
  233: "ACOSH",
  234: "ATANH",
  235: "DGET",
  236: "CREATE.OBJECT",
  237: "VOLATILE",
  238: "LAST.ERROR",
  239: "CUSTOM.UNDO",
  240: "CUSTOM.REPEAT",
  241: "FORMULA.CONVERT",
  242: "GET.LINK.INFO",
  243: "TEXT.BOX",
  244: "INFO",
  245: "GROUP",
  246: "GET.OBJECT",
  247: "DB",
  248: "PAUSE",
  251: "RESUME",
  252: "FREQUENCY",
  253: "ADD.TOOLBAR",
  254: "DELETE.TOOLBAR",
  255: "User",
  256: "RESET.TOOLBAR",
  257: "EVALUATE",
  258: "GET.TOOLBAR",
  259: "GET.TOOL",
  260: "SPELLING.CHECK",
  261: "ERROR.TYPE",
  262: "APP.TITLE",
  263: "WINDOW.TITLE",
  264: "SAVE.TOOLBAR",
  265: "ENABLE.TOOL",
  266: "PRESS.TOOL",
  267: "REGISTER.ID",
  268: "GET.WORKBOOK",
  269: "AVEDEV",
  270: "BETADIST",
  271: "GAMMALN",
  272: "BETAINV",
  273: "BINOMDIST",
  274: "CHIDIST",
  275: "CHIINV",
  276: "COMBIN",
  277: "CONFIDENCE",
  278: "CRITBINOM",
  279: "EVEN",
  280: "EXPONDIST",
  281: "FDIST",
  282: "FINV",
  283: "FISHER",
  284: "FISHERINV",
  285: "FLOOR",
  286: "GAMMADIST",
  287: "GAMMAINV",
  288: "CEILING",
  289: "HYPGEOMDIST",
  290: "LOGNORMDIST",
  291: "LOGINV",
  292: "NEGBINOMDIST",
  293: "NORMDIST",
  294: "NORMSDIST",
  295: "NORMINV",
  296: "NORMSINV",
  297: "STANDARDIZE",
  298: "ODD",
  299: "PERMUT",
  300: "POISSON",
  301: "TDIST",
  302: "WEIBULL",
  303: "SUMXMY2",
  304: "SUMX2MY2",
  305: "SUMX2PY2",
  306: "CHITEST",
  307: "CORREL",
  308: "COVAR",
  309: "FORECAST",
  310: "FTEST",
  311: "INTERCEPT",
  312: "PEARSON",
  313: "RSQ",
  314: "STEYX",
  315: "SLOPE",
  316: "TTEST",
  317: "PROB",
  318: "DEVSQ",
  319: "GEOMEAN",
  320: "HARMEAN",
  321: "SUMSQ",
  322: "KURT",
  323: "SKEW",
  324: "ZTEST",
  325: "LARGE",
  326: "SMALL",
  327: "QUARTILE",
  328: "PERCENTILE",
  329: "PERCENTRANK",
  330: "MODE",
  331: "TRIMMEAN",
  332: "TINV",
  334: "MOVIE.COMMAND",
  335: "GET.MOVIE",
  336: "CONCATENATE",
  337: "POWER",
  338: "PIVOT.ADD.DATA",
  339: "GET.PIVOT.TABLE",
  340: "GET.PIVOT.FIELD",
  341: "GET.PIVOT.ITEM",
  342: "RADIANS",
  343: "DEGREES",
  344: "SUBTOTAL",
  345: "SUMIF",
  346: "COUNTIF",
  347: "COUNTBLANK",
  348: "SCENARIO.GET",
  349: "OPTIONS.LISTS.GET",
  350: "ISPMT",
  351: "DATEDIF",
  352: "DATESTRING",
  353: "NUMBERSTRING",
  354: "ROMAN",
  355: "OPEN.DIALOG",
  356: "SAVE.DIALOG",
  357: "VIEW.GET",
  358: "GETPIVOTDATA",
  359: "HYPERLINK",
  360: "PHONETIC",
  361: "AVERAGEA",
  362: "MAXA",
  363: "MINA",
  364: "STDEVPA",
  365: "VARPA",
  366: "STDEVA",
  367: "VARA",
  368: "BAHTTEXT",
  369: "THAIDAYOFWEEK",
  370: "THAIDIGIT",
  371: "THAIMONTHOFYEAR",
  372: "THAINUMSOUND",
  373: "THAINUMSTRING",
  374: "THAISTRINGLENGTH",
  375: "ISTHAIDIGIT",
  376: "ROUNDBAHTDOWN",
  377: "ROUNDBAHTUP",
  378: "THAIYEAR",
  379: "RTD",
  380: "CUBEVALUE",
  381: "CUBEMEMBER",
  382: "CUBEMEMBERPROPERTY",
  383: "CUBERANKEDMEMBER",
  384: "HEX2BIN",
  385: "HEX2DEC",
  386: "HEX2OCT",
  387: "DEC2BIN",
  388: "DEC2HEX",
  389: "DEC2OCT",
  390: "OCT2BIN",
  391: "OCT2HEX",
  392: "OCT2DEC",
  393: "BIN2DEC",
  394: "BIN2OCT",
  395: "BIN2HEX",
  396: "IMSUB",
  397: "IMDIV",
  398: "IMPOWER",
  399: "IMABS",
  400: "IMSQRT",
  401: "IMLN",
  402: "IMLOG2",
  403: "IMLOG10",
  404: "IMSIN",
  405: "IMCOS",
  406: "IMEXP",
  407: "IMARGUMENT",
  408: "IMCONJUGATE",
  409: "IMAGINARY",
  410: "IMREAL",
  411: "COMPLEX",
  412: "IMSUM",
  413: "IMPRODUCT",
  414: "SERIESSUM",
  415: "FACTDOUBLE",
  416: "SQRTPI",
  417: "QUOTIENT",
  418: "DELTA",
  419: "GESTEP",
  420: "ISEVEN",
  421: "ISODD",
  422: "MROUND",
  423: "ERF",
  424: "ERFC",
  425: "BESSELJ",
  426: "BESSELK",
  427: "BESSELY",
  428: "BESSELI",
  429: "XIRR",
  430: "XNPV",
  431: "PRICEMAT",
  432: "YIELDMAT",
  433: "INTRATE",
  434: "RECEIVED",
  435: "DISC",
  436: "PRICEDISC",
  437: "YIELDDISC",
  438: "TBILLEQ",
  439: "TBILLPRICE",
  440: "TBILLYIELD",
  441: "PRICE",
  442: "YIELD",
  443: "DOLLARDE",
  444: "DOLLARFR",
  445: "NOMINAL",
  446: "EFFECT",
  447: "CUMPRINC",
  448: "CUMIPMT",
  449: "EDATE",
  450: "EOMONTH",
  451: "YEARFRAC",
  452: "COUPDAYBS",
  453: "COUPDAYS",
  454: "COUPDAYSNC",
  455: "COUPNCD",
  456: "COUPNUM",
  457: "COUPPCD",
  458: "DURATION",
  459: "MDURATION",
  460: "ODDLPRICE",
  461: "ODDLYIELD",
  462: "ODDFPRICE",
  463: "ODDFYIELD",
  464: "RANDBETWEEN",
  465: "WEEKNUM",
  466: "AMORDEGRC",
  467: "AMORLINC",
  468: "CONVERT",
  724: "SHEETJS",
  469: "ACCRINT",
  470: "ACCRINTM",
  471: "WORKDAY",
  472: "NETWORKDAYS",
  473: "GCD",
  474: "MULTINOMIAL",
  475: "LCM",
  476: "FVSCHEDULE",
  477: "CUBEKPIMEMBER",
  478: "CUBESET",
  479: "CUBESETCOUNT",
  480: "IFERROR",
  481: "COUNTIFS",
  482: "SUMIFS",
  483: "AVERAGEIF",
  484: "AVERAGEIFS"
};
var FtabArgc = {
  2: 1,
  3: 1,
  10: 0,
  15: 1,
  16: 1,
  17: 1,
  18: 1,
  19: 0,
  20: 1,
  21: 1,
  22: 1,
  23: 1,
  24: 1,
  25: 1,
  26: 1,
  27: 2,
  30: 2,
  31: 3,
  32: 1,
  33: 1,
  34: 0,
  35: 0,
  38: 1,
  39: 2,
  40: 3,
  41: 3,
  42: 3,
  43: 3,
  44: 3,
  45: 3,
  47: 3,
  48: 2,
  53: 1,
  61: 3,
  63: 0,
  65: 3,
  66: 3,
  67: 1,
  68: 1,
  69: 1,
  70: 1,
  71: 1,
  72: 1,
  73: 1,
  74: 0,
  75: 1,
  76: 1,
  77: 1,
  79: 2,
  80: 2,
  83: 1,
  85: 0,
  86: 1,
  89: 0,
  90: 1,
  94: 0,
  95: 0,
  97: 2,
  98: 1,
  99: 1,
  101: 3,
  102: 3,
  105: 1,
  106: 1,
  108: 2,
  111: 1,
  112: 1,
  113: 1,
  114: 1,
  117: 2,
  118: 1,
  119: 4,
  121: 1,
  126: 1,
  127: 1,
  128: 1,
  129: 1,
  130: 1,
  131: 1,
  133: 1,
  134: 1,
  135: 1,
  136: 2,
  137: 2,
  138: 2,
  140: 1,
  141: 1,
  142: 3,
  143: 4,
  144: 4,
  161: 1,
  162: 1,
  163: 1,
  164: 1,
  165: 2,
  172: 1,
  175: 2,
  176: 2,
  177: 3,
  178: 2,
  179: 1,
  184: 1,
  186: 1,
  189: 3,
  190: 1,
  195: 3,
  196: 3,
  197: 1,
  198: 1,
  199: 3,
  201: 1,
  207: 4,
  210: 3,
  211: 1,
  212: 2,
  213: 2,
  214: 1,
  215: 1,
  225: 0,
  229: 1,
  230: 1,
  231: 1,
  232: 1,
  233: 1,
  234: 1,
  235: 3,
  244: 1,
  247: 4,
  252: 2,
  257: 1,
  261: 1,
  271: 1,
  273: 4,
  274: 2,
  275: 2,
  276: 2,
  277: 3,
  278: 3,
  279: 1,
  280: 3,
  281: 3,
  282: 3,
  283: 1,
  284: 1,
  285: 2,
  286: 4,
  287: 3,
  288: 2,
  289: 4,
  290: 3,
  291: 3,
  292: 3,
  293: 4,
  294: 1,
  295: 3,
  296: 1,
  297: 3,
  298: 1,
  299: 2,
  300: 3,
  301: 3,
  302: 4,
  303: 2,
  304: 2,
  305: 2,
  306: 2,
  307: 2,
  308: 2,
  309: 3,
  310: 2,
  311: 2,
  312: 2,
  313: 2,
  314: 2,
  315: 2,
  316: 4,
  325: 2,
  326: 2,
  327: 2,
  328: 2,
  331: 2,
  332: 2,
  337: 2,
  342: 1,
  343: 1,
  346: 2,
  347: 1,
  350: 4,
  351: 3,
  352: 1,
  353: 2,
  360: 1,
  368: 1,
  369: 1,
  370: 1,
  371: 1,
  372: 1,
  373: 1,
  374: 1,
  375: 1,
  376: 1,
  377: 1,
  378: 1,
  382: 3,
  385: 1,
  392: 1,
  393: 1,
  396: 2,
  397: 2,
  398: 2,
  399: 1,
  400: 1,
  401: 1,
  402: 1,
  403: 1,
  404: 1,
  405: 1,
  406: 1,
  407: 1,
  408: 1,
  409: 1,
  410: 1,
  414: 4,
  415: 1,
  416: 1,
  417: 2,
  420: 1,
  421: 1,
  422: 2,
  424: 1,
  425: 2,
  426: 2,
  427: 2,
  428: 2,
  430: 3,
  438: 3,
  439: 3,
  440: 3,
  443: 2,
  444: 2,
  445: 2,
  446: 2,
  447: 6,
  448: 6,
  449: 2,
  450: 2,
  464: 2,
  468: 3,
  476: 2,
  479: 1,
  480: 2,
  65535: 0
};
function ods_to_csf_formula(f4) {
  if (f4.slice(0, 3) == "of:") f4 = f4.slice(3);
  if (f4.charCodeAt(0) == 61) {
    f4 = f4.slice(1);
    if (f4.charCodeAt(0) == 61) f4 = f4.slice(1);
  }
  f4 = f4.replace(/COM\.MICROSOFT\./g, "");
  f4 = f4.replace(/\[((?:\.[A-Z]+[0-9]+)(?::\.[A-Z]+[0-9]+)?)\]/g, function($$, $1) {
    return $1.replace(/\./g, "");
  });
  f4 = f4.replace(/\$'([^']|'')+'/g, function($$) {
    return $$.slice(1);
  });
  f4 = f4.replace(/\$([^\]\. #$]+)/g, function($$, $1) {
    return $1.match(/^([A-Z]{1,2}|[A-W][A-Z]{2}|X[A-E][A-Z]|XF[A-D])?(10[0-3]\d{4}|104[0-7]\d{3}|1048[0-4]\d{2}|10485[0-6]\d|104857[0-6]|[1-9]\d{0,5})?$/) ? $$ : $1;
  });
  f4 = f4.replace(/\[.(#[A-Z]*[?!])\]/g, "$1");
  return f4.replace(/[;~]/g, ",").replace(/\|/g, ";");
}
function ods_to_csf_3D(r8) {
  r8 = r8.replace(/\$'([^']|'')+'/g, function($$) {
    return $$.slice(1);
  });
  r8 = r8.replace(/\$([^\]\. #$]+)/g, function($$, $1) {
    return $1.match(/^([A-Z]{1,2}|[A-W][A-Z]{2}|X[A-E][A-Z]|XF[A-D])?(10[0-3]\d{4}|104[0-7]\d{3}|1048[0-4]\d{2}|10485[0-6]\d|104857[0-6]|[1-9]\d{0,5})?$/) ? $$ : $1;
  });
  var a3 = r8.split(":");
  var s6 = a3[0].split(".")[0];
  return [s6, a3[0].split(".")[1] + (a3.length > 1 ? ":" + (a3[1].split(".")[1] || a3[1].split(".")[0]) : "")];
}
var strs = {};
var _ssfopts = {};
function default_margins(margins, mode) {
  if (!margins) return;
  var defs = [0.7, 0.7, 0.75, 0.75, 0.3, 0.3];
  if (mode == "xlml") defs = [1, 1, 1, 1, 0.5, 0.5];
  if (margins.left == null) margins.left = defs[0];
  if (margins.right == null) margins.right = defs[1];
  if (margins.top == null) margins.top = defs[2];
  if (margins.bottom == null) margins.bottom = defs[3];
  if (margins.header == null) margins.header = defs[4];
  if (margins.footer == null) margins.footer = defs[5];
}
function safe_format(p4, fmtid, fillid, opts, themes, styles2, date1904) {
  try {
    if (opts.cellNF) p4.z = table_fmt[fmtid];
  } catch (e9) {
    if (opts.WTF) throw e9;
  }
  if (p4.t === "z" && !opts.cellStyles) return;
  if (p4.t === "d" && typeof p4.v === "string") p4.v = parseDate(p4.v);
  if ((!opts || opts.cellText !== false) && p4.t !== "z") try {
    if (table_fmt[fmtid] == null) SSF__load(SSFImplicit[fmtid] || "General", fmtid);
    if (p4.t === "e") p4.w = p4.w || BErr[p4.v];
    else if (fmtid === 0) {
      if (p4.t === "n") {
        if ((p4.v | 0) === p4.v) p4.w = p4.v.toString(10);
        else p4.w = SSF_general_num(p4.v);
      } else if (p4.t === "d") {
        var dd = datenum(p4.v, !!date1904);
        if ((dd | 0) === dd) p4.w = dd.toString(10);
        else p4.w = SSF_general_num(dd);
      } else if (p4.v === void 0) return "";
      else p4.w = SSF_general(p4.v, _ssfopts);
    } else if (p4.t === "d") p4.w = SSF_format(fmtid, datenum(p4.v, !!date1904), _ssfopts);
    else p4.w = SSF_format(fmtid, p4.v, _ssfopts);
  } catch (e9) {
    if (opts.WTF) throw e9;
  }
  if (!opts.cellStyles) return;
  if (fillid != null) try {
    p4.s = styles2.Fills[fillid];
    if (p4.s.fgColor && p4.s.fgColor.theme && !p4.s.fgColor.rgb) {
      p4.s.fgColor.rgb = rgb_tint(themes.themeElements.clrScheme[p4.s.fgColor.theme].rgb, p4.s.fgColor.tint || 0);
      if (opts.WTF) p4.s.fgColor.raw_rgb = themes.themeElements.clrScheme[p4.s.fgColor.theme].rgb;
    }
    if (p4.s.bgColor && p4.s.bgColor.theme) {
      p4.s.bgColor.rgb = rgb_tint(themes.themeElements.clrScheme[p4.s.bgColor.theme].rgb, p4.s.bgColor.tint || 0);
      if (opts.WTF) p4.s.bgColor.raw_rgb = themes.themeElements.clrScheme[p4.s.bgColor.theme].rgb;
    }
  } catch (e9) {
    if (opts.WTF && styles2.Fills) throw e9;
  }
}
function parse_ws_xml_dim(ws, s6) {
  var d4 = safe_decode_range(s6);
  if (d4.s.r <= d4.e.r && d4.s.c <= d4.e.c && d4.s.r >= 0 && d4.s.c >= 0) ws["!ref"] = encode_range(d4);
}
var mergecregex = /<(?:\w+:)?mergeCell ref=["'][A-Z0-9:]+['"]\s*[\/]?>/g;
var hlinkregex = /<(?:\w+:)?hyperlink [^<>]*>/mg;
var dimregex = /"(\w*:\w*)"/;
var colregex = /<(?:\w+:)?col\b[^<>]*[\/]?>/g;
var afregex = /<(?:\w+:)?autoFilter[^>]*/g;
var marginregex = /<(?:\w+:)?pageMargins[^<>]*\/>/g;
var sheetprregex = /<(?:\w+:)?sheetPr\b[^<>]*?\/>/;
function parse_ws_xml(data, opts, idx, rels, wb, themes, styles2) {
  if (!data) return data;
  if (!rels) rels = { "!id": {} };
  if (DENSE != null && opts.dense == null) opts.dense = DENSE;
  var s6 = {};
  if (opts.dense) s6["!data"] = [];
  var refguess = { s: { r: 2e6, c: 2e6 }, e: { r: 0, c: 0 } };
  var data1 = "", data2 = "";
  var mtch = str_match_xml_ns(data, "sheetData");
  if (mtch) {
    data1 = data.slice(0, mtch.index);
    data2 = data.slice(mtch.index + mtch[0].length);
  } else data1 = data2 = data;
  var sheetPr = data1.match(sheetprregex);
  if (sheetPr) parse_ws_xml_sheetpr(sheetPr[0], s6, wb, idx);
  else if (sheetPr = str_match_xml_ns(data1, "sheetPr")) parse_ws_xml_sheetpr2(sheetPr[0], sheetPr[1] || "", s6, wb, idx, styles2, themes);
  var ridx = (data1.match(/<(?:\w*:)?dimension/) || { index: -1 }).index;
  if (ridx > 0) {
    var ref = data1.slice(ridx, ridx + 50).match(dimregex);
    if (ref && !(opts && opts.nodim)) parse_ws_xml_dim(s6, ref[1]);
  }
  var svs = str_match_xml_ns(data1, "sheetViews");
  if (svs && svs[1]) parse_ws_xml_sheetviews(svs[1], wb);
  var columns = [];
  if (opts.cellStyles) {
    var cols = data1.match(colregex);
    if (cols) parse_ws_xml_cols(columns, cols);
  }
  if (mtch) parse_ws_xml_data(mtch[1], s6, opts, refguess, themes, styles2, wb);
  var afilter = data2.match(afregex);
  if (afilter) s6["!autofilter"] = parse_ws_xml_autofilter(afilter[0]);
  var merges = [];
  var _merge = data2.match(mergecregex);
  if (_merge) for (ridx = 0; ridx != _merge.length; ++ridx)
    merges[ridx] = safe_decode_range(_merge[ridx].slice(_merge[ridx].indexOf("=") + 2));
  var hlink = data2.match(hlinkregex);
  if (hlink) parse_ws_xml_hlinks(s6, hlink, rels);
  var margins = data2.match(marginregex);
  if (margins) s6["!margins"] = parse_ws_xml_margins(parsexmltag(margins[0]));
  var m4;
  if (m4 = data2.match(/legacyDrawing r:id="(.*?)"/)) s6["!legrel"] = m4[1];
  if (opts && opts.nodim) refguess.s.c = refguess.s.r = 0;
  if (!s6["!ref"] && refguess.e.c >= refguess.s.c && refguess.e.r >= refguess.s.r) s6["!ref"] = encode_range(refguess);
  if (opts.sheetRows > 0 && s6["!ref"]) {
    var tmpref = safe_decode_range(s6["!ref"]);
    if (opts.sheetRows <= +tmpref.e.r) {
      tmpref.e.r = opts.sheetRows - 1;
      if (tmpref.e.r > refguess.e.r) tmpref.e.r = refguess.e.r;
      if (tmpref.e.r < tmpref.s.r) tmpref.s.r = tmpref.e.r;
      if (tmpref.e.c > refguess.e.c) tmpref.e.c = refguess.e.c;
      if (tmpref.e.c < tmpref.s.c) tmpref.s.c = tmpref.e.c;
      s6["!fullref"] = s6["!ref"];
      s6["!ref"] = encode_range(tmpref);
    }
  }
  if (columns.length > 0) s6["!cols"] = columns;
  if (merges.length > 0) s6["!merges"] = merges;
  if (rels["!id"][s6["!legrel"]]) s6["!legdrawel"] = rels["!id"][s6["!legrel"]];
  return s6;
}
function parse_ws_xml_sheetpr(sheetPr, s6, wb, idx) {
  var data = parsexmltag(sheetPr);
  if (!wb.Sheets[idx]) wb.Sheets[idx] = {};
  if (data.codeName) wb.Sheets[idx].CodeName = unescapexml(utf8read(data.codeName));
}
function parse_ws_xml_sheetpr2(sheetPr, body, s6, wb, idx) {
  parse_ws_xml_sheetpr(sheetPr.slice(0, sheetPr.indexOf(">")), s6, wb, idx);
}
function parse_ws_xml_hlinks(s6, data, rels) {
  var dense = s6["!data"] != null;
  for (var i7 = 0; i7 != data.length; ++i7) {
    var val2 = parsexmltag(utf8read(data[i7]), true);
    if (!val2.ref) return;
    var rel2 = ((rels || {})["!id"] || [])[val2.id];
    if (rel2) {
      val2.Target = rel2.Target;
      if (val2.location) val2.Target += "#" + unescapexml(val2.location);
    } else {
      val2.Target = "#" + unescapexml(val2.location);
      rel2 = { Target: val2.Target, TargetMode: "Internal" };
    }
    val2.Rel = rel2;
    if (val2.tooltip) {
      val2.Tooltip = val2.tooltip;
      delete val2.tooltip;
    }
    var rng = safe_decode_range(val2.ref);
    for (var R3 = rng.s.r; R3 <= rng.e.r; ++R3) for (var C3 = rng.s.c; C3 <= rng.e.c; ++C3) {
      var addr = encode_col(C3) + encode_row(R3);
      if (dense) {
        if (!s6["!data"][R3]) s6["!data"][R3] = [];
        if (!s6["!data"][R3][C3]) s6["!data"][R3][C3] = { t: "z", v: void 0 };
        s6["!data"][R3][C3].l = val2;
      } else {
        if (!s6[addr]) s6[addr] = { t: "z", v: void 0 };
        s6[addr].l = val2;
      }
    }
  }
}
function parse_ws_xml_margins(margin) {
  var o9 = {};
  ["left", "right", "top", "bottom", "header", "footer"].forEach(function(k2) {
    if (margin[k2]) o9[k2] = parseFloat(margin[k2]);
  });
  return o9;
}
function parse_ws_xml_cols(columns, cols) {
  var seencol = false;
  for (var coli = 0; coli != cols.length; ++coli) {
    var coll = parsexmltag(cols[coli], true);
    if (coll.hidden) coll.hidden = parsexmlbool(coll.hidden);
    var colm = parseInt(coll.min, 10) - 1, colM = parseInt(coll.max, 10) - 1;
    if (coll.outlineLevel) coll.level = +coll.outlineLevel || 0;
    delete coll.min;
    delete coll.max;
    coll.width = +coll.width;
    if (!seencol && coll.width) {
      seencol = true;
      find_mdw_colw(coll.width);
    }
    process_col(coll);
    while (colm <= colM) columns[colm++] = dup(coll);
  }
}
function parse_ws_xml_autofilter(data) {
  var o9 = { ref: (data.match(/ref="([^"]*)"/) || [])[1] };
  return o9;
}
var sviewregex = /<(?:\w:)?sheetView(?:[^<>a-z][^<>]*)?\/?>/g;
function parse_ws_xml_sheetviews(data, wb) {
  if (!wb.Views) wb.Views = [{}];
  (data.match(sviewregex) || []).forEach(function(r8, i7) {
    var tag = parsexmltag(r8);
    if (!wb.Views[i7]) wb.Views[i7] = {};
    if (+tag.zoomScale) wb.Views[i7].zoom = +tag.zoomScale;
    if (tag.rightToLeft && parsexmlbool(tag.rightToLeft)) wb.Views[i7].RTL = true;
  });
}
var parse_ws_xml_data = /* @__PURE__ */ (function() {
  var cellregex = /<(?:\w+:)?c[ \/>]/, rowregex = /<\/(?:\w+:)?row>/;
  var rregex = /r=["']([^"']*)["']/;
  var refregex = /ref=["']([^"']*)["']/;
  return function parse_ws_xml_data2(sdata, s6, opts, guess, themes, styles2, wb) {
    var ri = 0, x2 = "", cells = [], cref = [], idx = 0, i7 = 0, cc = 0, d4 = "", p4;
    var tag, tagr = 0, tagc = 0;
    var sstr, ftag;
    var fmtid = 0, fillid = 0;
    var do_format = Array.isArray(styles2.CellXf), cf;
    var arrayf = [];
    var sharedf = [];
    var dense = s6["!data"] != null;
    var rows = [], rowobj = {}, rowrite = false;
    var sheetStubs = !!opts.sheetStubs;
    var date1904 = !!((wb || {}).WBProps || {}).date1904;
    for (var marr = sdata.split(rowregex), mt = 0, marrlen = marr.length; mt != marrlen; ++mt) {
      x2 = marr[mt].trim();
      var xlen = x2.length;
      if (xlen === 0) continue;
      var rstarti = 0;
      outa: for (ri = 0; ri < xlen; ++ri) switch (
        /*x.charCodeAt(ri)*/
        x2[ri]
      ) {
        case ">":
          if (
            /*x.charCodeAt(ri-1) != 47*/
            x2[ri - 1] != "/"
          ) {
            ++ri;
            break outa;
          }
          if (opts && opts.cellStyles) {
            tag = parsexmltag(x2.slice(rstarti, ri), true);
            tagr = tag.r != null ? parseInt(tag.r, 10) : tagr + 1;
            tagc = -1;
            if (opts.sheetRows && opts.sheetRows < tagr) continue;
            rowobj = {};
            rowrite = false;
            if (tag.ht) {
              rowrite = true;
              rowobj.hpt = parseFloat(tag.ht);
              rowobj.hpx = pt2px(rowobj.hpt);
            }
            if (tag.hidden && parsexmlbool(tag.hidden)) {
              rowrite = true;
              rowobj.hidden = true;
            }
            if (tag.outlineLevel != null) {
              rowrite = true;
              rowobj.level = +tag.outlineLevel;
            }
            if (rowrite) rows[tagr - 1] = rowobj;
          }
          break;
        case "<":
          rstarti = ri;
          break;
      }
      if (rstarti >= ri) break;
      tag = parsexmltag(x2.slice(rstarti, ri), true);
      tagr = tag.r != null ? parseInt(tag.r, 10) : tagr + 1;
      tagc = -1;
      if (opts.sheetRows && opts.sheetRows < tagr) continue;
      if (!opts.nodim) {
        if (guess.s.r > tagr - 1) guess.s.r = tagr - 1;
        if (guess.e.r < tagr - 1) guess.e.r = tagr - 1;
      }
      if (opts && opts.cellStyles) {
        rowobj = {};
        rowrite = false;
        if (tag.ht) {
          rowrite = true;
          rowobj.hpt = parseFloat(tag.ht);
          rowobj.hpx = pt2px(rowobj.hpt);
        }
        if (tag.hidden && parsexmlbool(tag.hidden)) {
          rowrite = true;
          rowobj.hidden = true;
        }
        if (tag.outlineLevel != null) {
          rowrite = true;
          rowobj.level = +tag.outlineLevel;
        }
        if (rowrite) rows[tagr - 1] = rowobj;
      }
      cells = x2.slice(ri).split(cellregex);
      for (var rslice = 0; rslice != cells.length; ++rslice) if (cells[rslice].trim().charAt(0) != "<") break;
      cells = cells.slice(rslice);
      for (ri = 0; ri != cells.length; ++ri) {
        x2 = cells[ri].trim();
        if (x2.length === 0) continue;
        cref = x2.match(rregex);
        idx = ri;
        i7 = 0;
        cc = 0;
        x2 = "<c " + (x2.slice(0, 1) == "<" ? ">" : "") + x2;
        if (cref != null && cref.length === 2) {
          idx = 0;
          d4 = cref[1];
          for (i7 = 0; i7 != d4.length; ++i7) {
            if ((cc = d4.charCodeAt(i7) - 64) < 1 || cc > 26) break;
            idx = 26 * idx + cc;
          }
          --idx;
          tagc = idx;
        } else ++tagc;
        for (i7 = 0; i7 != x2.length; ++i7) if (x2.charCodeAt(i7) === 62) break;
        ++i7;
        tag = parsexmltag(x2.slice(0, i7), true);
        if (!tag.r) tag.r = encode_cell({ r: tagr - 1, c: tagc });
        d4 = x2.slice(i7);
        p4 = { t: "" };
        if ((cref = str_match_xml_ns(d4, "v")) != null && /*::cref != null && */
        cref[1] !== "") p4.v = unescapexml(cref[1]);
        if (opts.cellFormula) {
          if ((cref = str_match_xml_ns(d4, "f")) != null) {
            if (cref[1] == "") {
              if (
                /*::cref != null && cref[0] != null && */
                cref[0].indexOf('t="shared"') > -1
              ) {
                ftag = parsexmltag(cref[0]);
                if (sharedf[ftag.si]) p4.f = shift_formula_xlsx(sharedf[ftag.si][1], sharedf[ftag.si][2], tag.r);
              }
            } else {
              p4.f = unescapexml(utf8read(cref[1]), true);
              if (!opts.xlfn) p4.f = _xlfn(p4.f);
              if (
                /*::cref != null && cref[0] != null && */
                cref[0].indexOf('t="array"') > -1
              ) {
                p4.F = (d4.match(refregex) || [])[1];
                if (p4.F.indexOf(":") > -1) arrayf.push([safe_decode_range(p4.F), p4.F]);
              } else if (
                /*::cref != null && cref[0] != null && */
                cref[0].indexOf('t="shared"') > -1
              ) {
                ftag = parsexmltag(cref[0]);
                var ___f = unescapexml(utf8read(cref[1]));
                if (!opts.xlfn) ___f = _xlfn(___f);
                sharedf[parseInt(ftag.si, 10)] = [ftag, ___f, tag.r];
              }
            }
          } else if (cref = d4.match(/<f[^<>]*\/>/)) {
            ftag = parsexmltag(cref[0]);
            if (sharedf[ftag.si]) p4.f = shift_formula_xlsx(sharedf[ftag.si][1], sharedf[ftag.si][2], tag.r);
          }
          var _tag = decode_cell(tag.r);
          for (i7 = 0; i7 < arrayf.length; ++i7)
            if (_tag.r >= arrayf[i7][0].s.r && _tag.r <= arrayf[i7][0].e.r) {
              if (_tag.c >= arrayf[i7][0].s.c && _tag.c <= arrayf[i7][0].e.c)
                p4.F = arrayf[i7][1];
            }
        }
        if (tag.t == null && p4.v === void 0) {
          if (p4.f || p4.F) {
            p4.v = 0;
            p4.t = "n";
          } else if (!sheetStubs) continue;
          else p4.t = "z";
        } else p4.t = tag.t || "n";
        if (guess.s.c > tagc) guess.s.c = tagc;
        if (guess.e.c < tagc) guess.e.c = tagc;
        switch (p4.t) {
          case "n":
            if (p4.v == "" || p4.v == null) {
              if (!sheetStubs) continue;
              p4.t = "z";
            } else p4.v = parseFloat(p4.v);
            break;
          case "s":
            if (typeof p4.v == "undefined") {
              if (!sheetStubs) continue;
              p4.t = "z";
            } else {
              sstr = strs[parseInt(p4.v, 10)];
              p4.v = sstr.t;
              p4.r = sstr.r;
              if (opts.cellHTML) p4.h = sstr.h;
            }
            break;
          case "str":
            p4.t = "s";
            p4.v = p4.v != null ? unescapexml(utf8read(p4.v), true) : "";
            if (opts.cellHTML) p4.h = escapehtml(p4.v);
            break;
          case "inlineStr":
            cref = str_match_xml_ns(d4, "is");
            p4.t = "s";
            if (cref != null && (sstr = parse_si(cref[1]))) {
              p4.v = sstr.t;
              if (opts.cellHTML) p4.h = sstr.h;
            } else p4.v = "";
            break;
          case "b":
            p4.v = parsexmlbool(p4.v);
            break;
          case "d":
            if (opts.cellDates) p4.v = parseDate(p4.v, date1904);
            else {
              p4.v = datenum(parseDate(p4.v, date1904), date1904);
              p4.t = "n";
            }
            break;
          /* error string in .w, number in .v */
          case "e":
            if (!opts || opts.cellText !== false) p4.w = p4.v;
            p4.v = RBErr[p4.v];
            break;
        }
        fmtid = fillid = 0;
        cf = null;
        if (do_format && tag.s !== void 0) {
          cf = styles2.CellXf[tag.s];
          if (cf != null) {
            if (cf.numFmtId != null) fmtid = cf.numFmtId;
            if (opts.cellStyles) {
              if (cf.fillId != null) fillid = cf.fillId;
            }
          }
        }
        safe_format(p4, fmtid, fillid, opts, themes, styles2, date1904);
        if (opts.cellDates && do_format && p4.t == "n" && fmt_is_date(table_fmt[fmtid])) {
          p4.v = numdate(p4.v + (date1904 ? 1462 : 0));
          p4.t = typeof p4.v == "number" ? "n" : "d";
        }
        if (tag.cm && opts.xlmeta) {
          var cm = (opts.xlmeta.Cell || [])[+tag.cm - 1];
          if (cm && cm.type == "XLDAPR") p4.D = true;
        }
        var _r;
        if (opts.nodim) {
          _r = decode_cell(tag.r);
          if (guess.s.r > _r.r) guess.s.r = _r.r;
          if (guess.e.r < _r.r) guess.e.r = _r.r;
        }
        if (dense) {
          _r = decode_cell(tag.r);
          if (!s6["!data"][_r.r]) s6["!data"][_r.r] = [];
          s6["!data"][_r.r][_r.c] = p4;
        } else s6[tag.r] = p4;
      }
    }
    if (rows.length > 0) s6["!rows"] = rows;
  };
})();
function parse_BrtRowHdr(data, length) {
  var z3 = {};
  var tgt = data.l + length;
  z3.r = data.read_shift(4);
  data.l += 4;
  var miyRw = data.read_shift(2);
  data.l += 1;
  var flags = data.read_shift(1);
  data.l = tgt;
  if (flags & 7) z3.level = flags & 7;
  if (flags & 16) z3.hidden = true;
  if (flags & 32) z3.hpt = miyRw / 20;
  return z3;
}
var parse_BrtWsDim = parse_UncheckedRfX;
function parse_BrtWsFmtInfo() {
}
function parse_BrtWsProp(data, length) {
  var z3 = {};
  var f4 = data[data.l];
  ++data.l;
  z3.above = !(f4 & 64);
  z3.left = !(f4 & 128);
  data.l += 18;
  z3.name = parse_XLSBCodeName(data, length - 19);
  return z3;
}
function parse_BrtCellBlank(data) {
  var cell = parse_XLSBCell(data);
  return [cell];
}
function parse_BrtShortBlank(data) {
  var cell = parse_XLSBShortCell(data);
  return [cell];
}
function parse_BrtCellBool(data) {
  var cell = parse_XLSBCell(data);
  var fBool = data.read_shift(1);
  return [cell, fBool, "b"];
}
function parse_BrtShortBool(data) {
  var cell = parse_XLSBShortCell(data);
  var fBool = data.read_shift(1);
  return [cell, fBool, "b"];
}
function parse_BrtCellError(data) {
  var cell = parse_XLSBCell(data);
  var bError = data.read_shift(1);
  return [cell, bError, "e"];
}
function parse_BrtShortError(data) {
  var cell = parse_XLSBShortCell(data);
  var bError = data.read_shift(1);
  return [cell, bError, "e"];
}
function parse_BrtCellIsst(data) {
  var cell = parse_XLSBCell(data);
  var isst = data.read_shift(4);
  return [cell, isst, "s"];
}
function parse_BrtShortIsst(data) {
  var cell = parse_XLSBShortCell(data);
  var isst = data.read_shift(4);
  return [cell, isst, "s"];
}
function parse_BrtCellReal(data) {
  var cell = parse_XLSBCell(data);
  var value = parse_Xnum(data);
  return [cell, value, "n"];
}
function parse_BrtShortReal(data) {
  var cell = parse_XLSBShortCell(data);
  var value = parse_Xnum(data);
  return [cell, value, "n"];
}
function parse_BrtCellRk(data) {
  var cell = parse_XLSBCell(data);
  var value = parse_RkNumber(data);
  return [cell, value, "n"];
}
function parse_BrtShortRk(data) {
  var cell = parse_XLSBShortCell(data);
  var value = parse_RkNumber(data);
  return [cell, value, "n"];
}
function parse_BrtCellRString(data) {
  var cell = parse_XLSBCell(data);
  var value = parse_RichStr(data);
  return [cell, value, "is"];
}
function parse_BrtCellSt(data) {
  var cell = parse_XLSBCell(data);
  var value = parse_XLWideString(data);
  return [cell, value, "str"];
}
function parse_BrtShortSt(data) {
  var cell = parse_XLSBShortCell(data);
  var value = parse_XLWideString(data);
  return [cell, value, "str"];
}
function parse_BrtFmlaBool(data, length, opts) {
  var end = data.l + length;
  var cell = parse_XLSBCell(data);
  cell.r = opts["!row"];
  var value = data.read_shift(1);
  var o9 = [cell, value, "b"];
  if (opts.cellFormula) {
    data.l += 2;
    var formula = parse_XLSBCellParsedFormula(data, end - data.l, opts);
    o9[3] = stringify_formula(formula, null, cell, opts.supbooks, opts);
  } else data.l = end;
  return o9;
}
function parse_BrtFmlaError(data, length, opts) {
  var end = data.l + length;
  var cell = parse_XLSBCell(data);
  cell.r = opts["!row"];
  var value = data.read_shift(1);
  var o9 = [cell, value, "e"];
  if (opts.cellFormula) {
    data.l += 2;
    var formula = parse_XLSBCellParsedFormula(data, end - data.l, opts);
    o9[3] = stringify_formula(formula, null, cell, opts.supbooks, opts);
  } else data.l = end;
  return o9;
}
function parse_BrtFmlaNum(data, length, opts) {
  var end = data.l + length;
  var cell = parse_XLSBCell(data);
  cell.r = opts["!row"];
  var value = parse_Xnum(data);
  var o9 = [cell, value, "n"];
  if (opts.cellFormula) {
    data.l += 2;
    var formula = parse_XLSBCellParsedFormula(data, end - data.l, opts);
    o9[3] = stringify_formula(formula, null, cell, opts.supbooks, opts);
  } else data.l = end;
  return o9;
}
function parse_BrtFmlaString(data, length, opts) {
  var end = data.l + length;
  var cell = parse_XLSBCell(data);
  cell.r = opts["!row"];
  var value = parse_XLWideString(data);
  var o9 = [cell, value, "str"];
  if (opts.cellFormula) {
    data.l += 2;
    var formula = parse_XLSBCellParsedFormula(data, end - data.l, opts);
    o9[3] = stringify_formula(formula, null, cell, opts.supbooks, opts);
  } else data.l = end;
  return o9;
}
var parse_BrtMergeCell = parse_UncheckedRfX;
function parse_BrtHLink(data, length) {
  var end = data.l + length;
  var rfx = parse_UncheckedRfX(data, 16);
  var relId = parse_XLNullableWideString(data);
  var loc = parse_XLWideString(data);
  var tooltip = parse_XLWideString(data);
  var display = parse_XLWideString(data);
  data.l = end;
  var o9 = { rfx, relId, loc, display };
  if (tooltip) o9.Tooltip = tooltip;
  return o9;
}
function parse_BrtPane() {
}
function parse_BrtArrFmla(data, length, opts) {
  var end = data.l + length;
  var rfx = parse_RfX(data, 16);
  var fAlwaysCalc = data.read_shift(1);
  var o9 = [rfx];
  o9[2] = fAlwaysCalc;
  if (opts.cellFormula) {
    var formula = parse_XLSBArrayParsedFormula(data, end - data.l, opts);
    o9[1] = formula;
  } else data.l = end;
  return o9;
}
function parse_BrtShrFmla(data, length, opts) {
  var end = data.l + length;
  var rfx = parse_UncheckedRfX(data, 16);
  var o9 = [rfx];
  if (opts.cellFormula) {
    var formula = parse_XLSBSharedParsedFormula(data, end - data.l, opts);
    o9[1] = formula;
    data.l = end;
  } else data.l = end;
  return o9;
}
var BrtMarginKeys = ["left", "right", "top", "bottom", "header", "footer"];
function parse_BrtMargins(data) {
  var margins = {};
  BrtMarginKeys.forEach(function(k2) {
    margins[k2] = parse_Xnum(data, 8);
  });
  return margins;
}
function parse_BrtBeginWsView(data) {
  var f4 = data.read_shift(2);
  data.l += 28;
  return { RTL: f4 & 32 };
}
function parse_BrtDVal() {
}
function parse_BrtDVal14() {
}
function parse_ws_bin(data, _opts, idx, rels, wb, themes, styles2) {
  if (!data) return data;
  var opts = _opts || {};
  if (!rels) rels = { "!id": {} };
  if (DENSE != null && opts.dense == null) opts.dense = DENSE;
  var s6 = {};
  if (opts.dense) s6["!data"] = [];
  var ref;
  var refguess = { s: { r: 2e6, c: 2e6 }, e: { r: 0, c: 0 } };
  var state = [];
  var pass = false, end = false;
  var row, p4, cf, R3, C3, addr, sstr, rr, cell;
  var merges = [];
  opts.biff = 12;
  opts["!row"] = 0;
  var ai = 0, af = false;
  var arrayf = [];
  var sharedf = {};
  var supbooks = opts.supbooks || /*::(*/
  wb.supbooks || [[]];
  supbooks.sharedf = sharedf;
  supbooks.arrayf = arrayf;
  supbooks.SheetNames = wb.SheetNames || wb.Sheets.map(function(x2) {
    return x2.name;
  });
  if (!opts.supbooks) {
    opts.supbooks = supbooks;
    if (wb.Names) for (var i7 = 0; i7 < wb.Names.length; ++i7) supbooks[0][i7 + 1] = wb.Names[i7];
  }
  var colinfo = [], rowinfo = [];
  var seencol = false;
  XLSBRecordEnum[16] = { n: "BrtShortReal", f: parse_BrtShortReal };
  var cm, vm;
  var date1904 = 1462 * +!!((wb || {}).WBProps || {}).date1904;
  recordhopper(data, function ws_parse(val2, RR, RT) {
    if (end) return;
    switch (RT) {
      case 148:
        ref = val2;
        break;
      case 0:
        row = val2;
        if (opts.sheetRows && opts.sheetRows <= row.r) end = true;
        rr = encode_row(R3 = row.r);
        opts["!row"] = row.r;
        if (val2.hidden || val2.hpt || val2.level != null) {
          if (val2.hpt) val2.hpx = pt2px(val2.hpt);
          rowinfo[val2.r] = val2;
        }
        break;
      case 2:
      /* 'BrtCellRk' */
      case 3:
      /* 'BrtCellError' */
      case 4:
      /* 'BrtCellBool' */
      case 5:
      /* 'BrtCellReal' */
      case 6:
      /* 'BrtCellSt' */
      case 7:
      /* 'BrtCellIsst' */
      case 8:
      /* 'BrtFmlaString' */
      case 9:
      /* 'BrtFmlaNum' */
      case 10:
      /* 'BrtFmlaBool' */
      case 11:
      /* 'BrtFmlaError' */
      case 13:
      /* 'BrtShortRk' */
      case 14:
      /* 'BrtShortError' */
      case 15:
      /* 'BrtShortBool' */
      case 16:
      /* 'BrtShortReal' */
      case 17:
      /* 'BrtShortSt' */
      case 18:
      /* 'BrtShortIsst' */
      case 62:
        p4 = { t: val2[2] };
        switch (val2[2]) {
          case "n":
            p4.v = val2[1];
            break;
          case "s":
            sstr = strs[val2[1]];
            p4.v = sstr.t;
            p4.r = sstr.r;
            break;
          case "b":
            p4.v = val2[1] ? true : false;
            break;
          case "e":
            p4.v = val2[1];
            if (opts.cellText !== false) p4.w = BErr[p4.v];
            break;
          case "str":
            p4.t = "s";
            p4.v = val2[1];
            break;
          case "is":
            p4.t = "s";
            p4.v = val2[1].t;
            break;
        }
        if (cf = styles2.CellXf[val2[0].iStyleRef]) safe_format(p4, cf.numFmtId, null, opts, themes, styles2, date1904 > 0);
        C3 = val2[0].c == -1 ? C3 + 1 : val2[0].c;
        if (opts.dense) {
          if (!s6["!data"][R3]) s6["!data"][R3] = [];
          s6["!data"][R3][C3] = p4;
        } else s6[encode_col(C3) + rr] = p4;
        if (opts.cellFormula) {
          af = false;
          for (ai = 0; ai < arrayf.length; ++ai) {
            var aii = arrayf[ai];
            if (row.r >= aii[0].s.r && row.r <= aii[0].e.r) {
              if (C3 >= aii[0].s.c && C3 <= aii[0].e.c) {
                p4.F = encode_range(aii[0]);
                af = true;
              }
            }
          }
          if (!af && val2.length > 3) p4.f = val2[3];
        }
        if (refguess.s.r > row.r) refguess.s.r = row.r;
        if (refguess.s.c > C3) refguess.s.c = C3;
        if (refguess.e.r < row.r) refguess.e.r = row.r;
        if (refguess.e.c < C3) refguess.e.c = C3;
        if (opts.cellDates && cf && p4.t == "n" && fmt_is_date(table_fmt[cf.numFmtId])) {
          var _d = SSF_parse_date_code(p4.v + date1904);
          if (_d) {
            p4.t = "d";
            p4.v = new Date(Date.UTC(_d.y, _d.m - 1, _d.d, _d.H, _d.M, _d.S, _d.u));
          }
        }
        if (cm) {
          if (cm.type == "XLDAPR") p4.D = true;
          cm = void 0;
        }
        if (vm) vm = void 0;
        break;
      case 1:
      /* 'BrtCellBlank' */
      case 12:
        if (!opts.sheetStubs || pass) break;
        p4 = { t: "z", v: void 0 };
        C3 = val2[0].c == -1 ? C3 + 1 : val2[0].c;
        if (opts.dense) {
          if (!s6["!data"][R3]) s6["!data"][R3] = [];
          s6["!data"][R3][C3] = p4;
        } else s6[encode_col(C3) + rr] = p4;
        if (refguess.s.r > row.r) refguess.s.r = row.r;
        if (refguess.s.c > C3) refguess.s.c = C3;
        if (refguess.e.r < row.r) refguess.e.r = row.r;
        if (refguess.e.c < C3) refguess.e.c = C3;
        if (cm) {
          if (cm.type == "XLDAPR") p4.D = true;
          cm = void 0;
        }
        if (vm) vm = void 0;
        break;
      case 176:
        merges.push(val2);
        break;
      case 49:
        {
          cm = ((opts.xlmeta || {}).Cell || [])[val2 - 1];
        }
        break;
      case 494:
        var rel2 = rels["!id"][val2.relId];
        if (rel2) {
          val2.Target = rel2.Target;
          if (val2.loc) val2.Target += "#" + val2.loc;
          val2.Rel = rel2;
        } else if (val2.relId == "") {
          val2.Target = "#" + val2.loc;
        }
        for (R3 = val2.rfx.s.r; R3 <= val2.rfx.e.r; ++R3) for (C3 = val2.rfx.s.c; C3 <= val2.rfx.e.c; ++C3) {
          if (opts.dense) {
            if (!s6["!data"][R3]) s6["!data"][R3] = [];
            if (!s6["!data"][R3][C3]) s6["!data"][R3][C3] = { t: "z", v: void 0 };
            s6["!data"][R3][C3].l = val2;
          } else {
            addr = encode_col(C3) + encode_row(R3);
            if (!s6[addr]) s6[addr] = { t: "z", v: void 0 };
            s6[addr].l = val2;
          }
        }
        break;
      case 426:
        if (!opts.cellFormula) break;
        arrayf.push(val2);
        cell = opts.dense ? s6["!data"][R3][C3] : s6[encode_col(C3) + rr];
        cell.f = stringify_formula(val2[1], refguess, { r: row.r, c: C3 }, supbooks, opts);
        cell.F = encode_range(val2[0]);
        break;
      case 427:
        if (!opts.cellFormula) break;
        sharedf[encode_cell(val2[0].s)] = val2[1];
        cell = opts.dense ? s6["!data"][R3][C3] : s6[encode_col(C3) + rr];
        cell.f = stringify_formula(val2[1], refguess, { r: row.r, c: C3 }, supbooks, opts);
        break;
      /* identical to 'ColInfo' in XLS */
      case 60:
        if (!opts.cellStyles) break;
        while (val2.e >= val2.s) {
          colinfo[val2.e--] = { width: val2.w / 256, hidden: !!(val2.flags & 1), level: val2.level };
          if (!seencol) {
            seencol = true;
            find_mdw_colw(val2.w / 256);
          }
          process_col(colinfo[val2.e + 1]);
        }
        break;
      case 551:
        if (val2) s6["!legrel"] = val2;
        break;
      case 161:
        s6["!autofilter"] = { ref: encode_range(val2) };
        break;
      case 476:
        s6["!margins"] = val2;
        break;
      case 147:
        if (!wb.Sheets[idx]) wb.Sheets[idx] = {};
        if (val2.name) wb.Sheets[idx].CodeName = val2.name;
        if (val2.above || val2.left) s6["!outline"] = { above: val2.above, left: val2.left };
        break;
      case 137:
        if (!wb.Views) wb.Views = [{}];
        if (!wb.Views[0]) wb.Views[0] = {};
        if (val2.RTL) wb.Views[0].RTL = true;
        break;
      case 485:
        break;
      case 64:
      /* 'BrtDVal' */
      case 1053:
        break;
      case 151:
        break;
      case 152:
      /* 'BrtSel' */
      case 175:
      /* 'BrtAFilterDateGroupItem' */
      case 644:
      /* 'BrtActiveX' */
      case 625:
      /* 'BrtBigName' */
      case 562:
      /* 'BrtBkHim' */
      case 396:
      /* 'BrtBrk' */
      case 1112:
      /* 'BrtCFIcon' */
      case 1146:
      /* 'BrtCFRuleExt' */
      case 471:
      /* 'BrtCFVO' */
      case 1050:
      /* 'BrtCFVO14' */
      case 649:
      /* 'BrtCellIgnoreEC' */
      case 1105:
      /* 'BrtCellIgnoreEC14' */
      case 589:
      /* 'BrtCellSmartTagProperty' */
      case 607:
      /* 'BrtCellWatch' */
      case 564:
      /* 'BrtColor' */
      case 1055:
      /* 'BrtColor14' */
      case 168:
      /* 'BrtColorFilter' */
      case 174:
      /* 'BrtCustomFilter' */
      case 1180:
      /* 'BrtCustomFilter14' */
      case 499:
      /* 'BrtDRef' */
      case 507:
      /* 'BrtDXF' */
      case 550:
      /* 'BrtDrawing' */
      case 171:
      /* 'BrtDynamicFilter' */
      case 167:
      /* 'BrtFilter' */
      case 1177:
      /* 'BrtFilter14' */
      case 169:
      /* 'BrtIconFilter' */
      case 1181:
      /* 'BrtIconFilter14' */
      case 552:
      /* 'BrtLegacyDrawingHF' */
      case 661:
      /* 'BrtListPart' */
      case 639:
      /* 'BrtOleObject' */
      case 478:
      /* 'BrtPageSetup' */
      case 537:
      /* 'BrtPhoneticInfo' */
      case 477:
      /* 'BrtPrintOptions' */
      case 536:
      /* 'BrtRangeProtection' */
      case 1103:
      /* 'BrtRangeProtection14' */
      case 680:
      /* 'BrtRangeProtectionIso' */
      case 1104:
      /* 'BrtRangeProtectionIso14' */
      case 1024:
      /* 'BrtRwDescent' */
      case 663:
      /* 'BrtSheetCalcProp' */
      case 535:
      /* 'BrtSheetProtection' */
      case 678:
      /* 'BrtSheetProtectionIso' */
      case 504:
      /* 'BrtSlc' */
      case 1043:
      /* 'BrtSparkline' */
      case 428:
      /* 'BrtTable' */
      case 170:
      /* 'BrtTop10Filter' */
      case 3072:
      /* 'BrtUid' */
      case 50:
      /* 'BrtValueMeta' */
      case 2070:
      /* 'BrtWebExtension' */
      case 1045:
        break;
      case 35:
        pass = true;
        break;
      case 36:
        pass = false;
        break;
      case 37:
        state.push(RT);
        pass = true;
        break;
      case 38:
        state.pop();
        pass = false;
        break;
      default:
        if (RR.T) {
        } else if (!pass || opts.WTF) throw new Error("Unexpected record 0x" + RT.toString(16));
    }
  }, opts);
  delete opts.supbooks;
  delete opts["!row"];
  if (!s6["!ref"] && (refguess.s.r < 2e6 || ref && (ref.e.r > 0 || ref.e.c > 0 || ref.s.r > 0 || ref.s.c > 0))) s6["!ref"] = encode_range(ref || refguess);
  if (opts.sheetRows && s6["!ref"]) {
    var tmpref = safe_decode_range(s6["!ref"]);
    if (opts.sheetRows <= +tmpref.e.r) {
      tmpref.e.r = opts.sheetRows - 1;
      if (tmpref.e.r > refguess.e.r) tmpref.e.r = refguess.e.r;
      if (tmpref.e.r < tmpref.s.r) tmpref.s.r = tmpref.e.r;
      if (tmpref.e.c > refguess.e.c) tmpref.e.c = refguess.e.c;
      if (tmpref.e.c < tmpref.s.c) tmpref.s.c = tmpref.e.c;
      s6["!fullref"] = s6["!ref"];
      s6["!ref"] = encode_range(tmpref);
    }
  }
  if (merges.length > 0) s6["!merges"] = merges;
  if (colinfo.length > 0) s6["!cols"] = colinfo;
  if (rowinfo.length > 0) s6["!rows"] = rowinfo;
  if (rels["!id"][s6["!legrel"]]) s6["!legdrawel"] = rels["!id"][s6["!legrel"]];
  return s6;
}
function parse_Cache(data) {
  var col = [];
  var num = data.match(/^<c:numCache>/);
  var f4;
  (data.match(/<c:pt idx="(\d*)"[^<>\/]*><c:v>([^<])<\/c:v><\/c:pt>/mg) || []).forEach(function(pt) {
    var q2 = pt.match(/<c:pt idx="(\d*)"[^<>\/]*><c:v>([^<]*)<\/c:v><\/c:pt>/);
    if (!q2) return;
    col[+q2[1]] = num ? +q2[2] : q2[2];
  });
  var nf = unescapexml((str_match_xml(data, "c:formatCode") || ["", "General"])[1]);
  (str_match_ng(data, "<c:f>", "</c:f>") || []).forEach(function(F2) {
    f4 = F2.replace(/<[^<>]*>/g, "");
  });
  return [col, nf, f4];
}
function parse_chart(data, name, opts, rels, wb, csheet) {
  var cs = csheet || { "!type": "chart" };
  if (!data) return csheet;
  var C3 = 0, R3 = 0, col = "A";
  var refguess = { s: { r: 2e6, c: 2e6 }, e: { r: 0, c: 0 } };
  (str_match_ng(data, "<c:numCache>", "</c:numCache>") || []).forEach(function(nc) {
    var cache = parse_Cache(nc);
    refguess.s.r = refguess.s.c = 0;
    refguess.e.c = C3;
    col = encode_col(C3);
    cache[0].forEach(function(n7, i7) {
      if (cs["!data"]) {
        if (!cs["!data"][i7]) cs["!data"][i7] = [];
        cs["!data"][i7][C3] = { t: "n", v: n7, z: cache[1] };
      } else cs[col + encode_row(i7)] = { t: "n", v: n7, z: cache[1] };
      R3 = i7;
    });
    if (refguess.e.r < R3) refguess.e.r = R3;
    ++C3;
  });
  if (C3 > 0) cs["!ref"] = encode_range(refguess);
  return cs;
}
function parse_cs_xml(data, opts, idx, rels, wb) {
  if (!data) return data;
  if (!rels) rels = { "!id": {} };
  var s6 = { "!type": "chart", "!drawel": null, "!rel": "" };
  var m4;
  var sheetPr = data.match(sheetprregex);
  if (sheetPr) parse_ws_xml_sheetpr(sheetPr[0], s6, wb, idx);
  if (m4 = data.match(/drawing r:id="(.*?)"/)) s6["!rel"] = m4[1];
  if (rels["!id"][s6["!rel"]]) s6["!drawel"] = rels["!id"][s6["!rel"]];
  return s6;
}
function parse_BrtCsProp(data, length) {
  data.l += 10;
  var name = parse_XLWideString(data, length - 10);
  return { name };
}
function parse_cs_bin(data, opts, idx, rels, wb) {
  if (!data) return data;
  if (!rels) rels = { "!id": {} };
  var s6 = { "!type": "chart", "!drawel": null, "!rel": "" };
  var state = [];
  var pass = false;
  recordhopper(data, function cs_parse(val2, R3, RT) {
    switch (RT) {
      case 550:
        s6["!rel"] = val2;
        break;
      case 651:
        if (!wb.Sheets[idx]) wb.Sheets[idx] = {};
        if (val2.name) wb.Sheets[idx].CodeName = val2.name;
        break;
      case 562:
      /* 'BrtBkHim' */
      case 652:
      /* 'BrtCsPageSetup' */
      case 669:
      /* 'BrtCsProtection' */
      case 679:
      /* 'BrtCsProtectionIso' */
      case 551:
      /* 'BrtLegacyDrawing' */
      case 552:
      /* 'BrtLegacyDrawingHF' */
      case 476:
      /* 'BrtMargins' */
      case 3072:
        break;
      case 35:
        pass = true;
        break;
      case 36:
        pass = false;
        break;
      case 37:
        state.push(RT);
        break;
      case 38:
        state.pop();
        break;
      default:
        if (R3.T > 0) state.push(RT);
        else if (R3.T < 0) state.pop();
        else if (!pass || opts.WTF) throw new Error("Unexpected record 0x" + RT.toString(16));
    }
  }, opts);
  if (rels["!id"][s6["!rel"]]) s6["!drawel"] = rels["!id"][s6["!rel"]];
  return s6;
}
var WBPropsDef = [
  ["allowRefreshQuery", false, "bool"],
  ["autoCompressPictures", true, "bool"],
  ["backupFile", false, "bool"],
  ["checkCompatibility", false, "bool"],
  ["CodeName", ""],
  ["date1904", false, "bool"],
  ["defaultThemeVersion", 0, "int"],
  ["filterPrivacy", false, "bool"],
  ["hidePivotFieldList", false, "bool"],
  ["promptedSolutions", false, "bool"],
  ["publishItems", false, "bool"],
  ["refreshAllConnections", false, "bool"],
  ["saveExternalLinkValues", true, "bool"],
  ["showBorderUnselectedTables", true, "bool"],
  ["showInkAnnotation", true, "bool"],
  ["showObjects", "all"],
  ["showPivotChartFilter", false, "bool"],
  ["updateLinks", "userSet"]
];
var WBViewDef = [
  ["activeTab", 0, "int"],
  ["autoFilterDateGrouping", true, "bool"],
  ["firstSheet", 0, "int"],
  ["minimized", false, "bool"],
  ["showHorizontalScroll", true, "bool"],
  ["showSheetTabs", true, "bool"],
  ["showVerticalScroll", true, "bool"],
  ["tabRatio", 600, "int"],
  ["visibility", "visible"]
  //window{Height,Width}, {x,y}Window
];
var SheetDef = [
  //['state', 'visible']
];
var CalcPrDef = [
  ["calcCompleted", "true"],
  ["calcMode", "auto"],
  ["calcOnSave", "true"],
  ["concurrentCalc", "true"],
  ["fullCalcOnLoad", "false"],
  ["fullPrecision", "true"],
  ["iterate", "false"],
  ["iterateCount", "100"],
  ["iterateDelta", "0.001"],
  ["refMode", "A1"]
];
function push_defaults_array(target, defaults3) {
  for (var j3 = 0; j3 != target.length; ++j3) {
    var w3 = target[j3];
    for (var i7 = 0; i7 != defaults3.length; ++i7) {
      var z3 = defaults3[i7];
      if (w3[z3[0]] == null) w3[z3[0]] = z3[1];
      else switch (z3[2]) {
        case "bool":
          if (typeof w3[z3[0]] == "string") w3[z3[0]] = parsexmlbool(w3[z3[0]]);
          break;
        case "int":
          if (typeof w3[z3[0]] == "string") w3[z3[0]] = parseInt(w3[z3[0]], 10);
          break;
      }
    }
  }
}
function push_defaults(target, defaults3) {
  for (var i7 = 0; i7 != defaults3.length; ++i7) {
    var z3 = defaults3[i7];
    if (target[z3[0]] == null) target[z3[0]] = z3[1];
    else switch (z3[2]) {
      case "bool":
        if (typeof target[z3[0]] == "string") target[z3[0]] = parsexmlbool(target[z3[0]]);
        break;
      case "int":
        if (typeof target[z3[0]] == "string") target[z3[0]] = parseInt(target[z3[0]], 10);
        break;
    }
  }
}
function parse_wb_defaults(wb) {
  push_defaults(wb.WBProps, WBPropsDef);
  push_defaults(wb.CalcPr, CalcPrDef);
  push_defaults_array(wb.WBView, WBViewDef);
  push_defaults_array(wb.Sheets, SheetDef);
  _ssfopts.date1904 = parsexmlbool(wb.WBProps.date1904);
}
var badchars = /* @__PURE__ */ ":][*?/\\".split("");
function check_ws_name(n7, safe) {
  try {
    if (n7 == "") throw new Error("Sheet name cannot be blank");
    if (n7.length > 31) throw new Error("Sheet name cannot exceed 31 chars");
    if (n7.charCodeAt(0) == 39 || n7.charCodeAt(n7.length - 1) == 39) throw new Error("Sheet name cannot start or end with apostrophe (')");
    if (n7.toLowerCase() == "history") throw new Error("Sheet name cannot be 'History'");
    badchars.forEach(function(c6) {
      if (n7.indexOf(c6) == -1) return;
      throw new Error("Sheet name cannot contain : \\ / ? * [ ]");
    });
  } catch (e9) {
    if (safe) return false;
    throw e9;
  }
  return true;
}
var wbnsregex = /<\w+:workbook/;
function parse_wb_xml(data, opts) {
  if (!data) throw new Error("Could not find file");
  var wb = (
    /*::(*/
    { AppVersion: {}, WBProps: {}, WBView: [], Sheets: [], CalcPr: {}, Names: [], xmlns: "" }
  );
  var pass = false, xmlns = "xmlns";
  var dname = {}, dnstart = 0;
  data.replace(tagregex, function xml_wb(x2, idx) {
    var y4 = parsexmltag(x2);
    switch (strip_ns(y4[0])) {
      case "<?xml":
        break;
      /* 18.2.27 workbook CT_Workbook 1 */
      case "<workbook":
        if (x2.match(wbnsregex)) xmlns = "xmlns" + x2.match(/<(\w+):/)[1];
        wb.xmlns = y4[xmlns];
        break;
      case "</workbook>":
        break;
      /* 18.2.13 fileVersion CT_FileVersion ? */
      case "<fileVersion":
        delete y4[0];
        wb.AppVersion = y4;
        break;
      case "<fileVersion/>":
      case "</fileVersion>":
        break;
      /* 18.2.12 fileSharing CT_FileSharing ? */
      case "<fileSharing":
        break;
      case "<fileSharing/>":
        break;
      /* 18.2.28 workbookPr CT_WorkbookPr ? */
      case "<workbookPr":
      case "<workbookPr/>":
        WBPropsDef.forEach(function(w3) {
          if (y4[w3[0]] == null) return;
          switch (w3[2]) {
            case "bool":
              wb.WBProps[w3[0]] = parsexmlbool(y4[w3[0]]);
              break;
            case "int":
              wb.WBProps[w3[0]] = parseInt(y4[w3[0]], 10);
              break;
            default:
              wb.WBProps[w3[0]] = y4[w3[0]];
          }
        });
        if (y4.codeName) wb.WBProps.CodeName = utf8read(y4.codeName);
        break;
      case "</workbookPr>":
        break;
      /* 18.2.29 workbookProtection CT_WorkbookProtection ? */
      case "<workbookProtection":
        break;
      case "<workbookProtection/>":
        break;
      /* 18.2.1  bookViews CT_BookViews ? */
      case "<bookViews":
      case "<bookViews>":
      case "</bookViews>":
        break;
      /* 18.2.30   workbookView CT_BookView + */
      case "<workbookView":
      case "<workbookView/>":
        delete y4[0];
        wb.WBView.push(y4);
        break;
      case "</workbookView>":
        break;
      /* 18.2.20 sheets CT_Sheets 1 */
      case "<sheets":
      case "<sheets>":
      case "</sheets>":
        break;
      // aggregate sheet
      /* 18.2.19   sheet CT_Sheet + */
      case "<sheet":
        switch (y4.state) {
          case "hidden":
            y4.Hidden = 1;
            break;
          case "veryHidden":
            y4.Hidden = 2;
            break;
          default:
            y4.Hidden = 0;
        }
        delete y4.state;
        y4.name = unescapexml(utf8read(y4.name));
        delete y4[0];
        wb.Sheets.push(y4);
        break;
      case "</sheet>":
        break;
      /* 18.2.15 functionGroups CT_FunctionGroups ? */
      case "<functionGroups":
      case "<functionGroups/>":
        break;
      /* 18.2.14   functionGroup CT_FunctionGroup + */
      case "<functionGroup":
        break;
      /* 18.2.9  externalReferences CT_ExternalReferences ? */
      case "<externalReferences":
      case "</externalReferences>":
      case "<externalReferences>":
        break;
      /* 18.2.8    externalReference CT_ExternalReference + */
      case "<externalReference":
        break;
      /* 18.2.6  definedNames CT_DefinedNames ? */
      case "<definedNames/>":
        break;
      case "<definedNames>":
      case "<definedNames":
        pass = true;
        break;
      case "</definedNames>":
        pass = false;
        break;
      /* 18.2.5    definedName CT_DefinedName + */
      case "<definedName":
        {
          dname = {};
          dname.Name = utf8read(y4.name);
          if (y4.comment) dname.Comment = y4.comment;
          if (y4.localSheetId) dname.Sheet = +y4.localSheetId;
          if (parsexmlbool(y4.hidden || "0")) dname.Hidden = true;
          dnstart = idx + x2.length;
        }
        break;
      case "</definedName>":
        {
          dname.Ref = unescapexml(utf8read(data.slice(dnstart, idx)));
          wb.Names.push(dname);
        }
        break;
      case "<definedName/>":
        break;
      /* 18.2.2  calcPr CT_CalcPr ? */
      case "<calcPr":
        delete y4[0];
        wb.CalcPr = y4;
        break;
      case "<calcPr/>":
        delete y4[0];
        wb.CalcPr = y4;
        break;
      case "</calcPr>":
        break;
      /* 18.2.16 oleSize CT_OleSize ? (ref required) */
      case "<oleSize":
        break;
      /* 18.2.4  customWorkbookViews CT_CustomWorkbookViews ? */
      case "<customWorkbookViews>":
      case "</customWorkbookViews>":
      case "<customWorkbookViews":
        break;
      /* 18.2.3  customWorkbookView CT_CustomWorkbookView + */
      case "<customWorkbookView":
      case "</customWorkbookView>":
        break;
      /* 18.2.18 pivotCaches CT_PivotCaches ? */
      case "<pivotCaches>":
      case "</pivotCaches>":
      case "<pivotCaches":
        break;
      /* 18.2.17 pivotCache CT_PivotCache ? */
      case "<pivotCache":
        break;
      /* 18.2.21 smartTagPr CT_SmartTagPr ? */
      case "<smartTagPr":
      case "<smartTagPr/>":
        break;
      /* 18.2.23 smartTagTypes CT_SmartTagTypes ? */
      case "<smartTagTypes":
      case "<smartTagTypes>":
      case "</smartTagTypes>":
        break;
      /* 18.2.22 smartTagType CT_SmartTagType ? */
      case "<smartTagType":
        break;
      /* 18.2.24 webPublishing CT_WebPublishing ? */
      case "<webPublishing":
      case "<webPublishing/>":
        break;
      /* 18.2.11 fileRecoveryPr CT_FileRecoveryPr ? */
      case "<fileRecoveryPr":
      case "<fileRecoveryPr/>":
        break;
      /* 18.2.26 webPublishObjects CT_WebPublishObjects ? */
      case "<webPublishObjects>":
      case "<webPublishObjects":
      case "</webPublishObjects>":
        break;
      /* 18.2.25 webPublishObject CT_WebPublishObject ? */
      case "<webPublishObject":
        break;
      /* 18.2.10 extLst CT_ExtensionList ? */
      case "<extLst":
      case "<extLst>":
      case "</extLst>":
      case "<extLst/>":
        break;
      /* 18.2.7  ext CT_Extension + */
      case "<ext":
        pass = true;
        break;
      //TODO: check with versions of excel
      case "</ext>":
        pass = false;
        break;
      /* Others */
      case "<ArchID":
        break;
      case "<AlternateContent":
      case "<AlternateContent>":
        pass = true;
        break;
      case "</AlternateContent>":
        pass = false;
        break;
      /* TODO */
      case "<revisionPtr":
        break;
      default:
        if (!pass && opts.WTF) throw new Error("unrecognized " + y4[0] + " in workbook");
    }
    return x2;
  });
  if (XMLNS_main.indexOf(wb.xmlns) === -1) throw new Error("Unknown Namespace: " + wb.xmlns);
  parse_wb_defaults(wb);
  return wb;
}
function parse_BrtBundleSh(data, length) {
  var z3 = {};
  z3.Hidden = data.read_shift(4);
  z3.iTabID = data.read_shift(4);
  z3.strRelID = parse_RelID(data, length - 8);
  z3.name = parse_XLWideString(data);
  return z3;
}
function parse_BrtWbProp(data, length) {
  var o9 = {};
  var flags = data.read_shift(4);
  o9.defaultThemeVersion = data.read_shift(4);
  var strName = length > 8 ? parse_XLWideString(data) : "";
  if (strName.length > 0) o9.CodeName = strName;
  o9.autoCompressPictures = !!(flags & 65536);
  o9.backupFile = !!(flags & 64);
  o9.checkCompatibility = !!(flags & 4096);
  o9.date1904 = !!(flags & 1);
  o9.filterPrivacy = !!(flags & 8);
  o9.hidePivotFieldList = !!(flags & 1024);
  o9.promptedSolutions = !!(flags & 16);
  o9.publishItems = !!(flags & 2048);
  o9.refreshAllConnections = !!(flags & 262144);
  o9.saveExternalLinkValues = !!(flags & 128);
  o9.showBorderUnselectedTables = !!(flags & 4);
  o9.showInkAnnotation = !!(flags & 32);
  o9.showObjects = ["all", "placeholders", "none"][flags >> 13 & 3];
  o9.showPivotChartFilter = !!(flags & 32768);
  o9.updateLinks = ["userSet", "never", "always"][flags >> 8 & 3];
  return o9;
}
function parse_BrtFRTArchID$(data, length) {
  var o9 = {};
  data.read_shift(4);
  o9.ArchID = data.read_shift(4);
  data.l += length - 8;
  return o9;
}
function parse_BrtName(data, length, opts) {
  var end = data.l + length;
  var flags = data.read_shift(4);
  data.l += 1;
  var itab = data.read_shift(4);
  var name = parse_XLNameWideString(data);
  var formula;
  var comment = "";
  try {
    formula = parse_XLSBNameParsedFormula(data, 0, opts);
    try {
      comment = parse_XLNullableWideString(data);
    } catch (e9) {
    }
  } catch (e9) {
    console.error("Could not parse defined name " + name);
  }
  if (flags & 32) name = "_xlnm." + name;
  data.l = end;
  var out = { Name: name, Ptg: formula, Flags: flags };
  if (itab < 268435455) out.Sheet = itab;
  if (comment) out.Comment = comment;
  return out;
}
function parse_wb_bin(data, opts) {
  var wb = { AppVersion: {}, WBProps: {}, WBView: [], Sheets: [], CalcPr: {}, xmlns: "" };
  var state = [];
  var pass = false;
  if (!opts) opts = {};
  opts.biff = 12;
  var Names = [];
  var supbooks = [[]];
  supbooks.SheetNames = [];
  supbooks.XTI = [];
  XLSBRecordEnum[16] = { n: "BrtFRTArchID$", f: parse_BrtFRTArchID$ };
  recordhopper(data, function hopper_wb(val2, R3, RT) {
    switch (RT) {
      case 156:
        supbooks.SheetNames.push(val2.name);
        wb.Sheets.push(val2);
        break;
      case 153:
        wb.WBProps = val2;
        break;
      case 39:
        if (val2.Sheet != null) opts.SID = val2.Sheet;
        val2.Ref = val2.Ptg ? stringify_formula(val2.Ptg, null, null, supbooks, opts) : "#REF!";
        delete opts.SID;
        delete val2.Ptg;
        Names.push(val2);
        break;
      case 1036:
        break;
      case 357:
      /* 'BrtSupSelf' */
      case 358:
      /* 'BrtSupSame' */
      case 355:
      /* 'BrtSupBookSrc' */
      case 667:
        if (!supbooks[0].length) supbooks[0] = [RT, val2];
        else supbooks.push([RT, val2]);
        supbooks[supbooks.length - 1].XTI = [];
        break;
      case 362:
        if (supbooks.length === 0) {
          supbooks[0] = [];
          supbooks[0].XTI = [];
        }
        supbooks[supbooks.length - 1].XTI = supbooks[supbooks.length - 1].XTI.concat(val2);
        supbooks.XTI = supbooks.XTI.concat(val2);
        break;
      case 361:
        break;
      case 2071:
      /* 'BrtAbsPath15' */
      case 158:
      /* 'BrtBookView' */
      case 143:
      /* 'BrtBeginBundleShs' */
      case 664:
      /* 'BrtBeginFnGroup' */
      case 353:
        break;
      /* case 'BrtModelTimeGroupingCalcCol' */
      case 3072:
      /* 'BrtUid' */
      case 3073:
      /* 'BrtRevisionPtr' */
      case 534:
      /* 'BrtBookProtection' */
      case 677:
      /* 'BrtBookProtectionIso' */
      case 157:
      /* 'BrtCalcProp' */
      case 610:
      /* 'BrtCrashRecErr' */
      case 2050:
      /* 'BrtDecoupledPivotCacheID' */
      case 155:
      /* 'BrtFileRecover' */
      case 548:
      /* 'BrtFileSharing' */
      case 676:
      /* 'BrtFileSharingIso' */
      case 128:
      /* 'BrtFileVersion' */
      case 665:
      /* 'BrtFnGroup' */
      case 2128:
      /* 'BrtModelRelationship' */
      case 2125:
      /* 'BrtModelTable' */
      case 549:
      /* 'BrtOleSize' */
      case 2053:
      /* 'BrtPivotTableRef' */
      case 596:
      /* 'BrtSmartTagType' */
      case 2076:
      /* 'BrtTableSlicerCacheID' */
      case 2075:
      /* 'BrtTableSlicerCacheIDs' */
      case 2082:
      /* 'BrtTimelineCachePivotCacheID' */
      case 397:
      /* 'BrtUserBookView' */
      case 154:
      /* 'BrtWbFactoid' */
      case 1117:
      /* 'BrtWbProp14' */
      case 553:
      /* 'BrtWebOpt' */
      case 2091:
        break;
      case 35:
        state.push(RT);
        pass = true;
        break;
      case 36:
        state.pop();
        pass = false;
        break;
      case 37:
        state.push(RT);
        pass = true;
        break;
      case 38:
        state.pop();
        pass = false;
        break;
      case 16:
        break;
      default:
        if (R3.T) {
        } else if (!pass || opts.WTF && state[state.length - 1] != 37 && state[state.length - 1] != 35) throw new Error("Unexpected record 0x" + RT.toString(16));
    }
  }, opts);
  parse_wb_defaults(wb);
  wb.Names = Names;
  wb.supbooks = supbooks;
  return wb;
}
function parse_wb(data, name, opts) {
  if (name.slice(-4) === ".bin") return parse_wb_bin(data, opts);
  return parse_wb_xml(data, opts);
}
function parse_ws(data, name, idx, opts, rels, wb, themes, styles2) {
  if (name.slice(-4) === ".bin") return parse_ws_bin(data, opts, idx, rels, wb, themes, styles2);
  return parse_ws_xml(data, opts, idx, rels, wb, themes, styles2);
}
function parse_cs(data, name, idx, opts, rels, wb, themes, styles2) {
  if (name.slice(-4) === ".bin") return parse_cs_bin(data, opts, idx, rels, wb, themes, styles2);
  return parse_cs_xml(data, opts, idx, rels, wb, themes, styles2);
}
function parse_ms(data, name, idx, opts, rels, wb, themes, styles2) {
  if (name.slice(-4) === ".bin") return parse_ms_bin(data, opts, idx, rels, wb, themes, styles2);
  return parse_ms_xml(data, opts, idx, rels, wb, themes, styles2);
}
function parse_ds(data, name, idx, opts, rels, wb, themes, styles2) {
  if (name.slice(-4) === ".bin") return parse_ds_bin(data, opts, idx, rels, wb, themes, styles2);
  return parse_ds_xml(data, opts, idx, rels, wb, themes, styles2);
}
function parse_sty(data, name, themes, opts) {
  if (name.slice(-4) === ".bin") return parse_sty_bin(data, themes, opts);
  return parse_sty_xml(data, themes, opts);
}
function parse_sst(data, name, opts) {
  if (name.slice(-4) === ".bin") return parse_sst_bin(data, opts);
  return parse_sst_xml(data, opts);
}
function parse_cmnt(data, name, opts) {
  if (name.slice(-4) === ".bin") return parse_comments_bin(data, opts);
  return parse_comments_xml(data, opts);
}
function parse_cc(data, name, opts) {
  if (name.slice(-4) === ".bin") return parse_cc_bin(data, name, opts);
  return parse_cc_xml(data, name, opts);
}
function parse_xlink(data, rel2, name, opts) {
  if (name.slice(-4) === ".bin") return parse_xlink_bin(data, rel2, name, opts);
  return parse_xlink_xml(data, rel2, name, opts);
}
function parse_xlmeta(data, name, opts) {
  if (name.slice(-4) === ".bin") return parse_xlmeta_bin(data, name, opts);
  return parse_xlmeta_xml(data, name, opts);
}
var attregexg2 = /\b((?:\w+:)?[\w]+)=((?:")([^"]*)(?:")|(?:')([^']*)(?:'))/g;
var attregex2 = /\b((?:\w+:)?[\w]+)=((?:")(?:[^"]*)(?:")|(?:')(?:[^']*)(?:'))/;
function xlml_parsexmltag(tag, skip_root) {
  var words = tag.split(/\s+/);
  var z3 = [];
  if (!skip_root) z3[0] = words[0];
  if (words.length === 1) return z3;
  var m4 = tag.match(attregexg2), y4, j3, w3, i7;
  if (m4) for (i7 = 0; i7 != m4.length; ++i7) {
    y4 = m4[i7].match(attregex2);
    if ((j3 = y4[1].indexOf(":")) === -1) z3[y4[1]] = y4[2].slice(1, y4[2].length - 1);
    else {
      if (y4[1].slice(0, 6) === "xmlns:") w3 = "xmlns" + y4[1].slice(6);
      else w3 = y4[1].slice(j3 + 1);
      z3[w3] = y4[2].slice(1, y4[2].length - 1);
    }
  }
  return z3;
}
function xlml_parsexmltagobj(tag) {
  var words = tag.split(/\s+/);
  var z3 = {};
  if (words.length === 1) return z3;
  var m4 = tag.match(attregexg2), y4, j3, w3, i7;
  if (m4) for (i7 = 0; i7 != m4.length; ++i7) {
    y4 = m4[i7].match(attregex2);
    if ((j3 = y4[1].indexOf(":")) === -1) z3[y4[1]] = y4[2].slice(1, y4[2].length - 1);
    else {
      if (y4[1].slice(0, 6) === "xmlns:") w3 = "xmlns" + y4[1].slice(6);
      else w3 = y4[1].slice(j3 + 1);
      z3[w3] = y4[2].slice(1, y4[2].length - 1);
    }
  }
  return z3;
}
var XLMLFormatMap;
function xlml_format(format, value, date1904) {
  var fmt = XLMLFormatMap[format] || unescapexml(format);
  if (fmt === "General") return SSF_general(value);
  return SSF_format(fmt, value, { date1904: !!date1904 });
}
function xlml_set_custprop(Custprops, key, cp, val2) {
  var oval = val2;
  switch ((cp[0].match(/dt:dt="([\w.]+)"/) || ["", ""])[1]) {
    case "boolean":
      oval = parsexmlbool(val2);
      break;
    case "i2":
    case "int":
      oval = parseInt(val2, 10);
      break;
    case "r4":
    case "float":
      oval = parseFloat(val2);
      break;
    case "date":
    case "dateTime.tz":
      oval = parseDate(val2);
      break;
    case "i8":
    case "string":
    case "fixed":
    case "uuid":
    case "bin.base64":
      break;
    default:
      throw new Error("bad custprop:" + cp[0]);
  }
  Custprops[unescapexml(key)] = oval;
}
function safe_format_xlml(cell, nf, o9, date1904) {
  if (cell.t === "z") return;
  if (!o9 || o9.cellText !== false) try {
    if (cell.t === "e") {
      cell.w = cell.w || BErr[cell.v];
    } else if (nf === "General") {
      if (cell.t === "n") {
        if ((cell.v | 0) === cell.v) cell.w = cell.v.toString(10);
        else cell.w = SSF_general_num(cell.v);
      } else cell.w = SSF_general(cell.v);
    } else cell.w = xlml_format(nf || "General", cell.v, date1904);
  } catch (e9) {
    if (o9.WTF) throw e9;
  }
  try {
    var z3 = XLMLFormatMap[nf] || nf || "General";
    if (o9.cellNF) cell.z = z3;
    if (o9.cellDates && cell.t == "n" && fmt_is_date(z3)) {
      var _d = SSF_parse_date_code(cell.v + (date1904 ? 1462 : 0));
      if (_d) {
        cell.t = "d";
        cell.v = new Date(Date.UTC(_d.y, _d.m - 1, _d.d, _d.H, _d.M, _d.S, _d.u));
      }
    }
  } catch (e9) {
    if (o9.WTF) throw e9;
  }
}
function process_style_xlml(styles2, stag, opts) {
  if (opts.cellStyles) {
    if (stag.Interior) {
      var I3 = stag.Interior;
      if (I3.Pattern) I3.patternType = XLMLPatternTypeMap[I3.Pattern] || I3.Pattern;
    }
  }
  styles2[stag.ID] = stag;
}
function parse_xlml_data(xml2, ss, data, cell, base, styles2, csty, row, arrayf, o9, date1904) {
  var nf = "General", sid = cell.StyleID, S5 = {};
  o9 = o9 || {};
  var interiors = [];
  var i7 = 0;
  if (sid === void 0 && row) sid = row.StyleID;
  if (sid === void 0 && csty) sid = csty.StyleID;
  while (styles2[sid] !== void 0) {
    var ssid = styles2[sid];
    if (ssid.nf) nf = ssid.nf;
    if (ssid.Interior) interiors.push(ssid.Interior);
    if (!ssid.Parent) break;
    sid = ssid.Parent;
  }
  switch (data.Type) {
    case "Boolean":
      cell.t = "b";
      cell.v = parsexmlbool(xml2);
      break;
    case "String":
      cell.t = "s";
      cell.r = xlml_fixstr(unescapexml(xml2));
      cell.v = xml2.indexOf("<") > -1 ? unescapexml(ss || xml2).replace(/<[^<>]*>/g, "") : cell.r;
      break;
    case "DateTime":
      if (xml2.slice(-1) != "Z") xml2 += "Z";
      cell.v = datenum(parseDate(xml2, date1904), date1904);
      if (cell.v !== cell.v) cell.v = unescapexml(xml2);
      if (!nf || nf == "General") nf = "yyyy-mm-dd";
    /* falls through */
    case "Number":
      if (cell.v === void 0) cell.v = +xml2;
      if (!cell.t) cell.t = "n";
      break;
    case "Error":
      cell.t = "e";
      cell.v = RBErr[xml2];
      if (o9.cellText !== false) cell.w = xml2;
      break;
    default:
      if (xml2 == "" && ss == "") {
        cell.t = "z";
      } else {
        cell.t = "s";
        cell.v = xlml_fixstr(ss || xml2);
      }
      break;
  }
  safe_format_xlml(cell, nf, o9, date1904);
  if (o9.cellFormula !== false) {
    if (cell.Formula) {
      var fstr = unescapexml(cell.Formula);
      if (fstr.charCodeAt(0) == 61) fstr = fstr.slice(1);
      cell.f = rc_to_a1(fstr, base);
      delete cell.Formula;
      if (cell.ArrayRange == "RC") cell.F = rc_to_a1("RC:RC", base);
      else if (cell.ArrayRange) {
        cell.F = rc_to_a1(cell.ArrayRange, base);
        arrayf.push([safe_decode_range(cell.F), cell.F]);
      }
    } else {
      for (i7 = 0; i7 < arrayf.length; ++i7)
        if (base.r >= arrayf[i7][0].s.r && base.r <= arrayf[i7][0].e.r) {
          if (base.c >= arrayf[i7][0].s.c && base.c <= arrayf[i7][0].e.c)
            cell.F = arrayf[i7][1];
        }
    }
  }
  if (o9.cellStyles) {
    interiors.forEach(function(x2) {
      if (!S5.patternType && x2.patternType) S5.patternType = x2.patternType;
    });
    cell.s = S5;
  }
  if (cell.StyleID !== void 0) cell.ixfe = cell.StyleID;
}
function xlml_prefix_dname(dname) {
  return XLSLblBuiltIn.indexOf("_xlnm." + dname) > -1 ? "_xlnm." + dname : dname;
}
function xlml_clean_comment(comment) {
  comment.t = comment.v || "";
  comment.t = comment.t.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
  comment.v = comment.w = comment.ixfe = void 0;
}
function parse_xlml_xml(d4, _opts) {
  var opts = _opts || {};
  make_ssf();
  var str2 = debom(xlml_normalize(d4));
  if (opts.type == "binary" || opts.type == "array" || opts.type == "base64") {
    if (typeof $cptable !== "undefined") str2 = $cptable.utils.decode(65001, char_codes(str2));
    else str2 = utf8read(str2);
  }
  var opening = str2.slice(0, 1024).toLowerCase(), ishtml = false;
  opening = opening.replace(/".*?"/g, "");
  if ((opening.indexOf(">") & 1023) > Math.min(opening.indexOf(",") & 1023, opening.indexOf(";") & 1023)) {
    var _o = dup(opts);
    _o.type = "string";
    return PRN.to_workbook(str2, _o);
  }
  if (opening.indexOf("<?xml") == -1) ["html", "table", "head", "meta", "script", "style", "div"].forEach(function(tag) {
    if (opening.indexOf("<" + tag) >= 0) ishtml = true;
  });
  if (ishtml) return html_to_workbook(str2, opts);
  XLMLFormatMap = {
    "General Number": "General",
    "General Date": table_fmt[22],
    "Long Date": "dddd, mmmm dd, yyyy",
    "Medium Date": table_fmt[15],
    "Short Date": table_fmt[14],
    "Long Time": table_fmt[19],
    "Medium Time": table_fmt[18],
    "Short Time": table_fmt[20],
    "Currency": '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)',
    "Fixed": table_fmt[2],
    "Standard": table_fmt[4],
    "Percent": table_fmt[10],
    "Scientific": table_fmt[11],
    "Yes/No": '"Yes";"Yes";"No";@',
    "True/False": '"True";"True";"False";@',
    "On/Off": '"Yes";"Yes";"No";@'
  };
  var Rn;
  var state = [], tmp;
  if (DENSE != null && opts.dense == null) opts.dense = DENSE;
  var sheets = {}, sheetnames = [], cursheet = {}, sheetname = "";
  if (opts.dense) cursheet["!data"] = [];
  var cell = {}, row = {};
  var dtag = xlml_parsexmltag('<Data ss:Type="String">'), didx = 0;
  var c6 = 0, r8 = 0;
  var refguess = { s: { r: 2e6, c: 2e6 }, e: { r: 0, c: 0 } };
  var styles2 = {}, stag = {};
  var ss = "", fidx = 0;
  var merges = [];
  var Props = {}, Custprops = {}, pidx = 0, cp = [];
  var comments = [], comment = {};
  var cstys = [], csty, seencol = false;
  var arrayf = [];
  var rowinfo = [], rowobj = {}, cc = 0, rr = 0;
  var Workbook = { Sheets: [], WBProps: { date1904: false } }, wsprops = {};
  xlmlregex.lastIndex = 0;
  str2 = str_remove_ng(str2, "<!--", "-->");
  var raw_Rn3 = "";
  while (Rn = xlmlregex.exec(str2)) switch (Rn[3] = (raw_Rn3 = Rn[3]).toLowerCase()) {
    case "data":
      if (raw_Rn3 == "data") {
        if (Rn[1] === "/") {
          if ((tmp = state.pop())[0] !== Rn[3]) throw new Error("Bad state: " + tmp.join("|"));
        } else if (Rn[0].charAt(Rn[0].length - 2) !== "/") state.push([Rn[3], true]);
        break;
      }
      if (state[state.length - 1][1]) break;
      if (Rn[1] === "/") parse_xlml_data(str2.slice(didx, Rn.index), ss, dtag, state[state.length - 1][0] == /*"Comment"*/
      "comment" ? comment : cell, { c: c6, r: r8 }, styles2, cstys[c6], row, arrayf, opts, Workbook.WBProps.date1904);
      else {
        ss = "";
        dtag = xlml_parsexmltag(Rn[0]);
        didx = Rn.index + Rn[0].length;
      }
      break;
    case "cell":
      if (Rn[1] === "/") {
        if (comments.length > 0) cell.c = comments;
        if ((!opts.sheetRows || opts.sheetRows > r8) && cell.v !== void 0) {
          if (opts.dense) {
            if (!cursheet["!data"][r8]) cursheet["!data"][r8] = [];
            cursheet["!data"][r8][c6] = cell;
          } else cursheet[encode_col(c6) + encode_row(r8)] = cell;
        }
        if (cell.HRef) {
          cell.l = { Target: unescapexml(cell.HRef) };
          if (cell.HRefScreenTip) cell.l.Tooltip = cell.HRefScreenTip;
          delete cell.HRef;
          delete cell.HRefScreenTip;
        }
        if (cell.MergeAcross || cell.MergeDown) {
          cc = c6 + (parseInt(cell.MergeAcross, 10) | 0);
          rr = r8 + (parseInt(cell.MergeDown, 10) | 0);
          if (cc > c6 || rr > r8) merges.push({ s: { c: c6, r: r8 }, e: { c: cc, r: rr } });
        }
        if (!opts.sheetStubs) {
          if (cell.MergeAcross) c6 = cc + 1;
          else ++c6;
        } else if (cell.MergeAcross || cell.MergeDown) {
          for (var cma = c6; cma <= cc; ++cma) {
            for (var cmd = r8; cmd <= rr; ++cmd) {
              if (cma > c6 || cmd > r8) {
                if (opts.dense) {
                  if (!cursheet["!data"][cmd]) cursheet["!data"][cmd] = [];
                  cursheet["!data"][cmd][cma] = { t: "z" };
                } else cursheet[encode_col(cma) + encode_row(cmd)] = { t: "z" };
              }
            }
          }
          c6 = cc + 1;
        } else ++c6;
      } else {
        cell = xlml_parsexmltagobj(Rn[0]);
        if (cell.Index) c6 = +cell.Index - 1;
        if (c6 < refguess.s.c) refguess.s.c = c6;
        if (c6 > refguess.e.c) refguess.e.c = c6;
        if (Rn[0].slice(-2) === "/>") ++c6;
        comments = [];
      }
      break;
    case "row":
      if (Rn[1] === "/" || Rn[0].slice(-2) === "/>") {
        if (r8 < refguess.s.r) refguess.s.r = r8;
        if (r8 > refguess.e.r) refguess.e.r = r8;
        if (Rn[0].slice(-2) === "/>") {
          row = xlml_parsexmltag(Rn[0]);
          if (row.Index) r8 = +row.Index - 1;
        }
        c6 = 0;
        ++r8;
      } else {
        row = xlml_parsexmltag(Rn[0]);
        if (row.Index) r8 = +row.Index - 1;
        rowobj = {};
        if (row.AutoFitHeight == "0" || row.Height) {
          rowobj.hpx = parseInt(row.Height, 10);
          rowobj.hpt = px2pt(rowobj.hpx);
          rowinfo[r8] = rowobj;
        }
        if (row.Hidden == "1") {
          rowobj.hidden = true;
          rowinfo[r8] = rowobj;
        }
      }
      break;
    case "worksheet":
      if (Rn[1] === "/") {
        if ((tmp = state.pop())[0] !== Rn[3]) throw new Error("Bad state: " + tmp.join("|"));
        sheetnames.push(sheetname);
        if (refguess.s.r <= refguess.e.r && refguess.s.c <= refguess.e.c) {
          cursheet["!ref"] = encode_range(refguess);
          if (opts.sheetRows && opts.sheetRows <= refguess.e.r) {
            cursheet["!fullref"] = cursheet["!ref"];
            refguess.e.r = opts.sheetRows - 1;
            cursheet["!ref"] = encode_range(refguess);
          }
        }
        if (merges.length) cursheet["!merges"] = merges;
        if (cstys.length > 0) cursheet["!cols"] = cstys;
        if (rowinfo.length > 0) cursheet["!rows"] = rowinfo;
        sheets[sheetname] = cursheet;
      } else {
        refguess = { s: { r: 2e6, c: 2e6 }, e: { r: 0, c: 0 } };
        r8 = c6 = 0;
        state.push([Rn[3], false]);
        tmp = xlml_parsexmltag(Rn[0]);
        sheetname = unescapexml(tmp.Name);
        cursheet = {};
        if (opts.dense) cursheet["!data"] = [];
        merges = [];
        arrayf = [];
        rowinfo = [];
        wsprops = { name: sheetname, Hidden: 0 };
        Workbook.Sheets.push(wsprops);
      }
      break;
    case "table":
      if (Rn[1] === "/") {
        if ((tmp = state.pop())[0] !== Rn[3]) throw new Error("Bad state: " + tmp.join("|"));
      } else if (Rn[0].slice(-2) == "/>") break;
      else {
        state.push([Rn[3], false]);
        cstys = [];
        seencol = false;
      }
      break;
    case "style":
      if (Rn[1] === "/") process_style_xlml(styles2, stag, opts);
      else stag = xlml_parsexmltag(Rn[0]);
      break;
    case "numberformat":
      stag.nf = unescapexml(xlml_parsexmltag(Rn[0]).Format || "General");
      if (XLMLFormatMap[stag.nf]) stag.nf = XLMLFormatMap[stag.nf];
      for (var ssfidx = 0; ssfidx != 392; ++ssfidx) if (table_fmt[ssfidx] == stag.nf) break;
      if (ssfidx == 392) {
        for (ssfidx = 57; ssfidx != 392; ++ssfidx) if (table_fmt[ssfidx] == null) {
          SSF__load(stag.nf, ssfidx);
          break;
        }
      }
      break;
    case "column":
      if (state[state.length - 1][0] !== /*'Table'*/
      "table") break;
      if (Rn[1] === "/") break;
      csty = xlml_parsexmltag(Rn[0]);
      if (csty.Hidden) {
        csty.hidden = true;
        delete csty.Hidden;
      }
      if (csty.Width) csty.wpx = parseInt(csty.Width, 10);
      if (!seencol && csty.wpx > 10) {
        seencol = true;
        MDW = DEF_MDW;
        for (var _col = 0; _col < cstys.length; ++_col) if (cstys[_col]) process_col(cstys[_col]);
      }
      if (seencol) process_col(csty);
      cstys[csty.Index - 1 || cstys.length] = csty;
      for (var i7 = 0; i7 < +csty.Span; ++i7) cstys[cstys.length] = dup(csty);
      break;
    case "namedrange":
      if (Rn[1] === "/") break;
      if (!Workbook.Names) Workbook.Names = [];
      var _NamedRange = parsexmltag(Rn[0]);
      var _DefinedName = {
        Name: xlml_prefix_dname(_NamedRange.Name),
        Ref: rc_to_a1(_NamedRange.RefersTo.slice(1), { r: 0, c: 0 })
      };
      if (Workbook.Sheets.length > 0) _DefinedName.Sheet = Workbook.Sheets.length - 1;
      Workbook.Names.push(_DefinedName);
      break;
    case "namedcell":
      break;
    case "b":
      break;
    case "i":
      break;
    case "u":
      break;
    case "s":
      break;
    case "em":
      break;
    case "h2":
      break;
    case "h3":
      break;
    case "sub":
      break;
    case "sup":
      break;
    case "span":
      break;
    case "alignment":
      break;
    case "borders":
      break;
    case "border":
      break;
    case "font":
      if (Rn[0].slice(-2) === "/>") break;
      else if (Rn[1] === "/") ss += str2.slice(fidx, Rn.index);
      else fidx = Rn.index + Rn[0].length;
      break;
    case "interior":
      if (!opts.cellStyles) break;
      stag.Interior = xlml_parsexmltag(Rn[0]);
      break;
    case "protection":
      break;
    case "author":
    case "title":
    case "description":
    case "created":
    case "keywords":
    case "subject":
    case "category":
    case "company":
    case "lastauthor":
    case "lastsaved":
    case "lastprinted":
    case "version":
    case "revision":
    case "totaltime":
    case "hyperlinkbase":
    case "manager":
    case "contentstatus":
    case "identifier":
    case "language":
    case "appname":
      if (Rn[0].slice(-2) === "/>") break;
      else if (Rn[1] === "/") xlml_set_prop(Props, raw_Rn3, str2.slice(pidx, Rn.index));
      else pidx = Rn.index + Rn[0].length;
      break;
    case "paragraphs":
      break;
    case "styles":
    case "workbook":
      if (Rn[1] === "/") {
        if ((tmp = state.pop())[0] !== Rn[3]) throw new Error("Bad state: " + tmp.join("|"));
      } else state.push([Rn[3], false]);
      break;
    case "comment":
      if (Rn[1] === "/") {
        if ((tmp = state.pop())[0] !== Rn[3]) throw new Error("Bad state: " + tmp.join("|"));
        xlml_clean_comment(comment);
        comments.push(comment);
      } else {
        state.push([Rn[3], false]);
        tmp = xlml_parsexmltag(Rn[0]);
        if (!parsexmlbool(tmp["ShowAlways"] || "0")) comments.hidden = true;
        comment = { a: tmp.Author };
      }
      break;
    case "autofilter":
      if (Rn[1] === "/") {
        if ((tmp = state.pop())[0] !== Rn[3]) throw new Error("Bad state: " + tmp.join("|"));
      } else if (Rn[0].charAt(Rn[0].length - 2) !== "/") {
        var AutoFilter = xlml_parsexmltag(Rn[0]);
        cursheet["!autofilter"] = { ref: rc_to_a1(AutoFilter.Range).replace(/\$/g, "") };
        state.push([Rn[3], true]);
      }
      break;
    case "name":
      break;
    case "datavalidation":
      if (Rn[1] === "/") {
        if ((tmp = state.pop())[0] !== Rn[3]) throw new Error("Bad state: " + tmp.join("|"));
      } else {
        if (Rn[0].charAt(Rn[0].length - 2) !== "/") state.push([Rn[3], true]);
      }
      break;
    case "pixelsperinch":
      break;
    case "componentoptions":
    case "documentproperties":
    case "customdocumentproperties":
    case "officedocumentsettings":
    case "pivottable":
    case "pivotcache":
    case "names":
    case "mapinfo":
    case "pagebreaks":
    case "querytable":
    case "sorting":
    case "schema":
    //case 'data' /*case 'data'*/:
    case "conditionalformatting":
    case "smarttagtype":
    case "smarttags":
    case "excelworkbook":
    case "workbookoptions":
    case "worksheetoptions":
      if (Rn[1] === "/") {
        if ((tmp = state.pop())[0] !== Rn[3]) throw new Error("Bad state: " + tmp.join("|"));
      } else if (Rn[0].charAt(Rn[0].length - 2) !== "/") state.push([Rn[3], true]);
      break;
    case "null":
      break;
    default:
      if (state.length == 0 && Rn[3] == "document") return parse_fods(str2, opts);
      if (state.length == 0 && Rn[3] == "uof") return parse_fods(str2, opts);
      var seen = true;
      switch (state[state.length - 1][0]) {
        /* OfficeDocumentSettings */
        case "officedocumentsettings":
          switch (Rn[3]) {
            case "allowpng":
              break;
            case "removepersonalinformation":
              break;
            case "downloadcomponents":
              break;
            case "locationofcomponents":
              break;
            case "colors":
              break;
            case "color":
              break;
            case "index":
              break;
            case "rgb":
              break;
            case "targetscreensize":
              break;
            case "readonlyrecommended":
              break;
            default:
              seen = false;
          }
          break;
        /* ComponentOptions */
        case "componentoptions":
          switch (Rn[3]) {
            case "toolbar":
              break;
            case "hideofficelogo":
              break;
            case "spreadsheetautofit":
              break;
            case "label":
              break;
            case "caption":
              break;
            case "maxheight":
              break;
            case "maxwidth":
              break;
            case "nextsheetnumber":
              break;
            default:
              seen = false;
          }
          break;
        /* ExcelWorkbook */
        case "excelworkbook":
          switch (Rn[3]) {
            case "date1904":
              Workbook.WBProps.date1904 = true;
              break;
            case "hidehorizontalscrollbar":
              break;
            case "hideverticalscrollbar":
              break;
            case "hideworkbooktabs":
              break;
            case "windowheight":
              break;
            case "windowwidth":
              break;
            case "windowtopx":
              break;
            case "windowtopy":
              break;
            case "tabratio":
              break;
            case "protectstructure":
              break;
            case "protectwindow":
              break;
            case "protectwindows":
              break;
            case "activesheet":
              break;
            case "displayinknotes":
              break;
            case "firstvisiblesheet":
              break;
            case "supbook":
              break;
            case "sheetname":
              break;
            case "sheetindex":
              break;
            case "sheetindexfirst":
              break;
            case "sheetindexlast":
              break;
            case "dll":
              break;
            case "acceptlabelsinformulas":
              break;
            case "donotsavelinkvalues":
              break;
            case "iteration":
              break;
            case "maxiterations":
              break;
            case "maxchange":
              break;
            case "path":
              break;
            case "xct":
              break;
            case "count":
              break;
            case "selectedsheets":
              break;
            case "calculation":
              break;
            case "uncalced":
              break;
            case "startupprompt":
              break;
            case "crn":
              break;
            case "externname":
              break;
            case "formula":
              break;
            case "colfirst":
              break;
            case "collast":
              break;
            case "wantadvise":
              break;
            case "boolean":
              break;
            case "error":
              break;
            case "text":
              break;
            case "ole":
              break;
            case "noautorecover":
              break;
            case "publishobjects":
              break;
            case "donotcalculatebeforesave":
              break;
            case "number":
              break;
            case "refmoder1c1":
              break;
            case "embedsavesmarttags":
              break;
            default:
              seen = false;
          }
          break;
        /* WorkbookOptions */
        case "workbookoptions":
          switch (Rn[3]) {
            case "owcversion":
              break;
            case "height":
              break;
            case "width":
              break;
            default:
              seen = false;
          }
          break;
        /* WorksheetOptions */
        case "worksheetoptions":
          switch (Rn[3]) {
            case "visible":
              if (Rn[0].slice(-2) === "/>") {
              } else if (Rn[1] === "/") switch (str2.slice(pidx, Rn.index)) {
                case "SheetHidden":
                  wsprops.Hidden = 1;
                  break;
                case "SheetVeryHidden":
                  wsprops.Hidden = 2;
                  break;
              }
              else pidx = Rn.index + Rn[0].length;
              break;
            case "header":
              if (!cursheet["!margins"]) default_margins(cursheet["!margins"] = {}, "xlml");
              if (!isNaN(+parsexmltag(Rn[0]).Margin)) cursheet["!margins"].header = +parsexmltag(Rn[0]).Margin;
              break;
            case "footer":
              if (!cursheet["!margins"]) default_margins(cursheet["!margins"] = {}, "xlml");
              if (!isNaN(+parsexmltag(Rn[0]).Margin)) cursheet["!margins"].footer = +parsexmltag(Rn[0]).Margin;
              break;
            case "pagemargins":
              var pagemargins = parsexmltag(Rn[0]);
              if (!cursheet["!margins"]) default_margins(cursheet["!margins"] = {}, "xlml");
              if (!isNaN(+pagemargins.Top)) cursheet["!margins"].top = +pagemargins.Top;
              if (!isNaN(+pagemargins.Left)) cursheet["!margins"].left = +pagemargins.Left;
              if (!isNaN(+pagemargins.Right)) cursheet["!margins"].right = +pagemargins.Right;
              if (!isNaN(+pagemargins.Bottom)) cursheet["!margins"].bottom = +pagemargins.Bottom;
              break;
            case "displayrighttoleft":
              if (!Workbook.Views) Workbook.Views = [];
              if (!Workbook.Views[0]) Workbook.Views[0] = {};
              Workbook.Views[0].RTL = true;
              break;
            case "freezepanes":
              break;
            case "frozennosplit":
              break;
            case "splithorizontal":
            case "splitvertical":
              break;
            case "donotdisplaygridlines":
              break;
            case "activerow":
              break;
            case "activecol":
              break;
            case "toprowbottompane":
              break;
            case "leftcolumnrightpane":
              break;
            case "unsynced":
              break;
            case "print":
              break;
            case "printerrors":
              break;
            case "panes":
              break;
            case "scale":
              break;
            case "pane":
              break;
            case "number":
              break;
            case "layout":
              break;
            case "pagesetup":
              break;
            case "selected":
              break;
            case "protectobjects":
              break;
            case "enableselection":
              break;
            case "protectscenarios":
              break;
            case "validprinterinfo":
              break;
            case "horizontalresolution":
              break;
            case "verticalresolution":
              break;
            case "numberofcopies":
              break;
            case "activepane":
              break;
            case "toprowvisible":
              break;
            case "leftcolumnvisible":
              break;
            case "fittopage":
              break;
            case "rangeselection":
              break;
            case "papersizeindex":
              break;
            case "pagelayoutzoom":
              break;
            case "pagebreakzoom":
              break;
            case "filteron":
              break;
            case "fitwidth":
              break;
            case "fitheight":
              break;
            case "commentslayout":
              break;
            case "zoom":
              break;
            case "lefttoright":
              break;
            case "gridlines":
              break;
            case "allowsort":
              break;
            case "allowfilter":
              break;
            case "allowinsertrows":
              break;
            case "allowdeleterows":
              break;
            case "allowinsertcols":
              break;
            case "allowdeletecols":
              break;
            case "allowinserthyperlinks":
              break;
            case "allowformatcells":
              break;
            case "allowsizecols":
              break;
            case "allowsizerows":
              break;
            case "nosummaryrowsbelowdetail":
              if (!cursheet["!outline"]) cursheet["!outline"] = {};
              cursheet["!outline"].above = true;
              break;
            case "tabcolorindex":
              break;
            case "donotdisplayheadings":
              break;
            case "showpagelayoutzoom":
              break;
            case "nosummarycolumnsrightdetail":
              if (!cursheet["!outline"]) cursheet["!outline"] = {};
              cursheet["!outline"].left = true;
              break;
            case "blackandwhite":
              break;
            case "donotdisplayzeros":
              break;
            case "displaypagebreak":
              break;
            case "rowcolheadings":
              break;
            case "donotdisplayoutline":
              break;
            case "noorientation":
              break;
            case "allowusepivottables":
              break;
            case "zeroheight":
              break;
            case "viewablerange":
              break;
            case "selection":
              break;
            case "protectcontents":
              break;
            default:
              seen = false;
          }
          break;
        /* PivotTable */
        case "pivottable":
        case "pivotcache":
          switch (Rn[3]) {
            case "immediateitemsondrop":
              break;
            case "showpagemultipleitemlabel":
              break;
            case "compactrowindent":
              break;
            case "location":
              break;
            case "pivotfield":
              break;
            case "orientation":
              break;
            case "layoutform":
              break;
            case "layoutsubtotallocation":
              break;
            case "layoutcompactrow":
              break;
            case "position":
              break;
            case "pivotitem":
              break;
            case "datatype":
              break;
            case "datafield":
              break;
            case "sourcename":
              break;
            case "parentfield":
              break;
            case "ptlineitems":
              break;
            case "ptlineitem":
              break;
            case "countofsameitems":
              break;
            case "item":
              break;
            case "itemtype":
              break;
            case "ptsource":
              break;
            case "cacheindex":
              break;
            case "consolidationreference":
              break;
            case "filename":
              break;
            case "reference":
              break;
            case "nocolumngrand":
              break;
            case "norowgrand":
              break;
            case "blanklineafteritems":
              break;
            case "hidden":
              break;
            case "subtotal":
              break;
            case "basefield":
              break;
            case "mapchilditems":
              break;
            case "function":
              break;
            case "refreshonfileopen":
              break;
            case "printsettitles":
              break;
            case "mergelabels":
              break;
            case "defaultversion":
              break;
            case "refreshname":
              break;
            case "refreshdate":
              break;
            case "refreshdatecopy":
              break;
            case "versionlastrefresh":
              break;
            case "versionlastupdate":
              break;
            case "versionupdateablemin":
              break;
            case "versionrefreshablemin":
              break;
            case "calculation":
              break;
            default:
              seen = false;
          }
          break;
        /* PageBreaks */
        case "pagebreaks":
          switch (Rn[3]) {
            case "colbreaks":
              break;
            case "colbreak":
              break;
            case "rowbreaks":
              break;
            case "rowbreak":
              break;
            case "colstart":
              break;
            case "colend":
              break;
            case "rowend":
              break;
            default:
              seen = false;
          }
          break;
        /* AutoFilter */
        case "autofilter":
          switch (Rn[3]) {
            case "autofiltercolumn":
              break;
            case "autofiltercondition":
              break;
            case "autofilterand":
              break;
            case "autofilteror":
              break;
            default:
              seen = false;
          }
          break;
        /* QueryTable */
        case "querytable":
          switch (Rn[3]) {
            case "id":
              break;
            case "autoformatfont":
              break;
            case "autoformatpattern":
              break;
            case "querysource":
              break;
            case "querytype":
              break;
            case "enableredirections":
              break;
            case "refreshedinxl9":
              break;
            case "urlstring":
              break;
            case "htmltables":
              break;
            case "connection":
              break;
            case "commandtext":
              break;
            case "refreshinfo":
              break;
            case "notitles":
              break;
            case "nextid":
              break;
            case "columninfo":
              break;
            case "overwritecells":
              break;
            case "donotpromptforfile":
              break;
            case "textwizardsettings":
              break;
            case "source":
              break;
            case "number":
              break;
            case "decimal":
              break;
            case "thousandseparator":
              break;
            case "trailingminusnumbers":
              break;
            case "formatsettings":
              break;
            case "fieldtype":
              break;
            case "delimiters":
              break;
            case "tab":
              break;
            case "comma":
              break;
            case "autoformatname":
              break;
            case "versionlastedit":
              break;
            case "versionlastrefresh":
              break;
            default:
              seen = false;
          }
          break;
        case "datavalidation":
          switch (Rn[3]) {
            case "range":
              break;
            case "type":
              break;
            case "min":
              break;
            case "max":
              break;
            case "sort":
              break;
            case "descending":
              break;
            case "order":
              break;
            case "casesensitive":
              break;
            case "value":
              break;
            case "errorstyle":
              break;
            case "errormessage":
              break;
            case "errortitle":
              break;
            case "inputmessage":
              break;
            case "inputtitle":
              break;
            case "combohide":
              break;
            case "inputhide":
              break;
            case "condition":
              break;
            case "qualifier":
              break;
            case "useblank":
              break;
            case "value1":
              break;
            case "value2":
              break;
            case "format":
              break;
            case "cellrangelist":
              break;
            default:
              seen = false;
          }
          break;
        case "sorting":
        case "conditionalformatting":
          switch (Rn[3]) {
            case "range":
              break;
            case "type":
              break;
            case "min":
              break;
            case "max":
              break;
            case "sort":
              break;
            case "descending":
              break;
            case "order":
              break;
            case "casesensitive":
              break;
            case "value":
              break;
            case "errorstyle":
              break;
            case "errormessage":
              break;
            case "errortitle":
              break;
            case "cellrangelist":
              break;
            case "inputmessage":
              break;
            case "inputtitle":
              break;
            case "combohide":
              break;
            case "inputhide":
              break;
            case "condition":
              break;
            case "qualifier":
              break;
            case "useblank":
              break;
            case "value1":
              break;
            case "value2":
              break;
            case "format":
              break;
            default:
              seen = false;
          }
          break;
        /* MapInfo (schema) */
        case "mapinfo":
        case "schema":
        case "data":
          switch (Rn[3]) {
            case "map":
              break;
            case "entry":
              break;
            case "range":
              break;
            case "xpath":
              break;
            case "field":
              break;
            case "xsdtype":
              break;
            case "filteron":
              break;
            case "aggregate":
              break;
            case "elementtype":
              break;
            case "attributetype":
              break;
            /* These are from xsd (XML Schema Definition) */
            case "schema":
            case "element":
            case "complextype":
            case "datatype":
            case "all":
            case "attribute":
            case "extends":
              break;
            case "row":
              break;
            default:
              seen = false;
          }
          break;
        /* SmartTags (can be anything) */
        case "smarttags":
          break;
        default:
          seen = false;
          break;
      }
      if (seen) break;
      if (Rn[3].match(/!\[CDATA/)) break;
      if (!state[state.length - 1][1]) throw "Unrecognized tag: " + Rn[3] + "|" + state.join("|");
      if (state[state.length - 1][0] === /*'CustomDocumentProperties'*/
      "customdocumentproperties") {
        if (Rn[0].slice(-2) === "/>") break;
        else if (Rn[1] === "/") xlml_set_custprop(Custprops, raw_Rn3, cp, str2.slice(pidx, Rn.index));
        else {
          cp = Rn;
          pidx = Rn.index + Rn[0].length;
        }
        break;
      }
      if (opts.WTF) throw "Unrecognized tag: " + Rn[3] + "|" + state.join("|");
  }
  var out = {};
  if (!opts.bookSheets && !opts.bookProps) out.Sheets = sheets;
  out.SheetNames = sheetnames;
  out.Workbook = Workbook;
  out.SSF = dup(table_fmt);
  out.Props = Props;
  out.Custprops = Custprops;
  out.bookType = "xlml";
  return out;
}
function parse_xlml(data, opts) {
  fix_read_opts(opts = opts || {});
  switch (opts.type || "base64") {
    case "base64":
      return parse_xlml_xml(Base64_decode(data), opts);
    case "binary":
    case "buffer":
    case "file":
      return parse_xlml_xml(data, opts);
    case "array":
      return parse_xlml_xml(a2s(data), opts);
  }
}
function parse_compobj(obj) {
  var v4 = {};
  var o9 = obj.content;
  o9.l = 28;
  v4.AnsiUserType = o9.read_shift(0, "lpstr-ansi");
  v4.AnsiClipboardFormat = parse_ClipboardFormatOrAnsiString(o9);
  if (o9.length - o9.l <= 4) return v4;
  var m4 = o9.read_shift(4);
  if (m4 == 0 || m4 > 40) return v4;
  o9.l -= 4;
  v4.Reserved1 = o9.read_shift(0, "lpstr-ansi");
  if (o9.length - o9.l <= 4) return v4;
  m4 = o9.read_shift(4);
  if (m4 !== 1907505652) return v4;
  v4.UnicodeClipboardFormat = parse_ClipboardFormatOrUnicodeString(o9);
  m4 = o9.read_shift(4);
  if (m4 == 0 || m4 > 40) return v4;
  o9.l -= 4;
  v4.Reserved2 = o9.read_shift(0, "lpwstr");
}
var CONTINUE_RT = [60, 1084, 2066, 2165, 2175];
function slurp(RecordType, R3, blob, length, opts) {
  var l5 = length;
  var bufs = [];
  var d4 = blob.slice(blob.l, blob.l + l5);
  if (opts && opts.enc && opts.enc.insitu && d4.length > 0) switch (RecordType) {
    case 9:
    case 521:
    case 1033:
    case 2057:
    case 47:
    case 405:
    case 225:
    case 406:
    case 312:
    case 404:
    case 10:
      break;
    case 133:
      break;
    default:
      opts.enc.insitu(d4);
  }
  bufs.push(d4);
  blob.l += l5;
  var nextrt = __readUInt16LE(blob, blob.l), next = XLSRecordEnum[nextrt];
  var start = 0;
  while (next != null && CONTINUE_RT.indexOf(nextrt) > -1) {
    l5 = __readUInt16LE(blob, blob.l + 2);
    start = blob.l + 4;
    if (nextrt == 2066) start += 4;
    else if (nextrt == 2165 || nextrt == 2175) {
      start += 12;
    }
    d4 = blob.slice(start, blob.l + 4 + l5);
    bufs.push(d4);
    blob.l += 4 + l5;
    next = XLSRecordEnum[nextrt = __readUInt16LE(blob, blob.l)];
  }
  var b4 = bconcat(bufs);
  prep_blob(b4, 0);
  var ll = 0;
  b4.lens = [];
  for (var j3 = 0; j3 < bufs.length; ++j3) {
    b4.lens.push(ll);
    ll += bufs[j3].length;
  }
  if (b4.length < length) throw "XLS Record 0x" + RecordType.toString(16) + " Truncated: " + b4.length + " < " + length;
  return R3.f(b4, b4.length, opts);
}
function safe_format_xf(p4, opts, date1904) {
  if (p4.t === "z") return;
  if (!p4.XF) return;
  var fmtid = 0;
  try {
    fmtid = p4.z || p4.XF.numFmtId || 0;
    if (opts.cellNF && p4.z == null) p4.z = table_fmt[fmtid];
  } catch (e9) {
    if (opts.WTF) throw e9;
  }
  if (!opts || opts.cellText !== false) try {
    if (p4.t === "e") {
      p4.w = p4.w || BErr[p4.v];
    } else if (fmtid === 0 || fmtid == "General") {
      if (p4.t === "n") {
        if ((p4.v | 0) === p4.v) p4.w = p4.v.toString(10);
        else p4.w = SSF_general_num(p4.v);
      } else p4.w = SSF_general(p4.v);
    } else p4.w = SSF_format(fmtid, p4.v, { date1904: !!date1904, dateNF: opts && opts.dateNF });
  } catch (e9) {
    if (opts.WTF) throw e9;
  }
  if (opts.cellDates && fmtid && p4.t == "n" && fmt_is_date(table_fmt[fmtid] || String(fmtid))) {
    var _d = SSF_parse_date_code(p4.v + (date1904 ? 1462 : 0));
    if (_d) {
      p4.t = "d";
      p4.v = new Date(Date.UTC(_d.y, _d.m - 1, _d.d, _d.H, _d.M, _d.S, _d.u));
    }
  }
}
function make_cell(val2, ixfe, t6) {
  return { v: val2, ixfe, t: t6 };
}
function parse_workbook(blob, options) {
  var wb = { opts: {} };
  var Sheets = {};
  if (DENSE != null && options.dense == null) options.dense = DENSE;
  var out = {};
  if (options.dense) out["!data"] = [];
  var Directory = {};
  var range2 = {};
  var last_formula = null;
  var sst = [];
  var cur_sheet = "";
  var Preamble = {};
  var lastcell, last_cell = "", cc, cmnt, rngC, rngR;
  var sharedf = {};
  var arrayf = [];
  var temp_val;
  var country;
  var XFs = [];
  var palette = [];
  var Workbook = { Sheets: [], WBProps: { date1904: false }, Views: [{}] }, wsprops = {};
  var biff4w = false;
  var get_rgb = function getrgb(icv) {
    if (icv < 8) return XLSIcv[icv];
    if (icv < 64) return palette[icv - 8] || XLSIcv[icv];
    return XLSIcv[icv];
  };
  var process_cell_style = function pcs(line, options2) {
    var xfd = line.XF.data;
    if (!xfd || !xfd.patternType || !options2 || !options2.cellStyles) return;
    line.s = {};
    line.s.patternType = xfd.patternType;
    var t6;
    if (t6 = rgb2Hex(get_rgb(xfd.icvFore))) {
      line.s.fgColor = { rgb: t6 };
    }
    if (t6 = rgb2Hex(get_rgb(xfd.icvBack))) {
      line.s.bgColor = { rgb: t6 };
    }
  };
  var addcell = function addcell2(cell, line, options2) {
    if (!biff4w && file_depth > 1) return;
    if (options2.sheetRows && cell.r >= options2.sheetRows) return;
    if (options2.cellStyles && line.XF && line.XF.data) process_cell_style(line, options2);
    delete line.ixfe;
    delete line.XF;
    lastcell = cell;
    last_cell = encode_cell(cell);
    if (!range2 || !range2.s || !range2.e) range2 = { s: { r: 0, c: 0 }, e: { r: 0, c: 0 } };
    if (cell.r < range2.s.r) range2.s.r = cell.r;
    if (cell.c < range2.s.c) range2.s.c = cell.c;
    if (cell.r + 1 > range2.e.r) range2.e.r = cell.r + 1;
    if (cell.c + 1 > range2.e.c) range2.e.c = cell.c + 1;
    if (options2.cellFormula && line.f) {
      for (var afi = 0; afi < arrayf.length; ++afi) {
        if (arrayf[afi][0].s.c > cell.c || arrayf[afi][0].s.r > cell.r) continue;
        if (arrayf[afi][0].e.c < cell.c || arrayf[afi][0].e.r < cell.r) continue;
        line.F = encode_range(arrayf[afi][0]);
        if (arrayf[afi][0].s.c != cell.c || arrayf[afi][0].s.r != cell.r) delete line.f;
        if (line.f) line.f = "" + stringify_formula(arrayf[afi][1], range2, cell, supbooks, opts);
        break;
      }
    }
    {
      if (options2.dense) {
        if (!out["!data"][cell.r]) out["!data"][cell.r] = [];
        out["!data"][cell.r][cell.c] = line;
      } else out[last_cell] = line;
    }
  };
  var opts = {
    enc: false,
    // encrypted
    sbcch: 0,
    // cch in the preceding SupBook
    snames: [],
    // sheetnames
    sharedf,
    // shared formulae by address
    arrayf,
    // array formulae array
    rrtabid: [],
    // RRTabId
    lastuser: "",
    // Last User from WriteAccess
    biff: 8,
    // BIFF version
    codepage: 0,
    // CP from CodePage record
    winlocked: 0,
    // fLockWn from WinProtect
    cellStyles: !!options && !!options.cellStyles,
    WTF: !!options && !!options.wtf
  };
  if (options.password) opts.password = options.password;
  var themes;
  var merges = [];
  var objects = [];
  var colinfo = [], rowinfo = [];
  var seencol = false;
  var supbooks = [];
  supbooks.SheetNames = opts.snames;
  supbooks.sharedf = opts.sharedf;
  supbooks.arrayf = opts.arrayf;
  supbooks.names = [];
  supbooks.XTI = [];
  var last_RT = 0;
  var file_depth = 0;
  var BIFF2Fmt = 0, BIFF2FmtTable = [];
  var FilterDatabases = [];
  var last_lbl;
  opts.codepage = 1200;
  set_cp(1200);
  var seen_codepage = false;
  while (blob.l < blob.length - 1) {
    var s6 = blob.l;
    var RecordType = blob.read_shift(2);
    if (RecordType === 0 && last_RT === 10) break;
    var length = blob.l === blob.length ? 0 : blob.read_shift(2);
    var R3 = XLSRecordEnum[RecordType];
    if (file_depth == 0 && [9, 521, 1033, 2057].indexOf(RecordType) == -1) break;
    if (R3 && R3.f) {
      if (options.bookSheets) {
        if (last_RT === 133 && RecordType !== 133) break;
      }
      last_RT = RecordType;
      if (R3.r === 2 || R3.r == 12) {
        var rt = blob.read_shift(2);
        length -= 2;
        if (!opts.enc && rt !== RecordType && ((rt & 255) << 8 | rt >> 8) !== RecordType) throw new Error("rt mismatch: " + rt + "!=" + RecordType);
        if (R3.r == 12) {
          blob.l += 10;
          length -= 10;
        }
      }
      var val2 = {};
      if (RecordType === 10) val2 = /*::(*/
      R3.f(blob, length, opts);
      else val2 = /*::(*/
      slurp(RecordType, R3, blob, length, opts);
      if (file_depth == 0 && [9, 521, 1033, 2057].indexOf(last_RT) === -1) continue;
      switch (RecordType) {
        case 34:
          wb.opts.Date1904 = Workbook.WBProps.date1904 = val2;
          break;
        case 134:
          wb.opts.WriteProtect = true;
          break;
        case 47:
          if (!opts.enc) blob.l = 0;
          opts.enc = val2;
          if (!options.password) throw new Error("File is password-protected");
          if (val2.valid == null) throw new Error("Encryption scheme unsupported");
          if (!val2.valid) throw new Error("Password is incorrect");
          break;
        case 92:
          opts.lastuser = val2;
          break;
        case 66:
          var cpval = Number(val2);
          switch (cpval) {
            case 21010:
              cpval = 1200;
              break;
            case 32768:
              cpval = 1e4;
              break;
            case 32769:
              cpval = 1252;
              break;
          }
          set_cp(opts.codepage = cpval);
          seen_codepage = true;
          break;
        case 317:
          opts.rrtabid = val2;
          break;
        case 25:
          opts.winlocked = val2;
          break;
        case 439:
          wb.opts["RefreshAll"] = val2;
          break;
        case 12:
          wb.opts["CalcCount"] = val2;
          break;
        case 16:
          wb.opts["CalcDelta"] = val2;
          break;
        case 17:
          wb.opts["CalcIter"] = val2;
          break;
        case 13:
          wb.opts["CalcMode"] = val2;
          break;
        case 14:
          wb.opts["CalcPrecision"] = val2;
          break;
        case 95:
          wb.opts["CalcSaveRecalc"] = val2;
          break;
        case 15:
          opts.CalcRefMode = val2;
          break;
        // TODO: implement R1C1
        case 2211:
          wb.opts.FullCalc = val2;
          break;
        case 129:
          if (val2.fDialog) out["!type"] = "dialog";
          if (!val2.fBelow) (out["!outline"] || (out["!outline"] = {})).above = true;
          if (!val2.fRight) (out["!outline"] || (out["!outline"] = {})).left = true;
          break;
        // TODO
        case 67:
        /* BIFF2XF */
        case 579:
        /* BIFF3XF */
        case 1091:
        /* BIFF4XF */
        case 224:
          XFs.push(val2);
          break;
        case 430:
          supbooks.push([val2]);
          supbooks[supbooks.length - 1].XTI = [];
          break;
        case 35:
        case 547:
          supbooks[supbooks.length - 1].push(val2);
          break;
        case 24:
        case 536:
          last_lbl = {
            Name: val2.Name,
            Ref: stringify_formula(val2.rgce, range2, null, supbooks, opts)
          };
          if (val2.itab > 0) last_lbl.Sheet = val2.itab - 1;
          supbooks.names.push(last_lbl);
          if (!supbooks[0]) {
            supbooks[0] = [];
            supbooks[0].XTI = [];
          }
          supbooks[supbooks.length - 1].push(val2);
          if (val2.Name == "_xlnm._FilterDatabase" && val2.itab > 0) {
            if (val2.rgce && val2.rgce[0] && val2.rgce[0][0] && val2.rgce[0][0][0] == "PtgArea3d")
              FilterDatabases[val2.itab - 1] = { ref: encode_range(val2.rgce[0][0][1][2]) };
          }
          break;
        case 22:
          opts.ExternCount = val2;
          break;
        case 23:
          if (supbooks.length == 0) {
            supbooks[0] = [];
            supbooks[0].XTI = [];
          }
          supbooks[supbooks.length - 1].XTI = supbooks[supbooks.length - 1].XTI.concat(val2);
          supbooks.XTI = supbooks.XTI.concat(val2);
          break;
        case 2196:
          if (opts.biff < 8) break;
          if (last_lbl != null) last_lbl.Comment = val2[1];
          break;
        case 18:
          out["!protect"] = val2;
          break;
        /* for sheet or book */
        case 19:
          if (val2 !== 0 && opts.WTF) console.error("Password verifier: " + val2);
          break;
        case 133:
          {
            Directory[opts.biff == 4 ? opts.snames.length : val2.pos] = val2;
            opts.snames.push(val2.name);
          }
          break;
        case 10:
          {
            if (--file_depth ? !biff4w : biff4w) break;
            if (range2.e) {
              if (range2.e.r > 0 && range2.e.c > 0) {
                range2.e.r--;
                range2.e.c--;
                out["!ref"] = encode_range(range2);
                if (options.sheetRows && options.sheetRows <= range2.e.r) {
                  var tmpri = range2.e.r;
                  range2.e.r = options.sheetRows - 1;
                  out["!fullref"] = out["!ref"];
                  out["!ref"] = encode_range(range2);
                  range2.e.r = tmpri;
                }
                range2.e.r++;
                range2.e.c++;
              }
              if (merges.length > 0) out["!merges"] = merges;
              if (objects.length > 0) out["!objects"] = objects;
              if (colinfo.length > 0) out["!cols"] = colinfo;
              if (rowinfo.length > 0) out["!rows"] = rowinfo;
              Workbook.Sheets.push(wsprops);
            }
            if (cur_sheet === "") Preamble = out;
            else Sheets[cur_sheet] = out;
            out = {};
            if (options.dense) out["!data"] = [];
          }
          break;
        case 9:
        case 521:
        case 1033:
        case 2057:
          {
            if (opts.biff === 8) opts.biff = {
              9: 2,
              521: 3,
              1033: 4
            }[RecordType] || {
              512: 2,
              768: 3,
              1024: 4,
              1280: 5,
              1536: 8,
              2: 2,
              7: 2
            }[val2.BIFFVer] || 8;
            opts.biffguess = val2.BIFFVer == 0;
            if (val2.BIFFVer == 0 && val2.dt == 4096) {
              opts.biff = 5;
              seen_codepage = true;
              set_cp(opts.codepage = 28591);
            }
            if (opts.biff == 4 && val2.dt & 256) biff4w = true;
            if (opts.biff == 8 && val2.BIFFVer == 0 && val2.dt == 16) opts.biff = 2;
            if (file_depth++ && !biff4w) break;
            out = {};
            if (options.dense) out["!data"] = [];
            if (opts.biff < 8 && !seen_codepage) {
              seen_codepage = true;
              set_cp(opts.codepage = options.codepage || 1252);
            }
            if (opts.biff == 4 && biff4w) {
              cur_sheet = (Directory[opts.snames.indexOf(cur_sheet) + 1] || { name: "" }).name;
            } else if (opts.biff < 5 || val2.BIFFVer == 0 && val2.dt == 4096) {
              if (cur_sheet === "") cur_sheet = "Sheet1";
              range2 = { s: { r: 0, c: 0 }, e: { r: 0, c: 0 } };
              var fakebs8 = { pos: blob.l - length, name: cur_sheet };
              Directory[fakebs8.pos] = fakebs8;
              opts.snames.push(cur_sheet);
            } else cur_sheet = (Directory[s6] || { name: "" }).name;
            if (val2.dt == 32) out["!type"] = "chart";
            if (val2.dt == 64) out["!type"] = "macro";
            merges = [];
            objects = [];
            opts.arrayf = arrayf = [];
            colinfo = [];
            rowinfo = [];
            seencol = false;
            wsprops = { Hidden: (Directory[s6] || { hs: 0 }).hs, name: cur_sheet };
          }
          break;
        case 515:
        case 3:
        case 2:
          {
            if (out["!type"] == "chart") {
              if (options.dense ? (out["!data"][val2.r] || [])[val2.c] : out[encode_col(val2.c) + encode_row(val2.r)]) ++val2.c;
            }
            temp_val = { ixfe: val2.ixfe, XF: XFs[val2.ixfe] || {}, v: val2.val, t: "n" };
            if (BIFF2Fmt > 0) temp_val.z = temp_val.XF && temp_val.XF.numFmtId && BIFF2FmtTable[temp_val.XF.numFmtId] || BIFF2FmtTable[temp_val.ixfe >> 8 & 63];
            safe_format_xf(temp_val, options, wb.opts.Date1904);
            addcell({ c: val2.c, r: val2.r }, temp_val, options);
          }
          break;
        case 5:
        case 517:
          {
            temp_val = { ixfe: val2.ixfe, XF: XFs[val2.ixfe], v: val2.val, t: val2.t };
            if (BIFF2Fmt > 0) temp_val.z = temp_val.XF && temp_val.XF.numFmtId && BIFF2FmtTable[temp_val.XF.numFmtId] || BIFF2FmtTable[temp_val.ixfe >> 8 & 63];
            safe_format_xf(temp_val, options, wb.opts.Date1904);
            addcell({ c: val2.c, r: val2.r }, temp_val, options);
          }
          break;
        case 638:
          {
            temp_val = { ixfe: val2.ixfe, XF: XFs[val2.ixfe], v: val2.rknum, t: "n" };
            if (BIFF2Fmt > 0) temp_val.z = temp_val.XF && temp_val.XF.numFmtId && BIFF2FmtTable[temp_val.XF.numFmtId] || BIFF2FmtTable[temp_val.ixfe >> 8 & 63];
            safe_format_xf(temp_val, options, wb.opts.Date1904);
            addcell({ c: val2.c, r: val2.r }, temp_val, options);
          }
          break;
        case 189:
          {
            for (var j3 = val2.c; j3 <= val2.C; ++j3) {
              var ixfe = val2.rkrec[j3 - val2.c][0];
              temp_val = { ixfe, XF: XFs[ixfe], v: val2.rkrec[j3 - val2.c][1], t: "n" };
              if (BIFF2Fmt > 0) temp_val.z = temp_val.XF && temp_val.XF.numFmtId && BIFF2FmtTable[temp_val.XF.numFmtId] || BIFF2FmtTable[temp_val.ixfe >> 8 & 63];
              safe_format_xf(temp_val, options, wb.opts.Date1904);
              addcell({ c: j3, r: val2.r }, temp_val, options);
            }
          }
          break;
        case 6:
        case 518:
        case 1030:
          {
            if (val2.val == "String") {
              last_formula = val2;
              break;
            }
            temp_val = make_cell(val2.val, val2.cell.ixfe, val2.tt);
            temp_val.XF = XFs[temp_val.ixfe];
            if (options.cellFormula) {
              var _f = val2.formula;
              if (_f && _f[0] && _f[0][0] && _f[0][0][0] == "PtgExp") {
                var _fr = _f[0][0][1][0], _fc = _f[0][0][1][1];
                var _fe = encode_cell({ r: _fr, c: _fc });
                if (sharedf[_fe]) temp_val.f = "" + stringify_formula(val2.formula, range2, val2.cell, supbooks, opts);
                else temp_val.F = ((options.dense ? (out["!data"][_fr] || [])[_fc] : out[_fe]) || {}).F;
              } else temp_val.f = "" + stringify_formula(val2.formula, range2, val2.cell, supbooks, opts);
            }
            if (BIFF2Fmt > 0) temp_val.z = temp_val.XF && temp_val.XF.numFmtId && BIFF2FmtTable[temp_val.XF.numFmtId] || BIFF2FmtTable[temp_val.ixfe >> 8 & 63];
            safe_format_xf(temp_val, options, wb.opts.Date1904);
            addcell(val2.cell, temp_val, options);
            last_formula = val2;
          }
          break;
        case 7:
        case 519:
          {
            if (last_formula) {
              last_formula.val = val2;
              temp_val = make_cell(val2, last_formula.cell.ixfe, "s");
              temp_val.XF = XFs[temp_val.ixfe];
              if (options.cellFormula) {
                temp_val.f = "" + stringify_formula(last_formula.formula, range2, last_formula.cell, supbooks, opts);
              }
              if (BIFF2Fmt > 0) temp_val.z = temp_val.XF && temp_val.XF.numFmtId && BIFF2FmtTable[temp_val.XF.numFmtId] || BIFF2FmtTable[temp_val.ixfe >> 8 & 63];
              safe_format_xf(temp_val, options, wb.opts.Date1904);
              addcell(last_formula.cell, temp_val, options);
              last_formula = null;
            } else throw new Error("String record expects Formula");
          }
          break;
        case 33:
        case 545:
          {
            arrayf.push(val2);
            var _arraystart = encode_cell(val2[0].s);
            cc = options.dense ? (out["!data"][val2[0].s.r] || [])[val2[0].s.c] : out[_arraystart];
            if (options.cellFormula && cc) {
              if (!last_formula) break;
              if (!_arraystart || !cc) break;
              cc.f = "" + stringify_formula(val2[1], range2, val2[0], supbooks, opts);
              cc.F = encode_range(val2[0]);
            }
          }
          break;
        case 1212:
          {
            if (!options.cellFormula) break;
            if (last_cell) {
              if (!last_formula) break;
              sharedf[encode_cell(last_formula.cell)] = val2[0];
              cc = options.dense ? (out["!data"][last_formula.cell.r] || [])[last_formula.cell.c] : out[encode_cell(last_formula.cell)];
              (cc || {}).f = "" + stringify_formula(val2[0], range2, lastcell, supbooks, opts);
            }
          }
          break;
        case 253:
          temp_val = make_cell(sst[val2.isst].t, val2.ixfe, "s");
          if (sst[val2.isst].h) temp_val.h = sst[val2.isst].h;
          temp_val.XF = XFs[temp_val.ixfe];
          if (BIFF2Fmt > 0) temp_val.z = temp_val.XF && temp_val.XF.numFmtId && BIFF2FmtTable[temp_val.XF.numFmtId] || BIFF2FmtTable[temp_val.ixfe >> 8 & 63];
          safe_format_xf(temp_val, options, wb.opts.Date1904);
          addcell({ c: val2.c, r: val2.r }, temp_val, options);
          break;
        case 513:
          if (options.sheetStubs) {
            temp_val = { ixfe: val2.ixfe, XF: XFs[val2.ixfe], t: "z" };
            if (BIFF2Fmt > 0) temp_val.z = temp_val.XF && temp_val.XF.numFmtId && BIFF2FmtTable[temp_val.XF.numFmtId] || BIFF2FmtTable[temp_val.ixfe >> 8 & 63];
            safe_format_xf(temp_val, options, wb.opts.Date1904);
            addcell({ c: val2.c, r: val2.r }, temp_val, options);
          }
          break;
        case 190:
          if (options.sheetStubs) {
            for (var _j = val2.c; _j <= val2.C; ++_j) {
              var _ixfe = val2.ixfe[_j - val2.c];
              temp_val = { ixfe: _ixfe, XF: XFs[_ixfe], t: "z" };
              if (BIFF2Fmt > 0) temp_val.z = temp_val.XF && temp_val.XF.numFmtId && BIFF2FmtTable[temp_val.XF.numFmtId] || BIFF2FmtTable[temp_val.ixfe >> 8 & 63];
              safe_format_xf(temp_val, options, wb.opts.Date1904);
              addcell({ c: _j, r: val2.r }, temp_val, options);
            }
          }
          break;
        case 214:
        case 516:
        case 4:
          temp_val = make_cell(val2.val, val2.ixfe, "s");
          temp_val.XF = XFs[temp_val.ixfe];
          if (BIFF2Fmt > 0) temp_val.z = temp_val.XF && temp_val.XF.numFmtId && BIFF2FmtTable[temp_val.XF.numFmtId] || BIFF2FmtTable[temp_val.ixfe >> 8 & 63];
          safe_format_xf(temp_val, options, wb.opts.Date1904);
          addcell({ c: val2.c, r: val2.r }, temp_val, options);
          break;
        case 0:
        case 512:
          {
            if (file_depth === 1) range2 = val2;
          }
          break;
        case 252:
          {
            sst = val2;
          }
          break;
        case 1054:
          {
            if (opts.biff >= 3 && opts.biff <= 4) {
              BIFF2FmtTable[BIFF2Fmt++] = val2[1];
              for (var b4idx = 0; b4idx < BIFF2Fmt + 163; ++b4idx) if (table_fmt[b4idx] == val2[1]) break;
              if (b4idx >= 163) SSF__load(val2[1], BIFF2Fmt + 163);
            } else SSF__load(val2[1], val2[0]);
          }
          break;
        case 30:
          {
            BIFF2FmtTable[BIFF2Fmt++] = val2;
            for (var b2idx = 0; b2idx < BIFF2Fmt + 163; ++b2idx) if (table_fmt[b2idx] == val2) break;
            if (b2idx >= 163) SSF__load(val2, BIFF2Fmt + 163);
          }
          break;
        case 229:
          merges = merges.concat(val2);
          break;
        case 93:
          objects[val2.cmo[0]] = opts.lastobj = val2;
          break;
        case 438:
          opts.lastobj.TxO = val2;
          break;
        case 127:
          opts.lastobj.ImData = val2;
          break;
        case 440:
          {
            for (rngR = val2[0].s.r; rngR <= val2[0].e.r; ++rngR)
              for (rngC = val2[0].s.c; rngC <= val2[0].e.c; ++rngC) {
                cc = options.dense ? (out["!data"][rngR] || [])[rngC] : out[encode_cell({ c: rngC, r: rngR })];
                if (cc) cc.l = val2[1];
              }
          }
          break;
        case 2048:
          {
            for (rngR = val2[0].s.r; rngR <= val2[0].e.r; ++rngR)
              for (rngC = val2[0].s.c; rngC <= val2[0].e.c; ++rngC) {
                cc = options.dense ? (out["!data"][rngR] || [])[rngC] : out[encode_cell({ c: rngC, r: rngR })];
                if (cc && cc.l) cc.l.Tooltip = val2[1];
              }
          }
          break;
        case 28:
          {
            cc = options.dense ? (out["!data"][val2[0].r] || [])[val2[0].c] : out[encode_cell(val2[0])];
            if (!cc) {
              if (options.dense) {
                if (!out["!data"][val2[0].r]) out["!data"][val2[0].r] = [];
                cc = out["!data"][val2[0].r][val2[0].c] = { t: "z" };
              } else {
                cc = out[encode_cell(val2[0])] = { t: "z" };
              }
              range2.e.r = Math.max(range2.e.r, val2[0].r);
              range2.s.r = Math.min(range2.s.r, val2[0].r);
              range2.e.c = Math.max(range2.e.c, val2[0].c);
              range2.s.c = Math.min(range2.s.c, val2[0].c);
            }
            if (!cc.c) cc.c = [];
            if (opts.biff <= 5 && opts.biff >= 2) cmnt = { a: "SheetJ5", t: val2[1] };
            else {
              var noteobj = objects[val2[2]];
              cmnt = { a: val2[1], t: noteobj.TxO.t };
              if (val2[3] != null && !(val2[3] & 2)) cc.c.hidden = true;
            }
            cc.c.push(cmnt);
          }
          break;
        case 2173:
          update_xfext(XFs[val2.ixfe], val2.ext);
          break;
        case 125:
          {
            if (!opts.cellStyles) break;
            while (val2.e >= val2.s) {
              colinfo[val2.e--] = { width: val2.w / 256, level: val2.level || 0, hidden: !!(val2.flags & 1) };
              if (!seencol) {
                seencol = true;
                find_mdw_colw(val2.w / 256);
              }
              process_col(colinfo[val2.e + 1]);
            }
          }
          break;
        case 520:
          {
            var rowobj = {};
            if (val2.level != null) {
              rowinfo[val2.r] = rowobj;
              rowobj.level = val2.level;
            }
            if (val2.hidden) {
              rowinfo[val2.r] = rowobj;
              rowobj.hidden = true;
            }
            if (val2.hpt) {
              rowinfo[val2.r] = rowobj;
              rowobj.hpt = val2.hpt;
              rowobj.hpx = pt2px(val2.hpt);
            }
          }
          break;
        case 38:
        case 39:
        case 40:
        case 41:
          if (!out["!margins"]) default_margins(out["!margins"] = {});
          out["!margins"][{ 38: "left", 39: "right", 40: "top", 41: "bottom" }[RecordType]] = val2;
          break;
        case 161:
          if (!out["!margins"]) default_margins(out["!margins"] = {});
          out["!margins"].header = val2.header;
          out["!margins"].footer = val2.footer;
          break;
        case 574:
          if (val2.RTL) Workbook.Views[0].RTL = true;
          break;
        case 146:
          palette = val2;
          break;
        case 2198:
          themes = val2;
          break;
        case 140:
          country = val2;
          break;
        case 442:
          {
            if (!cur_sheet) Workbook.WBProps.CodeName = val2 || "ThisWorkbook";
            else wsprops.CodeName = val2 || wsprops.name;
          }
          break;
      }
    } else {
      if (!R3) console.error("Missing Info for XLS Record 0x" + RecordType.toString(16));
      blob.l += length;
    }
  }
  wb.SheetNames = keys(Directory).sort(function(a3, b4) {
    return Number(a3) - Number(b4);
  }).map(function(x2) {
    return Directory[x2].name;
  });
  if (!options.bookSheets) wb.Sheets = Sheets;
  if (!wb.SheetNames.length && Preamble["!ref"]) {
    wb.SheetNames.push("Sheet1");
    if (wb.Sheets) wb.Sheets["Sheet1"] = Preamble;
  } else wb.Preamble = Preamble;
  if (wb.Sheets) FilterDatabases.forEach(function(r8, i7) {
    wb.Sheets[wb.SheetNames[i7]]["!autofilter"] = r8;
  });
  wb.Strings = sst;
  wb.SSF = dup(table_fmt);
  if (opts.enc) wb.Encryption = opts.enc;
  if (themes) wb.Themes = themes;
  wb.Metadata = {};
  if (country !== void 0) wb.Metadata.Country = country;
  if (supbooks.names.length > 0) Workbook.Names = supbooks.names;
  wb.Workbook = Workbook;
  return wb;
}
var PSCLSID = {
  SI: "e0859ff2f94f6810ab9108002b27b3d9",
  DSI: "02d5cdd59c2e1b10939708002b2cf9ae",
  UDI: "05d5cdd59c2e1b10939708002b2cf9ae"
};
function parse_xls_props(cfb, props, o9) {
  var DSI = CFB.find(cfb, "/!DocumentSummaryInformation");
  if (DSI && DSI.size > 0) try {
    var DocSummary = parse_PropertySetStream(DSI, DocSummaryPIDDSI, PSCLSID.DSI);
    for (var d4 in DocSummary) props[d4] = DocSummary[d4];
  } catch (e9) {
    if (o9.WTF) throw e9;
  }
  var SI = CFB.find(cfb, "/!SummaryInformation");
  if (SI && SI.size > 0) try {
    var Summary = parse_PropertySetStream(SI, SummaryPIDSI, PSCLSID.SI);
    for (var s6 in Summary) if (props[s6] == null) props[s6] = Summary[s6];
  } catch (e9) {
    if (o9.WTF) throw e9;
  }
  if (props.HeadingPairs && props.TitlesOfParts) {
    load_props_pairs(props.HeadingPairs, props.TitlesOfParts, props, o9);
    delete props.HeadingPairs;
    delete props.TitlesOfParts;
  }
}
function parse_xlscfb(cfb, options) {
  if (!options) options = {};
  fix_read_opts(options);
  reset_cp();
  if (options.codepage) set_ansi(options.codepage);
  var CompObj, WB;
  if (cfb.FullPaths) {
    if (CFB.find(cfb, "/encryption")) throw new Error("File is password-protected");
    CompObj = CFB.find(cfb, "!CompObj");
    WB = CFB.find(cfb, "/Workbook") || CFB.find(cfb, "/Book");
  } else {
    switch (options.type) {
      case "base64":
        cfb = s2a(Base64_decode(cfb));
        break;
      case "binary":
        cfb = s2a(cfb);
        break;
      case "buffer":
        break;
      case "array":
        if (!Array.isArray(cfb)) cfb = Array.prototype.slice.call(cfb);
        break;
    }
    prep_blob(cfb, 0);
    WB = { content: cfb };
  }
  var WorkbookP;
  var _data;
  if (CompObj) parse_compobj(CompObj);
  if (options.bookProps && !options.bookSheets) WorkbookP = {};
  else {
    var T3 = has_buf ? "buffer" : "array";
    if (WB && WB.content) WorkbookP = parse_workbook(WB.content, options);
    else if ((_data = CFB.find(cfb, "PerfectOffice_MAIN")) && _data.content) WorkbookP = WK_.to_workbook(_data.content, (options.type = T3, options));
    else if ((_data = CFB.find(cfb, "NativeContent_MAIN")) && _data.content) WorkbookP = WK_.to_workbook(_data.content, (options.type = T3, options));
    else if ((_data = CFB.find(cfb, "MN0")) && _data.content) throw new Error("Unsupported Works 4 for Mac file");
    else throw new Error("Cannot find Workbook stream");
    if (options.bookVBA && cfb.FullPaths && CFB.find(cfb, "/_VBA_PROJECT_CUR/VBA/dir")) WorkbookP.vbaraw = make_vba_xls(cfb);
  }
  var props = {};
  if (cfb.FullPaths) parse_xls_props(
    /*::((*/
    cfb,
    props,
    options
  );
  WorkbookP.Props = WorkbookP.Custprops = props;
  if (options.bookFiles) WorkbookP.cfb = cfb;
  return WorkbookP;
}
var XLSBRecordEnum = {
  0: {
    /* n:"BrtRowHdr", */
    f: parse_BrtRowHdr
  },
  1: {
    /* n:"BrtCellBlank", */
    f: parse_BrtCellBlank
  },
  2: {
    /* n:"BrtCellRk", */
    f: parse_BrtCellRk
  },
  3: {
    /* n:"BrtCellError", */
    f: parse_BrtCellError
  },
  4: {
    /* n:"BrtCellBool", */
    f: parse_BrtCellBool
  },
  5: {
    /* n:"BrtCellReal", */
    f: parse_BrtCellReal
  },
  6: {
    /* n:"BrtCellSt", */
    f: parse_BrtCellSt
  },
  7: {
    /* n:"BrtCellIsst", */
    f: parse_BrtCellIsst
  },
  8: {
    /* n:"BrtFmlaString", */
    f: parse_BrtFmlaString
  },
  9: {
    /* n:"BrtFmlaNum", */
    f: parse_BrtFmlaNum
  },
  10: {
    /* n:"BrtFmlaBool", */
    f: parse_BrtFmlaBool
  },
  11: {
    /* n:"BrtFmlaError", */
    f: parse_BrtFmlaError
  },
  12: {
    /* n:"BrtShortBlank", */
    f: parse_BrtShortBlank
  },
  13: {
    /* n:"BrtShortRk", */
    f: parse_BrtShortRk
  },
  14: {
    /* n:"BrtShortError", */
    f: parse_BrtShortError
  },
  15: {
    /* n:"BrtShortBool", */
    f: parse_BrtShortBool
  },
  16: {
    /* n:"BrtShortReal", */
    f: parse_BrtShortReal
  },
  17: {
    /* n:"BrtShortSt", */
    f: parse_BrtShortSt
  },
  18: {
    /* n:"BrtShortIsst", */
    f: parse_BrtShortIsst
  },
  19: {
    /* n:"BrtSSTItem", */
    f: parse_RichStr
  },
  20: {
    /* n:"BrtPCDIMissing" */
  },
  21: {
    /* n:"BrtPCDINumber" */
  },
  22: {
    /* n:"BrtPCDIBoolean" */
  },
  23: {
    /* n:"BrtPCDIError" */
  },
  24: {
    /* n:"BrtPCDIString" */
  },
  25: {
    /* n:"BrtPCDIDatetime" */
  },
  26: {
    /* n:"BrtPCDIIndex" */
  },
  27: {
    /* n:"BrtPCDIAMissing" */
  },
  28: {
    /* n:"BrtPCDIANumber" */
  },
  29: {
    /* n:"BrtPCDIABoolean" */
  },
  30: {
    /* n:"BrtPCDIAError" */
  },
  31: {
    /* n:"BrtPCDIAString" */
  },
  32: {
    /* n:"BrtPCDIADatetime" */
  },
  33: {
    /* n:"BrtPCRRecord" */
  },
  34: {
    /* n:"BrtPCRRecordDt" */
  },
  35: {
    /* n:"BrtFRTBegin", */
    T: 1
  },
  36: {
    /* n:"BrtFRTEnd", */
    T: -1
  },
  37: {
    /* n:"BrtACBegin", */
    T: 1
  },
  38: {
    /* n:"BrtACEnd", */
    T: -1
  },
  39: {
    /* n:"BrtName", */
    f: parse_BrtName
  },
  40: {
    /* n:"BrtIndexRowBlock" */
  },
  42: {
    /* n:"BrtIndexBlock" */
  },
  43: {
    /* n:"BrtFont", */
    f: parse_BrtFont
  },
  44: {
    /* n:"BrtFmt", */
    f: parse_BrtFmt
  },
  45: {
    /* n:"BrtFill", */
    f: parse_BrtFill
  },
  46: {
    /* n:"BrtBorder", */
    f: parse_BrtBorder
  },
  47: {
    /* n:"BrtXF", */
    f: parse_BrtXF
  },
  48: {
    /* n:"BrtStyle" */
  },
  49: {
    /* n:"BrtCellMeta", */
    f: parse_Int32LE
  },
  50: {
    /* n:"BrtValueMeta" */
  },
  51: {
    /* n:"BrtMdb" */
    f: parse_BrtMdb
  },
  52: {
    /* n:"BrtBeginFmd", */
    T: 1
  },
  53: {
    /* n:"BrtEndFmd", */
    T: -1
  },
  54: {
    /* n:"BrtBeginMdx", */
    T: 1
  },
  55: {
    /* n:"BrtEndMdx", */
    T: -1
  },
  56: {
    /* n:"BrtBeginMdxTuple", */
    T: 1
  },
  57: {
    /* n:"BrtEndMdxTuple", */
    T: -1
  },
  58: {
    /* n:"BrtMdxMbrIstr" */
  },
  59: {
    /* n:"BrtStr" */
  },
  60: {
    /* n:"BrtColInfo", */
    f: parse_ColInfo
  },
  62: {
    /* n:"BrtCellRString", */
    f: parse_BrtCellRString
  },
  63: {
    /* n:"BrtCalcChainItem$", */
    f: parse_BrtCalcChainItem$
  },
  64: {
    /* n:"BrtDVal", */
    f: parse_BrtDVal
  },
  65: {
    /* n:"BrtSxvcellNum" */
  },
  66: {
    /* n:"BrtSxvcellStr" */
  },
  67: {
    /* n:"BrtSxvcellBool" */
  },
  68: {
    /* n:"BrtSxvcellErr" */
  },
  69: {
    /* n:"BrtSxvcellDate" */
  },
  70: {
    /* n:"BrtSxvcellNil" */
  },
  128: {
    /* n:"BrtFileVersion" */
  },
  129: {
    /* n:"BrtBeginSheet", */
    T: 1
  },
  130: {
    /* n:"BrtEndSheet", */
    T: -1
  },
  131: {
    /* n:"BrtBeginBook", */
    T: 1,
    f: parsenoop,
    p: 0
  },
  132: {
    /* n:"BrtEndBook", */
    T: -1
  },
  133: {
    /* n:"BrtBeginWsViews", */
    T: 1
  },
  134: {
    /* n:"BrtEndWsViews", */
    T: -1
  },
  135: {
    /* n:"BrtBeginBookViews", */
    T: 1
  },
  136: {
    /* n:"BrtEndBookViews", */
    T: -1
  },
  137: {
    /* n:"BrtBeginWsView", */
    T: 1,
    f: parse_BrtBeginWsView
  },
  138: {
    /* n:"BrtEndWsView", */
    T: -1
  },
  139: {
    /* n:"BrtBeginCsViews", */
    T: 1
  },
  140: {
    /* n:"BrtEndCsViews", */
    T: -1
  },
  141: {
    /* n:"BrtBeginCsView", */
    T: 1
  },
  142: {
    /* n:"BrtEndCsView", */
    T: -1
  },
  143: {
    /* n:"BrtBeginBundleShs", */
    T: 1
  },
  144: {
    /* n:"BrtEndBundleShs", */
    T: -1
  },
  145: {
    /* n:"BrtBeginSheetData", */
    T: 1
  },
  146: {
    /* n:"BrtEndSheetData", */
    T: -1
  },
  147: {
    /* n:"BrtWsProp", */
    f: parse_BrtWsProp
  },
  148: {
    /* n:"BrtWsDim", */
    f: parse_BrtWsDim,
    p: 16
  },
  151: {
    /* n:"BrtPane", */
    f: parse_BrtPane
  },
  152: {
    /* n:"BrtSel" */
  },
  153: {
    /* n:"BrtWbProp", */
    f: parse_BrtWbProp
  },
  154: {
    /* n:"BrtWbFactoid" */
  },
  155: {
    /* n:"BrtFileRecover" */
  },
  156: {
    /* n:"BrtBundleSh", */
    f: parse_BrtBundleSh
  },
  157: {
    /* n:"BrtCalcProp" */
  },
  158: {
    /* n:"BrtBookView" */
  },
  159: {
    /* n:"BrtBeginSst", */
    T: 1,
    f: parse_BrtBeginSst
  },
  160: {
    /* n:"BrtEndSst", */
    T: -1
  },
  161: {
    /* n:"BrtBeginAFilter", */
    T: 1,
    f: parse_UncheckedRfX
  },
  162: {
    /* n:"BrtEndAFilter", */
    T: -1
  },
  163: {
    /* n:"BrtBeginFilterColumn", */
    T: 1
  },
  164: {
    /* n:"BrtEndFilterColumn", */
    T: -1
  },
  165: {
    /* n:"BrtBeginFilters", */
    T: 1
  },
  166: {
    /* n:"BrtEndFilters", */
    T: -1
  },
  167: {
    /* n:"BrtFilter" */
  },
  168: {
    /* n:"BrtColorFilter" */
  },
  169: {
    /* n:"BrtIconFilter" */
  },
  170: {
    /* n:"BrtTop10Filter" */
  },
  171: {
    /* n:"BrtDynamicFilter" */
  },
  172: {
    /* n:"BrtBeginCustomFilters", */
    T: 1
  },
  173: {
    /* n:"BrtEndCustomFilters", */
    T: -1
  },
  174: {
    /* n:"BrtCustomFilter" */
  },
  175: {
    /* n:"BrtAFilterDateGroupItem" */
  },
  176: {
    /* n:"BrtMergeCell", */
    f: parse_BrtMergeCell
  },
  177: {
    /* n:"BrtBeginMergeCells", */
    T: 1
  },
  178: {
    /* n:"BrtEndMergeCells", */
    T: -1
  },
  179: {
    /* n:"BrtBeginPivotCacheDef", */
    T: 1
  },
  180: {
    /* n:"BrtEndPivotCacheDef", */
    T: -1
  },
  181: {
    /* n:"BrtBeginPCDFields", */
    T: 1
  },
  182: {
    /* n:"BrtEndPCDFields", */
    T: -1
  },
  183: {
    /* n:"BrtBeginPCDField", */
    T: 1
  },
  184: {
    /* n:"BrtEndPCDField", */
    T: -1
  },
  185: {
    /* n:"BrtBeginPCDSource", */
    T: 1
  },
  186: {
    /* n:"BrtEndPCDSource", */
    T: -1
  },
  187: {
    /* n:"BrtBeginPCDSRange", */
    T: 1
  },
  188: {
    /* n:"BrtEndPCDSRange", */
    T: -1
  },
  189: {
    /* n:"BrtBeginPCDFAtbl", */
    T: 1
  },
  190: {
    /* n:"BrtEndPCDFAtbl", */
    T: -1
  },
  191: {
    /* n:"BrtBeginPCDIRun", */
    T: 1
  },
  192: {
    /* n:"BrtEndPCDIRun", */
    T: -1
  },
  193: {
    /* n:"BrtBeginPivotCacheRecords", */
    T: 1
  },
  194: {
    /* n:"BrtEndPivotCacheRecords", */
    T: -1
  },
  195: {
    /* n:"BrtBeginPCDHierarchies", */
    T: 1
  },
  196: {
    /* n:"BrtEndPCDHierarchies", */
    T: -1
  },
  197: {
    /* n:"BrtBeginPCDHierarchy", */
    T: 1
  },
  198: {
    /* n:"BrtEndPCDHierarchy", */
    T: -1
  },
  199: {
    /* n:"BrtBeginPCDHFieldsUsage", */
    T: 1
  },
  200: {
    /* n:"BrtEndPCDHFieldsUsage", */
    T: -1
  },
  201: {
    /* n:"BrtBeginExtConnection", */
    T: 1
  },
  202: {
    /* n:"BrtEndExtConnection", */
    T: -1
  },
  203: {
    /* n:"BrtBeginECDbProps", */
    T: 1
  },
  204: {
    /* n:"BrtEndECDbProps", */
    T: -1
  },
  205: {
    /* n:"BrtBeginECOlapProps", */
    T: 1
  },
  206: {
    /* n:"BrtEndECOlapProps", */
    T: -1
  },
  207: {
    /* n:"BrtBeginPCDSConsol", */
    T: 1
  },
  208: {
    /* n:"BrtEndPCDSConsol", */
    T: -1
  },
  209: {
    /* n:"BrtBeginPCDSCPages", */
    T: 1
  },
  210: {
    /* n:"BrtEndPCDSCPages", */
    T: -1
  },
  211: {
    /* n:"BrtBeginPCDSCPage", */
    T: 1
  },
  212: {
    /* n:"BrtEndPCDSCPage", */
    T: -1
  },
  213: {
    /* n:"BrtBeginPCDSCPItem", */
    T: 1
  },
  214: {
    /* n:"BrtEndPCDSCPItem", */
    T: -1
  },
  215: {
    /* n:"BrtBeginPCDSCSets", */
    T: 1
  },
  216: {
    /* n:"BrtEndPCDSCSets", */
    T: -1
  },
  217: {
    /* n:"BrtBeginPCDSCSet", */
    T: 1
  },
  218: {
    /* n:"BrtEndPCDSCSet", */
    T: -1
  },
  219: {
    /* n:"BrtBeginPCDFGroup", */
    T: 1
  },
  220: {
    /* n:"BrtEndPCDFGroup", */
    T: -1
  },
  221: {
    /* n:"BrtBeginPCDFGItems", */
    T: 1
  },
  222: {
    /* n:"BrtEndPCDFGItems", */
    T: -1
  },
  223: {
    /* n:"BrtBeginPCDFGRange", */
    T: 1
  },
  224: {
    /* n:"BrtEndPCDFGRange", */
    T: -1
  },
  225: {
    /* n:"BrtBeginPCDFGDiscrete", */
    T: 1
  },
  226: {
    /* n:"BrtEndPCDFGDiscrete", */
    T: -1
  },
  227: {
    /* n:"BrtBeginPCDSDTupleCache", */
    T: 1
  },
  228: {
    /* n:"BrtEndPCDSDTupleCache", */
    T: -1
  },
  229: {
    /* n:"BrtBeginPCDSDTCEntries", */
    T: 1
  },
  230: {
    /* n:"BrtEndPCDSDTCEntries", */
    T: -1
  },
  231: {
    /* n:"BrtBeginPCDSDTCEMembers", */
    T: 1
  },
  232: {
    /* n:"BrtEndPCDSDTCEMembers", */
    T: -1
  },
  233: {
    /* n:"BrtBeginPCDSDTCEMember", */
    T: 1
  },
  234: {
    /* n:"BrtEndPCDSDTCEMember", */
    T: -1
  },
  235: {
    /* n:"BrtBeginPCDSDTCQueries", */
    T: 1
  },
  236: {
    /* n:"BrtEndPCDSDTCQueries", */
    T: -1
  },
  237: {
    /* n:"BrtBeginPCDSDTCQuery", */
    T: 1
  },
  238: {
    /* n:"BrtEndPCDSDTCQuery", */
    T: -1
  },
  239: {
    /* n:"BrtBeginPCDSDTCSets", */
    T: 1
  },
  240: {
    /* n:"BrtEndPCDSDTCSets", */
    T: -1
  },
  241: {
    /* n:"BrtBeginPCDSDTCSet", */
    T: 1
  },
  242: {
    /* n:"BrtEndPCDSDTCSet", */
    T: -1
  },
  243: {
    /* n:"BrtBeginPCDCalcItems", */
    T: 1
  },
  244: {
    /* n:"BrtEndPCDCalcItems", */
    T: -1
  },
  245: {
    /* n:"BrtBeginPCDCalcItem", */
    T: 1
  },
  246: {
    /* n:"BrtEndPCDCalcItem", */
    T: -1
  },
  247: {
    /* n:"BrtBeginPRule", */
    T: 1
  },
  248: {
    /* n:"BrtEndPRule", */
    T: -1
  },
  249: {
    /* n:"BrtBeginPRFilters", */
    T: 1
  },
  250: {
    /* n:"BrtEndPRFilters", */
    T: -1
  },
  251: {
    /* n:"BrtBeginPRFilter", */
    T: 1
  },
  252: {
    /* n:"BrtEndPRFilter", */
    T: -1
  },
  253: {
    /* n:"BrtBeginPNames", */
    T: 1
  },
  254: {
    /* n:"BrtEndPNames", */
    T: -1
  },
  255: {
    /* n:"BrtBeginPName", */
    T: 1
  },
  256: {
    /* n:"BrtEndPName", */
    T: -1
  },
  257: {
    /* n:"BrtBeginPNPairs", */
    T: 1
  },
  258: {
    /* n:"BrtEndPNPairs", */
    T: -1
  },
  259: {
    /* n:"BrtBeginPNPair", */
    T: 1
  },
  260: {
    /* n:"BrtEndPNPair", */
    T: -1
  },
  261: {
    /* n:"BrtBeginECWebProps", */
    T: 1
  },
  262: {
    /* n:"BrtEndECWebProps", */
    T: -1
  },
  263: {
    /* n:"BrtBeginEcWpTables", */
    T: 1
  },
  264: {
    /* n:"BrtEndECWPTables", */
    T: -1
  },
  265: {
    /* n:"BrtBeginECParams", */
    T: 1
  },
  266: {
    /* n:"BrtEndECParams", */
    T: -1
  },
  267: {
    /* n:"BrtBeginECParam", */
    T: 1
  },
  268: {
    /* n:"BrtEndECParam", */
    T: -1
  },
  269: {
    /* n:"BrtBeginPCDKPIs", */
    T: 1
  },
  270: {
    /* n:"BrtEndPCDKPIs", */
    T: -1
  },
  271: {
    /* n:"BrtBeginPCDKPI", */
    T: 1
  },
  272: {
    /* n:"BrtEndPCDKPI", */
    T: -1
  },
  273: {
    /* n:"BrtBeginDims", */
    T: 1
  },
  274: {
    /* n:"BrtEndDims", */
    T: -1
  },
  275: {
    /* n:"BrtBeginDim", */
    T: 1
  },
  276: {
    /* n:"BrtEndDim", */
    T: -1
  },
  277: {
    /* n:"BrtIndexPartEnd" */
  },
  278: {
    /* n:"BrtBeginStyleSheet", */
    T: 1
  },
  279: {
    /* n:"BrtEndStyleSheet", */
    T: -1
  },
  280: {
    /* n:"BrtBeginSXView", */
    T: 1
  },
  281: {
    /* n:"BrtEndSXVI", */
    T: -1
  },
  282: {
    /* n:"BrtBeginSXVI", */
    T: 1
  },
  283: {
    /* n:"BrtBeginSXVIs", */
    T: 1
  },
  284: {
    /* n:"BrtEndSXVIs", */
    T: -1
  },
  285: {
    /* n:"BrtBeginSXVD", */
    T: 1
  },
  286: {
    /* n:"BrtEndSXVD", */
    T: -1
  },
  287: {
    /* n:"BrtBeginSXVDs", */
    T: 1
  },
  288: {
    /* n:"BrtEndSXVDs", */
    T: -1
  },
  289: {
    /* n:"BrtBeginSXPI", */
    T: 1
  },
  290: {
    /* n:"BrtEndSXPI", */
    T: -1
  },
  291: {
    /* n:"BrtBeginSXPIs", */
    T: 1
  },
  292: {
    /* n:"BrtEndSXPIs", */
    T: -1
  },
  293: {
    /* n:"BrtBeginSXDI", */
    T: 1
  },
  294: {
    /* n:"BrtEndSXDI", */
    T: -1
  },
  295: {
    /* n:"BrtBeginSXDIs", */
    T: 1
  },
  296: {
    /* n:"BrtEndSXDIs", */
    T: -1
  },
  297: {
    /* n:"BrtBeginSXLI", */
    T: 1
  },
  298: {
    /* n:"BrtEndSXLI", */
    T: -1
  },
  299: {
    /* n:"BrtBeginSXLIRws", */
    T: 1
  },
  300: {
    /* n:"BrtEndSXLIRws", */
    T: -1
  },
  301: {
    /* n:"BrtBeginSXLICols", */
    T: 1
  },
  302: {
    /* n:"BrtEndSXLICols", */
    T: -1
  },
  303: {
    /* n:"BrtBeginSXFormat", */
    T: 1
  },
  304: {
    /* n:"BrtEndSXFormat", */
    T: -1
  },
  305: {
    /* n:"BrtBeginSXFormats", */
    T: 1
  },
  306: {
    /* n:"BrtEndSxFormats", */
    T: -1
  },
  307: {
    /* n:"BrtBeginSxSelect", */
    T: 1
  },
  308: {
    /* n:"BrtEndSxSelect", */
    T: -1
  },
  309: {
    /* n:"BrtBeginISXVDRws", */
    T: 1
  },
  310: {
    /* n:"BrtEndISXVDRws", */
    T: -1
  },
  311: {
    /* n:"BrtBeginISXVDCols", */
    T: 1
  },
  312: {
    /* n:"BrtEndISXVDCols", */
    T: -1
  },
  313: {
    /* n:"BrtEndSXLocation", */
    T: -1
  },
  314: {
    /* n:"BrtBeginSXLocation", */
    T: 1
  },
  315: {
    /* n:"BrtEndSXView", */
    T: -1
  },
  316: {
    /* n:"BrtBeginSXTHs", */
    T: 1
  },
  317: {
    /* n:"BrtEndSXTHs", */
    T: -1
  },
  318: {
    /* n:"BrtBeginSXTH", */
    T: 1
  },
  319: {
    /* n:"BrtEndSXTH", */
    T: -1
  },
  320: {
    /* n:"BrtBeginISXTHRws", */
    T: 1
  },
  321: {
    /* n:"BrtEndISXTHRws", */
    T: -1
  },
  322: {
    /* n:"BrtBeginISXTHCols", */
    T: 1
  },
  323: {
    /* n:"BrtEndISXTHCols", */
    T: -1
  },
  324: {
    /* n:"BrtBeginSXTDMPS", */
    T: 1
  },
  325: {
    /* n:"BrtEndSXTDMPs", */
    T: -1
  },
  326: {
    /* n:"BrtBeginSXTDMP", */
    T: 1
  },
  327: {
    /* n:"BrtEndSXTDMP", */
    T: -1
  },
  328: {
    /* n:"BrtBeginSXTHItems", */
    T: 1
  },
  329: {
    /* n:"BrtEndSXTHItems", */
    T: -1
  },
  330: {
    /* n:"BrtBeginSXTHItem", */
    T: 1
  },
  331: {
    /* n:"BrtEndSXTHItem", */
    T: -1
  },
  332: {
    /* n:"BrtBeginMetadata", */
    T: 1
  },
  333: {
    /* n:"BrtEndMetadata", */
    T: -1
  },
  334: {
    /* n:"BrtBeginEsmdtinfo", */
    T: 1
  },
  335: {
    /* n:"BrtMdtinfo", */
    f: parse_BrtMdtinfo
  },
  336: {
    /* n:"BrtEndEsmdtinfo", */
    T: -1
  },
  337: {
    /* n:"BrtBeginEsmdb", */
    f: parse_BrtBeginEsmdb,
    T: 1
  },
  338: {
    /* n:"BrtEndEsmdb", */
    T: -1
  },
  339: {
    /* n:"BrtBeginEsfmd", */
    T: 1
  },
  340: {
    /* n:"BrtEndEsfmd", */
    T: -1
  },
  341: {
    /* n:"BrtBeginSingleCells", */
    T: 1
  },
  342: {
    /* n:"BrtEndSingleCells", */
    T: -1
  },
  343: {
    /* n:"BrtBeginList", */
    T: 1
  },
  344: {
    /* n:"BrtEndList", */
    T: -1
  },
  345: {
    /* n:"BrtBeginListCols", */
    T: 1
  },
  346: {
    /* n:"BrtEndListCols", */
    T: -1
  },
  347: {
    /* n:"BrtBeginListCol", */
    T: 1
  },
  348: {
    /* n:"BrtEndListCol", */
    T: -1
  },
  349: {
    /* n:"BrtBeginListXmlCPr", */
    T: 1
  },
  350: {
    /* n:"BrtEndListXmlCPr", */
    T: -1
  },
  351: {
    /* n:"BrtListCCFmla" */
  },
  352: {
    /* n:"BrtListTrFmla" */
  },
  353: {
    /* n:"BrtBeginExternals", */
    T: 1
  },
  354: {
    /* n:"BrtEndExternals", */
    T: -1
  },
  355: {
    /* n:"BrtSupBookSrc", */
    f: parse_RelID
  },
  357: {
    /* n:"BrtSupSelf" */
  },
  358: {
    /* n:"BrtSupSame" */
  },
  359: {
    /* n:"BrtSupTabs" */
  },
  360: {
    /* n:"BrtBeginSupBook", */
    T: 1
  },
  361: {
    /* n:"BrtPlaceholderName" */
  },
  362: {
    /* n:"BrtExternSheet", */
    f: parse_ExternSheet
  },
  363: {
    /* n:"BrtExternTableStart" */
  },
  364: {
    /* n:"BrtExternTableEnd" */
  },
  366: {
    /* n:"BrtExternRowHdr" */
  },
  367: {
    /* n:"BrtExternCellBlank" */
  },
  368: {
    /* n:"BrtExternCellReal" */
  },
  369: {
    /* n:"BrtExternCellBool" */
  },
  370: {
    /* n:"BrtExternCellError" */
  },
  371: {
    /* n:"BrtExternCellString" */
  },
  372: {
    /* n:"BrtBeginEsmdx", */
    T: 1
  },
  373: {
    /* n:"BrtEndEsmdx", */
    T: -1
  },
  374: {
    /* n:"BrtBeginMdxSet", */
    T: 1
  },
  375: {
    /* n:"BrtEndMdxSet", */
    T: -1
  },
  376: {
    /* n:"BrtBeginMdxMbrProp", */
    T: 1
  },
  377: {
    /* n:"BrtEndMdxMbrProp", */
    T: -1
  },
  378: {
    /* n:"BrtBeginMdxKPI", */
    T: 1
  },
  379: {
    /* n:"BrtEndMdxKPI", */
    T: -1
  },
  380: {
    /* n:"BrtBeginEsstr", */
    T: 1
  },
  381: {
    /* n:"BrtEndEsstr", */
    T: -1
  },
  382: {
    /* n:"BrtBeginPRFItem", */
    T: 1
  },
  383: {
    /* n:"BrtEndPRFItem", */
    T: -1
  },
  384: {
    /* n:"BrtBeginPivotCacheIDs", */
    T: 1
  },
  385: {
    /* n:"BrtEndPivotCacheIDs", */
    T: -1
  },
  386: {
    /* n:"BrtBeginPivotCacheID", */
    T: 1
  },
  387: {
    /* n:"BrtEndPivotCacheID", */
    T: -1
  },
  388: {
    /* n:"BrtBeginISXVIs", */
    T: 1
  },
  389: {
    /* n:"BrtEndISXVIs", */
    T: -1
  },
  390: {
    /* n:"BrtBeginColInfos", */
    T: 1
  },
  391: {
    /* n:"BrtEndColInfos", */
    T: -1
  },
  392: {
    /* n:"BrtBeginRwBrk", */
    T: 1
  },
  393: {
    /* n:"BrtEndRwBrk", */
    T: -1
  },
  394: {
    /* n:"BrtBeginColBrk", */
    T: 1
  },
  395: {
    /* n:"BrtEndColBrk", */
    T: -1
  },
  396: {
    /* n:"BrtBrk" */
  },
  397: {
    /* n:"BrtUserBookView" */
  },
  398: {
    /* n:"BrtInfo" */
  },
  399: {
    /* n:"BrtCUsr" */
  },
  400: {
    /* n:"BrtUsr" */
  },
  401: {
    /* n:"BrtBeginUsers", */
    T: 1
  },
  403: {
    /* n:"BrtEOF" */
  },
  404: {
    /* n:"BrtUCR" */
  },
  405: {
    /* n:"BrtRRInsDel" */
  },
  406: {
    /* n:"BrtRREndInsDel" */
  },
  407: {
    /* n:"BrtRRMove" */
  },
  408: {
    /* n:"BrtRREndMove" */
  },
  409: {
    /* n:"BrtRRChgCell" */
  },
  410: {
    /* n:"BrtRREndChgCell" */
  },
  411: {
    /* n:"BrtRRHeader" */
  },
  412: {
    /* n:"BrtRRUserView" */
  },
  413: {
    /* n:"BrtRRRenSheet" */
  },
  414: {
    /* n:"BrtRRInsertSh" */
  },
  415: {
    /* n:"BrtRRDefName" */
  },
  416: {
    /* n:"BrtRRNote" */
  },
  417: {
    /* n:"BrtRRConflict" */
  },
  418: {
    /* n:"BrtRRTQSIF" */
  },
  419: {
    /* n:"BrtRRFormat" */
  },
  420: {
    /* n:"BrtRREndFormat" */
  },
  421: {
    /* n:"BrtRRAutoFmt" */
  },
  422: {
    /* n:"BrtBeginUserShViews", */
    T: 1
  },
  423: {
    /* n:"BrtBeginUserShView", */
    T: 1
  },
  424: {
    /* n:"BrtEndUserShView", */
    T: -1
  },
  425: {
    /* n:"BrtEndUserShViews", */
    T: -1
  },
  426: {
    /* n:"BrtArrFmla", */
    f: parse_BrtArrFmla
  },
  427: {
    /* n:"BrtShrFmla", */
    f: parse_BrtShrFmla
  },
  428: {
    /* n:"BrtTable" */
  },
  429: {
    /* n:"BrtBeginExtConnections", */
    T: 1
  },
  430: {
    /* n:"BrtEndExtConnections", */
    T: -1
  },
  431: {
    /* n:"BrtBeginPCDCalcMems", */
    T: 1
  },
  432: {
    /* n:"BrtEndPCDCalcMems", */
    T: -1
  },
  433: {
    /* n:"BrtBeginPCDCalcMem", */
    T: 1
  },
  434: {
    /* n:"BrtEndPCDCalcMem", */
    T: -1
  },
  435: {
    /* n:"BrtBeginPCDHGLevels", */
    T: 1
  },
  436: {
    /* n:"BrtEndPCDHGLevels", */
    T: -1
  },
  437: {
    /* n:"BrtBeginPCDHGLevel", */
    T: 1
  },
  438: {
    /* n:"BrtEndPCDHGLevel", */
    T: -1
  },
  439: {
    /* n:"BrtBeginPCDHGLGroups", */
    T: 1
  },
  440: {
    /* n:"BrtEndPCDHGLGroups", */
    T: -1
  },
  441: {
    /* n:"BrtBeginPCDHGLGroup", */
    T: 1
  },
  442: {
    /* n:"BrtEndPCDHGLGroup", */
    T: -1
  },
  443: {
    /* n:"BrtBeginPCDHGLGMembers", */
    T: 1
  },
  444: {
    /* n:"BrtEndPCDHGLGMembers", */
    T: -1
  },
  445: {
    /* n:"BrtBeginPCDHGLGMember", */
    T: 1
  },
  446: {
    /* n:"BrtEndPCDHGLGMember", */
    T: -1
  },
  447: {
    /* n:"BrtBeginQSI", */
    T: 1
  },
  448: {
    /* n:"BrtEndQSI", */
    T: -1
  },
  449: {
    /* n:"BrtBeginQSIR", */
    T: 1
  },
  450: {
    /* n:"BrtEndQSIR", */
    T: -1
  },
  451: {
    /* n:"BrtBeginDeletedNames", */
    T: 1
  },
  452: {
    /* n:"BrtEndDeletedNames", */
    T: -1
  },
  453: {
    /* n:"BrtBeginDeletedName", */
    T: 1
  },
  454: {
    /* n:"BrtEndDeletedName", */
    T: -1
  },
  455: {
    /* n:"BrtBeginQSIFs", */
    T: 1
  },
  456: {
    /* n:"BrtEndQSIFs", */
    T: -1
  },
  457: {
    /* n:"BrtBeginQSIF", */
    T: 1
  },
  458: {
    /* n:"BrtEndQSIF", */
    T: -1
  },
  459: {
    /* n:"BrtBeginAutoSortScope", */
    T: 1
  },
  460: {
    /* n:"BrtEndAutoSortScope", */
    T: -1
  },
  461: {
    /* n:"BrtBeginConditionalFormatting", */
    T: 1
  },
  462: {
    /* n:"BrtEndConditionalFormatting", */
    T: -1
  },
  463: {
    /* n:"BrtBeginCFRule", */
    T: 1
  },
  464: {
    /* n:"BrtEndCFRule", */
    T: -1
  },
  465: {
    /* n:"BrtBeginIconSet", */
    T: 1
  },
  466: {
    /* n:"BrtEndIconSet", */
    T: -1
  },
  467: {
    /* n:"BrtBeginDatabar", */
    T: 1
  },
  468: {
    /* n:"BrtEndDatabar", */
    T: -1
  },
  469: {
    /* n:"BrtBeginColorScale", */
    T: 1
  },
  470: {
    /* n:"BrtEndColorScale", */
    T: -1
  },
  471: {
    /* n:"BrtCFVO" */
  },
  472: {
    /* n:"BrtExternValueMeta" */
  },
  473: {
    /* n:"BrtBeginColorPalette", */
    T: 1
  },
  474: {
    /* n:"BrtEndColorPalette", */
    T: -1
  },
  475: {
    /* n:"BrtIndexedColor" */
  },
  476: {
    /* n:"BrtMargins", */
    f: parse_BrtMargins
  },
  477: {
    /* n:"BrtPrintOptions" */
  },
  478: {
    /* n:"BrtPageSetup" */
  },
  479: {
    /* n:"BrtBeginHeaderFooter", */
    T: 1
  },
  480: {
    /* n:"BrtEndHeaderFooter", */
    T: -1
  },
  481: {
    /* n:"BrtBeginSXCrtFormat", */
    T: 1
  },
  482: {
    /* n:"BrtEndSXCrtFormat", */
    T: -1
  },
  483: {
    /* n:"BrtBeginSXCrtFormats", */
    T: 1
  },
  484: {
    /* n:"BrtEndSXCrtFormats", */
    T: -1
  },
  485: {
    /* n:"BrtWsFmtInfo", */
    f: parse_BrtWsFmtInfo
  },
  486: {
    /* n:"BrtBeginMgs", */
    T: 1
  },
  487: {
    /* n:"BrtEndMGs", */
    T: -1
  },
  488: {
    /* n:"BrtBeginMGMaps", */
    T: 1
  },
  489: {
    /* n:"BrtEndMGMaps", */
    T: -1
  },
  490: {
    /* n:"BrtBeginMG", */
    T: 1
  },
  491: {
    /* n:"BrtEndMG", */
    T: -1
  },
  492: {
    /* n:"BrtBeginMap", */
    T: 1
  },
  493: {
    /* n:"BrtEndMap", */
    T: -1
  },
  494: {
    /* n:"BrtHLink", */
    f: parse_BrtHLink
  },
  495: {
    /* n:"BrtBeginDCon", */
    T: 1
  },
  496: {
    /* n:"BrtEndDCon", */
    T: -1
  },
  497: {
    /* n:"BrtBeginDRefs", */
    T: 1
  },
  498: {
    /* n:"BrtEndDRefs", */
    T: -1
  },
  499: {
    /* n:"BrtDRef" */
  },
  500: {
    /* n:"BrtBeginScenMan", */
    T: 1
  },
  501: {
    /* n:"BrtEndScenMan", */
    T: -1
  },
  502: {
    /* n:"BrtBeginSct", */
    T: 1
  },
  503: {
    /* n:"BrtEndSct", */
    T: -1
  },
  504: {
    /* n:"BrtSlc" */
  },
  505: {
    /* n:"BrtBeginDXFs", */
    T: 1
  },
  506: {
    /* n:"BrtEndDXFs", */
    T: -1
  },
  507: {
    /* n:"BrtDXF" */
  },
  508: {
    /* n:"BrtBeginTableStyles", */
    T: 1
  },
  509: {
    /* n:"BrtEndTableStyles", */
    T: -1
  },
  510: {
    /* n:"BrtBeginTableStyle", */
    T: 1
  },
  511: {
    /* n:"BrtEndTableStyle", */
    T: -1
  },
  512: {
    /* n:"BrtTableStyleElement" */
  },
  513: {
    /* n:"BrtTableStyleClient" */
  },
  514: {
    /* n:"BrtBeginVolDeps", */
    T: 1
  },
  515: {
    /* n:"BrtEndVolDeps", */
    T: -1
  },
  516: {
    /* n:"BrtBeginVolType", */
    T: 1
  },
  517: {
    /* n:"BrtEndVolType", */
    T: -1
  },
  518: {
    /* n:"BrtBeginVolMain", */
    T: 1
  },
  519: {
    /* n:"BrtEndVolMain", */
    T: -1
  },
  520: {
    /* n:"BrtBeginVolTopic", */
    T: 1
  },
  521: {
    /* n:"BrtEndVolTopic", */
    T: -1
  },
  522: {
    /* n:"BrtVolSubtopic" */
  },
  523: {
    /* n:"BrtVolRef" */
  },
  524: {
    /* n:"BrtVolNum" */
  },
  525: {
    /* n:"BrtVolErr" */
  },
  526: {
    /* n:"BrtVolStr" */
  },
  527: {
    /* n:"BrtVolBool" */
  },
  528: {
    /* n:"BrtBeginCalcChain$", */
    T: 1
  },
  529: {
    /* n:"BrtEndCalcChain$", */
    T: -1
  },
  530: {
    /* n:"BrtBeginSortState", */
    T: 1
  },
  531: {
    /* n:"BrtEndSortState", */
    T: -1
  },
  532: {
    /* n:"BrtBeginSortCond", */
    T: 1
  },
  533: {
    /* n:"BrtEndSortCond", */
    T: -1
  },
  534: {
    /* n:"BrtBookProtection" */
  },
  535: {
    /* n:"BrtSheetProtection" */
  },
  536: {
    /* n:"BrtRangeProtection" */
  },
  537: {
    /* n:"BrtPhoneticInfo" */
  },
  538: {
    /* n:"BrtBeginECTxtWiz", */
    T: 1
  },
  539: {
    /* n:"BrtEndECTxtWiz", */
    T: -1
  },
  540: {
    /* n:"BrtBeginECTWFldInfoLst", */
    T: 1
  },
  541: {
    /* n:"BrtEndECTWFldInfoLst", */
    T: -1
  },
  542: {
    /* n:"BrtBeginECTwFldInfo", */
    T: 1
  },
  548: {
    /* n:"BrtFileSharing" */
  },
  549: {
    /* n:"BrtOleSize" */
  },
  550: {
    /* n:"BrtDrawing", */
    f: parse_RelID
  },
  551: {
    /* n:"BrtLegacyDrawing", */
    f: parse_XLNullableWideString
  },
  552: {
    /* n:"BrtLegacyDrawingHF" */
  },
  553: {
    /* n:"BrtWebOpt" */
  },
  554: {
    /* n:"BrtBeginWebPubItems", */
    T: 1
  },
  555: {
    /* n:"BrtEndWebPubItems", */
    T: -1
  },
  556: {
    /* n:"BrtBeginWebPubItem", */
    T: 1
  },
  557: {
    /* n:"BrtEndWebPubItem", */
    T: -1
  },
  558: {
    /* n:"BrtBeginSXCondFmt", */
    T: 1
  },
  559: {
    /* n:"BrtEndSXCondFmt", */
    T: -1
  },
  560: {
    /* n:"BrtBeginSXCondFmts", */
    T: 1
  },
  561: {
    /* n:"BrtEndSXCondFmts", */
    T: -1
  },
  562: {
    /* n:"BrtBkHim" */
  },
  564: {
    /* n:"BrtColor" */
  },
  565: {
    /* n:"BrtBeginIndexedColors", */
    T: 1
  },
  566: {
    /* n:"BrtEndIndexedColors", */
    T: -1
  },
  569: {
    /* n:"BrtBeginMRUColors", */
    T: 1
  },
  570: {
    /* n:"BrtEndMRUColors", */
    T: -1
  },
  572: {
    /* n:"BrtMRUColor" */
  },
  573: {
    /* n:"BrtBeginDVals", */
    T: 1
  },
  574: {
    /* n:"BrtEndDVals", */
    T: -1
  },
  577: {
    /* n:"BrtSupNameStart" */
  },
  578: {
    /* n:"BrtSupNameValueStart" */
  },
  579: {
    /* n:"BrtSupNameValueEnd" */
  },
  580: {
    /* n:"BrtSupNameNum" */
  },
  581: {
    /* n:"BrtSupNameErr" */
  },
  582: {
    /* n:"BrtSupNameSt" */
  },
  583: {
    /* n:"BrtSupNameNil" */
  },
  584: {
    /* n:"BrtSupNameBool" */
  },
  585: {
    /* n:"BrtSupNameFmla" */
  },
  586: {
    /* n:"BrtSupNameBits" */
  },
  587: {
    /* n:"BrtSupNameEnd" */
  },
  588: {
    /* n:"BrtEndSupBook", */
    T: -1
  },
  589: {
    /* n:"BrtCellSmartTagProperty" */
  },
  590: {
    /* n:"BrtBeginCellSmartTag", */
    T: 1
  },
  591: {
    /* n:"BrtEndCellSmartTag", */
    T: -1
  },
  592: {
    /* n:"BrtBeginCellSmartTags", */
    T: 1
  },
  593: {
    /* n:"BrtEndCellSmartTags", */
    T: -1
  },
  594: {
    /* n:"BrtBeginSmartTags", */
    T: 1
  },
  595: {
    /* n:"BrtEndSmartTags", */
    T: -1
  },
  596: {
    /* n:"BrtSmartTagType" */
  },
  597: {
    /* n:"BrtBeginSmartTagTypes", */
    T: 1
  },
  598: {
    /* n:"BrtEndSmartTagTypes", */
    T: -1
  },
  599: {
    /* n:"BrtBeginSXFilters", */
    T: 1
  },
  600: {
    /* n:"BrtEndSXFilters", */
    T: -1
  },
  601: {
    /* n:"BrtBeginSXFILTER", */
    T: 1
  },
  602: {
    /* n:"BrtEndSXFilter", */
    T: -1
  },
  603: {
    /* n:"BrtBeginFills", */
    T: 1
  },
  604: {
    /* n:"BrtEndFills", */
    T: -1
  },
  605: {
    /* n:"BrtBeginCellWatches", */
    T: 1
  },
  606: {
    /* n:"BrtEndCellWatches", */
    T: -1
  },
  607: {
    /* n:"BrtCellWatch" */
  },
  608: {
    /* n:"BrtBeginCRErrs", */
    T: 1
  },
  609: {
    /* n:"BrtEndCRErrs", */
    T: -1
  },
  610: {
    /* n:"BrtCrashRecErr" */
  },
  611: {
    /* n:"BrtBeginFonts", */
    T: 1
  },
  612: {
    /* n:"BrtEndFonts", */
    T: -1
  },
  613: {
    /* n:"BrtBeginBorders", */
    T: 1
  },
  614: {
    /* n:"BrtEndBorders", */
    T: -1
  },
  615: {
    /* n:"BrtBeginFmts", */
    T: 1
  },
  616: {
    /* n:"BrtEndFmts", */
    T: -1
  },
  617: {
    /* n:"BrtBeginCellXFs", */
    T: 1
  },
  618: {
    /* n:"BrtEndCellXFs", */
    T: -1
  },
  619: {
    /* n:"BrtBeginStyles", */
    T: 1
  },
  620: {
    /* n:"BrtEndStyles", */
    T: -1
  },
  625: {
    /* n:"BrtBigName" */
  },
  626: {
    /* n:"BrtBeginCellStyleXFs", */
    T: 1
  },
  627: {
    /* n:"BrtEndCellStyleXFs", */
    T: -1
  },
  628: {
    /* n:"BrtBeginComments", */
    T: 1
  },
  629: {
    /* n:"BrtEndComments", */
    T: -1
  },
  630: {
    /* n:"BrtBeginCommentAuthors", */
    T: 1
  },
  631: {
    /* n:"BrtEndCommentAuthors", */
    T: -1
  },
  632: {
    /* n:"BrtCommentAuthor", */
    f: parse_BrtCommentAuthor
  },
  633: {
    /* n:"BrtBeginCommentList", */
    T: 1
  },
  634: {
    /* n:"BrtEndCommentList", */
    T: -1
  },
  635: {
    /* n:"BrtBeginComment", */
    T: 1,
    f: parse_BrtBeginComment
  },
  636: {
    /* n:"BrtEndComment", */
    T: -1
  },
  637: {
    /* n:"BrtCommentText", */
    f: parse_BrtCommentText
  },
  638: {
    /* n:"BrtBeginOleObjects", */
    T: 1
  },
  639: {
    /* n:"BrtOleObject" */
  },
  640: {
    /* n:"BrtEndOleObjects", */
    T: -1
  },
  641: {
    /* n:"BrtBeginSxrules", */
    T: 1
  },
  642: {
    /* n:"BrtEndSxRules", */
    T: -1
  },
  643: {
    /* n:"BrtBeginActiveXControls", */
    T: 1
  },
  644: {
    /* n:"BrtActiveX" */
  },
  645: {
    /* n:"BrtEndActiveXControls", */
    T: -1
  },
  646: {
    /* n:"BrtBeginPCDSDTCEMembersSortBy", */
    T: 1
  },
  648: {
    /* n:"BrtBeginCellIgnoreECs", */
    T: 1
  },
  649: {
    /* n:"BrtCellIgnoreEC" */
  },
  650: {
    /* n:"BrtEndCellIgnoreECs", */
    T: -1
  },
  651: {
    /* n:"BrtCsProp", */
    f: parse_BrtCsProp
  },
  652: {
    /* n:"BrtCsPageSetup" */
  },
  653: {
    /* n:"BrtBeginUserCsViews", */
    T: 1
  },
  654: {
    /* n:"BrtEndUserCsViews", */
    T: -1
  },
  655: {
    /* n:"BrtBeginUserCsView", */
    T: 1
  },
  656: {
    /* n:"BrtEndUserCsView", */
    T: -1
  },
  657: {
    /* n:"BrtBeginPcdSFCIEntries", */
    T: 1
  },
  658: {
    /* n:"BrtEndPCDSFCIEntries", */
    T: -1
  },
  659: {
    /* n:"BrtPCDSFCIEntry" */
  },
  660: {
    /* n:"BrtBeginListParts", */
    T: 1
  },
  661: {
    /* n:"BrtListPart" */
  },
  662: {
    /* n:"BrtEndListParts", */
    T: -1
  },
  663: {
    /* n:"BrtSheetCalcProp" */
  },
  664: {
    /* n:"BrtBeginFnGroup", */
    T: 1
  },
  665: {
    /* n:"BrtFnGroup" */
  },
  666: {
    /* n:"BrtEndFnGroup", */
    T: -1
  },
  667: {
    /* n:"BrtSupAddin" */
  },
  668: {
    /* n:"BrtSXTDMPOrder" */
  },
  669: {
    /* n:"BrtCsProtection" */
  },
  671: {
    /* n:"BrtBeginWsSortMap", */
    T: 1
  },
  672: {
    /* n:"BrtEndWsSortMap", */
    T: -1
  },
  673: {
    /* n:"BrtBeginRRSort", */
    T: 1
  },
  674: {
    /* n:"BrtEndRRSort", */
    T: -1
  },
  675: {
    /* n:"BrtRRSortItem" */
  },
  676: {
    /* n:"BrtFileSharingIso" */
  },
  677: {
    /* n:"BrtBookProtectionIso" */
  },
  678: {
    /* n:"BrtSheetProtectionIso" */
  },
  679: {
    /* n:"BrtCsProtectionIso" */
  },
  680: {
    /* n:"BrtRangeProtectionIso" */
  },
  681: {
    /* n:"BrtDValList" */
  },
  1024: {
    /* n:"BrtRwDescent" */
  },
  1025: {
    /* n:"BrtKnownFonts" */
  },
  1026: {
    /* n:"BrtBeginSXTupleSet", */
    T: 1
  },
  1027: {
    /* n:"BrtEndSXTupleSet", */
    T: -1
  },
  1028: {
    /* n:"BrtBeginSXTupleSetHeader", */
    T: 1
  },
  1029: {
    /* n:"BrtEndSXTupleSetHeader", */
    T: -1
  },
  1030: {
    /* n:"BrtSXTupleSetHeaderItem" */
  },
  1031: {
    /* n:"BrtBeginSXTupleSetData", */
    T: 1
  },
  1032: {
    /* n:"BrtEndSXTupleSetData", */
    T: -1
  },
  1033: {
    /* n:"BrtBeginSXTupleSetRow", */
    T: 1
  },
  1034: {
    /* n:"BrtEndSXTupleSetRow", */
    T: -1
  },
  1035: {
    /* n:"BrtSXTupleSetRowItem" */
  },
  1036: {
    /* n:"BrtNameExt" */
  },
  1037: {
    /* n:"BrtPCDH14" */
  },
  1038: {
    /* n:"BrtBeginPCDCalcMem14", */
    T: 1
  },
  1039: {
    /* n:"BrtEndPCDCalcMem14", */
    T: -1
  },
  1040: {
    /* n:"BrtSXTH14" */
  },
  1041: {
    /* n:"BrtBeginSparklineGroup", */
    T: 1
  },
  1042: {
    /* n:"BrtEndSparklineGroup", */
    T: -1
  },
  1043: {
    /* n:"BrtSparkline" */
  },
  1044: {
    /* n:"BrtSXDI14" */
  },
  1045: {
    /* n:"BrtWsFmtInfoEx14" */
  },
  1046: {
    /* n:"BrtBeginConditionalFormatting14", */
    T: 1
  },
  1047: {
    /* n:"BrtEndConditionalFormatting14", */
    T: -1
  },
  1048: {
    /* n:"BrtBeginCFRule14", */
    T: 1
  },
  1049: {
    /* n:"BrtEndCFRule14", */
    T: -1
  },
  1050: {
    /* n:"BrtCFVO14" */
  },
  1051: {
    /* n:"BrtBeginDatabar14", */
    T: 1
  },
  1052: {
    /* n:"BrtBeginIconSet14", */
    T: 1
  },
  1053: {
    /* n:"BrtDVal14", */
    f: parse_BrtDVal14
  },
  1054: {
    /* n:"BrtBeginDVals14", */
    T: 1
  },
  1055: {
    /* n:"BrtColor14" */
  },
  1056: {
    /* n:"BrtBeginSparklines", */
    T: 1
  },
  1057: {
    /* n:"BrtEndSparklines", */
    T: -1
  },
  1058: {
    /* n:"BrtBeginSparklineGroups", */
    T: 1
  },
  1059: {
    /* n:"BrtEndSparklineGroups", */
    T: -1
  },
  1061: {
    /* n:"BrtSXVD14" */
  },
  1062: {
    /* n:"BrtBeginSXView14", */
    T: 1
  },
  1063: {
    /* n:"BrtEndSXView14", */
    T: -1
  },
  1064: {
    /* n:"BrtBeginSXView16", */
    T: 1
  },
  1065: {
    /* n:"BrtEndSXView16", */
    T: -1
  },
  1066: {
    /* n:"BrtBeginPCD14", */
    T: 1
  },
  1067: {
    /* n:"BrtEndPCD14", */
    T: -1
  },
  1068: {
    /* n:"BrtBeginExtConn14", */
    T: 1
  },
  1069: {
    /* n:"BrtEndExtConn14", */
    T: -1
  },
  1070: {
    /* n:"BrtBeginSlicerCacheIDs", */
    T: 1
  },
  1071: {
    /* n:"BrtEndSlicerCacheIDs", */
    T: -1
  },
  1072: {
    /* n:"BrtBeginSlicerCacheID", */
    T: 1
  },
  1073: {
    /* n:"BrtEndSlicerCacheID", */
    T: -1
  },
  1075: {
    /* n:"BrtBeginSlicerCache", */
    T: 1
  },
  1076: {
    /* n:"BrtEndSlicerCache", */
    T: -1
  },
  1077: {
    /* n:"BrtBeginSlicerCacheDef", */
    T: 1
  },
  1078: {
    /* n:"BrtEndSlicerCacheDef", */
    T: -1
  },
  1079: {
    /* n:"BrtBeginSlicersEx", */
    T: 1
  },
  1080: {
    /* n:"BrtEndSlicersEx", */
    T: -1
  },
  1081: {
    /* n:"BrtBeginSlicerEx", */
    T: 1
  },
  1082: {
    /* n:"BrtEndSlicerEx", */
    T: -1
  },
  1083: {
    /* n:"BrtBeginSlicer", */
    T: 1
  },
  1084: {
    /* n:"BrtEndSlicer", */
    T: -1
  },
  1085: {
    /* n:"BrtSlicerCachePivotTables" */
  },
  1086: {
    /* n:"BrtBeginSlicerCacheOlapImpl", */
    T: 1
  },
  1087: {
    /* n:"BrtEndSlicerCacheOlapImpl", */
    T: -1
  },
  1088: {
    /* n:"BrtBeginSlicerCacheLevelsData", */
    T: 1
  },
  1089: {
    /* n:"BrtEndSlicerCacheLevelsData", */
    T: -1
  },
  1090: {
    /* n:"BrtBeginSlicerCacheLevelData", */
    T: 1
  },
  1091: {
    /* n:"BrtEndSlicerCacheLevelData", */
    T: -1
  },
  1092: {
    /* n:"BrtBeginSlicerCacheSiRanges", */
    T: 1
  },
  1093: {
    /* n:"BrtEndSlicerCacheSiRanges", */
    T: -1
  },
  1094: {
    /* n:"BrtBeginSlicerCacheSiRange", */
    T: 1
  },
  1095: {
    /* n:"BrtEndSlicerCacheSiRange", */
    T: -1
  },
  1096: {
    /* n:"BrtSlicerCacheOlapItem" */
  },
  1097: {
    /* n:"BrtBeginSlicerCacheSelections", */
    T: 1
  },
  1098: {
    /* n:"BrtSlicerCacheSelection" */
  },
  1099: {
    /* n:"BrtEndSlicerCacheSelections", */
    T: -1
  },
  1100: {
    /* n:"BrtBeginSlicerCacheNative", */
    T: 1
  },
  1101: {
    /* n:"BrtEndSlicerCacheNative", */
    T: -1
  },
  1102: {
    /* n:"BrtSlicerCacheNativeItem" */
  },
  1103: {
    /* n:"BrtRangeProtection14" */
  },
  1104: {
    /* n:"BrtRangeProtectionIso14" */
  },
  1105: {
    /* n:"BrtCellIgnoreEC14" */
  },
  1111: {
    /* n:"BrtList14" */
  },
  1112: {
    /* n:"BrtCFIcon" */
  },
  1113: {
    /* n:"BrtBeginSlicerCachesPivotCacheIDs", */
    T: 1
  },
  1114: {
    /* n:"BrtEndSlicerCachesPivotCacheIDs", */
    T: -1
  },
  1115: {
    /* n:"BrtBeginSlicers", */
    T: 1
  },
  1116: {
    /* n:"BrtEndSlicers", */
    T: -1
  },
  1117: {
    /* n:"BrtWbProp14" */
  },
  1118: {
    /* n:"BrtBeginSXEdit", */
    T: 1
  },
  1119: {
    /* n:"BrtEndSXEdit", */
    T: -1
  },
  1120: {
    /* n:"BrtBeginSXEdits", */
    T: 1
  },
  1121: {
    /* n:"BrtEndSXEdits", */
    T: -1
  },
  1122: {
    /* n:"BrtBeginSXChange", */
    T: 1
  },
  1123: {
    /* n:"BrtEndSXChange", */
    T: -1
  },
  1124: {
    /* n:"BrtBeginSXChanges", */
    T: 1
  },
  1125: {
    /* n:"BrtEndSXChanges", */
    T: -1
  },
  1126: {
    /* n:"BrtSXTupleItems" */
  },
  1128: {
    /* n:"BrtBeginSlicerStyle", */
    T: 1
  },
  1129: {
    /* n:"BrtEndSlicerStyle", */
    T: -1
  },
  1130: {
    /* n:"BrtSlicerStyleElement" */
  },
  1131: {
    /* n:"BrtBeginStyleSheetExt14", */
    T: 1
  },
  1132: {
    /* n:"BrtEndStyleSheetExt14", */
    T: -1
  },
  1133: {
    /* n:"BrtBeginSlicerCachesPivotCacheID", */
    T: 1
  },
  1134: {
    /* n:"BrtEndSlicerCachesPivotCacheID", */
    T: -1
  },
  1135: {
    /* n:"BrtBeginConditionalFormattings", */
    T: 1
  },
  1136: {
    /* n:"BrtEndConditionalFormattings", */
    T: -1
  },
  1137: {
    /* n:"BrtBeginPCDCalcMemExt", */
    T: 1
  },
  1138: {
    /* n:"BrtEndPCDCalcMemExt", */
    T: -1
  },
  1139: {
    /* n:"BrtBeginPCDCalcMemsExt", */
    T: 1
  },
  1140: {
    /* n:"BrtEndPCDCalcMemsExt", */
    T: -1
  },
  1141: {
    /* n:"BrtPCDField14" */
  },
  1142: {
    /* n:"BrtBeginSlicerStyles", */
    T: 1
  },
  1143: {
    /* n:"BrtEndSlicerStyles", */
    T: -1
  },
  1144: {
    /* n:"BrtBeginSlicerStyleElements", */
    T: 1
  },
  1145: {
    /* n:"BrtEndSlicerStyleElements", */
    T: -1
  },
  1146: {
    /* n:"BrtCFRuleExt" */
  },
  1147: {
    /* n:"BrtBeginSXCondFmt14", */
    T: 1
  },
  1148: {
    /* n:"BrtEndSXCondFmt14", */
    T: -1
  },
  1149: {
    /* n:"BrtBeginSXCondFmts14", */
    T: 1
  },
  1150: {
    /* n:"BrtEndSXCondFmts14", */
    T: -1
  },
  1152: {
    /* n:"BrtBeginSortCond14", */
    T: 1
  },
  1153: {
    /* n:"BrtEndSortCond14", */
    T: -1
  },
  1154: {
    /* n:"BrtEndDVals14", */
    T: -1
  },
  1155: {
    /* n:"BrtEndIconSet14", */
    T: -1
  },
  1156: {
    /* n:"BrtEndDatabar14", */
    T: -1
  },
  1157: {
    /* n:"BrtBeginColorScale14", */
    T: 1
  },
  1158: {
    /* n:"BrtEndColorScale14", */
    T: -1
  },
  1159: {
    /* n:"BrtBeginSxrules14", */
    T: 1
  },
  1160: {
    /* n:"BrtEndSxrules14", */
    T: -1
  },
  1161: {
    /* n:"BrtBeginPRule14", */
    T: 1
  },
  1162: {
    /* n:"BrtEndPRule14", */
    T: -1
  },
  1163: {
    /* n:"BrtBeginPRFilters14", */
    T: 1
  },
  1164: {
    /* n:"BrtEndPRFilters14", */
    T: -1
  },
  1165: {
    /* n:"BrtBeginPRFilter14", */
    T: 1
  },
  1166: {
    /* n:"BrtEndPRFilter14", */
    T: -1
  },
  1167: {
    /* n:"BrtBeginPRFItem14", */
    T: 1
  },
  1168: {
    /* n:"BrtEndPRFItem14", */
    T: -1
  },
  1169: {
    /* n:"BrtBeginCellIgnoreECs14", */
    T: 1
  },
  1170: {
    /* n:"BrtEndCellIgnoreECs14", */
    T: -1
  },
  1171: {
    /* n:"BrtDxf14" */
  },
  1172: {
    /* n:"BrtBeginDxF14s", */
    T: 1
  },
  1173: {
    /* n:"BrtEndDxf14s", */
    T: -1
  },
  1177: {
    /* n:"BrtFilter14" */
  },
  1178: {
    /* n:"BrtBeginCustomFilters14", */
    T: 1
  },
  1180: {
    /* n:"BrtCustomFilter14" */
  },
  1181: {
    /* n:"BrtIconFilter14" */
  },
  1182: {
    /* n:"BrtPivotCacheConnectionName" */
  },
  2048: {
    /* n:"BrtBeginDecoupledPivotCacheIDs", */
    T: 1
  },
  2049: {
    /* n:"BrtEndDecoupledPivotCacheIDs", */
    T: -1
  },
  2050: {
    /* n:"BrtDecoupledPivotCacheID" */
  },
  2051: {
    /* n:"BrtBeginPivotTableRefs", */
    T: 1
  },
  2052: {
    /* n:"BrtEndPivotTableRefs", */
    T: -1
  },
  2053: {
    /* n:"BrtPivotTableRef" */
  },
  2054: {
    /* n:"BrtSlicerCacheBookPivotTables" */
  },
  2055: {
    /* n:"BrtBeginSxvcells", */
    T: 1
  },
  2056: {
    /* n:"BrtEndSxvcells", */
    T: -1
  },
  2057: {
    /* n:"BrtBeginSxRow", */
    T: 1
  },
  2058: {
    /* n:"BrtEndSxRow", */
    T: -1
  },
  2060: {
    /* n:"BrtPcdCalcMem15" */
  },
  2067: {
    /* n:"BrtQsi15" */
  },
  2068: {
    /* n:"BrtBeginWebExtensions", */
    T: 1
  },
  2069: {
    /* n:"BrtEndWebExtensions", */
    T: -1
  },
  2070: {
    /* n:"BrtWebExtension" */
  },
  2071: {
    /* n:"BrtAbsPath15" */
  },
  2072: {
    /* n:"BrtBeginPivotTableUISettings", */
    T: 1
  },
  2073: {
    /* n:"BrtEndPivotTableUISettings", */
    T: -1
  },
  2075: {
    /* n:"BrtTableSlicerCacheIDs" */
  },
  2076: {
    /* n:"BrtTableSlicerCacheID" */
  },
  2077: {
    /* n:"BrtBeginTableSlicerCache", */
    T: 1
  },
  2078: {
    /* n:"BrtEndTableSlicerCache", */
    T: -1
  },
  2079: {
    /* n:"BrtSxFilter15" */
  },
  2080: {
    /* n:"BrtBeginTimelineCachePivotCacheIDs", */
    T: 1
  },
  2081: {
    /* n:"BrtEndTimelineCachePivotCacheIDs", */
    T: -1
  },
  2082: {
    /* n:"BrtTimelineCachePivotCacheID" */
  },
  2083: {
    /* n:"BrtBeginTimelineCacheIDs", */
    T: 1
  },
  2084: {
    /* n:"BrtEndTimelineCacheIDs", */
    T: -1
  },
  2085: {
    /* n:"BrtBeginTimelineCacheID", */
    T: 1
  },
  2086: {
    /* n:"BrtEndTimelineCacheID", */
    T: -1
  },
  2087: {
    /* n:"BrtBeginTimelinesEx", */
    T: 1
  },
  2088: {
    /* n:"BrtEndTimelinesEx", */
    T: -1
  },
  2089: {
    /* n:"BrtBeginTimelineEx", */
    T: 1
  },
  2090: {
    /* n:"BrtEndTimelineEx", */
    T: -1
  },
  2091: {
    /* n:"BrtWorkBookPr15" */
  },
  2092: {
    /* n:"BrtPCDH15" */
  },
  2093: {
    /* n:"BrtBeginTimelineStyle", */
    T: 1
  },
  2094: {
    /* n:"BrtEndTimelineStyle", */
    T: -1
  },
  2095: {
    /* n:"BrtTimelineStyleElement" */
  },
  2096: {
    /* n:"BrtBeginTimelineStylesheetExt15", */
    T: 1
  },
  2097: {
    /* n:"BrtEndTimelineStylesheetExt15", */
    T: -1
  },
  2098: {
    /* n:"BrtBeginTimelineStyles", */
    T: 1
  },
  2099: {
    /* n:"BrtEndTimelineStyles", */
    T: -1
  },
  2100: {
    /* n:"BrtBeginTimelineStyleElements", */
    T: 1
  },
  2101: {
    /* n:"BrtEndTimelineStyleElements", */
    T: -1
  },
  2102: {
    /* n:"BrtDxf15" */
  },
  2103: {
    /* n:"BrtBeginDxfs15", */
    T: 1
  },
  2104: {
    /* n:"BrtEndDxfs15", */
    T: -1
  },
  2105: {
    /* n:"BrtSlicerCacheHideItemsWithNoData" */
  },
  2106: {
    /* n:"BrtBeginItemUniqueNames", */
    T: 1
  },
  2107: {
    /* n:"BrtEndItemUniqueNames", */
    T: -1
  },
  2108: {
    /* n:"BrtItemUniqueName" */
  },
  2109: {
    /* n:"BrtBeginExtConn15", */
    T: 1
  },
  2110: {
    /* n:"BrtEndExtConn15", */
    T: -1
  },
  2111: {
    /* n:"BrtBeginOledbPr15", */
    T: 1
  },
  2112: {
    /* n:"BrtEndOledbPr15", */
    T: -1
  },
  2113: {
    /* n:"BrtBeginDataFeedPr15", */
    T: 1
  },
  2114: {
    /* n:"BrtEndDataFeedPr15", */
    T: -1
  },
  2115: {
    /* n:"BrtTextPr15" */
  },
  2116: {
    /* n:"BrtRangePr15" */
  },
  2117: {
    /* n:"BrtDbCommand15" */
  },
  2118: {
    /* n:"BrtBeginDbTables15", */
    T: 1
  },
  2119: {
    /* n:"BrtEndDbTables15", */
    T: -1
  },
  2120: {
    /* n:"BrtDbTable15" */
  },
  2121: {
    /* n:"BrtBeginDataModel", */
    T: 1
  },
  2122: {
    /* n:"BrtEndDataModel", */
    T: -1
  },
  2123: {
    /* n:"BrtBeginModelTables", */
    T: 1
  },
  2124: {
    /* n:"BrtEndModelTables", */
    T: -1
  },
  2125: {
    /* n:"BrtModelTable" */
  },
  2126: {
    /* n:"BrtBeginModelRelationships", */
    T: 1
  },
  2127: {
    /* n:"BrtEndModelRelationships", */
    T: -1
  },
  2128: {
    /* n:"BrtModelRelationship" */
  },
  2129: {
    /* n:"BrtBeginECTxtWiz15", */
    T: 1
  },
  2130: {
    /* n:"BrtEndECTxtWiz15", */
    T: -1
  },
  2131: {
    /* n:"BrtBeginECTWFldInfoLst15", */
    T: 1
  },
  2132: {
    /* n:"BrtEndECTWFldInfoLst15", */
    T: -1
  },
  2133: {
    /* n:"BrtBeginECTWFldInfo15", */
    T: 1
  },
  2134: {
    /* n:"BrtFieldListActiveItem" */
  },
  2135: {
    /* n:"BrtPivotCacheIdVersion" */
  },
  2136: {
    /* n:"BrtSXDI15" */
  },
  2137: {
    /* n:"BrtBeginModelTimeGroupings", */
    T: 1
  },
  2138: {
    /* n:"BrtEndModelTimeGroupings", */
    T: -1
  },
  2139: {
    /* n:"BrtBeginModelTimeGrouping", */
    T: 1
  },
  2140: {
    /* n:"BrtEndModelTimeGrouping", */
    T: -1
  },
  2141: {
    /* n:"BrtModelTimeGroupingCalcCol" */
  },
  3072: {
    /* n:"BrtUid" */
  },
  3073: {
    /* n:"BrtRevisionPtr" */
  },
  4096: {
    /* n:"BrtBeginDynamicArrayPr", */
    T: 1
  },
  4097: {
    /* n:"BrtEndDynamicArrayPr", */
    T: -1
  },
  5002: {
    /* n:"BrtBeginRichValueBlock", */
    T: 1
  },
  5003: {
    /* n:"BrtEndRichValueBlock", */
    T: -1
  },
  5081: {
    /* n:"BrtBeginRichFilters", */
    T: 1
  },
  5082: {
    /* n:"BrtEndRichFilters", */
    T: -1
  },
  5083: {
    /* n:"BrtRichFilter" */
  },
  5084: {
    /* n:"BrtBeginRichFilterColumn", */
    T: 1
  },
  5085: {
    /* n:"BrtEndRichFilterColumn", */
    T: -1
  },
  5086: {
    /* n:"BrtBeginCustomRichFilters", */
    T: 1
  },
  5087: {
    /* n:"BrtEndCustomRichFilters", */
    T: -1
  },
  5088: {
    /* n:"BrtCustomRichFilter" */
  },
  5089: {
    /* n:"BrtTop10RichFilter" */
  },
  5090: {
    /* n:"BrtDynamicRichFilter" */
  },
  5092: {
    /* n:"BrtBeginRichSortCondition", */
    T: 1
  },
  5093: {
    /* n:"BrtEndRichSortCondition", */
    T: -1
  },
  5094: {
    /* n:"BrtRichFilterDateGroupItem" */
  },
  5095: {
    /* n:"BrtBeginCalcFeatures", */
    T: 1
  },
  5096: {
    /* n:"BrtEndCalcFeatures", */
    T: -1
  },
  5097: {
    /* n:"BrtCalcFeature" */
  },
  5099: {
    /* n:"BrtExternalLinksPr" */
  },
  65535: { n: "" }
};
var XLSRecordEnum = {
  /* [MS-XLS] 2.3 Record Enumeration 2021-08-17 */
  6: {
    /* n:"Formula", */
    f: parse_Formula
  },
  10: {
    /* n:"EOF", */
    f: parsenoop2
  },
  12: {
    /* n:"CalcCount", */
    f: parseuint16
  },
  //
  13: {
    /* n:"CalcMode", */
    f: parseuint16
  },
  //
  14: {
    /* n:"CalcPrecision", */
    f: parsebool
  },
  //
  15: {
    /* n:"CalcRefMode", */
    f: parsebool
  },
  //
  16: {
    /* n:"CalcDelta", */
    f: parse_Xnum
  },
  //
  17: {
    /* n:"CalcIter", */
    f: parsebool
  },
  //
  18: {
    /* n:"Protect", */
    f: parsebool
  },
  19: {
    /* n:"Password", */
    f: parseuint16
  },
  20: {
    /* n:"Header", */
    f: parse_XLHeaderFooter
  },
  21: {
    /* n:"Footer", */
    f: parse_XLHeaderFooter
  },
  23: {
    /* n:"ExternSheet", */
    f: parse_ExternSheet
  },
  24: {
    /* n:"Lbl", */
    f: parse_Lbl
  },
  25: {
    /* n:"WinProtect", */
    f: parsebool
  },
  26: {
    /* n:"VerticalPageBreaks", */
  },
  27: {
    /* n:"HorizontalPageBreaks", */
  },
  28: {
    /* n:"Note", */
    f: parse_Note
  },
  29: {
    /* n:"Selection", */
  },
  34: {
    /* n:"Date1904", */
    f: parsebool
  },
  35: {
    /* n:"ExternName", */
    f: parse_ExternName
  },
  38: {
    /* n:"LeftMargin", */
    f: parse_Xnum
  },
  // *
  39: {
    /* n:"RightMargin", */
    f: parse_Xnum
  },
  // *
  40: {
    /* n:"TopMargin", */
    f: parse_Xnum
  },
  // *
  41: {
    /* n:"BottomMargin", */
    f: parse_Xnum
  },
  // *
  42: {
    /* n:"PrintRowCol", */
    f: parsebool
  },
  43: {
    /* n:"PrintGrid", */
    f: parsebool
  },
  47: {
    /* n:"FilePass", */
    f: parse_FilePass
  },
  49: {
    /* n:"Font", */
    f: parse_Font
  },
  51: {
    /* n:"PrintSize", */
    f: parseuint16
  },
  60: {
    /* n:"Continue", */
  },
  61: {
    /* n:"Window1", */
    f: parse_Window1
  },
  64: {
    /* n:"Backup", */
    f: parsebool
  },
  65: {
    /* n:"Pane", */
    f: parse_Pane
  },
  66: {
    /* n:"CodePage", */
    f: parseuint16
  },
  77: {
    /* n:"Pls", */
  },
  80: {
    /* n:"DCon", */
  },
  81: {
    /* n:"DConRef", */
  },
  82: {
    /* n:"DConName", */
  },
  85: {
    /* n:"DefColWidth", */
    f: parseuint16
  },
  89: {
    /* n:"XCT", */
  },
  90: {
    /* n:"CRN", */
  },
  91: {
    /* n:"FileSharing", */
  },
  92: {
    /* n:"WriteAccess", */
    f: parse_WriteAccess
  },
  93: {
    /* n:"Obj", */
    f: parse_Obj
  },
  94: {
    /* n:"Uncalced", */
  },
  95: {
    /* n:"CalcSaveRecalc", */
    f: parsebool
  },
  //
  96: {
    /* n:"Template", */
  },
  97: {
    /* n:"Intl", */
  },
  99: {
    /* n:"ObjProtect", */
    f: parsebool
  },
  125: {
    /* n:"ColInfo", */
    f: parse_ColInfo
  },
  128: {
    /* n:"Guts", */
    f: parse_Guts
  },
  129: {
    /* n:"WsBool", */
    f: parse_WsBool
  },
  130: {
    /* n:"GridSet", */
    f: parseuint16
  },
  131: {
    /* n:"HCenter", */
    f: parsebool
  },
  132: {
    /* n:"VCenter", */
    f: parsebool
  },
  133: {
    /* n:"BoundSheet8", */
    f: parse_BoundSheet8
  },
  134: {
    /* n:"WriteProtect", */
  },
  140: {
    /* n:"Country", */
    f: parse_Country
  },
  141: {
    /* n:"HideObj", */
    f: parseuint16
  },
  144: {
    /* n:"Sort", */
  },
  146: {
    /* n:"Palette", */
    f: parse_Palette
  },
  151: {
    /* n:"Sync", */
  },
  152: {
    /* n:"LPr", */
  },
  153: {
    /* n:"DxGCol", */
  },
  154: {
    /* n:"FnGroupName", */
  },
  155: {
    /* n:"FilterMode", */
  },
  156: {
    /* n:"BuiltInFnGroupCount", */
    f: parseuint16
  },
  157: {
    /* n:"AutoFilterInfo", */
  },
  158: {
    /* n:"AutoFilter", */
  },
  160: {
    /* n:"Scl", */
    f: parse_Scl
  },
  161: {
    /* n:"Setup", */
    f: parse_Setup
  },
  174: {
    /* n:"ScenMan", */
  },
  175: {
    /* n:"SCENARIO", */
  },
  176: {
    /* n:"SxView", */
  },
  177: {
    /* n:"Sxvd", */
  },
  178: {
    /* n:"SXVI", */
  },
  180: {
    /* n:"SxIvd", */
  },
  181: {
    /* n:"SXLI", */
  },
  182: {
    /* n:"SXPI", */
  },
  184: {
    /* n:"DocRoute", */
  },
  185: {
    /* n:"RecipName", */
  },
  189: {
    /* n:"MulRk", */
    f: parse_MulRk
  },
  190: {
    /* n:"MulBlank", */
    f: parse_MulBlank
  },
  193: {
    /* n:"Mms", */
    f: parsenoop2
  },
  197: {
    /* n:"SXDI", */
  },
  198: {
    /* n:"SXDB", */
  },
  199: {
    /* n:"SXFDB", */
  },
  200: {
    /* n:"SXDBB", */
  },
  201: {
    /* n:"SXNum", */
  },
  202: {
    /* n:"SxBool", */
    f: parsebool
  },
  203: {
    /* n:"SxErr", */
  },
  204: {
    /* n:"SXInt", */
  },
  205: {
    /* n:"SXString", */
  },
  206: {
    /* n:"SXDtr", */
  },
  207: {
    /* n:"SxNil", */
  },
  208: {
    /* n:"SXTbl", */
  },
  209: {
    /* n:"SXTBRGIITM", */
  },
  210: {
    /* n:"SxTbpg", */
  },
  211: {
    /* n:"ObProj", */
  },
  213: {
    /* n:"SXStreamID", */
  },
  215: {
    /* n:"DBCell", */
  },
  216: {
    /* n:"SXRng", */
  },
  217: {
    /* n:"SxIsxoper", */
  },
  218: {
    /* n:"BookBool", */
    f: parseuint16
  },
  220: {
    /* n:"DbOrParamQry", */
  },
  221: {
    /* n:"ScenarioProtect", */
    f: parsebool
  },
  222: {
    /* n:"OleObjectSize", */
  },
  224: {
    /* n:"XF", */
    f: parse_XF
  },
  225: {
    /* n:"InterfaceHdr", */
    f: parse_InterfaceHdr
  },
  226: {
    /* n:"InterfaceEnd", */
    f: parsenoop2
  },
  227: {
    /* n:"SXVS", */
  },
  229: {
    /* n:"MergeCells", */
    f: parse_MergeCells
  },
  233: {
    /* n:"BkHim", */
  },
  235: {
    /* n:"MsoDrawingGroup", */
  },
  236: {
    /* n:"MsoDrawing", */
  },
  237: {
    /* n:"MsoDrawingSelection", */
  },
  239: {
    /* n:"PhoneticInfo", */
  },
  240: {
    /* n:"SxRule", */
  },
  241: {
    /* n:"SXEx", */
  },
  242: {
    /* n:"SxFilt", */
  },
  244: {
    /* n:"SxDXF", */
  },
  245: {
    /* n:"SxItm", */
  },
  246: {
    /* n:"SxName", */
  },
  247: {
    /* n:"SxSelect", */
  },
  248: {
    /* n:"SXPair", */
  },
  249: {
    /* n:"SxFmla", */
  },
  251: {
    /* n:"SxFormat", */
  },
  252: {
    /* n:"SST", */
    f: parse_SST
  },
  253: {
    /* n:"LabelSst", */
    f: parse_LabelSst
  },
  255: {
    /* n:"ExtSST", */
    f: parse_ExtSST
  },
  256: {
    /* n:"SXVDEx", */
  },
  259: {
    /* n:"SXFormula", */
  },
  290: {
    /* n:"SXDBEx", */
  },
  311: {
    /* n:"RRDInsDel", */
  },
  312: {
    /* n:"RRDHead", */
  },
  315: {
    /* n:"RRDChgCell", */
  },
  317: {
    /* n:"RRTabId", */
    f: parseuint16a
  },
  318: {
    /* n:"RRDRenSheet", */
  },
  319: {
    /* n:"RRSort", */
  },
  320: {
    /* n:"RRDMove", */
  },
  330: {
    /* n:"RRFormat", */
  },
  331: {
    /* n:"RRAutoFmt", */
  },
  333: {
    /* n:"RRInsertSh", */
  },
  334: {
    /* n:"RRDMoveBegin", */
  },
  335: {
    /* n:"RRDMoveEnd", */
  },
  336: {
    /* n:"RRDInsDelBegin", */
  },
  337: {
    /* n:"RRDInsDelEnd", */
  },
  338: {
    /* n:"RRDConflict", */
  },
  339: {
    /* n:"RRDDefName", */
  },
  340: {
    /* n:"RRDRstEtxp", */
  },
  351: {
    /* n:"LRng", */
  },
  352: {
    /* n:"UsesELFs", */
    f: parsebool
  },
  353: {
    /* n:"DSF", */
    f: parsenoop2
  },
  401: {
    /* n:"CUsr", */
  },
  402: {
    /* n:"CbUsr", */
  },
  403: {
    /* n:"UsrInfo", */
  },
  404: {
    /* n:"UsrExcl", */
  },
  405: {
    /* n:"FileLock", */
  },
  406: {
    /* n:"RRDInfo", */
  },
  407: {
    /* n:"BCUsrs", */
  },
  408: {
    /* n:"UsrChk", */
  },
  425: {
    /* n:"UserBView", */
  },
  426: {
    /* n:"UserSViewBegin", */
  },
  427: {
    /* n:"UserSViewEnd", */
  },
  428: {
    /* n:"RRDUserView", */
  },
  429: {
    /* n:"Qsi", */
  },
  430: {
    /* n:"SupBook", */
    f: parse_SupBook
  },
  431: {
    /* n:"Prot4Rev", */
    f: parsebool
  },
  432: {
    /* n:"CondFmt", */
  },
  433: {
    /* n:"CF", */
  },
  434: {
    /* n:"DVal", */
  },
  437: {
    /* n:"DConBin", */
  },
  438: {
    /* n:"TxO", */
    f: parse_TxO
  },
  439: {
    /* n:"RefreshAll", */
    f: parsebool
  },
  //
  440: {
    /* n:"HLink", */
    f: parse_HLink
  },
  441: {
    /* n:"Lel", */
  },
  442: {
    /* n:"CodeName", */
    f: parse_XLUnicodeString
  },
  443: {
    /* n:"SXFDBType", */
  },
  444: {
    /* n:"Prot4RevPass", */
    f: parseuint16
  },
  445: {
    /* n:"ObNoMacros", */
  },
  446: {
    /* n:"Dv", */
  },
  448: {
    /* n:"Excel9File", */
    f: parsenoop2
  },
  449: {
    /* n:"RecalcId", */
    f: parse_RecalcId,
    r: 2
  },
  450: {
    /* n:"EntExU2", */
    f: parsenoop2
  },
  512: {
    /* n:"Dimensions", */
    f: parse_Dimensions
  },
  513: {
    /* n:"Blank", */
    f: parse_Blank
  },
  515: {
    /* n:"Number", */
    f: parse_Number
  },
  516: {
    /* n:"Label", */
    f: parse_Label
  },
  517: {
    /* n:"BoolErr", */
    f: parse_BoolErr
  },
  519: {
    /* n:"String", */
    f: parse_String
  },
  520: {
    /* n:"Row", */
    f: parse_Row
  },
  523: {
    /* n:"Index", */
  },
  545: {
    /* n:"Array", */
    f: parse_Array
  },
  549: {
    /* n:"DefaultRowHeight", */
    f: parse_DefaultRowHeight
  },
  566: {
    /* n:"Table", */
  },
  574: {
    /* n:"Window2", */
    f: parse_Window2
  },
  638: {
    /* n:"RK", */
    f: parse_RK
  },
  659: {
    /* n:"Style", */
  },
  1048: {
    /* n:"BigName", */
  },
  1054: {
    /* n:"Format", */
    f: parse_Format
  },
  1084: {
    /* n:"ContinueBigName", */
  },
  1212: {
    /* n:"ShrFmla", */
    f: parse_ShrFmla
  },
  2048: {
    /* n:"HLinkTooltip", */
    f: parse_HLinkTooltip
  },
  2049: {
    /* n:"WebPub", */
  },
  2050: {
    /* n:"QsiSXTag", */
  },
  2051: {
    /* n:"DBQueryExt", */
  },
  2052: {
    /* n:"ExtString", */
  },
  2053: {
    /* n:"TxtQry", */
  },
  2054: {
    /* n:"Qsir", */
  },
  2055: {
    /* n:"Qsif", */
  },
  2056: {
    /* n:"RRDTQSIF", */
  },
  2057: {
    /* n:"BOF", */
    f: parse_BOF
  },
  2058: {
    /* n:"OleDbConn", */
  },
  2059: {
    /* n:"WOpt", */
  },
  2060: {
    /* n:"SXViewEx", */
  },
  2061: {
    /* n:"SXTH", */
  },
  2062: {
    /* n:"SXPIEx", */
  },
  2063: {
    /* n:"SXVDTEx", */
  },
  2064: {
    /* n:"SXViewEx9", */
  },
  2066: {
    /* n:"ContinueFrt", */
  },
  2067: {
    /* n:"RealTimeData", */
  },
  2128: {
    /* n:"ChartFrtInfo", */
  },
  2129: {
    /* n:"FrtWrapper", */
  },
  2130: {
    /* n:"StartBlock", */
  },
  2131: {
    /* n:"EndBlock", */
  },
  2132: {
    /* n:"StartObject", */
  },
  2133: {
    /* n:"EndObject", */
  },
  2134: {
    /* n:"CatLab", */
  },
  2135: {
    /* n:"YMult", */
  },
  2136: {
    /* n:"SXViewLink", */
  },
  2137: {
    /* n:"PivotChartBits", */
  },
  2138: {
    /* n:"FrtFontList", */
  },
  2146: {
    /* n:"SheetExt", */
  },
  2147: {
    /* n:"BookExt", */
    r: 12
  },
  2148: {
    /* n:"SXAddl", */
  },
  2149: {
    /* n:"CrErr", */
  },
  2150: {
    /* n:"HFPicture", */
  },
  2151: {
    /* n:"FeatHdr", */
    f: parsenoop2
  },
  2152: {
    /* n:"Feat", */
  },
  2154: {
    /* n:"DataLabExt", */
  },
  2155: {
    /* n:"DataLabExtContents", */
  },
  2156: {
    /* n:"CellWatch", */
  },
  2161: {
    /* n:"FeatHdr11", */
  },
  2162: {
    /* n:"Feature11", */
  },
  2164: {
    /* n:"DropDownObjIds", */
  },
  2165: {
    /* n:"ContinueFrt11", */
  },
  2166: {
    /* n:"DConn", */
  },
  2167: {
    /* n:"List12", */
  },
  2168: {
    /* n:"Feature12", */
  },
  2169: {
    /* n:"CondFmt12", */
  },
  2170: {
    /* n:"CF12", */
  },
  2171: {
    /* n:"CFEx", */
  },
  2172: {
    /* n:"XFCRC", */
    f: parse_XFCRC,
    r: 12
  },
  2173: {
    /* n:"XFExt", */
    f: parse_XFExt,
    r: 12
  },
  2174: {
    /* n:"AutoFilter12", */
  },
  2175: {
    /* n:"ContinueFrt12", */
  },
  2180: {
    /* n:"MDTInfo", */
  },
  2181: {
    /* n:"MDXStr", */
  },
  2182: {
    /* n:"MDXTuple", */
  },
  2183: {
    /* n:"MDXSet", */
  },
  2184: {
    /* n:"MDXProp", */
  },
  2185: {
    /* n:"MDXKPI", */
  },
  2186: {
    /* n:"MDB", */
  },
  2187: {
    /* n:"PLV", */
  },
  2188: {
    /* n:"Compat12", */
    f: parsebool,
    r: 12
  },
  2189: {
    /* n:"DXF", */
  },
  2190: {
    /* n:"TableStyles", */
    r: 12
  },
  2191: {
    /* n:"TableStyle", */
  },
  2192: {
    /* n:"TableStyleElement", */
  },
  2194: {
    /* n:"StyleExt", */
  },
  2195: {
    /* n:"NamePublish", */
  },
  2196: {
    /* n:"NameCmt", */
    f: parse_NameCmt,
    r: 12
  },
  2197: {
    /* n:"SortData", */
  },
  2198: {
    /* n:"Theme", */
    f: parse_Theme,
    r: 12
  },
  2199: {
    /* n:"GUIDTypeLib", */
  },
  2200: {
    /* n:"FnGrp12", */
  },
  2201: {
    /* n:"NameFnGrp12", */
  },
  2202: {
    /* n:"MTRSettings", */
    f: parse_MTRSettings,
    r: 12
  },
  2203: {
    /* n:"CompressPictures", */
    f: parsenoop2
  },
  2204: {
    /* n:"HeaderFooter", */
  },
  2205: {
    /* n:"CrtLayout12", */
  },
  2206: {
    /* n:"CrtMlFrt", */
  },
  2207: {
    /* n:"CrtMlFrtContinue", */
  },
  2211: {
    /* n:"ForceFullCalculation", */
    f: parse_ForceFullCalculation
  },
  2212: {
    /* n:"ShapePropsStream", */
  },
  2213: {
    /* n:"TextPropsStream", */
  },
  2214: {
    /* n:"RichTextStream", */
  },
  2215: {
    /* n:"CrtLayout12A", */
  },
  4097: {
    /* n:"Units", */
  },
  4098: {
    /* n:"Chart", */
  },
  4099: {
    /* n:"Series", */
  },
  4102: {
    /* n:"DataFormat", */
  },
  4103: {
    /* n:"LineFormat", */
  },
  4105: {
    /* n:"MarkerFormat", */
  },
  4106: {
    /* n:"AreaFormat", */
  },
  4107: {
    /* n:"PieFormat", */
  },
  4108: {
    /* n:"AttachedLabel", */
  },
  4109: {
    /* n:"SeriesText", */
  },
  4116: {
    /* n:"ChartFormat", */
  },
  4117: {
    /* n:"Legend", */
  },
  4118: {
    /* n:"SeriesList", */
  },
  4119: {
    /* n:"Bar", */
  },
  4120: {
    /* n:"Line", */
  },
  4121: {
    /* n:"Pie", */
  },
  4122: {
    /* n:"Area", */
  },
  4123: {
    /* n:"Scatter", */
  },
  4124: {
    /* n:"CrtLine", */
  },
  4125: {
    /* n:"Axis", */
  },
  4126: {
    /* n:"Tick", */
  },
  4127: {
    /* n:"ValueRange", */
  },
  4128: {
    /* n:"CatSerRange", */
  },
  4129: {
    /* n:"AxisLine", */
  },
  4130: {
    /* n:"CrtLink", */
  },
  4132: {
    /* n:"DefaultText", */
  },
  4133: {
    /* n:"Text", */
  },
  4134: {
    /* n:"FontX", */
    f: parseuint16
  },
  4135: {
    /* n:"ObjectLink", */
  },
  4146: {
    /* n:"Frame", */
  },
  4147: {
    /* n:"Begin", */
  },
  4148: {
    /* n:"End", */
  },
  4149: {
    /* n:"PlotArea", */
  },
  4154: {
    /* n:"Chart3d", */
  },
  4156: {
    /* n:"PicF", */
  },
  4157: {
    /* n:"DropBar", */
  },
  4158: {
    /* n:"Radar", */
  },
  4159: {
    /* n:"Surf", */
  },
  4160: {
    /* n:"RadarArea", */
  },
  4161: {
    /* n:"AxisParent", */
  },
  4163: {
    /* n:"LegendException", */
  },
  4164: {
    /* n:"ShtProps", */
    f: parse_ShtProps
  },
  4165: {
    /* n:"SerToCrt", */
  },
  4166: {
    /* n:"AxesUsed", */
  },
  4168: {
    /* n:"SBaseRef", */
  },
  4170: {
    /* n:"SerParent", */
  },
  4171: {
    /* n:"SerAuxTrend", */
  },
  4174: {
    /* n:"IFmtRecord", */
  },
  4175: {
    /* n:"Pos", */
  },
  4176: {
    /* n:"AlRuns", */
  },
  4177: {
    /* n:"BRAI", */
  },
  4187: {
    /* n:"SerAuxErrBar", */
  },
  4188: {
    /* n:"ClrtClient", */
    f: parse_ClrtClient
  },
  4189: {
    /* n:"SerFmt", */
  },
  4191: {
    /* n:"Chart3DBarShape", */
  },
  4192: {
    /* n:"Fbi", */
  },
  4193: {
    /* n:"BopPop", */
  },
  4194: {
    /* n:"AxcExt", */
  },
  4195: {
    /* n:"Dat", */
  },
  4196: {
    /* n:"PlotGrowth", */
  },
  4197: {
    /* n:"SIIndex", */
  },
  4198: {
    /* n:"GelFrame", */
  },
  4199: {
    /* n:"BopPopCustom", */
  },
  4200: {
    /* n:"Fbi2", */
  },
  0: {
    /* n:"Dimensions", */
    f: parse_Dimensions
  },
  1: {
    /* n:"BIFF2BLANK", */
  },
  2: {
    /* n:"BIFF2INT", */
    f: parse_BIFF2INT
  },
  3: {
    /* n:"BIFF2NUM", */
    f: parse_BIFF2NUM
  },
  4: {
    /* n:"BIFF2STR", */
    f: parse_BIFF2STR
  },
  5: {
    /* n:"BIFF2BOOLERR", */
    f: parse_BIFF2BOOLERR
  },
  7: {
    /* n:"String", */
    f: parse_BIFF2STRING
  },
  8: {
    /* n:"BIFF2ROW", */
  },
  9: {
    /* n:"BOF", */
    f: parse_BOF
  },
  11: {
    /* n:"Index", */
  },
  22: {
    /* n:"ExternCount", */
    f: parseuint16
  },
  30: {
    /* n:"BIFF2FORMAT", */
    f: parse_BIFF2Format
  },
  31: {
    /* n:"BIFF2FMTCNT", */
  },
  /* 16-bit cnt of BIFF2FORMAT records */
  32: {
    /* n:"BIFF2COLINFO", */
  },
  33: {
    /* n:"Array", */
    f: parse_Array
  },
  36: {
    /* n:"COLWIDTH", */
  },
  37: {
    /* n:"DefaultRowHeight", */
    f: parse_DefaultRowHeight
  },
  // 0x002c ??
  // 0x002d ??
  // 0x002e ??
  // 0x0030 FONTCOUNT: number of fonts
  50: {
    /* n:"BIFF2FONTXTRA", */
    f: parse_BIFF2FONTXTRA
  },
  // 0x0035: INFOOPTS
  // 0x0036: TABLE (BIFF2 only)
  // 0x0037: TABLE2 (BIFF2 only)
  // 0x0038: WNDESK
  // 0x0039 ??
  // 0x003a: BEGINPREF
  // 0x003b: ENDPREF
  62: {
    /* n:"BIFF2WINDOW2", */
  },
  // 0x003f ??
  // 0x0046: SHOWSCROLL
  // 0x0047: SHOWFORMULA
  // 0x0048: STATUSBAR
  // 0x0049: SHORTMENUS
  // 0x004A:
  // 0x004B:
  // 0x004C:
  // 0x004E:
  // 0x004F:
  // 0x0058: TOOLBAR (BIFF3)
  /* - - - */
  52: {
    /* n:"DDEObjName", */
  },
  67: {
    /* n:"BIFF2XF", */
    f: parse_BIFF2XF
  },
  68: {
    /* n:"BIFF2XFINDEX", */
    f: parseuint16
  },
  69: {
    /* n:"BIFF2FONTCLR", */
  },
  86: {
    /* n:"BIFF4FMTCNT", */
  },
  /* 16-bit cnt, similar to BIFF2 */
  126: {
    /* n:"RK", */
  },
  /* Not necessarily same as 0x027e */
  127: {
    /* n:"ImData", */
    f: parse_ImData
  },
  135: {
    /* n:"Addin", */
  },
  136: {
    /* n:"Edg", */
  },
  137: {
    /* n:"Pub", */
  },
  // 0x8A
  // 0x8B LH: alternate menu key flag (BIFF3/4)
  // 0x8E
  143: {
    /* n:"BIFF4SheetInfo", */
    f: parse_BIFF4SheetInfo
  },
  145: {
    /* n:"Sub", */
  },
  // 0x93 STYLE
  148: {
    /* n:"LHRecord", */
  },
  149: {
    /* n:"LHNGraph", */
  },
  150: {
    /* n:"Sound", */
  },
  // 0xA2 FNPROTO: function prototypes (BIFF4)
  // 0xA3
  // 0xA8
  169: {
    /* n:"CoordList", */
  },
  171: {
    /* n:"GCW", */
  },
  188: {
    /* n:"ShrFmla", */
  },
  /* Not necessarily same as 0x04bc */
  191: {
    /* n:"ToolbarHdr", */
  },
  192: {
    /* n:"ToolbarEnd", */
  },
  194: {
    /* n:"AddMenu", */
  },
  195: {
    /* n:"DelMenu", */
  },
  214: {
    /* n:"RString", */
    f: parse_RString
  },
  223: {
    /* n:"UDDesc", */
  },
  234: {
    /* n:"TabIdConf", */
  },
  354: {
    /* n:"XL5Modify", */
  },
  421: {
    /* n:"FileSharing2", */
  },
  518: {
    /* n:"Formula", */
    f: parse_Formula
  },
  521: {
    /* n:"BOF", */
    f: parse_BOF
  },
  536: {
    /* n:"Lbl", */
    f: parse_Lbl
  },
  547: {
    /* n:"ExternName", */
    f: parse_ExternName
  },
  561: {
    /* n:"Font", */
  },
  579: {
    /* n:"BIFF3XF", */
    f: parse_BIFF3XF
  },
  1030: {
    /* n:"Formula", */
    f: parse_Formula
  },
  1033: {
    /* n:"BOF", */
    f: parse_BOF
  },
  1091: {
    /* n:"BIFF4XF", */
    f: parse_BIFF4XF
  },
  2157: {
    /* n:"FeatInfo", */
  },
  2163: {
    /* n:"FeatInfo11", */
  },
  2177: {
    /* n:"SXAddl12", */
  },
  2240: {
    /* n:"AutoWebPub", */
  },
  2241: {
    /* n:"ListObj", */
  },
  2242: {
    /* n:"ListField", */
  },
  2243: {
    /* n:"ListDV", */
  },
  2244: {
    /* n:"ListCondFmt", */
  },
  2245: {
    /* n:"ListCF", */
  },
  2246: {
    /* n:"FMQry", */
  },
  2247: {
    /* n:"FMSQry", */
  },
  2248: {
    /* n:"PLV", */
  },
  2249: {
    /* n:"LnExt", */
  },
  2250: {
    /* n:"MkrExt", */
  },
  2251: {
    /* n:"CrtCoopt", */
  },
  2262: {
    /* n:"FRTArchId$", */
    r: 12
  },
  /* --- multiplan 4 records --- */
  101: {
    /* n:"", */
  },
  // one per window
  102: {
    /* n:"", */
  },
  // calc settings
  105: {
    /* n:"", */
  },
  // print header
  106: {
    /* n:"", */
  },
  // print footer
  107: {
    /* n:"", */
  },
  // print settings
  109: {
    /* n:"", */
  },
  // one per window
  112: {
    /* n:"", */
  },
  // includes default col width
  114: {
    /* n:"", */
  },
  // includes selected cell
  29282: {}
};
function write_biff_rec(ba, type, payload, length) {
  var t6 = type;
  if (isNaN(t6)) return;
  var len = length || (payload || []).length || 0;
  var o9 = ba.next(4);
  o9.write_shift(2, t6);
  o9.write_shift(2, len);
  if (
    /*:: len != null &&*/
    len > 0 && is_buf(payload)
  ) ba.push(payload);
}
function html_to_sheet(str2, _opts) {
  var opts = _opts || {};
  var dense = opts.dense != null ? opts.dense : DENSE;
  var ws = {};
  if (dense) ws["!data"] = [];
  str2 = str_remove_ng(str2, "<!--", "-->");
  var mtch = str2.match(/<table/i);
  if (!mtch) throw new Error("Invalid HTML: could not find <table>");
  var mtch2 = str2.match(/<\/table/i);
  var i7 = mtch.index, j3 = mtch2 && mtch2.index || str2.length;
  var rows = split_regex(str2.slice(i7, j3), /(:?<tr[^<>]*>)/i, "<tr>");
  var R3 = -1, C3 = 0, RS = 0, CS = 0;
  var range2 = { s: { r: 1e7, c: 1e7 }, e: { r: 0, c: 0 } };
  var merges = [];
  for (i7 = 0; i7 < rows.length; ++i7) {
    var row = rows[i7].trim();
    var hd = row.slice(0, 3).toLowerCase();
    if (hd == "<tr") {
      ++R3;
      if (opts.sheetRows && opts.sheetRows <= R3) {
        --R3;
        break;
      }
      C3 = 0;
      continue;
    }
    if (hd != "<td" && hd != "<th") continue;
    var cells = row.split(/<\/t[dh]>/i);
    for (j3 = 0; j3 < cells.length; ++j3) {
      var cell = cells[j3].trim();
      if (!cell.match(/<t[dh]/i)) continue;
      var m4 = cell, cc = 0;
      while (m4.charAt(0) == "<" && (cc = m4.indexOf(">")) > -1) m4 = m4.slice(cc + 1);
      for (var midx = 0; midx < merges.length; ++midx) {
        var _merge = merges[midx];
        if (_merge.s.c == C3 && _merge.s.r < R3 && R3 <= _merge.e.r) {
          C3 = _merge.e.c + 1;
          midx = -1;
        }
      }
      var tag = parsexmltag(cell.slice(0, cell.indexOf(">")));
      CS = tag.colspan ? +tag.colspan : 1;
      if ((RS = +tag.rowspan) > 1 || CS > 1) merges.push({ s: { r: R3, c: C3 }, e: { r: R3 + (RS || 1) - 1, c: C3 + CS - 1 } });
      var _t = tag.t || tag["data-t"] || "";
      if (!m4.length) {
        C3 += CS;
        continue;
      }
      m4 = htmldecode(m4);
      if (range2.s.r > R3) range2.s.r = R3;
      if (range2.e.r < R3) range2.e.r = R3;
      if (range2.s.c > C3) range2.s.c = C3;
      if (range2.e.c < C3) range2.e.c = C3;
      if (!m4.length) {
        C3 += CS;
        continue;
      }
      var o9 = { t: "s", v: m4 };
      if (opts.raw || !m4.trim().length || _t == "s") {
      } else if (m4 === "TRUE") o9 = { t: "b", v: true };
      else if (m4 === "FALSE") o9 = { t: "b", v: false };
      else if (!isNaN(fuzzynum(m4))) o9 = { t: "n", v: fuzzynum(m4) };
      else if (!isNaN(fuzzydate(m4).getDate())) {
        o9 = { t: "d", v: parseDate(m4) };
        if (opts.UTC === false) o9.v = utc_to_local(o9.v);
        if (!opts.cellDates) o9 = { t: "n", v: datenum(o9.v) };
        o9.z = opts.dateNF || table_fmt[14];
      } else if (m4.charCodeAt(0) == 35 && RBErr[m4] != null) {
        o9.t = "e";
        o9.w = m4;
        o9.v = RBErr[m4];
      }
      if (o9.cellText !== false) o9.w = m4;
      if (dense) {
        if (!ws["!data"][R3]) ws["!data"][R3] = [];
        ws["!data"][R3][C3] = o9;
      } else ws[encode_cell({ r: R3, c: C3 })] = o9;
      C3 += CS;
    }
  }
  ws["!ref"] = encode_range(range2);
  if (merges.length) ws["!merges"] = merges;
  return ws;
}
function make_html_row(ws, r8, R3, o9) {
  var M4 = ws["!merges"] || [];
  var oo = [];
  var sp = {};
  var dense = ws["!data"] != null;
  for (var C3 = r8.s.c; C3 <= r8.e.c; ++C3) {
    var RS = 0, CS = 0;
    for (var j3 = 0; j3 < M4.length; ++j3) {
      if (M4[j3].s.r > R3 || M4[j3].s.c > C3) continue;
      if (M4[j3].e.r < R3 || M4[j3].e.c < C3) continue;
      if (M4[j3].s.r < R3 || M4[j3].s.c < C3) {
        RS = -1;
        break;
      }
      RS = M4[j3].e.r - M4[j3].s.r + 1;
      CS = M4[j3].e.c - M4[j3].s.c + 1;
      break;
    }
    if (RS < 0) continue;
    var coord = encode_col(C3) + encode_row(R3);
    var cell = dense ? (ws["!data"][R3] || [])[C3] : ws[coord];
    if (cell && cell.t == "n" && cell.v != null && !isFinite(cell.v)) {
      if (isNaN(cell.v)) cell = { t: "e", v: 36, w: BErr[36] };
      else cell = { t: "e", v: 7, w: BErr[7] };
    }
    var w3 = cell && cell.v != null && (cell.h || escapehtml(cell.w || (format_cell(cell), cell.w) || "")) || "";
    sp = {};
    if (RS > 1) sp.rowspan = RS;
    if (CS > 1) sp.colspan = CS;
    if (o9.editable) w3 = '<span contenteditable="true">' + w3 + "</span>";
    else if (cell) {
      sp["data-t"] = cell && cell.t || "z";
      if (cell.v != null) sp["data-v"] = escapehtml(cell.v instanceof Date ? cell.v.toISOString() : cell.v);
      if (cell.z != null) sp["data-z"] = cell.z;
      if (cell.l && (cell.l.Target || "#").charAt(0) != "#") w3 = '<a href="' + escapehtml(cell.l.Target) + '">' + w3 + "</a>";
    }
    sp.id = (o9.id || "sjs") + "-" + coord;
    oo.push(writextag("td", w3, sp));
  }
  var preamble = "<tr>";
  return preamble + oo.join("") + "</tr>";
}
var HTML_BEGIN = '<html><head><meta charset="utf-8"/><title>SheetJS Table Export</title></head><body>';
var HTML_END = "</body></html>";
function html_to_workbook(str2, opts) {
  var mtch = str_match_xml_ig(str2, "table");
  if (!mtch || mtch.length == 0) throw new Error("Invalid HTML: could not find <table>");
  if (mtch.length == 1) {
    var w3 = sheet_to_workbook(html_to_sheet(mtch[0], opts), opts);
    w3.bookType = "html";
    return w3;
  }
  var wb = book_new();
  mtch.forEach(function(s6, idx) {
    book_append_sheet(wb, html_to_sheet(s6, opts), "Sheet" + (idx + 1));
  });
  wb.bookType = "html";
  return wb;
}
function make_html_preamble(ws, R3, o9) {
  var out = [];
  return out.join("") + "<table" + (o9 && o9.id ? ' id="' + o9.id + '"' : "") + ">";
}
function sheet_to_html(ws, opts) {
  var o9 = opts || {};
  var header = o9.header != null ? o9.header : HTML_BEGIN;
  var footer = o9.footer != null ? o9.footer : HTML_END;
  var out = [header];
  var r8 = decode_range(ws["!ref"] || "A1");
  out.push(make_html_preamble(ws, r8, o9));
  if (ws["!ref"]) for (var R3 = r8.s.r; R3 <= r8.e.r; ++R3) out.push(make_html_row(ws, r8, R3, o9));
  out.push("</table>" + footer);
  return out.join("");
}
function sheet_add_dom(ws, table, _opts) {
  var rows = table.rows;
  if (!rows) {
    throw "Unsupported origin when " + table.tagName + " is not a TABLE";
  }
  var opts = _opts || {};
  var dense = ws["!data"] != null;
  var or_R = 0, or_C = 0;
  if (opts.origin != null) {
    if (typeof opts.origin == "number") or_R = opts.origin;
    else {
      var _origin = typeof opts.origin == "string" ? decode_cell(opts.origin) : opts.origin;
      or_R = _origin.r;
      or_C = _origin.c;
    }
  }
  var sheetRows = Math.min(opts.sheetRows || 1e7, rows.length);
  var range2 = { s: { r: 0, c: 0 }, e: { r: or_R, c: or_C } };
  if (ws["!ref"]) {
    var _range = decode_range(ws["!ref"]);
    range2.s.r = Math.min(range2.s.r, _range.s.r);
    range2.s.c = Math.min(range2.s.c, _range.s.c);
    range2.e.r = Math.max(range2.e.r, _range.e.r);
    range2.e.c = Math.max(range2.e.c, _range.e.c);
    if (or_R == -1) range2.e.r = or_R = _range.e.r + 1;
  }
  var merges = [], midx = 0;
  var rowinfo = ws["!rows"] || (ws["!rows"] = []);
  var _R = 0, R3 = 0, _C = 0, C3 = 0, RS = 0, CS = 0;
  if (!ws["!cols"]) ws["!cols"] = [];
  for (; _R < rows.length && R3 < sheetRows; ++_R) {
    var row = rows[_R];
    if (is_dom_element_hidden(row)) {
      if (opts.display) continue;
      rowinfo[R3] = { hidden: true };
    }
    var elts = row.cells;
    for (_C = C3 = 0; _C < elts.length; ++_C) {
      var elt = elts[_C];
      if (opts.display && is_dom_element_hidden(elt)) continue;
      var v4 = elt.hasAttribute("data-v") ? elt.getAttribute("data-v") : elt.hasAttribute("v") ? elt.getAttribute("v") : htmldecode(elt.innerHTML);
      var z3 = elt.getAttribute("data-z") || elt.getAttribute("z");
      for (midx = 0; midx < merges.length; ++midx) {
        var m4 = merges[midx];
        if (m4.s.c == C3 + or_C && m4.s.r < R3 + or_R && R3 + or_R <= m4.e.r) {
          C3 = m4.e.c + 1 - or_C;
          midx = -1;
        }
      }
      CS = +elt.getAttribute("colspan") || 1;
      if ((RS = +elt.getAttribute("rowspan") || 1) > 1 || CS > 1) merges.push({ s: { r: R3 + or_R, c: C3 + or_C }, e: { r: R3 + or_R + (RS || 1) - 1, c: C3 + or_C + (CS || 1) - 1 } });
      var o9 = { t: "s", v: v4 };
      var _t = elt.getAttribute("data-t") || elt.getAttribute("t") || "";
      if (v4 != null) {
        if (v4.length == 0) o9.t = _t || "z";
        else if (opts.raw || v4.trim().length == 0 || _t == "s") {
        } else if (_t == "e" && BErr[+v4]) o9 = { t: "e", v: +v4, w: BErr[+v4] };
        else if (v4 === "TRUE") o9 = { t: "b", v: true };
        else if (v4 === "FALSE") o9 = { t: "b", v: false };
        else if (!isNaN(fuzzynum(v4))) o9 = { t: "n", v: fuzzynum(v4) };
        else if (!isNaN(fuzzydate(v4).getDate())) {
          o9 = { t: "d", v: parseDate(v4) };
          if (opts.UTC) o9.v = local_to_utc(o9.v);
          if (!opts.cellDates) o9 = { t: "n", v: datenum(o9.v) };
          o9.z = opts.dateNF || table_fmt[14];
        } else if (v4.charCodeAt(0) == 35 && RBErr[v4] != null) o9 = { t: "e", v: RBErr[v4], w: v4 };
      }
      if (o9.z === void 0 && z3 != null) o9.z = z3;
      var l5 = "", Aelts = elt.getElementsByTagName("A");
      if (Aelts && Aelts.length) {
        for (var Aelti = 0; Aelti < Aelts.length; ++Aelti) if (Aelts[Aelti].hasAttribute("href")) {
          l5 = Aelts[Aelti].getAttribute("href");
          if (l5.charAt(0) != "#") break;
        }
      }
      if (l5 && l5.charAt(0) != "#" && l5.slice(0, 11).toLowerCase() != "javascript:") o9.l = { Target: l5 };
      if (dense) {
        if (!ws["!data"][R3 + or_R]) ws["!data"][R3 + or_R] = [];
        ws["!data"][R3 + or_R][C3 + or_C] = o9;
      } else ws[encode_cell({ c: C3 + or_C, r: R3 + or_R })] = o9;
      if (range2.e.c < C3 + or_C) range2.e.c = C3 + or_C;
      C3 += CS;
    }
    ++R3;
  }
  if (merges.length) ws["!merges"] = (ws["!merges"] || []).concat(merges);
  range2.e.r = Math.max(range2.e.r, R3 - 1 + or_R);
  ws["!ref"] = encode_range(range2);
  if (R3 >= sheetRows) ws["!fullref"] = encode_range((range2.e.r = rows.length - _R + R3 - 1 + or_R, range2));
  return ws;
}
function parse_dom_table(table, _opts) {
  var opts = _opts || {};
  var ws = {};
  if (opts.dense) ws["!data"] = [];
  return sheet_add_dom(ws, table, _opts);
}
function table_to_book(table, opts) {
  var o9 = sheet_to_workbook(parse_dom_table(table, opts), opts);
  return o9;
}
function is_dom_element_hidden(element) {
  var display = "";
  var get_computed_style = get_get_computed_style_function(element);
  if (get_computed_style) display = get_computed_style(element).getPropertyValue("display");
  if (!display) display = element.style && element.style.display;
  return display === "none";
}
function get_get_computed_style_function(element) {
  if (element.ownerDocument.defaultView && typeof element.ownerDocument.defaultView.getComputedStyle === "function") return element.ownerDocument.defaultView.getComputedStyle;
  if (typeof getComputedStyle === "function") return getComputedStyle;
  return null;
}
function parse_text_p(text3) {
  var fixed = text3.replace(/[\t\r\n]/g, " ").trim().replace(/ +/g, " ").replace(/<text:s\/>/g, " ").replace(/<text:s text:c="(\d+)"\/>/g, function($$, $1) {
    return Array(parseInt($1, 10) + 1).join(" ");
  }).replace(/<text:tab[^<>]*\/>/g, "	").replace(/<text:line-break\/>/g, "\n");
  var v4 = unescapexml(fixed.replace(/<[^<>]*>/g, ""));
  return [v4];
}
function parse_ods_styles(d4, _opts, _nfm) {
  var number_format_map = _nfm || {};
  var str2 = xlml_normalize(d4);
  xlmlregex.lastIndex = 0;
  str2 = remove_doctype(str_remove_ng(str2, "<!--", "-->"));
  var Rn, NFtag, NF = "", tNF = "", y4, etpos = 0, tidx = -1, infmt = false, payload = "";
  while (Rn = xlmlregex.exec(str2)) {
    switch (Rn[3] = Rn[3].replace(/_[\s\S]*$/, "")) {
      /* Number Format Definitions */
      case "number-style":
      // <number:number-style> 16.29.2
      case "currency-style":
      // <number:currency-style> 16.29.8
      case "percentage-style":
      // <number:percentage-style> 16.29.10
      case "date-style":
      // <number:date-style> 16.29.11
      case "time-style":
      // <number:time-style> 16.29.19
      case "text-style":
        if (Rn[1] === "/") {
          infmt = false;
          if (NFtag["truncate-on-overflow"] == "false") {
            if (NF.match(/h/)) NF = NF.replace(/h+/, "[$&]");
            else if (NF.match(/m/)) NF = NF.replace(/m+/, "[$&]");
            else if (NF.match(/s/)) NF = NF.replace(/s+/, "[$&]");
          }
          number_format_map[NFtag.name] = NF;
          NF = "";
        } else if (Rn[0].charAt(Rn[0].length - 2) !== "/") {
          infmt = true;
          NF = "";
          NFtag = parsexmltag(Rn[0], false);
        }
        break;
      // LibreOffice bug https://bugs.documentfoundation.org/show_bug.cgi?id=149484
      case "boolean-style":
        if (Rn[1] === "/") {
          infmt = false;
          number_format_map[NFtag.name] = "General";
          NF = "";
        } else if (Rn[0].charAt(Rn[0].length - 2) !== "/") {
          infmt = true;
          NF = "";
          NFtag = parsexmltag(Rn[0], false);
        }
        break;
      /* Number Format Elements */
      case "boolean":
        NF += "General";
        break;
      case "text":
        if (Rn[1] === "/") {
          payload = str2.slice(tidx, xlmlregex.lastIndex - Rn[0].length);
          if (payload == "%" && NFtag[0] == "<number:percentage-style") NF += "%";
          else NF += '"' + payload.replace(/"/g, '""') + '"';
        } else if (Rn[0].charAt(Rn[0].length - 2) !== "/") {
          tidx = xlmlregex.lastIndex;
        }
        break;
      case "day":
        {
          y4 = parsexmltag(Rn[0], false);
          switch (y4["style"]) {
            case "short":
              NF += "d";
              break;
            case "long":
              NF += "dd";
              break;
            default:
              NF += "dd";
              break;
          }
        }
        break;
      case "day-of-week":
        {
          y4 = parsexmltag(Rn[0], false);
          switch (y4["style"]) {
            case "short":
              NF += "ddd";
              break;
            case "long":
              NF += "dddd";
              break;
            default:
              NF += "ddd";
              break;
          }
        }
        break;
      case "era":
        {
          y4 = parsexmltag(Rn[0], false);
          switch (y4["style"]) {
            case "short":
              NF += "ee";
              break;
            case "long":
              NF += "eeee";
              break;
            default:
              NF += "eeee";
              break;
          }
        }
        break;
      case "hours":
        {
          y4 = parsexmltag(Rn[0], false);
          switch (y4["style"]) {
            case "short":
              NF += "h";
              break;
            case "long":
              NF += "hh";
              break;
            default:
              NF += "hh";
              break;
          }
        }
        break;
      case "minutes":
        {
          y4 = parsexmltag(Rn[0], false);
          switch (y4["style"]) {
            case "short":
              NF += "m";
              break;
            case "long":
              NF += "mm";
              break;
            default:
              NF += "mm";
              break;
          }
        }
        break;
      case "month":
        {
          y4 = parsexmltag(Rn[0], false);
          if (y4["textual"]) NF += "mm";
          switch (y4["style"]) {
            case "short":
              NF += "m";
              break;
            case "long":
              NF += "mm";
              break;
            default:
              NF += "m";
              break;
          }
        }
        break;
      case "seconds":
        {
          y4 = parsexmltag(Rn[0], false);
          switch (y4["style"]) {
            case "short":
              NF += "s";
              break;
            case "long":
              NF += "ss";
              break;
            default:
              NF += "ss";
              break;
          }
          if (y4["decimal-places"]) NF += "." + fill("0", +y4["decimal-places"]);
        }
        break;
      case "year":
        {
          y4 = parsexmltag(Rn[0], false);
          switch (y4["style"]) {
            case "short":
              NF += "yy";
              break;
            case "long":
              NF += "yyyy";
              break;
            default:
              NF += "yy";
              break;
          }
        }
        break;
      case "am-pm":
        NF += "AM/PM";
        break;
      case "week-of-year":
      // <number:week-of-year> 16.29.17
      case "quarter":
        console.error("Excel does not support ODS format token " + Rn[3]);
        break;
      case "fill-character":
        if (Rn[1] === "/") {
          payload = str2.slice(tidx, xlmlregex.lastIndex - Rn[0].length);
          NF += '"' + payload.replace(/"/g, '""') + '"*';
        } else if (Rn[0].charAt(Rn[0].length - 2) !== "/") {
          tidx = xlmlregex.lastIndex;
        }
        break;
      case "scientific-number":
        y4 = parsexmltag(Rn[0], false);
        NF += "0." + fill("0", +y4["min-decimal-places"] || +y4["decimal-places"] || 2) + fill("?", +y4["decimal-places"] - +y4["min-decimal-places"] || 0) + "E" + (parsexmlbool(y4["forced-exponent-sign"]) ? "+" : "") + fill("0", +y4["min-exponent-digits"] || 2);
        break;
      case "fraction":
        y4 = parsexmltag(Rn[0], false);
        if (!+y4["min-integer-digits"]) NF += "#";
        else NF += fill("0", +y4["min-integer-digits"]);
        NF += " ";
        NF += fill("?", +y4["min-numerator-digits"] || 1);
        NF += "/";
        if (+y4["denominator-value"]) NF += y4["denominator-value"];
        else NF += fill("?", +y4["min-denominator-digits"] || 1);
        break;
      case "currency-symbol":
        if (Rn[1] === "/") {
          NF += '"' + str2.slice(tidx, xlmlregex.lastIndex - Rn[0].length).replace(/"/g, '""') + '"';
        } else if (Rn[0].charAt(Rn[0].length - 2) !== "/") {
          tidx = xlmlregex.lastIndex;
        } else NF += "$";
        break;
      case "text-properties":
        y4 = parsexmltag(Rn[0], false);
        switch ((y4["color"] || "").toLowerCase().replace("#", "")) {
          case "ff0000":
          case "red":
            NF = "[Red]" + NF;
            break;
        }
        break;
      case "text-content":
        NF += "@";
        break;
      case "map":
        y4 = parsexmltag(Rn[0], false);
        if (unescapexml(y4["condition"]) == "value()>=0") NF = number_format_map[y4["apply-style-name"]] + ";" + NF;
        else console.error("ODS number format may be incorrect: " + y4["condition"]);
        break;
      case "number":
        if (Rn[1] === "/") break;
        y4 = parsexmltag(Rn[0], false);
        tNF = "";
        tNF += fill("0", +y4["min-integer-digits"] || 1);
        if (parsexmlbool(y4["grouping"])) tNF = commaify(fill("#", Math.max(0, 4 - tNF.length)) + tNF);
        if (+y4["min-decimal-places"] || +y4["decimal-places"]) tNF += ".";
        if (+y4["min-decimal-places"]) tNF += fill("0", +y4["min-decimal-places"] || 1);
        if (+y4["decimal-places"] - (+y4["min-decimal-places"] || 0)) tNF += fill("0", +y4["decimal-places"] - (+y4["min-decimal-places"] || 0));
        NF += tNF;
        break;
      case "embedded-text":
        if (Rn[1] === "/") {
          if (etpos == 0) NF += '"' + str2.slice(tidx, xlmlregex.lastIndex - Rn[0].length).replace(/"/g, '""') + '"';
          else NF = NF.slice(0, etpos) + '"' + str2.slice(tidx, xlmlregex.lastIndex - Rn[0].length).replace(/"/g, '""') + '"' + NF.slice(etpos);
        } else if (Rn[0].charAt(Rn[0].length - 2) !== "/") {
          tidx = xlmlregex.lastIndex;
          etpos = -+parsexmltag(Rn[0], false)["position"] || 0;
        }
        break;
    }
  }
  return number_format_map;
}
function parse_content_xml(d4, _opts, _nfm) {
  var opts = _opts || {};
  if (DENSE != null && opts.dense == null) opts.dense = DENSE;
  var str2 = xlml_normalize(d4);
  var state = [], tmp;
  var tag;
  var nfidx, NF = "", pidx = 0;
  var sheetag;
  var rowtag;
  var Sheets = {}, SheetNames = [];
  var ws = {};
  if (opts.dense) ws["!data"] = [];
  var Rn, q2;
  var ctag = { value: "" }, ctag2 = {};
  var textp = "", textpidx = 0, textptag, oldtextp = "", oldtextpidx = 0;
  var textR = [], oldtextR = [];
  var R3 = -1, C3 = -1, range2 = { s: { r: 1e6, c: 1e7 }, e: { r: 0, c: 0 } };
  var row_ol = 0;
  var number_format_map = _nfm || {}, styles2 = {};
  var merges = [], mrange = {}, mR = 0, mC = 0;
  var rowinfo = [], rowpeat = 1, colpeat = 1;
  var arrayf = [];
  var WB = { Names: [], WBProps: {} };
  var atag = {};
  var _Ref = ["", ""];
  var comments = [], comment = {};
  var creator = "", creatoridx = 0;
  var isstub = false, intable = false;
  var i7 = 0;
  xlmlregex.lastIndex = 0;
  str2 = remove_doctype(str_remove_ng(str2, "<!--", "-->"));
  while (Rn = xlmlregex.exec(str2)) switch (Rn[3] = Rn[3].replace(/_[\s\S]*$/, "")) {
    case "table":
    case "\u5DE5\u4F5C\u8868":
      if (Rn[1] === "/") {
        if (range2.e.c >= range2.s.c && range2.e.r >= range2.s.r) ws["!ref"] = encode_range(range2);
        else ws["!ref"] = "A1:A1";
        if (opts.sheetRows > 0 && opts.sheetRows <= range2.e.r) {
          ws["!fullref"] = ws["!ref"];
          range2.e.r = opts.sheetRows - 1;
          ws["!ref"] = encode_range(range2);
        }
        if (merges.length) ws["!merges"] = merges;
        if (rowinfo.length) ws["!rows"] = rowinfo;
        sheetag.name = sheetag["\u540D\u79F0"] || sheetag.name;
        if (typeof JSON !== "undefined") JSON.stringify(sheetag);
        SheetNames.push(sheetag.name);
        Sheets[sheetag.name] = ws;
        intable = false;
      } else if (Rn[0].charAt(Rn[0].length - 2) !== "/") {
        sheetag = parsexmltag(Rn[0], false);
        R3 = C3 = -1;
        range2.s.r = range2.s.c = 1e7;
        range2.e.r = range2.e.c = 0;
        ws = {};
        if (opts.dense) ws["!data"] = [];
        merges = [];
        rowinfo = [];
        intable = true;
      }
      break;
    case "table-row-group":
      if (Rn[1] === "/") --row_ol;
      else ++row_ol;
      break;
    case "table-row":
    case "\u884C":
      if (Rn[1] === "/") {
        R3 += rowpeat;
        rowpeat = 1;
        break;
      }
      rowtag = parsexmltag(Rn[0], false);
      if (rowtag["\u884C\u53F7"]) R3 = rowtag["\u884C\u53F7"] - 1;
      else if (R3 == -1) R3 = 0;
      rowpeat = +rowtag["number-rows-repeated"] || 1;
      if (rowpeat < 10) {
        for (i7 = 0; i7 < rowpeat; ++i7) if (row_ol > 0) rowinfo[R3 + i7] = { level: row_ol };
      }
      C3 = -1;
      break;
    case "covered-table-cell":
      if (Rn[1] !== "/") {
        ++C3;
        ctag = parsexmltag(Rn[0], false);
        colpeat = parseInt(ctag["number-columns-repeated"] || "1", 10) || 1;
        if (opts.sheetStubs) {
          while (colpeat-- > 0) {
            if (opts.dense) {
              if (!ws["!data"][R3]) ws["!data"][R3] = [];
              ws["!data"][R3][C3] = { t: "z" };
            } else ws[encode_cell({ r: R3, c: C3 })] = { t: "z" };
            ++C3;
          }
          --C3;
        } else C3 += colpeat - 1;
      }
      textp = "";
      textR = [];
      break;
    /* stub */
    case "table-cell":
    case "\u6570\u636E":
      if (Rn[0].charAt(Rn[0].length - 2) === "/") {
        ++C3;
        ctag = parsexmltag(Rn[0], false);
        colpeat = parseInt(ctag["number-columns-repeated"] || "1", 10) || 1;
        q2 = {
          t: "z",
          v: null
          /*:: , z:null, w:"",c:[]*/
        };
        if (ctag.formula && opts.cellFormula != false) q2.f = ods_to_csf_formula(unescapexml(ctag.formula));
        if (ctag["style-name"] && styles2[ctag["style-name"]]) q2.z = styles2[ctag["style-name"]];
        if ((ctag["\u6570\u636E\u7C7B\u578B"] || ctag["value-type"]) == "string") {
          q2.t = "s";
          q2.v = unescapexml(ctag["string-value"] || "");
          if (opts.dense) {
            if (!ws["!data"][R3]) ws["!data"][R3] = [];
            ws["!data"][R3][C3] = q2;
          } else {
            ws[encode_col(C3) + encode_row(R3)] = q2;
          }
        }
        C3 += colpeat - 1;
      } else if (Rn[1] !== "/") {
        ++C3;
        textp = oldtextp = "";
        textpidx = oldtextpidx = 0;
        textR = [];
        oldtextR = [];
        colpeat = 1;
        var rptR = rowpeat ? R3 + rowpeat - 1 : R3;
        if (C3 > range2.e.c) range2.e.c = C3;
        if (C3 < range2.s.c) range2.s.c = C3;
        if (R3 < range2.s.r) range2.s.r = R3;
        if (rptR > range2.e.r) range2.e.r = rptR;
        ctag = parsexmltag(Rn[0], false);
        ctag2 = parsexmltagraw(Rn[0], true);
        comments = [];
        comment = {};
        q2 = {
          t: ctag["\u6570\u636E\u7C7B\u578B"] || ctag["value-type"],
          v: null
          /*:: , z:null, w:"",c:[]*/
        };
        if (ctag["style-name"] && styles2[ctag["style-name"]]) q2.z = styles2[ctag["style-name"]];
        if (opts.cellFormula) {
          if (ctag.formula) ctag.formula = unescapexml(ctag.formula);
          if (ctag["number-matrix-columns-spanned"] && ctag["number-matrix-rows-spanned"]) {
            mR = parseInt(ctag["number-matrix-rows-spanned"], 10) || 0;
            mC = parseInt(ctag["number-matrix-columns-spanned"], 10) || 0;
            mrange = { s: { r: R3, c: C3 }, e: { r: R3 + mR - 1, c: C3 + mC - 1 } };
            q2.F = encode_range(mrange);
            arrayf.push([mrange, q2.F]);
          }
          if (ctag.formula) q2.f = ods_to_csf_formula(ctag.formula);
          else for (i7 = 0; i7 < arrayf.length; ++i7)
            if (R3 >= arrayf[i7][0].s.r && R3 <= arrayf[i7][0].e.r) {
              if (C3 >= arrayf[i7][0].s.c && C3 <= arrayf[i7][0].e.c)
                q2.F = arrayf[i7][1];
            }
        }
        if (ctag["number-columns-spanned"] || ctag["number-rows-spanned"]) {
          mR = parseInt(ctag["number-rows-spanned"] || "1", 10) || 1;
          mC = parseInt(ctag["number-columns-spanned"] || "1", 10) || 1;
          if (mR * mC > 1) {
            mrange = { s: { r: R3, c: C3 }, e: { r: R3 + mR - 1, c: C3 + mC - 1 } };
            merges.push(mrange);
          }
        }
        if (ctag["number-columns-repeated"]) colpeat = parseInt(ctag["number-columns-repeated"], 10);
        switch (q2.t) {
          case "boolean":
            q2.t = "b";
            q2.v = parsexmlbool(ctag["boolean-value"]) || +ctag["boolean-value"] >= 1;
            break;
          case "float":
            q2.t = "n";
            q2.v = parseFloat(ctag.value);
            if (opts.cellDates && q2.z && fmt_is_date(q2.z)) {
              q2.v = numdate(q2.v + (WB.WBProps.date1904 ? 1462 : 0));
              q2.t = typeof q2.v == "number" ? "n" : "d";
            }
            break;
          case "percentage":
            q2.t = "n";
            q2.v = parseFloat(ctag.value);
            break;
          case "currency":
            q2.t = "n";
            q2.v = parseFloat(ctag.value);
            break;
          case "date":
            q2.t = "d";
            q2.v = parseDate(ctag["date-value"], WB.WBProps.date1904);
            if (!opts.cellDates) {
              q2.t = "n";
              q2.v = datenum(q2.v, WB.WBProps.date1904);
            }
            if (!q2.z) q2.z = "m/d/yy";
            break;
          /* NOTE: for `time`, Excel ODS export incorrectly uses durations relative to 1900 epoch even if 1904 is specified */
          case "time":
            q2.t = "n";
            q2.v = parse_isodur(ctag["time-value"]) / 86400;
            if (opts.cellDates) {
              q2.v = numdate(q2.v);
              q2.t = typeof q2.v == "number" ? "n" : "d";
            }
            if (!q2.z) q2.z = "HH:MM:SS";
            break;
          case "number":
            q2.t = "n";
            q2.v = parseFloat(ctag["\u6570\u636E\u6570\u503C"]);
            break;
          default:
            if (q2.t === "string" || q2.t === "text" || !q2.t) {
              q2.t = "s";
              if (ctag["string-value"] != null) {
                textp = unescapexml(ctag["string-value"]);
                textR = [];
              }
            } else throw new Error("Unsupported value type " + q2.t);
        }
      } else {
        isstub = false;
        if (ctag2["calcext:value-type"] == "error" && RBErr[textp] != null) {
          q2.t = "e";
          q2.w = textp;
          q2.v = RBErr[textp];
        }
        if (q2.t === "s") {
          q2.v = textp || "";
          if (textR.length) q2.R = textR;
          isstub = textpidx == 0;
        }
        if (atag.Target) q2.l = atag;
        if (comments.length > 0) {
          q2.c = comments;
          comments = [];
        }
        if (textp && opts.cellText !== false) q2.w = textp;
        if (isstub) {
          q2.t = "z";
          delete q2.v;
        }
        if (!isstub || opts.sheetStubs) {
          if (!(opts.sheetRows && opts.sheetRows <= R3)) {
            for (var rpt = 0; rpt < rowpeat; ++rpt) {
              colpeat = parseInt(ctag["number-columns-repeated"] || "1", 10);
              if (opts.dense) {
                if (!ws["!data"][R3 + rpt]) ws["!data"][R3 + rpt] = [];
                ws["!data"][R3 + rpt][C3] = rpt == 0 ? q2 : dup(q2);
                while (--colpeat > 0) ws["!data"][R3 + rpt][C3 + colpeat] = dup(q2);
              } else {
                ws[encode_cell({ r: R3 + rpt, c: C3 })] = q2;
                while (--colpeat > 0) ws[encode_cell({ r: R3 + rpt, c: C3 + colpeat })] = dup(q2);
              }
              if (range2.e.c <= C3) range2.e.c = C3;
            }
          }
        }
        colpeat = parseInt(ctag["number-columns-repeated"] || "1", 10);
        C3 += colpeat - 1;
        colpeat = 0;
        q2 = {
          /*:: t:"", v:null, z:null, w:"",c:[]*/
        };
        textp = "";
        textR = [];
      }
      atag = {};
      break;
    // 9.1.4 <table:table-cell>
    /* pure state */
    case "document":
    // TODO: <office:document> is the root for FODS
    case "document-content":
    case "\u7535\u5B50\u8868\u683C\u6587\u6863":
    // 3.1.3.2 <office:document-content>
    case "spreadsheet":
    case "\u4E3B\u4F53":
    // 3.7 <office:spreadsheet>
    case "scripts":
    // 3.12 <office:scripts>
    case "styles":
    // TODO <office:styles>
    case "font-face-decls":
    // 3.14 <office:font-face-decls>
    case "master-styles":
      if (Rn[1] === "/") {
        if ((tmp = state.pop())[0] !== Rn[3]) throw "Bad state: " + tmp;
      } else if (Rn[0].charAt(Rn[0].length - 2) !== "/") state.push([Rn[3], true]);
      break;
    case "annotation":
      if (Rn[1] === "/") {
        if ((tmp = state.pop())[0] !== Rn[3]) throw "Bad state: " + tmp;
        comment.t = textp;
        if (textR.length) comment.R = textR;
        comment.a = creator;
        comments.push(comment);
        textp = oldtextp;
        textpidx = oldtextpidx;
        textR = oldtextR;
      } else if (Rn[0].charAt(Rn[0].length - 2) !== "/") {
        state.push([Rn[3], false]);
        var annotag = parsexmltag(Rn[0], true);
        if (!(annotag["display"] && parsexmlbool(annotag["display"]))) comments.hidden = true;
        oldtextp = textp;
        oldtextpidx = textpidx;
        oldtextR = textR;
        textp = "";
        textpidx = 0;
        textR = [];
      }
      creator = "";
      creatoridx = 0;
      break;
    case "creator":
      if (Rn[1] === "/") {
        creator = str2.slice(creatoridx, Rn.index);
      } else creatoridx = Rn.index + Rn[0].length;
      break;
    /* ignore state */
    case "meta":
    case "\u5143\u6570\u636E":
    // TODO: <office:meta> <uof:元数据> FODS/UOF
    case "settings":
    // TODO: <office:settings>
    case "config-item-set":
    // TODO: <office:config-item-set>
    case "config-item-map-indexed":
    // TODO: <office:config-item-map-indexed>
    case "config-item-map-entry":
    // TODO: <office:config-item-map-entry>
    case "config-item-map-named":
    // TODO: <office:config-item-map-entry>
    case "shapes":
    // 9.2.8 <table:shapes>
    case "frame":
    // 10.4.2 <draw:frame>
    case "text-box":
    // 10.4.3 <draw:text-box>
    case "image":
    // 10.4.4 <draw:image>
    case "data-pilot-tables":
    // 9.6.2 <table:data-pilot-tables>
    case "list-style":
    // 16.30 <text:list-style>
    case "form":
    // 13.13 <form:form>
    case "dde-links":
    // 9.8 <table:dde-links>
    case "event-listeners":
    // TODO
    case "chart":
      if (Rn[1] === "/") {
        if ((tmp = state.pop())[0] !== Rn[3]) throw "Bad state: " + tmp;
      } else if (Rn[0].charAt(Rn[0].length - 2) !== "/") state.push([Rn[3], false]);
      textp = "";
      textpidx = 0;
      textR = [];
      break;
    case "scientific-number":
    // <number:scientific-number>
    case "currency-symbol":
    // <number:currency-symbol>
    case "fill-character":
      break;
    case "text-style":
    // 16.27.25 <number:text-style>
    case "boolean-style":
    // 16.27.23 <number:boolean-style>
    case "number-style":
    // 16.27.2 <number:number-style>
    case "currency-style":
    // 16.29.8 <number:currency-style>
    case "percentage-style":
    // 16.27.9 <number:percentage-style>
    case "date-style":
    // 16.27.10 <number:date-style>
    case "time-style":
      if (Rn[1] === "/") {
        var xlmlidx = xlmlregex.lastIndex;
        parse_ods_styles(str2.slice(nfidx, xlmlregex.lastIndex), _opts, number_format_map);
        xlmlregex.lastIndex = xlmlidx;
      } else if (Rn[0].charAt(Rn[0].length - 2) !== "/") {
        nfidx = xlmlregex.lastIndex - Rn[0].length;
      }
      break;
    case "script":
      break;
    // 3.13 <office:script>
    case "libraries":
      break;
    // TODO: <ooo:libraries>
    case "automatic-styles":
      break;
    // 3.15.3 <office:automatic-styles>
    case "default-style":
    // TODO: <style:default-style>
    case "page-layout":
      break;
    // TODO: <style:page-layout>
    case "style":
      {
        var styletag = parsexmltag(Rn[0], false);
        if (styletag["family"] == "table-cell" && number_format_map[styletag["data-style-name"]]) styles2[styletag["name"]] = number_format_map[styletag["data-style-name"]];
      }
      break;
    case "map":
      break;
    // 16.3 <style:map>
    case "font-face":
      break;
    // 16.21 <style:font-face>
    case "paragraph-properties":
      break;
    // 17.6 <style:paragraph-properties>
    case "table-properties":
      break;
    // 17.15 <style:table-properties>
    case "table-column-properties":
      break;
    // 17.16 <style:table-column-properties>
    case "table-row-properties":
      break;
    // 17.17 <style:table-row-properties>
    case "table-cell-properties":
      break;
    // 17.18 <style:table-cell-properties>
    case "number":
      break;
    case "fraction":
      break;
    // TODO 16.27.6 <number:fraction>
    case "day":
    // 16.27.11 <number:day>
    case "month":
    // 16.27.12 <number:month>
    case "year":
    // 16.27.13 <number:year>
    case "era":
    // 16.27.14 <number:era>
    case "day-of-week":
    // 16.27.15 <number:day-of-week>
    case "week-of-year":
    // 16.27.16 <number:week-of-year>
    case "quarter":
    // 16.27.17 <number:quarter>
    case "hours":
    // 16.27.19 <number:hours>
    case "minutes":
    // 16.27.20 <number:minutes>
    case "seconds":
    // 16.27.21 <number:seconds>
    case "am-pm":
      break;
    case "boolean":
      break;
    // 16.27.24 <number:boolean>
    case "text":
      if (Rn[0].slice(-2) === "/>") break;
      else if (Rn[1] === "/") switch (state[state.length - 1][0]) {
        case "number-style":
        case "date-style":
        case "time-style":
          NF += str2.slice(pidx, Rn.index);
          break;
      }
      else pidx = Rn.index + Rn[0].length;
      break;
    case "named-range":
      tag = parsexmltag(Rn[0], false);
      _Ref = ods_to_csf_3D(tag["cell-range-address"]);
      var nrange = { Name: tag.name, Ref: _Ref[0] + "!" + _Ref[1] };
      if (intable) nrange.Sheet = SheetNames.length;
      WB.Names.push(nrange);
      break;
    case "text-content":
      break;
    // 16.27.27 <number:text-content>
    case "text-properties":
      break;
    // 16.27.27 <style:text-properties>
    case "embedded-text":
      break;
    // 16.27.4 <number:embedded-text>
    case "body":
    case "\u7535\u5B50\u8868\u683C":
      break;
    // 3.3 16.9.6 19.726.3
    case "forms":
      break;
    // 12.25.2 13.2
    case "table-column":
      break;
    // 9.1.6 <table:table-column>
    case "table-header-rows":
      break;
    // 9.1.7 <table:table-header-rows>
    case "table-rows":
      break;
    // 9.1.12 <table:table-rows>
    /* TODO: outline levels */
    case "table-column-group":
      break;
    // 9.1.10 <table:table-column-group>
    case "table-header-columns":
      break;
    // 9.1.11 <table:table-header-columns>
    case "table-columns":
      break;
    // 9.1.12 <table:table-columns>
    case "null-date":
      tag = parsexmltag(Rn[0], false);
      switch (tag["date-value"]) {
        case "1904-01-01":
          WB.WBProps.date1904 = true;
          break;
      }
      break;
    case "graphic-properties":
      break;
    // 17.21 <style:graphic-properties>
    case "calculation-settings":
      break;
    // 9.4.1 <table:calculation-settings>
    case "named-expressions":
      break;
    // 9.4.11 <table:named-expressions>
    case "label-range":
      break;
    // 9.4.9 <table:label-range>
    case "label-ranges":
      break;
    // 9.4.10 <table:label-ranges>
    case "named-expression":
      break;
    // 9.4.13 <table:named-expression>
    case "sort":
      break;
    // 9.4.19 <table:sort>
    case "sort-by":
      break;
    // 9.4.20 <table:sort-by>
    case "sort-groups":
      break;
    // 9.4.22 <table:sort-groups>
    case "tab":
      break;
    // 6.1.4 <text:tab>
    case "line-break":
      break;
    // 6.1.5 <text:line-break>
    case "span":
      break;
    // 6.1.7 <text:span>
    case "p":
    case "\u6587\u672C\u4E32":
      if (["master-styles"].indexOf(state[state.length - 1][0]) > -1) break;
      if (Rn[1] === "/" && (!ctag || !ctag["string-value"])) {
        var ptp = parse_text_p(str2.slice(textpidx, Rn.index), textptag);
        textp = (textp.length > 0 ? textp + "\n" : "") + ptp[0];
      } else if (Rn[0].slice(-2) == "/>") {
        textp += "\n";
      } else {
        textptag = parsexmltag(Rn[0], false);
        textpidx = Rn.index + Rn[0].length;
      }
      break;
    // <text:p>
    case "s":
      break;
    // <text:s>
    case "database-range":
      if (Rn[1] === "/") break;
      try {
        _Ref = ods_to_csf_3D(parsexmltag(Rn[0])["target-range-address"]);
        Sheets[_Ref[0]]["!autofilter"] = { ref: _Ref[1] };
      } catch (e9) {
      }
      break;
    case "date":
      break;
    // <*:date>
    case "object":
      break;
    // 10.4.6.2 <draw:object>
    case "title":
    case "\u6807\u9898":
      break;
    // <*:title> OR <uof:标题>
    case "desc":
      break;
    // <*:desc>
    case "binary-data":
      break;
    // 10.4.5 TODO: b64 blob
    /* 9.2 Advanced Tables */
    case "table-source":
      break;
    // 9.2.6
    case "scenario":
      break;
    // 9.2.6
    case "iteration":
      break;
    // 9.4.3 <table:iteration>
    case "content-validations":
      break;
    // 9.4.4 <table:
    case "content-validation":
      break;
    // 9.4.5 <table:
    case "help-message":
      break;
    // 9.4.6 <table:
    case "error-message":
      break;
    // 9.4.7 <table:
    case "database-ranges":
      break;
    // 9.4.14 <table:database-ranges>
    /* 9.5 Filters */
    case "filter":
      break;
    // 9.5.2 <table:filter>
    case "filter-and":
      break;
    // 9.5.3 <table:filter-and>
    case "filter-or":
      break;
    // 9.5.4 <table:filter-or>
    case "filter-condition":
      break;
    // 9.5.5 <table:filter-condition>
    case "filter-set-item":
      break;
    // 9.5.6 <table:filter-condition>
    case "list-level-style-bullet":
      break;
    // 16.31 <text:
    case "list-level-style-number":
      break;
    // 16.32 <text:
    case "list-level-properties":
      break;
    // 17.19 <style:
    /* 7.3 Document Fields */
    case "sender-firstname":
    // 7.3.6.2
    case "sender-lastname":
    // 7.3.6.3
    case "sender-initials":
    // 7.3.6.4
    case "sender-title":
    // 7.3.6.5
    case "sender-position":
    // 7.3.6.6
    case "sender-email":
    // 7.3.6.7
    case "sender-phone-private":
    // 7.3.6.8
    case "sender-fax":
    // 7.3.6.9
    case "sender-company":
    // 7.3.6.10
    case "sender-phone-work":
    // 7.3.6.11
    case "sender-street":
    // 7.3.6.12
    case "sender-city":
    // 7.3.6.13
    case "sender-postal-code":
    // 7.3.6.14
    case "sender-country":
    // 7.3.6.15
    case "sender-state-or-province":
    // 7.3.6.16
    case "author-name":
    // 7.3.7.1
    case "author-initials":
    // 7.3.7.2
    case "chapter":
    // 7.3.8
    case "file-name":
    // 7.3.9
    case "template-name":
    // 7.3.9
    case "sheet-name":
      break;
    case "event-listener":
      break;
    /* TODO: FODS Properties */
    case "initial-creator":
    case "creation-date":
    case "print-date":
    case "generator":
    case "document-statistic":
    case "user-defined":
    case "editing-duration":
    case "editing-cycles":
      break;
    /* TODO: FODS Config */
    case "config-item":
      break;
    /* TODO: style tokens */
    case "page-number":
      break;
    // TODO <text:page-number>
    case "page-count":
      break;
    // TODO <text:page-count>
    case "time":
      break;
    // TODO <text:time>
    /* 9.3 Advanced Table Cells */
    case "cell-range-source":
      break;
    // 9.3.1 <table:
    case "detective":
      break;
    // 9.3.2 <table:
    case "operation":
      break;
    // 9.3.3 <table:
    case "highlighted-range":
      break;
    // 9.3.4 <table:
    /* 9.6 Data Pilot Tables <table: */
    case "data-pilot-table":
    // 9.6.3
    case "source-cell-range":
    // 9.6.5
    case "source-service":
    // 9.6.6
    case "data-pilot-field":
    // 9.6.7
    case "data-pilot-level":
    // 9.6.8
    case "data-pilot-subtotals":
    // 9.6.9
    case "data-pilot-subtotal":
    // 9.6.10
    case "data-pilot-members":
    // 9.6.11
    case "data-pilot-member":
    // 9.6.12
    case "data-pilot-display-info":
    // 9.6.13
    case "data-pilot-sort-info":
    // 9.6.14
    case "data-pilot-layout-info":
    // 9.6.15
    case "data-pilot-field-reference":
    // 9.6.16
    case "data-pilot-groups":
    // 9.6.17
    case "data-pilot-group":
    // 9.6.18
    case "data-pilot-group-member":
      break;
    /* 10.3 Drawing Shapes */
    case "rect":
      break;
    /* 14.6 DDE Connections */
    case "dde-connection-decls":
    // 14.6.2 <text:
    case "dde-connection-decl":
    // 14.6.3 <text:
    case "dde-link":
    // 14.6.4 <table:
    case "dde-source":
      break;
    case "properties":
      break;
    // 13.7 <form:properties>
    case "property":
      break;
    // 13.8 <form:property>
    case "a":
      if (Rn[1] !== "/") {
        atag = parsexmltag(Rn[0], false);
        if (!atag.href) break;
        atag.Target = unescapexml(atag.href);
        delete atag.href;
        if (atag.Target.charAt(0) == "#" && atag.Target.indexOf(".") > -1) {
          _Ref = ods_to_csf_3D(atag.Target.slice(1));
          atag.Target = "#" + _Ref[0] + "!" + _Ref[1];
        } else if (atag.Target.match(/^\.\.[\\\/]/)) atag.Target = atag.Target.slice(3);
      }
      break;
    /* non-standard */
    case "table-protection":
      break;
    case "data-pilot-grand-total":
      break;
    // <table:
    case "office-document-common-attrs":
      break;
    // bare
    default:
      switch (Rn[2]) {
        case "dc:":
        // TODO: properties
        case "calcext:":
        // ignore undocumented extensions
        case "loext:":
        // ignore undocumented extensions
        case "ooo:":
        // ignore undocumented extensions
        case "chartooo:":
        // ignore undocumented extensions
        case "draw:":
        // TODO: drawing
        case "style:":
        // TODO: styles
        case "chart:":
        // TODO: charts
        case "form:":
        // TODO: forms
        case "uof:":
        // TODO: uof
        case "\u8868:":
        // TODO: uof
        case "\u5B57:":
          break;
        default:
          if (opts.WTF) throw new Error(Rn);
      }
  }
  var out = {
    Sheets,
    SheetNames,
    Workbook: WB
  };
  if (opts.bookSheets) delete /*::(*/
  out.Sheets;
  return out;
}
function parse_ods(zip, opts) {
  opts = opts || {};
  if (safegetzipfile(zip, "META-INF/manifest.xml")) parse_manifest(getzipdata(zip, "META-INF/manifest.xml"), opts);
  var styles2 = getzipstr(zip, "styles.xml");
  var Styles = styles2 && parse_ods_styles(utf8read(styles2), opts);
  var content = getzipstr(zip, "content.xml");
  if (!content) throw new Error("Missing content.xml in ODS / UOF file");
  var wb = parse_content_xml(utf8read(content), opts, Styles);
  if (safegetzipfile(zip, "meta.xml")) wb.Props = parse_core_props(getzipdata(zip, "meta.xml"));
  wb.bookType = "ods";
  return wb;
}
function parse_fods(data, opts) {
  var wb = parse_content_xml(data, opts);
  wb.bookType = "fods";
  return wb;
}
var subarray = (function() {
  try {
    if (typeof Uint8Array == "undefined")
      return "slice";
    if (typeof Uint8Array.prototype.subarray == "undefined")
      return "slice";
    if (typeof Buffer !== "undefined") {
      if (typeof Buffer.prototype.subarray == "undefined")
        return "slice";
      if ((typeof Buffer.from == "function" ? Buffer.from([72, 62]) : new Buffer([72, 62])) instanceof Uint8Array)
        return "subarray";
      return "slice";
    }
    return "subarray";
  } catch (e9) {
    return "slice";
  }
})();
function u8_to_dataview(array) {
  return new DataView(array.buffer, array.byteOffset, array.byteLength);
}
function u8str(u8) {
  return typeof TextDecoder != "undefined" ? new TextDecoder().decode(u8) : utf8read(a2s(u8));
}
function u8concat(u8a) {
  var len = 0;
  for (var i7 = 0; i7 < u8a.length; ++i7)
    len += u8a[i7].length;
  var out = new Uint8Array(len);
  var off = 0;
  for (i7 = 0; i7 < u8a.length; ++i7) {
    var u8 = u8a[i7], L3 = u8.length;
    if (L3 < 250) {
      for (var j3 = 0; j3 < L3; ++j3)
        out[off++] = u8[j3];
    } else {
      out.set(u8, off);
      off += L3;
    }
  }
  return out;
}
function popcnt(x2) {
  x2 -= x2 >> 1 & 1431655765;
  x2 = (x2 & 858993459) + (x2 >> 2 & 858993459);
  return (x2 + (x2 >> 4) & 252645135) * 16843009 >>> 24;
}
function readDecimal128LE(buf, offset) {
  var exp = (buf[offset + 15] & 127) << 7 | buf[offset + 14] >> 1;
  var mantissa = buf[offset + 14] & 1;
  for (var j3 = offset + 13; j3 >= offset; --j3)
    mantissa = mantissa * 256 + buf[j3];
  return (buf[offset + 15] & 128 ? -mantissa : mantissa) * Math.pow(10, exp - 6176);
}
function parse_varint49(buf, ptr) {
  var l5 = ptr.l;
  var usz = buf[l5] & 127;
  varint:
    if (buf[l5++] >= 128) {
      usz |= (buf[l5] & 127) << 7;
      if (buf[l5++] < 128)
        break varint;
      usz |= (buf[l5] & 127) << 14;
      if (buf[l5++] < 128)
        break varint;
      usz |= (buf[l5] & 127) << 21;
      if (buf[l5++] < 128)
        break varint;
      usz += (buf[l5] & 127) * Math.pow(2, 28);
      ++l5;
      if (buf[l5++] < 128)
        break varint;
      usz += (buf[l5] & 127) * Math.pow(2, 35);
      ++l5;
      if (buf[l5++] < 128)
        break varint;
      usz += (buf[l5] & 127) * Math.pow(2, 42);
      ++l5;
      if (buf[l5++] < 128)
        break varint;
    }
  ptr.l = l5;
  return usz;
}
function varint_to_i32(buf) {
  var l5 = 0, i32 = buf[l5] & 127;
  if (buf[l5++] < 128)
    return i32;
  i32 |= (buf[l5] & 127) << 7;
  if (buf[l5++] < 128)
    return i32;
  i32 |= (buf[l5] & 127) << 14;
  if (buf[l5++] < 128)
    return i32;
  i32 |= (buf[l5] & 127) << 21;
  if (buf[l5++] < 128)
    return i32;
  i32 |= (buf[l5] & 15) << 28;
  return i32;
}
function parse_shallow(buf) {
  var out = [], ptr = { l: 0 };
  while (ptr.l < buf.length) {
    var off = ptr.l;
    var num = parse_varint49(buf, ptr);
    var type = num & 7;
    num = num / 8 | 0;
    var data;
    var l5 = ptr.l;
    switch (type) {
      case 0:
        {
          while (buf[l5++] >= 128)
            ;
          data = buf[subarray](ptr.l, l5);
          ptr.l = l5;
        }
        break;
      case 1:
        {
          data = buf[subarray](l5, l5 + 8);
          ptr.l = l5 + 8;
        }
        break;
      case 2:
        {
          var len = parse_varint49(buf, ptr);
          data = buf[subarray](ptr.l, ptr.l + len);
          ptr.l += len;
        }
        break;
      case 5:
        {
          data = buf[subarray](l5, l5 + 4);
          ptr.l = l5 + 4;
        }
        break;
      default:
        throw new Error("PB Type ".concat(type, " for Field ").concat(num, " at offset ").concat(off));
    }
    var v4 = { data, type };
    if (out[num] == null)
      out[num] = [];
    out[num].push(v4);
  }
  return out;
}
function mappa(data, cb) {
  return (data == null ? void 0 : data.map(function(d4) {
    return cb(d4.data);
  })) || [];
}
function parse_iwa_file(buf) {
  var _a7;
  var out = [], ptr = { l: 0 };
  while (ptr.l < buf.length) {
    var len = parse_varint49(buf, ptr);
    var ai = parse_shallow(buf[subarray](ptr.l, ptr.l + len));
    ptr.l += len;
    var res = {
      id: varint_to_i32(ai[1][0].data),
      messages: []
    };
    ai[2].forEach(function(b4) {
      var mi = parse_shallow(b4.data);
      var fl = varint_to_i32(mi[3][0].data);
      res.messages.push({
        meta: mi,
        data: buf[subarray](ptr.l, ptr.l + fl)
      });
      ptr.l += fl;
    });
    if ((_a7 = ai[3]) == null ? void 0 : _a7[0])
      res.merge = varint_to_i32(ai[3][0].data) >>> 0 > 0;
    out.push(res);
  }
  return out;
}
function parse_snappy_chunk(type, buf) {
  if (type != 0)
    throw new Error("Unexpected Snappy chunk type ".concat(type));
  var ptr = { l: 0 };
  var usz = parse_varint49(buf, ptr);
  var chunks = [];
  var l5 = ptr.l;
  while (l5 < buf.length) {
    var tag = buf[l5] & 3;
    if (tag == 0) {
      var len = buf[l5++] >> 2;
      if (len < 60)
        ++len;
      else {
        var c6 = len - 59;
        len = buf[l5];
        if (c6 > 1)
          len |= buf[l5 + 1] << 8;
        if (c6 > 2)
          len |= buf[l5 + 2] << 16;
        if (c6 > 3)
          len |= buf[l5 + 3] << 24;
        len >>>= 0;
        len++;
        l5 += c6;
      }
      chunks.push(buf[subarray](l5, l5 + len));
      l5 += len;
      continue;
    } else {
      var offset = 0, length = 0;
      if (tag == 1) {
        length = (buf[l5] >> 2 & 7) + 4;
        offset = (buf[l5++] & 224) << 3;
        offset |= buf[l5++];
      } else {
        length = (buf[l5++] >> 2) + 1;
        if (tag == 2) {
          offset = buf[l5] | buf[l5 + 1] << 8;
          l5 += 2;
        } else {
          offset = (buf[l5] | buf[l5 + 1] << 8 | buf[l5 + 2] << 16 | buf[l5 + 3] << 24) >>> 0;
          l5 += 4;
        }
      }
      if (offset == 0)
        throw new Error("Invalid offset 0");
      var j3 = chunks.length - 1, off = offset;
      while (j3 >= 0 && off >= chunks[j3].length) {
        off -= chunks[j3].length;
        --j3;
      }
      if (j3 < 0) {
        if (off == 0)
          off = chunks[j3 = 0].length;
        else
          throw new Error("Invalid offset beyond length");
      }
      if (length < off)
        chunks.push(chunks[j3][subarray](chunks[j3].length - off, chunks[j3].length - off + length));
      else {
        if (off > 0) {
          chunks.push(chunks[j3][subarray](chunks[j3].length - off));
          length -= off;
        }
        ++j3;
        while (length >= chunks[j3].length) {
          chunks.push(chunks[j3]);
          length -= chunks[j3].length;
          ++j3;
        }
        if (length)
          chunks.push(chunks[j3][subarray](0, length));
      }
      if (chunks.length > 25)
        chunks = [u8concat(chunks)];
    }
  }
  var clen = 0;
  for (var u8i = 0; u8i < chunks.length; ++u8i)
    clen += chunks[u8i].length;
  if (clen != usz)
    throw new Error("Unexpected length: ".concat(clen, " != ").concat(usz));
  return chunks;
}
function decompress_iwa_file(buf) {
  if (Array.isArray(buf))
    buf = new Uint8Array(buf);
  var out = [];
  var l5 = 0;
  while (l5 < buf.length) {
    var t6 = buf[l5++];
    var len = buf[l5] | buf[l5 + 1] << 8 | buf[l5 + 2] << 16;
    l5 += 3;
    out.push.apply(out, parse_snappy_chunk(t6, buf[subarray](l5, l5 + len)));
    l5 += len;
  }
  if (l5 !== buf.length)
    throw new Error("data is not a valid framed stream!");
  return out.length == 1 ? out[0] : u8concat(out);
}
var numbers_lut_new = function() {
  return { sst: [], rsst: [], ofmt: [], nfmt: [], fmla: [], ferr: [], cmnt: [] };
};
function numbers_format_cell(cell, t6, flags, ofmt, nfmt) {
  var _a7, _b, _c, _d;
  var ctype = t6 & 255, ver = t6 >> 8;
  var fmt = ver >= 5 ? nfmt : ofmt;
  dur:
    if (flags & (ver > 4 ? 8 : 4) && cell.t == "n" && ctype == 7) {
      var dstyle = ((_a7 = fmt[7]) == null ? void 0 : _a7[0]) ? varint_to_i32(fmt[7][0].data) : -1;
      if (dstyle == -1)
        break dur;
      var dmin = ((_b = fmt[15]) == null ? void 0 : _b[0]) ? varint_to_i32(fmt[15][0].data) : -1;
      var dmax = ((_c = fmt[16]) == null ? void 0 : _c[0]) ? varint_to_i32(fmt[16][0].data) : -1;
      var auto = ((_d = fmt[40]) == null ? void 0 : _d[0]) ? varint_to_i32(fmt[40][0].data) : -1;
      var d4 = cell.v, dd = d4;
      autodur:
        if (auto) {
          if (d4 == 0) {
            dmin = dmax = 2;
            break autodur;
          }
          if (d4 >= 604800)
            dmin = 1;
          else if (d4 >= 86400)
            dmin = 2;
          else if (d4 >= 3600)
            dmin = 4;
          else if (d4 >= 60)
            dmin = 8;
          else if (d4 >= 1)
            dmin = 16;
          else
            dmin = 32;
          if (Math.floor(d4) != d4)
            dmax = 32;
          else if (d4 % 60)
            dmax = 16;
          else if (d4 % 3600)
            dmax = 8;
          else if (d4 % 86400)
            dmax = 4;
          else if (d4 % 604800)
            dmax = 2;
          if (dmax < dmin)
            dmax = dmin;
        }
      if (dmin == -1 || dmax == -1)
        break dur;
      var dstr = [], zstr = [];
      if (dmin == 1) {
        dd = d4 / 604800;
        if (dmax == 1) {
          zstr.push('d"d"');
        } else {
          dd |= 0;
          d4 -= 604800 * dd;
        }
        dstr.push(dd + (dstyle == 2 ? " week" + (dd == 1 ? "" : "s") : dstyle == 1 ? "w" : ""));
      }
      if (dmin <= 2 && dmax >= 2) {
        dd = d4 / 86400;
        if (dmax > 2) {
          dd |= 0;
          d4 -= 86400 * dd;
        }
        zstr.push('d"d"');
        dstr.push(dd + (dstyle == 2 ? " day" + (dd == 1 ? "" : "s") : dstyle == 1 ? "d" : ""));
      }
      if (dmin <= 4 && dmax >= 4) {
        dd = d4 / 3600;
        if (dmax > 4) {
          dd |= 0;
          d4 -= 3600 * dd;
        }
        zstr.push((dmin >= 4 ? "[h]" : "h") + '"h"');
        dstr.push(dd + (dstyle == 2 ? " hour" + (dd == 1 ? "" : "s") : dstyle == 1 ? "h" : ""));
      }
      if (dmin <= 8 && dmax >= 8) {
        dd = d4 / 60;
        if (dmax > 8) {
          dd |= 0;
          d4 -= 60 * dd;
        }
        zstr.push((dmin >= 8 ? "[m]" : "m") + '"m"');
        if (dstyle == 0)
          dstr.push((dmin == 8 && dmax == 8 || dd >= 10 ? "" : "0") + dd);
        else
          dstr.push(dd + (dstyle == 2 ? " minute" + (dd == 1 ? "" : "s") : dstyle == 1 ? "m" : ""));
      }
      if (dmin <= 16 && dmax >= 16) {
        dd = d4;
        if (dmax > 16) {
          dd |= 0;
          d4 -= dd;
        }
        zstr.push((dmin >= 16 ? "[s]" : "s") + '"s"');
        if (dstyle == 0)
          dstr.push((dmax == 16 && dmin == 16 || dd >= 10 ? "" : "0") + dd);
        else
          dstr.push(dd + (dstyle == 2 ? " second" + (dd == 1 ? "" : "s") : dstyle == 1 ? "s" : ""));
      }
      if (dmax >= 32) {
        dd = Math.round(1e3 * d4);
        if (dmin < 32)
          zstr.push('.000"ms"');
        if (dstyle == 0)
          dstr.push((dd >= 100 ? "" : dd >= 10 ? "0" : "00") + dd);
        else
          dstr.push(dd + (dstyle == 2 ? " millisecond" + (dd == 1 ? "" : "s") : dstyle == 1 ? "ms" : ""));
      }
      cell.w = dstr.join(dstyle == 0 ? ":" : " ");
      cell.z = zstr.join(dstyle == 0 ? '":"' : " ");
      if (dstyle == 0)
        cell.w = cell.w.replace(/:(\d\d\d)$/, ".$1");
    }
}
function parse_old_storage(buf, lut, v4, opts) {
  var dv = u8_to_dataview(buf);
  var flags = dv.getUint32(4, true);
  var ridx = -1, sidx = -1, zidx = -1, ieee = NaN, dc = 0, dt = new Date(Date.UTC(2001, 0, 1));
  var doff = v4 > 1 ? 12 : 8;
  if (flags & 2) {
    zidx = dv.getUint32(doff, true);
    doff += 4;
  }
  doff += popcnt(flags & (v4 > 1 ? 3468 : 396)) * 4;
  if (flags & 512) {
    ridx = dv.getUint32(doff, true);
    doff += 4;
  }
  doff += popcnt(flags & (v4 > 1 ? 12288 : 4096)) * 4;
  if (flags & 16) {
    sidx = dv.getUint32(doff, true);
    doff += 4;
  }
  if (flags & 32) {
    ieee = dv.getFloat64(doff, true);
    doff += 8;
  }
  if (flags & 64) {
    dt.setTime(dt.getTime() + (dc = dv.getFloat64(doff, true)) * 1e3);
    doff += 8;
  }
  if (v4 > 1) {
    flags = dv.getUint32(8, true) >>> 16;
    if (flags & 255) {
      if (zidx == -1)
        zidx = dv.getUint32(doff, true);
      doff += 4;
    }
  }
  var ret;
  var t6 = buf[v4 >= 4 ? 1 : 2];
  switch (t6) {
    case 0:
      return void 0;
    case 2:
      ret = { t: "n", v: ieee };
      break;
    case 3:
      ret = { t: "s", v: lut.sst[sidx] };
      break;
    case 5:
      {
        if (opts == null ? void 0 : opts.cellDates)
          ret = { t: "d", v: dt };
        else
          ret = { t: "n", v: dc / 86400 + 35430, z: table_fmt[14] };
      }
      break;
    case 6:
      ret = { t: "b", v: ieee > 0 };
      break;
    case 7:
      ret = { t: "n", v: ieee };
      break;
    case 8:
      ret = { t: "e", v: 0 };
      break;
    case 9:
      {
        if (ridx > -1) {
          var rts = lut.rsst[ridx];
          ret = { t: "s", v: rts.v };
          if (rts.l)
            ret.l = { Target: rts.l };
        } else
          throw new Error("Unsupported cell type ".concat(buf[subarray](0, 4)));
      }
      break;
    default:
      throw new Error("Unsupported cell type ".concat(buf[subarray](0, 4)));
  }
  if (zidx > -1)
    numbers_format_cell(ret, t6 | v4 << 8, flags, lut.ofmt[zidx], lut.nfmt[zidx]);
  if (t6 == 7)
    ret.v /= 86400;
  return ret;
}
function parse_new_storage(buf, lut, opts) {
  var dv = u8_to_dataview(buf);
  var flags = dv.getUint32(4, true);
  var fields = dv.getUint32(8, true);
  var doff = 12;
  var ridx = -1, sidx = -1, zidx = -1, d128 = NaN, ieee = NaN, dc = 0, dt = new Date(Date.UTC(2001, 0, 1)), eidx = -1, fidx = -1;
  if (fields & 1) {
    d128 = readDecimal128LE(buf, doff);
    doff += 16;
  }
  if (fields & 2) {
    ieee = dv.getFloat64(doff, true);
    doff += 8;
  }
  if (fields & 4) {
    dt.setTime(dt.getTime() + (dc = dv.getFloat64(doff, true)) * 1e3);
    doff += 8;
  }
  if (fields & 8) {
    sidx = dv.getUint32(doff, true);
    doff += 4;
  }
  if (fields & 16) {
    ridx = dv.getUint32(doff, true);
    doff += 4;
  }
  doff += popcnt(fields & 480) * 4;
  if (fields & 512) {
    fidx = dv.getUint32(doff, true);
    doff += 4;
  }
  doff += popcnt(fields & 1024) * 4;
  if (fields & 2048) {
    eidx = dv.getUint32(doff, true);
    doff += 4;
  }
  var ret;
  var t6 = buf[1];
  switch (t6) {
    case 0:
      ret = { t: "z" };
      break;
    case 2:
      ret = { t: "n", v: d128 };
      break;
    case 3:
      ret = { t: "s", v: lut.sst[sidx] };
      break;
    case 5:
      {
        if (opts == null ? void 0 : opts.cellDates)
          ret = { t: "d", v: dt };
        else
          ret = { t: "n", v: dc / 86400 + 35430, z: table_fmt[14] };
      }
      break;
    case 6:
      ret = { t: "b", v: ieee > 0 };
      break;
    case 7:
      ret = { t: "n", v: ieee };
      break;
    case 8:
      ret = { t: "e", v: 0 };
      break;
    case 9:
      {
        if (ridx > -1) {
          var rts = lut.rsst[ridx];
          ret = { t: "s", v: rts.v };
          if (rts.l)
            ret.l = { Target: rts.l };
        } else
          throw new Error("Unsupported cell type ".concat(buf[1], " : ").concat(fields & 31, " : ").concat(buf[subarray](0, 4)));
      }
      break;
    case 10:
      ret = { t: "n", v: d128 };
      break;
    default:
      throw new Error("Unsupported cell type ".concat(buf[1], " : ").concat(fields & 31, " : ").concat(buf[subarray](0, 4)));
  }
  doff += popcnt(fields & 4096) * 4;
  if (fields & 516096) {
    if (zidx == -1)
      zidx = dv.getUint32(doff, true);
    doff += 4;
  }
  if (fields & 524288) {
    var cmntidx = dv.getUint32(doff, true);
    doff += 4;
    if (lut.cmnt[cmntidx])
      ret.c = iwa_to_s5s_comment(lut.cmnt[cmntidx]);
  }
  if (zidx > -1)
    numbers_format_cell(ret, t6 | 5 << 8, fields >> 13, lut.ofmt[zidx], lut.nfmt[zidx]);
  if (t6 == 7)
    ret.v /= 86400;
  return ret;
}
function parse_cell_storage(buf, lut, opts) {
  switch (buf[0]) {
    case 0:
    case 1:
    case 2:
    case 3:
    case 4:
      return parse_old_storage(buf, lut, buf[0], opts);
    case 5:
      return parse_new_storage(buf, lut, opts);
    default:
      throw new Error("Unsupported payload version ".concat(buf[0]));
  }
}
function parse_TSP_Reference(buf) {
  var pb = parse_shallow(buf);
  return varint_to_i32(pb[1][0].data);
}
function parse_TST_TableDataList(M4, root) {
  var pb = parse_shallow(root.data);
  var type = varint_to_i32(pb[1][0].data);
  var entries = pb[3];
  var data = [];
  (entries || []).forEach(function(entry) {
    var _a7, _b;
    var le2 = parse_shallow(entry.data);
    if (!le2[1])
      return;
    var key = varint_to_i32(le2[1][0].data) >>> 0;
    switch (type) {
      case 1:
        data[key] = u8str(le2[3][0].data);
        break;
      case 8:
        {
          var rt = M4[parse_TSP_Reference(le2[9][0].data)][0];
          var rtp = parse_shallow(rt.data);
          var rtpref = M4[parse_TSP_Reference(rtp[1][0].data)][0];
          var mtype = varint_to_i32(rtpref.meta[1][0].data);
          if (mtype != 2001)
            throw new Error("2000 unexpected reference to ".concat(mtype));
          var tswpsa = parse_shallow(rtpref.data);
          var richtext = { v: tswpsa[3].map(function(x2) {
            return u8str(x2.data);
          }).join("") };
          data[key] = richtext;
          sfields:
            if ((_a7 = tswpsa == null ? void 0 : tswpsa[11]) == null ? void 0 : _a7[0]) {
              var smartfields = (_b = parse_shallow(tswpsa[11][0].data)) == null ? void 0 : _b[1];
              if (!smartfields)
                break sfields;
              smartfields.forEach(function(sf) {
                var _a22, _b2, _c;
                var attr = parse_shallow(sf.data);
                if ((_a22 = attr[2]) == null ? void 0 : _a22[0]) {
                  var obj = M4[parse_TSP_Reference((_b2 = attr[2]) == null ? void 0 : _b2[0].data)][0];
                  var objtype = varint_to_i32(obj.meta[1][0].data);
                  switch (objtype) {
                    case 2032:
                      var hlink = parse_shallow(obj.data);
                      if (((_c = hlink == null ? void 0 : hlink[2]) == null ? void 0 : _c[0]) && !richtext.l)
                        richtext.l = u8str(hlink[2][0].data);
                      break;
                    case 2039:
                      break;
                    default:
                      console.log("unrecognized ObjectAttribute type ".concat(objtype));
                  }
                }
              });
            }
        }
        break;
      case 2:
        data[key] = parse_shallow(le2[6][0].data);
        break;
      case 3:
        data[key] = parse_shallow(le2[5][0].data);
        break;
      case 10:
        {
          var cs = M4[parse_TSP_Reference(le2[10][0].data)][0];
          data[key] = parse_TSD_CommentStorageArchive(M4, cs.data);
        }
        break;
      default:
        throw type;
    }
  });
  return data;
}
function parse_TST_TileRowInfo(u8, type) {
  var _a7, _b, _c, _d, _e2, _f, _g, _h, _i, _j, _k, _l, _m, _n;
  var pb = parse_shallow(u8);
  var R3 = varint_to_i32(pb[1][0].data) >>> 0;
  var cnt = varint_to_i32(pb[2][0].data) >>> 0;
  var wide_offsets = ((_b = (_a7 = pb[8]) == null ? void 0 : _a7[0]) == null ? void 0 : _b.data) && varint_to_i32(pb[8][0].data) > 0 || false;
  var used_storage_u8, used_storage;
  if (((_d = (_c = pb[7]) == null ? void 0 : _c[0]) == null ? void 0 : _d.data) && type != 0) {
    used_storage_u8 = (_f = (_e2 = pb[7]) == null ? void 0 : _e2[0]) == null ? void 0 : _f.data;
    used_storage = (_h = (_g = pb[6]) == null ? void 0 : _g[0]) == null ? void 0 : _h.data;
  } else if (((_j = (_i = pb[4]) == null ? void 0 : _i[0]) == null ? void 0 : _j.data) && type != 1) {
    used_storage_u8 = (_l = (_k = pb[4]) == null ? void 0 : _k[0]) == null ? void 0 : _l.data;
    used_storage = (_n = (_m = pb[3]) == null ? void 0 : _m[0]) == null ? void 0 : _n.data;
  } else
    throw "NUMBERS Tile missing ".concat(type, " cell storage");
  var width = wide_offsets ? 4 : 1;
  var used_storage_offsets = u8_to_dataview(used_storage_u8);
  var offsets = [];
  for (var C3 = 0; C3 < used_storage_u8.length / 2; ++C3) {
    var off = used_storage_offsets.getUint16(C3 * 2, true);
    if (off < 65535)
      offsets.push([C3, off]);
  }
  if (offsets.length != cnt)
    throw "Expected ".concat(cnt, " cells, found ").concat(offsets.length);
  var cells = [];
  for (C3 = 0; C3 < offsets.length - 1; ++C3)
    cells[offsets[C3][0]] = used_storage[subarray](offsets[C3][1] * width, offsets[C3 + 1][1] * width);
  if (offsets.length >= 1)
    cells[offsets[offsets.length - 1][0]] = used_storage[subarray](offsets[offsets.length - 1][1] * width);
  return { R: R3, cells };
}
function parse_TST_Tile(M4, root) {
  var _a7;
  var pb = parse_shallow(root.data);
  var storage2 = -1;
  if ((_a7 = pb == null ? void 0 : pb[7]) == null ? void 0 : _a7[0]) {
    if (varint_to_i32(pb[7][0].data) >>> 0)
      storage2 = 1;
    else
      storage2 = 0;
  }
  var ri = mappa(pb[5], function(u8) {
    return parse_TST_TileRowInfo(u8, storage2);
  });
  return {
    nrows: varint_to_i32(pb[4][0].data) >>> 0,
    data: ri.reduce(function(acc, x2) {
      if (!acc[x2.R])
        acc[x2.R] = [];
      x2.cells.forEach(function(cell, C3) {
        if (acc[x2.R][C3])
          throw new Error("Duplicate cell r=".concat(x2.R, " c=").concat(C3));
        acc[x2.R][C3] = cell;
      });
      return acc;
    }, [])
  };
}
function parse_TSD_CommentStorageArchive(M4, data) {
  var _a7, _b, _c, _d, _e2, _f, _g, _h, _i, _j;
  var out = { t: "", a: "" };
  var csp = parse_shallow(data);
  if ((_b = (_a7 = csp == null ? void 0 : csp[1]) == null ? void 0 : _a7[0]) == null ? void 0 : _b.data)
    out.t = u8str((_d = (_c = csp == null ? void 0 : csp[1]) == null ? void 0 : _c[0]) == null ? void 0 : _d.data) || "";
  if ((_f = (_e2 = csp == null ? void 0 : csp[3]) == null ? void 0 : _e2[0]) == null ? void 0 : _f.data) {
    var as = M4[parse_TSP_Reference((_h = (_g = csp == null ? void 0 : csp[3]) == null ? void 0 : _g[0]) == null ? void 0 : _h.data)][0];
    var asp = parse_shallow(as.data);
    if ((_j = (_i = asp[1]) == null ? void 0 : _i[0]) == null ? void 0 : _j.data)
      out.a = u8str(asp[1][0].data);
  }
  if (csp == null ? void 0 : csp[4]) {
    out.replies = [];
    csp[4].forEach(function(pi) {
      var cs = M4[parse_TSP_Reference(pi.data)][0];
      out.replies.push(parse_TSD_CommentStorageArchive(M4, cs.data));
    });
  }
  return out;
}
function iwa_to_s5s_comment(iwa) {
  var out = [];
  out.push({ t: iwa.t || "", a: iwa.a, T: iwa.replies && iwa.replies.length > 0 });
  if (iwa.replies)
    iwa.replies.forEach(function(reply) {
      out.push({ t: reply.t || "", a: reply.a, T: true });
    });
  return out;
}
function parse_TST_TableModelArchive(M4, root, ws, opts) {
  var _a7, _b, _c, _d, _e2, _f, _g, _h, _i, _j, _k, _l, _m, _n;
  var pb = parse_shallow(root.data);
  var range2 = { s: { r: 0, c: 0 }, e: { r: 0, c: 0 } };
  range2.e.r = (varint_to_i32(pb[6][0].data) >>> 0) - 1;
  if (range2.e.r < 0)
    throw new Error("Invalid row varint ".concat(pb[6][0].data));
  range2.e.c = (varint_to_i32(pb[7][0].data) >>> 0) - 1;
  if (range2.e.c < 0)
    throw new Error("Invalid col varint ".concat(pb[7][0].data));
  ws["!ref"] = encode_range(range2);
  var dense = ws["!data"] != null, dws = ws;
  var store = parse_shallow(pb[4][0].data);
  var lut = numbers_lut_new();
  if ((_a7 = store[4]) == null ? void 0 : _a7[0])
    lut.sst = parse_TST_TableDataList(M4, M4[parse_TSP_Reference(store[4][0].data)][0]);
  if ((_b = store[6]) == null ? void 0 : _b[0])
    lut.fmla = parse_TST_TableDataList(M4, M4[parse_TSP_Reference(store[6][0].data)][0]);
  if ((_c = store[11]) == null ? void 0 : _c[0])
    lut.ofmt = parse_TST_TableDataList(M4, M4[parse_TSP_Reference(store[11][0].data)][0]);
  if ((_d = store[12]) == null ? void 0 : _d[0])
    lut.ferr = parse_TST_TableDataList(M4, M4[parse_TSP_Reference(store[12][0].data)][0]);
  if ((_e2 = store[17]) == null ? void 0 : _e2[0])
    lut.rsst = parse_TST_TableDataList(M4, M4[parse_TSP_Reference(store[17][0].data)][0]);
  if ((_f = store[19]) == null ? void 0 : _f[0])
    lut.cmnt = parse_TST_TableDataList(M4, M4[parse_TSP_Reference(store[19][0].data)][0]);
  if ((_g = store[22]) == null ? void 0 : _g[0])
    lut.nfmt = parse_TST_TableDataList(M4, M4[parse_TSP_Reference(store[22][0].data)][0]);
  var tile = parse_shallow(store[3][0].data);
  var _R = 0;
  if (!((_h = store[9]) == null ? void 0 : _h[0]))
    throw "NUMBERS file missing row tree";
  var rtt = parse_shallow(store[9][0].data)[1].map(function(p4) {
    return parse_shallow(p4.data);
  });
  rtt.forEach(function(kv) {
    _R = varint_to_i32(kv[1][0].data);
    var tidx = varint_to_i32(kv[2][0].data);
    var t6 = tile[1][tidx];
    if (!t6)
      throw "NUMBERS missing tile " + tidx;
    var tl = parse_shallow(t6.data);
    var ref2 = M4[parse_TSP_Reference(tl[2][0].data)][0];
    var mtype2 = varint_to_i32(ref2.meta[1][0].data);
    if (mtype2 != 6002)
      throw new Error("6001 unexpected reference to ".concat(mtype2));
    var _tile = parse_TST_Tile(M4, ref2);
    _tile.data.forEach(function(row, R3) {
      row.forEach(function(buf, C3) {
        var res = parse_cell_storage(buf, lut, opts);
        if (res) {
          if (dense) {
            if (!dws["!data"][_R + R3])
              dws["!data"][_R + R3] = [];
            dws["!data"][_R + R3][C3] = res;
          } else {
            ws[encode_col(C3) + encode_row(_R + R3)] = res;
          }
        }
      });
    });
    _R += _tile.nrows;
  });
  if ((_i = store[13]) == null ? void 0 : _i[0]) {
    var ref = M4[parse_TSP_Reference(store[13][0].data)][0];
    var mtype = varint_to_i32(ref.meta[1][0].data);
    if (mtype != 6144)
      throw new Error("Expected merge type 6144, found ".concat(mtype));
    ws["!merges"] = (_j = parse_shallow(ref.data)) == null ? void 0 : _j[1].map(function(pi) {
      var merge = parse_shallow(pi.data);
      var origin = u8_to_dataview(parse_shallow(merge[1][0].data)[1][0].data), size = u8_to_dataview(parse_shallow(merge[2][0].data)[1][0].data);
      return {
        s: { r: origin.getUint16(0, true), c: origin.getUint16(2, true) },
        e: {
          r: origin.getUint16(0, true) + size.getUint16(0, true) - 1,
          c: origin.getUint16(2, true) + size.getUint16(2, true) - 1
        }
      };
    });
  }
  if (!((_k = ws["!merges"]) == null ? void 0 : _k.length) && ((_l = pb[47]) == null ? void 0 : _l[0])) {
    var merge_owner = parse_shallow(pb[47][0].data);
    if ((_m = merge_owner[2]) == null ? void 0 : _m[0]) {
      var formula_store = parse_shallow(merge_owner[2][0].data);
      if ((_n = formula_store[3]) == null ? void 0 : _n[0]) {
        ws["!merges"] = mappa(formula_store[3], function(u5) {
          var _a22, _b2, _c2, _d2, _e22;
          var formula_pair = parse_shallow(u5);
          var formula = parse_shallow(formula_pair[2][0].data);
          var AST_node_array = parse_shallow(formula[1][0].data);
          if (!((_a22 = AST_node_array[1]) == null ? void 0 : _a22[0]))
            return;
          var AST_node0 = parse_shallow(AST_node_array[1][0].data);
          var AST_node_type = varint_to_i32(AST_node0[1][0].data);
          if (AST_node_type != 67)
            return;
          var AST_colon_tract = parse_shallow(AST_node0[40][0].data);
          if (!((_b2 = AST_colon_tract[3]) == null ? void 0 : _b2[0]) || !((_c2 = AST_colon_tract[4]) == null ? void 0 : _c2[0]))
            return;
          var colrange = parse_shallow(AST_colon_tract[3][0].data);
          var rowrange = parse_shallow(AST_colon_tract[4][0].data);
          var c6 = varint_to_i32(colrange[1][0].data);
          var C3 = ((_d2 = colrange[2]) == null ? void 0 : _d2[0]) ? varint_to_i32(colrange[2][0].data) : c6;
          var r8 = varint_to_i32(rowrange[1][0].data);
          var R3 = ((_e22 = rowrange[2]) == null ? void 0 : _e22[0]) ? varint_to_i32(rowrange[2][0].data) : r8;
          return { s: { r: r8, c: c6 }, e: { r: R3, c: C3 } };
        }).filter(function(x2) {
          return x2 != null;
        });
      }
    }
  }
}
function parse_TST_TableInfoArchive(M4, root, opts) {
  var pb = parse_shallow(root.data);
  var out = { "!ref": "A1" };
  if (opts == null ? void 0 : opts.dense)
    out["!data"] = [];
  var tableref = M4[parse_TSP_Reference(pb[2][0].data)];
  var mtype = varint_to_i32(tableref[0].meta[1][0].data);
  if (mtype != 6001)
    throw new Error("6000 unexpected reference to ".concat(mtype));
  parse_TST_TableModelArchive(M4, tableref[0], out, opts);
  return out;
}
function parse_TN_SheetArchive(M4, root, opts) {
  var _a7;
  var pb = parse_shallow(root.data);
  var out = {
    name: ((_a7 = pb[1]) == null ? void 0 : _a7[0]) ? u8str(pb[1][0].data) : "",
    sheets: []
  };
  var shapeoffs = mappa(pb[2], parse_TSP_Reference);
  shapeoffs.forEach(function(off) {
    M4[off].forEach(function(m4) {
      var mtype = varint_to_i32(m4.meta[1][0].data);
      if (mtype == 6e3)
        out.sheets.push(parse_TST_TableInfoArchive(M4, m4, opts));
    });
  });
  return out;
}
function parse_TN_DocumentArchive(M4, root, opts) {
  var _a7;
  var out = book_new();
  out.Workbook = { WBProps: { date1904: true } };
  var pb = parse_shallow(root.data);
  if ((_a7 = pb[2]) == null ? void 0 : _a7[0])
    throw new Error("Keynote presentations are not supported");
  var sheetoffs = mappa(pb[1], parse_TSP_Reference);
  sheetoffs.forEach(function(off) {
    M4[off].forEach(function(m4) {
      var mtype = varint_to_i32(m4.meta[1][0].data);
      if (mtype == 2) {
        var root2 = parse_TN_SheetArchive(M4, m4, opts);
        root2.sheets.forEach(function(sheet, idx) {
          book_append_sheet(out, sheet, idx == 0 ? root2.name : root2.name + "_" + idx, true);
        });
      }
    });
  });
  if (out.SheetNames.length == 0)
    throw new Error("Empty NUMBERS file");
  out.bookType = "numbers";
  return out;
}
function parse_numbers_iwa(cfb, opts) {
  var _a7, _b, _c, _d, _e2, _f, _g;
  var M4 = {}, indices = [];
  cfb.FullPaths.forEach(function(p4) {
    if (p4.match(/\.iwpv2/))
      throw new Error("Unsupported password protection");
  });
  cfb.FileIndex.forEach(function(s6) {
    if (!s6.name.match(/\.iwa$/))
      return;
    if (s6.content[0] != 0)
      return;
    var o9;
    try {
      o9 = decompress_iwa_file(s6.content);
    } catch (e9) {
      return console.log("?? " + s6.content.length + " " + (e9.message || e9));
    }
    var packets;
    try {
      packets = parse_iwa_file(o9);
    } catch (e9) {
      return console.log("## " + (e9.message || e9));
    }
    packets.forEach(function(packet) {
      M4[packet.id] = packet.messages;
      indices.push(packet.id);
    });
  });
  if (!indices.length)
    throw new Error("File has no messages");
  if (((_c = (_b = (_a7 = M4 == null ? void 0 : M4[1]) == null ? void 0 : _a7[0].meta) == null ? void 0 : _b[1]) == null ? void 0 : _c[0].data) && varint_to_i32(M4[1][0].meta[1][0].data) == 1e4)
    throw new Error("Pages documents are not supported");
  var docroot = ((_g = (_f = (_e2 = (_d = M4 == null ? void 0 : M4[1]) == null ? void 0 : _d[0]) == null ? void 0 : _e2.meta) == null ? void 0 : _f[1]) == null ? void 0 : _g[0].data) && varint_to_i32(M4[1][0].meta[1][0].data) == 1 && M4[1][0];
  if (!docroot)
    indices.forEach(function(idx) {
      M4[idx].forEach(function(iwam) {
        var mtype = varint_to_i32(iwam.meta[1][0].data) >>> 0;
        if (mtype == 1) {
          if (!docroot)
            docroot = iwam;
          else
            throw new Error("Document has multiple roots");
        }
      });
    });
  if (!docroot)
    throw new Error("Cannot find Document root");
  return parse_TN_DocumentArchive(M4, docroot, opts);
}
function fix_opts_func(defaults3) {
  return function fix_opts(opts) {
    for (var i7 = 0; i7 != defaults3.length; ++i7) {
      var d4 = defaults3[i7];
      if (opts[d4[0]] === void 0) opts[d4[0]] = d4[1];
      if (d4[2] === "n") opts[d4[0]] = Number(opts[d4[0]]);
    }
  };
}
function fix_read_opts(opts) {
  fix_opts_func([
    ["cellNF", false],
    /* emit cell number format string as .z */
    ["cellHTML", true],
    /* emit html string as .h */
    ["cellFormula", true],
    /* emit formulae as .f */
    ["cellStyles", false],
    /* emits style/theme as .s */
    ["cellText", true],
    /* emit formatted text as .w */
    ["cellDates", false],
    /* emit date cells with type `d` */
    ["sheetStubs", false],
    /* emit empty cells */
    ["sheetRows", 0, "n"],
    /* read n rows (0 = read all rows) */
    ["bookDeps", false],
    /* parse calculation chains */
    ["bookSheets", false],
    /* only try to get sheet names (no Sheets) */
    ["bookProps", false],
    /* only try to get properties (no Sheets) */
    ["bookFiles", false],
    /* include raw file structure (keys, files, cfb) */
    ["bookVBA", false],
    /* include vba raw data (vbaraw) */
    ["password", ""],
    /* password */
    ["WTF", false]
    /* WTF mode (throws errors) */
  ])(opts);
}
function get_sheet_type(n7) {
  if (RELS.WS.indexOf(n7) > -1) return "sheet";
  if (RELS.CS && n7 == RELS.CS) return "chart";
  if (RELS.DS && n7 == RELS.DS) return "dialog";
  if (RELS.MS && n7 == RELS.MS) return "macro";
  return n7 && n7.length ? n7 : "sheet";
}
function safe_parse_wbrels(wbrels, sheets) {
  if (!wbrels) return 0;
  try {
    wbrels = sheets.map(function pwbr(w3) {
      if (!w3.id) w3.id = w3.strRelID;
      return [w3.name, wbrels["!id"][w3.id].Target, get_sheet_type(wbrels["!id"][w3.id].Type)];
    });
  } catch (e9) {
    return null;
  }
  return !wbrels || wbrels.length === 0 ? null : wbrels;
}
function parse_sheet_legacy_drawing(sheet, type, zip, path6, idx, opts, wb, comments) {
  if (!sheet || !sheet["!legdrawel"]) return;
  var dfile = resolve_path(sheet["!legdrawel"].Target, path6);
  var draw = getzipstr(zip, dfile, true);
  if (draw) parse_vml(utf8read(draw), sheet, comments || []);
}
function safe_parse_sheet(zip, path6, relsPath, sheet, idx, sheetRels, sheets, stype, opts, wb, themes, styles2) {
  try {
    sheetRels[sheet] = parse_rels(getzipstr(zip, relsPath, true), path6);
    var data = getzipdata(zip, path6);
    var _ws;
    switch (stype) {
      case "sheet":
        _ws = parse_ws(data, path6, idx, opts, sheetRels[sheet], wb, themes, styles2);
        break;
      case "chart":
        _ws = parse_cs(data, path6, idx, opts, sheetRels[sheet], wb, themes, styles2);
        if (!_ws || !_ws["!drawel"]) break;
        var dfile = resolve_path(_ws["!drawel"].Target, path6);
        var drelsp = get_rels_path(dfile);
        var draw = parse_drawing(getzipstr(zip, dfile, true), parse_rels(getzipstr(zip, drelsp, true), dfile));
        var chartp = resolve_path(draw, dfile);
        var crelsp = get_rels_path(chartp);
        _ws = parse_chart(getzipstr(zip, chartp, true), chartp, opts, parse_rels(getzipstr(zip, crelsp, true), chartp), wb, _ws);
        break;
      case "macro":
        _ws = parse_ms(data, path6, idx, opts, sheetRels[sheet], wb, themes, styles2);
        break;
      case "dialog":
        _ws = parse_ds(data, path6, idx, opts, sheetRels[sheet], wb, themes, styles2);
        break;
      default:
        throw new Error("Unrecognized sheet type " + stype);
    }
    sheets[sheet] = _ws;
    var comments = [], tcomments = [];
    if (sheetRels && sheetRels[sheet]) keys(sheetRels[sheet]).forEach(function(n7) {
      var dfile2 = "";
      if (sheetRels[sheet][n7].Type == RELS.CMNT) {
        dfile2 = resolve_path(sheetRels[sheet][n7].Target, path6);
        comments = parse_cmnt(getzipdata(zip, dfile2, true), dfile2, opts);
        if (!comments || !comments.length) return;
        sheet_insert_comments(_ws, comments, false);
      }
      if (sheetRels[sheet][n7].Type == RELS.TCMNT) {
        dfile2 = resolve_path(sheetRels[sheet][n7].Target, path6);
        tcomments = tcomments.concat(parse_tcmnt_xml(getzipdata(zip, dfile2, true), opts));
      }
    });
    if (tcomments && tcomments.length) sheet_insert_comments(_ws, tcomments, true, opts.people || []);
    parse_sheet_legacy_drawing(_ws, stype, zip, path6, idx, opts, wb, comments);
  } catch (e9) {
    if (opts.WTF) throw e9;
  }
}
function strip_front_slash(x2) {
  return x2.charAt(0) == "/" ? x2.slice(1) : x2;
}
function parse_zip(zip, opts) {
  make_ssf();
  opts = opts || {};
  fix_read_opts(opts);
  if (safegetzipfile(zip, "META-INF/manifest.xml")) return parse_ods(zip, opts);
  if (safegetzipfile(zip, "objectdata.xml")) return parse_ods(zip, opts);
  if (safegetzipfile(zip, "Index/Document.iwa")) {
    if (typeof Uint8Array == "undefined") throw new Error("NUMBERS file parsing requires Uint8Array support");
    if (typeof parse_numbers_iwa != "undefined") {
      if (zip.FileIndex) return parse_numbers_iwa(zip, opts);
      var _zip = CFB.utils.cfb_new();
      zipentries(zip).forEach(function(e9) {
        zip_add_file(_zip, e9, getzipbin(zip, e9));
      });
      return parse_numbers_iwa(_zip, opts);
    }
    throw new Error("Unsupported NUMBERS file");
  }
  if (!safegetzipfile(zip, "[Content_Types].xml")) {
    if (safegetzipfile(zip, "index.xml.gz")) throw new Error("Unsupported NUMBERS 08 file");
    if (safegetzipfile(zip, "index.xml")) throw new Error("Unsupported NUMBERS 09 file");
    var index_zip = CFB.find(zip, "Index.zip");
    if (index_zip) {
      opts = dup(opts);
      delete opts.type;
      if (typeof index_zip.content == "string") opts.type = "binary";
      if (typeof Bun !== "undefined" && Buffer.isBuffer(index_zip.content)) return readSync(new Uint8Array(index_zip.content), opts);
      return readSync(index_zip.content, opts);
    }
    throw new Error("Unsupported ZIP file");
  }
  var entries = zipentries(zip);
  var dir = parse_ct(getzipstr(zip, "[Content_Types].xml"));
  var xlsb = false;
  var sheets, binname;
  if (dir.workbooks.length === 0) {
    binname = "xl/workbook.xml";
    if (getzipdata(zip, binname, true)) dir.workbooks.push(binname);
  }
  if (dir.workbooks.length === 0) {
    binname = "xl/workbook.bin";
    if (!getzipdata(zip, binname, true)) throw new Error("Could not find workbook");
    dir.workbooks.push(binname);
    xlsb = true;
  }
  if (dir.workbooks[0].slice(-3) == "bin") xlsb = true;
  var themes = {};
  var styles2 = {};
  if (!opts.bookSheets && !opts.bookProps) {
    strs = [];
    if (dir.sst) try {
      strs = parse_sst(getzipdata(zip, strip_front_slash(dir.sst)), dir.sst, opts);
    } catch (e9) {
      if (opts.WTF) throw e9;
    }
    if (opts.cellStyles && dir.themes.length) themes = parse_theme_xml(getzipstr(zip, dir.themes[0].replace(/^\//, ""), true) || "", opts);
    if (dir.style) styles2 = parse_sty(getzipdata(zip, strip_front_slash(dir.style)), dir.style, themes, opts);
  }
  dir.links.map(function(link) {
    try {
      var rels = parse_rels(getzipstr(zip, get_rels_path(strip_front_slash(link))), link);
      return parse_xlink(getzipdata(zip, strip_front_slash(link)), rels, link, opts);
    } catch (e9) {
    }
  });
  var wb = parse_wb(getzipdata(zip, strip_front_slash(dir.workbooks[0])), dir.workbooks[0], opts);
  var props = {}, propdata = "";
  if (dir.coreprops.length) {
    propdata = getzipdata(zip, strip_front_slash(dir.coreprops[0]), true);
    if (propdata) props = parse_core_props(propdata);
    if (dir.extprops.length !== 0) {
      propdata = getzipdata(zip, strip_front_slash(dir.extprops[0]), true);
      if (propdata) parse_ext_props(propdata, props, opts);
    }
  }
  var custprops = {};
  if (!opts.bookSheets || opts.bookProps) {
    if (dir.custprops.length !== 0) {
      propdata = getzipstr(zip, strip_front_slash(dir.custprops[0]), true);
      if (propdata) custprops = parse_cust_props(propdata, opts);
    }
  }
  var out = {};
  if (opts.bookSheets || opts.bookProps) {
    if (wb.Sheets) sheets = wb.Sheets.map(function pluck(x2) {
      return x2.name;
    });
    else if (props.Worksheets && props.SheetNames.length > 0) sheets = props.SheetNames;
    if (opts.bookProps) {
      out.Props = props;
      out.Custprops = custprops;
    }
    if (opts.bookSheets && typeof sheets !== "undefined") out.SheetNames = sheets;
    if (opts.bookSheets ? out.SheetNames : opts.bookProps) return out;
  }
  sheets = {};
  var deps = {};
  if (opts.bookDeps && dir.calcchain) deps = parse_cc(getzipdata(zip, strip_front_slash(dir.calcchain)), dir.calcchain, opts);
  var i7 = 0;
  var sheetRels = {};
  var path6, relsPath;
  {
    var wbsheets = wb.Sheets;
    props.Worksheets = wbsheets.length;
    props.SheetNames = [];
    for (var j3 = 0; j3 != wbsheets.length; ++j3) {
      props.SheetNames[j3] = wbsheets[j3].name;
    }
  }
  var wbext = xlsb ? "bin" : "xml";
  var wbrelsi = dir.workbooks[0].lastIndexOf("/");
  var wbrelsfile = (dir.workbooks[0].slice(0, wbrelsi + 1) + "_rels/" + dir.workbooks[0].slice(wbrelsi + 1) + ".rels").replace(/^\//, "");
  if (!safegetzipfile(zip, wbrelsfile)) wbrelsfile = "xl/_rels/workbook." + wbext + ".rels";
  var wbrels = parse_rels(getzipstr(zip, wbrelsfile, true), wbrelsfile.replace(/_rels.*/, "s5s"));
  if ((dir.metadata || []).length >= 1) {
    opts.xlmeta = parse_xlmeta(getzipdata(zip, strip_front_slash(dir.metadata[0])), dir.metadata[0], opts);
  }
  if ((dir.people || []).length >= 1) {
    opts.people = parse_people_xml(getzipdata(zip, strip_front_slash(dir.people[0])), opts);
  }
  if (wbrels) wbrels = safe_parse_wbrels(wbrels, wb.Sheets);
  var nmode = getzipdata(zip, "xl/worksheets/sheet.xml", true) ? 1 : 0;
  wsloop: for (i7 = 0; i7 != props.Worksheets; ++i7) {
    var stype = "sheet";
    if (wbrels && wbrels[i7]) {
      path6 = "xl/" + wbrels[i7][1].replace(/[\/]?xl\//, "");
      if (!safegetzipfile(zip, path6)) path6 = wbrels[i7][1];
      if (!safegetzipfile(zip, path6)) path6 = wbrelsfile.replace(/_rels\/[\S\s]*$/, "") + wbrels[i7][1];
      stype = wbrels[i7][2];
    } else {
      path6 = "xl/worksheets/sheet" + (i7 + 1 - nmode) + "." + wbext;
      path6 = path6.replace(/sheet0\./, "sheet.");
    }
    relsPath = path6.replace(/^(.*)(\/)([^\/]*)$/, "$1/_rels/$3.rels");
    if (opts && opts.sheets != null) switch (typeof opts.sheets) {
      case "number":
        if (i7 != opts.sheets) continue wsloop;
        break;
      case "string":
        if (props.SheetNames[i7].toLowerCase() != opts.sheets.toLowerCase()) continue wsloop;
        break;
      default:
        if (Array.isArray && Array.isArray(opts.sheets)) {
          var snjseen = false;
          for (var snj = 0; snj != opts.sheets.length; ++snj) {
            if (typeof opts.sheets[snj] == "number" && opts.sheets[snj] == i7) snjseen = 1;
            if (typeof opts.sheets[snj] == "string" && opts.sheets[snj].toLowerCase() == props.SheetNames[i7].toLowerCase()) snjseen = 1;
          }
          if (!snjseen) continue wsloop;
        }
    }
    safe_parse_sheet(zip, path6, relsPath, props.SheetNames[i7], i7, sheetRels, sheets, stype, opts, wb, themes, styles2);
  }
  out = {
    Directory: dir,
    Workbook: wb,
    Props: props,
    Custprops: custprops,
    Deps: deps,
    Sheets: sheets,
    SheetNames: props.SheetNames,
    Strings: strs,
    Styles: styles2,
    Themes: themes,
    SSF: dup(table_fmt)
  };
  if (opts && opts.bookFiles) {
    if (zip.files) {
      out.keys = entries;
      out.files = zip.files;
    } else {
      out.keys = [];
      out.files = {};
      zip.FullPaths.forEach(function(p4, idx) {
        p4 = p4.replace(/^Root Entry[\/]/, "");
        out.keys.push(p4);
        out.files[p4] = zip.FileIndex[idx];
      });
    }
  }
  if (opts && opts.bookVBA) {
    if (dir.vba.length > 0) out.vbaraw = getzipdata(zip, strip_front_slash(dir.vba[0]), true);
    else if (dir.defaults && dir.defaults.bin === CT_VBA) out.vbaraw = getzipdata(zip, "xl/vbaProject.bin", true);
  }
  out.bookType = xlsb ? "xlsb" : "xlsx";
  return out;
}
function parse_xlsxcfb(cfb, _opts) {
  var opts = _opts || {};
  var f4 = "Workbook", data = CFB.find(cfb, f4);
  try {
    f4 = "/!DataSpaces/Version";
    data = CFB.find(cfb, f4);
    if (!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f4);
    parse_DataSpaceVersionInfo(data.content);
    f4 = "/!DataSpaces/DataSpaceMap";
    data = CFB.find(cfb, f4);
    if (!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f4);
    var dsm = parse_DataSpaceMap(data.content);
    if (dsm.length !== 1 || dsm[0].comps.length !== 1 || dsm[0].comps[0].t !== 0 || dsm[0].name !== "StrongEncryptionDataSpace" || dsm[0].comps[0].v !== "EncryptedPackage")
      throw new Error("ECMA-376 Encrypted file bad " + f4);
    f4 = "/!DataSpaces/DataSpaceInfo/StrongEncryptionDataSpace";
    data = CFB.find(cfb, f4);
    if (!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f4);
    var seds = parse_DataSpaceDefinition(data.content);
    if (seds.length != 1 || seds[0] != "StrongEncryptionTransform")
      throw new Error("ECMA-376 Encrypted file bad " + f4);
    f4 = "/!DataSpaces/TransformInfo/StrongEncryptionTransform/!Primary";
    data = CFB.find(cfb, f4);
    if (!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f4);
    parse_Primary(data.content);
  } catch (e9) {
  }
  f4 = "/EncryptionInfo";
  data = CFB.find(cfb, f4);
  if (!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f4);
  var einfo = parse_EncryptionInfo(data.content);
  f4 = "/EncryptedPackage";
  data = CFB.find(cfb, f4);
  if (!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f4);
  if (einfo[0] == 4 && typeof decrypt_agile !== "undefined") return decrypt_agile(einfo[1], data.content, opts.password || "", opts);
  if (einfo[0] == 2 && typeof decrypt_std76 !== "undefined") return decrypt_std76(einfo[1], data.content, opts.password || "", opts);
  throw new Error("File is password-protected");
}
function firstbyte(f4, o9) {
  var x2 = "";
  switch ((o9 || {}).type || "base64") {
    case "buffer":
      return [f4[0], f4[1], f4[2], f4[3], f4[4], f4[5], f4[6], f4[7]];
    case "base64":
      x2 = Base64_decode(f4.slice(0, 12));
      break;
    case "binary":
      x2 = f4;
      break;
    case "array":
      return [f4[0], f4[1], f4[2], f4[3], f4[4], f4[5], f4[6], f4[7]];
    default:
      throw new Error("Unrecognized type " + (o9 && o9.type || "undefined"));
  }
  return [x2.charCodeAt(0), x2.charCodeAt(1), x2.charCodeAt(2), x2.charCodeAt(3), x2.charCodeAt(4), x2.charCodeAt(5), x2.charCodeAt(6), x2.charCodeAt(7)];
}
function read_cfb(cfb, opts) {
  if (CFB.find(cfb, "EncryptedPackage")) return parse_xlsxcfb(cfb, opts);
  return parse_xlscfb(cfb, opts);
}
function read_zip(data, opts) {
  var zip, d4 = data;
  var o9 = opts || {};
  if (!o9.type) o9.type = has_buf && Buffer.isBuffer(data) ? "buffer" : "base64";
  zip = zip_read(d4, o9);
  return parse_zip(zip, o9);
}
function read_plaintext(data, o9) {
  var i7 = 0;
  main: while (i7 < data.length) switch (data.charCodeAt(i7)) {
    case 10:
    case 13:
    case 32:
      ++i7;
      break;
    case 60:
      return parse_xlml(data.slice(i7), o9);
    default:
      break main;
  }
  return PRN.to_workbook(data, o9);
}
function read_plaintext_raw(data, o9) {
  var str2 = "", bytes = firstbyte(data, o9);
  switch (o9.type) {
    case "base64":
      str2 = Base64_decode(data);
      break;
    case "binary":
      str2 = data;
      break;
    case "buffer":
      str2 = data.toString("binary");
      break;
    case "array":
      str2 = cc2str(data);
      break;
    default:
      throw new Error("Unrecognized type " + o9.type);
  }
  if (bytes[0] == 239 && bytes[1] == 187 && bytes[2] == 191) str2 = utf8read(str2);
  o9.type = "binary";
  return read_plaintext(str2, o9);
}
function read_utf16(data, o9) {
  var d4 = data;
  if (o9.type == "base64") d4 = Base64_decode(d4);
  if (typeof ArrayBuffer !== "undefined" && data instanceof ArrayBuffer) d4 = new Uint8Array(data);
  d4 = typeof $cptable !== "undefined" ? $cptable.utils.decode(1200, d4.slice(2), "str") : has_buf && Buffer.isBuffer(data) ? data.slice(2).toString("utf16le") : typeof Uint8Array !== "undefined" && d4 instanceof Uint8Array ? typeof TextDecoder !== "undefined" ? new TextDecoder("utf-16le").decode(d4.slice(2)) : utf16lereadu(d4.slice(2)) : utf16leread(d4.slice(2));
  o9.type = "binary";
  return read_plaintext(d4, o9);
}
function bstrify(data) {
  return !data.match(/[^\x00-\x7F]/) ? data : utf8write(data);
}
function read_prn(data, d4, o9, str2) {
  if (str2) {
    o9.type = "string";
    return PRN.to_workbook(data, o9);
  }
  return PRN.to_workbook(d4, o9);
}
function readSync(data, opts) {
  reset_cp();
  var o9 = opts || {};
  if (o9.codepage && typeof $cptable === "undefined") console.error("Codepage tables are not loaded.  Non-ASCII characters may not give expected results");
  if (typeof ArrayBuffer !== "undefined" && data instanceof ArrayBuffer) return readSync(new Uint8Array(data), (o9 = dup(o9), o9.type = "array", o9));
  if (typeof Int8Array !== "undefined" && data instanceof Int8Array) return readSync(new Uint8Array(data.buffer, data.byteOffset, data.length), o9);
  if (typeof Uint8Array !== "undefined" && data instanceof Uint8Array && !o9.type) o9.type = typeof Deno !== "undefined" ? "buffer" : "array";
  var d4 = data, n7 = [0, 0, 0, 0], str2 = false;
  if (o9.cellStyles) {
    o9.cellNF = true;
    o9.sheetStubs = true;
  }
  _ssfopts = {};
  if (o9.dateNF) _ssfopts.dateNF = o9.dateNF;
  if (!o9.type) o9.type = has_buf && Buffer.isBuffer(data) ? "buffer" : "base64";
  if (o9.type == "file") {
    o9.type = has_buf ? "buffer" : "binary";
    d4 = read_binary(data);
    if (typeof Uint8Array !== "undefined" && !has_buf) o9.type = "array";
  }
  if (o9.type == "string") {
    str2 = true;
    o9.type = "binary";
    o9.codepage = 65001;
    d4 = bstrify(data);
  }
  if (o9.type == "array" && typeof Uint8Array !== "undefined" && data instanceof Uint8Array && typeof ArrayBuffer !== "undefined") {
    var ab = new ArrayBuffer(3), vu = new Uint8Array(ab);
    vu.foo = "bar";
    if (!vu.foo) {
      o9 = dup(o9);
      o9.type = "array";
      return readSync(ab2a(d4), o9);
    }
  }
  switch ((n7 = firstbyte(d4, o9))[0]) {
    case 208:
      if (n7[1] === 207 && n7[2] === 17 && n7[3] === 224 && n7[4] === 161 && n7[5] === 177 && n7[6] === 26 && n7[7] === 225) return read_cfb(CFB.read(d4, o9), o9);
      break;
    case 9:
      if (n7[1] <= 8) return parse_xlscfb(d4, o9);
      break;
    case 60:
      return parse_xlml(d4, o9);
    case 73:
      if (n7[1] === 73 && n7[2] === 42 && n7[3] === 0) throw new Error("TIFF Image File is not a spreadsheet");
      if (n7[1] === 68) return read_wb_ID(d4, o9);
      break;
    case 84:
      if (n7[1] === 65 && n7[2] === 66 && n7[3] === 76) return DIF.to_workbook(d4, o9);
      break;
    case 80:
      return n7[1] === 75 && n7[2] < 9 && n7[3] < 9 ? read_zip(d4, o9) : read_prn(data, d4, o9, str2);
    case 239:
      return n7[3] === 60 ? parse_xlml(d4, o9) : read_prn(data, d4, o9, str2);
    case 255:
      if (n7[1] === 254) {
        return read_utf16(d4, o9);
      } else if (n7[1] === 0 && n7[2] === 2 && n7[3] === 0) return WK_.to_workbook(d4, o9);
      break;
    case 0:
      if (n7[1] === 0) {
        if (n7[2] >= 2 && n7[3] === 0) return WK_.to_workbook(d4, o9);
        if (n7[2] === 0 && (n7[3] === 8 || n7[3] === 9)) return WK_.to_workbook(d4, o9);
      }
      break;
    case 3:
    case 131:
    case 139:
    case 140:
      return DBF.to_workbook(d4, o9);
    case 123:
      if (n7[1] === 92 && n7[2] === 114 && n7[3] === 116) return rtf_to_workbook(d4, o9);
      break;
    case 10:
    case 13:
    case 32:
      return read_plaintext_raw(d4, o9);
    case 137:
      if (n7[1] === 80 && n7[2] === 78 && n7[3] === 71) throw new Error("PNG Image File is not a spreadsheet");
      break;
    case 8:
      if (n7[1] === 231) throw new Error("Unsupported Multiplan 1.x file!");
      break;
    case 12:
      if (n7[1] === 236) throw new Error("Unsupported Multiplan 2.x file!");
      if (n7[1] === 237) throw new Error("Unsupported Multiplan 3.x file!");
      break;
  }
  if (DBF_SUPPORTED_VERSIONS.indexOf(n7[0]) > -1 && n7[2] <= 12 && n7[3] <= 31) return DBF.to_workbook(d4, o9);
  return read_prn(data, d4, o9, str2);
}
function make_json_row(sheet, r8, R3, cols, header, hdr, o9) {
  var rr = encode_row(R3);
  var defval = o9.defval, raw = o9.raw || !Object.prototype.hasOwnProperty.call(o9, "raw");
  var isempty = true, dense = sheet["!data"] != null;
  var row = header === 1 ? [] : {};
  if (header !== 1) {
    if (Object.defineProperty) try {
      Object.defineProperty(row, "__rowNum__", { value: R3, enumerable: false });
    } catch (e9) {
      row.__rowNum__ = R3;
    }
    else row.__rowNum__ = R3;
  }
  if (!dense || sheet["!data"][R3]) for (var C3 = r8.s.c; C3 <= r8.e.c; ++C3) {
    var val2 = dense ? (sheet["!data"][R3] || [])[C3] : sheet[cols[C3] + rr];
    if (val2 == null || val2.t === void 0) {
      if (defval === void 0) continue;
      if (hdr[C3] != null) {
        row[hdr[C3]] = defval;
      }
      continue;
    }
    var v4 = val2.v;
    switch (val2.t) {
      case "z":
        if (v4 == null) break;
        continue;
      case "e":
        v4 = v4 == 0 ? null : void 0;
        break;
      case "s":
      case "b":
      case "n":
        if (!val2.z || !fmt_is_date(val2.z)) break;
        v4 = numdate(v4);
        if (typeof v4 == "number") break;
      /* falls through */
      case "d":
        if (!(o9 && (o9.UTC || o9.raw === false))) v4 = utc_to_local(new Date(v4));
        break;
      default:
        throw new Error("unrecognized type " + val2.t);
    }
    if (hdr[C3] != null) {
      if (v4 == null) {
        if (val2.t == "e" && v4 === null) row[hdr[C3]] = null;
        else if (defval !== void 0) row[hdr[C3]] = defval;
        else if (raw && v4 === null) row[hdr[C3]] = null;
        else continue;
      } else {
        row[hdr[C3]] = (val2.t === "n" && typeof o9.rawNumbers === "boolean" ? o9.rawNumbers : raw) ? v4 : format_cell(val2, v4, o9);
      }
      if (v4 != null) isempty = false;
    }
  }
  return { row, isempty };
}
function sheet_to_json(sheet, opts) {
  if (sheet == null || sheet["!ref"] == null) return [];
  var val2 = { t: "n", v: 0 }, header = 0, offset = 1, hdr = [], v4 = 0, vv = "";
  var r8 = { s: { r: 0, c: 0 }, e: { r: 0, c: 0 } };
  var o9 = opts || {};
  var range2 = o9.range != null ? o9.range : sheet["!ref"];
  if (o9.header === 1) header = 1;
  else if (o9.header === "A") header = 2;
  else if (Array.isArray(o9.header)) header = 3;
  else if (o9.header == null) header = 0;
  switch (typeof range2) {
    case "string":
      r8 = safe_decode_range(range2);
      break;
    case "number":
      r8 = safe_decode_range(sheet["!ref"]);
      r8.s.r = range2;
      break;
    default:
      r8 = range2;
  }
  if (header > 0) offset = 0;
  var rr = encode_row(r8.s.r);
  var cols = [];
  var out = [];
  var outi = 0, counter = 0;
  var dense = sheet["!data"] != null;
  var R3 = r8.s.r, C3 = 0;
  var header_cnt = {};
  if (dense && !sheet["!data"][R3]) sheet["!data"][R3] = [];
  var colinfo = o9.skipHidden && sheet["!cols"] || [];
  var rowinfo = o9.skipHidden && sheet["!rows"] || [];
  for (C3 = r8.s.c; C3 <= r8.e.c; ++C3) {
    if ((colinfo[C3] || {}).hidden) continue;
    cols[C3] = encode_col(C3);
    val2 = dense ? sheet["!data"][R3][C3] : sheet[cols[C3] + rr];
    switch (header) {
      case 1:
        hdr[C3] = C3 - r8.s.c;
        break;
      case 2:
        hdr[C3] = cols[C3];
        break;
      case 3:
        hdr[C3] = o9.header[C3 - r8.s.c];
        break;
      default:
        if (val2 == null) val2 = { w: "__EMPTY", t: "s" };
        vv = v4 = format_cell(val2, null, o9);
        counter = header_cnt[v4] || 0;
        if (!counter) header_cnt[v4] = 1;
        else {
          do {
            vv = v4 + "_" + counter++;
          } while (header_cnt[vv]);
          header_cnt[v4] = counter;
          header_cnt[vv] = 1;
        }
        hdr[C3] = vv;
    }
  }
  for (R3 = r8.s.r + offset; R3 <= r8.e.r; ++R3) {
    if ((rowinfo[R3] || {}).hidden) continue;
    var row = make_json_row(sheet, r8, R3, cols, header, hdr, o9);
    if (row.isempty === false || (header === 1 ? o9.blankrows !== false : !!o9.blankrows)) out[outi++] = row.row;
  }
  out.length = outi;
  return out;
}
var qreg = /"/g;
function make_csv_row(sheet, r8, R3, cols, fs, rs, FS, w3, o9) {
  var isempty = true;
  var row = [], txt = "", rr = encode_row(R3);
  var dense = sheet["!data"] != null;
  var datarow = dense && sheet["!data"][R3] || [];
  for (var C3 = r8.s.c; C3 <= r8.e.c; ++C3) {
    if (!cols[C3]) continue;
    var val2 = dense ? datarow[C3] : sheet[cols[C3] + rr];
    if (val2 == null) txt = "";
    else if (val2.v != null) {
      isempty = false;
      txt = "" + (o9.rawNumbers && val2.t == "n" ? val2.v : format_cell(val2, null, o9));
      for (var i7 = 0, cc = 0; i7 !== txt.length; ++i7) if ((cc = txt.charCodeAt(i7)) === fs || cc === rs || cc === 34 || o9.forceQuotes) {
        txt = '"' + txt.replace(qreg, '""') + '"';
        break;
      }
      if (txt == "ID" && w3 == 0 && row.length == 0) txt = '"ID"';
    } else if (val2.f != null && !val2.F) {
      isempty = false;
      txt = "=" + val2.f;
      if (txt.indexOf(",") >= 0) txt = '"' + txt.replace(qreg, '""') + '"';
    } else txt = "";
    row.push(txt);
  }
  if (o9.strip) while (row[row.length - 1] === "") --row.length;
  if (o9.blankrows === false && isempty) return null;
  return row.join(FS);
}
function sheet_to_csv(sheet, opts) {
  var out = [];
  var o9 = opts == null ? {} : opts;
  if (sheet == null || sheet["!ref"] == null) return "";
  var r8 = safe_decode_range(sheet["!ref"]);
  var FS = o9.FS !== void 0 ? o9.FS : ",", fs = FS.charCodeAt(0);
  var RS = o9.RS !== void 0 ? o9.RS : "\n", rs = RS.charCodeAt(0);
  var row = "", cols = [];
  var colinfo = o9.skipHidden && sheet["!cols"] || [];
  var rowinfo = o9.skipHidden && sheet["!rows"] || [];
  for (var C3 = r8.s.c; C3 <= r8.e.c; ++C3) if (!(colinfo[C3] || {}).hidden) cols[C3] = encode_col(C3);
  var w3 = 0;
  for (var R3 = r8.s.r; R3 <= r8.e.r; ++R3) {
    if ((rowinfo[R3] || {}).hidden) continue;
    row = make_csv_row(sheet, r8, R3, cols, fs, rs, FS, w3, o9);
    if (row == null) {
      continue;
    }
    if (row || o9.blankrows !== false) out.push((w3++ ? RS : "") + row);
  }
  return out.join("");
}
function sheet_to_txt(sheet, opts) {
  if (!opts) opts = {};
  opts.FS = "	";
  opts.RS = "\n";
  var s6 = sheet_to_csv(sheet, opts);
  if (typeof $cptable == "undefined" || opts.type == "string") return s6;
  var o9 = $cptable.utils.encode(1200, s6, "str");
  return String.fromCharCode(255) + String.fromCharCode(254) + o9;
}
function sheet_to_formulae(sheet, opts) {
  var y4 = "", x2, val2 = "";
  if (sheet == null || sheet["!ref"] == null) return [];
  var r8 = safe_decode_range(sheet["!ref"]), rr = "", cols = [], C3;
  var cmds = [];
  var dense = sheet["!data"] != null;
  for (C3 = r8.s.c; C3 <= r8.e.c; ++C3) cols[C3] = encode_col(C3);
  for (var R3 = r8.s.r; R3 <= r8.e.r; ++R3) {
    rr = encode_row(R3);
    for (C3 = r8.s.c; C3 <= r8.e.c; ++C3) {
      y4 = cols[C3] + rr;
      x2 = dense ? (sheet["!data"][R3] || [])[C3] : sheet[y4];
      val2 = "";
      if (x2 === void 0) continue;
      else if (x2.F != null) {
        y4 = x2.F;
        if (!x2.f) continue;
        val2 = x2.f;
        if (y4.indexOf(":") == -1) y4 = y4 + ":" + y4;
      }
      if (x2.f != null) val2 = x2.f;
      else if (opts && opts.values === false) continue;
      else if (x2.t == "z") continue;
      else if (x2.t == "n" && x2.v != null) val2 = "" + x2.v;
      else if (x2.t == "b") val2 = x2.v ? "TRUE" : "FALSE";
      else if (x2.w !== void 0) val2 = "'" + x2.w;
      else if (x2.v === void 0) continue;
      else if (x2.t == "s") val2 = "'" + x2.v;
      else val2 = "" + x2.v;
      cmds[cmds.length] = y4 + "=" + val2;
    }
  }
  return cmds;
}
function sheet_add_json(_ws, js, opts) {
  var o9 = opts || {};
  var dense = _ws ? _ws["!data"] != null : o9.dense;
  if (DENSE != null && dense == null) dense = DENSE;
  var offset = +!o9.skipHeader;
  var ws = _ws || {};
  if (!_ws && dense) ws["!data"] = [];
  var _R = 0, _C = 0;
  if (ws && o9.origin != null) {
    if (typeof o9.origin == "number") _R = o9.origin;
    else {
      var _origin = typeof o9.origin == "string" ? decode_cell(o9.origin) : o9.origin;
      _R = _origin.r;
      _C = _origin.c;
    }
  }
  var range2 = { s: { c: 0, r: 0 }, e: { c: _C, r: _R + js.length - 1 + offset } };
  if (ws["!ref"]) {
    var _range = safe_decode_range(ws["!ref"]);
    range2.e.c = Math.max(range2.e.c, _range.e.c);
    range2.e.r = Math.max(range2.e.r, _range.e.r);
    if (_R == -1) {
      _R = _range.e.r + 1;
      range2.e.r = _R + js.length - 1 + offset;
    }
  } else {
    if (_R == -1) {
      _R = 0;
      range2.e.r = js.length - 1 + offset;
    }
  }
  var hdr = o9.header || [], C3 = 0;
  var ROW = [];
  js.forEach(function(JS, R3) {
    if (dense && !ws["!data"][_R + R3 + offset]) ws["!data"][_R + R3 + offset] = [];
    if (dense) ROW = ws["!data"][_R + R3 + offset];
    keys(JS).forEach(function(k2) {
      if ((C3 = hdr.indexOf(k2)) == -1) hdr[C3 = hdr.length] = k2;
      var v4 = JS[k2];
      var t6 = "z";
      var z3 = "";
      var ref = dense ? "" : encode_col(_C + C3) + encode_row(_R + R3 + offset);
      var cell = dense ? ROW[_C + C3] : ws[ref];
      if (v4 && typeof v4 === "object" && !(v4 instanceof Date)) {
        if (dense) ROW[_C + C3] = v4;
        else ws[ref] = v4;
      } else {
        if (typeof v4 == "number") t6 = "n";
        else if (typeof v4 == "boolean") t6 = "b";
        else if (typeof v4 == "string") t6 = "s";
        else if (v4 instanceof Date) {
          t6 = "d";
          if (!o9.UTC) v4 = local_to_utc(v4);
          if (!o9.cellDates) {
            t6 = "n";
            v4 = datenum(v4);
          }
          z3 = cell != null && cell.z && fmt_is_date(cell.z) ? cell.z : o9.dateNF || table_fmt[14];
        } else if (v4 === null && o9.nullError) {
          t6 = "e";
          v4 = 0;
        }
        if (!cell) {
          if (!dense) ws[ref] = cell = { t: t6, v: v4 };
          else ROW[_C + C3] = cell = { t: t6, v: v4 };
        } else {
          cell.t = t6;
          cell.v = v4;
          delete cell.w;
          delete cell.R;
          if (z3) cell.z = z3;
        }
        if (z3) cell.z = z3;
      }
    });
  });
  range2.e.c = Math.max(range2.e.c, _C + hdr.length - 1);
  var __R = encode_row(_R);
  if (dense && !ws["!data"][_R]) ws["!data"][_R] = [];
  if (offset) for (C3 = 0; C3 < hdr.length; ++C3) {
    if (dense) ws["!data"][_R][C3 + _C] = { t: "s", v: hdr[C3] };
    else ws[encode_col(C3 + _C) + __R] = { t: "s", v: hdr[C3] };
  }
  ws["!ref"] = encode_range(range2);
  return ws;
}
function json_to_sheet(js, opts) {
  return sheet_add_json(null, js, opts);
}
function ws_get_cell_stub(ws, R3, C3) {
  if (typeof R3 == "string") {
    if (ws["!data"] != null) {
      var RC = decode_cell(R3);
      if (!ws["!data"][RC.r]) ws["!data"][RC.r] = [];
      return ws["!data"][RC.r][RC.c] || (ws["!data"][RC.r][RC.c] = { t: "z" });
    }
    return ws[R3] || (ws[R3] = { t: "z" });
  }
  if (typeof R3 != "number") return ws_get_cell_stub(ws, encode_cell(R3));
  return ws_get_cell_stub(ws, encode_col(C3 || 0) + encode_row(R3));
}
function wb_sheet_idx(wb, sh) {
  if (typeof sh == "number") {
    if (sh >= 0 && wb.SheetNames.length > sh) return sh;
    throw new Error("Cannot find sheet # " + sh);
  } else if (typeof sh == "string") {
    var idx = wb.SheetNames.indexOf(sh);
    if (idx > -1) return idx;
    throw new Error("Cannot find sheet name |" + sh + "|");
  } else throw new Error("Cannot find sheet |" + sh + "|");
}
function book_new(ws, wsname) {
  var wb = { SheetNames: [], Sheets: {} };
  if (ws) book_append_sheet(wb, ws, wsname || "Sheet1");
  return wb;
}
function book_append_sheet(wb, ws, name, roll) {
  var i7 = 1;
  if (!name) {
    for (; i7 <= 65535; ++i7, name = void 0) if (wb.SheetNames.indexOf(name = "Sheet" + i7) == -1) break;
  }
  if (!name || wb.SheetNames.length >= 65535) throw new Error("Too many worksheets");
  if (roll && wb.SheetNames.indexOf(name) >= 0 && name.length < 32) {
    var m4 = name.match(/\d+$/);
    i7 = m4 && +m4[0] || 0;
    var root = m4 && name.slice(0, m4.index) || name;
    for (++i7; i7 <= 65535; ++i7) if (wb.SheetNames.indexOf(name = root + i7) == -1) break;
  }
  check_ws_name(name);
  if (wb.SheetNames.indexOf(name) >= 0) throw new Error("Worksheet with name |" + name + "| already exists!");
  wb.SheetNames.push(name);
  wb.Sheets[name] = ws;
  return name;
}
function book_set_sheet_visibility(wb, sh, vis) {
  if (!wb.Workbook) wb.Workbook = {};
  if (!wb.Workbook.Sheets) wb.Workbook.Sheets = [];
  var idx = wb_sheet_idx(wb, sh);
  if (!wb.Workbook.Sheets[idx]) wb.Workbook.Sheets[idx] = {};
  switch (vis) {
    case 0:
    case 1:
    case 2:
      break;
    default:
      throw new Error("Bad sheet visibility setting " + vis);
  }
  wb.Workbook.Sheets[idx].Hidden = vis;
}
function cell_set_number_format(cell, fmt) {
  cell.z = fmt;
  return cell;
}
function cell_set_hyperlink(cell, target, tooltip) {
  if (!target) {
    delete cell.l;
  } else {
    cell.l = { Target: target };
    if (tooltip) cell.l.Tooltip = tooltip;
  }
  return cell;
}
function cell_set_internal_link(cell, range2, tooltip) {
  return cell_set_hyperlink(cell, "#" + range2, tooltip);
}
function cell_add_comment(cell, text3, author) {
  if (!cell.c) cell.c = [];
  cell.c.push({ t: text3, a: author || "SheetJS" });
}
function sheet_set_array_formula(ws, range2, formula, dynamic) {
  var rng = typeof range2 != "string" ? range2 : safe_decode_range(range2);
  var rngstr = typeof range2 == "string" ? range2 : encode_range(range2);
  for (var R3 = rng.s.r; R3 <= rng.e.r; ++R3) for (var C3 = rng.s.c; C3 <= rng.e.c; ++C3) {
    var cell = ws_get_cell_stub(ws, R3, C3);
    cell.t = "n";
    cell.F = rngstr;
    delete cell.v;
    if (R3 == rng.s.r && C3 == rng.s.c) {
      cell.f = formula;
      if (dynamic) cell.D = true;
    }
  }
  var wsr = decode_range(ws["!ref"]);
  if (wsr.s.r > rng.s.r) wsr.s.r = rng.s.r;
  if (wsr.s.c > rng.s.c) wsr.s.c = rng.s.c;
  if (wsr.e.r < rng.e.r) wsr.e.r = rng.e.r;
  if (wsr.e.c < rng.e.c) wsr.e.c = rng.e.c;
  ws["!ref"] = encode_range(wsr);
  return ws;
}
var utils = {
  encode_col,
  encode_row,
  encode_cell,
  encode_range,
  decode_col,
  decode_row,
  split_cell,
  decode_cell,
  decode_range,
  format_cell,
  sheet_new,
  sheet_add_aoa,
  sheet_add_json,
  sheet_add_dom,
  aoa_to_sheet,
  json_to_sheet,
  table_to_sheet: parse_dom_table,
  table_to_book,
  sheet_to_csv,
  sheet_to_txt,
  sheet_to_json,
  sheet_to_html,
  sheet_to_formulae,
  sheet_to_row_object_array: sheet_to_json,
  sheet_get_cell: ws_get_cell_stub,
  book_new,
  book_append_sheet,
  book_set_sheet_visibility,
  cell_set_number_format,
  cell_set_hyperlink,
  cell_set_internal_link,
  cell_add_comment,
  sheet_set_array_formula,
  consts: {
    SHEET_VISIBLE: 0,
    SHEET_HIDDEN: 1,
    SHEET_VERY_HIDDEN: 2
  }
};
var version3 = XLSX.version;

// ../pi-mono/packages/web-ui/dist/utils/attachment-utils.js
GlobalWorkerOptions.workerSrc = new URL("pdfjs-dist/build/pdf.worker.min.mjs", import.meta.url).toString();
async function loadAttachment(source, fileName) {
  let arrayBuffer;
  let detectedFileName = fileName || "unnamed";
  let mimeType = "application/octet-stream";
  let size = 0;
  if (typeof source === "string") {
    const response = await fetch(source);
    if (!response.ok) {
      throw new Error(i18n("Failed to fetch file"));
    }
    arrayBuffer = await response.arrayBuffer();
    size = arrayBuffer.byteLength;
    mimeType = response.headers.get("content-type") || mimeType;
    if (!fileName) {
      const urlParts = source.split("/");
      detectedFileName = urlParts[urlParts.length - 1] || "document";
    }
  } else if (source instanceof File) {
    arrayBuffer = await source.arrayBuffer();
    size = source.size;
    mimeType = source.type || mimeType;
    detectedFileName = fileName || source.name;
  } else if (source instanceof Blob) {
    arrayBuffer = await source.arrayBuffer();
    size = source.size;
    mimeType = source.type || mimeType;
  } else if (source instanceof ArrayBuffer) {
    arrayBuffer = source;
    size = source.byteLength;
  } else {
    throw new Error(i18n("Invalid source type"));
  }
  const uint8Array = new Uint8Array(arrayBuffer);
  let binary = "";
  const chunkSize = 32768;
  for (let i7 = 0; i7 < uint8Array.length; i7 += chunkSize) {
    const chunk = uint8Array.slice(i7, i7 + chunkSize);
    binary += String.fromCharCode(...chunk);
  }
  const base64Content = btoa(binary);
  const id = `${detectedFileName}_${Date.now()}_${Math.random()}`;
  if (mimeType === "application/pdf" || detectedFileName.toLowerCase().endsWith(".pdf")) {
    const { extractedText, preview } = await processPdf(arrayBuffer, detectedFileName);
    return {
      id,
      type: "document",
      fileName: detectedFileName,
      mimeType: "application/pdf",
      size,
      content: base64Content,
      extractedText,
      preview
    };
  }
  if (mimeType === "application/vnd.openxmlformats-officedocument.wordprocessingml.document" || detectedFileName.toLowerCase().endsWith(".docx")) {
    const { extractedText } = await processDocx(arrayBuffer, detectedFileName);
    return {
      id,
      type: "document",
      fileName: detectedFileName,
      mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      size,
      content: base64Content,
      extractedText
    };
  }
  if (mimeType === "application/vnd.openxmlformats-officedocument.presentationml.presentation" || detectedFileName.toLowerCase().endsWith(".pptx")) {
    const { extractedText } = await processPptx(arrayBuffer, detectedFileName);
    return {
      id,
      type: "document",
      fileName: detectedFileName,
      mimeType: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
      size,
      content: base64Content,
      extractedText
    };
  }
  const excelMimeTypes = [
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    "application/vnd.ms-excel"
  ];
  if (excelMimeTypes.includes(mimeType) || detectedFileName.toLowerCase().endsWith(".xlsx") || detectedFileName.toLowerCase().endsWith(".xls")) {
    const { extractedText } = await processExcel(arrayBuffer, detectedFileName);
    return {
      id,
      type: "document",
      fileName: detectedFileName,
      mimeType: mimeType.startsWith("application/vnd") ? mimeType : "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      size,
      content: base64Content,
      extractedText
    };
  }
  if (mimeType.startsWith("image/")) {
    return {
      id,
      type: "image",
      fileName: detectedFileName,
      mimeType,
      size,
      content: base64Content,
      preview: base64Content
      // For images, preview is the same as content
    };
  }
  const textExtensions = [
    ".txt",
    ".md",
    ".json",
    ".xml",
    ".html",
    ".css",
    ".js",
    ".ts",
    ".jsx",
    ".tsx",
    ".yml",
    ".yaml"
  ];
  const isTextFile = mimeType.startsWith("text/") || textExtensions.some((ext2) => detectedFileName.toLowerCase().endsWith(ext2));
  if (isTextFile) {
    const decoder = new TextDecoder();
    const text3 = decoder.decode(arrayBuffer);
    return {
      id,
      type: "document",
      fileName: detectedFileName,
      mimeType: mimeType.startsWith("text/") ? mimeType : "text/plain",
      size,
      content: base64Content,
      extractedText: text3
    };
  }
  throw new Error(`Unsupported file type: ${mimeType}`);
}
async function processPdf(arrayBuffer, fileName) {
  let pdf = null;
  try {
    pdf = await getDocument({ data: arrayBuffer }).promise;
    let extractedText = `<pdf filename="${fileName}">`;
    for (let i7 = 1; i7 <= pdf.numPages; i7++) {
      const page = await pdf.getPage(i7);
      const textContent = await page.getTextContent();
      const pageText = textContent.items.map((item) => item.str).filter((str2) => str2.trim()).join(" ");
      extractedText += `
<page number="${i7}">
${pageText}
</page>`;
    }
    extractedText += "\n</pdf>";
    const preview = await generatePdfPreview(pdf);
    return { extractedText, preview };
  } catch (error) {
    console.error("Error processing PDF:", error);
    throw new Error(`Failed to process PDF: ${String(error)}`);
  } finally {
    if (pdf) {
      pdf.destroy();
    }
  }
}
async function generatePdfPreview(pdf) {
  try {
    const page = await pdf.getPage(1);
    const viewport = page.getViewport({ scale: 1 });
    const scale = Math.min(160 / viewport.width, 160 / viewport.height);
    const scaledViewport = page.getViewport({ scale });
    const canvas = document.createElement("canvas");
    const context = canvas.getContext("2d");
    if (!context) {
      return void 0;
    }
    canvas.height = scaledViewport.height;
    canvas.width = scaledViewport.width;
    const renderContext = {
      canvasContext: context,
      viewport: scaledViewport,
      canvas
    };
    await page.render(renderContext).promise;
    return canvas.toDataURL("image/png").split(",")[1];
  } catch (error) {
    console.error("Error generating PDF preview:", error);
    return void 0;
  }
}
async function processDocx(arrayBuffer, fileName) {
  try {
    const wordDoc = await parseAsync(arrayBuffer);
    let extractedText = `<docx filename="${fileName}">
<page number="1">
`;
    const body = wordDoc.documentPart?.body;
    if (body?.children) {
      const texts = [];
      for (const element of body.children) {
        const text3 = extractTextFromElement(element);
        if (text3) {
          texts.push(text3);
        }
      }
      extractedText += texts.join("\n");
    }
    extractedText += `
</page>
</docx>`;
    return { extractedText };
  } catch (error) {
    console.error("Error processing DOCX:", error);
    throw new Error(`Failed to process DOCX: ${String(error)}`);
  }
}
function extractTextFromElement(element) {
  let text3 = "";
  const elementType = element.type?.toLowerCase() || "";
  if (elementType === "paragraph" && element.children) {
    for (const child of element.children) {
      const childType = child.type?.toLowerCase() || "";
      if (childType === "run" && child.children) {
        for (const textChild of child.children) {
          const textType = textChild.type?.toLowerCase() || "";
          if (textType === "text") {
            text3 += textChild.text || "";
          }
        }
      } else if (childType === "text") {
        text3 += child.text || "";
      }
    }
  } else if (elementType === "table") {
    if (element.children) {
      const tableTexts = [];
      for (const row of element.children) {
        const rowType = row.type?.toLowerCase() || "";
        if (rowType === "tablerow" && row.children) {
          const rowTexts = [];
          for (const cell of row.children) {
            const cellType = cell.type?.toLowerCase() || "";
            if (cellType === "tablecell" && cell.children) {
              const cellTexts = [];
              for (const cellElement of cell.children) {
                const cellText = extractTextFromElement(cellElement);
                if (cellText)
                  cellTexts.push(cellText);
              }
              if (cellTexts.length > 0)
                rowTexts.push(cellTexts.join(" "));
            }
          }
          if (rowTexts.length > 0)
            tableTexts.push(rowTexts.join(" | "));
        }
      }
      if (tableTexts.length > 0) {
        text3 = `
[Table]
${tableTexts.join("\n")}
[/Table]
`;
      }
    }
  } else if (element.children && Array.isArray(element.children)) {
    const childTexts = [];
    for (const child of element.children) {
      const childText = extractTextFromElement(child);
      if (childText)
        childTexts.push(childText);
    }
    text3 = childTexts.join(" ");
  }
  return text3.trim();
}
async function processPptx(arrayBuffer, fileName) {
  try {
    const zip = await import_jszip2.default.loadAsync(arrayBuffer);
    let extractedText = `<pptx filename="${fileName}">`;
    const slideFiles = Object.keys(zip.files).filter((name) => name.match(/ppt\/slides\/slide\d+\.xml$/)).sort((a3, b4) => {
      const numA = Number.parseInt(a3.match(/slide(\d+)\.xml$/)?.[1] || "0", 10);
      const numB = Number.parseInt(b4.match(/slide(\d+)\.xml$/)?.[1] || "0", 10);
      return numA - numB;
    });
    for (let i7 = 0; i7 < slideFiles.length; i7++) {
      const slideFile = zip.file(slideFiles[i7]);
      if (slideFile) {
        const slideXml = await slideFile.async("text");
        const textMatches = slideXml.match(/<a:t[^>]*>([^<]+)<\/a:t>/g);
        if (textMatches) {
          extractedText += `
<slide number="${i7 + 1}">`;
          const slideTexts = textMatches.map((match2) => {
            const textMatch = match2.match(/<a:t[^>]*>([^<]+)<\/a:t>/);
            return textMatch ? textMatch[1] : "";
          }).filter((t6) => t6.trim());
          if (slideTexts.length > 0) {
            extractedText += `
${slideTexts.join("\n")}`;
          }
          extractedText += "\n</slide>";
        }
      }
    }
    const notesFiles = Object.keys(zip.files).filter((name) => name.match(/ppt\/notesSlides\/notesSlide\d+\.xml$/)).sort((a3, b4) => {
      const numA = Number.parseInt(a3.match(/notesSlide(\d+)\.xml$/)?.[1] || "0", 10);
      const numB = Number.parseInt(b4.match(/notesSlide(\d+)\.xml$/)?.[1] || "0", 10);
      return numA - numB;
    });
    if (notesFiles.length > 0) {
      extractedText += "\n<notes>";
      for (const noteFile of notesFiles) {
        const file = zip.file(noteFile);
        if (file) {
          const noteXml = await file.async("text");
          const textMatches = noteXml.match(/<a:t[^>]*>([^<]+)<\/a:t>/g);
          if (textMatches) {
            const noteTexts = textMatches.map((match2) => {
              const textMatch = match2.match(/<a:t[^>]*>([^<]+)<\/a:t>/);
              return textMatch ? textMatch[1] : "";
            }).filter((t6) => t6.trim());
            if (noteTexts.length > 0) {
              const slideNum = noteFile.match(/notesSlide(\d+)\.xml$/)?.[1];
              extractedText += `
[Slide ${slideNum} notes]: ${noteTexts.join(" ")}`;
            }
          }
        }
      }
      extractedText += "\n</notes>";
    }
    extractedText += "\n</pptx>";
    return { extractedText };
  } catch (error) {
    console.error("Error processing PPTX:", error);
    throw new Error(`Failed to process PPTX: ${String(error)}`);
  }
}
async function processExcel(arrayBuffer, fileName) {
  try {
    const workbook = readSync(arrayBuffer, { type: "array" });
    let extractedText = `<excel filename="${fileName}">`;
    for (const [index, sheetName] of workbook.SheetNames.entries()) {
      const worksheet = workbook.Sheets[sheetName];
      const csvText = utils.sheet_to_csv(worksheet);
      extractedText += `
<sheet name="${sheetName}" index="${index + 1}">
${csvText}
</sheet>`;
    }
    extractedText += "\n</excel>";
    return { extractedText };
  } catch (error) {
    console.error("Error processing Excel:", error);
    throw new Error(`Failed to process Excel: ${String(error)}`);
  }
}

// ../pi-mono/packages/web-ui/dist/components/AttachmentTile.js
init_process_shim();

// node_modules/lit/html.js
init_process_shim();

// ../pi-mono/packages/web-ui/dist/dialogs/AttachmentOverlay.js
init_process_shim();

// ../mini-lit/dist/ModeToggle.js
init_process_shim();
var __decorate2 = function(decorators, target, key, desc) {
  var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc);
  else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8;
  return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8;
};
var ModeToggle = class ModeToggle2 extends i4 {
  constructor() {
    super(...arguments);
    this.modes = [i18n("Mode 1"), i18n("Mode 2")];
    this.selectedIndex = 0;
  }
  createRenderRoot() {
    return this;
  }
  setMode(index) {
    if (this.selectedIndex !== index && index >= 0 && index < this.modes.length) {
      this.selectedIndex = index;
      this.dispatchEvent(new CustomEvent("mode-change", {
        detail: { index, mode: this.modes[index] },
        bubbles: true
      }));
    }
  }
  render() {
    if (this.modes.length < 2)
      return b2``;
    return b2`
         <div class="inline-flex items-center h-7 rounded-md overflow-hidden border border-border bg-muted/60">
            ${this.modes.map((mode, index) => b2`
                  <button
                     class="px-3 h-full flex items-center text-sm font-medium transition-colors
								${index === this.selectedIndex ? "bg-card text-foreground shadow-sm" : "text-muted-foreground hover:text-accent-foreground"}"
                     @click=${() => this.setMode(index)}
                     title="${mode}"
                  >
                     ${mode}
                  </button>
               `)}
         </div>
      `;
  }
};
__decorate2([
  n6({ type: Array })
], ModeToggle.prototype, "modes", void 0);
__decorate2([
  n6({ type: Number })
], ModeToggle.prototype, "selectedIndex", void 0);
ModeToggle = __decorate2([
  t5("mode-toggle")
], ModeToggle);

// ../pi-mono/packages/web-ui/dist/dialogs/AttachmentOverlay.js
var __decorate3 = function(decorators, target, key, desc) {
  var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc);
  else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8;
  return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8;
};
var AttachmentOverlay = class _AttachmentOverlay extends i4 {
  constructor() {
    super(...arguments);
    this.showExtractedText = false;
    this.error = null;
    this.currentLoadingTask = null;
    this.handleBackdropClick = () => {
      this.close();
    };
    this.handleDownload = () => {
      if (!this.attachment)
        return;
      const byteCharacters = atob(this.attachment.content);
      const byteNumbers = new Array(byteCharacters.length);
      for (let i7 = 0; i7 < byteCharacters.length; i7++) {
        byteNumbers[i7] = byteCharacters.charCodeAt(i7);
      }
      const byteArray = new Uint8Array(byteNumbers);
      const blob = new Blob([byteArray], { type: this.attachment.mimeType });
      const url = URL.createObjectURL(blob);
      const a3 = document.createElement("a");
      a3.href = url;
      a3.download = this.attachment.fileName;
      document.body.appendChild(a3);
      a3.click();
      document.body.removeChild(a3);
      URL.revokeObjectURL(url);
    };
  }
  createRenderRoot() {
    return this;
  }
  static open(attachment, onClose) {
    const overlay = new _AttachmentOverlay();
    overlay.attachment = attachment;
    overlay.onCloseCallback = onClose;
    document.body.appendChild(overlay);
    overlay.setupEventListeners();
  }
  setupEventListeners() {
    this.boundHandleKeyDown = (e9) => {
      if (e9.key === "Escape") {
        this.close();
      }
    };
    window.addEventListener("keydown", this.boundHandleKeyDown);
  }
  close() {
    this.cleanup();
    if (this.boundHandleKeyDown) {
      window.removeEventListener("keydown", this.boundHandleKeyDown);
    }
    this.onCloseCallback?.();
    this.remove();
  }
  getFileType() {
    if (!this.attachment)
      return "text";
    if (this.attachment.type === "image")
      return "image";
    if (this.attachment.mimeType === "application/pdf")
      return "pdf";
    if (this.attachment.mimeType?.includes("wordprocessingml"))
      return "docx";
    if (this.attachment.mimeType?.includes("presentationml") || this.attachment.fileName.toLowerCase().endsWith(".pptx"))
      return "pptx";
    if (this.attachment.mimeType?.includes("spreadsheetml") || this.attachment.mimeType?.includes("ms-excel") || this.attachment.fileName.toLowerCase().endsWith(".xlsx") || this.attachment.fileName.toLowerCase().endsWith(".xls"))
      return "excel";
    return "text";
  }
  getFileTypeLabel() {
    const type = this.getFileType();
    switch (type) {
      case "pdf":
        return i18n("PDF");
      case "docx":
        return i18n("Document");
      case "pptx":
        return i18n("Presentation");
      case "excel":
        return i18n("Spreadsheet");
      default:
        return "";
    }
  }
  cleanup() {
    this.showExtractedText = false;
    this.error = null;
    if (this.currentLoadingTask) {
      this.currentLoadingTask.destroy();
      this.currentLoadingTask = null;
    }
  }
  render() {
    if (!this.attachment)
      return b2``;
    return b2`
			<!-- Full screen overlay -->
			<div class="fixed inset-0 bg-black/90 z-50 flex flex-col" @click=${this.handleBackdropClick}>
				<!-- Compact header bar -->
				<div class="bg-background/95 backdrop-blur border-b border-border" @click=${(e9) => e9.stopPropagation()}>
					<div class="px-4 py-2 flex items-center justify-between">
						<div class="flex items-center gap-3 min-w-0">
							<span class="text-sm font-medium text-foreground truncate">${this.attachment.fileName}</span>
						</div>
						<div class="flex items-center gap-2">
							${this.renderToggle()}
							${Button({
      variant: "ghost",
      size: "icon",
      onClick: this.handleDownload,
      children: icon(Download2, "sm"),
      className: "h-8 w-8"
    })}
							${Button({
      variant: "ghost",
      size: "icon",
      onClick: () => this.close(),
      children: icon(X, "sm"),
      className: "h-8 w-8"
    })}
						</div>
					</div>
				</div>

				<!-- Content container -->
				<div class="flex-1 flex items-center justify-center overflow-auto" @click=${(e9) => e9.stopPropagation()}>
					${this.renderContent()}
				</div>
			</div>
		`;
  }
  renderToggle() {
    if (!this.attachment)
      return b2``;
    const fileType = this.getFileType();
    const hasExtractedText = !!this.attachment.extractedText;
    const showToggle = fileType !== "image" && fileType !== "text" && fileType !== "pptx" && hasExtractedText;
    if (!showToggle)
      return b2``;
    const fileTypeLabel = this.getFileTypeLabel();
    return b2`
			<mode-toggle
				.modes=${[fileTypeLabel, i18n("Text")]}
				.selectedIndex=${this.showExtractedText ? 1 : 0}
				@mode-change=${(e9) => {
      e9.stopPropagation();
      this.showExtractedText = e9.detail.index === 1;
      this.error = null;
    }}
			></mode-toggle>
		`;
  }
  renderContent() {
    if (!this.attachment)
      return b2``;
    if (this.error) {
      return b2`
				<div class="bg-destructive/10 border border-destructive text-destructive p-4 rounded-lg max-w-2xl">
					<div class="font-medium mb-1">${i18n("Error loading file")}</div>
					<div class="text-sm opacity-90">${this.error}</div>
				</div>
			`;
    }
    return this.renderFileContent();
  }
  renderFileContent() {
    if (!this.attachment)
      return b2``;
    const fileType = this.getFileType();
    if (this.showExtractedText && fileType !== "image") {
      return b2`
				<div class="bg-card border border-border text-foreground p-6 w-full h-full max-w-4xl overflow-auto">
					<pre class="whitespace-pre-wrap font-mono text-xs leading-relaxed">${this.attachment.extractedText || i18n("No text content available")}</pre>
				</div>
			`;
    }
    switch (fileType) {
      case "image": {
        const imageUrl = `data:${this.attachment.mimeType};base64,${this.attachment.content}`;
        return b2`
					<img src="${imageUrl}" class="max-w-full max-h-full object-contain rounded-lg shadow-lg" alt="${this.attachment.fileName}" />
				`;
      }
      case "pdf":
        return b2`
					<div
						id="pdf-container"
						class="bg-card text-foreground overflow-auto shadow-lg border border-border w-full h-full max-w-[1000px]"
					></div>
				`;
      case "docx":
        return b2`
					<div
						id="docx-container"
						class="bg-card text-foreground overflow-auto shadow-lg border border-border w-full h-full max-w-[1000px]"
					></div>
				`;
      case "excel":
        return b2` <div id="excel-container" class="bg-card text-foreground overflow-auto w-full h-full"></div> `;
      case "pptx":
        return b2`
					<div
						id="pptx-container"
						class="bg-card text-foreground overflow-auto shadow-lg border border-border w-full h-full max-w-[1000px]"
					></div>
				`;
      default:
        return b2`
					<div class="bg-card border border-border text-foreground p-6 w-full h-full max-w-4xl overflow-auto">
						<pre class="whitespace-pre-wrap font-mono text-sm">${this.attachment.extractedText || i18n("No content available")}</pre>
					</div>
				`;
    }
  }
  async updated(changedProperties) {
    super.updated(changedProperties);
    if ((changedProperties.has("attachment") || changedProperties.has("showExtractedText")) && this.attachment && !this.showExtractedText && !this.error) {
      const fileType = this.getFileType();
      switch (fileType) {
        case "pdf":
          await this.renderPdf();
          break;
        case "docx":
          await this.renderDocx();
          break;
        case "excel":
          await this.renderExcel();
          break;
        case "pptx":
          await this.renderExtractedText();
          break;
      }
    }
  }
  async renderPdf() {
    const container = this.querySelector("#pdf-container");
    if (!container || !this.attachment)
      return;
    let pdf = null;
    try {
      const arrayBuffer = this.base64ToArrayBuffer(this.attachment.content);
      if (this.currentLoadingTask) {
        this.currentLoadingTask.destroy();
      }
      this.currentLoadingTask = getDocument({ data: arrayBuffer });
      pdf = await this.currentLoadingTask.promise;
      this.currentLoadingTask = null;
      container.innerHTML = "";
      const wrapper = document.createElement("div");
      wrapper.className = "";
      container.appendChild(wrapper);
      for (let pageNum = 1; pageNum <= pdf.numPages; pageNum++) {
        const page = await pdf.getPage(pageNum);
        const pageContainer = document.createElement("div");
        pageContainer.className = "mb-4 last:mb-0";
        const canvas = document.createElement("canvas");
        const context = canvas.getContext("2d");
        const viewport = page.getViewport({ scale: 1.5 });
        canvas.height = viewport.height;
        canvas.width = viewport.width;
        canvas.className = "w-full max-w-full h-auto block mx-auto bg-white rounded shadow-sm border border-border";
        if (context) {
          context.fillStyle = "white";
          context.fillRect(0, 0, canvas.width, canvas.height);
        }
        await page.render({
          canvasContext: context,
          viewport,
          canvas
        }).promise;
        pageContainer.appendChild(canvas);
        if (pageNum < pdf.numPages) {
          const separator = document.createElement("div");
          separator.className = "h-px bg-border my-4";
          pageContainer.appendChild(separator);
        }
        wrapper.appendChild(pageContainer);
      }
    } catch (error) {
      console.error("Error rendering PDF:", error);
      this.error = error?.message || i18n("Failed to load PDF");
    } finally {
      if (pdf) {
        pdf.destroy();
      }
    }
  }
  async renderDocx() {
    const container = this.querySelector("#docx-container");
    if (!container || !this.attachment)
      return;
    try {
      const arrayBuffer = this.base64ToArrayBuffer(this.attachment.content);
      container.innerHTML = "";
      const wrapper = document.createElement("div");
      wrapper.className = "docx-wrapper-custom";
      container.appendChild(wrapper);
      await renderAsync(arrayBuffer, wrapper, void 0, {
        className: "docx",
        inWrapper: true,
        ignoreWidth: true,
        // Let it be responsive
        ignoreHeight: false,
        ignoreFonts: false,
        breakPages: true,
        ignoreLastRenderedPageBreak: true,
        experimental: false,
        trimXmlDeclaration: true,
        useBase64URL: false,
        renderHeaders: true,
        renderFooters: true,
        renderFootnotes: true,
        renderEndnotes: true
      });
      const style = document.createElement("style");
      style.textContent = `
				#docx-container {
					padding: 0;
				}

				#docx-container .docx-wrapper-custom {
					max-width: 100%;
					overflow-x: auto;
				}

				#docx-container .docx-wrapper {
					max-width: 100% !important;
					margin: 0 !important;
					background: transparent !important;
					padding: 0em !important;
				}

				#docx-container .docx-wrapper > section.docx {
					box-shadow: none !important;
					border: none !important;
					border-radius: 0 !important;
					margin: 0 !important;
					padding: 2em !important;
					background: white !important;
					color: black !important;
					max-width: 100% !important;
					width: 100% !important;
					min-width: 0 !important;
					overflow-x: auto !important;
				}

				/* Fix tables and wide content */
				#docx-container table {
					max-width: 100% !important;
					width: auto !important;
					overflow-x: auto !important;
					display: block !important;
				}

				#docx-container img {
					max-width: 100% !important;
					height: auto !important;
				}

				/* Fix paragraphs and text */
				#docx-container p,
				#docx-container span,
				#docx-container div {
					max-width: 100% !important;
					word-wrap: break-word !important;
					overflow-wrap: break-word !important;
				}

				/* Hide page breaks in web view */
				#docx-container .docx-page-break {
					display: none !important;
				}
			`;
      container.appendChild(style);
    } catch (error) {
      console.error("Error rendering DOCX:", error);
      this.error = error?.message || i18n("Failed to load document");
    }
  }
  async renderExcel() {
    const container = this.querySelector("#excel-container");
    if (!container || !this.attachment)
      return;
    try {
      const arrayBuffer = this.base64ToArrayBuffer(this.attachment.content);
      const workbook = readSync(arrayBuffer, { type: "array" });
      container.innerHTML = "";
      const wrapper = document.createElement("div");
      wrapper.className = "overflow-auto h-full flex flex-col";
      container.appendChild(wrapper);
      if (workbook.SheetNames.length > 1) {
        const tabContainer = document.createElement("div");
        tabContainer.className = "flex gap-2 mb-4 border-b border-border sticky top-0 bg-card z-10";
        const sheetContents = [];
        workbook.SheetNames.forEach((sheetName, index) => {
          const tab = document.createElement("button");
          tab.textContent = sheetName;
          tab.className = index === 0 ? "px-4 py-2 text-sm font-medium border-b-2 border-primary text-primary" : "px-4 py-2 text-sm font-medium text-muted-foreground hover:text-foreground hover:border-b-2 hover:border-border transition-colors";
          const sheetDiv = document.createElement("div");
          sheetDiv.style.display = index === 0 ? "flex" : "none";
          sheetDiv.className = "flex-1 overflow-auto";
          sheetDiv.appendChild(this.renderExcelSheet(workbook.Sheets[sheetName], sheetName));
          sheetContents.push(sheetDiv);
          tab.onclick = () => {
            tabContainer.querySelectorAll("button").forEach((btn, btnIndex) => {
              if (btnIndex === index) {
                btn.className = "px-4 py-2 text-sm font-medium border-b-2 border-primary text-primary";
              } else {
                btn.className = "px-4 py-2 text-sm font-medium text-muted-foreground hover:text-foreground hover:border-b-2 hover:border-border transition-colors";
              }
            });
            sheetContents.forEach((content, contentIndex) => {
              content.style.display = contentIndex === index ? "flex" : "none";
            });
          };
          tabContainer.appendChild(tab);
        });
        wrapper.appendChild(tabContainer);
        sheetContents.forEach((content) => {
          wrapper.appendChild(content);
        });
      } else {
        const sheetName = workbook.SheetNames[0];
        wrapper.appendChild(this.renderExcelSheet(workbook.Sheets[sheetName], sheetName));
      }
    } catch (error) {
      console.error("Error rendering Excel:", error);
      this.error = error?.message || i18n("Failed to load spreadsheet");
    }
  }
  renderExcelSheet(worksheet, sheetName) {
    const sheetDiv = document.createElement("div");
    const htmlTable = utils.sheet_to_html(worksheet, { id: `sheet-${sheetName}` });
    const tempDiv = document.createElement("div");
    tempDiv.innerHTML = htmlTable;
    const table = tempDiv.querySelector("table");
    if (table) {
      table.className = "w-full border-collapse text-foreground";
      table.querySelectorAll("td, th").forEach((cell) => {
        const cellEl = cell;
        cellEl.className = "border border-border px-3 py-2 text-sm text-left";
      });
      const headerCells = table.querySelectorAll("thead th, tr:first-child td");
      if (headerCells.length > 0) {
        headerCells.forEach((th) => {
          const thEl = th;
          thEl.className = "border border-border px-3 py-2 text-sm font-semibold bg-muted text-foreground sticky top-0";
        });
      }
      table.querySelectorAll("tbody tr:nth-child(even)").forEach((row) => {
        const rowEl = row;
        rowEl.className = "bg-muted/30";
      });
      sheetDiv.appendChild(table);
    }
    return sheetDiv;
  }
  base64ToArrayBuffer(base64) {
    const binaryString = atob(base64);
    const bytes = new Uint8Array(binaryString.length);
    for (let i7 = 0; i7 < binaryString.length; i7++) {
      bytes[i7] = binaryString.charCodeAt(i7);
    }
    return bytes.buffer;
  }
  async renderExtractedText() {
    const container = this.querySelector("#pptx-container");
    if (!container || !this.attachment)
      return;
    try {
      container.innerHTML = "";
      const wrapper = document.createElement("div");
      wrapper.className = "p-6 overflow-auto";
      const pre = document.createElement("pre");
      pre.className = "whitespace-pre-wrap text-sm text-foreground font-mono";
      pre.textContent = this.attachment.extractedText || i18n("No text content available");
      wrapper.appendChild(pre);
      container.appendChild(wrapper);
    } catch (error) {
      console.error("Error rendering extracted text:", error);
      this.error = error?.message || i18n("Failed to display text content");
    }
  }
};
__decorate3([
  r7()
], AttachmentOverlay.prototype, "attachment", void 0);
__decorate3([
  r7()
], AttachmentOverlay.prototype, "showExtractedText", void 0);
__decorate3([
  r7()
], AttachmentOverlay.prototype, "error", void 0);
if (!customElements.get("attachment-overlay")) {
  customElements.define("attachment-overlay", AttachmentOverlay);
}

// ../pi-mono/packages/web-ui/dist/components/AttachmentTile.js
var __decorate4 = function(decorators, target, key, desc) {
  var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc);
  else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8;
  return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8;
};
var AttachmentTile = class AttachmentTile2 extends i4 {
  constructor() {
    super(...arguments);
    this.showDelete = false;
    this.handleClick = () => {
      AttachmentOverlay.open(this.attachment);
    };
  }
  createRenderRoot() {
    return this;
  }
  connectedCallback() {
    super.connectedCallback();
    this.style.display = "block";
    this.classList.add("max-h-16");
  }
  render() {
    const hasPreview = !!this.attachment.preview;
    const isImage = this.attachment.type === "image";
    const isPdf = this.attachment.mimeType === "application/pdf";
    const isExcel = this.attachment.mimeType?.includes("spreadsheetml") || this.attachment.fileName.toLowerCase().endsWith(".xlsx") || this.attachment.fileName.toLowerCase().endsWith(".xls");
    const getDocumentIcon = () => {
      if (isExcel)
        return icon(FileSpreadsheet, "md");
      return icon(FileText, "md");
    };
    return b2`
			<div class="relative group inline-block">
				${hasPreview ? b2`
							<div class="relative">
								<img
									src="data:${isImage ? this.attachment.mimeType : "image/png"};base64,${this.attachment.preview}"
									class="w-16 h-16 object-cover rounded-lg border border-input cursor-pointer hover:opacity-80 transition-opacity"
									alt="${this.attachment.fileName}"
									title="${this.attachment.fileName}"
									@click=${this.handleClick}
								/>
								${isPdf ? b2`
											<!-- PDF badge overlay -->
											<div class="absolute bottom-0 left-0 right-0 bg-background/90 px-1 py-0.5 rounded-b-lg">
												<div class="text-[10px] text-muted-foreground text-center font-medium">${i18n("PDF")}</div>
											</div>
										` : ""}
							</div>
						` : b2`
							<!-- Fallback: document icon + filename -->
							<div
								class="w-16 h-16 rounded-lg border border-input cursor-pointer hover:opacity-80 transition-opacity bg-muted text-muted-foreground flex flex-col items-center justify-center p-2"
								@click=${this.handleClick}
								title="${this.attachment.fileName}"
							>
								${getDocumentIcon()}
								<div class="text-[10px] text-center truncate w-full">
									${this.attachment.fileName.length > 10 ? `${this.attachment.fileName.substring(0, 8)}...` : this.attachment.fileName}
								</div>
							</div>
						`}
				${this.showDelete ? b2`
							<button
								@click=${(e9) => {
      e9.stopPropagation();
      this.onDelete?.();
    }}
								class="absolute -top-1 -right-1 w-5 h-5 bg-background hover:bg-muted text-muted-foreground hover:text-foreground rounded-full flex items-center justify-center opacity-100 hover:opacity-100 [@media(hover:hover)]:opacity-0 [@media(hover:hover)]:group-hover:opacity-100 transition-opacity border border-input shadow-sm"
								title="${i18n("Remove")}"
							>
								${icon(X, "xs")}
							</button>
						` : ""}
			</div>
		`;
  }
};
__decorate4([
  n6({ type: Object })
], AttachmentTile.prototype, "attachment", void 0);
__decorate4([
  n6({ type: Boolean })
], AttachmentTile.prototype, "showDelete", void 0);
__decorate4([
  n6()
], AttachmentTile.prototype, "onDelete", void 0);
AttachmentTile = __decorate4([
  t5("attachment-tile")
], AttachmentTile);

// ../pi-mono/packages/web-ui/dist/components/MessageEditor.js
var __decorate5 = function(decorators, target, key, desc) {
  var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc);
  else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8;
  return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8;
};
var MessageEditor = class MessageEditor2 extends i4 {
  constructor() {
    super(...arguments);
    this._value = "";
    this.textareaRef = e5();
    this.isStreaming = false;
    this.thinkingLevel = "off";
    this.showAttachmentButton = true;
    this.showModelSelector = true;
    this.showThinkingSelector = true;
    this.attachments = [];
    this.maxFiles = 10;
    this.maxFileSize = 20 * 1024 * 1024;
    this.acceptedTypes = "image/*,application/pdf,.docx,.pptx,.xlsx,.xls,.txt,.md,.json,.xml,.html,.css,.js,.ts,.jsx,.tsx,.yml,.yaml";
    this.processingFiles = false;
    this.isDragging = false;
    this.fileInputRef = e5();
    this.handleTextareaInput = (e9) => {
      const textarea = e9.target;
      this.value = textarea.value;
      this.onInput?.(this.value);
    };
    this.handleKeyDown = (e9) => {
      if (e9.key === "Enter" && !e9.shiftKey) {
        e9.preventDefault();
        if (!this.isStreaming && !this.processingFiles && (this.value.trim() || this.attachments.length > 0)) {
          this.handleSend();
        }
      } else if (e9.key === "Escape" && this.isStreaming) {
        e9.preventDefault();
        this.onAbort?.();
      }
    };
    this.handlePaste = async (e9) => {
      const items = e9.clipboardData?.items;
      if (!items)
        return;
      const imageFiles = [];
      for (let i7 = 0; i7 < items.length; i7++) {
        const item = items[i7];
        if (item.type.startsWith("image/")) {
          const file = item.getAsFile();
          if (file) {
            imageFiles.push(file);
          }
        }
      }
      if (imageFiles.length > 0) {
        e9.preventDefault();
        if (imageFiles.length + this.attachments.length > this.maxFiles) {
          alert(`Maximum ${this.maxFiles} files allowed`);
          return;
        }
        this.processingFiles = true;
        const newAttachments = [];
        for (const file of imageFiles) {
          try {
            if (file.size > this.maxFileSize) {
              alert(`Image exceeds maximum size of ${Math.round(this.maxFileSize / 1024 / 1024)}MB`);
              continue;
            }
            const attachment = await loadAttachment(file);
            newAttachments.push(attachment);
          } catch (error) {
            console.error("Error processing pasted image:", error);
            alert(`Failed to process pasted image: ${String(error)}`);
          }
        }
        this.attachments = [...this.attachments, ...newAttachments];
        this.onFilesChange?.(this.attachments);
        this.processingFiles = false;
      }
    };
    this.handleSend = () => {
      this.onSend?.(this.value, this.attachments);
    };
    this.handleAttachmentClick = () => {
      this.fileInputRef.value?.click();
    };
    this.handleDragOver = (e9) => {
      e9.preventDefault();
      e9.stopPropagation();
      if (!this.isDragging) {
        this.isDragging = true;
      }
    };
    this.handleDragLeave = (e9) => {
      e9.preventDefault();
      e9.stopPropagation();
      const rect = e9.currentTarget.getBoundingClientRect();
      const x2 = e9.clientX;
      const y4 = e9.clientY;
      if (x2 <= rect.left || x2 >= rect.right || y4 <= rect.top || y4 >= rect.bottom) {
        this.isDragging = false;
      }
    };
    this.handleDrop = async (e9) => {
      e9.preventDefault();
      e9.stopPropagation();
      this.isDragging = false;
      const files = Array.from(e9.dataTransfer?.files || []);
      if (files.length === 0)
        return;
      if (files.length + this.attachments.length > this.maxFiles) {
        alert(`Maximum ${this.maxFiles} files allowed`);
        return;
      }
      this.processingFiles = true;
      const newAttachments = [];
      for (const file of files) {
        try {
          if (file.size > this.maxFileSize) {
            alert(`${file.name} exceeds maximum size of ${Math.round(this.maxFileSize / 1024 / 1024)}MB`);
            continue;
          }
          const attachment = await loadAttachment(file);
          newAttachments.push(attachment);
        } catch (error) {
          console.error(`Error processing ${file.name}:`, error);
          alert(`Failed to process ${file.name}: ${String(error)}`);
        }
      }
      this.attachments = [...this.attachments, ...newAttachments];
      this.onFilesChange?.(this.attachments);
      this.processingFiles = false;
    };
  }
  get value() {
    return this._value;
  }
  set value(val2) {
    const oldValue = this._value;
    this._value = val2;
    this.requestUpdate("value", oldValue);
  }
  createRenderRoot() {
    return this;
  }
  async handleFilesSelected(e9) {
    const input = e9.target;
    const files = Array.from(input.files || []);
    if (files.length === 0)
      return;
    if (files.length + this.attachments.length > this.maxFiles) {
      alert(`Maximum ${this.maxFiles} files allowed`);
      input.value = "";
      return;
    }
    this.processingFiles = true;
    const newAttachments = [];
    for (const file of files) {
      try {
        if (file.size > this.maxFileSize) {
          alert(`${file.name} exceeds maximum size of ${Math.round(this.maxFileSize / 1024 / 1024)}MB`);
          continue;
        }
        const attachment = await loadAttachment(file);
        newAttachments.push(attachment);
      } catch (error) {
        console.error(`Error processing ${file.name}:`, error);
        alert(`Failed to process ${file.name}: ${String(error)}`);
      }
    }
    this.attachments = [...this.attachments, ...newAttachments];
    this.onFilesChange?.(this.attachments);
    this.processingFiles = false;
    input.value = "";
  }
  removeFile(fileId) {
    this.attachments = this.attachments.filter((f4) => f4.id !== fileId);
    this.onFilesChange?.(this.attachments);
  }
  firstUpdated() {
    const textarea = this.textareaRef.value;
    if (textarea) {
      textarea.focus();
    }
  }
  render() {
    const model = this.currentModel;
    const supportsThinking = model?.reasoning === true;
    return b2`
			<div
				class="bg-card rounded-xl border shadow-sm relative ${this.isDragging ? "border-primary border-2 bg-primary/5" : "border-border"}"
				@dragover=${this.handleDragOver}
				@dragleave=${this.handleDragLeave}
				@drop=${this.handleDrop}
			>
				<!-- Drag overlay -->
				${this.isDragging ? b2`
					<div class="absolute inset-0 bg-primary/10 rounded-xl pointer-events-none z-10 flex items-center justify-center">
						<div class="text-primary font-medium">${i18n("Drop files here")}</div>
					</div>
				` : ""}

				<!-- Attachments -->
				${this.attachments.length > 0 ? b2`
							<div class="px-4 pt-3 pb-2 flex flex-wrap gap-2">
								${this.attachments.map((attachment) => b2`
										<attachment-tile
											.attachment=${attachment}
											.showDelete=${true}
											.onDelete=${() => this.removeFile(attachment.id)}
										></attachment-tile>
									`)}
							</div>
						` : ""}

				<textarea
					class="w-full bg-transparent p-4 text-foreground placeholder-muted-foreground outline-none resize-none overflow-y-auto"
					placeholder=${i18n("Type a message...")}
					rows="1"
					style="max-height: 200px; field-sizing: content; min-height: 1lh; height: auto;"
					.value=${this.value}
					@input=${this.handleTextareaInput}
					@keydown=${this.handleKeyDown}
					@paste=${this.handlePaste}
					${n5(this.textareaRef)}
				></textarea>

				<!-- Hidden file input -->
				<input
					type="file"
					${n5(this.fileInputRef)}
					@change=${this.handleFilesSelected}
					accept=${this.acceptedTypes}
					multiple
					style="display: none;"
				/>

				<!-- Button Row -->
				<div class="px-2 pb-2 flex items-center justify-between">
					<!-- Left side - attachment and thinking selector -->
					<div class="flex gap-2 items-center">
						${this.showAttachmentButton ? this.processingFiles ? b2`
										<div class="h-8 w-8 flex items-center justify-center">
											${icon(LoaderCircle, "sm", "animate-spin text-muted-foreground")}
										</div>
									` : b2`
										${Button({
      variant: "ghost",
      size: "icon",
      className: "h-8 w-8",
      onClick: this.handleAttachmentClick,
      children: icon(Paperclip, "sm")
    })}
									` : ""}
						${supportsThinking && this.showThinkingSelector ? b2`
									${Select({
      value: this.thinkingLevel,
      placeholder: i18n("Off"),
      options: [
        { value: "off", label: i18n("Off"), icon: icon(Brain, "sm") },
        { value: "minimal", label: i18n("Minimal"), icon: icon(Brain, "sm") },
        { value: "low", label: i18n("Low"), icon: icon(Brain, "sm") },
        { value: "medium", label: i18n("Medium"), icon: icon(Brain, "sm") },
        { value: "high", label: i18n("High"), icon: icon(Brain, "sm") }
      ],
      onChange: (value) => {
        this.onThinkingChange?.(value);
      },
      width: "80px",
      size: "sm",
      variant: "ghost",
      fitContent: true
    })}
								` : ""}
					</div>

					<!-- Model selector and send on the right -->
					<div class="flex gap-2 items-center">
						${this.showModelSelector && this.currentModel ? b2`
									${Button({
      variant: "ghost",
      size: "sm",
      onClick: () => {
        this.textareaRef.value?.focus();
        requestAnimationFrame(() => {
          this.onModelSelect?.();
        });
      },
      children: b2`
											${icon(Sparkles, "sm")}
											<span class="ml-1">${this.currentModel.id}</span>
										`,
      className: "h-8 text-xs truncate"
    })}
								` : ""}
						${this.isStreaming ? b2`
									${Button({
      variant: "ghost",
      size: "icon",
      onClick: this.onAbort,
      children: icon(Square, "sm"),
      className: "h-8 w-8"
    })}
								` : b2`
									${Button({
      variant: "ghost",
      size: "icon",
      onClick: this.handleSend,
      disabled: !this.value.trim() && this.attachments.length === 0 || this.processingFiles,
      children: b2`<div style="transform: rotate(-45deg)">${icon(Send, "sm")}</div>`,
      className: "h-8 w-8"
    })}
								`}
					</div>
				</div>
			</div>
		`;
  }
};
__decorate5([
  n6()
], MessageEditor.prototype, "value", null);
__decorate5([
  n6()
], MessageEditor.prototype, "isStreaming", void 0);
__decorate5([
  n6()
], MessageEditor.prototype, "currentModel", void 0);
__decorate5([
  n6()
], MessageEditor.prototype, "thinkingLevel", void 0);
__decorate5([
  n6()
], MessageEditor.prototype, "showAttachmentButton", void 0);
__decorate5([
  n6()
], MessageEditor.prototype, "showModelSelector", void 0);
__decorate5([
  n6()
], MessageEditor.prototype, "showThinkingSelector", void 0);
__decorate5([
  n6()
], MessageEditor.prototype, "onInput", void 0);
__decorate5([
  n6()
], MessageEditor.prototype, "onSend", void 0);
__decorate5([
  n6()
], MessageEditor.prototype, "onAbort", void 0);
__decorate5([
  n6()
], MessageEditor.prototype, "onModelSelect", void 0);
__decorate5([
  n6()
], MessageEditor.prototype, "onThinkingChange", void 0);
__decorate5([
  n6()
], MessageEditor.prototype, "onFilesChange", void 0);
__decorate5([
  n6()
], MessageEditor.prototype, "attachments", void 0);
__decorate5([
  n6()
], MessageEditor.prototype, "maxFiles", void 0);
__decorate5([
  n6()
], MessageEditor.prototype, "maxFileSize", void 0);
__decorate5([
  n6()
], MessageEditor.prototype, "acceptedTypes", void 0);
__decorate5([
  r7()
], MessageEditor.prototype, "processingFiles", void 0);
__decorate5([
  r7()
], MessageEditor.prototype, "isDragging", void 0);
MessageEditor = __decorate5([
  t5("message-editor")
], MessageEditor);

// ../pi-mono/packages/web-ui/dist/components/MessageList.js
init_process_shim();

// node_modules/lit/directives/repeat.js
init_process_shim();

// node_modules/lit-html/directives/repeat.js
init_process_shim();
var u4 = (e9, s6, t6) => {
  const r8 = /* @__PURE__ */ new Map();
  for (let l5 = s6; l5 <= t6; l5++) r8.set(e9[l5], l5);
  return r8;
};
var c5 = e4(class extends i6 {
  constructor(e9) {
    if (super(e9), e9.type !== t4.CHILD) throw Error("repeat() can only be used in text expressions");
  }
  dt(e9, s6, t6) {
    let r8;
    void 0 === t6 ? t6 = s6 : void 0 !== s6 && (r8 = s6);
    const l5 = [], o9 = [];
    let i7 = 0;
    for (const s7 of e9) l5[i7] = r8 ? r8(s7, i7) : i7, o9[i7] = t6(s7, i7), i7++;
    return { values: o9, keys: l5 };
  }
  render(e9, s6, t6) {
    return this.dt(e9, s6, t6).values;
  }
  update(s6, [t6, r8, c6]) {
    const d4 = M2(s6), { values: p4, keys: a3 } = this.dt(t6, r8, c6);
    if (!Array.isArray(d4)) return this.ut = a3, p4;
    const h7 = this.ut ??= [], v4 = [];
    let m4, y4, x2 = 0, j3 = d4.length - 1, k2 = 0, w3 = p4.length - 1;
    for (; x2 <= j3 && k2 <= w3; ) if (null === d4[x2]) x2++;
    else if (null === d4[j3]) j3--;
    else if (h7[x2] === a3[k2]) v4[k2] = u3(d4[x2], p4[k2]), x2++, k2++;
    else if (h7[j3] === a3[w3]) v4[w3] = u3(d4[j3], p4[w3]), j3--, w3--;
    else if (h7[x2] === a3[w3]) v4[w3] = u3(d4[x2], p4[w3]), v2(s6, v4[w3 + 1], d4[x2]), x2++, w3--;
    else if (h7[j3] === a3[k2]) v4[k2] = u3(d4[j3], p4[k2]), v2(s6, d4[x2], d4[j3]), j3--, k2++;
    else if (void 0 === m4 && (m4 = u4(a3, k2, w3), y4 = u4(h7, x2, j3)), m4.has(h7[x2])) if (m4.has(h7[j3])) {
      const e9 = y4.get(a3[k2]), t7 = void 0 !== e9 ? d4[e9] : null;
      if (null === t7) {
        const e10 = v2(s6, d4[x2]);
        u3(e10, p4[k2]), v4[k2] = e10;
      } else v4[k2] = u3(t7, p4[k2]), v2(s6, d4[x2], t7), d4[e9] = null;
      k2++;
    } else h3(d4[j3]), j3--;
    else h3(d4[x2]), x2++;
    for (; k2 <= w3; ) {
      const e9 = v2(s6, v4[w3 + 1]);
      u3(e9, p4[k2]), v4[k2++] = e9;
    }
    for (; x2 <= j3; ) {
      const e9 = d4[x2++];
      null !== e9 && h3(e9);
    }
    return this.ut = a3, p3(s6, v4), E;
  }
});

// ../pi-mono/packages/web-ui/dist/components/message-renderer-registry.js
init_process_shim();
var messageRenderers = /* @__PURE__ */ new Map();
function renderMessage(message) {
  return messageRenderers.get(message.role)?.render(message);
}

// ../pi-mono/packages/web-ui/dist/components/MessageList.js
var __decorate6 = function(decorators, target, key, desc) {
  var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc);
  else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8;
  return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8;
};
var MessageList = class extends i4 {
  constructor() {
    super(...arguments);
    this.messages = [];
    this.tools = [];
    this.isStreaming = false;
  }
  createRenderRoot() {
    return this;
  }
  connectedCallback() {
    super.connectedCallback();
    this.style.display = "block";
  }
  buildRenderItems() {
    const resultByCallId = /* @__PURE__ */ new Map();
    for (const message of this.messages) {
      if (message.role === "toolResult") {
        resultByCallId.set(message.toolCallId, message);
      }
    }
    const items = [];
    let index = 0;
    for (const msg of this.messages) {
      if (msg.role === "artifact") {
        continue;
      }
      const customTemplate = renderMessage(msg);
      if (customTemplate) {
        items.push({ key: `msg:${index}`, template: customTemplate });
        index++;
        continue;
      }
      if (msg.role === "user" || msg.role === "user-with-attachments") {
        items.push({
          key: `msg:${index}`,
          template: b2`<user-message .message=${msg}></user-message>`
        });
        index++;
      } else if (msg.role === "assistant") {
        const amsg = msg;
        items.push({
          key: `msg:${index}`,
          template: b2`<assistant-message
						.message=${amsg}
						.tools=${this.tools}
						.isStreaming=${false}
						.pendingToolCalls=${this.pendingToolCalls}
						.toolResultsById=${resultByCallId}
						.hideToolCalls=${false}
						.hidePendingToolCalls=${this.isStreaming}
						.onCostClick=${this.onCostClick}
					></assistant-message>`
        });
        index++;
      } else {
      }
    }
    return items;
  }
  render() {
    const items = this.buildRenderItems();
    return b2`<div class="flex flex-col gap-3">
			${c5(items, (it) => it.key, (it) => it.template)}
		</div>`;
  }
};
__decorate6([
  n6({ type: Array })
], MessageList.prototype, "messages", void 0);
__decorate6([
  n6({ type: Array })
], MessageList.prototype, "tools", void 0);
__decorate6([
  n6({ type: Object })
], MessageList.prototype, "pendingToolCalls", void 0);
__decorate6([
  n6({ type: Boolean })
], MessageList.prototype, "isStreaming", void 0);
__decorate6([
  n6({ attribute: false })
], MessageList.prototype, "onCostClick", void 0);
if (!customElements.get("message-list")) {
  customElements.define("message-list", MessageList);
}

// ../pi-mono/packages/web-ui/dist/components/Messages.js
init_process_shim();

// ../pi-mono/packages/web-ui/dist/tools/index.js
init_process_shim();

// ../pi-mono/packages/web-ui/dist/tools/javascript-repl.js
init_process_shim();

// ../pi-mono/packages/web-ui/dist/components/SandboxedIframe.js
init_process_shim();

// ../pi-mono/packages/web-ui/dist/components/sandbox/ConsoleRuntimeProvider.js
init_process_shim();
var ConsoleRuntimeProvider = class {
  constructor() {
    this.logs = [];
    this.completionError = null;
    this.completed = false;
  }
  getData() {
    return {};
  }
  getDescription() {
    return "";
  }
  getRuntime() {
    return (_sandboxId) => {
      if (!window.__originalConsole) {
        window.__originalConsole = {
          log: console.log.bind(console),
          error: console.error.bind(console),
          warn: console.warn.bind(console),
          info: console.info.bind(console)
        };
      }
      const originalConsole = window.__originalConsole;
      const pendingSends = [];
      ["log", "error", "warn", "info"].forEach((method) => {
        console[method] = (...args) => {
          const text3 = args.map((arg) => {
            try {
              return typeof arg === "object" ? JSON.stringify(arg) : String(arg);
            } catch {
              return String(arg);
            }
          }).join(" ");
          originalConsole[method].apply(console, args);
          if (window.sendRuntimeMessage) {
            const sendPromise = window.sendRuntimeMessage({
              type: "console",
              method,
              text: text3,
              args
            }).catch(() => {
            });
            pendingSends.push(sendPromise);
          }
        };
      });
      if (window.onCompleted) {
        window.onCompleted(async (_success) => {
          if (pendingSends.length > 0) {
            await Promise.all(pendingSends);
          }
        });
      }
      let lastError = null;
      window.addEventListener("error", (e9) => {
        const text3 = `${e9.error?.stack || e9.message || String(e9)} at line ${e9.lineno || "?"}:${e9.colno || "?"}`;
        lastError = {
          message: e9.error?.message || e9.message || String(e9),
          stack: e9.error?.stack || text3
        };
      });
      window.addEventListener("unhandledrejection", (e9) => {
        const text3 = `Unhandled promise rejection: ${e9.reason?.message || e9.reason || "Unknown error"}`;
        lastError = {
          message: e9.reason?.message || String(e9.reason) || "Unhandled promise rejection",
          stack: e9.reason?.stack || text3
        };
      });
      let completionSent = false;
      window.complete = async (error, returnValue) => {
        if (completionSent)
          return;
        completionSent = true;
        const finalError = error || lastError;
        if (window.sendRuntimeMessage) {
          if (finalError) {
            await window.sendRuntimeMessage({
              type: "execution-error",
              error: finalError
            });
          } else {
            await window.sendRuntimeMessage({
              type: "execution-complete",
              returnValue
            });
          }
        }
      };
    };
  }
  async handleMessage(message, respond) {
    if (message.type === "console") {
      this.logs.push({
        type: message.method === "error" ? "error" : message.method === "warn" ? "warn" : message.method === "info" ? "info" : "log",
        text: message.text,
        args: message.args
      });
      respond({ success: true });
    }
  }
  /**
   * Get collected console logs
   */
  getLogs() {
    return this.logs;
  }
  /**
   * Get completion status
   */
  isCompleted() {
    return this.completed;
  }
  /**
   * Get completion error if any
   */
  getCompletionError() {
    return this.completionError;
  }
  /**
   * Reset state for reuse
   */
  reset() {
    this.logs = [];
    this.completionError = null;
    this.completed = false;
  }
};

// ../pi-mono/packages/web-ui/dist/components/sandbox/RuntimeMessageBridge.js
init_process_shim();
var RuntimeMessageBridge = class _RuntimeMessageBridge {
  /**
   * Generate sendRuntimeMessage() function as injectable string.
   * Returns the function source code to be injected into target context.
   */
  static generateBridgeCode(options) {
    if (options.context === "sandbox-iframe") {
      return _RuntimeMessageBridge.generateSandboxBridge(options.sandboxId);
    } else {
      return _RuntimeMessageBridge.generateUserScriptBridge(options.sandboxId);
    }
  }
  static generateSandboxBridge(sandboxId) {
    return `
window.__completionCallbacks = [];
window.sendRuntimeMessage = async (message) => {
    const messageId = 'msg_' + Date.now() + '_' + Math.random().toString(36).substring(2, 9);

    return new Promise((resolve, reject) => {
        const handler = (e) => {
            if (e.data.type === 'runtime-response' && e.data.messageId === messageId) {
                window.removeEventListener('message', handler);
                if (e.data.success) {
                    resolve(e.data);
                } else {
                    reject(new Error(e.data.error || 'Operation failed'));
                }
            }
        };

        window.addEventListener('message', handler);

        window.parent.postMessage({
            ...message,
            sandboxId: ${JSON.stringify(sandboxId)},
            messageId: messageId
        }, '*');

        // Timeout after 30s
        setTimeout(() => {
            window.removeEventListener('message', handler);
            reject(new Error('Runtime message timeout'));
        }, 30000);
    });
};
window.onCompleted = (callback) => {
    window.__completionCallbacks.push(callback);
};
`.trim();
  }
  static generateUserScriptBridge(sandboxId) {
    return `
window.__completionCallbacks = [];
window.sendRuntimeMessage = async (message) => {
    return await chrome.runtime.sendMessage({
        ...message,
        sandboxId: ${JSON.stringify(sandboxId)}
    });
};
window.onCompleted = (callback) => {
    window.__completionCallbacks.push(callback);
};
`.trim();
  }
};

// ../pi-mono/packages/web-ui/dist/components/sandbox/RuntimeMessageRouter.js
init_process_shim();
var RuntimeMessageRouter = class {
  constructor() {
    this.sandboxes = /* @__PURE__ */ new Map();
    this.messageListener = null;
    this.userScriptMessageListener = null;
  }
  /**
   * Register a new sandbox with its runtime providers.
   * Call this BEFORE creating the iframe (for sandbox contexts) or executing user script.
   */
  registerSandbox(sandboxId, providers, consumers) {
    this.sandboxes.set(sandboxId, {
      sandboxId,
      iframe: null,
      // Will be set via setSandboxIframe() for sandbox contexts
      providers,
      consumers: new Set(consumers)
    });
    this.setupListener();
  }
  /**
   * Update the iframe reference for a sandbox.
   * Call this AFTER creating the iframe.
   * This is needed so providers can send responses back to the sandbox.
   */
  setSandboxIframe(sandboxId, iframe) {
    const context = this.sandboxes.get(sandboxId);
    if (context) {
      context.iframe = iframe;
    }
  }
  /**
   * Unregister a sandbox and remove all its consumers.
   * Call this when the sandbox is destroyed.
   */
  unregisterSandbox(sandboxId) {
    this.sandboxes.delete(sandboxId);
    if (this.sandboxes.size === 0) {
      if (this.messageListener) {
        window.removeEventListener("message", this.messageListener);
        this.messageListener = null;
      }
      if (this.userScriptMessageListener && typeof chrome !== "undefined" && chrome.runtime?.onUserScriptMessage) {
        chrome.runtime.onUserScriptMessage.removeListener(this.userScriptMessageListener);
        this.userScriptMessageListener = null;
      }
    }
  }
  /**
   * Add a message consumer for a sandbox.
   * Consumers receive broadcast messages (console, execution-complete, etc.)
   */
  addConsumer(sandboxId, consumer) {
    const context = this.sandboxes.get(sandboxId);
    if (context) {
      context.consumers.add(consumer);
    }
  }
  /**
   * Remove a message consumer from a sandbox.
   */
  removeConsumer(sandboxId, consumer) {
    const context = this.sandboxes.get(sandboxId);
    if (context) {
      context.consumers.delete(consumer);
    }
  }
  /**
   * Setup the global message listeners (called automatically)
   */
  setupListener() {
    if (!this.messageListener) {
      this.messageListener = async (e9) => {
        const { sandboxId, messageId } = e9.data;
        if (!sandboxId)
          return;
        const context = this.sandboxes.get(sandboxId);
        if (!context) {
          return;
        }
        const respond = (response) => {
          context.iframe?.contentWindow?.postMessage({
            type: "runtime-response",
            messageId,
            sandboxId,
            ...response
          }, "*");
        };
        for (const provider of context.providers) {
          if (provider.handleMessage) {
            await provider.handleMessage(e9.data, respond);
          }
        }
        for (const consumer of context.consumers) {
          await consumer.handleMessage(e9.data);
        }
      };
      window.addEventListener("message", this.messageListener);
    }
    if (!this.userScriptMessageListener) {
      if (typeof chrome === "undefined" || !chrome.runtime?.onUserScriptMessage) {
        return;
      }
      this.userScriptMessageListener = (message, _sender, sendResponse) => {
        const { sandboxId } = message;
        if (!sandboxId)
          return false;
        const context = this.sandboxes.get(sandboxId);
        if (!context)
          return false;
        const respond = (response) => {
          sendResponse({
            ...response,
            sandboxId
          });
        };
        (async () => {
          for (const provider of context.providers) {
            if (provider.handleMessage) {
              await provider.handleMessage(message, respond);
            }
          }
          for (const consumer of context.consumers) {
            await consumer.handleMessage(message);
          }
        })();
        return true;
      };
      chrome.runtime.onUserScriptMessage.addListener(this.userScriptMessageListener);
    }
  }
};
var RUNTIME_MESSAGE_ROUTER = new RuntimeMessageRouter();

// ../pi-mono/packages/web-ui/dist/components/SandboxedIframe.js
var __decorate7 = function(decorators, target, key, desc) {
  var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc);
  else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8;
  return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8;
};
function escapeScriptContent(code) {
  return code.replace(/<\/script/gi, "<\\/script");
}
var SandboxIframe = class SandboxIframe2 extends i4 {
  createRenderRoot() {
    return this;
  }
  connectedCallback() {
    super.connectedCallback();
  }
  disconnectedCallback() {
    super.disconnectedCallback();
    this.iframe?.remove();
  }
  /**
   * Load HTML content into sandbox and keep it displayed (for HTML artifacts)
   * @param sandboxId Unique ID
   * @param htmlContent Full HTML content
   * @param providers Runtime providers to inject
   * @param consumers Message consumers to register (optional)
   */
  loadContent(sandboxId, htmlContent, providers = [], consumers = []) {
    try {
      RUNTIME_MESSAGE_ROUTER.unregisterSandbox(sandboxId);
    } catch {
    }
    providers = [new ConsoleRuntimeProvider(), ...providers];
    RUNTIME_MESSAGE_ROUTER.registerSandbox(sandboxId, providers, consumers);
    const completeHtml = this.prepareHtmlDocument(sandboxId, htmlContent, providers, {
      isHtmlArtifact: true,
      isStandalone: false
    });
    const validationError = this.validateHtml(completeHtml);
    if (validationError) {
      console.error("HTML validation failed:", validationError);
      this.iframe?.remove();
      this.iframe = document.createElement("iframe");
      this.iframe.style.cssText = "width: 100%; height: 100%; border: none;";
      this.iframe.srcdoc = `
				<html>
				<body style="font-family: monospace; padding: 20px; background: #fff; color: #000;">
					<h3 style="color: #c00;">HTML Validation Error</h3>
					<pre style="background: #f5f5f5; padding: 10px; border-radius: 4px; overflow-x: auto; white-space: pre-wrap;">${validationError}</pre>
				</body>
				</html>
			`;
      this.appendChild(this.iframe);
      return;
    }
    this.iframe?.remove();
    if (this.sandboxUrlProvider) {
      this.loadViaSandboxUrl(sandboxId, completeHtml);
    } else {
      this.loadViaSrcdoc(sandboxId, completeHtml);
    }
  }
  loadViaSandboxUrl(sandboxId, completeHtml) {
    this.iframe = document.createElement("iframe");
    this.iframe.sandbox.add("allow-scripts");
    this.iframe.sandbox.add("allow-modals");
    this.iframe.style.width = "100%";
    this.iframe.style.height = "100%";
    this.iframe.style.border = "none";
    this.iframe.src = this.sandboxUrlProvider();
    RUNTIME_MESSAGE_ROUTER.setSandboxIframe(sandboxId, this.iframe);
    const externalUrlHandler = (e9) => {
      if (e9.data.type === "open-external-url" && e9.source === this.iframe?.contentWindow) {
        const chromeAPI = globalThis.chrome;
        if (chromeAPI?.tabs) {
          chromeAPI.tabs.create({ url: e9.data.url });
        } else {
          window.open(e9.data.url, "_blank");
        }
      }
    };
    window.addEventListener("message", externalUrlHandler);
    const readyHandler = (e9) => {
      if (e9.data.type === "sandbox-ready" && e9.source === this.iframe?.contentWindow) {
        window.removeEventListener("message", readyHandler);
        window.removeEventListener("message", errorHandler);
        this.iframe?.contentWindow?.postMessage({
          type: "sandbox-load",
          sandboxId,
          code: completeHtml
        }, "*");
      }
    };
    const errorHandler = (e9) => {
      if (e9.data.type === "sandbox-error" && e9.source === this.iframe?.contentWindow) {
        window.removeEventListener("message", readyHandler);
        window.removeEventListener("message", errorHandler);
        window.postMessage({
          sandboxId,
          type: "execution-error",
          error: { message: e9.data.error, stack: e9.data.stack }
        }, "*");
      }
    };
    window.addEventListener("message", readyHandler);
    window.addEventListener("message", errorHandler);
    this.appendChild(this.iframe);
  }
  loadViaSrcdoc(sandboxId, completeHtml) {
    this.iframe = document.createElement("iframe");
    this.iframe.sandbox.add("allow-scripts");
    this.iframe.sandbox.add("allow-modals");
    this.iframe.style.width = "100%";
    this.iframe.style.height = "100%";
    this.iframe.style.border = "none";
    this.iframe.srcdoc = completeHtml;
    RUNTIME_MESSAGE_ROUTER.setSandboxIframe(sandboxId, this.iframe);
    const externalUrlHandler = (e9) => {
      if (e9.data.type === "open-external-url" && e9.source === this.iframe?.contentWindow) {
        window.open(e9.data.url, "_blank");
      }
    };
    window.addEventListener("message", externalUrlHandler);
    this.appendChild(this.iframe);
  }
  /**
   * Execute code in sandbox
   * @param sandboxId Unique ID for this execution
   * @param code User code (plain JS for REPL, or full HTML for artifacts)
   * @param providers Runtime providers to inject
   * @param consumers Additional message consumers (optional, execute has its own internal consumer)
   * @param signal Abort signal
   * @returns Promise resolving to execution result
   */
  async execute(sandboxId, code, providers = [], consumers = [], signal, isHtmlArtifact = false) {
    if (signal?.aborted) {
      throw new Error("Execution aborted");
    }
    const consoleProvider = new ConsoleRuntimeProvider();
    providers = [consoleProvider, ...providers];
    RUNTIME_MESSAGE_ROUTER.registerSandbox(sandboxId, providers, consumers);
    for (const provider of providers) {
      provider.onExecutionStart?.(sandboxId, signal);
    }
    const files = [];
    let completed = false;
    return new Promise((resolve, reject) => {
      const executionConsumer = {
        async handleMessage(message) {
          if (message.type === "file-returned") {
            files.push({
              fileName: message.fileName,
              content: message.content,
              mimeType: message.mimeType
            });
          } else if (message.type === "execution-complete") {
            completed = true;
            cleanup();
            resolve({
              success: true,
              console: consoleProvider.getLogs(),
              files,
              returnValue: message.returnValue
            });
          } else if (message.type === "execution-error") {
            completed = true;
            cleanup();
            resolve({ success: false, console: consoleProvider.getLogs(), error: message.error, files });
          }
        }
      };
      RUNTIME_MESSAGE_ROUTER.addConsumer(sandboxId, executionConsumer);
      const cleanup = () => {
        for (const provider of providers) {
          provider.onExecutionEnd?.(sandboxId);
        }
        RUNTIME_MESSAGE_ROUTER.unregisterSandbox(sandboxId);
        signal?.removeEventListener("abort", abortHandler);
        clearTimeout(timeoutId);
        this.iframe?.remove();
        this.iframe = void 0;
      };
      const abortHandler = () => {
        if (!completed) {
          completed = true;
          cleanup();
          reject(new Error("Execution aborted"));
        }
      };
      if (signal) {
        signal.addEventListener("abort", abortHandler);
      }
      const timeoutId = setTimeout(() => {
        if (!completed) {
          completed = true;
          cleanup();
          resolve({
            success: false,
            console: consoleProvider.getLogs(),
            error: { message: "Execution timeout (120s)", stack: "" },
            files
          });
        }
      }, 12e4);
      const completeHtml = this.prepareHtmlDocument(sandboxId, code, providers, {
        isHtmlArtifact,
        isStandalone: false
      });
      const validationError = this.validateHtml(completeHtml);
      if (validationError) {
        reject(new Error(`HTML validation failed: ${validationError}`));
        return;
      }
      if (this.sandboxUrlProvider) {
        this.iframe = document.createElement("iframe");
        this.iframe.sandbox.add("allow-scripts", "allow-modals");
        this.iframe.style.cssText = "width: 100%; height: 100%; border: none;";
        this.iframe.src = this.sandboxUrlProvider();
        RUNTIME_MESSAGE_ROUTER.setSandboxIframe(sandboxId, this.iframe);
        const readyHandler = (e9) => {
          if (e9.data.type === "sandbox-ready" && e9.source === this.iframe?.contentWindow) {
            window.removeEventListener("message", readyHandler);
            window.removeEventListener("message", errorHandler);
            this.iframe?.contentWindow?.postMessage({
              type: "sandbox-load",
              sandboxId,
              code: completeHtml
            }, "*");
          }
        };
        const errorHandler = (e9) => {
          if (e9.data.type === "sandbox-error" && e9.source === this.iframe?.contentWindow) {
            window.removeEventListener("message", readyHandler);
            window.removeEventListener("message", errorHandler);
            window.postMessage({
              sandboxId,
              type: "execution-error",
              error: { message: e9.data.error, stack: e9.data.stack }
            }, "*");
          }
        };
        window.addEventListener("message", readyHandler);
        window.addEventListener("message", errorHandler);
        this.appendChild(this.iframe);
      } else {
        this.iframe = document.createElement("iframe");
        this.iframe.sandbox.add("allow-scripts", "allow-modals");
        this.iframe.style.cssText = "width: 100%; height: 100%; border: none; display: none;";
        this.iframe.srcdoc = completeHtml;
        RUNTIME_MESSAGE_ROUTER.setSandboxIframe(sandboxId, this.iframe);
        this.appendChild(this.iframe);
      }
    });
  }
  /**
   * Validate HTML using DOMParser - returns error message if invalid, null if valid
   * Note: JavaScript syntax validation is done in sandbox.js to avoid CSP restrictions
   */
  validateHtml(html) {
    try {
      const parser = new DOMParser();
      const doc = parser.parseFromString(html, "text/html");
      const parserError = doc.querySelector("parsererror");
      if (parserError) {
        return parserError.textContent || "Unknown parse error";
      }
      return null;
    } catch (error) {
      return error.message || "Unknown validation error";
    }
  }
  /**
   * Prepare complete HTML document with runtime + user code
   * PUBLIC so HtmlArtifact can use it for download button
   */
  prepareHtmlDocument(sandboxId, userCode, providers = [], options) {
    const opts = {
      isHtmlArtifact: false,
      isStandalone: false,
      ...options
    };
    const runtime = this.getRuntimeScript(sandboxId, providers, opts.isStandalone || false);
    if (opts.isHtmlArtifact) {
      const headMatch = userCode.match(/<head[^>]*>/i);
      if (headMatch) {
        const index = headMatch.index + headMatch[0].length;
        return userCode.slice(0, index) + runtime + userCode.slice(index);
      }
      const htmlMatch = userCode.match(/<html[^>]*>/i);
      if (htmlMatch) {
        const index = htmlMatch.index + htmlMatch[0].length;
        return userCode.slice(0, index) + runtime + userCode.slice(index);
      }
      return runtime + userCode;
    } else {
      const escapedUserCode = escapeScriptContent(userCode);
      return `<!DOCTYPE html>
<html>
<head>
	${runtime}
</head>
<body>
	<script type="module">
		(async () => {
			try {
				// Wrap user code in async function to capture return value
				const userCodeFunc = async () => {
					${escapedUserCode}
				};

				const returnValue = await userCodeFunc();

				// Call completion callbacks before complete()
				if (window.__completionCallbacks && window.__completionCallbacks.length > 0) {
					try {
						await Promise.all(window.__completionCallbacks.map(cb => cb(true)));
					} catch (e) {
						console.error('Completion callback error:', e);
					}
				}

				await window.complete(null, returnValue);
			} catch (error) {

				// Call completion callbacks before complete() (error path)
				if (window.__completionCallbacks && window.__completionCallbacks.length > 0) {
					try {
						await Promise.all(window.__completionCallbacks.map(cb => cb(false)));
					} catch (e) {
						console.error('Completion callback error:', e);
					}
				}

				await window.complete({
					message: error?.message || String(error),
					stack: error?.stack || new Error().stack
				});
			}
		})();
	<\/script>
</body>
</html>`;
    }
  }
  /**
   * Generate runtime script from providers
   * @param sandboxId Unique sandbox ID
   * @param providers Runtime providers
   * @param isStandalone If true, skip runtime bridge and navigation interceptor (for standalone downloads)
   */
  getRuntimeScript(sandboxId, providers = [], isStandalone = false) {
    const allData = {};
    for (const provider of providers) {
      Object.assign(allData, provider.getData());
    }
    const bridgeCode = isStandalone ? "" : RuntimeMessageBridge.generateBridgeCode({
      context: "sandbox-iframe",
      sandboxId
    });
    const runtimeFunctions = [];
    for (const provider of providers) {
      runtimeFunctions.push(`(${provider.getRuntime().toString()})(${JSON.stringify(sandboxId)});`);
    }
    const dataInjection = Object.entries(allData).map(([key, value]) => {
      const jsonStr = JSON.stringify(value).replace(/<\/script/gi, "<\\/script");
      return `window.${key} = ${jsonStr};`;
    }).join("\n");
    const navigationInterceptor = isStandalone ? "" : `
// Navigation interceptor: prevent all navigation and open externally
(function() {
	// Intercept link clicks
	document.addEventListener('click', function(e) {
		const link = e.target.closest('a');
		if (link && link.href) {
			// Check if it's an external link (not javascript: or #hash)
			if (link.href.startsWith('http://') || link.href.startsWith('https://')) {
				e.preventDefault();
				e.stopPropagation();
				window.parent.postMessage({ type: 'open-external-url', url: link.href }, '*');
			}
		}
	}, true);

	// Intercept form submissions
	document.addEventListener('submit', function(e) {
		const form = e.target;
		if (form && form.action) {
			e.preventDefault();
			e.stopPropagation();
			window.parent.postMessage({ type: 'open-external-url', url: form.action }, '*');
		}
	}, true);

	// Prevent window.location changes (only if not already redefined)
	try {
		const originalLocation = window.location;
		Object.defineProperty(window, 'location', {
			get: function() { return originalLocation; },
			set: function(url) {
				window.parent.postMessage({ type: 'open-external-url', url: url.toString() }, '*');
			}
		});
	} catch (e) {
		// Already defined, skip
	}
})();
`;
    return `<style>
html, body {
	font-size: initial;
}
</style>
<script>
window.sandboxId = ${JSON.stringify(sandboxId)};
${dataInjection}
${bridgeCode}
${runtimeFunctions.join("\n")}
${navigationInterceptor}
<\/script>`;
  }
};
__decorate7([
  n6({ attribute: false })
], SandboxIframe.prototype, "sandboxUrlProvider", void 0);
SandboxIframe = __decorate7([
  t5("sandbox-iframe")
], SandboxIframe);

// ../pi-mono/packages/web-ui/dist/prompts/prompts.js
init_process_shim();
var JAVASCRIPT_REPL_TOOL_DESCRIPTION = (runtimeProviderDescriptions) => `# JavaScript REPL

## Purpose
Execute JavaScript code in a sandboxed browser environment with full Web APIs.

## When to Use
- Quick calculations or data transformations
- Testing JavaScript code snippets in isolation
- Processing data with libraries (XLSX, CSV, etc.)
- Creating artifacts from data

## Environment
- ES2023+ JavaScript (async/await, optional chaining, nullish coalescing, etc.)
- All browser APIs: DOM, Canvas, WebGL, Fetch, Web Workers, WebSockets, Crypto, etc.
- Import any npm package: await import('https://esm.run/package-name')

## Common Libraries
- XLSX: const XLSX = await import('https://esm.run/xlsx');
- CSV: const Papa = (await import('https://esm.run/papaparse')).default;
- Chart.js: const Chart = (await import('https://esm.run/chart.js/auto')).default;
- Three.js: const THREE = await import('https://esm.run/three');

## Persistence between tool calls
- Objects stored on global scope do not persist between calls.
- Use artifacts as a key-value JSON object store:
  - Use createOrUpdateArtifact(filename, content) to persist data between calls. JSON objects are auto-stringified.
  - Use listArtifacts() and getArtifact(filename) to read persisted data. JSON files are auto-parsed to objects.
  - Prefer to use a single artifact throughout the session to store intermediate data (e.g. 'data.json').

## Input
- You have access to the user's attachments via listAttachments(), readTextAttachment(id), and readBinaryAttachment(id)
- You have access to previously created artifacts via listArtifacts() and getArtifact(filename)

## Output
- All console.log() calls are captured for you to inspect. The user does not see these logs.
- Create artifacts for file results (images, JSON, CSV, etc.) which persiste throughout the
  session and are accessible to you and the user.

## Example
const data = [10, 20, 15, 25];
const sum = data.reduce((a, b) => a + b, 0);
const avg = sum / data.length;
console.log('Sum:', sum, 'Average:', avg);

## Important Notes
- Graphics: Use fixed dimensions (800x600), NOT window.innerWidth/Height
- Chart.js: Set options: { responsive: false, animation: false }
- Three.js: renderer.setSize(800, 600) with matching aspect ratio

## Helper Functions (Automatically Available)

These functions are injected into the execution environment and available globally:

${runtimeProviderDescriptions.join("\n\n")}
`;
var ARTIFACTS_TOOL_DESCRIPTION = (runtimeProviderDescriptions) => `# Artifacts

Create and manage persistent files that live alongside the conversation.

## When to Use - Artifacts Tool vs REPL

**Use artifacts tool when YOU are the author:**
- Writing research summaries, analysis, ideas, documentation
- Creating markdown notes for user to read
- Building HTML applications/visualizations that present data
- Creating HTML artifacts that render charts from programmatically generated data

**Use repl + artifact storage functions when CODE processes data:**
- Scraping workflows that extract and store data
- Processing CSV/Excel files programmatically
- Data transformation pipelines
- Binary file generation requiring libraries (PDF, DOCX)

**Pattern: REPL generates data \u2192 Artifacts tool creates HTML that visualizes it**
Example: repl scrapes products \u2192 stores products.json \u2192 you author dashboard.html that reads products.json and renders Chart.js visualizations

## Input
- { action: "create", filename: "notes.md", content: "..." } - Create new file
- { action: "update", filename: "notes.md", old_str: "...", new_str: "..." } - Update part of file (PREFERRED)
- { action: "rewrite", filename: "notes.md", content: "..." } - Replace entire file (LAST RESORT)
- { action: "get", filename: "data.json" } - Retrieve file content
- { action: "delete", filename: "old.csv" } - Delete file
- { action: "htmlArtifactLogs", filename: "app.html" } - Get console logs from HTML artifact

## Returns
Depends on action:
- create/update/rewrite/delete: Success status or error
- get: File content
- htmlArtifactLogs: Console logs and errors

## Supported File Types
\u2705 Text-based files you author: .md, .txt, .html, .js, .css, .json, .csv, .svg
\u274C Binary files requiring libraries (use repl): .pdf, .docx

## Critical - Prefer Update Over Rewrite
\u274C NEVER: get entire file + rewrite to change small sections
\u2705 ALWAYS: update for targeted edits (token efficient)
\u2705 Ask: Can I describe the change as old_str \u2192 new_str? Use update.

---

## HTML Artifacts

Interactive HTML applications that can visualize data from other artifacts.

### Data Access
- Can read artifacts created by repl and user attachments
- Use to build dashboards, visualizations, interactive tools
- See Helper Functions section below for available functions

### Requirements
- Self-contained single file
- Import ES modules from esm.sh: <script type="module">import X from 'https://esm.sh/pkg';<\/script>
- Use Tailwind CDN: <script src="https://cdn.tailwindcss.com"><\/script>
- Can embed images from any domain: <img src="https://example.com/image.jpg">
- MUST set background color explicitly (avoid transparent)
- Inline CSS or Tailwind utility classes
- No localStorage/sessionStorage

### Styling
- Use Tailwind utility classes for clean, functional designs
- Ensure responsive layout (iframe may be resized)
- Avoid purple gradients, AI aesthetic clich\xE9s, and emojis

### Helper Functions (Automatically Available)

These functions are injected into HTML artifact sandbox:

${runtimeProviderDescriptions.join("\n\n")}
`;
var ARTIFACTS_RUNTIME_PROVIDER_DESCRIPTION_RW = `
### Artifacts Storage

Create, read, update, and delete files in artifacts storage.

#### When to Use
- Store intermediate results between tool calls
- Save generated files (images, CSVs, processed data) for user to view and download

#### Do NOT Use For
- Content you author directly, like summaries of content you read (use artifacts tool instead)

#### Functions
- listArtifacts() - List all artifact filenames, returns Promise<string[]>
- getArtifact(filename) - Read artifact content, returns Promise<string | object>. JSON files auto-parse to objects, binary files return base64 string
- createOrUpdateArtifact(filename, content, mimeType?) - Create or update artifact, returns Promise<void>. JSON files auto-stringify objects, binary requires base64 string with mimeType
- deleteArtifact(filename) - Delete artifact, returns Promise<void>

#### Example
JSON workflow:
\`\`\`javascript
// Fetch and save
const response = await fetch('https://api.example.com/products');
const products = await response.json();
await createOrUpdateArtifact('products.json', products);

// Later: read and filter
const all = await getArtifact('products.json');
const cheap = all.filter(p => p.price < 100);
await createOrUpdateArtifact('cheap.json', cheap);
\`\`\`

Binary file (image):
\`\`\`javascript
const canvas = document.createElement('canvas');
canvas.width = 800; canvas.height = 600;
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'blue';
ctx.fillRect(0, 0, 800, 600);
// Remove data:image/png;base64, prefix
const base64 = canvas.toDataURL().split(',')[1];
await createOrUpdateArtifact('chart.png', base64, 'image/png');
\`\`\`
`;
var ARTIFACTS_RUNTIME_PROVIDER_DESCRIPTION_RO = `
### Artifacts Storage

Read files from artifacts storage.

#### When to Use
- Read artifacts created by REPL or artifacts tool
- Access data from other HTML artifacts
- Load configuration or data files

#### Do NOT Use For
- Creating new artifacts (not available in HTML artifacts)
- Modifying artifacts (read-only access)

#### Functions
- listArtifacts() - List all artifact filenames, returns Promise<string[]>
- getArtifact(filename) - Read artifact content, returns Promise<string | object>. JSON files auto-parse to objects, binary files return base64 string

#### Example
JSON data:
\`\`\`javascript
const products = await getArtifact('products.json');
const html = products.map(p => \`<div>\${p.name}: $\${p.price}</div>\`).join('');
document.body.innerHTML = html;
\`\`\`

Binary image:
\`\`\`javascript
const base64 = await getArtifact('chart.png');
const img = document.createElement('img');
img.src = 'data:image/png;base64,' + base64;
document.body.appendChild(img);
\`\`\`
`;
var ATTACHMENTS_RUNTIME_DESCRIPTION = `
### User Attachments

Read files the user uploaded to the conversation.

#### When to Use
- Process user-uploaded files (CSV, JSON, Excel, images, PDFs)

#### Functions
- listAttachments() - List all attachments, returns array of {id, fileName, mimeType, size}
- readTextAttachment(id) - Read attachment as text, returns string
- readBinaryAttachment(id) - Read attachment as binary data, returns Uint8Array

#### Example
CSV file:
\`\`\`javascript
const files = listAttachments();
const csvFile = files.find(f => f.fileName.endsWith('.csv'));
const csvData = readTextAttachment(csvFile.id);
const rows = csvData.split('\\n').map(row => row.split(','));
\`\`\`

Excel file:
\`\`\`javascript
const XLSX = await import('https://esm.run/xlsx');
const files = listAttachments();
const xlsxFile = files.find(f => f.fileName.endsWith('.xlsx'));
const bytes = readBinaryAttachment(xlsxFile.id);
const workbook = XLSX.read(bytes);
const data = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]]);
\`\`\`
`;
var EXTRACT_DOCUMENT_DESCRIPTION = `# Extract Document

Extract plain text from documents on the web (PDF, DOCX, XLSX, PPTX).

## When to Use
User wants you to read a document at a URL.

## Input
- { url: "https://example.com/document.pdf" } - URL to PDF, DOCX, XLSX, or PPTX

## Returns
Structured plain text with page/sheet/slide delimiters.`;

// ../pi-mono/packages/web-ui/dist/tools/renderer-registry.js
init_process_shim();
var toolRenderers = /* @__PURE__ */ new Map();
function registerToolRenderer(toolName, renderer) {
  toolRenderers.set(toolName, renderer);
}
function getToolRenderer(toolName) {
  return toolRenderers.get(toolName);
}
function renderHeader(state, toolIcon, text3) {
  const statusIcon = (iconComponent, color) => b2`<span class="inline-block ${color}">${icon(iconComponent, "sm")}</span>`;
  switch (state) {
    case "inprogress":
      return b2`
				<div class="flex items-center justify-between gap-2 text-sm text-muted-foreground">
					<div class="flex items-center gap-2">
						${statusIcon(toolIcon, "text-foreground")}
						${text3}
					</div>
					${statusIcon(Loader, "text-foreground animate-spin")}
				</div>
			`;
    case "complete":
      return b2`
				<div class="flex items-center gap-2 text-sm text-muted-foreground">
					${statusIcon(toolIcon, "text-green-600 dark:text-green-500")}
					${text3}
				</div>
			`;
    case "error":
      return b2`
				<div class="flex items-center gap-2 text-sm text-muted-foreground">
					${statusIcon(toolIcon, "text-destructive")}
					${text3}
				</div>
			`;
  }
}
function renderCollapsibleHeader(state, toolIcon, text3, contentRef, chevronRef, defaultExpanded = false) {
  const statusIcon = (iconComponent, color) => b2`<span class="inline-block ${color}">${icon(iconComponent, "sm")}</span>`;
  const toggleContent = (e9) => {
    e9.preventDefault();
    const content = contentRef.value;
    const chevron = chevronRef.value;
    if (content && chevron) {
      const isCollapsed = content.classList.contains("max-h-0");
      if (isCollapsed) {
        content.classList.remove("max-h-0");
        content.classList.add("max-h-[2000px]", "mt-3");
        const upIcon = chevron.querySelector(".chevron-up");
        const downIcon = chevron.querySelector(".chevrons-up-down");
        if (upIcon && downIcon) {
          upIcon.classList.remove("hidden");
          downIcon.classList.add("hidden");
        }
      } else {
        content.classList.remove("max-h-[2000px]", "mt-3");
        content.classList.add("max-h-0");
        const upIcon = chevron.querySelector(".chevron-up");
        const downIcon = chevron.querySelector(".chevrons-up-down");
        if (upIcon && downIcon) {
          upIcon.classList.add("hidden");
          downIcon.classList.remove("hidden");
        }
      }
    }
  };
  const toolIconColor = state === "complete" ? "text-green-600 dark:text-green-500" : state === "error" ? "text-destructive" : "text-foreground";
  return b2`
		<button @click=${toggleContent} class="flex items-center justify-between gap-2 text-sm text-muted-foreground w-full text-left hover:text-foreground transition-colors cursor-pointer">
			<div class="flex items-center gap-2">
				${state === "inprogress" ? statusIcon(Loader, "text-foreground animate-spin") : ""}
				${statusIcon(toolIcon, toolIconColor)}
				${text3}
			</div>
			<span class="inline-block text-muted-foreground" ${n5(chevronRef)}>
				<span class="chevron-up ${defaultExpanded ? "" : "hidden"}">${icon(ChevronUp, "sm")}</span>
				<span class="chevrons-up-down ${defaultExpanded ? "hidden" : ""}">${icon(ChevronsUpDown, "sm")}</span>
			</span>
		</button>
	`;
}

// ../pi-mono/packages/web-ui/dist/tools/javascript-repl.js
async function executeJavaScript(code, runtimeProviders, signal, sandboxUrlProvider) {
  if (!code) {
    throw new Error("Code parameter is required");
  }
  if (signal?.aborted) {
    throw new Error("Execution aborted");
  }
  const sandbox = new SandboxIframe();
  if (sandboxUrlProvider) {
    sandbox.sandboxUrlProvider = sandboxUrlProvider;
  }
  sandbox.style.display = "none";
  document.body.appendChild(sandbox);
  try {
    const sandboxId = `repl-${Date.now()}-${Math.random().toString(36).substring(7)}`;
    const result = await sandbox.execute(sandboxId, code, runtimeProviders, [], signal);
    sandbox.remove();
    let output = "";
    if (result.console && result.console.length > 0) {
      for (const entry of result.console) {
        output += `${entry.text}
`;
      }
    }
    if (!result.success) {
      if (output)
        output += "\n";
      output += `Error: ${result.error?.message || "Unknown error"}
${result.error?.stack || ""}`;
      throw new Error(output.trim());
    }
    if (result.returnValue !== void 0) {
      if (output)
        output += "\n";
      output += `=> ${typeof result.returnValue === "object" ? JSON.stringify(result.returnValue, null, 2) : result.returnValue}`;
    }
    if (result.files && result.files.length > 0) {
      output += `
[Files returned: ${result.files.length}]
`;
      for (const file of result.files) {
        output += `  - ${file.fileName} (${file.mimeType})
`;
      }
    } else {
      if (code.includes("returnFile")) {
        output += "\n[No files returned - check async operations]";
      }
    }
    return {
      output: output.trim() || "Code executed successfully (no output)",
      files: result.files
    };
  } catch (error) {
    sandbox.remove();
    throw new Error(error.message || "Execution failed");
  }
}
var javascriptReplSchema = Type.Object({
  title: Type.String({
    description: "Brief title describing what the code snippet tries to achieve in active form, e.g. 'Calculating sum'"
  }),
  code: Type.String({ description: "JavaScript code to execute" })
});
function createJavaScriptReplTool() {
  return {
    label: "JavaScript REPL",
    name: "javascript_repl",
    runtimeProvidersFactory: () => [],
    // default to empty array
    sandboxUrlProvider: void 0,
    // optional, for browser extensions
    get description() {
      const runtimeProviderDescriptions = this.runtimeProvidersFactory?.().map((d4) => d4.getDescription()).filter((d4) => d4.trim().length > 0) || [];
      return JAVASCRIPT_REPL_TOOL_DESCRIPTION(runtimeProviderDescriptions);
    },
    parameters: javascriptReplSchema,
    execute: async function(_toolCallId, args, signal) {
      const result = await executeJavaScript(args.code, this.runtimeProvidersFactory?.() ?? [], signal, this.sandboxUrlProvider);
      const files = (result.files || []).map((f4) => {
        const toBase64 = (input) => {
          if (input instanceof Uint8Array) {
            let binary = "";
            const chunk = 32768;
            for (let i7 = 0; i7 < input.length; i7 += chunk) {
              binary += String.fromCharCode(...input.subarray(i7, i7 + chunk));
            }
            return { base64: btoa(binary), size: input.length };
          } else if (typeof input === "string") {
            const enc = new TextEncoder();
            const bytes = enc.encode(input);
            let binary = "";
            const chunk = 32768;
            for (let i7 = 0; i7 < bytes.length; i7 += chunk) {
              binary += String.fromCharCode(...bytes.subarray(i7, i7 + chunk));
            }
            return { base64: btoa(binary), size: bytes.length };
          } else {
            const s6 = String(input);
            const enc = new TextEncoder();
            const bytes = enc.encode(s6);
            let binary = "";
            const chunk = 32768;
            for (let i7 = 0; i7 < bytes.length; i7 += chunk) {
              binary += String.fromCharCode(...bytes.subarray(i7, i7 + chunk));
            }
            return { base64: btoa(binary), size: bytes.length };
          }
        };
        const { base64, size } = toBase64(f4.content);
        return {
          fileName: f4.fileName || "file",
          mimeType: f4.mimeType || "application/octet-stream",
          size,
          contentBase64: base64
        };
      });
      return { content: [{ type: "text", text: result.output }], details: { files } };
    }
  };
}
var javascriptReplTool = createJavaScriptReplTool();
var javascriptReplRenderer = {
  render(params, result, isStreaming) {
    const state = result ? result.isError ? "error" : "complete" : isStreaming ? "inprogress" : "complete";
    const codeContentRef = e5();
    const codeChevronRef = e5();
    if (result && params) {
      const output = result.content?.filter((c6) => c6.type === "text").map((c6) => c6.text).join("\n") || "";
      const files = result.details?.files || [];
      const attachments = files.map((f4, i7) => {
        let extractedText;
        const isTextBased = f4.mimeType?.startsWith("text/") || f4.mimeType === "application/json" || f4.mimeType === "application/javascript" || f4.mimeType?.includes("xml");
        if (isTextBased && f4.contentBase64) {
          try {
            extractedText = atob(f4.contentBase64);
          } catch (_e2) {
            console.warn("Failed to decode base64 content for", f4.fileName);
          }
        }
        return {
          id: `repl-${Date.now()}-${i7}`,
          type: f4.mimeType?.startsWith("image/") ? "image" : "document",
          fileName: f4.fileName || `file-${i7}`,
          mimeType: f4.mimeType || "application/octet-stream",
          size: f4.size ?? 0,
          content: f4.contentBase64,
          preview: f4.mimeType?.startsWith("image/") ? f4.contentBase64 : void 0,
          extractedText
        };
      });
      return {
        content: b2`
					<div>
						${renderCollapsibleHeader(state, Code2, params.title ? params.title : i18n("Executing JavaScript"), codeContentRef, codeChevronRef, false)}
						<div ${n5(codeContentRef)} class="max-h-0 overflow-hidden transition-all duration-300 space-y-3">
							<code-block .code=${params.code || ""} language="javascript"></code-block>
							${output ? b2`<console-block .content=${output} .variant=${result.isError ? "error" : "default"}></console-block>` : ""}
						</div>
						${attachments.length ? b2`<div class="flex flex-wrap gap-2 mt-3">
									${attachments.map((att) => b2`<attachment-tile .attachment=${att}></attachment-tile>`)}
							  </div>` : ""}
					</div>
				`,
        isCustom: false
      };
    }
    if (params) {
      return {
        content: b2`
					<div>
						${renderCollapsibleHeader(state, Code2, params.title ? params.title : i18n("Executing JavaScript"), codeContentRef, codeChevronRef, false)}
						<div ${n5(codeContentRef)} class="max-h-0 overflow-hidden transition-all duration-300">
							${params.code ? b2`<code-block .code=${params.code} language="javascript"></code-block>` : ""}
						</div>
					</div>
				`,
        isCustom: false
      };
    }
    return { content: renderHeader(state, Code2, i18n("Preparing JavaScript...")), isCustom: false };
  }
};
registerToolRenderer(javascriptReplTool.name, javascriptReplRenderer);

// ../pi-mono/packages/web-ui/dist/tools/extract-document.js
init_process_shim();

// ../pi-mono/packages/web-ui/dist/utils/proxy-utils.js
init_process_shim();
function shouldUseProxyForProvider(provider, apiKey) {
  switch (provider.toLowerCase()) {
    case "zai":
      return true;
    case "anthropic":
      return apiKey.startsWith("sk-ant-oat") || apiKey.startsWith("{");
    case "openai-codex":
      return true;
    // These providers work without proxy
    case "openai":
    case "google":
    case "groq":
    case "openrouter":
    case "cerebras":
    case "xai":
    case "ollama":
    case "lmstudio":
    case "github-copilot":
      return false;
    // Unknown providers - assume no proxy needed
    // This allows new providers to work by default
    default:
      return false;
  }
}
function applyProxyIfNeeded(model, apiKey, proxyUrl) {
  if (!proxyUrl) {
    return model;
  }
  if (!model.baseUrl) {
    return model;
  }
  if (!shouldUseProxyForProvider(model.provider, apiKey)) {
    return model;
  }
  return {
    ...model,
    baseUrl: `${proxyUrl}/?url=${encodeURIComponent(model.baseUrl)}`
  };
}
function isCorsError(error) {
  if (!(error instanceof Error)) {
    return false;
  }
  const message = error.message.toLowerCase();
  if (error.name === "TypeError" && message.includes("failed to fetch")) {
    return true;
  }
  if (error.name === "NetworkError") {
    return true;
  }
  if (message.includes("cors") || message.includes("cross-origin")) {
    return true;
  }
  return false;
}
function createStreamFn(getProxyUrl) {
  return async (model, context, options) => {
    const apiKey = options?.apiKey;
    const proxyUrl = await getProxyUrl();
    if (!apiKey || !proxyUrl) {
      return streamSimple(model, context, options);
    }
    const proxiedModel = applyProxyIfNeeded(model, apiKey, proxyUrl);
    return streamSimple(proxiedModel, context, options);
  };
}

// ../pi-mono/packages/web-ui/dist/tools/extract-document.js
var extractDocumentSchema = Type.Object({
  url: Type.String({
    description: "URL of the document to extract text from (PDF, DOCX, XLSX, or PPTX)"
  })
});
function createExtractDocumentTool() {
  const tool = {
    label: "Extract Document",
    name: "extract_document",
    corsProxyUrl: void 0,
    // Can be set by consumer (e.g., from user settings)
    description: EXTRACT_DOCUMENT_DESCRIPTION,
    parameters: extractDocumentSchema,
    execute: async (_toolCallId, args, signal) => {
      if (signal?.aborted) {
        throw new Error("Extract document aborted");
      }
      const url = args.url.trim();
      if (!url) {
        throw new Error("URL is required");
      }
      try {
        new URL(url);
      } catch {
        throw new Error(`Invalid URL: ${url}`);
      }
      const MAX_SIZE = 50 * 1024 * 1024;
      const fetchAndProcess = async (fetchUrl) => {
        const response = await fetch(fetchUrl, { signal });
        if (!response.ok) {
          throw new Error(`TELL USER: Unable to download the document (${response.status} ${response.statusText}). The site likely blocks automated downloads.

INSTRUCT USER: Please download the file manually and attach it to your message using the attachment button (paperclip icon) in the message input area. I can then extract the text from the attached file.`);
        }
        const contentLength = response.headers.get("content-length");
        if (contentLength) {
          const size2 = Number.parseInt(contentLength, 10);
          if (size2 > MAX_SIZE) {
            throw new Error(`Document is too large (${(size2 / 1024 / 1024).toFixed(1)}MB). Maximum supported size is 50MB.`);
          }
        }
        const arrayBuffer2 = await response.arrayBuffer();
        const size = arrayBuffer2.byteLength;
        if (size > MAX_SIZE) {
          throw new Error(`Document is too large (${(size / 1024 / 1024).toFixed(1)}MB). Maximum supported size is 50MB.`);
        }
        return arrayBuffer2;
      };
      let arrayBuffer;
      try {
        arrayBuffer = await fetchAndProcess(url);
      } catch (directError) {
        if (isCorsError(directError) && tool.corsProxyUrl) {
          try {
            const proxiedUrl = tool.corsProxyUrl + encodeURIComponent(url);
            arrayBuffer = await fetchAndProcess(proxiedUrl);
          } catch (proxyError) {
            throw new Error(`TELL USER: Unable to fetch the document due to CORS restrictions.

Tried with proxy but it also failed: ${proxyError.message}

INSTRUCT USER: Please download the file manually and attach it to your message using the attachment button (paperclip icon) in the message input area. I can then extract the text from the attached file.`);
          }
        } else if (isCorsError(directError) && !tool.corsProxyUrl) {
          throw new Error(`TELL USER: Unable to fetch the document due to CORS restrictions (the server blocks requests from browser extensions).

To fix this, you need to configure a CORS proxy in Sitegeist settings:
1. Open Sitegeist settings
2. Find "CORS Proxy URL" setting
3. Enter a proxy URL like: https://corsproxy.io/?
4. Save and try again

Alternatively, download the file manually and attach it to your message using the attachment button (paperclip icon).`);
        } else {
          throw directError;
        }
      }
      const urlParts = url.split("/");
      let fileName = urlParts[urlParts.length - 1]?.split("?")[0] || "document";
      if (url.startsWith("https://arxiv.org/")) {
        fileName = `${fileName}.pdf`;
      }
      const attachment = await loadAttachment(arrayBuffer, fileName);
      if (!attachment.extractedText) {
        throw new Error(`Document format not supported. Supported formats:
- PDF (.pdf)
- Word (.docx)
- Excel (.xlsx, .xls)
- PowerPoint (.pptx)`);
      }
      let format = "unknown";
      if (attachment.mimeType.includes("pdf")) {
        format = "pdf";
      } else if (attachment.mimeType.includes("wordprocessingml")) {
        format = "docx";
      } else if (attachment.mimeType.includes("spreadsheetml") || attachment.mimeType.includes("ms-excel")) {
        format = "xlsx";
      } else if (attachment.mimeType.includes("presentationml")) {
        format = "pptx";
      }
      return {
        content: [{ type: "text", text: attachment.extractedText }],
        details: {
          extractedText: attachment.extractedText,
          format,
          fileName: attachment.fileName,
          size: attachment.size
        }
      };
    }
  };
  return tool;
}
var extractDocumentTool = createExtractDocumentTool();
var extractDocumentRenderer = {
  render(params, result, isStreaming) {
    const state = result ? result.isError ? "error" : "complete" : isStreaming ? "inprogress" : "complete";
    const contentRef = e5();
    const chevronRef = e5();
    if (result && params) {
      const details = result.details;
      const title = details ? result.isError ? `Failed to extract ${details.fileName || "document"}` : `Extracted text from ${details.fileName} (${details.format.toUpperCase()}, ${(details.size / 1024).toFixed(1)}KB)` : result.isError ? "Failed to extract document" : "Extracted text from document";
      const output = result.content?.filter((c6) => c6.type === "text").map((c6) => c6.text).join("\n") || "";
      return {
        content: b2`
					<div>
						${renderCollapsibleHeader(state, FileText, title, contentRef, chevronRef, false)}
						<div ${n5(contentRef)} class="max-h-0 overflow-hidden transition-all duration-300 space-y-3">
							${params.url ? b2`<div class="text-sm text-gray-600 dark:text-gray-400">
										<strong>URL:</strong> ${params.url}
								  </div>` : ""}
							${output && !result.isError ? b2`<code-block .code=${output} language="plaintext"></code-block>` : ""}
							${result.isError && output ? b2`<console-block .content=${output} .variant=${"error"}></console-block>` : ""}
						</div>
					</div>
				`,
        isCustom: false
      };
    }
    if (params) {
      const title = "Extracting document...";
      return {
        content: b2`
					<div>
						${renderCollapsibleHeader(state, FileText, title, contentRef, chevronRef, false)}
						<div ${n5(contentRef)} class="max-h-0 overflow-hidden transition-all duration-300">
							<div class="text-sm text-gray-600 dark:text-gray-400"><strong>URL:</strong> ${params.url}</div>
						</div>
					</div>
				`,
        isCustom: false
      };
    }
    return {
      content: renderHeader(state, FileText, "Preparing extraction..."),
      isCustom: false
    };
  }
};
registerToolRenderer("extract_document", extractDocumentRenderer);

// ../pi-mono/packages/web-ui/dist/tools/renderers/BashRenderer.js
init_process_shim();
var BashRenderer = class {
  render(params, result) {
    const state = result ? result.isError ? "error" : "complete" : "inprogress";
    if (result && params?.command) {
      const output = result.content?.filter((c6) => c6.type === "text").map((c6) => c6.text).join("\n") || "";
      const combined = output ? `> ${params.command}

${output}` : `> ${params.command}`;
      return {
        content: b2`
					<div class="space-y-3">
						${renderHeader(state, SquareTerminal, i18n("Running command..."))}
						<console-block .content=${combined} .variant=${result.isError ? "error" : "default"}></console-block>
					</div>
				`,
        isCustom: false
      };
    }
    if (params?.command) {
      return {
        content: b2`
					<div class="space-y-3">
						${renderHeader(state, SquareTerminal, i18n("Running command..."))}
						<console-block .content=${`> ${params.command}`}></console-block>
					</div>
				`,
        isCustom: false
      };
    }
    return { content: renderHeader(state, SquareTerminal, i18n("Waiting for command...")), isCustom: false };
  }
};

// ../pi-mono/packages/web-ui/dist/tools/renderers/DefaultRenderer.js
init_process_shim();
var DefaultRenderer = class {
  render(params, result, isStreaming) {
    const state = result ? result.isError ? "error" : "complete" : isStreaming ? "inprogress" : "complete";
    let paramsJson = "";
    if (params) {
      try {
        paramsJson = JSON.stringify(JSON.parse(params), null, 2);
      } catch {
        try {
          paramsJson = JSON.stringify(params, null, 2);
        } catch {
          paramsJson = String(params);
        }
      }
    }
    if (result) {
      let outputJson = result.content?.filter((c6) => c6.type === "text").map((c6) => c6.text).join("\n") || i18n("(no output)");
      let outputLanguage = "text";
      try {
        const parsed = JSON.parse(outputJson);
        outputJson = JSON.stringify(parsed, null, 2);
        outputLanguage = "json";
      } catch {
      }
      return {
        content: b2`
					<div class="space-y-3">
						${renderHeader(state, Code2, "Tool Call")}
						${paramsJson ? b2`<div>
							<div class="text-xs font-medium mb-1 text-muted-foreground">${i18n("Input")}</div>
							<code-block .code=${paramsJson} language="json"></code-block>
						</div>` : ""}
						<div>
							<div class="text-xs font-medium mb-1 text-muted-foreground">${i18n("Output")}</div>
							<code-block .code=${outputJson} language="${outputLanguage}"></code-block>
						</div>
					</div>
				`,
        isCustom: false
      };
    }
    if (params) {
      if (isStreaming && (!paramsJson || paramsJson === "{}" || paramsJson === "null")) {
        return {
          content: b2`
						<div>
							${renderHeader(state, Code2, "Preparing tool parameters...")}
						</div>
					`,
          isCustom: false
        };
      }
      return {
        content: b2`
					<div class="space-y-3">
						${renderHeader(state, Code2, "Tool Call")}
						<div>
							<div class="text-xs font-medium mb-1 text-muted-foreground">${i18n("Input")}</div>
							<code-block .code=${paramsJson} language="json"></code-block>
						</div>
					</div>
				`,
        isCustom: false
      };
    }
    return {
      content: b2`
				<div>
					${renderHeader(state, Code2, "Preparing tool...")}
				</div>
			`,
      isCustom: false
    };
  }
};

// ../pi-mono/packages/web-ui/dist/tools/index.js
registerToolRenderer("bash", new BashRenderer());
var defaultRenderer = new DefaultRenderer();
var showJsonMode = false;
function renderTool(toolName, params, result, isStreaming) {
  if (showJsonMode) {
    return defaultRenderer.render(params, result, isStreaming);
  }
  const renderer = getToolRenderer(toolName);
  if (renderer) {
    return renderer.render(params, result, isStreaming);
  }
  return defaultRenderer.render(params, result, isStreaming);
}

// ../pi-mono/packages/web-ui/dist/components/ThinkingBlock.js
init_process_shim();
var __decorate8 = function(decorators, target, key, desc) {
  var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc);
  else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8;
  return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8;
};
var ThinkingBlock = class ThinkingBlock2 extends i4 {
  constructor() {
    super(...arguments);
    this.isStreaming = false;
    this.isExpanded = false;
  }
  createRenderRoot() {
    return this;
  }
  connectedCallback() {
    super.connectedCallback();
    this.style.display = "block";
  }
  toggleExpanded() {
    this.isExpanded = !this.isExpanded;
  }
  render() {
    const shimmerClasses = this.isStreaming ? "animate-shimmer bg-gradient-to-r from-muted-foreground via-foreground to-muted-foreground bg-[length:200%_100%] bg-clip-text text-transparent" : "";
    return b2`
			<div class="thinking-block">
				<div
					class="thinking-header cursor-pointer select-none flex items-center gap-2 py-1 text-sm text-muted-foreground hover:text-foreground transition-colors"
					@click=${this.toggleExpanded}
				>
					<span class="transition-transform inline-block ${this.isExpanded ? "rotate-90" : ""}">${icon(ChevronRight, "sm")}</span>
					<span class="${shimmerClasses}">Thinking...</span>
				</div>
				${this.isExpanded ? b2`<markdown-block .content=${this.content} .isThinking=${true}></markdown-block>` : ""}
			</div>
		`;
  }
};
__decorate8([
  n6()
], ThinkingBlock.prototype, "content", void 0);
__decorate8([
  n6({ type: Boolean })
], ThinkingBlock.prototype, "isStreaming", void 0);
__decorate8([
  r7()
], ThinkingBlock.prototype, "isExpanded", void 0);
ThinkingBlock = __decorate8([
  t5("thinking-block")
], ThinkingBlock);

// ../pi-mono/packages/web-ui/dist/components/Messages.js
var __decorate9 = function(decorators, target, key, desc) {
  var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc);
  else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8;
  return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8;
};
var UserMessage = class UserMessage2 extends i4 {
  createRenderRoot() {
    return this;
  }
  connectedCallback() {
    super.connectedCallback();
    this.style.display = "block";
  }
  render() {
    const content = typeof this.message.content === "string" ? this.message.content : this.message.content.find((c6) => c6.type === "text")?.text || "";
    return b2`
			<div class="flex justify-start mx-4">
				<div class="user-message-container py-2 px-4 rounded-xl">
					<markdown-block .content=${content}></markdown-block>
					${this.message.role === "user-with-attachments" && this.message.attachments && this.message.attachments.length > 0 ? b2`
								<div class="mt-3 flex flex-wrap gap-2">
									${this.message.attachments.map((attachment) => b2` <attachment-tile .attachment=${attachment}></attachment-tile> `)}
								</div>
							` : ""}
				</div>
			</div>
		`;
  }
};
__decorate9([
  n6({ type: Object })
], UserMessage.prototype, "message", void 0);
UserMessage = __decorate9([
  t5("user-message")
], UserMessage);
var AssistantMessage = class AssistantMessage2 extends i4 {
  constructor() {
    super(...arguments);
    this.hideToolCalls = false;
    this.isStreaming = false;
    this.hidePendingToolCalls = false;
  }
  createRenderRoot() {
    return this;
  }
  connectedCallback() {
    super.connectedCallback();
    this.style.display = "block";
  }
  render() {
    const orderedParts = [];
    for (const chunk of this.message.content) {
      if (chunk.type === "text" && chunk.text.trim() !== "") {
        orderedParts.push(b2`<markdown-block .content=${chunk.text}></markdown-block>`);
      } else if (chunk.type === "thinking" && chunk.thinking.trim() !== "") {
        orderedParts.push(b2`<thinking-block .content=${chunk.thinking} .isStreaming=${this.isStreaming}></thinking-block>`);
      } else if (chunk.type === "toolCall") {
        if (!this.hideToolCalls) {
          const tool = this.tools?.find((t6) => t6.name === chunk.name);
          const pending = this.pendingToolCalls?.has(chunk.id) ?? false;
          const result = this.toolResultsById?.get(chunk.id);
          if (this.hidePendingToolCalls && pending && !result) {
            continue;
          }
          const aborted = this.message.stopReason === "aborted" && !result;
          orderedParts.push(b2`<tool-message
							.tool=${tool}
							.toolCall=${chunk}
							.result=${result}
							.pending=${pending}
							.aborted=${aborted}
							.isStreaming=${this.isStreaming}
						></tool-message>`);
        }
      }
    }
    return b2`
			<div>
				${orderedParts.length ? b2` <div class="px-4 flex flex-col gap-3">${orderedParts}</div> ` : ""}
				${this.message.usage && !this.isStreaming ? this.onCostClick ? b2` <div class="px-4 mt-2 text-xs text-muted-foreground cursor-pointer hover:text-foreground transition-colors" @click=${this.onCostClick}>${formatUsage(this.message.usage)}</div> ` : b2` <div class="px-4 mt-2 text-xs text-muted-foreground">${formatUsage(this.message.usage)}</div> ` : ""}
				${this.message.stopReason === "error" && this.message.errorMessage ? b2`
							<div class="mx-4 mt-3 p-3 bg-destructive/10 text-destructive rounded-lg text-sm overflow-hidden">
								<strong>${i18n("Error:")}</strong> ${this.message.errorMessage}
							</div>
						` : ""}
				${this.message.stopReason === "aborted" ? b2`<span class="text-sm text-destructive italic">${i18n("Request aborted")}</span>` : ""}
			</div>
		`;
  }
};
__decorate9([
  n6({ type: Object })
], AssistantMessage.prototype, "message", void 0);
__decorate9([
  n6({ type: Array })
], AssistantMessage.prototype, "tools", void 0);
__decorate9([
  n6({ type: Object })
], AssistantMessage.prototype, "pendingToolCalls", void 0);
__decorate9([
  n6({ type: Boolean })
], AssistantMessage.prototype, "hideToolCalls", void 0);
__decorate9([
  n6({ type: Object })
], AssistantMessage.prototype, "toolResultsById", void 0);
__decorate9([
  n6({ type: Boolean })
], AssistantMessage.prototype, "isStreaming", void 0);
__decorate9([
  n6({ type: Boolean })
], AssistantMessage.prototype, "hidePendingToolCalls", void 0);
__decorate9([
  n6({ attribute: false })
], AssistantMessage.prototype, "onCostClick", void 0);
AssistantMessage = __decorate9([
  t5("assistant-message")
], AssistantMessage);
var ToolMessageDebugView = class ToolMessageDebugView2 extends i4 {
  constructor() {
    super(...arguments);
    this.hasResult = false;
  }
  createRenderRoot() {
    return this;
  }
  connectedCallback() {
    super.connectedCallback();
    this.style.display = "block";
  }
  pretty(value) {
    try {
      if (typeof value === "string") {
        const maybeJson = JSON.parse(value);
        return { content: JSON.stringify(maybeJson, null, 2), isJson: true };
      }
      return { content: JSON.stringify(value, null, 2), isJson: true };
    } catch {
      return { content: typeof value === "string" ? value : String(value), isJson: false };
    }
  }
  render() {
    const textOutput = this.result?.content?.filter((c6) => c6.type === "text").map((c6) => c6.text).join("\n") || "";
    const output = this.pretty(textOutput);
    const details = this.pretty(this.result?.details);
    return b2`
			<div class="mt-3 flex flex-col gap-2">
				<div>
					<div class="text-xs font-medium mb-1 text-muted-foreground">${i18n("Call")}</div>
					<code-block .code=${this.pretty(this.callArgs).content} language="json"></code-block>
				</div>
				<div>
					<div class="text-xs font-medium mb-1 text-muted-foreground">${i18n("Result")}</div>
					${this.hasResult ? b2`<code-block .code=${output.content} language="${output.isJson ? "json" : "text"}"></code-block>
								<code-block .code=${details.content} language="${details.isJson ? "json" : "text"}"></code-block>` : b2`<div class="text-xs text-muted-foreground">${i18n("(no result)")}</div>`}
				</div>
			</div>
		`;
  }
};
__decorate9([
  n6({ type: Object })
], ToolMessageDebugView.prototype, "callArgs", void 0);
__decorate9([
  n6({ type: Object })
], ToolMessageDebugView.prototype, "result", void 0);
__decorate9([
  n6({ type: Boolean })
], ToolMessageDebugView.prototype, "hasResult", void 0);
ToolMessageDebugView = __decorate9([
  t5("tool-message-debug")
], ToolMessageDebugView);
var ToolMessage = class ToolMessage2 extends i4 {
  constructor() {
    super(...arguments);
    this.pending = false;
    this.aborted = false;
    this.isStreaming = false;
  }
  createRenderRoot() {
    return this;
  }
  connectedCallback() {
    super.connectedCallback();
    this.style.display = "block";
  }
  render() {
    const toolName = this.tool?.name || this.toolCall.name;
    const result = this.aborted ? {
      role: "toolResult",
      isError: true,
      content: [],
      toolCallId: this.toolCall.id,
      toolName: this.toolCall.name,
      timestamp: Date.now()
    } : this.result;
    const renderResult = renderTool(toolName, this.toolCall.arguments, result, !this.aborted && (this.isStreaming || this.pending));
    if (renderResult.isCustom) {
      return renderResult.content;
    }
    return b2`
			<div class="p-2.5 border border-border rounded-md bg-card text-card-foreground shadow-xs">
				${renderResult.content}
			</div>
		`;
  }
};
__decorate9([
  n6({ type: Object })
], ToolMessage.prototype, "toolCall", void 0);
__decorate9([
  n6({ type: Object })
], ToolMessage.prototype, "tool", void 0);
__decorate9([
  n6({ type: Object })
], ToolMessage.prototype, "result", void 0);
__decorate9([
  n6({ type: Boolean })
], ToolMessage.prototype, "pending", void 0);
__decorate9([
  n6({ type: Boolean })
], ToolMessage.prototype, "aborted", void 0);
__decorate9([
  n6({ type: Boolean })
], ToolMessage.prototype, "isStreaming", void 0);
ToolMessage = __decorate9([
  t5("tool-message")
], ToolMessage);
var AbortedMessage = class AbortedMessage2 extends i4 {
  createRenderRoot() {
    return this;
  }
  connectedCallback() {
    super.connectedCallback();
    this.style.display = "block";
  }
  render() {
    return b2`<span class="text-sm text-destructive italic">${i18n("Request aborted")}</span>`;
  }
};
AbortedMessage = __decorate9([
  t5("aborted-message")
], AbortedMessage);

// ../pi-mono/packages/web-ui/dist/components/StreamingMessageContainer.js
init_process_shim();
var __decorate10 = function(decorators, target, key, desc) {
  var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc);
  else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8;
  return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8;
};
var StreamingMessageContainer = class extends i4 {
  constructor() {
    super(...arguments);
    this.tools = [];
    this.isStreaming = false;
    this._message = null;
    this._pendingMessage = null;
    this._updateScheduled = false;
    this._immediateUpdate = false;
  }
  createRenderRoot() {
    return this;
  }
  connectedCallback() {
    super.connectedCallback();
    this.style.display = "block";
  }
  // Public method to update the message with batching for performance
  setMessage(message, immediate = false) {
    this._pendingMessage = message;
    if (immediate || message === null) {
      this._immediateUpdate = true;
      this._message = message;
      this.requestUpdate();
      this._pendingMessage = null;
      this._updateScheduled = false;
      return;
    }
    if (!this._updateScheduled) {
      this._updateScheduled = true;
      requestAnimationFrame(async () => {
        if (!this._immediateUpdate && this._pendingMessage !== null) {
          this._message = JSON.parse(JSON.stringify(this._pendingMessage));
          this.requestUpdate();
        }
        this._pendingMessage = null;
        this._updateScheduled = false;
        this._immediateUpdate = false;
      });
    }
  }
  render() {
    if (!this._message) {
      if (this.isStreaming)
        return b2`<div class="flex flex-col gap-3 mb-3">
					<span class="mx-4 inline-block w-2 h-4 bg-muted-foreground animate-pulse"></span>
				</div>`;
      return b2``;
    }
    const msg = this._message;
    if (msg.role === "toolResult") {
      return b2``;
    } else if (msg.role === "user" || msg.role === "user-with-attachments") {
      return b2``;
    } else if (msg.role === "assistant") {
      return b2`
				<div class="flex flex-col gap-3 mb-3">
					<assistant-message
						.message=${msg}
						.tools=${this.tools}
						.isStreaming=${this.isStreaming}
						.pendingToolCalls=${this.pendingToolCalls}
						.toolResultsById=${this.toolResultsById}
						.hideToolCalls=${false}
						.onCostClick=${this.onCostClick}
					></assistant-message>
					${this.isStreaming ? b2`<span class="mx-4 inline-block w-2 h-4 bg-muted-foreground animate-pulse"></span>` : ""}
				</div>
			`;
    }
  }
};
__decorate10([
  n6({ type: Array })
], StreamingMessageContainer.prototype, "tools", void 0);
__decorate10([
  n6({ type: Boolean })
], StreamingMessageContainer.prototype, "isStreaming", void 0);
__decorate10([
  n6({ type: Object })
], StreamingMessageContainer.prototype, "pendingToolCalls", void 0);
__decorate10([
  n6({ type: Object })
], StreamingMessageContainer.prototype, "toolResultsById", void 0);
__decorate10([
  n6({ attribute: false })
], StreamingMessageContainer.prototype, "onCostClick", void 0);
__decorate10([
  r7()
], StreamingMessageContainer.prototype, "_message", void 0);
if (!customElements.get("streaming-message-container")) {
  customElements.define("streaming-message-container", StreamingMessageContainer);
}

// ../pi-mono/packages/web-ui/dist/components/AgentInterface.js
var __decorate11 = function(decorators, target, key, desc) {
  var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc);
  else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8;
  return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8;
};
var AgentInterface = class AgentInterface2 extends i4 {
  constructor() {
    super(...arguments);
    this.enableAttachments = true;
    this.enableModelSelector = true;
    this.enableThinkingSelector = true;
    this.showThemeToggle = false;
    this._autoScroll = true;
    this._lastScrollTop = 0;
    this._lastClientHeight = 0;
    this._handleScroll = (_ev) => {
      if (!this._scrollContainer)
        return;
      const currentScrollTop = this._scrollContainer.scrollTop;
      const scrollHeight = this._scrollContainer.scrollHeight;
      const clientHeight = this._scrollContainer.clientHeight;
      const distanceFromBottom = scrollHeight - currentScrollTop - clientHeight;
      if (clientHeight < this._lastClientHeight) {
        this._lastClientHeight = clientHeight;
        return;
      }
      if (currentScrollTop !== 0 && currentScrollTop < this._lastScrollTop && distanceFromBottom > 50) {
        this._autoScroll = false;
      } else if (distanceFromBottom < 10) {
        this._autoScroll = true;
      }
      this._lastScrollTop = currentScrollTop;
      this._lastClientHeight = clientHeight;
    };
  }
  setInput(text3, attachments) {
    const update = () => {
      if (!this._messageEditor)
        requestAnimationFrame(update);
      else {
        this._messageEditor.value = text3;
        this._messageEditor.attachments = attachments || [];
      }
    };
    update();
  }
  setAutoScroll(enabled) {
    this._autoScroll = enabled;
  }
  createRenderRoot() {
    return this;
  }
  willUpdate(changedProperties) {
    super.willUpdate(changedProperties);
    if (changedProperties.has("session")) {
      this.setupSessionSubscription();
    }
  }
  async connectedCallback() {
    super.connectedCallback();
    this.style.display = "flex";
    this.style.flexDirection = "column";
    this.style.height = "100%";
    this.style.minHeight = "0";
    await this.updateComplete;
    this._scrollContainer = this.querySelector(".overflow-y-auto");
    if (this._scrollContainer) {
      this._resizeObserver = new ResizeObserver(() => {
        if (this._autoScroll && this._scrollContainer) {
          this._scrollContainer.scrollTop = this._scrollContainer.scrollHeight;
        }
      });
      const contentContainer = this._scrollContainer.querySelector(".max-w-3xl");
      if (contentContainer) {
        this._resizeObserver.observe(contentContainer);
      }
      this._scrollContainer.addEventListener("scroll", this._handleScroll);
    }
    this.setupSessionSubscription();
  }
  disconnectedCallback() {
    super.disconnectedCallback();
    if (this._resizeObserver) {
      this._resizeObserver.disconnect();
      this._resizeObserver = void 0;
    }
    if (this._scrollContainer) {
      this._scrollContainer.removeEventListener("scroll", this._handleScroll);
    }
    if (this._unsubscribeSession) {
      this._unsubscribeSession();
      this._unsubscribeSession = void 0;
    }
  }
  setupSessionSubscription() {
    if (this._unsubscribeSession) {
      this._unsubscribeSession();
      this._unsubscribeSession = void 0;
    }
    if (!this.session)
      return;
    if (this.session.streamFn === streamSimple) {
      this.session.streamFn = createStreamFn(async () => {
        const enabled = await getAppStorage().settings.get("proxy.enabled");
        return enabled ? await getAppStorage().settings.get("proxy.url") || void 0 : void 0;
      });
    }
    if (!this.session.getApiKey) {
      this.session.getApiKey = async (provider) => {
        const key = await getAppStorage().providerKeys.get(provider);
        return key ?? void 0;
      };
    }
    this._unsubscribeSession = this.session.subscribe(async (ev) => {
      switch (ev.type) {
        case "message_start":
        case "turn_start":
        case "turn_end":
        case "agent_start":
          this.requestUpdate();
          break;
        case "message_end":
          if (this._streamingContainer) {
            this._streamingContainer.setMessage(null, true);
          }
          this.requestUpdate();
          break;
        case "agent_end":
          if (this._streamingContainer) {
            this._streamingContainer.isStreaming = false;
            this._streamingContainer.setMessage(null, true);
          }
          this.requestUpdate();
          break;
        case "message_update":
          if (this._streamingContainer) {
            const isStreaming = this.session?.state.isStreaming || false;
            this._streamingContainer.isStreaming = isStreaming;
            this._streamingContainer.setMessage(ev.message, !isStreaming);
          }
          this.requestUpdate();
          break;
      }
    });
  }
  async sendMessage(input, attachments) {
    if (!input.trim() && attachments?.length === 0 || this.session?.state.isStreaming)
      return;
    const session = this.session;
    if (!session)
      throw new Error("No session set on AgentInterface");
    if (!session.state.model)
      throw new Error("No model set on AgentInterface");
    const provider = session.state.model.provider;
    const apiKey = await getAppStorage().providerKeys.get(provider);
    if (!apiKey) {
      if (!this.onApiKeyRequired) {
        console.error("No API key configured and no onApiKeyRequired handler set");
        return;
      }
      const success = await this.onApiKeyRequired(provider);
      if (!success) {
        return;
      }
    }
    if (this.onBeforeSend) {
      await this.onBeforeSend();
    }
    this._messageEditor.value = "";
    this._messageEditor.attachments = [];
    this._autoScroll = true;
    if (attachments && attachments.length > 0) {
      const message = {
        role: "user-with-attachments",
        content: input,
        attachments,
        timestamp: Date.now()
      };
      await this.session?.prompt(message);
    } else {
      await this.session?.prompt(input);
    }
  }
  renderMessages() {
    if (!this.session)
      return b2`<div class="p-4 text-center text-muted-foreground">${i18n("No session available")}</div>`;
    const state = this.session.state;
    const toolResultsById = /* @__PURE__ */ new Map();
    for (const message of state.messages) {
      if (message.role === "toolResult") {
        toolResultsById.set(message.toolCallId, message);
      }
    }
    return b2`
			<div class="flex flex-col gap-3">
				<!-- Stable messages list - won't re-render during streaming -->
				<message-list
					.messages=${this.session.state.messages}
					.tools=${state.tools}
					.pendingToolCalls=${this.session ? this.session.state.pendingToolCalls : /* @__PURE__ */ new Set()}
					.isStreaming=${state.isStreaming}
					.onCostClick=${this.onCostClick}
				></message-list>

				<!-- Streaming message container - manages its own updates -->
				<streaming-message-container
					class="${state.isStreaming ? "" : "hidden"}"
					.tools=${state.tools}
					.isStreaming=${state.isStreaming}
					.pendingToolCalls=${state.pendingToolCalls}
					.toolResultsById=${toolResultsById}
					.onCostClick=${this.onCostClick}
				></streaming-message-container>
			</div>
		`;
  }
  renderStats() {
    if (!this.session)
      return b2`<div class="text-xs h-5"></div>`;
    const state = this.session.state;
    const totals = state.messages.filter((m4) => m4.role === "assistant").reduce((acc, msg) => {
      const usage = msg.usage;
      if (usage) {
        acc.input += usage.input;
        acc.output += usage.output;
        acc.cacheRead += usage.cacheRead;
        acc.cacheWrite += usage.cacheWrite;
        acc.cost.total += usage.cost.total;
      }
      return acc;
    }, {
      input: 0,
      output: 0,
      cacheRead: 0,
      cacheWrite: 0,
      totalTokens: 0,
      cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
    });
    const hasTotals = totals.input || totals.output || totals.cacheRead || totals.cacheWrite;
    const totalsText = hasTotals ? formatUsage(totals) : "";
    return b2`
			<div class="text-xs text-muted-foreground flex justify-between items-center h-5">
				<div class="flex items-center gap-1">
					${this.showThemeToggle ? b2`<theme-toggle></theme-toggle>` : b2``}
				</div>
				<div class="flex ml-auto items-center gap-3">
					${totalsText ? this.onCostClick ? b2`<span class="cursor-pointer hover:text-foreground transition-colors" @click=${this.onCostClick}>${totalsText}</span>` : b2`<span>${totalsText}</span>` : ""}
				</div>
			</div>
		`;
  }
  render() {
    if (!this.session)
      return b2`<div class="p-4 text-center text-muted-foreground">${i18n("No session set")}</div>`;
    const session = this.session;
    const state = this.session.state;
    return b2`
			<div class="flex flex-col h-full bg-background text-foreground">
				<!-- Messages Area -->
				<div class="flex-1 overflow-y-auto">
					<div class="max-w-3xl mx-auto p-4 pb-0">${this.renderMessages()}</div>
				</div>

				<!-- Input Area -->
				<div class="shrink-0">
					<div class="max-w-3xl mx-auto px-2">
						<message-editor
							.isStreaming=${state.isStreaming}
							.currentModel=${state.model}
							.thinkingLevel=${state.thinkingLevel}
							.showAttachmentButton=${this.enableAttachments}
							.showModelSelector=${this.enableModelSelector}
							.showThinkingSelector=${this.enableThinkingSelector}
							.onSend=${(input, attachments) => {
      this.sendMessage(input, attachments);
    }}
							.onAbort=${() => session.abort()}
							.onModelSelect=${() => {
      if (this.onModelSelect) {
        this.onModelSelect();
      } else {
        ModelSelector.open(state.model, (model) => session.setModel(model));
      }
    }}
							.onThinkingChange=${this.enableThinkingSelector ? (level) => {
      session.setThinkingLevel(level);
    } : void 0}
						></message-editor>
						${this.renderStats()}
					</div>
				</div>
			</div>
		`;
  }
};
__decorate11([
  n6({ attribute: false })
], AgentInterface.prototype, "session", void 0);
__decorate11([
  n6({ type: Boolean })
], AgentInterface.prototype, "enableAttachments", void 0);
__decorate11([
  n6({ type: Boolean })
], AgentInterface.prototype, "enableModelSelector", void 0);
__decorate11([
  n6({ type: Boolean })
], AgentInterface.prototype, "enableThinkingSelector", void 0);
__decorate11([
  n6({ type: Boolean })
], AgentInterface.prototype, "showThemeToggle", void 0);
__decorate11([
  n6({ attribute: false })
], AgentInterface.prototype, "onApiKeyRequired", void 0);
__decorate11([
  n6({ attribute: false })
], AgentInterface.prototype, "onBeforeSend", void 0);
__decorate11([
  n6({ attribute: false })
], AgentInterface.prototype, "onBeforeToolCall", void 0);
__decorate11([
  n6({ attribute: false })
], AgentInterface.prototype, "onCostClick", void 0);
__decorate11([
  n6({ attribute: false })
], AgentInterface.prototype, "onModelSelect", void 0);
__decorate11([
  e8("message-editor")
], AgentInterface.prototype, "_messageEditor", void 0);
__decorate11([
  e8("streaming-message-container")
], AgentInterface.prototype, "_streamingContainer", void 0);
AgentInterface = __decorate11([
  t5("agent-interface")
], AgentInterface);
if (!customElements.get("agent-interface")) {
  customElements.define("agent-interface", AgentInterface);
}

// ../pi-mono/packages/web-ui/dist/components/sandbox/ArtifactsRuntimeProvider.js
init_process_shim();
var ArtifactsRuntimeProvider = class {
  constructor(artifactsPanel, agent, readWrite = true) {
    this.artifactsPanel = artifactsPanel;
    this.agent = agent;
    this.readWrite = readWrite;
  }
  getData() {
    const snapshot = {};
    this.artifactsPanel.artifacts.forEach((artifact, filename) => {
      snapshot[filename] = artifact.content;
    });
    return { artifacts: snapshot };
  }
  getRuntime() {
    return (_sandboxId) => {
      const isJsonFile = (filename) => filename.endsWith(".json");
      window.listArtifacts = async () => {
        if (window.sendRuntimeMessage) {
          const response = await window.sendRuntimeMessage({
            type: "artifact-operation",
            action: "list"
          });
          if (!response.success)
            throw new Error(response.error);
          return response.result;
        } else {
          return Object.keys(window.artifacts || {});
        }
      };
      window.getArtifact = async (filename) => {
        let content;
        if (window.sendRuntimeMessage) {
          const response = await window.sendRuntimeMessage({
            type: "artifact-operation",
            action: "get",
            filename
          });
          if (!response.success)
            throw new Error(response.error);
          content = response.result;
        } else {
          if (!window.artifacts?.[filename]) {
            throw new Error(`Artifact not found (offline mode): ${filename}`);
          }
          content = window.artifacts[filename];
        }
        if (isJsonFile(filename)) {
          try {
            return JSON.parse(content);
          } catch (e9) {
            throw new Error(`Failed to parse JSON from ${filename}: ${e9}`);
          }
        }
        return content;
      };
      window.createOrUpdateArtifact = async (filename, content, mimeType) => {
        if (!window.sendRuntimeMessage) {
          throw new Error("Cannot create/update artifacts in offline mode (read-only)");
        }
        let finalContent = content;
        if (isJsonFile(filename) && typeof content !== "string") {
          finalContent = JSON.stringify(content, null, 2);
        } else if (typeof content !== "string") {
          finalContent = JSON.stringify(content, null, 2);
        }
        const response = await window.sendRuntimeMessage({
          type: "artifact-operation",
          action: "createOrUpdate",
          filename,
          content: finalContent,
          mimeType
        });
        if (!response.success)
          throw new Error(response.error);
      };
      window.deleteArtifact = async (filename) => {
        if (!window.sendRuntimeMessage) {
          throw new Error("Cannot delete artifacts in offline mode (read-only)");
        }
        const response = await window.sendRuntimeMessage({
          type: "artifact-operation",
          action: "delete",
          filename
        });
        if (!response.success)
          throw new Error(response.error);
      };
    };
  }
  async handleMessage(message, respond) {
    if (message.type !== "artifact-operation") {
      return;
    }
    const { action, filename, content } = message;
    try {
      switch (action) {
        case "list": {
          const filenames = Array.from(this.artifactsPanel.artifacts.keys());
          respond({ success: true, result: filenames });
          break;
        }
        case "get": {
          const artifact = this.artifactsPanel.artifacts.get(filename);
          if (!artifact) {
            respond({ success: false, error: `Artifact not found: ${filename}` });
          } else {
            respond({ success: true, result: artifact.content });
          }
          break;
        }
        case "createOrUpdate": {
          try {
            const exists = this.artifactsPanel.artifacts.has(filename);
            const command = exists ? "rewrite" : "create";
            const action2 = exists ? "update" : "create";
            await this.artifactsPanel.tool.execute("", {
              command,
              filename,
              content
            });
            this.agent?.appendMessage({
              role: "artifact",
              action: action2,
              filename,
              content,
              ...action2 === "create" && { title: filename },
              timestamp: (/* @__PURE__ */ new Date()).toISOString()
            });
            respond({ success: true });
          } catch (err) {
            respond({ success: false, error: err.message });
          }
          break;
        }
        case "delete": {
          try {
            await this.artifactsPanel.tool.execute("", {
              command: "delete",
              filename
            });
            this.agent?.appendMessage({
              role: "artifact",
              action: "delete",
              filename,
              timestamp: (/* @__PURE__ */ new Date()).toISOString()
            });
            respond({ success: true });
          } catch (err) {
            respond({ success: false, error: err.message });
          }
          break;
        }
        default:
          respond({ success: false, error: `Unknown artifact action: ${action}` });
      }
    } catch (error) {
      respond({ success: false, error: error.message });
    }
  }
  getDescription() {
    return this.readWrite ? ARTIFACTS_RUNTIME_PROVIDER_DESCRIPTION_RW : ARTIFACTS_RUNTIME_PROVIDER_DESCRIPTION_RO;
  }
};

// ../pi-mono/packages/web-ui/dist/components/sandbox/AttachmentsRuntimeProvider.js
init_process_shim();
var AttachmentsRuntimeProvider = class {
  constructor(attachments) {
    this.attachments = attachments;
  }
  getData() {
    const attachmentsData = this.attachments.map((a3) => ({
      id: a3.id,
      fileName: a3.fileName,
      mimeType: a3.mimeType,
      size: a3.size,
      content: a3.content,
      extractedText: a3.extractedText
    }));
    return { attachments: attachmentsData };
  }
  getRuntime() {
    return (_sandboxId) => {
      window.listAttachments = () => (window.attachments || []).map((a3) => ({
        id: a3.id,
        fileName: a3.fileName,
        mimeType: a3.mimeType,
        size: a3.size
      }));
      window.readTextAttachment = (attachmentId) => {
        const a3 = (window.attachments || []).find((x2) => x2.id === attachmentId);
        if (!a3)
          throw new Error(`Attachment not found: ${attachmentId}`);
        if (a3.extractedText)
          return a3.extractedText;
        try {
          return atob(a3.content);
        } catch {
          throw new Error(`Failed to decode text content for: ${attachmentId}`);
        }
      };
      window.readBinaryAttachment = (attachmentId) => {
        const a3 = (window.attachments || []).find((x2) => x2.id === attachmentId);
        if (!a3)
          throw new Error(`Attachment not found: ${attachmentId}`);
        const bin2 = atob(a3.content);
        const bytes = new Uint8Array(bin2.length);
        for (let i7 = 0; i7 < bin2.length; i7++)
          bytes[i7] = bin2.charCodeAt(i7);
        return bytes;
      };
    };
  }
  getDescription() {
    return ATTACHMENTS_RUNTIME_DESCRIPTION;
  }
};

// ../pi-mono/packages/web-ui/dist/tools/artifacts/index.js
init_process_shim();

// ../pi-mono/packages/web-ui/dist/tools/artifacts/ArtifactElement.js
init_process_shim();
var ArtifactElement = class extends i4 {
  constructor() {
    super(...arguments);
    this.filename = "";
  }
  createRenderRoot() {
    return this;
  }
};

// ../pi-mono/packages/web-ui/dist/tools/artifacts/artifacts.js
init_process_shim();

// ../mini-lit/dist/MarkdownBlock.js
init_process_shim();

// ../mini-lit/node_modules/katex/dist/katex.mjs
init_process_shim();
var SourceLocation = class _SourceLocation {
  // The + prefix indicates that these fields aren't writeable
  // Lexer holding the input string.
  // Start offset, zero-based inclusive.
  // End offset, zero-based exclusive.
  constructor(lexer, start, end) {
    this.lexer = void 0;
    this.start = void 0;
    this.end = void 0;
    this.lexer = lexer;
    this.start = start;
    this.end = end;
  }
  /**
   * Merges two `SourceLocation`s from location providers, given they are
   * provided in order of appearance.
   * - Returns the first one's location if only the first is provided.
   * - Returns a merged range of the first and the last if both are provided
   *   and their lexers match.
   * - Otherwise, returns null.
   */
  static range(first, second) {
    if (!second) {
      return first && first.loc;
    } else if (!first || !first.loc || !second.loc || first.loc.lexer !== second.loc.lexer) {
      return null;
    } else {
      return new _SourceLocation(first.loc.lexer, first.loc.start, second.loc.end);
    }
  }
};
var Token = class _Token {
  // don't expand the token
  // used in \noexpand
  constructor(text3, loc) {
    this.text = void 0;
    this.loc = void 0;
    this.noexpand = void 0;
    this.treatAsRelax = void 0;
    this.text = text3;
    this.loc = loc;
  }
  /**
   * Given a pair of tokens (this and endToken), compute a `Token` encompassing
   * the whole input range enclosed by these two.
   */
  range(endToken, text3) {
    return new _Token(text3, SourceLocation.range(this, endToken));
  }
};
var ParseError = class _ParseError {
  // Error start position based on passed-in Token or ParseNode.
  // Length of affected text based on passed-in Token or ParseNode.
  // The underlying error message without any context added.
  constructor(message, token) {
    this.name = void 0;
    this.position = void 0;
    this.length = void 0;
    this.rawMessage = void 0;
    var error = "KaTeX parse error: " + message;
    var start;
    var end;
    var loc = token && token.loc;
    if (loc && loc.start <= loc.end) {
      var input = loc.lexer.input;
      start = loc.start;
      end = loc.end;
      if (start === input.length) {
        error += " at end of input: ";
      } else {
        error += " at position " + (start + 1) + ": ";
      }
      var underlined = input.slice(start, end).replace(/[^]/g, "$&\u0332");
      var left;
      if (start > 15) {
        left = "\u2026" + input.slice(start - 15, start);
      } else {
        left = input.slice(0, start);
      }
      var right;
      if (end + 15 < input.length) {
        right = input.slice(end, end + 15) + "\u2026";
      } else {
        right = input.slice(end);
      }
      error += left + underlined + right;
    }
    var self2 = new Error(error);
    self2.name = "ParseError";
    self2.__proto__ = _ParseError.prototype;
    self2.position = start;
    if (start != null && end != null) {
      self2.length = end - start;
    }
    self2.rawMessage = message;
    return self2;
  }
};
ParseError.prototype.__proto__ = Error.prototype;
var contains = function contains2(list, elem) {
  return list.indexOf(elem) !== -1;
};
var deflt = function deflt2(setting, defaultIfUndefined) {
  return setting === void 0 ? defaultIfUndefined : setting;
};
var uppercase = /([A-Z])/g;
var hyphenate = function hyphenate2(str2) {
  return str2.replace(uppercase, "-$1").toLowerCase();
};
var ESCAPE_LOOKUP = {
  "&": "&amp;",
  ">": "&gt;",
  "<": "&lt;",
  '"': "&quot;",
  "'": "&#x27;"
};
var ESCAPE_REGEX = /[&><"']/g;
function escape2(text3) {
  return String(text3).replace(ESCAPE_REGEX, (match2) => ESCAPE_LOOKUP[match2]);
}
var getBaseElem = function getBaseElem2(group) {
  if (group.type === "ordgroup") {
    if (group.body.length === 1) {
      return getBaseElem2(group.body[0]);
    } else {
      return group;
    }
  } else if (group.type === "color") {
    if (group.body.length === 1) {
      return getBaseElem2(group.body[0]);
    } else {
      return group;
    }
  } else if (group.type === "font") {
    return getBaseElem2(group.body);
  } else {
    return group;
  }
};
var isCharacterBox = function isCharacterBox2(group) {
  var baseElem = getBaseElem(group);
  return baseElem.type === "mathord" || baseElem.type === "textord" || baseElem.type === "atom";
};
var assert2 = function assert3(value) {
  if (!value) {
    throw new Error("Expected non-null, but got " + String(value));
  }
  return value;
};
var protocolFromUrl = function protocolFromUrl2(url) {
  var protocol = /^[\x00-\x20]*([^\\/#?]*?)(:|&#0*58|&#x0*3a|&colon)/i.exec(url);
  if (!protocol) {
    return "_relative";
  }
  if (protocol[2] !== ":") {
    return null;
  }
  if (!/^[a-zA-Z][a-zA-Z0-9+\-.]*$/.test(protocol[1])) {
    return null;
  }
  return protocol[1].toLowerCase();
};
var utils2 = {
  contains,
  deflt,
  escape: escape2,
  hyphenate,
  getBaseElem,
  isCharacterBox,
  protocolFromUrl
};
var SETTINGS_SCHEMA = {
  displayMode: {
    type: "boolean",
    description: "Render math in display mode, which puts the math in display style (so \\int and \\sum are large, for example), and centers the math on the page on its own line.",
    cli: "-d, --display-mode"
  },
  output: {
    type: {
      enum: ["htmlAndMathml", "html", "mathml"]
    },
    description: "Determines the markup language of the output.",
    cli: "-F, --format <type>"
  },
  leqno: {
    type: "boolean",
    description: "Render display math in leqno style (left-justified tags)."
  },
  fleqn: {
    type: "boolean",
    description: "Render display math flush left."
  },
  throwOnError: {
    type: "boolean",
    default: true,
    cli: "-t, --no-throw-on-error",
    cliDescription: "Render errors (in the color given by --error-color) instead of throwing a ParseError exception when encountering an error."
  },
  errorColor: {
    type: "string",
    default: "#cc0000",
    cli: "-c, --error-color <color>",
    cliDescription: "A color string given in the format 'rgb' or 'rrggbb' (no #). This option determines the color of errors rendered by the -t option.",
    cliProcessor: (color) => "#" + color
  },
  macros: {
    type: "object",
    cli: "-m, --macro <def>",
    cliDescription: "Define custom macro of the form '\\foo:expansion' (use multiple -m arguments for multiple macros).",
    cliDefault: [],
    cliProcessor: (def, defs) => {
      defs.push(def);
      return defs;
    }
  },
  minRuleThickness: {
    type: "number",
    description: "Specifies a minimum thickness, in ems, for fraction lines, `\\sqrt` top lines, `{array}` vertical lines, `\\hline`, `\\hdashline`, `\\underline`, `\\overline`, and the borders of `\\fbox`, `\\boxed`, and `\\fcolorbox`.",
    processor: (t6) => Math.max(0, t6),
    cli: "--min-rule-thickness <size>",
    cliProcessor: parseFloat
  },
  colorIsTextColor: {
    type: "boolean",
    description: "Makes \\color behave like LaTeX's 2-argument \\textcolor, instead of LaTeX's one-argument \\color mode change.",
    cli: "-b, --color-is-text-color"
  },
  strict: {
    type: [{
      enum: ["warn", "ignore", "error"]
    }, "boolean", "function"],
    description: "Turn on strict / LaTeX faithfulness mode, which throws an error if the input uses features that are not supported by LaTeX.",
    cli: "-S, --strict",
    cliDefault: false
  },
  trust: {
    type: ["boolean", "function"],
    description: "Trust the input, enabling all HTML features such as \\url.",
    cli: "-T, --trust"
  },
  maxSize: {
    type: "number",
    default: Infinity,
    description: "If non-zero, all user-specified sizes, e.g. in \\rule{500em}{500em}, will be capped to maxSize ems. Otherwise, elements and spaces can be arbitrarily large",
    processor: (s6) => Math.max(0, s6),
    cli: "-s, --max-size <n>",
    cliProcessor: parseInt
  },
  maxExpand: {
    type: "number",
    default: 1e3,
    description: "Limit the number of macro expansions to the specified number, to prevent e.g. infinite macro loops. If set to Infinity, the macro expander will try to fully expand as in LaTeX.",
    processor: (n7) => Math.max(0, n7),
    cli: "-e, --max-expand <n>",
    cliProcessor: (n7) => n7 === "Infinity" ? Infinity : parseInt(n7)
  },
  globalGroup: {
    type: "boolean",
    cli: false
  }
};
function getDefaultValue(schema) {
  if (schema.default) {
    return schema.default;
  }
  var type = schema.type;
  var defaultType = Array.isArray(type) ? type[0] : type;
  if (typeof defaultType !== "string") {
    return defaultType.enum[0];
  }
  switch (defaultType) {
    case "boolean":
      return false;
    case "string":
      return "";
    case "number":
      return 0;
    case "object":
      return {};
  }
}
var Settings = class {
  constructor(options) {
    this.displayMode = void 0;
    this.output = void 0;
    this.leqno = void 0;
    this.fleqn = void 0;
    this.throwOnError = void 0;
    this.errorColor = void 0;
    this.macros = void 0;
    this.minRuleThickness = void 0;
    this.colorIsTextColor = void 0;
    this.strict = void 0;
    this.trust = void 0;
    this.maxSize = void 0;
    this.maxExpand = void 0;
    this.globalGroup = void 0;
    options = options || {};
    for (var prop in SETTINGS_SCHEMA) {
      if (SETTINGS_SCHEMA.hasOwnProperty(prop)) {
        var schema = SETTINGS_SCHEMA[prop];
        this[prop] = options[prop] !== void 0 ? schema.processor ? schema.processor(options[prop]) : options[prop] : getDefaultValue(schema);
      }
    }
  }
  /**
   * Report nonstrict (non-LaTeX-compatible) input.
   * Can safely not be called if `this.strict` is false in JavaScript.
   */
  reportNonstrict(errorCode, errorMsg, token) {
    var strict = this.strict;
    if (typeof strict === "function") {
      strict = strict(errorCode, errorMsg, token);
    }
    if (!strict || strict === "ignore") {
      return;
    } else if (strict === true || strict === "error") {
      throw new ParseError("LaTeX-incompatible input and strict mode is set to 'error': " + (errorMsg + " [" + errorCode + "]"), token);
    } else if (strict === "warn") {
      typeof console !== "undefined" && console.warn("LaTeX-incompatible input and strict mode is set to 'warn': " + (errorMsg + " [" + errorCode + "]"));
    } else {
      typeof console !== "undefined" && console.warn("LaTeX-incompatible input and strict mode is set to " + ("unrecognized '" + strict + "': " + errorMsg + " [" + errorCode + "]"));
    }
  }
  /**
   * Check whether to apply strict (LaTeX-adhering) behavior for unusual
   * input (like `\\`).  Unlike `nonstrict`, will not throw an error;
   * instead, "error" translates to a return value of `true`, while "ignore"
   * translates to a return value of `false`.  May still print a warning:
   * "warn" prints a warning and returns `false`.
   * This is for the second category of `errorCode`s listed in the README.
   */
  useStrictBehavior(errorCode, errorMsg, token) {
    var strict = this.strict;
    if (typeof strict === "function") {
      try {
        strict = strict(errorCode, errorMsg, token);
      } catch (error) {
        strict = "error";
      }
    }
    if (!strict || strict === "ignore") {
      return false;
    } else if (strict === true || strict === "error") {
      return true;
    } else if (strict === "warn") {
      typeof console !== "undefined" && console.warn("LaTeX-incompatible input and strict mode is set to 'warn': " + (errorMsg + " [" + errorCode + "]"));
      return false;
    } else {
      typeof console !== "undefined" && console.warn("LaTeX-incompatible input and strict mode is set to " + ("unrecognized '" + strict + "': " + errorMsg + " [" + errorCode + "]"));
      return false;
    }
  }
  /**
   * Check whether to test potentially dangerous input, and return
   * `true` (trusted) or `false` (untrusted).  The sole argument `context`
   * should be an object with `command` field specifying the relevant LaTeX
   * command (as a string starting with `\`), and any other arguments, etc.
   * If `context` has a `url` field, a `protocol` field will automatically
   * get added by this function (changing the specified object).
   */
  isTrusted(context) {
    if (context.url && !context.protocol) {
      var protocol = utils2.protocolFromUrl(context.url);
      if (protocol == null) {
        return false;
      }
      context.protocol = protocol;
    }
    var trust = typeof this.trust === "function" ? this.trust(context) : this.trust;
    return Boolean(trust);
  }
};
var Style = class {
  constructor(id, size, cramped) {
    this.id = void 0;
    this.size = void 0;
    this.cramped = void 0;
    this.id = id;
    this.size = size;
    this.cramped = cramped;
  }
  /**
   * Get the style of a superscript given a base in the current style.
   */
  sup() {
    return styles[sup[this.id]];
  }
  /**
   * Get the style of a subscript given a base in the current style.
   */
  sub() {
    return styles[sub[this.id]];
  }
  /**
   * Get the style of a fraction numerator given the fraction in the current
   * style.
   */
  fracNum() {
    return styles[fracNum[this.id]];
  }
  /**
   * Get the style of a fraction denominator given the fraction in the current
   * style.
   */
  fracDen() {
    return styles[fracDen[this.id]];
  }
  /**
   * Get the cramped version of a style (in particular, cramping a cramped style
   * doesn't change the style).
   */
  cramp() {
    return styles[cramp[this.id]];
  }
  /**
   * Get a text or display version of this style.
   */
  text() {
    return styles[text$1[this.id]];
  }
  /**
   * Return true if this style is tightly spaced (scriptstyle/scriptscriptstyle)
   */
  isTight() {
    return this.size >= 2;
  }
};
var D2 = 0;
var Dc = 1;
var T2 = 2;
var Tc = 3;
var S3 = 4;
var Sc = 5;
var SS = 6;
var SSc = 7;
var styles = [new Style(D2, 0, false), new Style(Dc, 0, true), new Style(T2, 1, false), new Style(Tc, 1, true), new Style(S3, 2, false), new Style(Sc, 2, true), new Style(SS, 3, false), new Style(SSc, 3, true)];
var sup = [S3, Sc, S3, Sc, SS, SSc, SS, SSc];
var sub = [Sc, Sc, Sc, Sc, SSc, SSc, SSc, SSc];
var fracNum = [T2, Tc, S3, Sc, SS, SSc, SS, SSc];
var fracDen = [Tc, Tc, Sc, Sc, SSc, SSc, SSc, SSc];
var cramp = [Dc, Dc, Tc, Tc, Sc, Sc, SSc, SSc];
var text$1 = [D2, Dc, T2, Tc, T2, Tc, T2, Tc];
var Style$1 = {
  DISPLAY: styles[D2],
  TEXT: styles[T2],
  SCRIPT: styles[S3],
  SCRIPTSCRIPT: styles[SS]
};
var scriptData = [{
  // Latin characters beyond the Latin-1 characters we have metrics for.
  // Needed for Czech, Hungarian and Turkish text, for example.
  name: "latin",
  blocks: [
    [256, 591],
    // Latin Extended-A and Latin Extended-B
    [768, 879]
    // Combining Diacritical marks
  ]
}, {
  // The Cyrillic script used by Russian and related languages.
  // A Cyrillic subset used to be supported as explicitly defined
  // symbols in symbols.js
  name: "cyrillic",
  blocks: [[1024, 1279]]
}, {
  // Armenian
  name: "armenian",
  blocks: [[1328, 1423]]
}, {
  // The Brahmic scripts of South and Southeast Asia
  // Devanagari (0900–097F)
  // Bengali (0980–09FF)
  // Gurmukhi (0A00–0A7F)
  // Gujarati (0A80–0AFF)
  // Oriya (0B00–0B7F)
  // Tamil (0B80–0BFF)
  // Telugu (0C00–0C7F)
  // Kannada (0C80–0CFF)
  // Malayalam (0D00–0D7F)
  // Sinhala (0D80–0DFF)
  // Thai (0E00–0E7F)
  // Lao (0E80–0EFF)
  // Tibetan (0F00–0FFF)
  // Myanmar (1000–109F)
  name: "brahmic",
  blocks: [[2304, 4255]]
}, {
  name: "georgian",
  blocks: [[4256, 4351]]
}, {
  // Chinese and Japanese.
  // The "k" in cjk is for Korean, but we've separated Korean out
  name: "cjk",
  blocks: [
    [12288, 12543],
    // CJK symbols and punctuation, Hiragana, Katakana
    [19968, 40879],
    // CJK ideograms
    [65280, 65376]
    // Fullwidth punctuation
    // TODO: add halfwidth Katakana and Romanji glyphs
  ]
}, {
  // Korean
  name: "hangul",
  blocks: [[44032, 55215]]
}];
function scriptFromCodepoint(codepoint) {
  for (var i7 = 0; i7 < scriptData.length; i7++) {
    var script = scriptData[i7];
    for (var _i = 0; _i < script.blocks.length; _i++) {
      var block = script.blocks[_i];
      if (codepoint >= block[0] && codepoint <= block[1]) {
        return script.name;
      }
    }
  }
  return null;
}
var allBlocks = [];
scriptData.forEach((s6) => s6.blocks.forEach((b4) => allBlocks.push(...b4)));
function supportedCodepoint(codepoint) {
  for (var i7 = 0; i7 < allBlocks.length; i7 += 2) {
    if (codepoint >= allBlocks[i7] && codepoint <= allBlocks[i7 + 1]) {
      return true;
    }
  }
  return false;
}
var hLinePad = 80;
var sqrtMain = function sqrtMain2(extraVinculum, hLinePad2) {
  return "M95," + (622 + extraVinculum + hLinePad2) + "\nc-2.7,0,-7.17,-2.7,-13.5,-8c-5.8,-5.3,-9.5,-10,-9.5,-14\nc0,-2,0.3,-3.3,1,-4c1.3,-2.7,23.83,-20.7,67.5,-54\nc44.2,-33.3,65.8,-50.3,66.5,-51c1.3,-1.3,3,-2,5,-2c4.7,0,8.7,3.3,12,10\ns173,378,173,378c0.7,0,35.3,-71,104,-213c68.7,-142,137.5,-285,206.5,-429\nc69,-144,104.5,-217.7,106.5,-221\nl" + extraVinculum / 2.075 + " -" + extraVinculum + "\nc5.3,-9.3,12,-14,20,-14\nH400000v" + (40 + extraVinculum) + "H845.2724\ns-225.272,467,-225.272,467s-235,486,-235,486c-2.7,4.7,-9,7,-19,7\nc-6,0,-10,-1,-12,-3s-194,-422,-194,-422s-65,47,-65,47z\nM" + (834 + extraVinculum) + " " + hLinePad2 + "h400000v" + (40 + extraVinculum) + "h-400000z";
};
var sqrtSize1 = function sqrtSize12(extraVinculum, hLinePad2) {
  return "M263," + (601 + extraVinculum + hLinePad2) + "c0.7,0,18,39.7,52,119\nc34,79.3,68.167,158.7,102.5,238c34.3,79.3,51.8,119.3,52.5,120\nc340,-704.7,510.7,-1060.3,512,-1067\nl" + extraVinculum / 2.084 + " -" + extraVinculum + "\nc4.7,-7.3,11,-11,19,-11\nH40000v" + (40 + extraVinculum) + "H1012.3\ns-271.3,567,-271.3,567c-38.7,80.7,-84,175,-136,283c-52,108,-89.167,185.3,-111.5,232\nc-22.3,46.7,-33.8,70.3,-34.5,71c-4.7,4.7,-12.3,7,-23,7s-12,-1,-12,-1\ns-109,-253,-109,-253c-72.7,-168,-109.3,-252,-110,-252c-10.7,8,-22,16.7,-34,26\nc-22,17.3,-33.3,26,-34,26s-26,-26,-26,-26s76,-59,76,-59s76,-60,76,-60z\nM" + (1001 + extraVinculum) + " " + hLinePad2 + "h400000v" + (40 + extraVinculum) + "h-400000z";
};
var sqrtSize2 = function sqrtSize22(extraVinculum, hLinePad2) {
  return "M983 " + (10 + extraVinculum + hLinePad2) + "\nl" + extraVinculum / 3.13 + " -" + extraVinculum + "\nc4,-6.7,10,-10,18,-10 H400000v" + (40 + extraVinculum) + "\nH1013.1s-83.4,268,-264.1,840c-180.7,572,-277,876.3,-289,913c-4.7,4.7,-12.7,7,-24,7\ns-12,0,-12,0c-1.3,-3.3,-3.7,-11.7,-7,-25c-35.3,-125.3,-106.7,-373.3,-214,-744\nc-10,12,-21,25,-33,39s-32,39,-32,39c-6,-5.3,-15,-14,-27,-26s25,-30,25,-30\nc26.7,-32.7,52,-63,76,-91s52,-60,52,-60s208,722,208,722\nc56,-175.3,126.3,-397.3,211,-666c84.7,-268.7,153.8,-488.2,207.5,-658.5\nc53.7,-170.3,84.5,-266.8,92.5,-289.5z\nM" + (1001 + extraVinculum) + " " + hLinePad2 + "h400000v" + (40 + extraVinculum) + "h-400000z";
};
var sqrtSize3 = function sqrtSize32(extraVinculum, hLinePad2) {
  return "M424," + (2398 + extraVinculum + hLinePad2) + "\nc-1.3,-0.7,-38.5,-172,-111.5,-514c-73,-342,-109.8,-513.3,-110.5,-514\nc0,-2,-10.7,14.3,-32,49c-4.7,7.3,-9.8,15.7,-15.5,25c-5.7,9.3,-9.8,16,-12.5,20\ns-5,7,-5,7c-4,-3.3,-8.3,-7.7,-13,-13s-13,-13,-13,-13s76,-122,76,-122s77,-121,77,-121\ns209,968,209,968c0,-2,84.7,-361.7,254,-1079c169.3,-717.3,254.7,-1077.7,256,-1081\nl" + extraVinculum / 4.223 + " -" + extraVinculum + "c4,-6.7,10,-10,18,-10 H400000\nv" + (40 + extraVinculum) + "H1014.6\ns-87.3,378.7,-272.6,1166c-185.3,787.3,-279.3,1182.3,-282,1185\nc-2,6,-10,9,-24,9\nc-8,0,-12,-0.7,-12,-2z M" + (1001 + extraVinculum) + " " + hLinePad2 + "\nh400000v" + (40 + extraVinculum) + "h-400000z";
};
var sqrtSize4 = function sqrtSize42(extraVinculum, hLinePad2) {
  return "M473," + (2713 + extraVinculum + hLinePad2) + "\nc339.3,-1799.3,509.3,-2700,510,-2702 l" + extraVinculum / 5.298 + " -" + extraVinculum + "\nc3.3,-7.3,9.3,-11,18,-11 H400000v" + (40 + extraVinculum) + "H1017.7\ns-90.5,478,-276.2,1466c-185.7,988,-279.5,1483,-281.5,1485c-2,6,-10,9,-24,9\nc-8,0,-12,-0.7,-12,-2c0,-1.3,-5.3,-32,-16,-92c-50.7,-293.3,-119.7,-693.3,-207,-1200\nc0,-1.3,-5.3,8.7,-16,30c-10.7,21.3,-21.3,42.7,-32,64s-16,33,-16,33s-26,-26,-26,-26\ns76,-153,76,-153s77,-151,77,-151c0.7,0.7,35.7,202,105,604c67.3,400.7,102,602.7,104,\n606zM" + (1001 + extraVinculum) + " " + hLinePad2 + "h400000v" + (40 + extraVinculum) + "H1017.7z";
};
var phasePath = function phasePath2(y4) {
  var x2 = y4 / 2;
  return "M400000 " + y4 + " H0 L" + x2 + " 0 l65 45 L145 " + (y4 - 80) + " H400000z";
};
var sqrtTall = function sqrtTall2(extraVinculum, hLinePad2, viewBoxHeight) {
  var vertSegment = viewBoxHeight - 54 - hLinePad2 - extraVinculum;
  return "M702 " + (extraVinculum + hLinePad2) + "H400000" + (40 + extraVinculum) + "\nH742v" + vertSegment + "l-4 4-4 4c-.667.7 -2 1.5-4 2.5s-4.167 1.833-6.5 2.5-5.5 1-9.5 1\nh-12l-28-84c-16.667-52-96.667 -294.333-240-727l-212 -643 -85 170\nc-4-3.333-8.333-7.667-13 -13l-13-13l77-155 77-156c66 199.333 139 419.667\n219 661 l218 661zM702 " + hLinePad2 + "H400000v" + (40 + extraVinculum) + "H742z";
};
var sqrtPath = function sqrtPath2(size, extraVinculum, viewBoxHeight) {
  extraVinculum = 1e3 * extraVinculum;
  var path6 = "";
  switch (size) {
    case "sqrtMain":
      path6 = sqrtMain(extraVinculum, hLinePad);
      break;
    case "sqrtSize1":
      path6 = sqrtSize1(extraVinculum, hLinePad);
      break;
    case "sqrtSize2":
      path6 = sqrtSize2(extraVinculum, hLinePad);
      break;
    case "sqrtSize3":
      path6 = sqrtSize3(extraVinculum, hLinePad);
      break;
    case "sqrtSize4":
      path6 = sqrtSize4(extraVinculum, hLinePad);
      break;
    case "sqrtTall":
      path6 = sqrtTall(extraVinculum, hLinePad, viewBoxHeight);
  }
  return path6;
};
var innerPath = function innerPath2(name, height) {
  switch (name) {
    case "\u239C":
      return "M291 0 H417 V" + height + " H291z M291 0 H417 V" + height + " H291z";
    case "\u2223":
      return "M145 0 H188 V" + height + " H145z M145 0 H188 V" + height + " H145z";
    case "\u2225":
      return "M145 0 H188 V" + height + " H145z M145 0 H188 V" + height + " H145z" + ("M367 0 H410 V" + height + " H367z M367 0 H410 V" + height + " H367z");
    case "\u239F":
      return "M457 0 H583 V" + height + " H457z M457 0 H583 V" + height + " H457z";
    case "\u23A2":
      return "M319 0 H403 V" + height + " H319z M319 0 H403 V" + height + " H319z";
    case "\u23A5":
      return "M263 0 H347 V" + height + " H263z M263 0 H347 V" + height + " H263z";
    case "\u23AA":
      return "M384 0 H504 V" + height + " H384z M384 0 H504 V" + height + " H384z";
    case "\u23D0":
      return "M312 0 H355 V" + height + " H312z M312 0 H355 V" + height + " H312z";
    case "\u2016":
      return "M257 0 H300 V" + height + " H257z M257 0 H300 V" + height + " H257z" + ("M478 0 H521 V" + height + " H478z M478 0 H521 V" + height + " H478z");
    default:
      return "";
  }
};
var path4 = {
  // The doubleleftarrow geometry is from glyph U+21D0 in the font KaTeX Main
  doubleleftarrow: "M262 157\nl10-10c34-36 62.7-77 86-123 3.3-8 5-13.3 5-16 0-5.3-6.7-8-20-8-7.3\n 0-12.2.5-14.5 1.5-2.3 1-4.8 4.5-7.5 10.5-49.3 97.3-121.7 169.3-217 216-28\n 14-57.3 25-88 33-6.7 2-11 3.8-13 5.5-2 1.7-3 4.2-3 7.5s1 5.8 3 7.5\nc2 1.7 6.3 3.5 13 5.5 68 17.3 128.2 47.8 180.5 91.5 52.3 43.7 93.8 96.2 124.5\n 157.5 9.3 8 15.3 12.3 18 13h6c12-.7 18-4 18-10 0-2-1.7-7-5-15-23.3-46-52-87\n-86-123l-10-10h399738v-40H218c328 0 0 0 0 0l-10-8c-26.7-20-65.7-43-117-69 2.7\n-2 6-3.7 10-5 36.7-16 72.3-37.3 107-64l10-8h399782v-40z\nm8 0v40h399730v-40zm0 194v40h399730v-40z",
  // doublerightarrow is from glyph U+21D2 in font KaTeX Main
  doublerightarrow: "M399738 392l\n-10 10c-34 36-62.7 77-86 123-3.3 8-5 13.3-5 16 0 5.3 6.7 8 20 8 7.3 0 12.2-.5\n 14.5-1.5 2.3-1 4.8-4.5 7.5-10.5 49.3-97.3 121.7-169.3 217-216 28-14 57.3-25 88\n-33 6.7-2 11-3.8 13-5.5 2-1.7 3-4.2 3-7.5s-1-5.8-3-7.5c-2-1.7-6.3-3.5-13-5.5-68\n-17.3-128.2-47.8-180.5-91.5-52.3-43.7-93.8-96.2-124.5-157.5-9.3-8-15.3-12.3-18\n-13h-6c-12 .7-18 4-18 10 0 2 1.7 7 5 15 23.3 46 52 87 86 123l10 10H0v40h399782\nc-328 0 0 0 0 0l10 8c26.7 20 65.7 43 117 69-2.7 2-6 3.7-10 5-36.7 16-72.3 37.3\n-107 64l-10 8H0v40zM0 157v40h399730v-40zm0 194v40h399730v-40z",
  // leftarrow is from glyph U+2190 in font KaTeX Main
  leftarrow: "M400000 241H110l3-3c68.7-52.7 113.7-120\n 135-202 4-14.7 6-23 6-25 0-7.3-7-11-21-11-8 0-13.2.8-15.5 2.5-2.3 1.7-4.2 5.8\n-5.5 12.5-1.3 4.7-2.7 10.3-4 17-12 48.7-34.8 92-68.5 130S65.3 228.3 18 247\nc-10 4-16 7.7-18 11 0 8.7 6 14.3 18 17 47.3 18.7 87.8 47 121.5 85S196 441.3 208\n 490c.7 2 1.3 5 2 9s1.2 6.7 1.5 8c.3 1.3 1 3.3 2 6s2.2 4.5 3.5 5.5c1.3 1 3.3\n 1.8 6 2.5s6 1 10 1c14 0 21-3.7 21-11 0-2-2-10.3-6-25-20-79.3-65-146.7-135-202\n l-3-3h399890zM100 241v40h399900v-40z",
  // overbrace is from glyphs U+23A9/23A8/23A7 in font KaTeX_Size4-Regular
  leftbrace: "M6 548l-6-6v-35l6-11c56-104 135.3-181.3 238-232 57.3-28.7 117\n-45 179-50h399577v120H403c-43.3 7-81 15-113 26-100.7 33-179.7 91-237 174-2.7\n 5-6 9-10 13-.7 1-7.3 1-20 1H6z",
  leftbraceunder: "M0 6l6-6h17c12.688 0 19.313.3 20 1 4 4 7.313 8.3 10 13\n 35.313 51.3 80.813 93.8 136.5 127.5 55.688 33.7 117.188 55.8 184.5 66.5.688\n 0 2 .3 4 1 18.688 2.7 76 4.3 172 5h399450v120H429l-6-1c-124.688-8-235-61.7\n-331-161C60.687 138.7 32.312 99.3 7 54L0 41V6z",
  // overgroup is from the MnSymbol package (public domain)
  leftgroup: "M400000 80\nH435C64 80 168.3 229.4 21 260c-5.9 1.2-18 0-18 0-2 0-3-1-3-3v-38C76 61 257 0\n 435 0h399565z",
  leftgroupunder: "M400000 262\nH435C64 262 168.3 112.6 21 82c-5.9-1.2-18 0-18 0-2 0-3 1-3 3v38c76 158 257 219\n 435 219h399565z",
  // Harpoons are from glyph U+21BD in font KaTeX Main
  leftharpoon: "M0 267c.7 5.3 3 10 7 14h399993v-40H93c3.3\n-3.3 10.2-9.5 20.5-18.5s17.8-15.8 22.5-20.5c50.7-52 88-110.3 112-175 4-11.3 5\n-18.3 3-21-1.3-4-7.3-6-18-6-8 0-13 .7-15 2s-4.7 6.7-8 16c-42 98.7-107.3 174.7\n-196 228-6.7 4.7-10.7 8-12 10-1.3 2-2 5.7-2 11zm100-26v40h399900v-40z",
  leftharpoonplus: "M0 267c.7 5.3 3 10 7 14h399993v-40H93c3.3-3.3 10.2-9.5\n 20.5-18.5s17.8-15.8 22.5-20.5c50.7-52 88-110.3 112-175 4-11.3 5-18.3 3-21-1.3\n-4-7.3-6-18-6-8 0-13 .7-15 2s-4.7 6.7-8 16c-42 98.7-107.3 174.7-196 228-6.7 4.7\n-10.7 8-12 10-1.3 2-2 5.7-2 11zm100-26v40h399900v-40zM0 435v40h400000v-40z\nm0 0v40h400000v-40z",
  leftharpoondown: "M7 241c-4 4-6.333 8.667-7 14 0 5.333.667 9 2 11s5.333\n 5.333 12 10c90.667 54 156 130 196 228 3.333 10.667 6.333 16.333 9 17 2 .667 5\n 1 9 1h5c10.667 0 16.667-2 18-6 2-2.667 1-9.667-3-21-32-87.333-82.667-157.667\n-152-211l-3-3h399907v-40zM93 281 H400000 v-40L7 241z",
  leftharpoondownplus: "M7 435c-4 4-6.3 8.7-7 14 0 5.3.7 9 2 11s5.3 5.3 12\n 10c90.7 54 156 130 196 228 3.3 10.7 6.3 16.3 9 17 2 .7 5 1 9 1h5c10.7 0 16.7\n-2 18-6 2-2.7 1-9.7-3-21-32-87.3-82.7-157.7-152-211l-3-3h399907v-40H7zm93 0\nv40h399900v-40zM0 241v40h399900v-40zm0 0v40h399900v-40z",
  // hook is from glyph U+21A9 in font KaTeX Main
  lefthook: "M400000 281 H103s-33-11.2-61-33.5S0 197.3 0 164s14.2-61.2 42.5\n-83.5C70.8 58.2 104 47 142 47 c16.7 0 25 6.7 25 20 0 12-8.7 18.7-26 20-40 3.3\n-68.7 15.7-86 37-10 12-15 25.3-15 40 0 22.7 9.8 40.7 29.5 54 19.7 13.3 43.5 21\n 71.5 23h399859zM103 281v-40h399897v40z",
  leftlinesegment: "M40 281 V428 H0 V94 H40 V241 H400000 v40z\nM40 281 V428 H0 V94 H40 V241 H400000 v40z",
  leftmapsto: "M40 281 V448H0V74H40V241H400000v40z\nM40 281 V448H0V74H40V241H400000v40z",
  // tofrom is from glyph U+21C4 in font KaTeX AMS Regular
  leftToFrom: "M0 147h400000v40H0zm0 214c68 40 115.7 95.7 143 167h22c15.3 0 23\n-.3 23-1 0-1.3-5.3-13.7-16-37-18-35.3-41.3-69-70-101l-7-8h399905v-40H95l7-8\nc28.7-32 52-65.7 70-101 10.7-23.3 16-35.7 16-37 0-.7-7.7-1-23-1h-22C115.7 265.3\n 68 321 0 361zm0-174v-40h399900v40zm100 154v40h399900v-40z",
  longequal: "M0 50 h400000 v40H0z m0 194h40000v40H0z\nM0 50 h400000 v40H0z m0 194h40000v40H0z",
  midbrace: "M200428 334\nc-100.7-8.3-195.3-44-280-108-55.3-42-101.7-93-139-153l-9-14c-2.7 4-5.7 8.7-9 14\n-53.3 86.7-123.7 153-211 199-66.7 36-137.3 56.3-212 62H0V214h199568c178.3-11.7\n 311.7-78.3 403-201 6-8 9.7-12 11-12 .7-.7 6.7-1 18-1s17.3.3 18 1c1.3 0 5 4 11\n 12 44.7 59.3 101.3 106.3 170 141s145.3 54.3 229 60h199572v120z",
  midbraceunder: "M199572 214\nc100.7 8.3 195.3 44 280 108 55.3 42 101.7 93 139 153l9 14c2.7-4 5.7-8.7 9-14\n 53.3-86.7 123.7-153 211-199 66.7-36 137.3-56.3 212-62h199568v120H200432c-178.3\n 11.7-311.7 78.3-403 201-6 8-9.7 12-11 12-.7.7-6.7 1-18 1s-17.3-.3-18-1c-1.3 0\n-5-4-11-12-44.7-59.3-101.3-106.3-170-141s-145.3-54.3-229-60H0V214z",
  oiintSize1: "M512.6 71.6c272.6 0 320.3 106.8 320.3 178.2 0 70.8-47.7 177.6\n-320.3 177.6S193.1 320.6 193.1 249.8c0-71.4 46.9-178.2 319.5-178.2z\nm368.1 178.2c0-86.4-60.9-215.4-368.1-215.4-306.4 0-367.3 129-367.3 215.4 0 85.8\n60.9 214.8 367.3 214.8 307.2 0 368.1-129 368.1-214.8z",
  oiintSize2: "M757.8 100.1c384.7 0 451.1 137.6 451.1 230 0 91.3-66.4 228.8\n-451.1 228.8-386.3 0-452.7-137.5-452.7-228.8 0-92.4 66.4-230 452.7-230z\nm502.4 230c0-111.2-82.4-277.2-502.4-277.2s-504 166-504 277.2\nc0 110 84 276 504 276s502.4-166 502.4-276z",
  oiiintSize1: "M681.4 71.6c408.9 0 480.5 106.8 480.5 178.2 0 70.8-71.6 177.6\n-480.5 177.6S202.1 320.6 202.1 249.8c0-71.4 70.5-178.2 479.3-178.2z\nm525.8 178.2c0-86.4-86.8-215.4-525.7-215.4-437.9 0-524.7 129-524.7 215.4 0\n85.8 86.8 214.8 524.7 214.8 438.9 0 525.7-129 525.7-214.8z",
  oiiintSize2: "M1021.2 53c603.6 0 707.8 165.8 707.8 277.2 0 110-104.2 275.8\n-707.8 275.8-606 0-710.2-165.8-710.2-275.8C311 218.8 415.2 53 1021.2 53z\nm770.4 277.1c0-131.2-126.4-327.6-770.5-327.6S248.4 198.9 248.4 330.1\nc0 130 128.8 326.4 772.7 326.4s770.5-196.4 770.5-326.4z",
  rightarrow: "M0 241v40h399891c-47.3 35.3-84 78-110 128\n-16.7 32-27.7 63.7-33 95 0 1.3-.2 2.7-.5 4-.3 1.3-.5 2.3-.5 3 0 7.3 6.7 11 20\n 11 8 0 13.2-.8 15.5-2.5 2.3-1.7 4.2-5.5 5.5-11.5 2-13.3 5.7-27 11-41 14.7-44.7\n 39-84.5 73-119.5s73.7-60.2 119-75.5c6-2 9-5.7 9-11s-3-9-9-11c-45.3-15.3-85\n-40.5-119-75.5s-58.3-74.8-73-119.5c-4.7-14-8.3-27.3-11-40-1.3-6.7-3.2-10.8-5.5\n-12.5-2.3-1.7-7.5-2.5-15.5-2.5-14 0-21 3.7-21 11 0 2 2 10.3 6 25 20.7 83.3 67\n 151.7 139 205zm0 0v40h399900v-40z",
  rightbrace: "M400000 542l\n-6 6h-17c-12.7 0-19.3-.3-20-1-4-4-7.3-8.3-10-13-35.3-51.3-80.8-93.8-136.5-127.5\ns-117.2-55.8-184.5-66.5c-.7 0-2-.3-4-1-18.7-2.7-76-4.3-172-5H0V214h399571l6 1\nc124.7 8 235 61.7 331 161 31.3 33.3 59.7 72.7 85 118l7 13v35z",
  rightbraceunder: "M399994 0l6 6v35l-6 11c-56 104-135.3 181.3-238 232-57.3\n 28.7-117 45-179 50H-300V214h399897c43.3-7 81-15 113-26 100.7-33 179.7-91 237\n-174 2.7-5 6-9 10-13 .7-1 7.3-1 20-1h17z",
  rightgroup: "M0 80h399565c371 0 266.7 149.4 414 180 5.9 1.2 18 0 18 0 2 0\n 3-1 3-3v-38c-76-158-257-219-435-219H0z",
  rightgroupunder: "M0 262h399565c371 0 266.7-149.4 414-180 5.9-1.2 18 0 18\n 0 2 0 3 1 3 3v38c-76 158-257 219-435 219H0z",
  rightharpoon: "M0 241v40h399993c4.7-4.7 7-9.3 7-14 0-9.3\n-3.7-15.3-11-18-92.7-56.7-159-133.7-199-231-3.3-9.3-6-14.7-8-16-2-1.3-7-2-15-2\n-10.7 0-16.7 2-18 6-2 2.7-1 9.7 3 21 15.3 42 36.7 81.8 64 119.5 27.3 37.7 58\n 69.2 92 94.5zm0 0v40h399900v-40z",
  rightharpoonplus: "M0 241v40h399993c4.7-4.7 7-9.3 7-14 0-9.3-3.7-15.3-11\n-18-92.7-56.7-159-133.7-199-231-3.3-9.3-6-14.7-8-16-2-1.3-7-2-15-2-10.7 0-16.7\n 2-18 6-2 2.7-1 9.7 3 21 15.3 42 36.7 81.8 64 119.5 27.3 37.7 58 69.2 92 94.5z\nm0 0v40h399900v-40z m100 194v40h399900v-40zm0 0v40h399900v-40z",
  rightharpoondown: "M399747 511c0 7.3 6.7 11 20 11 8 0 13-.8 15-2.5s4.7-6.8\n 8-15.5c40-94 99.3-166.3 178-217 13.3-8 20.3-12.3 21-13 5.3-3.3 8.5-5.8 9.5\n-7.5 1-1.7 1.5-5.2 1.5-10.5s-2.3-10.3-7-15H0v40h399908c-34 25.3-64.7 57-92 95\n-27.3 38-48.7 77.7-64 119-3.3 8.7-5 14-5 16zM0 241v40h399900v-40z",
  rightharpoondownplus: "M399747 705c0 7.3 6.7 11 20 11 8 0 13-.8\n 15-2.5s4.7-6.8 8-15.5c40-94 99.3-166.3 178-217 13.3-8 20.3-12.3 21-13 5.3-3.3\n 8.5-5.8 9.5-7.5 1-1.7 1.5-5.2 1.5-10.5s-2.3-10.3-7-15H0v40h399908c-34 25.3\n-64.7 57-92 95-27.3 38-48.7 77.7-64 119-3.3 8.7-5 14-5 16zM0 435v40h399900v-40z\nm0-194v40h400000v-40zm0 0v40h400000v-40z",
  righthook: "M399859 241c-764 0 0 0 0 0 40-3.3 68.7-15.7 86-37 10-12 15-25.3\n 15-40 0-22.7-9.8-40.7-29.5-54-19.7-13.3-43.5-21-71.5-23-17.3-1.3-26-8-26-20 0\n-13.3 8.7-20 26-20 38 0 71 11.2 99 33.5 0 0 7 5.6 21 16.7 14 11.2 21 33.5 21\n 66.8s-14 61.2-42 83.5c-28 22.3-61 33.5-99 33.5L0 241z M0 281v-40h399859v40z",
  rightlinesegment: "M399960 241 V94 h40 V428 h-40 V281 H0 v-40z\nM399960 241 V94 h40 V428 h-40 V281 H0 v-40z",
  rightToFrom: "M400000 167c-70.7-42-118-97.7-142-167h-23c-15.3 0-23 .3-23\n 1 0 1.3 5.3 13.7 16 37 18 35.3 41.3 69 70 101l7 8H0v40h399905l-7 8c-28.7 32\n-52 65.7-70 101-10.7 23.3-16 35.7-16 37 0 .7 7.7 1 23 1h23c24-69.3 71.3-125 142\n-167z M100 147v40h399900v-40zM0 341v40h399900v-40z",
  // twoheadleftarrow is from glyph U+219E in font KaTeX AMS Regular
  twoheadleftarrow: "M0 167c68 40\n 115.7 95.7 143 167h22c15.3 0 23-.3 23-1 0-1.3-5.3-13.7-16-37-18-35.3-41.3-69\n-70-101l-7-8h125l9 7c50.7 39.3 85 86 103 140h46c0-4.7-6.3-18.7-19-42-18-35.3\n-40-67.3-66-96l-9-9h399716v-40H284l9-9c26-28.7 48-60.7 66-96 12.7-23.333 19\n-37.333 19-42h-46c-18 54-52.3 100.7-103 140l-9 7H95l7-8c28.7-32 52-65.7 70-101\n 10.7-23.333 16-35.7 16-37 0-.7-7.7-1-23-1h-22C115.7 71.3 68 127 0 167z",
  twoheadrightarrow: "M400000 167\nc-68-40-115.7-95.7-143-167h-22c-15.3 0-23 .3-23 1 0 1.3 5.3 13.7 16 37 18 35.3\n 41.3 69 70 101l7 8h-125l-9-7c-50.7-39.3-85-86-103-140h-46c0 4.7 6.3 18.7 19 42\n 18 35.3 40 67.3 66 96l9 9H0v40h399716l-9 9c-26 28.7-48 60.7-66 96-12.7 23.333\n-19 37.333-19 42h46c18-54 52.3-100.7 103-140l9-7h125l-7 8c-28.7 32-52 65.7-70\n 101-10.7 23.333-16 35.7-16 37 0 .7 7.7 1 23 1h22c27.3-71.3 75-127 143-167z",
  // tilde1 is a modified version of a glyph from the MnSymbol package
  tilde1: "M200 55.538c-77 0-168 73.953-177 73.953-3 0-7\n-2.175-9-5.437L2 97c-1-2-2-4-2-6 0-4 2-7 5-9l20-12C116 12 171 0 207 0c86 0\n 114 68 191 68 78 0 168-68 177-68 4 0 7 2 9 5l12 19c1 2.175 2 4.35 2 6.525 0\n 4.35-2 7.613-5 9.788l-19 13.05c-92 63.077-116.937 75.308-183 76.128\n-68.267.847-113-73.952-191-73.952z",
  // ditto tilde2, tilde3, & tilde4
  tilde2: "M344 55.266c-142 0-300.638 81.316-311.5 86.418\n-8.01 3.762-22.5 10.91-23.5 5.562L1 120c-1-2-1-3-1-4 0-5 3-9 8-10l18.4-9C160.9\n 31.9 283 0 358 0c148 0 188 122 331 122s314-97 326-97c4 0 8 2 10 7l7 21.114\nc1 2.14 1 3.21 1 4.28 0 5.347-3 9.626-7 10.696l-22.3 12.622C852.6 158.372 751\n 181.476 676 181.476c-149 0-189-126.21-332-126.21z",
  tilde3: "M786 59C457 59 32 175.242 13 175.242c-6 0-10-3.457\n-11-10.37L.15 138c-1-7 3-12 10-13l19.2-6.4C378.4 40.7 634.3 0 804.3 0c337 0\n 411.8 157 746.8 157 328 0 754-112 773-112 5 0 10 3 11 9l1 14.075c1 8.066-.697\n 16.595-6.697 17.492l-21.052 7.31c-367.9 98.146-609.15 122.696-778.15 122.696\n -338 0-409-156.573-744-156.573z",
  tilde4: "M786 58C457 58 32 177.487 13 177.487c-6 0-10-3.345\n-11-10.035L.15 143c-1-7 3-12 10-13l22-6.7C381.2 35 637.15 0 807.15 0c337 0 409\n 177 744 177 328 0 754-127 773-127 5 0 10 3 11 9l1 14.794c1 7.805-3 13.38-9\n 14.495l-20.7 5.574c-366.85 99.79-607.3 139.372-776.3 139.372-338 0-409\n -175.236-744-175.236z",
  // vec is from glyph U+20D7 in font KaTeX Main
  vec: "M377 20c0-5.333 1.833-10 5.5-14S391 0 397 0c4.667 0 8.667 1.667 12 5\n3.333 2.667 6.667 9 10 19 6.667 24.667 20.333 43.667 41 57 7.333 4.667 11\n10.667 11 18 0 6-1 10-3 12s-6.667 5-14 9c-28.667 14.667-53.667 35.667-75 63\n-1.333 1.333-3.167 3.5-5.5 6.5s-4 4.833-5 5.5c-1 .667-2.5 1.333-4.5 2s-4.333 1\n-7 1c-4.667 0-9.167-1.833-13.5-5.5S337 184 337 178c0-12.667 15.667-32.333 47-59\nH213l-171-1c-8.667-6-13-12.333-13-19 0-4.667 4.333-11.333 13-20h359\nc-16-25.333-24-45-24-59z",
  // widehat1 is a modified version of a glyph from the MnSymbol package
  widehat1: "M529 0h5l519 115c5 1 9 5 9 10 0 1-1 2-1 3l-4 22\nc-1 5-5 9-11 9h-2L532 67 19 159h-2c-5 0-9-4-11-9l-5-22c-1-6 2-12 8-13z",
  // ditto widehat2, widehat3, & widehat4
  widehat2: "M1181 0h2l1171 176c6 0 10 5 10 11l-2 23c-1 6-5 10\n-11 10h-1L1182 67 15 220h-1c-6 0-10-4-11-10l-2-23c-1-6 4-11 10-11z",
  widehat3: "M1181 0h2l1171 236c6 0 10 5 10 11l-2 23c-1 6-5 10\n-11 10h-1L1182 67 15 280h-1c-6 0-10-4-11-10l-2-23c-1-6 4-11 10-11z",
  widehat4: "M1181 0h2l1171 296c6 0 10 5 10 11l-2 23c-1 6-5 10\n-11 10h-1L1182 67 15 340h-1c-6 0-10-4-11-10l-2-23c-1-6 4-11 10-11z",
  // widecheck paths are all inverted versions of widehat
  widecheck1: "M529,159h5l519,-115c5,-1,9,-5,9,-10c0,-1,-1,-2,-1,-3l-4,-22c-1,\n-5,-5,-9,-11,-9h-2l-512,92l-513,-92h-2c-5,0,-9,4,-11,9l-5,22c-1,6,2,12,8,13z",
  widecheck2: "M1181,220h2l1171,-176c6,0,10,-5,10,-11l-2,-23c-1,-6,-5,-10,\n-11,-10h-1l-1168,153l-1167,-153h-1c-6,0,-10,4,-11,10l-2,23c-1,6,4,11,10,11z",
  widecheck3: "M1181,280h2l1171,-236c6,0,10,-5,10,-11l-2,-23c-1,-6,-5,-10,\n-11,-10h-1l-1168,213l-1167,-213h-1c-6,0,-10,4,-11,10l-2,23c-1,6,4,11,10,11z",
  widecheck4: "M1181,340h2l1171,-296c6,0,10,-5,10,-11l-2,-23c-1,-6,-5,-10,\n-11,-10h-1l-1168,273l-1167,-273h-1c-6,0,-10,4,-11,10l-2,23c-1,6,4,11,10,11z",
  // The next ten paths support reaction arrows from the mhchem package.
  // Arrows for \ce{<-->} are offset from xAxis by 0.22ex, per mhchem in LaTeX
  // baraboveleftarrow is mostly from glyph U+2190 in font KaTeX Main
  baraboveleftarrow: "M400000 620h-399890l3 -3c68.7 -52.7 113.7 -120 135 -202\nc4 -14.7 6 -23 6 -25c0 -7.3 -7 -11 -21 -11c-8 0 -13.2 0.8 -15.5 2.5\nc-2.3 1.7 -4.2 5.8 -5.5 12.5c-1.3 4.7 -2.7 10.3 -4 17c-12 48.7 -34.8 92 -68.5 130\ns-74.2 66.3 -121.5 85c-10 4 -16 7.7 -18 11c0 8.7 6 14.3 18 17c47.3 18.7 87.8 47\n121.5 85s56.5 81.3 68.5 130c0.7 2 1.3 5 2 9s1.2 6.7 1.5 8c0.3 1.3 1 3.3 2 6\ns2.2 4.5 3.5 5.5c1.3 1 3.3 1.8 6 2.5s6 1 10 1c14 0 21 -3.7 21 -11\nc0 -2 -2 -10.3 -6 -25c-20 -79.3 -65 -146.7 -135 -202l-3 -3h399890z\nM100 620v40h399900v-40z M0 241v40h399900v-40zM0 241v40h399900v-40z",
  // rightarrowabovebar is mostly from glyph U+2192, KaTeX Main
  rightarrowabovebar: "M0 241v40h399891c-47.3 35.3-84 78-110 128-16.7 32\n-27.7 63.7-33 95 0 1.3-.2 2.7-.5 4-.3 1.3-.5 2.3-.5 3 0 7.3 6.7 11 20 11 8 0\n13.2-.8 15.5-2.5 2.3-1.7 4.2-5.5 5.5-11.5 2-13.3 5.7-27 11-41 14.7-44.7 39\n-84.5 73-119.5s73.7-60.2 119-75.5c6-2 9-5.7 9-11s-3-9-9-11c-45.3-15.3-85-40.5\n-119-75.5s-58.3-74.8-73-119.5c-4.7-14-8.3-27.3-11-40-1.3-6.7-3.2-10.8-5.5\n-12.5-2.3-1.7-7.5-2.5-15.5-2.5-14 0-21 3.7-21 11 0 2 2 10.3 6 25 20.7 83.3 67\n151.7 139 205zm96 379h399894v40H0zm0 0h399904v40H0z",
  // The short left harpoon has 0.5em (i.e. 500 units) kern on the left end.
  // Ref from mhchem.sty: \rlap{\raisebox{-.22ex}{$\kern0.5em
  baraboveshortleftharpoon: "M507,435c-4,4,-6.3,8.7,-7,14c0,5.3,0.7,9,2,11\nc1.3,2,5.3,5.3,12,10c90.7,54,156,130,196,228c3.3,10.7,6.3,16.3,9,17\nc2,0.7,5,1,9,1c0,0,5,0,5,0c10.7,0,16.7,-2,18,-6c2,-2.7,1,-9.7,-3,-21\nc-32,-87.3,-82.7,-157.7,-152,-211c0,0,-3,-3,-3,-3l399351,0l0,-40\nc-398570,0,-399437,0,-399437,0z M593 435 v40 H399500 v-40z\nM0 281 v-40 H399908 v40z M0 281 v-40 H399908 v40z",
  rightharpoonaboveshortbar: "M0,241 l0,40c399126,0,399993,0,399993,0\nc4.7,-4.7,7,-9.3,7,-14c0,-9.3,-3.7,-15.3,-11,-18c-92.7,-56.7,-159,-133.7,-199,\n-231c-3.3,-9.3,-6,-14.7,-8,-16c-2,-1.3,-7,-2,-15,-2c-10.7,0,-16.7,2,-18,6\nc-2,2.7,-1,9.7,3,21c15.3,42,36.7,81.8,64,119.5c27.3,37.7,58,69.2,92,94.5z\nM0 241 v40 H399908 v-40z M0 475 v-40 H399500 v40z M0 475 v-40 H399500 v40z",
  shortbaraboveleftharpoon: "M7,435c-4,4,-6.3,8.7,-7,14c0,5.3,0.7,9,2,11\nc1.3,2,5.3,5.3,12,10c90.7,54,156,130,196,228c3.3,10.7,6.3,16.3,9,17c2,0.7,5,1,9,\n1c0,0,5,0,5,0c10.7,0,16.7,-2,18,-6c2,-2.7,1,-9.7,-3,-21c-32,-87.3,-82.7,-157.7,\n-152,-211c0,0,-3,-3,-3,-3l399907,0l0,-40c-399126,0,-399993,0,-399993,0z\nM93 435 v40 H400000 v-40z M500 241 v40 H400000 v-40z M500 241 v40 H400000 v-40z",
  shortrightharpoonabovebar: "M53,241l0,40c398570,0,399437,0,399437,0\nc4.7,-4.7,7,-9.3,7,-14c0,-9.3,-3.7,-15.3,-11,-18c-92.7,-56.7,-159,-133.7,-199,\n-231c-3.3,-9.3,-6,-14.7,-8,-16c-2,-1.3,-7,-2,-15,-2c-10.7,0,-16.7,2,-18,6\nc-2,2.7,-1,9.7,3,21c15.3,42,36.7,81.8,64,119.5c27.3,37.7,58,69.2,92,94.5z\nM500 241 v40 H399408 v-40z M500 435 v40 H400000 v-40z"
};
var tallDelim = function tallDelim2(label, midHeight) {
  switch (label) {
    case "lbrack":
      return "M403 1759 V84 H666 V0 H319 V1759 v" + midHeight + " v1759 h347 v-84\nH403z M403 1759 V0 H319 V1759 v" + midHeight + " v1759 h84z";
    case "rbrack":
      return "M347 1759 V0 H0 V84 H263 V1759 v" + midHeight + " v1759 H0 v84 H347z\nM347 1759 V0 H263 V1759 v" + midHeight + " v1759 h84z";
    case "vert":
      return "M145 15 v585 v" + midHeight + " v585 c2.667,10,9.667,15,21,15\nc10,0,16.667,-5,20,-15 v-585 v" + -midHeight + " v-585 c-2.667,-10,-9.667,-15,-21,-15\nc-10,0,-16.667,5,-20,15z M188 15 H145 v585 v" + midHeight + " v585 h43z";
    case "doublevert":
      return "M145 15 v585 v" + midHeight + " v585 c2.667,10,9.667,15,21,15\nc10,0,16.667,-5,20,-15 v-585 v" + -midHeight + " v-585 c-2.667,-10,-9.667,-15,-21,-15\nc-10,0,-16.667,5,-20,15z M188 15 H145 v585 v" + midHeight + " v585 h43z\nM367 15 v585 v" + midHeight + " v585 c2.667,10,9.667,15,21,15\nc10,0,16.667,-5,20,-15 v-585 v" + -midHeight + " v-585 c-2.667,-10,-9.667,-15,-21,-15\nc-10,0,-16.667,5,-20,15z M410 15 H367 v585 v" + midHeight + " v585 h43z";
    case "lfloor":
      return "M319 602 V0 H403 V602 v" + midHeight + " v1715 h263 v84 H319z\nMM319 602 V0 H403 V602 v" + midHeight + " v1715 H319z";
    case "rfloor":
      return "M319 602 V0 H403 V602 v" + midHeight + " v1799 H0 v-84 H319z\nMM319 602 V0 H403 V602 v" + midHeight + " v1715 H319z";
    case "lceil":
      return "M403 1759 V84 H666 V0 H319 V1759 v" + midHeight + " v602 h84z\nM403 1759 V0 H319 V1759 v" + midHeight + " v602 h84z";
    case "rceil":
      return "M347 1759 V0 H0 V84 H263 V1759 v" + midHeight + " v602 h84z\nM347 1759 V0 h-84 V1759 v" + midHeight + " v602 h84z";
    case "lparen":
      return "M863,9c0,-2,-2,-5,-6,-9c0,0,-17,0,-17,0c-12.7,0,-19.3,0.3,-20,1\nc-5.3,5.3,-10.3,11,-15,17c-242.7,294.7,-395.3,682,-458,1162c-21.3,163.3,-33.3,349,\n-36,557 l0," + (midHeight + 84) + "c0.2,6,0,26,0,60c2,159.3,10,310.7,24,454c53.3,528,210,\n949.7,470,1265c4.7,6,9.7,11.7,15,17c0.7,0.7,7,1,19,1c0,0,18,0,18,0c4,-4,6,-7,6,-9\nc0,-2.7,-3.3,-8.7,-10,-18c-135.3,-192.7,-235.5,-414.3,-300.5,-665c-65,-250.7,-102.5,\n-544.7,-112.5,-882c-2,-104,-3,-167,-3,-189\nl0,-" + (midHeight + 92) + "c0,-162.7,5.7,-314,17,-454c20.7,-272,63.7,-513,129,-723c65.3,\n-210,155.3,-396.3,270,-559c6.7,-9.3,10,-15.3,10,-18z";
    case "rparen":
      return "M76,0c-16.7,0,-25,3,-25,9c0,2,2,6.3,6,13c21.3,28.7,42.3,60.3,\n63,95c96.7,156.7,172.8,332.5,228.5,527.5c55.7,195,92.8,416.5,111.5,664.5\nc11.3,139.3,17,290.7,17,454c0,28,1.7,43,3.3,45l0," + (midHeight + 9) + "\nc-3,4,-3.3,16.7,-3.3,38c0,162,-5.7,313.7,-17,455c-18.7,248,-55.8,469.3,-111.5,664\nc-55.7,194.7,-131.8,370.3,-228.5,527c-20.7,34.7,-41.7,66.3,-63,95c-2,3.3,-4,7,-6,11\nc0,7.3,5.7,11,17,11c0,0,11,0,11,0c9.3,0,14.3,-0.3,15,-1c5.3,-5.3,10.3,-11,15,-17\nc242.7,-294.7,395.3,-681.7,458,-1161c21.3,-164.7,33.3,-350.7,36,-558\nl0,-" + (midHeight + 144) + "c-2,-159.3,-10,-310.7,-24,-454c-53.3,-528,-210,-949.7,\n-470,-1265c-4.7,-6,-9.7,-11.7,-15,-17c-0.7,-0.7,-6.7,-1,-18,-1z";
    default:
      throw new Error("Unknown stretchy delimiter.");
  }
};
var DocumentFragment2 = class {
  // HtmlDomNode
  // Never used; needed for satisfying interface.
  constructor(children) {
    this.children = void 0;
    this.classes = void 0;
    this.height = void 0;
    this.depth = void 0;
    this.maxFontSize = void 0;
    this.style = void 0;
    this.children = children;
    this.classes = [];
    this.height = 0;
    this.depth = 0;
    this.maxFontSize = 0;
    this.style = {};
  }
  hasClass(className) {
    return utils2.contains(this.classes, className);
  }
  /** Convert the fragment into a node. */
  toNode() {
    var frag = document.createDocumentFragment();
    for (var i7 = 0; i7 < this.children.length; i7++) {
      frag.appendChild(this.children[i7].toNode());
    }
    return frag;
  }
  /** Convert the fragment into HTML markup. */
  toMarkup() {
    var markup = "";
    for (var i7 = 0; i7 < this.children.length; i7++) {
      markup += this.children[i7].toMarkup();
    }
    return markup;
  }
  /**
   * Converts the math node into a string, similar to innerText. Applies to
   * MathDomNode's only.
   */
  toText() {
    var toText = (child) => child.toText();
    return this.children.map(toText).join("");
  }
};
var fontMetricsData = {
  "AMS-Regular": {
    "32": [0, 0, 0, 0, 0.25],
    "65": [0, 0.68889, 0, 0, 0.72222],
    "66": [0, 0.68889, 0, 0, 0.66667],
    "67": [0, 0.68889, 0, 0, 0.72222],
    "68": [0, 0.68889, 0, 0, 0.72222],
    "69": [0, 0.68889, 0, 0, 0.66667],
    "70": [0, 0.68889, 0, 0, 0.61111],
    "71": [0, 0.68889, 0, 0, 0.77778],
    "72": [0, 0.68889, 0, 0, 0.77778],
    "73": [0, 0.68889, 0, 0, 0.38889],
    "74": [0.16667, 0.68889, 0, 0, 0.5],
    "75": [0, 0.68889, 0, 0, 0.77778],
    "76": [0, 0.68889, 0, 0, 0.66667],
    "77": [0, 0.68889, 0, 0, 0.94445],
    "78": [0, 0.68889, 0, 0, 0.72222],
    "79": [0.16667, 0.68889, 0, 0, 0.77778],
    "80": [0, 0.68889, 0, 0, 0.61111],
    "81": [0.16667, 0.68889, 0, 0, 0.77778],
    "82": [0, 0.68889, 0, 0, 0.72222],
    "83": [0, 0.68889, 0, 0, 0.55556],
    "84": [0, 0.68889, 0, 0, 0.66667],
    "85": [0, 0.68889, 0, 0, 0.72222],
    "86": [0, 0.68889, 0, 0, 0.72222],
    "87": [0, 0.68889, 0, 0, 1],
    "88": [0, 0.68889, 0, 0, 0.72222],
    "89": [0, 0.68889, 0, 0, 0.72222],
    "90": [0, 0.68889, 0, 0, 0.66667],
    "107": [0, 0.68889, 0, 0, 0.55556],
    "160": [0, 0, 0, 0, 0.25],
    "165": [0, 0.675, 0.025, 0, 0.75],
    "174": [0.15559, 0.69224, 0, 0, 0.94666],
    "240": [0, 0.68889, 0, 0, 0.55556],
    "295": [0, 0.68889, 0, 0, 0.54028],
    "710": [0, 0.825, 0, 0, 2.33334],
    "732": [0, 0.9, 0, 0, 2.33334],
    "770": [0, 0.825, 0, 0, 2.33334],
    "771": [0, 0.9, 0, 0, 2.33334],
    "989": [0.08167, 0.58167, 0, 0, 0.77778],
    "1008": [0, 0.43056, 0.04028, 0, 0.66667],
    "8245": [0, 0.54986, 0, 0, 0.275],
    "8463": [0, 0.68889, 0, 0, 0.54028],
    "8487": [0, 0.68889, 0, 0, 0.72222],
    "8498": [0, 0.68889, 0, 0, 0.55556],
    "8502": [0, 0.68889, 0, 0, 0.66667],
    "8503": [0, 0.68889, 0, 0, 0.44445],
    "8504": [0, 0.68889, 0, 0, 0.66667],
    "8513": [0, 0.68889, 0, 0, 0.63889],
    "8592": [-0.03598, 0.46402, 0, 0, 0.5],
    "8594": [-0.03598, 0.46402, 0, 0, 0.5],
    "8602": [-0.13313, 0.36687, 0, 0, 1],
    "8603": [-0.13313, 0.36687, 0, 0, 1],
    "8606": [0.01354, 0.52239, 0, 0, 1],
    "8608": [0.01354, 0.52239, 0, 0, 1],
    "8610": [0.01354, 0.52239, 0, 0, 1.11111],
    "8611": [0.01354, 0.52239, 0, 0, 1.11111],
    "8619": [0, 0.54986, 0, 0, 1],
    "8620": [0, 0.54986, 0, 0, 1],
    "8621": [-0.13313, 0.37788, 0, 0, 1.38889],
    "8622": [-0.13313, 0.36687, 0, 0, 1],
    "8624": [0, 0.69224, 0, 0, 0.5],
    "8625": [0, 0.69224, 0, 0, 0.5],
    "8630": [0, 0.43056, 0, 0, 1],
    "8631": [0, 0.43056, 0, 0, 1],
    "8634": [0.08198, 0.58198, 0, 0, 0.77778],
    "8635": [0.08198, 0.58198, 0, 0, 0.77778],
    "8638": [0.19444, 0.69224, 0, 0, 0.41667],
    "8639": [0.19444, 0.69224, 0, 0, 0.41667],
    "8642": [0.19444, 0.69224, 0, 0, 0.41667],
    "8643": [0.19444, 0.69224, 0, 0, 0.41667],
    "8644": [0.1808, 0.675, 0, 0, 1],
    "8646": [0.1808, 0.675, 0, 0, 1],
    "8647": [0.1808, 0.675, 0, 0, 1],
    "8648": [0.19444, 0.69224, 0, 0, 0.83334],
    "8649": [0.1808, 0.675, 0, 0, 1],
    "8650": [0.19444, 0.69224, 0, 0, 0.83334],
    "8651": [0.01354, 0.52239, 0, 0, 1],
    "8652": [0.01354, 0.52239, 0, 0, 1],
    "8653": [-0.13313, 0.36687, 0, 0, 1],
    "8654": [-0.13313, 0.36687, 0, 0, 1],
    "8655": [-0.13313, 0.36687, 0, 0, 1],
    "8666": [0.13667, 0.63667, 0, 0, 1],
    "8667": [0.13667, 0.63667, 0, 0, 1],
    "8669": [-0.13313, 0.37788, 0, 0, 1],
    "8672": [-0.064, 0.437, 0, 0, 1.334],
    "8674": [-0.064, 0.437, 0, 0, 1.334],
    "8705": [0, 0.825, 0, 0, 0.5],
    "8708": [0, 0.68889, 0, 0, 0.55556],
    "8709": [0.08167, 0.58167, 0, 0, 0.77778],
    "8717": [0, 0.43056, 0, 0, 0.42917],
    "8722": [-0.03598, 0.46402, 0, 0, 0.5],
    "8724": [0.08198, 0.69224, 0, 0, 0.77778],
    "8726": [0.08167, 0.58167, 0, 0, 0.77778],
    "8733": [0, 0.69224, 0, 0, 0.77778],
    "8736": [0, 0.69224, 0, 0, 0.72222],
    "8737": [0, 0.69224, 0, 0, 0.72222],
    "8738": [0.03517, 0.52239, 0, 0, 0.72222],
    "8739": [0.08167, 0.58167, 0, 0, 0.22222],
    "8740": [0.25142, 0.74111, 0, 0, 0.27778],
    "8741": [0.08167, 0.58167, 0, 0, 0.38889],
    "8742": [0.25142, 0.74111, 0, 0, 0.5],
    "8756": [0, 0.69224, 0, 0, 0.66667],
    "8757": [0, 0.69224, 0, 0, 0.66667],
    "8764": [-0.13313, 0.36687, 0, 0, 0.77778],
    "8765": [-0.13313, 0.37788, 0, 0, 0.77778],
    "8769": [-0.13313, 0.36687, 0, 0, 0.77778],
    "8770": [-0.03625, 0.46375, 0, 0, 0.77778],
    "8774": [0.30274, 0.79383, 0, 0, 0.77778],
    "8776": [-0.01688, 0.48312, 0, 0, 0.77778],
    "8778": [0.08167, 0.58167, 0, 0, 0.77778],
    "8782": [0.06062, 0.54986, 0, 0, 0.77778],
    "8783": [0.06062, 0.54986, 0, 0, 0.77778],
    "8785": [0.08198, 0.58198, 0, 0, 0.77778],
    "8786": [0.08198, 0.58198, 0, 0, 0.77778],
    "8787": [0.08198, 0.58198, 0, 0, 0.77778],
    "8790": [0, 0.69224, 0, 0, 0.77778],
    "8791": [0.22958, 0.72958, 0, 0, 0.77778],
    "8796": [0.08198, 0.91667, 0, 0, 0.77778],
    "8806": [0.25583, 0.75583, 0, 0, 0.77778],
    "8807": [0.25583, 0.75583, 0, 0, 0.77778],
    "8808": [0.25142, 0.75726, 0, 0, 0.77778],
    "8809": [0.25142, 0.75726, 0, 0, 0.77778],
    "8812": [0.25583, 0.75583, 0, 0, 0.5],
    "8814": [0.20576, 0.70576, 0, 0, 0.77778],
    "8815": [0.20576, 0.70576, 0, 0, 0.77778],
    "8816": [0.30274, 0.79383, 0, 0, 0.77778],
    "8817": [0.30274, 0.79383, 0, 0, 0.77778],
    "8818": [0.22958, 0.72958, 0, 0, 0.77778],
    "8819": [0.22958, 0.72958, 0, 0, 0.77778],
    "8822": [0.1808, 0.675, 0, 0, 0.77778],
    "8823": [0.1808, 0.675, 0, 0, 0.77778],
    "8828": [0.13667, 0.63667, 0, 0, 0.77778],
    "8829": [0.13667, 0.63667, 0, 0, 0.77778],
    "8830": [0.22958, 0.72958, 0, 0, 0.77778],
    "8831": [0.22958, 0.72958, 0, 0, 0.77778],
    "8832": [0.20576, 0.70576, 0, 0, 0.77778],
    "8833": [0.20576, 0.70576, 0, 0, 0.77778],
    "8840": [0.30274, 0.79383, 0, 0, 0.77778],
    "8841": [0.30274, 0.79383, 0, 0, 0.77778],
    "8842": [0.13597, 0.63597, 0, 0, 0.77778],
    "8843": [0.13597, 0.63597, 0, 0, 0.77778],
    "8847": [0.03517, 0.54986, 0, 0, 0.77778],
    "8848": [0.03517, 0.54986, 0, 0, 0.77778],
    "8858": [0.08198, 0.58198, 0, 0, 0.77778],
    "8859": [0.08198, 0.58198, 0, 0, 0.77778],
    "8861": [0.08198, 0.58198, 0, 0, 0.77778],
    "8862": [0, 0.675, 0, 0, 0.77778],
    "8863": [0, 0.675, 0, 0, 0.77778],
    "8864": [0, 0.675, 0, 0, 0.77778],
    "8865": [0, 0.675, 0, 0, 0.77778],
    "8872": [0, 0.69224, 0, 0, 0.61111],
    "8873": [0, 0.69224, 0, 0, 0.72222],
    "8874": [0, 0.69224, 0, 0, 0.88889],
    "8876": [0, 0.68889, 0, 0, 0.61111],
    "8877": [0, 0.68889, 0, 0, 0.61111],
    "8878": [0, 0.68889, 0, 0, 0.72222],
    "8879": [0, 0.68889, 0, 0, 0.72222],
    "8882": [0.03517, 0.54986, 0, 0, 0.77778],
    "8883": [0.03517, 0.54986, 0, 0, 0.77778],
    "8884": [0.13667, 0.63667, 0, 0, 0.77778],
    "8885": [0.13667, 0.63667, 0, 0, 0.77778],
    "8888": [0, 0.54986, 0, 0, 1.11111],
    "8890": [0.19444, 0.43056, 0, 0, 0.55556],
    "8891": [0.19444, 0.69224, 0, 0, 0.61111],
    "8892": [0.19444, 0.69224, 0, 0, 0.61111],
    "8901": [0, 0.54986, 0, 0, 0.27778],
    "8903": [0.08167, 0.58167, 0, 0, 0.77778],
    "8905": [0.08167, 0.58167, 0, 0, 0.77778],
    "8906": [0.08167, 0.58167, 0, 0, 0.77778],
    "8907": [0, 0.69224, 0, 0, 0.77778],
    "8908": [0, 0.69224, 0, 0, 0.77778],
    "8909": [-0.03598, 0.46402, 0, 0, 0.77778],
    "8910": [0, 0.54986, 0, 0, 0.76042],
    "8911": [0, 0.54986, 0, 0, 0.76042],
    "8912": [0.03517, 0.54986, 0, 0, 0.77778],
    "8913": [0.03517, 0.54986, 0, 0, 0.77778],
    "8914": [0, 0.54986, 0, 0, 0.66667],
    "8915": [0, 0.54986, 0, 0, 0.66667],
    "8916": [0, 0.69224, 0, 0, 0.66667],
    "8918": [0.0391, 0.5391, 0, 0, 0.77778],
    "8919": [0.0391, 0.5391, 0, 0, 0.77778],
    "8920": [0.03517, 0.54986, 0, 0, 1.33334],
    "8921": [0.03517, 0.54986, 0, 0, 1.33334],
    "8922": [0.38569, 0.88569, 0, 0, 0.77778],
    "8923": [0.38569, 0.88569, 0, 0, 0.77778],
    "8926": [0.13667, 0.63667, 0, 0, 0.77778],
    "8927": [0.13667, 0.63667, 0, 0, 0.77778],
    "8928": [0.30274, 0.79383, 0, 0, 0.77778],
    "8929": [0.30274, 0.79383, 0, 0, 0.77778],
    "8934": [0.23222, 0.74111, 0, 0, 0.77778],
    "8935": [0.23222, 0.74111, 0, 0, 0.77778],
    "8936": [0.23222, 0.74111, 0, 0, 0.77778],
    "8937": [0.23222, 0.74111, 0, 0, 0.77778],
    "8938": [0.20576, 0.70576, 0, 0, 0.77778],
    "8939": [0.20576, 0.70576, 0, 0, 0.77778],
    "8940": [0.30274, 0.79383, 0, 0, 0.77778],
    "8941": [0.30274, 0.79383, 0, 0, 0.77778],
    "8994": [0.19444, 0.69224, 0, 0, 0.77778],
    "8995": [0.19444, 0.69224, 0, 0, 0.77778],
    "9416": [0.15559, 0.69224, 0, 0, 0.90222],
    "9484": [0, 0.69224, 0, 0, 0.5],
    "9488": [0, 0.69224, 0, 0, 0.5],
    "9492": [0, 0.37788, 0, 0, 0.5],
    "9496": [0, 0.37788, 0, 0, 0.5],
    "9585": [0.19444, 0.68889, 0, 0, 0.88889],
    "9586": [0.19444, 0.74111, 0, 0, 0.88889],
    "9632": [0, 0.675, 0, 0, 0.77778],
    "9633": [0, 0.675, 0, 0, 0.77778],
    "9650": [0, 0.54986, 0, 0, 0.72222],
    "9651": [0, 0.54986, 0, 0, 0.72222],
    "9654": [0.03517, 0.54986, 0, 0, 0.77778],
    "9660": [0, 0.54986, 0, 0, 0.72222],
    "9661": [0, 0.54986, 0, 0, 0.72222],
    "9664": [0.03517, 0.54986, 0, 0, 0.77778],
    "9674": [0.11111, 0.69224, 0, 0, 0.66667],
    "9733": [0.19444, 0.69224, 0, 0, 0.94445],
    "10003": [0, 0.69224, 0, 0, 0.83334],
    "10016": [0, 0.69224, 0, 0, 0.83334],
    "10731": [0.11111, 0.69224, 0, 0, 0.66667],
    "10846": [0.19444, 0.75583, 0, 0, 0.61111],
    "10877": [0.13667, 0.63667, 0, 0, 0.77778],
    "10878": [0.13667, 0.63667, 0, 0, 0.77778],
    "10885": [0.25583, 0.75583, 0, 0, 0.77778],
    "10886": [0.25583, 0.75583, 0, 0, 0.77778],
    "10887": [0.13597, 0.63597, 0, 0, 0.77778],
    "10888": [0.13597, 0.63597, 0, 0, 0.77778],
    "10889": [0.26167, 0.75726, 0, 0, 0.77778],
    "10890": [0.26167, 0.75726, 0, 0, 0.77778],
    "10891": [0.48256, 0.98256, 0, 0, 0.77778],
    "10892": [0.48256, 0.98256, 0, 0, 0.77778],
    "10901": [0.13667, 0.63667, 0, 0, 0.77778],
    "10902": [0.13667, 0.63667, 0, 0, 0.77778],
    "10933": [0.25142, 0.75726, 0, 0, 0.77778],
    "10934": [0.25142, 0.75726, 0, 0, 0.77778],
    "10935": [0.26167, 0.75726, 0, 0, 0.77778],
    "10936": [0.26167, 0.75726, 0, 0, 0.77778],
    "10937": [0.26167, 0.75726, 0, 0, 0.77778],
    "10938": [0.26167, 0.75726, 0, 0, 0.77778],
    "10949": [0.25583, 0.75583, 0, 0, 0.77778],
    "10950": [0.25583, 0.75583, 0, 0, 0.77778],
    "10955": [0.28481, 0.79383, 0, 0, 0.77778],
    "10956": [0.28481, 0.79383, 0, 0, 0.77778],
    "57350": [0.08167, 0.58167, 0, 0, 0.22222],
    "57351": [0.08167, 0.58167, 0, 0, 0.38889],
    "57352": [0.08167, 0.58167, 0, 0, 0.77778],
    "57353": [0, 0.43056, 0.04028, 0, 0.66667],
    "57356": [0.25142, 0.75726, 0, 0, 0.77778],
    "57357": [0.25142, 0.75726, 0, 0, 0.77778],
    "57358": [0.41951, 0.91951, 0, 0, 0.77778],
    "57359": [0.30274, 0.79383, 0, 0, 0.77778],
    "57360": [0.30274, 0.79383, 0, 0, 0.77778],
    "57361": [0.41951, 0.91951, 0, 0, 0.77778],
    "57366": [0.25142, 0.75726, 0, 0, 0.77778],
    "57367": [0.25142, 0.75726, 0, 0, 0.77778],
    "57368": [0.25142, 0.75726, 0, 0, 0.77778],
    "57369": [0.25142, 0.75726, 0, 0, 0.77778],
    "57370": [0.13597, 0.63597, 0, 0, 0.77778],
    "57371": [0.13597, 0.63597, 0, 0, 0.77778]
  },
  "Caligraphic-Regular": {
    "32": [0, 0, 0, 0, 0.25],
    "65": [0, 0.68333, 0, 0.19445, 0.79847],
    "66": [0, 0.68333, 0.03041, 0.13889, 0.65681],
    "67": [0, 0.68333, 0.05834, 0.13889, 0.52653],
    "68": [0, 0.68333, 0.02778, 0.08334, 0.77139],
    "69": [0, 0.68333, 0.08944, 0.11111, 0.52778],
    "70": [0, 0.68333, 0.09931, 0.11111, 0.71875],
    "71": [0.09722, 0.68333, 0.0593, 0.11111, 0.59487],
    "72": [0, 0.68333, 965e-5, 0.11111, 0.84452],
    "73": [0, 0.68333, 0.07382, 0, 0.54452],
    "74": [0.09722, 0.68333, 0.18472, 0.16667, 0.67778],
    "75": [0, 0.68333, 0.01445, 0.05556, 0.76195],
    "76": [0, 0.68333, 0, 0.13889, 0.68972],
    "77": [0, 0.68333, 0, 0.13889, 1.2009],
    "78": [0, 0.68333, 0.14736, 0.08334, 0.82049],
    "79": [0, 0.68333, 0.02778, 0.11111, 0.79611],
    "80": [0, 0.68333, 0.08222, 0.08334, 0.69556],
    "81": [0.09722, 0.68333, 0, 0.11111, 0.81667],
    "82": [0, 0.68333, 0, 0.08334, 0.8475],
    "83": [0, 0.68333, 0.075, 0.13889, 0.60556],
    "84": [0, 0.68333, 0.25417, 0, 0.54464],
    "85": [0, 0.68333, 0.09931, 0.08334, 0.62583],
    "86": [0, 0.68333, 0.08222, 0, 0.61278],
    "87": [0, 0.68333, 0.08222, 0.08334, 0.98778],
    "88": [0, 0.68333, 0.14643, 0.13889, 0.7133],
    "89": [0.09722, 0.68333, 0.08222, 0.08334, 0.66834],
    "90": [0, 0.68333, 0.07944, 0.13889, 0.72473],
    "160": [0, 0, 0, 0, 0.25]
  },
  "Fraktur-Regular": {
    "32": [0, 0, 0, 0, 0.25],
    "33": [0, 0.69141, 0, 0, 0.29574],
    "34": [0, 0.69141, 0, 0, 0.21471],
    "38": [0, 0.69141, 0, 0, 0.73786],
    "39": [0, 0.69141, 0, 0, 0.21201],
    "40": [0.24982, 0.74947, 0, 0, 0.38865],
    "41": [0.24982, 0.74947, 0, 0, 0.38865],
    "42": [0, 0.62119, 0, 0, 0.27764],
    "43": [0.08319, 0.58283, 0, 0, 0.75623],
    "44": [0, 0.10803, 0, 0, 0.27764],
    "45": [0.08319, 0.58283, 0, 0, 0.75623],
    "46": [0, 0.10803, 0, 0, 0.27764],
    "47": [0.24982, 0.74947, 0, 0, 0.50181],
    "48": [0, 0.47534, 0, 0, 0.50181],
    "49": [0, 0.47534, 0, 0, 0.50181],
    "50": [0, 0.47534, 0, 0, 0.50181],
    "51": [0.18906, 0.47534, 0, 0, 0.50181],
    "52": [0.18906, 0.47534, 0, 0, 0.50181],
    "53": [0.18906, 0.47534, 0, 0, 0.50181],
    "54": [0, 0.69141, 0, 0, 0.50181],
    "55": [0.18906, 0.47534, 0, 0, 0.50181],
    "56": [0, 0.69141, 0, 0, 0.50181],
    "57": [0.18906, 0.47534, 0, 0, 0.50181],
    "58": [0, 0.47534, 0, 0, 0.21606],
    "59": [0.12604, 0.47534, 0, 0, 0.21606],
    "61": [-0.13099, 0.36866, 0, 0, 0.75623],
    "63": [0, 0.69141, 0, 0, 0.36245],
    "65": [0, 0.69141, 0, 0, 0.7176],
    "66": [0, 0.69141, 0, 0, 0.88397],
    "67": [0, 0.69141, 0, 0, 0.61254],
    "68": [0, 0.69141, 0, 0, 0.83158],
    "69": [0, 0.69141, 0, 0, 0.66278],
    "70": [0.12604, 0.69141, 0, 0, 0.61119],
    "71": [0, 0.69141, 0, 0, 0.78539],
    "72": [0.06302, 0.69141, 0, 0, 0.7203],
    "73": [0, 0.69141, 0, 0, 0.55448],
    "74": [0.12604, 0.69141, 0, 0, 0.55231],
    "75": [0, 0.69141, 0, 0, 0.66845],
    "76": [0, 0.69141, 0, 0, 0.66602],
    "77": [0, 0.69141, 0, 0, 1.04953],
    "78": [0, 0.69141, 0, 0, 0.83212],
    "79": [0, 0.69141, 0, 0, 0.82699],
    "80": [0.18906, 0.69141, 0, 0, 0.82753],
    "81": [0.03781, 0.69141, 0, 0, 0.82699],
    "82": [0, 0.69141, 0, 0, 0.82807],
    "83": [0, 0.69141, 0, 0, 0.82861],
    "84": [0, 0.69141, 0, 0, 0.66899],
    "85": [0, 0.69141, 0, 0, 0.64576],
    "86": [0, 0.69141, 0, 0, 0.83131],
    "87": [0, 0.69141, 0, 0, 1.04602],
    "88": [0, 0.69141, 0, 0, 0.71922],
    "89": [0.18906, 0.69141, 0, 0, 0.83293],
    "90": [0.12604, 0.69141, 0, 0, 0.60201],
    "91": [0.24982, 0.74947, 0, 0, 0.27764],
    "93": [0.24982, 0.74947, 0, 0, 0.27764],
    "94": [0, 0.69141, 0, 0, 0.49965],
    "97": [0, 0.47534, 0, 0, 0.50046],
    "98": [0, 0.69141, 0, 0, 0.51315],
    "99": [0, 0.47534, 0, 0, 0.38946],
    "100": [0, 0.62119, 0, 0, 0.49857],
    "101": [0, 0.47534, 0, 0, 0.40053],
    "102": [0.18906, 0.69141, 0, 0, 0.32626],
    "103": [0.18906, 0.47534, 0, 0, 0.5037],
    "104": [0.18906, 0.69141, 0, 0, 0.52126],
    "105": [0, 0.69141, 0, 0, 0.27899],
    "106": [0, 0.69141, 0, 0, 0.28088],
    "107": [0, 0.69141, 0, 0, 0.38946],
    "108": [0, 0.69141, 0, 0, 0.27953],
    "109": [0, 0.47534, 0, 0, 0.76676],
    "110": [0, 0.47534, 0, 0, 0.52666],
    "111": [0, 0.47534, 0, 0, 0.48885],
    "112": [0.18906, 0.52396, 0, 0, 0.50046],
    "113": [0.18906, 0.47534, 0, 0, 0.48912],
    "114": [0, 0.47534, 0, 0, 0.38919],
    "115": [0, 0.47534, 0, 0, 0.44266],
    "116": [0, 0.62119, 0, 0, 0.33301],
    "117": [0, 0.47534, 0, 0, 0.5172],
    "118": [0, 0.52396, 0, 0, 0.5118],
    "119": [0, 0.52396, 0, 0, 0.77351],
    "120": [0.18906, 0.47534, 0, 0, 0.38865],
    "121": [0.18906, 0.47534, 0, 0, 0.49884],
    "122": [0.18906, 0.47534, 0, 0, 0.39054],
    "160": [0, 0, 0, 0, 0.25],
    "8216": [0, 0.69141, 0, 0, 0.21471],
    "8217": [0, 0.69141, 0, 0, 0.21471],
    "58112": [0, 0.62119, 0, 0, 0.49749],
    "58113": [0, 0.62119, 0, 0, 0.4983],
    "58114": [0.18906, 0.69141, 0, 0, 0.33328],
    "58115": [0.18906, 0.69141, 0, 0, 0.32923],
    "58116": [0.18906, 0.47534, 0, 0, 0.50343],
    "58117": [0, 0.69141, 0, 0, 0.33301],
    "58118": [0, 0.62119, 0, 0, 0.33409],
    "58119": [0, 0.47534, 0, 0, 0.50073]
  },
  "Main-Bold": {
    "32": [0, 0, 0, 0, 0.25],
    "33": [0, 0.69444, 0, 0, 0.35],
    "34": [0, 0.69444, 0, 0, 0.60278],
    "35": [0.19444, 0.69444, 0, 0, 0.95833],
    "36": [0.05556, 0.75, 0, 0, 0.575],
    "37": [0.05556, 0.75, 0, 0, 0.95833],
    "38": [0, 0.69444, 0, 0, 0.89444],
    "39": [0, 0.69444, 0, 0, 0.31944],
    "40": [0.25, 0.75, 0, 0, 0.44722],
    "41": [0.25, 0.75, 0, 0, 0.44722],
    "42": [0, 0.75, 0, 0, 0.575],
    "43": [0.13333, 0.63333, 0, 0, 0.89444],
    "44": [0.19444, 0.15556, 0, 0, 0.31944],
    "45": [0, 0.44444, 0, 0, 0.38333],
    "46": [0, 0.15556, 0, 0, 0.31944],
    "47": [0.25, 0.75, 0, 0, 0.575],
    "48": [0, 0.64444, 0, 0, 0.575],
    "49": [0, 0.64444, 0, 0, 0.575],
    "50": [0, 0.64444, 0, 0, 0.575],
    "51": [0, 0.64444, 0, 0, 0.575],
    "52": [0, 0.64444, 0, 0, 0.575],
    "53": [0, 0.64444, 0, 0, 0.575],
    "54": [0, 0.64444, 0, 0, 0.575],
    "55": [0, 0.64444, 0, 0, 0.575],
    "56": [0, 0.64444, 0, 0, 0.575],
    "57": [0, 0.64444, 0, 0, 0.575],
    "58": [0, 0.44444, 0, 0, 0.31944],
    "59": [0.19444, 0.44444, 0, 0, 0.31944],
    "60": [0.08556, 0.58556, 0, 0, 0.89444],
    "61": [-0.10889, 0.39111, 0, 0, 0.89444],
    "62": [0.08556, 0.58556, 0, 0, 0.89444],
    "63": [0, 0.69444, 0, 0, 0.54305],
    "64": [0, 0.69444, 0, 0, 0.89444],
    "65": [0, 0.68611, 0, 0, 0.86944],
    "66": [0, 0.68611, 0, 0, 0.81805],
    "67": [0, 0.68611, 0, 0, 0.83055],
    "68": [0, 0.68611, 0, 0, 0.88194],
    "69": [0, 0.68611, 0, 0, 0.75555],
    "70": [0, 0.68611, 0, 0, 0.72361],
    "71": [0, 0.68611, 0, 0, 0.90416],
    "72": [0, 0.68611, 0, 0, 0.9],
    "73": [0, 0.68611, 0, 0, 0.43611],
    "74": [0, 0.68611, 0, 0, 0.59444],
    "75": [0, 0.68611, 0, 0, 0.90138],
    "76": [0, 0.68611, 0, 0, 0.69166],
    "77": [0, 0.68611, 0, 0, 1.09166],
    "78": [0, 0.68611, 0, 0, 0.9],
    "79": [0, 0.68611, 0, 0, 0.86388],
    "80": [0, 0.68611, 0, 0, 0.78611],
    "81": [0.19444, 0.68611, 0, 0, 0.86388],
    "82": [0, 0.68611, 0, 0, 0.8625],
    "83": [0, 0.68611, 0, 0, 0.63889],
    "84": [0, 0.68611, 0, 0, 0.8],
    "85": [0, 0.68611, 0, 0, 0.88472],
    "86": [0, 0.68611, 0.01597, 0, 0.86944],
    "87": [0, 0.68611, 0.01597, 0, 1.18888],
    "88": [0, 0.68611, 0, 0, 0.86944],
    "89": [0, 0.68611, 0.02875, 0, 0.86944],
    "90": [0, 0.68611, 0, 0, 0.70277],
    "91": [0.25, 0.75, 0, 0, 0.31944],
    "92": [0.25, 0.75, 0, 0, 0.575],
    "93": [0.25, 0.75, 0, 0, 0.31944],
    "94": [0, 0.69444, 0, 0, 0.575],
    "95": [0.31, 0.13444, 0.03194, 0, 0.575],
    "97": [0, 0.44444, 0, 0, 0.55902],
    "98": [0, 0.69444, 0, 0, 0.63889],
    "99": [0, 0.44444, 0, 0, 0.51111],
    "100": [0, 0.69444, 0, 0, 0.63889],
    "101": [0, 0.44444, 0, 0, 0.52708],
    "102": [0, 0.69444, 0.10903, 0, 0.35139],
    "103": [0.19444, 0.44444, 0.01597, 0, 0.575],
    "104": [0, 0.69444, 0, 0, 0.63889],
    "105": [0, 0.69444, 0, 0, 0.31944],
    "106": [0.19444, 0.69444, 0, 0, 0.35139],
    "107": [0, 0.69444, 0, 0, 0.60694],
    "108": [0, 0.69444, 0, 0, 0.31944],
    "109": [0, 0.44444, 0, 0, 0.95833],
    "110": [0, 0.44444, 0, 0, 0.63889],
    "111": [0, 0.44444, 0, 0, 0.575],
    "112": [0.19444, 0.44444, 0, 0, 0.63889],
    "113": [0.19444, 0.44444, 0, 0, 0.60694],
    "114": [0, 0.44444, 0, 0, 0.47361],
    "115": [0, 0.44444, 0, 0, 0.45361],
    "116": [0, 0.63492, 0, 0, 0.44722],
    "117": [0, 0.44444, 0, 0, 0.63889],
    "118": [0, 0.44444, 0.01597, 0, 0.60694],
    "119": [0, 0.44444, 0.01597, 0, 0.83055],
    "120": [0, 0.44444, 0, 0, 0.60694],
    "121": [0.19444, 0.44444, 0.01597, 0, 0.60694],
    "122": [0, 0.44444, 0, 0, 0.51111],
    "123": [0.25, 0.75, 0, 0, 0.575],
    "124": [0.25, 0.75, 0, 0, 0.31944],
    "125": [0.25, 0.75, 0, 0, 0.575],
    "126": [0.35, 0.34444, 0, 0, 0.575],
    "160": [0, 0, 0, 0, 0.25],
    "163": [0, 0.69444, 0, 0, 0.86853],
    "168": [0, 0.69444, 0, 0, 0.575],
    "172": [0, 0.44444, 0, 0, 0.76666],
    "176": [0, 0.69444, 0, 0, 0.86944],
    "177": [0.13333, 0.63333, 0, 0, 0.89444],
    "184": [0.17014, 0, 0, 0, 0.51111],
    "198": [0, 0.68611, 0, 0, 1.04166],
    "215": [0.13333, 0.63333, 0, 0, 0.89444],
    "216": [0.04861, 0.73472, 0, 0, 0.89444],
    "223": [0, 0.69444, 0, 0, 0.59722],
    "230": [0, 0.44444, 0, 0, 0.83055],
    "247": [0.13333, 0.63333, 0, 0, 0.89444],
    "248": [0.09722, 0.54167, 0, 0, 0.575],
    "305": [0, 0.44444, 0, 0, 0.31944],
    "338": [0, 0.68611, 0, 0, 1.16944],
    "339": [0, 0.44444, 0, 0, 0.89444],
    "567": [0.19444, 0.44444, 0, 0, 0.35139],
    "710": [0, 0.69444, 0, 0, 0.575],
    "711": [0, 0.63194, 0, 0, 0.575],
    "713": [0, 0.59611, 0, 0, 0.575],
    "714": [0, 0.69444, 0, 0, 0.575],
    "715": [0, 0.69444, 0, 0, 0.575],
    "728": [0, 0.69444, 0, 0, 0.575],
    "729": [0, 0.69444, 0, 0, 0.31944],
    "730": [0, 0.69444, 0, 0, 0.86944],
    "732": [0, 0.69444, 0, 0, 0.575],
    "733": [0, 0.69444, 0, 0, 0.575],
    "915": [0, 0.68611, 0, 0, 0.69166],
    "916": [0, 0.68611, 0, 0, 0.95833],
    "920": [0, 0.68611, 0, 0, 0.89444],
    "923": [0, 0.68611, 0, 0, 0.80555],
    "926": [0, 0.68611, 0, 0, 0.76666],
    "928": [0, 0.68611, 0, 0, 0.9],
    "931": [0, 0.68611, 0, 0, 0.83055],
    "933": [0, 0.68611, 0, 0, 0.89444],
    "934": [0, 0.68611, 0, 0, 0.83055],
    "936": [0, 0.68611, 0, 0, 0.89444],
    "937": [0, 0.68611, 0, 0, 0.83055],
    "8211": [0, 0.44444, 0.03194, 0, 0.575],
    "8212": [0, 0.44444, 0.03194, 0, 1.14999],
    "8216": [0, 0.69444, 0, 0, 0.31944],
    "8217": [0, 0.69444, 0, 0, 0.31944],
    "8220": [0, 0.69444, 0, 0, 0.60278],
    "8221": [0, 0.69444, 0, 0, 0.60278],
    "8224": [0.19444, 0.69444, 0, 0, 0.51111],
    "8225": [0.19444, 0.69444, 0, 0, 0.51111],
    "8242": [0, 0.55556, 0, 0, 0.34444],
    "8407": [0, 0.72444, 0.15486, 0, 0.575],
    "8463": [0, 0.69444, 0, 0, 0.66759],
    "8465": [0, 0.69444, 0, 0, 0.83055],
    "8467": [0, 0.69444, 0, 0, 0.47361],
    "8472": [0.19444, 0.44444, 0, 0, 0.74027],
    "8476": [0, 0.69444, 0, 0, 0.83055],
    "8501": [0, 0.69444, 0, 0, 0.70277],
    "8592": [-0.10889, 0.39111, 0, 0, 1.14999],
    "8593": [0.19444, 0.69444, 0, 0, 0.575],
    "8594": [-0.10889, 0.39111, 0, 0, 1.14999],
    "8595": [0.19444, 0.69444, 0, 0, 0.575],
    "8596": [-0.10889, 0.39111, 0, 0, 1.14999],
    "8597": [0.25, 0.75, 0, 0, 0.575],
    "8598": [0.19444, 0.69444, 0, 0, 1.14999],
    "8599": [0.19444, 0.69444, 0, 0, 1.14999],
    "8600": [0.19444, 0.69444, 0, 0, 1.14999],
    "8601": [0.19444, 0.69444, 0, 0, 1.14999],
    "8636": [-0.10889, 0.39111, 0, 0, 1.14999],
    "8637": [-0.10889, 0.39111, 0, 0, 1.14999],
    "8640": [-0.10889, 0.39111, 0, 0, 1.14999],
    "8641": [-0.10889, 0.39111, 0, 0, 1.14999],
    "8656": [-0.10889, 0.39111, 0, 0, 1.14999],
    "8657": [0.19444, 0.69444, 0, 0, 0.70277],
    "8658": [-0.10889, 0.39111, 0, 0, 1.14999],
    "8659": [0.19444, 0.69444, 0, 0, 0.70277],
    "8660": [-0.10889, 0.39111, 0, 0, 1.14999],
    "8661": [0.25, 0.75, 0, 0, 0.70277],
    "8704": [0, 0.69444, 0, 0, 0.63889],
    "8706": [0, 0.69444, 0.06389, 0, 0.62847],
    "8707": [0, 0.69444, 0, 0, 0.63889],
    "8709": [0.05556, 0.75, 0, 0, 0.575],
    "8711": [0, 0.68611, 0, 0, 0.95833],
    "8712": [0.08556, 0.58556, 0, 0, 0.76666],
    "8715": [0.08556, 0.58556, 0, 0, 0.76666],
    "8722": [0.13333, 0.63333, 0, 0, 0.89444],
    "8723": [0.13333, 0.63333, 0, 0, 0.89444],
    "8725": [0.25, 0.75, 0, 0, 0.575],
    "8726": [0.25, 0.75, 0, 0, 0.575],
    "8727": [-0.02778, 0.47222, 0, 0, 0.575],
    "8728": [-0.02639, 0.47361, 0, 0, 0.575],
    "8729": [-0.02639, 0.47361, 0, 0, 0.575],
    "8730": [0.18, 0.82, 0, 0, 0.95833],
    "8733": [0, 0.44444, 0, 0, 0.89444],
    "8734": [0, 0.44444, 0, 0, 1.14999],
    "8736": [0, 0.69224, 0, 0, 0.72222],
    "8739": [0.25, 0.75, 0, 0, 0.31944],
    "8741": [0.25, 0.75, 0, 0, 0.575],
    "8743": [0, 0.55556, 0, 0, 0.76666],
    "8744": [0, 0.55556, 0, 0, 0.76666],
    "8745": [0, 0.55556, 0, 0, 0.76666],
    "8746": [0, 0.55556, 0, 0, 0.76666],
    "8747": [0.19444, 0.69444, 0.12778, 0, 0.56875],
    "8764": [-0.10889, 0.39111, 0, 0, 0.89444],
    "8768": [0.19444, 0.69444, 0, 0, 0.31944],
    "8771": [222e-5, 0.50222, 0, 0, 0.89444],
    "8773": [0.027, 0.638, 0, 0, 0.894],
    "8776": [0.02444, 0.52444, 0, 0, 0.89444],
    "8781": [222e-5, 0.50222, 0, 0, 0.89444],
    "8801": [222e-5, 0.50222, 0, 0, 0.89444],
    "8804": [0.19667, 0.69667, 0, 0, 0.89444],
    "8805": [0.19667, 0.69667, 0, 0, 0.89444],
    "8810": [0.08556, 0.58556, 0, 0, 1.14999],
    "8811": [0.08556, 0.58556, 0, 0, 1.14999],
    "8826": [0.08556, 0.58556, 0, 0, 0.89444],
    "8827": [0.08556, 0.58556, 0, 0, 0.89444],
    "8834": [0.08556, 0.58556, 0, 0, 0.89444],
    "8835": [0.08556, 0.58556, 0, 0, 0.89444],
    "8838": [0.19667, 0.69667, 0, 0, 0.89444],
    "8839": [0.19667, 0.69667, 0, 0, 0.89444],
    "8846": [0, 0.55556, 0, 0, 0.76666],
    "8849": [0.19667, 0.69667, 0, 0, 0.89444],
    "8850": [0.19667, 0.69667, 0, 0, 0.89444],
    "8851": [0, 0.55556, 0, 0, 0.76666],
    "8852": [0, 0.55556, 0, 0, 0.76666],
    "8853": [0.13333, 0.63333, 0, 0, 0.89444],
    "8854": [0.13333, 0.63333, 0, 0, 0.89444],
    "8855": [0.13333, 0.63333, 0, 0, 0.89444],
    "8856": [0.13333, 0.63333, 0, 0, 0.89444],
    "8857": [0.13333, 0.63333, 0, 0, 0.89444],
    "8866": [0, 0.69444, 0, 0, 0.70277],
    "8867": [0, 0.69444, 0, 0, 0.70277],
    "8868": [0, 0.69444, 0, 0, 0.89444],
    "8869": [0, 0.69444, 0, 0, 0.89444],
    "8900": [-0.02639, 0.47361, 0, 0, 0.575],
    "8901": [-0.02639, 0.47361, 0, 0, 0.31944],
    "8902": [-0.02778, 0.47222, 0, 0, 0.575],
    "8968": [0.25, 0.75, 0, 0, 0.51111],
    "8969": [0.25, 0.75, 0, 0, 0.51111],
    "8970": [0.25, 0.75, 0, 0, 0.51111],
    "8971": [0.25, 0.75, 0, 0, 0.51111],
    "8994": [-0.13889, 0.36111, 0, 0, 1.14999],
    "8995": [-0.13889, 0.36111, 0, 0, 1.14999],
    "9651": [0.19444, 0.69444, 0, 0, 1.02222],
    "9657": [-0.02778, 0.47222, 0, 0, 0.575],
    "9661": [0.19444, 0.69444, 0, 0, 1.02222],
    "9667": [-0.02778, 0.47222, 0, 0, 0.575],
    "9711": [0.19444, 0.69444, 0, 0, 1.14999],
    "9824": [0.12963, 0.69444, 0, 0, 0.89444],
    "9825": [0.12963, 0.69444, 0, 0, 0.89444],
    "9826": [0.12963, 0.69444, 0, 0, 0.89444],
    "9827": [0.12963, 0.69444, 0, 0, 0.89444],
    "9837": [0, 0.75, 0, 0, 0.44722],
    "9838": [0.19444, 0.69444, 0, 0, 0.44722],
    "9839": [0.19444, 0.69444, 0, 0, 0.44722],
    "10216": [0.25, 0.75, 0, 0, 0.44722],
    "10217": [0.25, 0.75, 0, 0, 0.44722],
    "10815": [0, 0.68611, 0, 0, 0.9],
    "10927": [0.19667, 0.69667, 0, 0, 0.89444],
    "10928": [0.19667, 0.69667, 0, 0, 0.89444],
    "57376": [0.19444, 0.69444, 0, 0, 0]
  },
  "Main-BoldItalic": {
    "32": [0, 0, 0, 0, 0.25],
    "33": [0, 0.69444, 0.11417, 0, 0.38611],
    "34": [0, 0.69444, 0.07939, 0, 0.62055],
    "35": [0.19444, 0.69444, 0.06833, 0, 0.94444],
    "37": [0.05556, 0.75, 0.12861, 0, 0.94444],
    "38": [0, 0.69444, 0.08528, 0, 0.88555],
    "39": [0, 0.69444, 0.12945, 0, 0.35555],
    "40": [0.25, 0.75, 0.15806, 0, 0.47333],
    "41": [0.25, 0.75, 0.03306, 0, 0.47333],
    "42": [0, 0.75, 0.14333, 0, 0.59111],
    "43": [0.10333, 0.60333, 0.03306, 0, 0.88555],
    "44": [0.19444, 0.14722, 0, 0, 0.35555],
    "45": [0, 0.44444, 0.02611, 0, 0.41444],
    "46": [0, 0.14722, 0, 0, 0.35555],
    "47": [0.25, 0.75, 0.15806, 0, 0.59111],
    "48": [0, 0.64444, 0.13167, 0, 0.59111],
    "49": [0, 0.64444, 0.13167, 0, 0.59111],
    "50": [0, 0.64444, 0.13167, 0, 0.59111],
    "51": [0, 0.64444, 0.13167, 0, 0.59111],
    "52": [0.19444, 0.64444, 0.13167, 0, 0.59111],
    "53": [0, 0.64444, 0.13167, 0, 0.59111],
    "54": [0, 0.64444, 0.13167, 0, 0.59111],
    "55": [0.19444, 0.64444, 0.13167, 0, 0.59111],
    "56": [0, 0.64444, 0.13167, 0, 0.59111],
    "57": [0, 0.64444, 0.13167, 0, 0.59111],
    "58": [0, 0.44444, 0.06695, 0, 0.35555],
    "59": [0.19444, 0.44444, 0.06695, 0, 0.35555],
    "61": [-0.10889, 0.39111, 0.06833, 0, 0.88555],
    "63": [0, 0.69444, 0.11472, 0, 0.59111],
    "64": [0, 0.69444, 0.09208, 0, 0.88555],
    "65": [0, 0.68611, 0, 0, 0.86555],
    "66": [0, 0.68611, 0.0992, 0, 0.81666],
    "67": [0, 0.68611, 0.14208, 0, 0.82666],
    "68": [0, 0.68611, 0.09062, 0, 0.87555],
    "69": [0, 0.68611, 0.11431, 0, 0.75666],
    "70": [0, 0.68611, 0.12903, 0, 0.72722],
    "71": [0, 0.68611, 0.07347, 0, 0.89527],
    "72": [0, 0.68611, 0.17208, 0, 0.8961],
    "73": [0, 0.68611, 0.15681, 0, 0.47166],
    "74": [0, 0.68611, 0.145, 0, 0.61055],
    "75": [0, 0.68611, 0.14208, 0, 0.89499],
    "76": [0, 0.68611, 0, 0, 0.69777],
    "77": [0, 0.68611, 0.17208, 0, 1.07277],
    "78": [0, 0.68611, 0.17208, 0, 0.8961],
    "79": [0, 0.68611, 0.09062, 0, 0.85499],
    "80": [0, 0.68611, 0.0992, 0, 0.78721],
    "81": [0.19444, 0.68611, 0.09062, 0, 0.85499],
    "82": [0, 0.68611, 0.02559, 0, 0.85944],
    "83": [0, 0.68611, 0.11264, 0, 0.64999],
    "84": [0, 0.68611, 0.12903, 0, 0.7961],
    "85": [0, 0.68611, 0.17208, 0, 0.88083],
    "86": [0, 0.68611, 0.18625, 0, 0.86555],
    "87": [0, 0.68611, 0.18625, 0, 1.15999],
    "88": [0, 0.68611, 0.15681, 0, 0.86555],
    "89": [0, 0.68611, 0.19803, 0, 0.86555],
    "90": [0, 0.68611, 0.14208, 0, 0.70888],
    "91": [0.25, 0.75, 0.1875, 0, 0.35611],
    "93": [0.25, 0.75, 0.09972, 0, 0.35611],
    "94": [0, 0.69444, 0.06709, 0, 0.59111],
    "95": [0.31, 0.13444, 0.09811, 0, 0.59111],
    "97": [0, 0.44444, 0.09426, 0, 0.59111],
    "98": [0, 0.69444, 0.07861, 0, 0.53222],
    "99": [0, 0.44444, 0.05222, 0, 0.53222],
    "100": [0, 0.69444, 0.10861, 0, 0.59111],
    "101": [0, 0.44444, 0.085, 0, 0.53222],
    "102": [0.19444, 0.69444, 0.21778, 0, 0.4],
    "103": [0.19444, 0.44444, 0.105, 0, 0.53222],
    "104": [0, 0.69444, 0.09426, 0, 0.59111],
    "105": [0, 0.69326, 0.11387, 0, 0.35555],
    "106": [0.19444, 0.69326, 0.1672, 0, 0.35555],
    "107": [0, 0.69444, 0.11111, 0, 0.53222],
    "108": [0, 0.69444, 0.10861, 0, 0.29666],
    "109": [0, 0.44444, 0.09426, 0, 0.94444],
    "110": [0, 0.44444, 0.09426, 0, 0.64999],
    "111": [0, 0.44444, 0.07861, 0, 0.59111],
    "112": [0.19444, 0.44444, 0.07861, 0, 0.59111],
    "113": [0.19444, 0.44444, 0.105, 0, 0.53222],
    "114": [0, 0.44444, 0.11111, 0, 0.50167],
    "115": [0, 0.44444, 0.08167, 0, 0.48694],
    "116": [0, 0.63492, 0.09639, 0, 0.385],
    "117": [0, 0.44444, 0.09426, 0, 0.62055],
    "118": [0, 0.44444, 0.11111, 0, 0.53222],
    "119": [0, 0.44444, 0.11111, 0, 0.76777],
    "120": [0, 0.44444, 0.12583, 0, 0.56055],
    "121": [0.19444, 0.44444, 0.105, 0, 0.56166],
    "122": [0, 0.44444, 0.13889, 0, 0.49055],
    "126": [0.35, 0.34444, 0.11472, 0, 0.59111],
    "160": [0, 0, 0, 0, 0.25],
    "168": [0, 0.69444, 0.11473, 0, 0.59111],
    "176": [0, 0.69444, 0, 0, 0.94888],
    "184": [0.17014, 0, 0, 0, 0.53222],
    "198": [0, 0.68611, 0.11431, 0, 1.02277],
    "216": [0.04861, 0.73472, 0.09062, 0, 0.88555],
    "223": [0.19444, 0.69444, 0.09736, 0, 0.665],
    "230": [0, 0.44444, 0.085, 0, 0.82666],
    "248": [0.09722, 0.54167, 0.09458, 0, 0.59111],
    "305": [0, 0.44444, 0.09426, 0, 0.35555],
    "338": [0, 0.68611, 0.11431, 0, 1.14054],
    "339": [0, 0.44444, 0.085, 0, 0.82666],
    "567": [0.19444, 0.44444, 0.04611, 0, 0.385],
    "710": [0, 0.69444, 0.06709, 0, 0.59111],
    "711": [0, 0.63194, 0.08271, 0, 0.59111],
    "713": [0, 0.59444, 0.10444, 0, 0.59111],
    "714": [0, 0.69444, 0.08528, 0, 0.59111],
    "715": [0, 0.69444, 0, 0, 0.59111],
    "728": [0, 0.69444, 0.10333, 0, 0.59111],
    "729": [0, 0.69444, 0.12945, 0, 0.35555],
    "730": [0, 0.69444, 0, 0, 0.94888],
    "732": [0, 0.69444, 0.11472, 0, 0.59111],
    "733": [0, 0.69444, 0.11472, 0, 0.59111],
    "915": [0, 0.68611, 0.12903, 0, 0.69777],
    "916": [0, 0.68611, 0, 0, 0.94444],
    "920": [0, 0.68611, 0.09062, 0, 0.88555],
    "923": [0, 0.68611, 0, 0, 0.80666],
    "926": [0, 0.68611, 0.15092, 0, 0.76777],
    "928": [0, 0.68611, 0.17208, 0, 0.8961],
    "931": [0, 0.68611, 0.11431, 0, 0.82666],
    "933": [0, 0.68611, 0.10778, 0, 0.88555],
    "934": [0, 0.68611, 0.05632, 0, 0.82666],
    "936": [0, 0.68611, 0.10778, 0, 0.88555],
    "937": [0, 0.68611, 0.0992, 0, 0.82666],
    "8211": [0, 0.44444, 0.09811, 0, 0.59111],
    "8212": [0, 0.44444, 0.09811, 0, 1.18221],
    "8216": [0, 0.69444, 0.12945, 0, 0.35555],
    "8217": [0, 0.69444, 0.12945, 0, 0.35555],
    "8220": [0, 0.69444, 0.16772, 0, 0.62055],
    "8221": [0, 0.69444, 0.07939, 0, 0.62055]
  },
  "Main-Italic": {
    "32": [0, 0, 0, 0, 0.25],
    "33": [0, 0.69444, 0.12417, 0, 0.30667],
    "34": [0, 0.69444, 0.06961, 0, 0.51444],
    "35": [0.19444, 0.69444, 0.06616, 0, 0.81777],
    "37": [0.05556, 0.75, 0.13639, 0, 0.81777],
    "38": [0, 0.69444, 0.09694, 0, 0.76666],
    "39": [0, 0.69444, 0.12417, 0, 0.30667],
    "40": [0.25, 0.75, 0.16194, 0, 0.40889],
    "41": [0.25, 0.75, 0.03694, 0, 0.40889],
    "42": [0, 0.75, 0.14917, 0, 0.51111],
    "43": [0.05667, 0.56167, 0.03694, 0, 0.76666],
    "44": [0.19444, 0.10556, 0, 0, 0.30667],
    "45": [0, 0.43056, 0.02826, 0, 0.35778],
    "46": [0, 0.10556, 0, 0, 0.30667],
    "47": [0.25, 0.75, 0.16194, 0, 0.51111],
    "48": [0, 0.64444, 0.13556, 0, 0.51111],
    "49": [0, 0.64444, 0.13556, 0, 0.51111],
    "50": [0, 0.64444, 0.13556, 0, 0.51111],
    "51": [0, 0.64444, 0.13556, 0, 0.51111],
    "52": [0.19444, 0.64444, 0.13556, 0, 0.51111],
    "53": [0, 0.64444, 0.13556, 0, 0.51111],
    "54": [0, 0.64444, 0.13556, 0, 0.51111],
    "55": [0.19444, 0.64444, 0.13556, 0, 0.51111],
    "56": [0, 0.64444, 0.13556, 0, 0.51111],
    "57": [0, 0.64444, 0.13556, 0, 0.51111],
    "58": [0, 0.43056, 0.0582, 0, 0.30667],
    "59": [0.19444, 0.43056, 0.0582, 0, 0.30667],
    "61": [-0.13313, 0.36687, 0.06616, 0, 0.76666],
    "63": [0, 0.69444, 0.1225, 0, 0.51111],
    "64": [0, 0.69444, 0.09597, 0, 0.76666],
    "65": [0, 0.68333, 0, 0, 0.74333],
    "66": [0, 0.68333, 0.10257, 0, 0.70389],
    "67": [0, 0.68333, 0.14528, 0, 0.71555],
    "68": [0, 0.68333, 0.09403, 0, 0.755],
    "69": [0, 0.68333, 0.12028, 0, 0.67833],
    "70": [0, 0.68333, 0.13305, 0, 0.65277],
    "71": [0, 0.68333, 0.08722, 0, 0.77361],
    "72": [0, 0.68333, 0.16389, 0, 0.74333],
    "73": [0, 0.68333, 0.15806, 0, 0.38555],
    "74": [0, 0.68333, 0.14028, 0, 0.525],
    "75": [0, 0.68333, 0.14528, 0, 0.76888],
    "76": [0, 0.68333, 0, 0, 0.62722],
    "77": [0, 0.68333, 0.16389, 0, 0.89666],
    "78": [0, 0.68333, 0.16389, 0, 0.74333],
    "79": [0, 0.68333, 0.09403, 0, 0.76666],
    "80": [0, 0.68333, 0.10257, 0, 0.67833],
    "81": [0.19444, 0.68333, 0.09403, 0, 0.76666],
    "82": [0, 0.68333, 0.03868, 0, 0.72944],
    "83": [0, 0.68333, 0.11972, 0, 0.56222],
    "84": [0, 0.68333, 0.13305, 0, 0.71555],
    "85": [0, 0.68333, 0.16389, 0, 0.74333],
    "86": [0, 0.68333, 0.18361, 0, 0.74333],
    "87": [0, 0.68333, 0.18361, 0, 0.99888],
    "88": [0, 0.68333, 0.15806, 0, 0.74333],
    "89": [0, 0.68333, 0.19383, 0, 0.74333],
    "90": [0, 0.68333, 0.14528, 0, 0.61333],
    "91": [0.25, 0.75, 0.1875, 0, 0.30667],
    "93": [0.25, 0.75, 0.10528, 0, 0.30667],
    "94": [0, 0.69444, 0.06646, 0, 0.51111],
    "95": [0.31, 0.12056, 0.09208, 0, 0.51111],
    "97": [0, 0.43056, 0.07671, 0, 0.51111],
    "98": [0, 0.69444, 0.06312, 0, 0.46],
    "99": [0, 0.43056, 0.05653, 0, 0.46],
    "100": [0, 0.69444, 0.10333, 0, 0.51111],
    "101": [0, 0.43056, 0.07514, 0, 0.46],
    "102": [0.19444, 0.69444, 0.21194, 0, 0.30667],
    "103": [0.19444, 0.43056, 0.08847, 0, 0.46],
    "104": [0, 0.69444, 0.07671, 0, 0.51111],
    "105": [0, 0.65536, 0.1019, 0, 0.30667],
    "106": [0.19444, 0.65536, 0.14467, 0, 0.30667],
    "107": [0, 0.69444, 0.10764, 0, 0.46],
    "108": [0, 0.69444, 0.10333, 0, 0.25555],
    "109": [0, 0.43056, 0.07671, 0, 0.81777],
    "110": [0, 0.43056, 0.07671, 0, 0.56222],
    "111": [0, 0.43056, 0.06312, 0, 0.51111],
    "112": [0.19444, 0.43056, 0.06312, 0, 0.51111],
    "113": [0.19444, 0.43056, 0.08847, 0, 0.46],
    "114": [0, 0.43056, 0.10764, 0, 0.42166],
    "115": [0, 0.43056, 0.08208, 0, 0.40889],
    "116": [0, 0.61508, 0.09486, 0, 0.33222],
    "117": [0, 0.43056, 0.07671, 0, 0.53666],
    "118": [0, 0.43056, 0.10764, 0, 0.46],
    "119": [0, 0.43056, 0.10764, 0, 0.66444],
    "120": [0, 0.43056, 0.12042, 0, 0.46389],
    "121": [0.19444, 0.43056, 0.08847, 0, 0.48555],
    "122": [0, 0.43056, 0.12292, 0, 0.40889],
    "126": [0.35, 0.31786, 0.11585, 0, 0.51111],
    "160": [0, 0, 0, 0, 0.25],
    "168": [0, 0.66786, 0.10474, 0, 0.51111],
    "176": [0, 0.69444, 0, 0, 0.83129],
    "184": [0.17014, 0, 0, 0, 0.46],
    "198": [0, 0.68333, 0.12028, 0, 0.88277],
    "216": [0.04861, 0.73194, 0.09403, 0, 0.76666],
    "223": [0.19444, 0.69444, 0.10514, 0, 0.53666],
    "230": [0, 0.43056, 0.07514, 0, 0.71555],
    "248": [0.09722, 0.52778, 0.09194, 0, 0.51111],
    "338": [0, 0.68333, 0.12028, 0, 0.98499],
    "339": [0, 0.43056, 0.07514, 0, 0.71555],
    "710": [0, 0.69444, 0.06646, 0, 0.51111],
    "711": [0, 0.62847, 0.08295, 0, 0.51111],
    "713": [0, 0.56167, 0.10333, 0, 0.51111],
    "714": [0, 0.69444, 0.09694, 0, 0.51111],
    "715": [0, 0.69444, 0, 0, 0.51111],
    "728": [0, 0.69444, 0.10806, 0, 0.51111],
    "729": [0, 0.66786, 0.11752, 0, 0.30667],
    "730": [0, 0.69444, 0, 0, 0.83129],
    "732": [0, 0.66786, 0.11585, 0, 0.51111],
    "733": [0, 0.69444, 0.1225, 0, 0.51111],
    "915": [0, 0.68333, 0.13305, 0, 0.62722],
    "916": [0, 0.68333, 0, 0, 0.81777],
    "920": [0, 0.68333, 0.09403, 0, 0.76666],
    "923": [0, 0.68333, 0, 0, 0.69222],
    "926": [0, 0.68333, 0.15294, 0, 0.66444],
    "928": [0, 0.68333, 0.16389, 0, 0.74333],
    "931": [0, 0.68333, 0.12028, 0, 0.71555],
    "933": [0, 0.68333, 0.11111, 0, 0.76666],
    "934": [0, 0.68333, 0.05986, 0, 0.71555],
    "936": [0, 0.68333, 0.11111, 0, 0.76666],
    "937": [0, 0.68333, 0.10257, 0, 0.71555],
    "8211": [0, 0.43056, 0.09208, 0, 0.51111],
    "8212": [0, 0.43056, 0.09208, 0, 1.02222],
    "8216": [0, 0.69444, 0.12417, 0, 0.30667],
    "8217": [0, 0.69444, 0.12417, 0, 0.30667],
    "8220": [0, 0.69444, 0.1685, 0, 0.51444],
    "8221": [0, 0.69444, 0.06961, 0, 0.51444],
    "8463": [0, 0.68889, 0, 0, 0.54028]
  },
  "Main-Regular": {
    "32": [0, 0, 0, 0, 0.25],
    "33": [0, 0.69444, 0, 0, 0.27778],
    "34": [0, 0.69444, 0, 0, 0.5],
    "35": [0.19444, 0.69444, 0, 0, 0.83334],
    "36": [0.05556, 0.75, 0, 0, 0.5],
    "37": [0.05556, 0.75, 0, 0, 0.83334],
    "38": [0, 0.69444, 0, 0, 0.77778],
    "39": [0, 0.69444, 0, 0, 0.27778],
    "40": [0.25, 0.75, 0, 0, 0.38889],
    "41": [0.25, 0.75, 0, 0, 0.38889],
    "42": [0, 0.75, 0, 0, 0.5],
    "43": [0.08333, 0.58333, 0, 0, 0.77778],
    "44": [0.19444, 0.10556, 0, 0, 0.27778],
    "45": [0, 0.43056, 0, 0, 0.33333],
    "46": [0, 0.10556, 0, 0, 0.27778],
    "47": [0.25, 0.75, 0, 0, 0.5],
    "48": [0, 0.64444, 0, 0, 0.5],
    "49": [0, 0.64444, 0, 0, 0.5],
    "50": [0, 0.64444, 0, 0, 0.5],
    "51": [0, 0.64444, 0, 0, 0.5],
    "52": [0, 0.64444, 0, 0, 0.5],
    "53": [0, 0.64444, 0, 0, 0.5],
    "54": [0, 0.64444, 0, 0, 0.5],
    "55": [0, 0.64444, 0, 0, 0.5],
    "56": [0, 0.64444, 0, 0, 0.5],
    "57": [0, 0.64444, 0, 0, 0.5],
    "58": [0, 0.43056, 0, 0, 0.27778],
    "59": [0.19444, 0.43056, 0, 0, 0.27778],
    "60": [0.0391, 0.5391, 0, 0, 0.77778],
    "61": [-0.13313, 0.36687, 0, 0, 0.77778],
    "62": [0.0391, 0.5391, 0, 0, 0.77778],
    "63": [0, 0.69444, 0, 0, 0.47222],
    "64": [0, 0.69444, 0, 0, 0.77778],
    "65": [0, 0.68333, 0, 0, 0.75],
    "66": [0, 0.68333, 0, 0, 0.70834],
    "67": [0, 0.68333, 0, 0, 0.72222],
    "68": [0, 0.68333, 0, 0, 0.76389],
    "69": [0, 0.68333, 0, 0, 0.68056],
    "70": [0, 0.68333, 0, 0, 0.65278],
    "71": [0, 0.68333, 0, 0, 0.78472],
    "72": [0, 0.68333, 0, 0, 0.75],
    "73": [0, 0.68333, 0, 0, 0.36111],
    "74": [0, 0.68333, 0, 0, 0.51389],
    "75": [0, 0.68333, 0, 0, 0.77778],
    "76": [0, 0.68333, 0, 0, 0.625],
    "77": [0, 0.68333, 0, 0, 0.91667],
    "78": [0, 0.68333, 0, 0, 0.75],
    "79": [0, 0.68333, 0, 0, 0.77778],
    "80": [0, 0.68333, 0, 0, 0.68056],
    "81": [0.19444, 0.68333, 0, 0, 0.77778],
    "82": [0, 0.68333, 0, 0, 0.73611],
    "83": [0, 0.68333, 0, 0, 0.55556],
    "84": [0, 0.68333, 0, 0, 0.72222],
    "85": [0, 0.68333, 0, 0, 0.75],
    "86": [0, 0.68333, 0.01389, 0, 0.75],
    "87": [0, 0.68333, 0.01389, 0, 1.02778],
    "88": [0, 0.68333, 0, 0, 0.75],
    "89": [0, 0.68333, 0.025, 0, 0.75],
    "90": [0, 0.68333, 0, 0, 0.61111],
    "91": [0.25, 0.75, 0, 0, 0.27778],
    "92": [0.25, 0.75, 0, 0, 0.5],
    "93": [0.25, 0.75, 0, 0, 0.27778],
    "94": [0, 0.69444, 0, 0, 0.5],
    "95": [0.31, 0.12056, 0.02778, 0, 0.5],
    "97": [0, 0.43056, 0, 0, 0.5],
    "98": [0, 0.69444, 0, 0, 0.55556],
    "99": [0, 0.43056, 0, 0, 0.44445],
    "100": [0, 0.69444, 0, 0, 0.55556],
    "101": [0, 0.43056, 0, 0, 0.44445],
    "102": [0, 0.69444, 0.07778, 0, 0.30556],
    "103": [0.19444, 0.43056, 0.01389, 0, 0.5],
    "104": [0, 0.69444, 0, 0, 0.55556],
    "105": [0, 0.66786, 0, 0, 0.27778],
    "106": [0.19444, 0.66786, 0, 0, 0.30556],
    "107": [0, 0.69444, 0, 0, 0.52778],
    "108": [0, 0.69444, 0, 0, 0.27778],
    "109": [0, 0.43056, 0, 0, 0.83334],
    "110": [0, 0.43056, 0, 0, 0.55556],
    "111": [0, 0.43056, 0, 0, 0.5],
    "112": [0.19444, 0.43056, 0, 0, 0.55556],
    "113": [0.19444, 0.43056, 0, 0, 0.52778],
    "114": [0, 0.43056, 0, 0, 0.39167],
    "115": [0, 0.43056, 0, 0, 0.39445],
    "116": [0, 0.61508, 0, 0, 0.38889],
    "117": [0, 0.43056, 0, 0, 0.55556],
    "118": [0, 0.43056, 0.01389, 0, 0.52778],
    "119": [0, 0.43056, 0.01389, 0, 0.72222],
    "120": [0, 0.43056, 0, 0, 0.52778],
    "121": [0.19444, 0.43056, 0.01389, 0, 0.52778],
    "122": [0, 0.43056, 0, 0, 0.44445],
    "123": [0.25, 0.75, 0, 0, 0.5],
    "124": [0.25, 0.75, 0, 0, 0.27778],
    "125": [0.25, 0.75, 0, 0, 0.5],
    "126": [0.35, 0.31786, 0, 0, 0.5],
    "160": [0, 0, 0, 0, 0.25],
    "163": [0, 0.69444, 0, 0, 0.76909],
    "167": [0.19444, 0.69444, 0, 0, 0.44445],
    "168": [0, 0.66786, 0, 0, 0.5],
    "172": [0, 0.43056, 0, 0, 0.66667],
    "176": [0, 0.69444, 0, 0, 0.75],
    "177": [0.08333, 0.58333, 0, 0, 0.77778],
    "182": [0.19444, 0.69444, 0, 0, 0.61111],
    "184": [0.17014, 0, 0, 0, 0.44445],
    "198": [0, 0.68333, 0, 0, 0.90278],
    "215": [0.08333, 0.58333, 0, 0, 0.77778],
    "216": [0.04861, 0.73194, 0, 0, 0.77778],
    "223": [0, 0.69444, 0, 0, 0.5],
    "230": [0, 0.43056, 0, 0, 0.72222],
    "247": [0.08333, 0.58333, 0, 0, 0.77778],
    "248": [0.09722, 0.52778, 0, 0, 0.5],
    "305": [0, 0.43056, 0, 0, 0.27778],
    "338": [0, 0.68333, 0, 0, 1.01389],
    "339": [0, 0.43056, 0, 0, 0.77778],
    "567": [0.19444, 0.43056, 0, 0, 0.30556],
    "710": [0, 0.69444, 0, 0, 0.5],
    "711": [0, 0.62847, 0, 0, 0.5],
    "713": [0, 0.56778, 0, 0, 0.5],
    "714": [0, 0.69444, 0, 0, 0.5],
    "715": [0, 0.69444, 0, 0, 0.5],
    "728": [0, 0.69444, 0, 0, 0.5],
    "729": [0, 0.66786, 0, 0, 0.27778],
    "730": [0, 0.69444, 0, 0, 0.75],
    "732": [0, 0.66786, 0, 0, 0.5],
    "733": [0, 0.69444, 0, 0, 0.5],
    "915": [0, 0.68333, 0, 0, 0.625],
    "916": [0, 0.68333, 0, 0, 0.83334],
    "920": [0, 0.68333, 0, 0, 0.77778],
    "923": [0, 0.68333, 0, 0, 0.69445],
    "926": [0, 0.68333, 0, 0, 0.66667],
    "928": [0, 0.68333, 0, 0, 0.75],
    "931": [0, 0.68333, 0, 0, 0.72222],
    "933": [0, 0.68333, 0, 0, 0.77778],
    "934": [0, 0.68333, 0, 0, 0.72222],
    "936": [0, 0.68333, 0, 0, 0.77778],
    "937": [0, 0.68333, 0, 0, 0.72222],
    "8211": [0, 0.43056, 0.02778, 0, 0.5],
    "8212": [0, 0.43056, 0.02778, 0, 1],
    "8216": [0, 0.69444, 0, 0, 0.27778],
    "8217": [0, 0.69444, 0, 0, 0.27778],
    "8220": [0, 0.69444, 0, 0, 0.5],
    "8221": [0, 0.69444, 0, 0, 0.5],
    "8224": [0.19444, 0.69444, 0, 0, 0.44445],
    "8225": [0.19444, 0.69444, 0, 0, 0.44445],
    "8230": [0, 0.123, 0, 0, 1.172],
    "8242": [0, 0.55556, 0, 0, 0.275],
    "8407": [0, 0.71444, 0.15382, 0, 0.5],
    "8463": [0, 0.68889, 0, 0, 0.54028],
    "8465": [0, 0.69444, 0, 0, 0.72222],
    "8467": [0, 0.69444, 0, 0.11111, 0.41667],
    "8472": [0.19444, 0.43056, 0, 0.11111, 0.63646],
    "8476": [0, 0.69444, 0, 0, 0.72222],
    "8501": [0, 0.69444, 0, 0, 0.61111],
    "8592": [-0.13313, 0.36687, 0, 0, 1],
    "8593": [0.19444, 0.69444, 0, 0, 0.5],
    "8594": [-0.13313, 0.36687, 0, 0, 1],
    "8595": [0.19444, 0.69444, 0, 0, 0.5],
    "8596": [-0.13313, 0.36687, 0, 0, 1],
    "8597": [0.25, 0.75, 0, 0, 0.5],
    "8598": [0.19444, 0.69444, 0, 0, 1],
    "8599": [0.19444, 0.69444, 0, 0, 1],
    "8600": [0.19444, 0.69444, 0, 0, 1],
    "8601": [0.19444, 0.69444, 0, 0, 1],
    "8614": [0.011, 0.511, 0, 0, 1],
    "8617": [0.011, 0.511, 0, 0, 1.126],
    "8618": [0.011, 0.511, 0, 0, 1.126],
    "8636": [-0.13313, 0.36687, 0, 0, 1],
    "8637": [-0.13313, 0.36687, 0, 0, 1],
    "8640": [-0.13313, 0.36687, 0, 0, 1],
    "8641": [-0.13313, 0.36687, 0, 0, 1],
    "8652": [0.011, 0.671, 0, 0, 1],
    "8656": [-0.13313, 0.36687, 0, 0, 1],
    "8657": [0.19444, 0.69444, 0, 0, 0.61111],
    "8658": [-0.13313, 0.36687, 0, 0, 1],
    "8659": [0.19444, 0.69444, 0, 0, 0.61111],
    "8660": [-0.13313, 0.36687, 0, 0, 1],
    "8661": [0.25, 0.75, 0, 0, 0.61111],
    "8704": [0, 0.69444, 0, 0, 0.55556],
    "8706": [0, 0.69444, 0.05556, 0.08334, 0.5309],
    "8707": [0, 0.69444, 0, 0, 0.55556],
    "8709": [0.05556, 0.75, 0, 0, 0.5],
    "8711": [0, 0.68333, 0, 0, 0.83334],
    "8712": [0.0391, 0.5391, 0, 0, 0.66667],
    "8715": [0.0391, 0.5391, 0, 0, 0.66667],
    "8722": [0.08333, 0.58333, 0, 0, 0.77778],
    "8723": [0.08333, 0.58333, 0, 0, 0.77778],
    "8725": [0.25, 0.75, 0, 0, 0.5],
    "8726": [0.25, 0.75, 0, 0, 0.5],
    "8727": [-0.03472, 0.46528, 0, 0, 0.5],
    "8728": [-0.05555, 0.44445, 0, 0, 0.5],
    "8729": [-0.05555, 0.44445, 0, 0, 0.5],
    "8730": [0.2, 0.8, 0, 0, 0.83334],
    "8733": [0, 0.43056, 0, 0, 0.77778],
    "8734": [0, 0.43056, 0, 0, 1],
    "8736": [0, 0.69224, 0, 0, 0.72222],
    "8739": [0.25, 0.75, 0, 0, 0.27778],
    "8741": [0.25, 0.75, 0, 0, 0.5],
    "8743": [0, 0.55556, 0, 0, 0.66667],
    "8744": [0, 0.55556, 0, 0, 0.66667],
    "8745": [0, 0.55556, 0, 0, 0.66667],
    "8746": [0, 0.55556, 0, 0, 0.66667],
    "8747": [0.19444, 0.69444, 0.11111, 0, 0.41667],
    "8764": [-0.13313, 0.36687, 0, 0, 0.77778],
    "8768": [0.19444, 0.69444, 0, 0, 0.27778],
    "8771": [-0.03625, 0.46375, 0, 0, 0.77778],
    "8773": [-0.022, 0.589, 0, 0, 0.778],
    "8776": [-0.01688, 0.48312, 0, 0, 0.77778],
    "8781": [-0.03625, 0.46375, 0, 0, 0.77778],
    "8784": [-0.133, 0.673, 0, 0, 0.778],
    "8801": [-0.03625, 0.46375, 0, 0, 0.77778],
    "8804": [0.13597, 0.63597, 0, 0, 0.77778],
    "8805": [0.13597, 0.63597, 0, 0, 0.77778],
    "8810": [0.0391, 0.5391, 0, 0, 1],
    "8811": [0.0391, 0.5391, 0, 0, 1],
    "8826": [0.0391, 0.5391, 0, 0, 0.77778],
    "8827": [0.0391, 0.5391, 0, 0, 0.77778],
    "8834": [0.0391, 0.5391, 0, 0, 0.77778],
    "8835": [0.0391, 0.5391, 0, 0, 0.77778],
    "8838": [0.13597, 0.63597, 0, 0, 0.77778],
    "8839": [0.13597, 0.63597, 0, 0, 0.77778],
    "8846": [0, 0.55556, 0, 0, 0.66667],
    "8849": [0.13597, 0.63597, 0, 0, 0.77778],
    "8850": [0.13597, 0.63597, 0, 0, 0.77778],
    "8851": [0, 0.55556, 0, 0, 0.66667],
    "8852": [0, 0.55556, 0, 0, 0.66667],
    "8853": [0.08333, 0.58333, 0, 0, 0.77778],
    "8854": [0.08333, 0.58333, 0, 0, 0.77778],
    "8855": [0.08333, 0.58333, 0, 0, 0.77778],
    "8856": [0.08333, 0.58333, 0, 0, 0.77778],
    "8857": [0.08333, 0.58333, 0, 0, 0.77778],
    "8866": [0, 0.69444, 0, 0, 0.61111],
    "8867": [0, 0.69444, 0, 0, 0.61111],
    "8868": [0, 0.69444, 0, 0, 0.77778],
    "8869": [0, 0.69444, 0, 0, 0.77778],
    "8872": [0.249, 0.75, 0, 0, 0.867],
    "8900": [-0.05555, 0.44445, 0, 0, 0.5],
    "8901": [-0.05555, 0.44445, 0, 0, 0.27778],
    "8902": [-0.03472, 0.46528, 0, 0, 0.5],
    "8904": [5e-3, 0.505, 0, 0, 0.9],
    "8942": [0.03, 0.903, 0, 0, 0.278],
    "8943": [-0.19, 0.313, 0, 0, 1.172],
    "8945": [-0.1, 0.823, 0, 0, 1.282],
    "8968": [0.25, 0.75, 0, 0, 0.44445],
    "8969": [0.25, 0.75, 0, 0, 0.44445],
    "8970": [0.25, 0.75, 0, 0, 0.44445],
    "8971": [0.25, 0.75, 0, 0, 0.44445],
    "8994": [-0.14236, 0.35764, 0, 0, 1],
    "8995": [-0.14236, 0.35764, 0, 0, 1],
    "9136": [0.244, 0.744, 0, 0, 0.412],
    "9137": [0.244, 0.745, 0, 0, 0.412],
    "9651": [0.19444, 0.69444, 0, 0, 0.88889],
    "9657": [-0.03472, 0.46528, 0, 0, 0.5],
    "9661": [0.19444, 0.69444, 0, 0, 0.88889],
    "9667": [-0.03472, 0.46528, 0, 0, 0.5],
    "9711": [0.19444, 0.69444, 0, 0, 1],
    "9824": [0.12963, 0.69444, 0, 0, 0.77778],
    "9825": [0.12963, 0.69444, 0, 0, 0.77778],
    "9826": [0.12963, 0.69444, 0, 0, 0.77778],
    "9827": [0.12963, 0.69444, 0, 0, 0.77778],
    "9837": [0, 0.75, 0, 0, 0.38889],
    "9838": [0.19444, 0.69444, 0, 0, 0.38889],
    "9839": [0.19444, 0.69444, 0, 0, 0.38889],
    "10216": [0.25, 0.75, 0, 0, 0.38889],
    "10217": [0.25, 0.75, 0, 0, 0.38889],
    "10222": [0.244, 0.744, 0, 0, 0.412],
    "10223": [0.244, 0.745, 0, 0, 0.412],
    "10229": [0.011, 0.511, 0, 0, 1.609],
    "10230": [0.011, 0.511, 0, 0, 1.638],
    "10231": [0.011, 0.511, 0, 0, 1.859],
    "10232": [0.024, 0.525, 0, 0, 1.609],
    "10233": [0.024, 0.525, 0, 0, 1.638],
    "10234": [0.024, 0.525, 0, 0, 1.858],
    "10236": [0.011, 0.511, 0, 0, 1.638],
    "10815": [0, 0.68333, 0, 0, 0.75],
    "10927": [0.13597, 0.63597, 0, 0, 0.77778],
    "10928": [0.13597, 0.63597, 0, 0, 0.77778],
    "57376": [0.19444, 0.69444, 0, 0, 0]
  },
  "Math-BoldItalic": {
    "32": [0, 0, 0, 0, 0.25],
    "48": [0, 0.44444, 0, 0, 0.575],
    "49": [0, 0.44444, 0, 0, 0.575],
    "50": [0, 0.44444, 0, 0, 0.575],
    "51": [0.19444, 0.44444, 0, 0, 0.575],
    "52": [0.19444, 0.44444, 0, 0, 0.575],
    "53": [0.19444, 0.44444, 0, 0, 0.575],
    "54": [0, 0.64444, 0, 0, 0.575],
    "55": [0.19444, 0.44444, 0, 0, 0.575],
    "56": [0, 0.64444, 0, 0, 0.575],
    "57": [0.19444, 0.44444, 0, 0, 0.575],
    "65": [0, 0.68611, 0, 0, 0.86944],
    "66": [0, 0.68611, 0.04835, 0, 0.8664],
    "67": [0, 0.68611, 0.06979, 0, 0.81694],
    "68": [0, 0.68611, 0.03194, 0, 0.93812],
    "69": [0, 0.68611, 0.05451, 0, 0.81007],
    "70": [0, 0.68611, 0.15972, 0, 0.68889],
    "71": [0, 0.68611, 0, 0, 0.88673],
    "72": [0, 0.68611, 0.08229, 0, 0.98229],
    "73": [0, 0.68611, 0.07778, 0, 0.51111],
    "74": [0, 0.68611, 0.10069, 0, 0.63125],
    "75": [0, 0.68611, 0.06979, 0, 0.97118],
    "76": [0, 0.68611, 0, 0, 0.75555],
    "77": [0, 0.68611, 0.11424, 0, 1.14201],
    "78": [0, 0.68611, 0.11424, 0, 0.95034],
    "79": [0, 0.68611, 0.03194, 0, 0.83666],
    "80": [0, 0.68611, 0.15972, 0, 0.72309],
    "81": [0.19444, 0.68611, 0, 0, 0.86861],
    "82": [0, 0.68611, 421e-5, 0, 0.87235],
    "83": [0, 0.68611, 0.05382, 0, 0.69271],
    "84": [0, 0.68611, 0.15972, 0, 0.63663],
    "85": [0, 0.68611, 0.11424, 0, 0.80027],
    "86": [0, 0.68611, 0.25555, 0, 0.67778],
    "87": [0, 0.68611, 0.15972, 0, 1.09305],
    "88": [0, 0.68611, 0.07778, 0, 0.94722],
    "89": [0, 0.68611, 0.25555, 0, 0.67458],
    "90": [0, 0.68611, 0.06979, 0, 0.77257],
    "97": [0, 0.44444, 0, 0, 0.63287],
    "98": [0, 0.69444, 0, 0, 0.52083],
    "99": [0, 0.44444, 0, 0, 0.51342],
    "100": [0, 0.69444, 0, 0, 0.60972],
    "101": [0, 0.44444, 0, 0, 0.55361],
    "102": [0.19444, 0.69444, 0.11042, 0, 0.56806],
    "103": [0.19444, 0.44444, 0.03704, 0, 0.5449],
    "104": [0, 0.69444, 0, 0, 0.66759],
    "105": [0, 0.69326, 0, 0, 0.4048],
    "106": [0.19444, 0.69326, 0.0622, 0, 0.47083],
    "107": [0, 0.69444, 0.01852, 0, 0.6037],
    "108": [0, 0.69444, 88e-4, 0, 0.34815],
    "109": [0, 0.44444, 0, 0, 1.0324],
    "110": [0, 0.44444, 0, 0, 0.71296],
    "111": [0, 0.44444, 0, 0, 0.58472],
    "112": [0.19444, 0.44444, 0, 0, 0.60092],
    "113": [0.19444, 0.44444, 0.03704, 0, 0.54213],
    "114": [0, 0.44444, 0.03194, 0, 0.5287],
    "115": [0, 0.44444, 0, 0, 0.53125],
    "116": [0, 0.63492, 0, 0, 0.41528],
    "117": [0, 0.44444, 0, 0, 0.68102],
    "118": [0, 0.44444, 0.03704, 0, 0.56666],
    "119": [0, 0.44444, 0.02778, 0, 0.83148],
    "120": [0, 0.44444, 0, 0, 0.65903],
    "121": [0.19444, 0.44444, 0.03704, 0, 0.59028],
    "122": [0, 0.44444, 0.04213, 0, 0.55509],
    "160": [0, 0, 0, 0, 0.25],
    "915": [0, 0.68611, 0.15972, 0, 0.65694],
    "916": [0, 0.68611, 0, 0, 0.95833],
    "920": [0, 0.68611, 0.03194, 0, 0.86722],
    "923": [0, 0.68611, 0, 0, 0.80555],
    "926": [0, 0.68611, 0.07458, 0, 0.84125],
    "928": [0, 0.68611, 0.08229, 0, 0.98229],
    "931": [0, 0.68611, 0.05451, 0, 0.88507],
    "933": [0, 0.68611, 0.15972, 0, 0.67083],
    "934": [0, 0.68611, 0, 0, 0.76666],
    "936": [0, 0.68611, 0.11653, 0, 0.71402],
    "937": [0, 0.68611, 0.04835, 0, 0.8789],
    "945": [0, 0.44444, 0, 0, 0.76064],
    "946": [0.19444, 0.69444, 0.03403, 0, 0.65972],
    "947": [0.19444, 0.44444, 0.06389, 0, 0.59003],
    "948": [0, 0.69444, 0.03819, 0, 0.52222],
    "949": [0, 0.44444, 0, 0, 0.52882],
    "950": [0.19444, 0.69444, 0.06215, 0, 0.50833],
    "951": [0.19444, 0.44444, 0.03704, 0, 0.6],
    "952": [0, 0.69444, 0.03194, 0, 0.5618],
    "953": [0, 0.44444, 0, 0, 0.41204],
    "954": [0, 0.44444, 0, 0, 0.66759],
    "955": [0, 0.69444, 0, 0, 0.67083],
    "956": [0.19444, 0.44444, 0, 0, 0.70787],
    "957": [0, 0.44444, 0.06898, 0, 0.57685],
    "958": [0.19444, 0.69444, 0.03021, 0, 0.50833],
    "959": [0, 0.44444, 0, 0, 0.58472],
    "960": [0, 0.44444, 0.03704, 0, 0.68241],
    "961": [0.19444, 0.44444, 0, 0, 0.6118],
    "962": [0.09722, 0.44444, 0.07917, 0, 0.42361],
    "963": [0, 0.44444, 0.03704, 0, 0.68588],
    "964": [0, 0.44444, 0.13472, 0, 0.52083],
    "965": [0, 0.44444, 0.03704, 0, 0.63055],
    "966": [0.19444, 0.44444, 0, 0, 0.74722],
    "967": [0.19444, 0.44444, 0, 0, 0.71805],
    "968": [0.19444, 0.69444, 0.03704, 0, 0.75833],
    "969": [0, 0.44444, 0.03704, 0, 0.71782],
    "977": [0, 0.69444, 0, 0, 0.69155],
    "981": [0.19444, 0.69444, 0, 0, 0.7125],
    "982": [0, 0.44444, 0.03194, 0, 0.975],
    "1009": [0.19444, 0.44444, 0, 0, 0.6118],
    "1013": [0, 0.44444, 0, 0, 0.48333],
    "57649": [0, 0.44444, 0, 0, 0.39352],
    "57911": [0.19444, 0.44444, 0, 0, 0.43889]
  },
  "Math-Italic": {
    "32": [0, 0, 0, 0, 0.25],
    "48": [0, 0.43056, 0, 0, 0.5],
    "49": [0, 0.43056, 0, 0, 0.5],
    "50": [0, 0.43056, 0, 0, 0.5],
    "51": [0.19444, 0.43056, 0, 0, 0.5],
    "52": [0.19444, 0.43056, 0, 0, 0.5],
    "53": [0.19444, 0.43056, 0, 0, 0.5],
    "54": [0, 0.64444, 0, 0, 0.5],
    "55": [0.19444, 0.43056, 0, 0, 0.5],
    "56": [0, 0.64444, 0, 0, 0.5],
    "57": [0.19444, 0.43056, 0, 0, 0.5],
    "65": [0, 0.68333, 0, 0.13889, 0.75],
    "66": [0, 0.68333, 0.05017, 0.08334, 0.75851],
    "67": [0, 0.68333, 0.07153, 0.08334, 0.71472],
    "68": [0, 0.68333, 0.02778, 0.05556, 0.82792],
    "69": [0, 0.68333, 0.05764, 0.08334, 0.7382],
    "70": [0, 0.68333, 0.13889, 0.08334, 0.64306],
    "71": [0, 0.68333, 0, 0.08334, 0.78625],
    "72": [0, 0.68333, 0.08125, 0.05556, 0.83125],
    "73": [0, 0.68333, 0.07847, 0.11111, 0.43958],
    "74": [0, 0.68333, 0.09618, 0.16667, 0.55451],
    "75": [0, 0.68333, 0.07153, 0.05556, 0.84931],
    "76": [0, 0.68333, 0, 0.02778, 0.68056],
    "77": [0, 0.68333, 0.10903, 0.08334, 0.97014],
    "78": [0, 0.68333, 0.10903, 0.08334, 0.80347],
    "79": [0, 0.68333, 0.02778, 0.08334, 0.76278],
    "80": [0, 0.68333, 0.13889, 0.08334, 0.64201],
    "81": [0.19444, 0.68333, 0, 0.08334, 0.79056],
    "82": [0, 0.68333, 773e-5, 0.08334, 0.75929],
    "83": [0, 0.68333, 0.05764, 0.08334, 0.6132],
    "84": [0, 0.68333, 0.13889, 0.08334, 0.58438],
    "85": [0, 0.68333, 0.10903, 0.02778, 0.68278],
    "86": [0, 0.68333, 0.22222, 0, 0.58333],
    "87": [0, 0.68333, 0.13889, 0, 0.94445],
    "88": [0, 0.68333, 0.07847, 0.08334, 0.82847],
    "89": [0, 0.68333, 0.22222, 0, 0.58056],
    "90": [0, 0.68333, 0.07153, 0.08334, 0.68264],
    "97": [0, 0.43056, 0, 0, 0.52859],
    "98": [0, 0.69444, 0, 0, 0.42917],
    "99": [0, 0.43056, 0, 0.05556, 0.43276],
    "100": [0, 0.69444, 0, 0.16667, 0.52049],
    "101": [0, 0.43056, 0, 0.05556, 0.46563],
    "102": [0.19444, 0.69444, 0.10764, 0.16667, 0.48959],
    "103": [0.19444, 0.43056, 0.03588, 0.02778, 0.47697],
    "104": [0, 0.69444, 0, 0, 0.57616],
    "105": [0, 0.65952, 0, 0, 0.34451],
    "106": [0.19444, 0.65952, 0.05724, 0, 0.41181],
    "107": [0, 0.69444, 0.03148, 0, 0.5206],
    "108": [0, 0.69444, 0.01968, 0.08334, 0.29838],
    "109": [0, 0.43056, 0, 0, 0.87801],
    "110": [0, 0.43056, 0, 0, 0.60023],
    "111": [0, 0.43056, 0, 0.05556, 0.48472],
    "112": [0.19444, 0.43056, 0, 0.08334, 0.50313],
    "113": [0.19444, 0.43056, 0.03588, 0.08334, 0.44641],
    "114": [0, 0.43056, 0.02778, 0.05556, 0.45116],
    "115": [0, 0.43056, 0, 0.05556, 0.46875],
    "116": [0, 0.61508, 0, 0.08334, 0.36111],
    "117": [0, 0.43056, 0, 0.02778, 0.57246],
    "118": [0, 0.43056, 0.03588, 0.02778, 0.48472],
    "119": [0, 0.43056, 0.02691, 0.08334, 0.71592],
    "120": [0, 0.43056, 0, 0.02778, 0.57153],
    "121": [0.19444, 0.43056, 0.03588, 0.05556, 0.49028],
    "122": [0, 0.43056, 0.04398, 0.05556, 0.46505],
    "160": [0, 0, 0, 0, 0.25],
    "915": [0, 0.68333, 0.13889, 0.08334, 0.61528],
    "916": [0, 0.68333, 0, 0.16667, 0.83334],
    "920": [0, 0.68333, 0.02778, 0.08334, 0.76278],
    "923": [0, 0.68333, 0, 0.16667, 0.69445],
    "926": [0, 0.68333, 0.07569, 0.08334, 0.74236],
    "928": [0, 0.68333, 0.08125, 0.05556, 0.83125],
    "931": [0, 0.68333, 0.05764, 0.08334, 0.77986],
    "933": [0, 0.68333, 0.13889, 0.05556, 0.58333],
    "934": [0, 0.68333, 0, 0.08334, 0.66667],
    "936": [0, 0.68333, 0.11, 0.05556, 0.61222],
    "937": [0, 0.68333, 0.05017, 0.08334, 0.7724],
    "945": [0, 0.43056, 37e-4, 0.02778, 0.6397],
    "946": [0.19444, 0.69444, 0.05278, 0.08334, 0.56563],
    "947": [0.19444, 0.43056, 0.05556, 0, 0.51773],
    "948": [0, 0.69444, 0.03785, 0.05556, 0.44444],
    "949": [0, 0.43056, 0, 0.08334, 0.46632],
    "950": [0.19444, 0.69444, 0.07378, 0.08334, 0.4375],
    "951": [0.19444, 0.43056, 0.03588, 0.05556, 0.49653],
    "952": [0, 0.69444, 0.02778, 0.08334, 0.46944],
    "953": [0, 0.43056, 0, 0.05556, 0.35394],
    "954": [0, 0.43056, 0, 0, 0.57616],
    "955": [0, 0.69444, 0, 0, 0.58334],
    "956": [0.19444, 0.43056, 0, 0.02778, 0.60255],
    "957": [0, 0.43056, 0.06366, 0.02778, 0.49398],
    "958": [0.19444, 0.69444, 0.04601, 0.11111, 0.4375],
    "959": [0, 0.43056, 0, 0.05556, 0.48472],
    "960": [0, 0.43056, 0.03588, 0, 0.57003],
    "961": [0.19444, 0.43056, 0, 0.08334, 0.51702],
    "962": [0.09722, 0.43056, 0.07986, 0.08334, 0.36285],
    "963": [0, 0.43056, 0.03588, 0, 0.57141],
    "964": [0, 0.43056, 0.1132, 0.02778, 0.43715],
    "965": [0, 0.43056, 0.03588, 0.02778, 0.54028],
    "966": [0.19444, 0.43056, 0, 0.08334, 0.65417],
    "967": [0.19444, 0.43056, 0, 0.05556, 0.62569],
    "968": [0.19444, 0.69444, 0.03588, 0.11111, 0.65139],
    "969": [0, 0.43056, 0.03588, 0, 0.62245],
    "977": [0, 0.69444, 0, 0.08334, 0.59144],
    "981": [0.19444, 0.69444, 0, 0.08334, 0.59583],
    "982": [0, 0.43056, 0.02778, 0, 0.82813],
    "1009": [0.19444, 0.43056, 0, 0.08334, 0.51702],
    "1013": [0, 0.43056, 0, 0.05556, 0.4059],
    "57649": [0, 0.43056, 0, 0.02778, 0.32246],
    "57911": [0.19444, 0.43056, 0, 0.08334, 0.38403]
  },
  "SansSerif-Bold": {
    "32": [0, 0, 0, 0, 0.25],
    "33": [0, 0.69444, 0, 0, 0.36667],
    "34": [0, 0.69444, 0, 0, 0.55834],
    "35": [0.19444, 0.69444, 0, 0, 0.91667],
    "36": [0.05556, 0.75, 0, 0, 0.55],
    "37": [0.05556, 0.75, 0, 0, 1.02912],
    "38": [0, 0.69444, 0, 0, 0.83056],
    "39": [0, 0.69444, 0, 0, 0.30556],
    "40": [0.25, 0.75, 0, 0, 0.42778],
    "41": [0.25, 0.75, 0, 0, 0.42778],
    "42": [0, 0.75, 0, 0, 0.55],
    "43": [0.11667, 0.61667, 0, 0, 0.85556],
    "44": [0.10556, 0.13056, 0, 0, 0.30556],
    "45": [0, 0.45833, 0, 0, 0.36667],
    "46": [0, 0.13056, 0, 0, 0.30556],
    "47": [0.25, 0.75, 0, 0, 0.55],
    "48": [0, 0.69444, 0, 0, 0.55],
    "49": [0, 0.69444, 0, 0, 0.55],
    "50": [0, 0.69444, 0, 0, 0.55],
    "51": [0, 0.69444, 0, 0, 0.55],
    "52": [0, 0.69444, 0, 0, 0.55],
    "53": [0, 0.69444, 0, 0, 0.55],
    "54": [0, 0.69444, 0, 0, 0.55],
    "55": [0, 0.69444, 0, 0, 0.55],
    "56": [0, 0.69444, 0, 0, 0.55],
    "57": [0, 0.69444, 0, 0, 0.55],
    "58": [0, 0.45833, 0, 0, 0.30556],
    "59": [0.10556, 0.45833, 0, 0, 0.30556],
    "61": [-0.09375, 0.40625, 0, 0, 0.85556],
    "63": [0, 0.69444, 0, 0, 0.51945],
    "64": [0, 0.69444, 0, 0, 0.73334],
    "65": [0, 0.69444, 0, 0, 0.73334],
    "66": [0, 0.69444, 0, 0, 0.73334],
    "67": [0, 0.69444, 0, 0, 0.70278],
    "68": [0, 0.69444, 0, 0, 0.79445],
    "69": [0, 0.69444, 0, 0, 0.64167],
    "70": [0, 0.69444, 0, 0, 0.61111],
    "71": [0, 0.69444, 0, 0, 0.73334],
    "72": [0, 0.69444, 0, 0, 0.79445],
    "73": [0, 0.69444, 0, 0, 0.33056],
    "74": [0, 0.69444, 0, 0, 0.51945],
    "75": [0, 0.69444, 0, 0, 0.76389],
    "76": [0, 0.69444, 0, 0, 0.58056],
    "77": [0, 0.69444, 0, 0, 0.97778],
    "78": [0, 0.69444, 0, 0, 0.79445],
    "79": [0, 0.69444, 0, 0, 0.79445],
    "80": [0, 0.69444, 0, 0, 0.70278],
    "81": [0.10556, 0.69444, 0, 0, 0.79445],
    "82": [0, 0.69444, 0, 0, 0.70278],
    "83": [0, 0.69444, 0, 0, 0.61111],
    "84": [0, 0.69444, 0, 0, 0.73334],
    "85": [0, 0.69444, 0, 0, 0.76389],
    "86": [0, 0.69444, 0.01528, 0, 0.73334],
    "87": [0, 0.69444, 0.01528, 0, 1.03889],
    "88": [0, 0.69444, 0, 0, 0.73334],
    "89": [0, 0.69444, 0.0275, 0, 0.73334],
    "90": [0, 0.69444, 0, 0, 0.67223],
    "91": [0.25, 0.75, 0, 0, 0.34306],
    "93": [0.25, 0.75, 0, 0, 0.34306],
    "94": [0, 0.69444, 0, 0, 0.55],
    "95": [0.35, 0.10833, 0.03056, 0, 0.55],
    "97": [0, 0.45833, 0, 0, 0.525],
    "98": [0, 0.69444, 0, 0, 0.56111],
    "99": [0, 0.45833, 0, 0, 0.48889],
    "100": [0, 0.69444, 0, 0, 0.56111],
    "101": [0, 0.45833, 0, 0, 0.51111],
    "102": [0, 0.69444, 0.07639, 0, 0.33611],
    "103": [0.19444, 0.45833, 0.01528, 0, 0.55],
    "104": [0, 0.69444, 0, 0, 0.56111],
    "105": [0, 0.69444, 0, 0, 0.25556],
    "106": [0.19444, 0.69444, 0, 0, 0.28611],
    "107": [0, 0.69444, 0, 0, 0.53056],
    "108": [0, 0.69444, 0, 0, 0.25556],
    "109": [0, 0.45833, 0, 0, 0.86667],
    "110": [0, 0.45833, 0, 0, 0.56111],
    "111": [0, 0.45833, 0, 0, 0.55],
    "112": [0.19444, 0.45833, 0, 0, 0.56111],
    "113": [0.19444, 0.45833, 0, 0, 0.56111],
    "114": [0, 0.45833, 0.01528, 0, 0.37222],
    "115": [0, 0.45833, 0, 0, 0.42167],
    "116": [0, 0.58929, 0, 0, 0.40417],
    "117": [0, 0.45833, 0, 0, 0.56111],
    "118": [0, 0.45833, 0.01528, 0, 0.5],
    "119": [0, 0.45833, 0.01528, 0, 0.74445],
    "120": [0, 0.45833, 0, 0, 0.5],
    "121": [0.19444, 0.45833, 0.01528, 0, 0.5],
    "122": [0, 0.45833, 0, 0, 0.47639],
    "126": [0.35, 0.34444, 0, 0, 0.55],
    "160": [0, 0, 0, 0, 0.25],
    "168": [0, 0.69444, 0, 0, 0.55],
    "176": [0, 0.69444, 0, 0, 0.73334],
    "180": [0, 0.69444, 0, 0, 0.55],
    "184": [0.17014, 0, 0, 0, 0.48889],
    "305": [0, 0.45833, 0, 0, 0.25556],
    "567": [0.19444, 0.45833, 0, 0, 0.28611],
    "710": [0, 0.69444, 0, 0, 0.55],
    "711": [0, 0.63542, 0, 0, 0.55],
    "713": [0, 0.63778, 0, 0, 0.55],
    "728": [0, 0.69444, 0, 0, 0.55],
    "729": [0, 0.69444, 0, 0, 0.30556],
    "730": [0, 0.69444, 0, 0, 0.73334],
    "732": [0, 0.69444, 0, 0, 0.55],
    "733": [0, 0.69444, 0, 0, 0.55],
    "915": [0, 0.69444, 0, 0, 0.58056],
    "916": [0, 0.69444, 0, 0, 0.91667],
    "920": [0, 0.69444, 0, 0, 0.85556],
    "923": [0, 0.69444, 0, 0, 0.67223],
    "926": [0, 0.69444, 0, 0, 0.73334],
    "928": [0, 0.69444, 0, 0, 0.79445],
    "931": [0, 0.69444, 0, 0, 0.79445],
    "933": [0, 0.69444, 0, 0, 0.85556],
    "934": [0, 0.69444, 0, 0, 0.79445],
    "936": [0, 0.69444, 0, 0, 0.85556],
    "937": [0, 0.69444, 0, 0, 0.79445],
    "8211": [0, 0.45833, 0.03056, 0, 0.55],
    "8212": [0, 0.45833, 0.03056, 0, 1.10001],
    "8216": [0, 0.69444, 0, 0, 0.30556],
    "8217": [0, 0.69444, 0, 0, 0.30556],
    "8220": [0, 0.69444, 0, 0, 0.55834],
    "8221": [0, 0.69444, 0, 0, 0.55834]
  },
  "SansSerif-Italic": {
    "32": [0, 0, 0, 0, 0.25],
    "33": [0, 0.69444, 0.05733, 0, 0.31945],
    "34": [0, 0.69444, 316e-5, 0, 0.5],
    "35": [0.19444, 0.69444, 0.05087, 0, 0.83334],
    "36": [0.05556, 0.75, 0.11156, 0, 0.5],
    "37": [0.05556, 0.75, 0.03126, 0, 0.83334],
    "38": [0, 0.69444, 0.03058, 0, 0.75834],
    "39": [0, 0.69444, 0.07816, 0, 0.27778],
    "40": [0.25, 0.75, 0.13164, 0, 0.38889],
    "41": [0.25, 0.75, 0.02536, 0, 0.38889],
    "42": [0, 0.75, 0.11775, 0, 0.5],
    "43": [0.08333, 0.58333, 0.02536, 0, 0.77778],
    "44": [0.125, 0.08333, 0, 0, 0.27778],
    "45": [0, 0.44444, 0.01946, 0, 0.33333],
    "46": [0, 0.08333, 0, 0, 0.27778],
    "47": [0.25, 0.75, 0.13164, 0, 0.5],
    "48": [0, 0.65556, 0.11156, 0, 0.5],
    "49": [0, 0.65556, 0.11156, 0, 0.5],
    "50": [0, 0.65556, 0.11156, 0, 0.5],
    "51": [0, 0.65556, 0.11156, 0, 0.5],
    "52": [0, 0.65556, 0.11156, 0, 0.5],
    "53": [0, 0.65556, 0.11156, 0, 0.5],
    "54": [0, 0.65556, 0.11156, 0, 0.5],
    "55": [0, 0.65556, 0.11156, 0, 0.5],
    "56": [0, 0.65556, 0.11156, 0, 0.5],
    "57": [0, 0.65556, 0.11156, 0, 0.5],
    "58": [0, 0.44444, 0.02502, 0, 0.27778],
    "59": [0.125, 0.44444, 0.02502, 0, 0.27778],
    "61": [-0.13, 0.37, 0.05087, 0, 0.77778],
    "63": [0, 0.69444, 0.11809, 0, 0.47222],
    "64": [0, 0.69444, 0.07555, 0, 0.66667],
    "65": [0, 0.69444, 0, 0, 0.66667],
    "66": [0, 0.69444, 0.08293, 0, 0.66667],
    "67": [0, 0.69444, 0.11983, 0, 0.63889],
    "68": [0, 0.69444, 0.07555, 0, 0.72223],
    "69": [0, 0.69444, 0.11983, 0, 0.59722],
    "70": [0, 0.69444, 0.13372, 0, 0.56945],
    "71": [0, 0.69444, 0.11983, 0, 0.66667],
    "72": [0, 0.69444, 0.08094, 0, 0.70834],
    "73": [0, 0.69444, 0.13372, 0, 0.27778],
    "74": [0, 0.69444, 0.08094, 0, 0.47222],
    "75": [0, 0.69444, 0.11983, 0, 0.69445],
    "76": [0, 0.69444, 0, 0, 0.54167],
    "77": [0, 0.69444, 0.08094, 0, 0.875],
    "78": [0, 0.69444, 0.08094, 0, 0.70834],
    "79": [0, 0.69444, 0.07555, 0, 0.73611],
    "80": [0, 0.69444, 0.08293, 0, 0.63889],
    "81": [0.125, 0.69444, 0.07555, 0, 0.73611],
    "82": [0, 0.69444, 0.08293, 0, 0.64584],
    "83": [0, 0.69444, 0.09205, 0, 0.55556],
    "84": [0, 0.69444, 0.13372, 0, 0.68056],
    "85": [0, 0.69444, 0.08094, 0, 0.6875],
    "86": [0, 0.69444, 0.1615, 0, 0.66667],
    "87": [0, 0.69444, 0.1615, 0, 0.94445],
    "88": [0, 0.69444, 0.13372, 0, 0.66667],
    "89": [0, 0.69444, 0.17261, 0, 0.66667],
    "90": [0, 0.69444, 0.11983, 0, 0.61111],
    "91": [0.25, 0.75, 0.15942, 0, 0.28889],
    "93": [0.25, 0.75, 0.08719, 0, 0.28889],
    "94": [0, 0.69444, 0.0799, 0, 0.5],
    "95": [0.35, 0.09444, 0.08616, 0, 0.5],
    "97": [0, 0.44444, 981e-5, 0, 0.48056],
    "98": [0, 0.69444, 0.03057, 0, 0.51667],
    "99": [0, 0.44444, 0.08336, 0, 0.44445],
    "100": [0, 0.69444, 0.09483, 0, 0.51667],
    "101": [0, 0.44444, 0.06778, 0, 0.44445],
    "102": [0, 0.69444, 0.21705, 0, 0.30556],
    "103": [0.19444, 0.44444, 0.10836, 0, 0.5],
    "104": [0, 0.69444, 0.01778, 0, 0.51667],
    "105": [0, 0.67937, 0.09718, 0, 0.23889],
    "106": [0.19444, 0.67937, 0.09162, 0, 0.26667],
    "107": [0, 0.69444, 0.08336, 0, 0.48889],
    "108": [0, 0.69444, 0.09483, 0, 0.23889],
    "109": [0, 0.44444, 0.01778, 0, 0.79445],
    "110": [0, 0.44444, 0.01778, 0, 0.51667],
    "111": [0, 0.44444, 0.06613, 0, 0.5],
    "112": [0.19444, 0.44444, 0.0389, 0, 0.51667],
    "113": [0.19444, 0.44444, 0.04169, 0, 0.51667],
    "114": [0, 0.44444, 0.10836, 0, 0.34167],
    "115": [0, 0.44444, 0.0778, 0, 0.38333],
    "116": [0, 0.57143, 0.07225, 0, 0.36111],
    "117": [0, 0.44444, 0.04169, 0, 0.51667],
    "118": [0, 0.44444, 0.10836, 0, 0.46111],
    "119": [0, 0.44444, 0.10836, 0, 0.68334],
    "120": [0, 0.44444, 0.09169, 0, 0.46111],
    "121": [0.19444, 0.44444, 0.10836, 0, 0.46111],
    "122": [0, 0.44444, 0.08752, 0, 0.43472],
    "126": [0.35, 0.32659, 0.08826, 0, 0.5],
    "160": [0, 0, 0, 0, 0.25],
    "168": [0, 0.67937, 0.06385, 0, 0.5],
    "176": [0, 0.69444, 0, 0, 0.73752],
    "184": [0.17014, 0, 0, 0, 0.44445],
    "305": [0, 0.44444, 0.04169, 0, 0.23889],
    "567": [0.19444, 0.44444, 0.04169, 0, 0.26667],
    "710": [0, 0.69444, 0.0799, 0, 0.5],
    "711": [0, 0.63194, 0.08432, 0, 0.5],
    "713": [0, 0.60889, 0.08776, 0, 0.5],
    "714": [0, 0.69444, 0.09205, 0, 0.5],
    "715": [0, 0.69444, 0, 0, 0.5],
    "728": [0, 0.69444, 0.09483, 0, 0.5],
    "729": [0, 0.67937, 0.07774, 0, 0.27778],
    "730": [0, 0.69444, 0, 0, 0.73752],
    "732": [0, 0.67659, 0.08826, 0, 0.5],
    "733": [0, 0.69444, 0.09205, 0, 0.5],
    "915": [0, 0.69444, 0.13372, 0, 0.54167],
    "916": [0, 0.69444, 0, 0, 0.83334],
    "920": [0, 0.69444, 0.07555, 0, 0.77778],
    "923": [0, 0.69444, 0, 0, 0.61111],
    "926": [0, 0.69444, 0.12816, 0, 0.66667],
    "928": [0, 0.69444, 0.08094, 0, 0.70834],
    "931": [0, 0.69444, 0.11983, 0, 0.72222],
    "933": [0, 0.69444, 0.09031, 0, 0.77778],
    "934": [0, 0.69444, 0.04603, 0, 0.72222],
    "936": [0, 0.69444, 0.09031, 0, 0.77778],
    "937": [0, 0.69444, 0.08293, 0, 0.72222],
    "8211": [0, 0.44444, 0.08616, 0, 0.5],
    "8212": [0, 0.44444, 0.08616, 0, 1],
    "8216": [0, 0.69444, 0.07816, 0, 0.27778],
    "8217": [0, 0.69444, 0.07816, 0, 0.27778],
    "8220": [0, 0.69444, 0.14205, 0, 0.5],
    "8221": [0, 0.69444, 316e-5, 0, 0.5]
  },
  "SansSerif-Regular": {
    "32": [0, 0, 0, 0, 0.25],
    "33": [0, 0.69444, 0, 0, 0.31945],
    "34": [0, 0.69444, 0, 0, 0.5],
    "35": [0.19444, 0.69444, 0, 0, 0.83334],
    "36": [0.05556, 0.75, 0, 0, 0.5],
    "37": [0.05556, 0.75, 0, 0, 0.83334],
    "38": [0, 0.69444, 0, 0, 0.75834],
    "39": [0, 0.69444, 0, 0, 0.27778],
    "40": [0.25, 0.75, 0, 0, 0.38889],
    "41": [0.25, 0.75, 0, 0, 0.38889],
    "42": [0, 0.75, 0, 0, 0.5],
    "43": [0.08333, 0.58333, 0, 0, 0.77778],
    "44": [0.125, 0.08333, 0, 0, 0.27778],
    "45": [0, 0.44444, 0, 0, 0.33333],
    "46": [0, 0.08333, 0, 0, 0.27778],
    "47": [0.25, 0.75, 0, 0, 0.5],
    "48": [0, 0.65556, 0, 0, 0.5],
    "49": [0, 0.65556, 0, 0, 0.5],
    "50": [0, 0.65556, 0, 0, 0.5],
    "51": [0, 0.65556, 0, 0, 0.5],
    "52": [0, 0.65556, 0, 0, 0.5],
    "53": [0, 0.65556, 0, 0, 0.5],
    "54": [0, 0.65556, 0, 0, 0.5],
    "55": [0, 0.65556, 0, 0, 0.5],
    "56": [0, 0.65556, 0, 0, 0.5],
    "57": [0, 0.65556, 0, 0, 0.5],
    "58": [0, 0.44444, 0, 0, 0.27778],
    "59": [0.125, 0.44444, 0, 0, 0.27778],
    "61": [-0.13, 0.37, 0, 0, 0.77778],
    "63": [0, 0.69444, 0, 0, 0.47222],
    "64": [0, 0.69444, 0, 0, 0.66667],
    "65": [0, 0.69444, 0, 0, 0.66667],
    "66": [0, 0.69444, 0, 0, 0.66667],
    "67": [0, 0.69444, 0, 0, 0.63889],
    "68": [0, 0.69444, 0, 0, 0.72223],
    "69": [0, 0.69444, 0, 0, 0.59722],
    "70": [0, 0.69444, 0, 0, 0.56945],
    "71": [0, 0.69444, 0, 0, 0.66667],
    "72": [0, 0.69444, 0, 0, 0.70834],
    "73": [0, 0.69444, 0, 0, 0.27778],
    "74": [0, 0.69444, 0, 0, 0.47222],
    "75": [0, 0.69444, 0, 0, 0.69445],
    "76": [0, 0.69444, 0, 0, 0.54167],
    "77": [0, 0.69444, 0, 0, 0.875],
    "78": [0, 0.69444, 0, 0, 0.70834],
    "79": [0, 0.69444, 0, 0, 0.73611],
    "80": [0, 0.69444, 0, 0, 0.63889],
    "81": [0.125, 0.69444, 0, 0, 0.73611],
    "82": [0, 0.69444, 0, 0, 0.64584],
    "83": [0, 0.69444, 0, 0, 0.55556],
    "84": [0, 0.69444, 0, 0, 0.68056],
    "85": [0, 0.69444, 0, 0, 0.6875],
    "86": [0, 0.69444, 0.01389, 0, 0.66667],
    "87": [0, 0.69444, 0.01389, 0, 0.94445],
    "88": [0, 0.69444, 0, 0, 0.66667],
    "89": [0, 0.69444, 0.025, 0, 0.66667],
    "90": [0, 0.69444, 0, 0, 0.61111],
    "91": [0.25, 0.75, 0, 0, 0.28889],
    "93": [0.25, 0.75, 0, 0, 0.28889],
    "94": [0, 0.69444, 0, 0, 0.5],
    "95": [0.35, 0.09444, 0.02778, 0, 0.5],
    "97": [0, 0.44444, 0, 0, 0.48056],
    "98": [0, 0.69444, 0, 0, 0.51667],
    "99": [0, 0.44444, 0, 0, 0.44445],
    "100": [0, 0.69444, 0, 0, 0.51667],
    "101": [0, 0.44444, 0, 0, 0.44445],
    "102": [0, 0.69444, 0.06944, 0, 0.30556],
    "103": [0.19444, 0.44444, 0.01389, 0, 0.5],
    "104": [0, 0.69444, 0, 0, 0.51667],
    "105": [0, 0.67937, 0, 0, 0.23889],
    "106": [0.19444, 0.67937, 0, 0, 0.26667],
    "107": [0, 0.69444, 0, 0, 0.48889],
    "108": [0, 0.69444, 0, 0, 0.23889],
    "109": [0, 0.44444, 0, 0, 0.79445],
    "110": [0, 0.44444, 0, 0, 0.51667],
    "111": [0, 0.44444, 0, 0, 0.5],
    "112": [0.19444, 0.44444, 0, 0, 0.51667],
    "113": [0.19444, 0.44444, 0, 0, 0.51667],
    "114": [0, 0.44444, 0.01389, 0, 0.34167],
    "115": [0, 0.44444, 0, 0, 0.38333],
    "116": [0, 0.57143, 0, 0, 0.36111],
    "117": [0, 0.44444, 0, 0, 0.51667],
    "118": [0, 0.44444, 0.01389, 0, 0.46111],
    "119": [0, 0.44444, 0.01389, 0, 0.68334],
    "120": [0, 0.44444, 0, 0, 0.46111],
    "121": [0.19444, 0.44444, 0.01389, 0, 0.46111],
    "122": [0, 0.44444, 0, 0, 0.43472],
    "126": [0.35, 0.32659, 0, 0, 0.5],
    "160": [0, 0, 0, 0, 0.25],
    "168": [0, 0.67937, 0, 0, 0.5],
    "176": [0, 0.69444, 0, 0, 0.66667],
    "184": [0.17014, 0, 0, 0, 0.44445],
    "305": [0, 0.44444, 0, 0, 0.23889],
    "567": [0.19444, 0.44444, 0, 0, 0.26667],
    "710": [0, 0.69444, 0, 0, 0.5],
    "711": [0, 0.63194, 0, 0, 0.5],
    "713": [0, 0.60889, 0, 0, 0.5],
    "714": [0, 0.69444, 0, 0, 0.5],
    "715": [0, 0.69444, 0, 0, 0.5],
    "728": [0, 0.69444, 0, 0, 0.5],
    "729": [0, 0.67937, 0, 0, 0.27778],
    "730": [0, 0.69444, 0, 0, 0.66667],
    "732": [0, 0.67659, 0, 0, 0.5],
    "733": [0, 0.69444, 0, 0, 0.5],
    "915": [0, 0.69444, 0, 0, 0.54167],
    "916": [0, 0.69444, 0, 0, 0.83334],
    "920": [0, 0.69444, 0, 0, 0.77778],
    "923": [0, 0.69444, 0, 0, 0.61111],
    "926": [0, 0.69444, 0, 0, 0.66667],
    "928": [0, 0.69444, 0, 0, 0.70834],
    "931": [0, 0.69444, 0, 0, 0.72222],
    "933": [0, 0.69444, 0, 0, 0.77778],
    "934": [0, 0.69444, 0, 0, 0.72222],
    "936": [0, 0.69444, 0, 0, 0.77778],
    "937": [0, 0.69444, 0, 0, 0.72222],
    "8211": [0, 0.44444, 0.02778, 0, 0.5],
    "8212": [0, 0.44444, 0.02778, 0, 1],
    "8216": [0, 0.69444, 0, 0, 0.27778],
    "8217": [0, 0.69444, 0, 0, 0.27778],
    "8220": [0, 0.69444, 0, 0, 0.5],
    "8221": [0, 0.69444, 0, 0, 0.5]
  },
  "Script-Regular": {
    "32": [0, 0, 0, 0, 0.25],
    "65": [0, 0.7, 0.22925, 0, 0.80253],
    "66": [0, 0.7, 0.04087, 0, 0.90757],
    "67": [0, 0.7, 0.1689, 0, 0.66619],
    "68": [0, 0.7, 0.09371, 0, 0.77443],
    "69": [0, 0.7, 0.18583, 0, 0.56162],
    "70": [0, 0.7, 0.13634, 0, 0.89544],
    "71": [0, 0.7, 0.17322, 0, 0.60961],
    "72": [0, 0.7, 0.29694, 0, 0.96919],
    "73": [0, 0.7, 0.19189, 0, 0.80907],
    "74": [0.27778, 0.7, 0.19189, 0, 1.05159],
    "75": [0, 0.7, 0.31259, 0, 0.91364],
    "76": [0, 0.7, 0.19189, 0, 0.87373],
    "77": [0, 0.7, 0.15981, 0, 1.08031],
    "78": [0, 0.7, 0.3525, 0, 0.9015],
    "79": [0, 0.7, 0.08078, 0, 0.73787],
    "80": [0, 0.7, 0.08078, 0, 1.01262],
    "81": [0, 0.7, 0.03305, 0, 0.88282],
    "82": [0, 0.7, 0.06259, 0, 0.85],
    "83": [0, 0.7, 0.19189, 0, 0.86767],
    "84": [0, 0.7, 0.29087, 0, 0.74697],
    "85": [0, 0.7, 0.25815, 0, 0.79996],
    "86": [0, 0.7, 0.27523, 0, 0.62204],
    "87": [0, 0.7, 0.27523, 0, 0.80532],
    "88": [0, 0.7, 0.26006, 0, 0.94445],
    "89": [0, 0.7, 0.2939, 0, 0.70961],
    "90": [0, 0.7, 0.24037, 0, 0.8212],
    "160": [0, 0, 0, 0, 0.25]
  },
  "Size1-Regular": {
    "32": [0, 0, 0, 0, 0.25],
    "40": [0.35001, 0.85, 0, 0, 0.45834],
    "41": [0.35001, 0.85, 0, 0, 0.45834],
    "47": [0.35001, 0.85, 0, 0, 0.57778],
    "91": [0.35001, 0.85, 0, 0, 0.41667],
    "92": [0.35001, 0.85, 0, 0, 0.57778],
    "93": [0.35001, 0.85, 0, 0, 0.41667],
    "123": [0.35001, 0.85, 0, 0, 0.58334],
    "125": [0.35001, 0.85, 0, 0, 0.58334],
    "160": [0, 0, 0, 0, 0.25],
    "710": [0, 0.72222, 0, 0, 0.55556],
    "732": [0, 0.72222, 0, 0, 0.55556],
    "770": [0, 0.72222, 0, 0, 0.55556],
    "771": [0, 0.72222, 0, 0, 0.55556],
    "8214": [-99e-5, 0.601, 0, 0, 0.77778],
    "8593": [1e-5, 0.6, 0, 0, 0.66667],
    "8595": [1e-5, 0.6, 0, 0, 0.66667],
    "8657": [1e-5, 0.6, 0, 0, 0.77778],
    "8659": [1e-5, 0.6, 0, 0, 0.77778],
    "8719": [0.25001, 0.75, 0, 0, 0.94445],
    "8720": [0.25001, 0.75, 0, 0, 0.94445],
    "8721": [0.25001, 0.75, 0, 0, 1.05556],
    "8730": [0.35001, 0.85, 0, 0, 1],
    "8739": [-599e-5, 0.606, 0, 0, 0.33333],
    "8741": [-599e-5, 0.606, 0, 0, 0.55556],
    "8747": [0.30612, 0.805, 0.19445, 0, 0.47222],
    "8748": [0.306, 0.805, 0.19445, 0, 0.47222],
    "8749": [0.306, 0.805, 0.19445, 0, 0.47222],
    "8750": [0.30612, 0.805, 0.19445, 0, 0.47222],
    "8896": [0.25001, 0.75, 0, 0, 0.83334],
    "8897": [0.25001, 0.75, 0, 0, 0.83334],
    "8898": [0.25001, 0.75, 0, 0, 0.83334],
    "8899": [0.25001, 0.75, 0, 0, 0.83334],
    "8968": [0.35001, 0.85, 0, 0, 0.47222],
    "8969": [0.35001, 0.85, 0, 0, 0.47222],
    "8970": [0.35001, 0.85, 0, 0, 0.47222],
    "8971": [0.35001, 0.85, 0, 0, 0.47222],
    "9168": [-99e-5, 0.601, 0, 0, 0.66667],
    "10216": [0.35001, 0.85, 0, 0, 0.47222],
    "10217": [0.35001, 0.85, 0, 0, 0.47222],
    "10752": [0.25001, 0.75, 0, 0, 1.11111],
    "10753": [0.25001, 0.75, 0, 0, 1.11111],
    "10754": [0.25001, 0.75, 0, 0, 1.11111],
    "10756": [0.25001, 0.75, 0, 0, 0.83334],
    "10758": [0.25001, 0.75, 0, 0, 0.83334]
  },
  "Size2-Regular": {
    "32": [0, 0, 0, 0, 0.25],
    "40": [0.65002, 1.15, 0, 0, 0.59722],
    "41": [0.65002, 1.15, 0, 0, 0.59722],
    "47": [0.65002, 1.15, 0, 0, 0.81111],
    "91": [0.65002, 1.15, 0, 0, 0.47222],
    "92": [0.65002, 1.15, 0, 0, 0.81111],
    "93": [0.65002, 1.15, 0, 0, 0.47222],
    "123": [0.65002, 1.15, 0, 0, 0.66667],
    "125": [0.65002, 1.15, 0, 0, 0.66667],
    "160": [0, 0, 0, 0, 0.25],
    "710": [0, 0.75, 0, 0, 1],
    "732": [0, 0.75, 0, 0, 1],
    "770": [0, 0.75, 0, 0, 1],
    "771": [0, 0.75, 0, 0, 1],
    "8719": [0.55001, 1.05, 0, 0, 1.27778],
    "8720": [0.55001, 1.05, 0, 0, 1.27778],
    "8721": [0.55001, 1.05, 0, 0, 1.44445],
    "8730": [0.65002, 1.15, 0, 0, 1],
    "8747": [0.86225, 1.36, 0.44445, 0, 0.55556],
    "8748": [0.862, 1.36, 0.44445, 0, 0.55556],
    "8749": [0.862, 1.36, 0.44445, 0, 0.55556],
    "8750": [0.86225, 1.36, 0.44445, 0, 0.55556],
    "8896": [0.55001, 1.05, 0, 0, 1.11111],
    "8897": [0.55001, 1.05, 0, 0, 1.11111],
    "8898": [0.55001, 1.05, 0, 0, 1.11111],
    "8899": [0.55001, 1.05, 0, 0, 1.11111],
    "8968": [0.65002, 1.15, 0, 0, 0.52778],
    "8969": [0.65002, 1.15, 0, 0, 0.52778],
    "8970": [0.65002, 1.15, 0, 0, 0.52778],
    "8971": [0.65002, 1.15, 0, 0, 0.52778],
    "10216": [0.65002, 1.15, 0, 0, 0.61111],
    "10217": [0.65002, 1.15, 0, 0, 0.61111],
    "10752": [0.55001, 1.05, 0, 0, 1.51112],
    "10753": [0.55001, 1.05, 0, 0, 1.51112],
    "10754": [0.55001, 1.05, 0, 0, 1.51112],
    "10756": [0.55001, 1.05, 0, 0, 1.11111],
    "10758": [0.55001, 1.05, 0, 0, 1.11111]
  },
  "Size3-Regular": {
    "32": [0, 0, 0, 0, 0.25],
    "40": [0.95003, 1.45, 0, 0, 0.73611],
    "41": [0.95003, 1.45, 0, 0, 0.73611],
    "47": [0.95003, 1.45, 0, 0, 1.04445],
    "91": [0.95003, 1.45, 0, 0, 0.52778],
    "92": [0.95003, 1.45, 0, 0, 1.04445],
    "93": [0.95003, 1.45, 0, 0, 0.52778],
    "123": [0.95003, 1.45, 0, 0, 0.75],
    "125": [0.95003, 1.45, 0, 0, 0.75],
    "160": [0, 0, 0, 0, 0.25],
    "710": [0, 0.75, 0, 0, 1.44445],
    "732": [0, 0.75, 0, 0, 1.44445],
    "770": [0, 0.75, 0, 0, 1.44445],
    "771": [0, 0.75, 0, 0, 1.44445],
    "8730": [0.95003, 1.45, 0, 0, 1],
    "8968": [0.95003, 1.45, 0, 0, 0.58334],
    "8969": [0.95003, 1.45, 0, 0, 0.58334],
    "8970": [0.95003, 1.45, 0, 0, 0.58334],
    "8971": [0.95003, 1.45, 0, 0, 0.58334],
    "10216": [0.95003, 1.45, 0, 0, 0.75],
    "10217": [0.95003, 1.45, 0, 0, 0.75]
  },
  "Size4-Regular": {
    "32": [0, 0, 0, 0, 0.25],
    "40": [1.25003, 1.75, 0, 0, 0.79167],
    "41": [1.25003, 1.75, 0, 0, 0.79167],
    "47": [1.25003, 1.75, 0, 0, 1.27778],
    "91": [1.25003, 1.75, 0, 0, 0.58334],
    "92": [1.25003, 1.75, 0, 0, 1.27778],
    "93": [1.25003, 1.75, 0, 0, 0.58334],
    "123": [1.25003, 1.75, 0, 0, 0.80556],
    "125": [1.25003, 1.75, 0, 0, 0.80556],
    "160": [0, 0, 0, 0, 0.25],
    "710": [0, 0.825, 0, 0, 1.8889],
    "732": [0, 0.825, 0, 0, 1.8889],
    "770": [0, 0.825, 0, 0, 1.8889],
    "771": [0, 0.825, 0, 0, 1.8889],
    "8730": [1.25003, 1.75, 0, 0, 1],
    "8968": [1.25003, 1.75, 0, 0, 0.63889],
    "8969": [1.25003, 1.75, 0, 0, 0.63889],
    "8970": [1.25003, 1.75, 0, 0, 0.63889],
    "8971": [1.25003, 1.75, 0, 0, 0.63889],
    "9115": [0.64502, 1.155, 0, 0, 0.875],
    "9116": [1e-5, 0.6, 0, 0, 0.875],
    "9117": [0.64502, 1.155, 0, 0, 0.875],
    "9118": [0.64502, 1.155, 0, 0, 0.875],
    "9119": [1e-5, 0.6, 0, 0, 0.875],
    "9120": [0.64502, 1.155, 0, 0, 0.875],
    "9121": [0.64502, 1.155, 0, 0, 0.66667],
    "9122": [-99e-5, 0.601, 0, 0, 0.66667],
    "9123": [0.64502, 1.155, 0, 0, 0.66667],
    "9124": [0.64502, 1.155, 0, 0, 0.66667],
    "9125": [-99e-5, 0.601, 0, 0, 0.66667],
    "9126": [0.64502, 1.155, 0, 0, 0.66667],
    "9127": [1e-5, 0.9, 0, 0, 0.88889],
    "9128": [0.65002, 1.15, 0, 0, 0.88889],
    "9129": [0.90001, 0, 0, 0, 0.88889],
    "9130": [0, 0.3, 0, 0, 0.88889],
    "9131": [1e-5, 0.9, 0, 0, 0.88889],
    "9132": [0.65002, 1.15, 0, 0, 0.88889],
    "9133": [0.90001, 0, 0, 0, 0.88889],
    "9143": [0.88502, 0.915, 0, 0, 1.05556],
    "10216": [1.25003, 1.75, 0, 0, 0.80556],
    "10217": [1.25003, 1.75, 0, 0, 0.80556],
    "57344": [-499e-5, 0.605, 0, 0, 1.05556],
    "57345": [-499e-5, 0.605, 0, 0, 1.05556],
    "57680": [0, 0.12, 0, 0, 0.45],
    "57681": [0, 0.12, 0, 0, 0.45],
    "57682": [0, 0.12, 0, 0, 0.45],
    "57683": [0, 0.12, 0, 0, 0.45]
  },
  "Typewriter-Regular": {
    "32": [0, 0, 0, 0, 0.525],
    "33": [0, 0.61111, 0, 0, 0.525],
    "34": [0, 0.61111, 0, 0, 0.525],
    "35": [0, 0.61111, 0, 0, 0.525],
    "36": [0.08333, 0.69444, 0, 0, 0.525],
    "37": [0.08333, 0.69444, 0, 0, 0.525],
    "38": [0, 0.61111, 0, 0, 0.525],
    "39": [0, 0.61111, 0, 0, 0.525],
    "40": [0.08333, 0.69444, 0, 0, 0.525],
    "41": [0.08333, 0.69444, 0, 0, 0.525],
    "42": [0, 0.52083, 0, 0, 0.525],
    "43": [-0.08056, 0.53055, 0, 0, 0.525],
    "44": [0.13889, 0.125, 0, 0, 0.525],
    "45": [-0.08056, 0.53055, 0, 0, 0.525],
    "46": [0, 0.125, 0, 0, 0.525],
    "47": [0.08333, 0.69444, 0, 0, 0.525],
    "48": [0, 0.61111, 0, 0, 0.525],
    "49": [0, 0.61111, 0, 0, 0.525],
    "50": [0, 0.61111, 0, 0, 0.525],
    "51": [0, 0.61111, 0, 0, 0.525],
    "52": [0, 0.61111, 0, 0, 0.525],
    "53": [0, 0.61111, 0, 0, 0.525],
    "54": [0, 0.61111, 0, 0, 0.525],
    "55": [0, 0.61111, 0, 0, 0.525],
    "56": [0, 0.61111, 0, 0, 0.525],
    "57": [0, 0.61111, 0, 0, 0.525],
    "58": [0, 0.43056, 0, 0, 0.525],
    "59": [0.13889, 0.43056, 0, 0, 0.525],
    "60": [-0.05556, 0.55556, 0, 0, 0.525],
    "61": [-0.19549, 0.41562, 0, 0, 0.525],
    "62": [-0.05556, 0.55556, 0, 0, 0.525],
    "63": [0, 0.61111, 0, 0, 0.525],
    "64": [0, 0.61111, 0, 0, 0.525],
    "65": [0, 0.61111, 0, 0, 0.525],
    "66": [0, 0.61111, 0, 0, 0.525],
    "67": [0, 0.61111, 0, 0, 0.525],
    "68": [0, 0.61111, 0, 0, 0.525],
    "69": [0, 0.61111, 0, 0, 0.525],
    "70": [0, 0.61111, 0, 0, 0.525],
    "71": [0, 0.61111, 0, 0, 0.525],
    "72": [0, 0.61111, 0, 0, 0.525],
    "73": [0, 0.61111, 0, 0, 0.525],
    "74": [0, 0.61111, 0, 0, 0.525],
    "75": [0, 0.61111, 0, 0, 0.525],
    "76": [0, 0.61111, 0, 0, 0.525],
    "77": [0, 0.61111, 0, 0, 0.525],
    "78": [0, 0.61111, 0, 0, 0.525],
    "79": [0, 0.61111, 0, 0, 0.525],
    "80": [0, 0.61111, 0, 0, 0.525],
    "81": [0.13889, 0.61111, 0, 0, 0.525],
    "82": [0, 0.61111, 0, 0, 0.525],
    "83": [0, 0.61111, 0, 0, 0.525],
    "84": [0, 0.61111, 0, 0, 0.525],
    "85": [0, 0.61111, 0, 0, 0.525],
    "86": [0, 0.61111, 0, 0, 0.525],
    "87": [0, 0.61111, 0, 0, 0.525],
    "88": [0, 0.61111, 0, 0, 0.525],
    "89": [0, 0.61111, 0, 0, 0.525],
    "90": [0, 0.61111, 0, 0, 0.525],
    "91": [0.08333, 0.69444, 0, 0, 0.525],
    "92": [0.08333, 0.69444, 0, 0, 0.525],
    "93": [0.08333, 0.69444, 0, 0, 0.525],
    "94": [0, 0.61111, 0, 0, 0.525],
    "95": [0.09514, 0, 0, 0, 0.525],
    "96": [0, 0.61111, 0, 0, 0.525],
    "97": [0, 0.43056, 0, 0, 0.525],
    "98": [0, 0.61111, 0, 0, 0.525],
    "99": [0, 0.43056, 0, 0, 0.525],
    "100": [0, 0.61111, 0, 0, 0.525],
    "101": [0, 0.43056, 0, 0, 0.525],
    "102": [0, 0.61111, 0, 0, 0.525],
    "103": [0.22222, 0.43056, 0, 0, 0.525],
    "104": [0, 0.61111, 0, 0, 0.525],
    "105": [0, 0.61111, 0, 0, 0.525],
    "106": [0.22222, 0.61111, 0, 0, 0.525],
    "107": [0, 0.61111, 0, 0, 0.525],
    "108": [0, 0.61111, 0, 0, 0.525],
    "109": [0, 0.43056, 0, 0, 0.525],
    "110": [0, 0.43056, 0, 0, 0.525],
    "111": [0, 0.43056, 0, 0, 0.525],
    "112": [0.22222, 0.43056, 0, 0, 0.525],
    "113": [0.22222, 0.43056, 0, 0, 0.525],
    "114": [0, 0.43056, 0, 0, 0.525],
    "115": [0, 0.43056, 0, 0, 0.525],
    "116": [0, 0.55358, 0, 0, 0.525],
    "117": [0, 0.43056, 0, 0, 0.525],
    "118": [0, 0.43056, 0, 0, 0.525],
    "119": [0, 0.43056, 0, 0, 0.525],
    "120": [0, 0.43056, 0, 0, 0.525],
    "121": [0.22222, 0.43056, 0, 0, 0.525],
    "122": [0, 0.43056, 0, 0, 0.525],
    "123": [0.08333, 0.69444, 0, 0, 0.525],
    "124": [0.08333, 0.69444, 0, 0, 0.525],
    "125": [0.08333, 0.69444, 0, 0, 0.525],
    "126": [0, 0.61111, 0, 0, 0.525],
    "127": [0, 0.61111, 0, 0, 0.525],
    "160": [0, 0, 0, 0, 0.525],
    "176": [0, 0.61111, 0, 0, 0.525],
    "184": [0.19445, 0, 0, 0, 0.525],
    "305": [0, 0.43056, 0, 0, 0.525],
    "567": [0.22222, 0.43056, 0, 0, 0.525],
    "711": [0, 0.56597, 0, 0, 0.525],
    "713": [0, 0.56555, 0, 0, 0.525],
    "714": [0, 0.61111, 0, 0, 0.525],
    "715": [0, 0.61111, 0, 0, 0.525],
    "728": [0, 0.61111, 0, 0, 0.525],
    "730": [0, 0.61111, 0, 0, 0.525],
    "770": [0, 0.61111, 0, 0, 0.525],
    "771": [0, 0.61111, 0, 0, 0.525],
    "776": [0, 0.61111, 0, 0, 0.525],
    "915": [0, 0.61111, 0, 0, 0.525],
    "916": [0, 0.61111, 0, 0, 0.525],
    "920": [0, 0.61111, 0, 0, 0.525],
    "923": [0, 0.61111, 0, 0, 0.525],
    "926": [0, 0.61111, 0, 0, 0.525],
    "928": [0, 0.61111, 0, 0, 0.525],
    "931": [0, 0.61111, 0, 0, 0.525],
    "933": [0, 0.61111, 0, 0, 0.525],
    "934": [0, 0.61111, 0, 0, 0.525],
    "936": [0, 0.61111, 0, 0, 0.525],
    "937": [0, 0.61111, 0, 0, 0.525],
    "8216": [0, 0.61111, 0, 0, 0.525],
    "8217": [0, 0.61111, 0, 0, 0.525],
    "8242": [0, 0.61111, 0, 0, 0.525],
    "9251": [0.11111, 0.21944, 0, 0, 0.525]
  }
};
var sigmasAndXis = {
  slant: [0.25, 0.25, 0.25],
  // sigma1
  space: [0, 0, 0],
  // sigma2
  stretch: [0, 0, 0],
  // sigma3
  shrink: [0, 0, 0],
  // sigma4
  xHeight: [0.431, 0.431, 0.431],
  // sigma5
  quad: [1, 1.171, 1.472],
  // sigma6
  extraSpace: [0, 0, 0],
  // sigma7
  num1: [0.677, 0.732, 0.925],
  // sigma8
  num2: [0.394, 0.384, 0.387],
  // sigma9
  num3: [0.444, 0.471, 0.504],
  // sigma10
  denom1: [0.686, 0.752, 1.025],
  // sigma11
  denom2: [0.345, 0.344, 0.532],
  // sigma12
  sup1: [0.413, 0.503, 0.504],
  // sigma13
  sup2: [0.363, 0.431, 0.404],
  // sigma14
  sup3: [0.289, 0.286, 0.294],
  // sigma15
  sub1: [0.15, 0.143, 0.2],
  // sigma16
  sub2: [0.247, 0.286, 0.4],
  // sigma17
  supDrop: [0.386, 0.353, 0.494],
  // sigma18
  subDrop: [0.05, 0.071, 0.1],
  // sigma19
  delim1: [2.39, 1.7, 1.98],
  // sigma20
  delim2: [1.01, 1.157, 1.42],
  // sigma21
  axisHeight: [0.25, 0.25, 0.25],
  // sigma22
  // These font metrics are extracted from TeX by using tftopl on cmex10.tfm;
  // they correspond to the font parameters of the extension fonts (family 3).
  // See the TeXbook, page 441. In AMSTeX, the extension fonts scale; to
  // match cmex7, we'd use cmex7.tfm values for script and scriptscript
  // values.
  defaultRuleThickness: [0.04, 0.049, 0.049],
  // xi8; cmex7: 0.049
  bigOpSpacing1: [0.111, 0.111, 0.111],
  // xi9
  bigOpSpacing2: [0.166, 0.166, 0.166],
  // xi10
  bigOpSpacing3: [0.2, 0.2, 0.2],
  // xi11
  bigOpSpacing4: [0.6, 0.611, 0.611],
  // xi12; cmex7: 0.611
  bigOpSpacing5: [0.1, 0.143, 0.143],
  // xi13; cmex7: 0.143
  // The \sqrt rule width is taken from the height of the surd character.
  // Since we use the same font at all sizes, this thickness doesn't scale.
  sqrtRuleThickness: [0.04, 0.04, 0.04],
  // This value determines how large a pt is, for metrics which are defined
  // in terms of pts.
  // This value is also used in katex.scss; if you change it make sure the
  // values match.
  ptPerEm: [10, 10, 10],
  // The space between adjacent `|` columns in an array definition. From
  // `\showthe\doublerulesep` in LaTeX. Equals 2.0 / ptPerEm.
  doubleRuleSep: [0.2, 0.2, 0.2],
  // The width of separator lines in {array} environments. From
  // `\showthe\arrayrulewidth` in LaTeX. Equals 0.4 / ptPerEm.
  arrayRuleWidth: [0.04, 0.04, 0.04],
  // Two values from LaTeX source2e:
  fboxsep: [0.3, 0.3, 0.3],
  //        3 pt / ptPerEm
  fboxrule: [0.04, 0.04, 0.04]
  // 0.4 pt / ptPerEm
};
var extraCharacterMap = {
  // Latin-1
  "\xC5": "A",
  "\xD0": "D",
  "\xDE": "o",
  "\xE5": "a",
  "\xF0": "d",
  "\xFE": "o",
  // Cyrillic
  "\u0410": "A",
  "\u0411": "B",
  "\u0412": "B",
  "\u0413": "F",
  "\u0414": "A",
  "\u0415": "E",
  "\u0416": "K",
  "\u0417": "3",
  "\u0418": "N",
  "\u0419": "N",
  "\u041A": "K",
  "\u041B": "N",
  "\u041C": "M",
  "\u041D": "H",
  "\u041E": "O",
  "\u041F": "N",
  "\u0420": "P",
  "\u0421": "C",
  "\u0422": "T",
  "\u0423": "y",
  "\u0424": "O",
  "\u0425": "X",
  "\u0426": "U",
  "\u0427": "h",
  "\u0428": "W",
  "\u0429": "W",
  "\u042A": "B",
  "\u042B": "X",
  "\u042C": "B",
  "\u042D": "3",
  "\u042E": "X",
  "\u042F": "R",
  "\u0430": "a",
  "\u0431": "b",
  "\u0432": "a",
  "\u0433": "r",
  "\u0434": "y",
  "\u0435": "e",
  "\u0436": "m",
  "\u0437": "e",
  "\u0438": "n",
  "\u0439": "n",
  "\u043A": "n",
  "\u043B": "n",
  "\u043C": "m",
  "\u043D": "n",
  "\u043E": "o",
  "\u043F": "n",
  "\u0440": "p",
  "\u0441": "c",
  "\u0442": "o",
  "\u0443": "y",
  "\u0444": "b",
  "\u0445": "x",
  "\u0446": "n",
  "\u0447": "n",
  "\u0448": "w",
  "\u0449": "w",
  "\u044A": "a",
  "\u044B": "m",
  "\u044C": "a",
  "\u044D": "e",
  "\u044E": "m",
  "\u044F": "r"
};
function setFontMetrics(fontName, metrics) {
  fontMetricsData[fontName] = metrics;
}
function getCharacterMetrics(character, font, mode) {
  if (!fontMetricsData[font]) {
    throw new Error("Font metrics not found for font: " + font + ".");
  }
  var ch = character.charCodeAt(0);
  var metrics = fontMetricsData[font][ch];
  if (!metrics && character[0] in extraCharacterMap) {
    ch = extraCharacterMap[character[0]].charCodeAt(0);
    metrics = fontMetricsData[font][ch];
  }
  if (!metrics && mode === "text") {
    if (supportedCodepoint(ch)) {
      metrics = fontMetricsData[font][77];
    }
  }
  if (metrics) {
    return {
      depth: metrics[0],
      height: metrics[1],
      italic: metrics[2],
      skew: metrics[3],
      width: metrics[4]
    };
  }
}
var fontMetricsBySizeIndex = {};
function getGlobalMetrics(size) {
  var sizeIndex;
  if (size >= 5) {
    sizeIndex = 0;
  } else if (size >= 3) {
    sizeIndex = 1;
  } else {
    sizeIndex = 2;
  }
  if (!fontMetricsBySizeIndex[sizeIndex]) {
    var metrics = fontMetricsBySizeIndex[sizeIndex] = {
      cssEmPerMu: sigmasAndXis.quad[sizeIndex] / 18
    };
    for (var key in sigmasAndXis) {
      if (sigmasAndXis.hasOwnProperty(key)) {
        metrics[key] = sigmasAndXis[key][sizeIndex];
      }
    }
  }
  return fontMetricsBySizeIndex[sizeIndex];
}
var sizeStyleMap = [
  // Each element contains [textsize, scriptsize, scriptscriptsize].
  // The size mappings are taken from TeX with \normalsize=10pt.
  [1, 1, 1],
  // size1: [5, 5, 5]              \tiny
  [2, 1, 1],
  // size2: [6, 5, 5]
  [3, 1, 1],
  // size3: [7, 5, 5]              \scriptsize
  [4, 2, 1],
  // size4: [8, 6, 5]              \footnotesize
  [5, 2, 1],
  // size5: [9, 6, 5]              \small
  [6, 3, 1],
  // size6: [10, 7, 5]             \normalsize
  [7, 4, 2],
  // size7: [12, 8, 6]             \large
  [8, 6, 3],
  // size8: [14.4, 10, 7]          \Large
  [9, 7, 6],
  // size9: [17.28, 12, 10]        \LARGE
  [10, 8, 7],
  // size10: [20.74, 14.4, 12]     \huge
  [11, 10, 9]
  // size11: [24.88, 20.74, 17.28] \HUGE
];
var sizeMultipliers = [
  // fontMetrics.js:getGlobalMetrics also uses size indexes, so if
  // you change size indexes, change that function.
  0.5,
  0.6,
  0.7,
  0.8,
  0.9,
  1,
  1.2,
  1.44,
  1.728,
  2.074,
  2.488
];
var sizeAtStyle = function sizeAtStyle2(size, style) {
  return style.size < 2 ? size : sizeStyleMap[size - 1][style.size - 1];
};
var Options = class _Options {
  // A font family applies to a group of fonts (i.e. SansSerif), while a font
  // represents a specific font (i.e. SansSerif Bold).
  // See: https://tex.stackexchange.com/questions/22350/difference-between-textrm-and-mathrm
  /**
   * The base size index.
   */
  constructor(data) {
    this.style = void 0;
    this.color = void 0;
    this.size = void 0;
    this.textSize = void 0;
    this.phantom = void 0;
    this.font = void 0;
    this.fontFamily = void 0;
    this.fontWeight = void 0;
    this.fontShape = void 0;
    this.sizeMultiplier = void 0;
    this.maxSize = void 0;
    this.minRuleThickness = void 0;
    this._fontMetrics = void 0;
    this.style = data.style;
    this.color = data.color;
    this.size = data.size || _Options.BASESIZE;
    this.textSize = data.textSize || this.size;
    this.phantom = !!data.phantom;
    this.font = data.font || "";
    this.fontFamily = data.fontFamily || "";
    this.fontWeight = data.fontWeight || "";
    this.fontShape = data.fontShape || "";
    this.sizeMultiplier = sizeMultipliers[this.size - 1];
    this.maxSize = data.maxSize;
    this.minRuleThickness = data.minRuleThickness;
    this._fontMetrics = void 0;
  }
  /**
   * Returns a new options object with the same properties as "this".  Properties
   * from "extension" will be copied to the new options object.
   */
  extend(extension) {
    var data = {
      style: this.style,
      size: this.size,
      textSize: this.textSize,
      color: this.color,
      phantom: this.phantom,
      font: this.font,
      fontFamily: this.fontFamily,
      fontWeight: this.fontWeight,
      fontShape: this.fontShape,
      maxSize: this.maxSize,
      minRuleThickness: this.minRuleThickness
    };
    for (var key in extension) {
      if (extension.hasOwnProperty(key)) {
        data[key] = extension[key];
      }
    }
    return new _Options(data);
  }
  /**
   * Return an options object with the given style. If `this.style === style`,
   * returns `this`.
   */
  havingStyle(style) {
    if (this.style === style) {
      return this;
    } else {
      return this.extend({
        style,
        size: sizeAtStyle(this.textSize, style)
      });
    }
  }
  /**
   * Return an options object with a cramped version of the current style. If
   * the current style is cramped, returns `this`.
   */
  havingCrampedStyle() {
    return this.havingStyle(this.style.cramp());
  }
  /**
   * Return an options object with the given size and in at least `\textstyle`.
   * Returns `this` if appropriate.
   */
  havingSize(size) {
    if (this.size === size && this.textSize === size) {
      return this;
    } else {
      return this.extend({
        style: this.style.text(),
        size,
        textSize: size,
        sizeMultiplier: sizeMultipliers[size - 1]
      });
    }
  }
  /**
   * Like `this.havingSize(BASESIZE).havingStyle(style)`. If `style` is omitted,
   * changes to at least `\textstyle`.
   */
  havingBaseStyle(style) {
    style = style || this.style.text();
    var wantSize = sizeAtStyle(_Options.BASESIZE, style);
    if (this.size === wantSize && this.textSize === _Options.BASESIZE && this.style === style) {
      return this;
    } else {
      return this.extend({
        style,
        size: wantSize
      });
    }
  }
  /**
   * Remove the effect of sizing changes such as \Huge.
   * Keep the effect of the current style, such as \scriptstyle.
   */
  havingBaseSizing() {
    var size;
    switch (this.style.id) {
      case 4:
      case 5:
        size = 3;
        break;
      case 6:
      case 7:
        size = 1;
        break;
      default:
        size = 6;
    }
    return this.extend({
      style: this.style.text(),
      size
    });
  }
  /**
   * Create a new options object with the given color.
   */
  withColor(color) {
    return this.extend({
      color
    });
  }
  /**
   * Create a new options object with "phantom" set to true.
   */
  withPhantom() {
    return this.extend({
      phantom: true
    });
  }
  /**
   * Creates a new options object with the given math font or old text font.
   * @type {[type]}
   */
  withFont(font) {
    return this.extend({
      font
    });
  }
  /**
   * Create a new options objects with the given fontFamily.
   */
  withTextFontFamily(fontFamily) {
    return this.extend({
      fontFamily,
      font: ""
    });
  }
  /**
   * Creates a new options object with the given font weight
   */
  withTextFontWeight(fontWeight) {
    return this.extend({
      fontWeight,
      font: ""
    });
  }
  /**
   * Creates a new options object with the given font weight
   */
  withTextFontShape(fontShape) {
    return this.extend({
      fontShape,
      font: ""
    });
  }
  /**
   * Return the CSS sizing classes required to switch from enclosing options
   * `oldOptions` to `this`. Returns an array of classes.
   */
  sizingClasses(oldOptions) {
    if (oldOptions.size !== this.size) {
      return ["sizing", "reset-size" + oldOptions.size, "size" + this.size];
    } else {
      return [];
    }
  }
  /**
   * Return the CSS sizing classes required to switch to the base size. Like
   * `this.havingSize(BASESIZE).sizingClasses(this)`.
   */
  baseSizingClasses() {
    if (this.size !== _Options.BASESIZE) {
      return ["sizing", "reset-size" + this.size, "size" + _Options.BASESIZE];
    } else {
      return [];
    }
  }
  /**
   * Return the font metrics for this size.
   */
  fontMetrics() {
    if (!this._fontMetrics) {
      this._fontMetrics = getGlobalMetrics(this.size);
    }
    return this._fontMetrics;
  }
  /**
   * Gets the CSS color of the current options object
   */
  getColor() {
    if (this.phantom) {
      return "transparent";
    } else {
      return this.color;
    }
  }
};
Options.BASESIZE = 6;
var ptPerUnit = {
  // https://en.wikibooks.org/wiki/LaTeX/Lengths and
  // https://tex.stackexchange.com/a/8263
  "pt": 1,
  // TeX point
  "mm": 7227 / 2540,
  // millimeter
  "cm": 7227 / 254,
  // centimeter
  "in": 72.27,
  // inch
  "bp": 803 / 800,
  // big (PostScript) points
  "pc": 12,
  // pica
  "dd": 1238 / 1157,
  // didot
  "cc": 14856 / 1157,
  // cicero (12 didot)
  "nd": 685 / 642,
  // new didot
  "nc": 1370 / 107,
  // new cicero (12 new didot)
  "sp": 1 / 65536,
  // scaled point (TeX's internal smallest unit)
  // https://tex.stackexchange.com/a/41371
  "px": 803 / 800
  // \pdfpxdimen defaults to 1 bp in pdfTeX and LuaTeX
};
var relativeUnit = {
  "ex": true,
  "em": true,
  "mu": true
};
var validUnit = function validUnit2(unit) {
  if (typeof unit !== "string") {
    unit = unit.unit;
  }
  return unit in ptPerUnit || unit in relativeUnit || unit === "ex";
};
var calculateSize = function calculateSize2(sizeValue, options) {
  var scale;
  if (sizeValue.unit in ptPerUnit) {
    scale = ptPerUnit[sizeValue.unit] / options.fontMetrics().ptPerEm / options.sizeMultiplier;
  } else if (sizeValue.unit === "mu") {
    scale = options.fontMetrics().cssEmPerMu;
  } else {
    var unitOptions;
    if (options.style.isTight()) {
      unitOptions = options.havingStyle(options.style.text());
    } else {
      unitOptions = options;
    }
    if (sizeValue.unit === "ex") {
      scale = unitOptions.fontMetrics().xHeight;
    } else if (sizeValue.unit === "em") {
      scale = unitOptions.fontMetrics().quad;
    } else {
      throw new ParseError("Invalid unit: '" + sizeValue.unit + "'");
    }
    if (unitOptions !== options) {
      scale *= unitOptions.sizeMultiplier / options.sizeMultiplier;
    }
  }
  return Math.min(sizeValue.number * scale, options.maxSize);
};
var makeEm = function makeEm2(n7) {
  return +n7.toFixed(4) + "em";
};
var createClass = function createClass2(classes) {
  return classes.filter((cls) => cls).join(" ");
};
var initNode = function initNode2(classes, options, style) {
  this.classes = classes || [];
  this.attributes = {};
  this.height = 0;
  this.depth = 0;
  this.maxFontSize = 0;
  this.style = style || {};
  if (options) {
    if (options.style.isTight()) {
      this.classes.push("mtight");
    }
    var color = options.getColor();
    if (color) {
      this.style.color = color;
    }
  }
};
var toNode = function toNode2(tagName) {
  var node = document.createElement(tagName);
  node.className = createClass(this.classes);
  for (var style in this.style) {
    if (this.style.hasOwnProperty(style)) {
      node.style[style] = this.style[style];
    }
  }
  for (var attr in this.attributes) {
    if (this.attributes.hasOwnProperty(attr)) {
      node.setAttribute(attr, this.attributes[attr]);
    }
  }
  for (var i7 = 0; i7 < this.children.length; i7++) {
    node.appendChild(this.children[i7].toNode());
  }
  return node;
};
var invalidAttributeNameRegex = /[\s"'>/=\x00-\x1f]/;
var toMarkup = function toMarkup2(tagName) {
  var markup = "<" + tagName;
  if (this.classes.length) {
    markup += ' class="' + utils2.escape(createClass(this.classes)) + '"';
  }
  var styles2 = "";
  for (var style in this.style) {
    if (this.style.hasOwnProperty(style)) {
      styles2 += utils2.hyphenate(style) + ":" + this.style[style] + ";";
    }
  }
  if (styles2) {
    markup += ' style="' + utils2.escape(styles2) + '"';
  }
  for (var attr in this.attributes) {
    if (this.attributes.hasOwnProperty(attr)) {
      if (invalidAttributeNameRegex.test(attr)) {
        throw new ParseError("Invalid attribute name '" + attr + "'");
      }
      markup += " " + attr + '="' + utils2.escape(this.attributes[attr]) + '"';
    }
  }
  markup += ">";
  for (var i7 = 0; i7 < this.children.length; i7++) {
    markup += this.children[i7].toMarkup();
  }
  markup += "</" + tagName + ">";
  return markup;
};
var Span = class {
  constructor(classes, children, options, style) {
    this.children = void 0;
    this.attributes = void 0;
    this.classes = void 0;
    this.height = void 0;
    this.depth = void 0;
    this.width = void 0;
    this.maxFontSize = void 0;
    this.style = void 0;
    initNode.call(this, classes, options, style);
    this.children = children || [];
  }
  /**
   * Sets an arbitrary attribute on the span. Warning: use this wisely. Not
   * all browsers support attributes the same, and having too many custom
   * attributes is probably bad.
   */
  setAttribute(attribute, value) {
    this.attributes[attribute] = value;
  }
  hasClass(className) {
    return utils2.contains(this.classes, className);
  }
  toNode() {
    return toNode.call(this, "span");
  }
  toMarkup() {
    return toMarkup.call(this, "span");
  }
};
var Anchor = class {
  constructor(href, classes, children, options) {
    this.children = void 0;
    this.attributes = void 0;
    this.classes = void 0;
    this.height = void 0;
    this.depth = void 0;
    this.maxFontSize = void 0;
    this.style = void 0;
    initNode.call(this, classes, options);
    this.children = children || [];
    this.setAttribute("href", href);
  }
  setAttribute(attribute, value) {
    this.attributes[attribute] = value;
  }
  hasClass(className) {
    return utils2.contains(this.classes, className);
  }
  toNode() {
    return toNode.call(this, "a");
  }
  toMarkup() {
    return toMarkup.call(this, "a");
  }
};
var Img = class {
  constructor(src, alt, style) {
    this.src = void 0;
    this.alt = void 0;
    this.classes = void 0;
    this.height = void 0;
    this.depth = void 0;
    this.maxFontSize = void 0;
    this.style = void 0;
    this.alt = alt;
    this.src = src;
    this.classes = ["mord"];
    this.style = style;
  }
  hasClass(className) {
    return utils2.contains(this.classes, className);
  }
  toNode() {
    var node = document.createElement("img");
    node.src = this.src;
    node.alt = this.alt;
    node.className = "mord";
    for (var style in this.style) {
      if (this.style.hasOwnProperty(style)) {
        node.style[style] = this.style[style];
      }
    }
    return node;
  }
  toMarkup() {
    var markup = '<img src="' + utils2.escape(this.src) + '"' + (' alt="' + utils2.escape(this.alt) + '"');
    var styles2 = "";
    for (var style in this.style) {
      if (this.style.hasOwnProperty(style)) {
        styles2 += utils2.hyphenate(style) + ":" + this.style[style] + ";";
      }
    }
    if (styles2) {
      markup += ' style="' + utils2.escape(styles2) + '"';
    }
    markup += "'/>";
    return markup;
  }
};
var iCombinations = {
  "\xEE": "\u0131\u0302",
  "\xEF": "\u0131\u0308",
  "\xED": "\u0131\u0301",
  // 'ī': '\u0131\u0304', // enable when we add Extended Latin
  "\xEC": "\u0131\u0300"
};
var SymbolNode = class {
  constructor(text3, height, depth, italic, skew, width, classes, style) {
    this.text = void 0;
    this.height = void 0;
    this.depth = void 0;
    this.italic = void 0;
    this.skew = void 0;
    this.width = void 0;
    this.maxFontSize = void 0;
    this.classes = void 0;
    this.style = void 0;
    this.text = text3;
    this.height = height || 0;
    this.depth = depth || 0;
    this.italic = italic || 0;
    this.skew = skew || 0;
    this.width = width || 0;
    this.classes = classes || [];
    this.style = style || {};
    this.maxFontSize = 0;
    var script = scriptFromCodepoint(this.text.charCodeAt(0));
    if (script) {
      this.classes.push(script + "_fallback");
    }
    if (/[îïíì]/.test(this.text)) {
      this.text = iCombinations[this.text];
    }
  }
  hasClass(className) {
    return utils2.contains(this.classes, className);
  }
  /**
   * Creates a text node or span from a symbol node. Note that a span is only
   * created if it is needed.
   */
  toNode() {
    var node = document.createTextNode(this.text);
    var span = null;
    if (this.italic > 0) {
      span = document.createElement("span");
      span.style.marginRight = makeEm(this.italic);
    }
    if (this.classes.length > 0) {
      span = span || document.createElement("span");
      span.className = createClass(this.classes);
    }
    for (var style in this.style) {
      if (this.style.hasOwnProperty(style)) {
        span = span || document.createElement("span");
        span.style[style] = this.style[style];
      }
    }
    if (span) {
      span.appendChild(node);
      return span;
    } else {
      return node;
    }
  }
  /**
   * Creates markup for a symbol node.
   */
  toMarkup() {
    var needsSpan = false;
    var markup = "<span";
    if (this.classes.length) {
      needsSpan = true;
      markup += ' class="';
      markup += utils2.escape(createClass(this.classes));
      markup += '"';
    }
    var styles2 = "";
    if (this.italic > 0) {
      styles2 += "margin-right:" + this.italic + "em;";
    }
    for (var style in this.style) {
      if (this.style.hasOwnProperty(style)) {
        styles2 += utils2.hyphenate(style) + ":" + this.style[style] + ";";
      }
    }
    if (styles2) {
      needsSpan = true;
      markup += ' style="' + utils2.escape(styles2) + '"';
    }
    var escaped = utils2.escape(this.text);
    if (needsSpan) {
      markup += ">";
      markup += escaped;
      markup += "</span>";
      return markup;
    } else {
      return escaped;
    }
  }
};
var SvgNode = class {
  constructor(children, attributes) {
    this.children = void 0;
    this.attributes = void 0;
    this.children = children || [];
    this.attributes = attributes || {};
  }
  toNode() {
    var svgNS = "http://www.w3.org/2000/svg";
    var node = document.createElementNS(svgNS, "svg");
    for (var attr in this.attributes) {
      if (Object.prototype.hasOwnProperty.call(this.attributes, attr)) {
        node.setAttribute(attr, this.attributes[attr]);
      }
    }
    for (var i7 = 0; i7 < this.children.length; i7++) {
      node.appendChild(this.children[i7].toNode());
    }
    return node;
  }
  toMarkup() {
    var markup = '<svg xmlns="http://www.w3.org/2000/svg"';
    for (var attr in this.attributes) {
      if (Object.prototype.hasOwnProperty.call(this.attributes, attr)) {
        markup += " " + attr + '="' + utils2.escape(this.attributes[attr]) + '"';
      }
    }
    markup += ">";
    for (var i7 = 0; i7 < this.children.length; i7++) {
      markup += this.children[i7].toMarkup();
    }
    markup += "</svg>";
    return markup;
  }
};
var PathNode = class {
  constructor(pathName, alternate) {
    this.pathName = void 0;
    this.alternate = void 0;
    this.pathName = pathName;
    this.alternate = alternate;
  }
  toNode() {
    var svgNS = "http://www.w3.org/2000/svg";
    var node = document.createElementNS(svgNS, "path");
    if (this.alternate) {
      node.setAttribute("d", this.alternate);
    } else {
      node.setAttribute("d", path4[this.pathName]);
    }
    return node;
  }
  toMarkup() {
    if (this.alternate) {
      return '<path d="' + utils2.escape(this.alternate) + '"/>';
    } else {
      return '<path d="' + utils2.escape(path4[this.pathName]) + '"/>';
    }
  }
};
var LineNode = class {
  constructor(attributes) {
    this.attributes = void 0;
    this.attributes = attributes || {};
  }
  toNode() {
    var svgNS = "http://www.w3.org/2000/svg";
    var node = document.createElementNS(svgNS, "line");
    for (var attr in this.attributes) {
      if (Object.prototype.hasOwnProperty.call(this.attributes, attr)) {
        node.setAttribute(attr, this.attributes[attr]);
      }
    }
    return node;
  }
  toMarkup() {
    var markup = "<line";
    for (var attr in this.attributes) {
      if (Object.prototype.hasOwnProperty.call(this.attributes, attr)) {
        markup += " " + attr + '="' + utils2.escape(this.attributes[attr]) + '"';
      }
    }
    markup += "/>";
    return markup;
  }
};
function assertSymbolDomNode(group) {
  if (group instanceof SymbolNode) {
    return group;
  } else {
    throw new Error("Expected symbolNode but got " + String(group) + ".");
  }
}
function assertSpan(group) {
  if (group instanceof Span) {
    return group;
  } else {
    throw new Error("Expected span<HtmlDomNode> but got " + String(group) + ".");
  }
}
var ATOMS = {
  "bin": 1,
  "close": 1,
  "inner": 1,
  "open": 1,
  "punct": 1,
  "rel": 1
};
var NON_ATOMS = {
  "accent-token": 1,
  "mathord": 1,
  "op-token": 1,
  "spacing": 1,
  "textord": 1
};
var symbols = {
  "math": {},
  "text": {}
};
function defineSymbol(mode, font, group, replace, name, acceptUnicodeChar) {
  symbols[mode][name] = {
    font,
    group,
    replace
  };
  if (acceptUnicodeChar && replace) {
    symbols[mode][replace] = symbols[mode][name];
  }
}
var math = "math";
var text2 = "text";
var main = "main";
var ams = "ams";
var accent = "accent-token";
var bin = "bin";
var close = "close";
var inner = "inner";
var mathord = "mathord";
var op = "op-token";
var open = "open";
var punct = "punct";
var rel = "rel";
var spacing = "spacing";
var textord = "textord";
defineSymbol(math, main, rel, "\u2261", "\\equiv", true);
defineSymbol(math, main, rel, "\u227A", "\\prec", true);
defineSymbol(math, main, rel, "\u227B", "\\succ", true);
defineSymbol(math, main, rel, "\u223C", "\\sim", true);
defineSymbol(math, main, rel, "\u22A5", "\\perp");
defineSymbol(math, main, rel, "\u2AAF", "\\preceq", true);
defineSymbol(math, main, rel, "\u2AB0", "\\succeq", true);
defineSymbol(math, main, rel, "\u2243", "\\simeq", true);
defineSymbol(math, main, rel, "\u2223", "\\mid", true);
defineSymbol(math, main, rel, "\u226A", "\\ll", true);
defineSymbol(math, main, rel, "\u226B", "\\gg", true);
defineSymbol(math, main, rel, "\u224D", "\\asymp", true);
defineSymbol(math, main, rel, "\u2225", "\\parallel");
defineSymbol(math, main, rel, "\u22C8", "\\bowtie", true);
defineSymbol(math, main, rel, "\u2323", "\\smile", true);
defineSymbol(math, main, rel, "\u2291", "\\sqsubseteq", true);
defineSymbol(math, main, rel, "\u2292", "\\sqsupseteq", true);
defineSymbol(math, main, rel, "\u2250", "\\doteq", true);
defineSymbol(math, main, rel, "\u2322", "\\frown", true);
defineSymbol(math, main, rel, "\u220B", "\\ni", true);
defineSymbol(math, main, rel, "\u221D", "\\propto", true);
defineSymbol(math, main, rel, "\u22A2", "\\vdash", true);
defineSymbol(math, main, rel, "\u22A3", "\\dashv", true);
defineSymbol(math, main, rel, "\u220B", "\\owns");
defineSymbol(math, main, punct, ".", "\\ldotp");
defineSymbol(math, main, punct, "\u22C5", "\\cdotp");
defineSymbol(math, main, textord, "#", "\\#");
defineSymbol(text2, main, textord, "#", "\\#");
defineSymbol(math, main, textord, "&", "\\&");
defineSymbol(text2, main, textord, "&", "\\&");
defineSymbol(math, main, textord, "\u2135", "\\aleph", true);
defineSymbol(math, main, textord, "\u2200", "\\forall", true);
defineSymbol(math, main, textord, "\u210F", "\\hbar", true);
defineSymbol(math, main, textord, "\u2203", "\\exists", true);
defineSymbol(math, main, textord, "\u2207", "\\nabla", true);
defineSymbol(math, main, textord, "\u266D", "\\flat", true);
defineSymbol(math, main, textord, "\u2113", "\\ell", true);
defineSymbol(math, main, textord, "\u266E", "\\natural", true);
defineSymbol(math, main, textord, "\u2663", "\\clubsuit", true);
defineSymbol(math, main, textord, "\u2118", "\\wp", true);
defineSymbol(math, main, textord, "\u266F", "\\sharp", true);
defineSymbol(math, main, textord, "\u2662", "\\diamondsuit", true);
defineSymbol(math, main, textord, "\u211C", "\\Re", true);
defineSymbol(math, main, textord, "\u2661", "\\heartsuit", true);
defineSymbol(math, main, textord, "\u2111", "\\Im", true);
defineSymbol(math, main, textord, "\u2660", "\\spadesuit", true);
defineSymbol(math, main, textord, "\xA7", "\\S", true);
defineSymbol(text2, main, textord, "\xA7", "\\S");
defineSymbol(math, main, textord, "\xB6", "\\P", true);
defineSymbol(text2, main, textord, "\xB6", "\\P");
defineSymbol(math, main, textord, "\u2020", "\\dag");
defineSymbol(text2, main, textord, "\u2020", "\\dag");
defineSymbol(text2, main, textord, "\u2020", "\\textdagger");
defineSymbol(math, main, textord, "\u2021", "\\ddag");
defineSymbol(text2, main, textord, "\u2021", "\\ddag");
defineSymbol(text2, main, textord, "\u2021", "\\textdaggerdbl");
defineSymbol(math, main, close, "\u23B1", "\\rmoustache", true);
defineSymbol(math, main, open, "\u23B0", "\\lmoustache", true);
defineSymbol(math, main, close, "\u27EF", "\\rgroup", true);
defineSymbol(math, main, open, "\u27EE", "\\lgroup", true);
defineSymbol(math, main, bin, "\u2213", "\\mp", true);
defineSymbol(math, main, bin, "\u2296", "\\ominus", true);
defineSymbol(math, main, bin, "\u228E", "\\uplus", true);
defineSymbol(math, main, bin, "\u2293", "\\sqcap", true);
defineSymbol(math, main, bin, "\u2217", "\\ast");
defineSymbol(math, main, bin, "\u2294", "\\sqcup", true);
defineSymbol(math, main, bin, "\u25EF", "\\bigcirc", true);
defineSymbol(math, main, bin, "\u2219", "\\bullet", true);
defineSymbol(math, main, bin, "\u2021", "\\ddagger");
defineSymbol(math, main, bin, "\u2240", "\\wr", true);
defineSymbol(math, main, bin, "\u2A3F", "\\amalg");
defineSymbol(math, main, bin, "&", "\\And");
defineSymbol(math, main, rel, "\u27F5", "\\longleftarrow", true);
defineSymbol(math, main, rel, "\u21D0", "\\Leftarrow", true);
defineSymbol(math, main, rel, "\u27F8", "\\Longleftarrow", true);
defineSymbol(math, main, rel, "\u27F6", "\\longrightarrow", true);
defineSymbol(math, main, rel, "\u21D2", "\\Rightarrow", true);
defineSymbol(math, main, rel, "\u27F9", "\\Longrightarrow", true);
defineSymbol(math, main, rel, "\u2194", "\\leftrightarrow", true);
defineSymbol(math, main, rel, "\u27F7", "\\longleftrightarrow", true);
defineSymbol(math, main, rel, "\u21D4", "\\Leftrightarrow", true);
defineSymbol(math, main, rel, "\u27FA", "\\Longleftrightarrow", true);
defineSymbol(math, main, rel, "\u21A6", "\\mapsto", true);
defineSymbol(math, main, rel, "\u27FC", "\\longmapsto", true);
defineSymbol(math, main, rel, "\u2197", "\\nearrow", true);
defineSymbol(math, main, rel, "\u21A9", "\\hookleftarrow", true);
defineSymbol(math, main, rel, "\u21AA", "\\hookrightarrow", true);
defineSymbol(math, main, rel, "\u2198", "\\searrow", true);
defineSymbol(math, main, rel, "\u21BC", "\\leftharpoonup", true);
defineSymbol(math, main, rel, "\u21C0", "\\rightharpoonup", true);
defineSymbol(math, main, rel, "\u2199", "\\swarrow", true);
defineSymbol(math, main, rel, "\u21BD", "\\leftharpoondown", true);
defineSymbol(math, main, rel, "\u21C1", "\\rightharpoondown", true);
defineSymbol(math, main, rel, "\u2196", "\\nwarrow", true);
defineSymbol(math, main, rel, "\u21CC", "\\rightleftharpoons", true);
defineSymbol(math, ams, rel, "\u226E", "\\nless", true);
defineSymbol(math, ams, rel, "\uE010", "\\@nleqslant");
defineSymbol(math, ams, rel, "\uE011", "\\@nleqq");
defineSymbol(math, ams, rel, "\u2A87", "\\lneq", true);
defineSymbol(math, ams, rel, "\u2268", "\\lneqq", true);
defineSymbol(math, ams, rel, "\uE00C", "\\@lvertneqq");
defineSymbol(math, ams, rel, "\u22E6", "\\lnsim", true);
defineSymbol(math, ams, rel, "\u2A89", "\\lnapprox", true);
defineSymbol(math, ams, rel, "\u2280", "\\nprec", true);
defineSymbol(math, ams, rel, "\u22E0", "\\npreceq", true);
defineSymbol(math, ams, rel, "\u22E8", "\\precnsim", true);
defineSymbol(math, ams, rel, "\u2AB9", "\\precnapprox", true);
defineSymbol(math, ams, rel, "\u2241", "\\nsim", true);
defineSymbol(math, ams, rel, "\uE006", "\\@nshortmid");
defineSymbol(math, ams, rel, "\u2224", "\\nmid", true);
defineSymbol(math, ams, rel, "\u22AC", "\\nvdash", true);
defineSymbol(math, ams, rel, "\u22AD", "\\nvDash", true);
defineSymbol(math, ams, rel, "\u22EA", "\\ntriangleleft");
defineSymbol(math, ams, rel, "\u22EC", "\\ntrianglelefteq", true);
defineSymbol(math, ams, rel, "\u228A", "\\subsetneq", true);
defineSymbol(math, ams, rel, "\uE01A", "\\@varsubsetneq");
defineSymbol(math, ams, rel, "\u2ACB", "\\subsetneqq", true);
defineSymbol(math, ams, rel, "\uE017", "\\@varsubsetneqq");
defineSymbol(math, ams, rel, "\u226F", "\\ngtr", true);
defineSymbol(math, ams, rel, "\uE00F", "\\@ngeqslant");
defineSymbol(math, ams, rel, "\uE00E", "\\@ngeqq");
defineSymbol(math, ams, rel, "\u2A88", "\\gneq", true);
defineSymbol(math, ams, rel, "\u2269", "\\gneqq", true);
defineSymbol(math, ams, rel, "\uE00D", "\\@gvertneqq");
defineSymbol(math, ams, rel, "\u22E7", "\\gnsim", true);
defineSymbol(math, ams, rel, "\u2A8A", "\\gnapprox", true);
defineSymbol(math, ams, rel, "\u2281", "\\nsucc", true);
defineSymbol(math, ams, rel, "\u22E1", "\\nsucceq", true);
defineSymbol(math, ams, rel, "\u22E9", "\\succnsim", true);
defineSymbol(math, ams, rel, "\u2ABA", "\\succnapprox", true);
defineSymbol(math, ams, rel, "\u2246", "\\ncong", true);
defineSymbol(math, ams, rel, "\uE007", "\\@nshortparallel");
defineSymbol(math, ams, rel, "\u2226", "\\nparallel", true);
defineSymbol(math, ams, rel, "\u22AF", "\\nVDash", true);
defineSymbol(math, ams, rel, "\u22EB", "\\ntriangleright");
defineSymbol(math, ams, rel, "\u22ED", "\\ntrianglerighteq", true);
defineSymbol(math, ams, rel, "\uE018", "\\@nsupseteqq");
defineSymbol(math, ams, rel, "\u228B", "\\supsetneq", true);
defineSymbol(math, ams, rel, "\uE01B", "\\@varsupsetneq");
defineSymbol(math, ams, rel, "\u2ACC", "\\supsetneqq", true);
defineSymbol(math, ams, rel, "\uE019", "\\@varsupsetneqq");
defineSymbol(math, ams, rel, "\u22AE", "\\nVdash", true);
defineSymbol(math, ams, rel, "\u2AB5", "\\precneqq", true);
defineSymbol(math, ams, rel, "\u2AB6", "\\succneqq", true);
defineSymbol(math, ams, rel, "\uE016", "\\@nsubseteqq");
defineSymbol(math, ams, bin, "\u22B4", "\\unlhd");
defineSymbol(math, ams, bin, "\u22B5", "\\unrhd");
defineSymbol(math, ams, rel, "\u219A", "\\nleftarrow", true);
defineSymbol(math, ams, rel, "\u219B", "\\nrightarrow", true);
defineSymbol(math, ams, rel, "\u21CD", "\\nLeftarrow", true);
defineSymbol(math, ams, rel, "\u21CF", "\\nRightarrow", true);
defineSymbol(math, ams, rel, "\u21AE", "\\nleftrightarrow", true);
defineSymbol(math, ams, rel, "\u21CE", "\\nLeftrightarrow", true);
defineSymbol(math, ams, rel, "\u25B3", "\\vartriangle");
defineSymbol(math, ams, textord, "\u210F", "\\hslash");
defineSymbol(math, ams, textord, "\u25BD", "\\triangledown");
defineSymbol(math, ams, textord, "\u25CA", "\\lozenge");
defineSymbol(math, ams, textord, "\u24C8", "\\circledS");
defineSymbol(math, ams, textord, "\xAE", "\\circledR");
defineSymbol(text2, ams, textord, "\xAE", "\\circledR");
defineSymbol(math, ams, textord, "\u2221", "\\measuredangle", true);
defineSymbol(math, ams, textord, "\u2204", "\\nexists");
defineSymbol(math, ams, textord, "\u2127", "\\mho");
defineSymbol(math, ams, textord, "\u2132", "\\Finv", true);
defineSymbol(math, ams, textord, "\u2141", "\\Game", true);
defineSymbol(math, ams, textord, "\u2035", "\\backprime");
defineSymbol(math, ams, textord, "\u25B2", "\\blacktriangle");
defineSymbol(math, ams, textord, "\u25BC", "\\blacktriangledown");
defineSymbol(math, ams, textord, "\u25A0", "\\blacksquare");
defineSymbol(math, ams, textord, "\u29EB", "\\blacklozenge");
defineSymbol(math, ams, textord, "\u2605", "\\bigstar");
defineSymbol(math, ams, textord, "\u2222", "\\sphericalangle", true);
defineSymbol(math, ams, textord, "\u2201", "\\complement", true);
defineSymbol(math, ams, textord, "\xF0", "\\eth", true);
defineSymbol(text2, main, textord, "\xF0", "\xF0");
defineSymbol(math, ams, textord, "\u2571", "\\diagup");
defineSymbol(math, ams, textord, "\u2572", "\\diagdown");
defineSymbol(math, ams, textord, "\u25A1", "\\square");
defineSymbol(math, ams, textord, "\u25A1", "\\Box");
defineSymbol(math, ams, textord, "\u25CA", "\\Diamond");
defineSymbol(math, ams, textord, "\xA5", "\\yen", true);
defineSymbol(text2, ams, textord, "\xA5", "\\yen", true);
defineSymbol(math, ams, textord, "\u2713", "\\checkmark", true);
defineSymbol(text2, ams, textord, "\u2713", "\\checkmark");
defineSymbol(math, ams, textord, "\u2136", "\\beth", true);
defineSymbol(math, ams, textord, "\u2138", "\\daleth", true);
defineSymbol(math, ams, textord, "\u2137", "\\gimel", true);
defineSymbol(math, ams, textord, "\u03DD", "\\digamma", true);
defineSymbol(math, ams, textord, "\u03F0", "\\varkappa");
defineSymbol(math, ams, open, "\u250C", "\\@ulcorner", true);
defineSymbol(math, ams, close, "\u2510", "\\@urcorner", true);
defineSymbol(math, ams, open, "\u2514", "\\@llcorner", true);
defineSymbol(math, ams, close, "\u2518", "\\@lrcorner", true);
defineSymbol(math, ams, rel, "\u2266", "\\leqq", true);
defineSymbol(math, ams, rel, "\u2A7D", "\\leqslant", true);
defineSymbol(math, ams, rel, "\u2A95", "\\eqslantless", true);
defineSymbol(math, ams, rel, "\u2272", "\\lesssim", true);
defineSymbol(math, ams, rel, "\u2A85", "\\lessapprox", true);
defineSymbol(math, ams, rel, "\u224A", "\\approxeq", true);
defineSymbol(math, ams, bin, "\u22D6", "\\lessdot");
defineSymbol(math, ams, rel, "\u22D8", "\\lll", true);
defineSymbol(math, ams, rel, "\u2276", "\\lessgtr", true);
defineSymbol(math, ams, rel, "\u22DA", "\\lesseqgtr", true);
defineSymbol(math, ams, rel, "\u2A8B", "\\lesseqqgtr", true);
defineSymbol(math, ams, rel, "\u2251", "\\doteqdot");
defineSymbol(math, ams, rel, "\u2253", "\\risingdotseq", true);
defineSymbol(math, ams, rel, "\u2252", "\\fallingdotseq", true);
defineSymbol(math, ams, rel, "\u223D", "\\backsim", true);
defineSymbol(math, ams, rel, "\u22CD", "\\backsimeq", true);
defineSymbol(math, ams, rel, "\u2AC5", "\\subseteqq", true);
defineSymbol(math, ams, rel, "\u22D0", "\\Subset", true);
defineSymbol(math, ams, rel, "\u228F", "\\sqsubset", true);
defineSymbol(math, ams, rel, "\u227C", "\\preccurlyeq", true);
defineSymbol(math, ams, rel, "\u22DE", "\\curlyeqprec", true);
defineSymbol(math, ams, rel, "\u227E", "\\precsim", true);
defineSymbol(math, ams, rel, "\u2AB7", "\\precapprox", true);
defineSymbol(math, ams, rel, "\u22B2", "\\vartriangleleft");
defineSymbol(math, ams, rel, "\u22B4", "\\trianglelefteq");
defineSymbol(math, ams, rel, "\u22A8", "\\vDash", true);
defineSymbol(math, ams, rel, "\u22AA", "\\Vvdash", true);
defineSymbol(math, ams, rel, "\u2323", "\\smallsmile");
defineSymbol(math, ams, rel, "\u2322", "\\smallfrown");
defineSymbol(math, ams, rel, "\u224F", "\\bumpeq", true);
defineSymbol(math, ams, rel, "\u224E", "\\Bumpeq", true);
defineSymbol(math, ams, rel, "\u2267", "\\geqq", true);
defineSymbol(math, ams, rel, "\u2A7E", "\\geqslant", true);
defineSymbol(math, ams, rel, "\u2A96", "\\eqslantgtr", true);
defineSymbol(math, ams, rel, "\u2273", "\\gtrsim", true);
defineSymbol(math, ams, rel, "\u2A86", "\\gtrapprox", true);
defineSymbol(math, ams, bin, "\u22D7", "\\gtrdot");
defineSymbol(math, ams, rel, "\u22D9", "\\ggg", true);
defineSymbol(math, ams, rel, "\u2277", "\\gtrless", true);
defineSymbol(math, ams, rel, "\u22DB", "\\gtreqless", true);
defineSymbol(math, ams, rel, "\u2A8C", "\\gtreqqless", true);
defineSymbol(math, ams, rel, "\u2256", "\\eqcirc", true);
defineSymbol(math, ams, rel, "\u2257", "\\circeq", true);
defineSymbol(math, ams, rel, "\u225C", "\\triangleq", true);
defineSymbol(math, ams, rel, "\u223C", "\\thicksim");
defineSymbol(math, ams, rel, "\u2248", "\\thickapprox");
defineSymbol(math, ams, rel, "\u2AC6", "\\supseteqq", true);
defineSymbol(math, ams, rel, "\u22D1", "\\Supset", true);
defineSymbol(math, ams, rel, "\u2290", "\\sqsupset", true);
defineSymbol(math, ams, rel, "\u227D", "\\succcurlyeq", true);
defineSymbol(math, ams, rel, "\u22DF", "\\curlyeqsucc", true);
defineSymbol(math, ams, rel, "\u227F", "\\succsim", true);
defineSymbol(math, ams, rel, "\u2AB8", "\\succapprox", true);
defineSymbol(math, ams, rel, "\u22B3", "\\vartriangleright");
defineSymbol(math, ams, rel, "\u22B5", "\\trianglerighteq");
defineSymbol(math, ams, rel, "\u22A9", "\\Vdash", true);
defineSymbol(math, ams, rel, "\u2223", "\\shortmid");
defineSymbol(math, ams, rel, "\u2225", "\\shortparallel");
defineSymbol(math, ams, rel, "\u226C", "\\between", true);
defineSymbol(math, ams, rel, "\u22D4", "\\pitchfork", true);
defineSymbol(math, ams, rel, "\u221D", "\\varpropto");
defineSymbol(math, ams, rel, "\u25C0", "\\blacktriangleleft");
defineSymbol(math, ams, rel, "\u2234", "\\therefore", true);
defineSymbol(math, ams, rel, "\u220D", "\\backepsilon");
defineSymbol(math, ams, rel, "\u25B6", "\\blacktriangleright");
defineSymbol(math, ams, rel, "\u2235", "\\because", true);
defineSymbol(math, ams, rel, "\u22D8", "\\llless");
defineSymbol(math, ams, rel, "\u22D9", "\\gggtr");
defineSymbol(math, ams, bin, "\u22B2", "\\lhd");
defineSymbol(math, ams, bin, "\u22B3", "\\rhd");
defineSymbol(math, ams, rel, "\u2242", "\\eqsim", true);
defineSymbol(math, main, rel, "\u22C8", "\\Join");
defineSymbol(math, ams, rel, "\u2251", "\\Doteq", true);
defineSymbol(math, ams, bin, "\u2214", "\\dotplus", true);
defineSymbol(math, ams, bin, "\u2216", "\\smallsetminus");
defineSymbol(math, ams, bin, "\u22D2", "\\Cap", true);
defineSymbol(math, ams, bin, "\u22D3", "\\Cup", true);
defineSymbol(math, ams, bin, "\u2A5E", "\\doublebarwedge", true);
defineSymbol(math, ams, bin, "\u229F", "\\boxminus", true);
defineSymbol(math, ams, bin, "\u229E", "\\boxplus", true);
defineSymbol(math, ams, bin, "\u22C7", "\\divideontimes", true);
defineSymbol(math, ams, bin, "\u22C9", "\\ltimes", true);
defineSymbol(math, ams, bin, "\u22CA", "\\rtimes", true);
defineSymbol(math, ams, bin, "\u22CB", "\\leftthreetimes", true);
defineSymbol(math, ams, bin, "\u22CC", "\\rightthreetimes", true);
defineSymbol(math, ams, bin, "\u22CF", "\\curlywedge", true);
defineSymbol(math, ams, bin, "\u22CE", "\\curlyvee", true);
defineSymbol(math, ams, bin, "\u229D", "\\circleddash", true);
defineSymbol(math, ams, bin, "\u229B", "\\circledast", true);
defineSymbol(math, ams, bin, "\u22C5", "\\centerdot");
defineSymbol(math, ams, bin, "\u22BA", "\\intercal", true);
defineSymbol(math, ams, bin, "\u22D2", "\\doublecap");
defineSymbol(math, ams, bin, "\u22D3", "\\doublecup");
defineSymbol(math, ams, bin, "\u22A0", "\\boxtimes", true);
defineSymbol(math, ams, rel, "\u21E2", "\\dashrightarrow", true);
defineSymbol(math, ams, rel, "\u21E0", "\\dashleftarrow", true);
defineSymbol(math, ams, rel, "\u21C7", "\\leftleftarrows", true);
defineSymbol(math, ams, rel, "\u21C6", "\\leftrightarrows", true);
defineSymbol(math, ams, rel, "\u21DA", "\\Lleftarrow", true);
defineSymbol(math, ams, rel, "\u219E", "\\twoheadleftarrow", true);
defineSymbol(math, ams, rel, "\u21A2", "\\leftarrowtail", true);
defineSymbol(math, ams, rel, "\u21AB", "\\looparrowleft", true);
defineSymbol(math, ams, rel, "\u21CB", "\\leftrightharpoons", true);
defineSymbol(math, ams, rel, "\u21B6", "\\curvearrowleft", true);
defineSymbol(math, ams, rel, "\u21BA", "\\circlearrowleft", true);
defineSymbol(math, ams, rel, "\u21B0", "\\Lsh", true);
defineSymbol(math, ams, rel, "\u21C8", "\\upuparrows", true);
defineSymbol(math, ams, rel, "\u21BF", "\\upharpoonleft", true);
defineSymbol(math, ams, rel, "\u21C3", "\\downharpoonleft", true);
defineSymbol(math, main, rel, "\u22B6", "\\origof", true);
defineSymbol(math, main, rel, "\u22B7", "\\imageof", true);
defineSymbol(math, ams, rel, "\u22B8", "\\multimap", true);
defineSymbol(math, ams, rel, "\u21AD", "\\leftrightsquigarrow", true);
defineSymbol(math, ams, rel, "\u21C9", "\\rightrightarrows", true);
defineSymbol(math, ams, rel, "\u21C4", "\\rightleftarrows", true);
defineSymbol(math, ams, rel, "\u21A0", "\\twoheadrightarrow", true);
defineSymbol(math, ams, rel, "\u21A3", "\\rightarrowtail", true);
defineSymbol(math, ams, rel, "\u21AC", "\\looparrowright", true);
defineSymbol(math, ams, rel, "\u21B7", "\\curvearrowright", true);
defineSymbol(math, ams, rel, "\u21BB", "\\circlearrowright", true);
defineSymbol(math, ams, rel, "\u21B1", "\\Rsh", true);
defineSymbol(math, ams, rel, "\u21CA", "\\downdownarrows", true);
defineSymbol(math, ams, rel, "\u21BE", "\\upharpoonright", true);
defineSymbol(math, ams, rel, "\u21C2", "\\downharpoonright", true);
defineSymbol(math, ams, rel, "\u21DD", "\\rightsquigarrow", true);
defineSymbol(math, ams, rel, "\u21DD", "\\leadsto");
defineSymbol(math, ams, rel, "\u21DB", "\\Rrightarrow", true);
defineSymbol(math, ams, rel, "\u21BE", "\\restriction");
defineSymbol(math, main, textord, "\u2018", "`");
defineSymbol(math, main, textord, "$", "\\$");
defineSymbol(text2, main, textord, "$", "\\$");
defineSymbol(text2, main, textord, "$", "\\textdollar");
defineSymbol(math, main, textord, "%", "\\%");
defineSymbol(text2, main, textord, "%", "\\%");
defineSymbol(math, main, textord, "_", "\\_");
defineSymbol(text2, main, textord, "_", "\\_");
defineSymbol(text2, main, textord, "_", "\\textunderscore");
defineSymbol(math, main, textord, "\u2220", "\\angle", true);
defineSymbol(math, main, textord, "\u221E", "\\infty", true);
defineSymbol(math, main, textord, "\u2032", "\\prime");
defineSymbol(math, main, textord, "\u25B3", "\\triangle");
defineSymbol(math, main, textord, "\u0393", "\\Gamma", true);
defineSymbol(math, main, textord, "\u0394", "\\Delta", true);
defineSymbol(math, main, textord, "\u0398", "\\Theta", true);
defineSymbol(math, main, textord, "\u039B", "\\Lambda", true);
defineSymbol(math, main, textord, "\u039E", "\\Xi", true);
defineSymbol(math, main, textord, "\u03A0", "\\Pi", true);
defineSymbol(math, main, textord, "\u03A3", "\\Sigma", true);
defineSymbol(math, main, textord, "\u03A5", "\\Upsilon", true);
defineSymbol(math, main, textord, "\u03A6", "\\Phi", true);
defineSymbol(math, main, textord, "\u03A8", "\\Psi", true);
defineSymbol(math, main, textord, "\u03A9", "\\Omega", true);
defineSymbol(math, main, textord, "A", "\u0391");
defineSymbol(math, main, textord, "B", "\u0392");
defineSymbol(math, main, textord, "E", "\u0395");
defineSymbol(math, main, textord, "Z", "\u0396");
defineSymbol(math, main, textord, "H", "\u0397");
defineSymbol(math, main, textord, "I", "\u0399");
defineSymbol(math, main, textord, "K", "\u039A");
defineSymbol(math, main, textord, "M", "\u039C");
defineSymbol(math, main, textord, "N", "\u039D");
defineSymbol(math, main, textord, "O", "\u039F");
defineSymbol(math, main, textord, "P", "\u03A1");
defineSymbol(math, main, textord, "T", "\u03A4");
defineSymbol(math, main, textord, "X", "\u03A7");
defineSymbol(math, main, textord, "\xAC", "\\neg", true);
defineSymbol(math, main, textord, "\xAC", "\\lnot");
defineSymbol(math, main, textord, "\u22A4", "\\top");
defineSymbol(math, main, textord, "\u22A5", "\\bot");
defineSymbol(math, main, textord, "\u2205", "\\emptyset");
defineSymbol(math, ams, textord, "\u2205", "\\varnothing");
defineSymbol(math, main, mathord, "\u03B1", "\\alpha", true);
defineSymbol(math, main, mathord, "\u03B2", "\\beta", true);
defineSymbol(math, main, mathord, "\u03B3", "\\gamma", true);
defineSymbol(math, main, mathord, "\u03B4", "\\delta", true);
defineSymbol(math, main, mathord, "\u03F5", "\\epsilon", true);
defineSymbol(math, main, mathord, "\u03B6", "\\zeta", true);
defineSymbol(math, main, mathord, "\u03B7", "\\eta", true);
defineSymbol(math, main, mathord, "\u03B8", "\\theta", true);
defineSymbol(math, main, mathord, "\u03B9", "\\iota", true);
defineSymbol(math, main, mathord, "\u03BA", "\\kappa", true);
defineSymbol(math, main, mathord, "\u03BB", "\\lambda", true);
defineSymbol(math, main, mathord, "\u03BC", "\\mu", true);
defineSymbol(math, main, mathord, "\u03BD", "\\nu", true);
defineSymbol(math, main, mathord, "\u03BE", "\\xi", true);
defineSymbol(math, main, mathord, "\u03BF", "\\omicron", true);
defineSymbol(math, main, mathord, "\u03C0", "\\pi", true);
defineSymbol(math, main, mathord, "\u03C1", "\\rho", true);
defineSymbol(math, main, mathord, "\u03C3", "\\sigma", true);
defineSymbol(math, main, mathord, "\u03C4", "\\tau", true);
defineSymbol(math, main, mathord, "\u03C5", "\\upsilon", true);
defineSymbol(math, main, mathord, "\u03D5", "\\phi", true);
defineSymbol(math, main, mathord, "\u03C7", "\\chi", true);
defineSymbol(math, main, mathord, "\u03C8", "\\psi", true);
defineSymbol(math, main, mathord, "\u03C9", "\\omega", true);
defineSymbol(math, main, mathord, "\u03B5", "\\varepsilon", true);
defineSymbol(math, main, mathord, "\u03D1", "\\vartheta", true);
defineSymbol(math, main, mathord, "\u03D6", "\\varpi", true);
defineSymbol(math, main, mathord, "\u03F1", "\\varrho", true);
defineSymbol(math, main, mathord, "\u03C2", "\\varsigma", true);
defineSymbol(math, main, mathord, "\u03C6", "\\varphi", true);
defineSymbol(math, main, bin, "\u2217", "*", true);
defineSymbol(math, main, bin, "+", "+");
defineSymbol(math, main, bin, "\u2212", "-", true);
defineSymbol(math, main, bin, "\u22C5", "\\cdot", true);
defineSymbol(math, main, bin, "\u2218", "\\circ", true);
defineSymbol(math, main, bin, "\xF7", "\\div", true);
defineSymbol(math, main, bin, "\xB1", "\\pm", true);
defineSymbol(math, main, bin, "\xD7", "\\times", true);
defineSymbol(math, main, bin, "\u2229", "\\cap", true);
defineSymbol(math, main, bin, "\u222A", "\\cup", true);
defineSymbol(math, main, bin, "\u2216", "\\setminus", true);
defineSymbol(math, main, bin, "\u2227", "\\land");
defineSymbol(math, main, bin, "\u2228", "\\lor");
defineSymbol(math, main, bin, "\u2227", "\\wedge", true);
defineSymbol(math, main, bin, "\u2228", "\\vee", true);
defineSymbol(math, main, textord, "\u221A", "\\surd");
defineSymbol(math, main, open, "\u27E8", "\\langle", true);
defineSymbol(math, main, open, "\u2223", "\\lvert");
defineSymbol(math, main, open, "\u2225", "\\lVert");
defineSymbol(math, main, close, "?", "?");
defineSymbol(math, main, close, "!", "!");
defineSymbol(math, main, close, "\u27E9", "\\rangle", true);
defineSymbol(math, main, close, "\u2223", "\\rvert");
defineSymbol(math, main, close, "\u2225", "\\rVert");
defineSymbol(math, main, rel, "=", "=");
defineSymbol(math, main, rel, ":", ":");
defineSymbol(math, main, rel, "\u2248", "\\approx", true);
defineSymbol(math, main, rel, "\u2245", "\\cong", true);
defineSymbol(math, main, rel, "\u2265", "\\ge");
defineSymbol(math, main, rel, "\u2265", "\\geq", true);
defineSymbol(math, main, rel, "\u2190", "\\gets");
defineSymbol(math, main, rel, ">", "\\gt", true);
defineSymbol(math, main, rel, "\u2208", "\\in", true);
defineSymbol(math, main, rel, "\uE020", "\\@not");
defineSymbol(math, main, rel, "\u2282", "\\subset", true);
defineSymbol(math, main, rel, "\u2283", "\\supset", true);
defineSymbol(math, main, rel, "\u2286", "\\subseteq", true);
defineSymbol(math, main, rel, "\u2287", "\\supseteq", true);
defineSymbol(math, ams, rel, "\u2288", "\\nsubseteq", true);
defineSymbol(math, ams, rel, "\u2289", "\\nsupseteq", true);
defineSymbol(math, main, rel, "\u22A8", "\\models");
defineSymbol(math, main, rel, "\u2190", "\\leftarrow", true);
defineSymbol(math, main, rel, "\u2264", "\\le");
defineSymbol(math, main, rel, "\u2264", "\\leq", true);
defineSymbol(math, main, rel, "<", "\\lt", true);
defineSymbol(math, main, rel, "\u2192", "\\rightarrow", true);
defineSymbol(math, main, rel, "\u2192", "\\to");
defineSymbol(math, ams, rel, "\u2271", "\\ngeq", true);
defineSymbol(math, ams, rel, "\u2270", "\\nleq", true);
defineSymbol(math, main, spacing, "\xA0", "\\ ");
defineSymbol(math, main, spacing, "\xA0", "\\space");
defineSymbol(math, main, spacing, "\xA0", "\\nobreakspace");
defineSymbol(text2, main, spacing, "\xA0", "\\ ");
defineSymbol(text2, main, spacing, "\xA0", " ");
defineSymbol(text2, main, spacing, "\xA0", "\\space");
defineSymbol(text2, main, spacing, "\xA0", "\\nobreakspace");
defineSymbol(math, main, spacing, null, "\\nobreak");
defineSymbol(math, main, spacing, null, "\\allowbreak");
defineSymbol(math, main, punct, ",", ",");
defineSymbol(math, main, punct, ";", ";");
defineSymbol(math, ams, bin, "\u22BC", "\\barwedge", true);
defineSymbol(math, ams, bin, "\u22BB", "\\veebar", true);
defineSymbol(math, main, bin, "\u2299", "\\odot", true);
defineSymbol(math, main, bin, "\u2295", "\\oplus", true);
defineSymbol(math, main, bin, "\u2297", "\\otimes", true);
defineSymbol(math, main, textord, "\u2202", "\\partial", true);
defineSymbol(math, main, bin, "\u2298", "\\oslash", true);
defineSymbol(math, ams, bin, "\u229A", "\\circledcirc", true);
defineSymbol(math, ams, bin, "\u22A1", "\\boxdot", true);
defineSymbol(math, main, bin, "\u25B3", "\\bigtriangleup");
defineSymbol(math, main, bin, "\u25BD", "\\bigtriangledown");
defineSymbol(math, main, bin, "\u2020", "\\dagger");
defineSymbol(math, main, bin, "\u22C4", "\\diamond");
defineSymbol(math, main, bin, "\u22C6", "\\star");
defineSymbol(math, main, bin, "\u25C3", "\\triangleleft");
defineSymbol(math, main, bin, "\u25B9", "\\triangleright");
defineSymbol(math, main, open, "{", "\\{");
defineSymbol(text2, main, textord, "{", "\\{");
defineSymbol(text2, main, textord, "{", "\\textbraceleft");
defineSymbol(math, main, close, "}", "\\}");
defineSymbol(text2, main, textord, "}", "\\}");
defineSymbol(text2, main, textord, "}", "\\textbraceright");
defineSymbol(math, main, open, "{", "\\lbrace");
defineSymbol(math, main, close, "}", "\\rbrace");
defineSymbol(math, main, open, "[", "\\lbrack", true);
defineSymbol(text2, main, textord, "[", "\\lbrack", true);
defineSymbol(math, main, close, "]", "\\rbrack", true);
defineSymbol(text2, main, textord, "]", "\\rbrack", true);
defineSymbol(math, main, open, "(", "\\lparen", true);
defineSymbol(math, main, close, ")", "\\rparen", true);
defineSymbol(text2, main, textord, "<", "\\textless", true);
defineSymbol(text2, main, textord, ">", "\\textgreater", true);
defineSymbol(math, main, open, "\u230A", "\\lfloor", true);
defineSymbol(math, main, close, "\u230B", "\\rfloor", true);
defineSymbol(math, main, open, "\u2308", "\\lceil", true);
defineSymbol(math, main, close, "\u2309", "\\rceil", true);
defineSymbol(math, main, textord, "\\", "\\backslash");
defineSymbol(math, main, textord, "\u2223", "|");
defineSymbol(math, main, textord, "\u2223", "\\vert");
defineSymbol(text2, main, textord, "|", "\\textbar", true);
defineSymbol(math, main, textord, "\u2225", "\\|");
defineSymbol(math, main, textord, "\u2225", "\\Vert");
defineSymbol(text2, main, textord, "\u2225", "\\textbardbl");
defineSymbol(text2, main, textord, "~", "\\textasciitilde");
defineSymbol(text2, main, textord, "\\", "\\textbackslash");
defineSymbol(text2, main, textord, "^", "\\textasciicircum");
defineSymbol(math, main, rel, "\u2191", "\\uparrow", true);
defineSymbol(math, main, rel, "\u21D1", "\\Uparrow", true);
defineSymbol(math, main, rel, "\u2193", "\\downarrow", true);
defineSymbol(math, main, rel, "\u21D3", "\\Downarrow", true);
defineSymbol(math, main, rel, "\u2195", "\\updownarrow", true);
defineSymbol(math, main, rel, "\u21D5", "\\Updownarrow", true);
defineSymbol(math, main, op, "\u2210", "\\coprod");
defineSymbol(math, main, op, "\u22C1", "\\bigvee");
defineSymbol(math, main, op, "\u22C0", "\\bigwedge");
defineSymbol(math, main, op, "\u2A04", "\\biguplus");
defineSymbol(math, main, op, "\u22C2", "\\bigcap");
defineSymbol(math, main, op, "\u22C3", "\\bigcup");
defineSymbol(math, main, op, "\u222B", "\\int");
defineSymbol(math, main, op, "\u222B", "\\intop");
defineSymbol(math, main, op, "\u222C", "\\iint");
defineSymbol(math, main, op, "\u222D", "\\iiint");
defineSymbol(math, main, op, "\u220F", "\\prod");
defineSymbol(math, main, op, "\u2211", "\\sum");
defineSymbol(math, main, op, "\u2A02", "\\bigotimes");
defineSymbol(math, main, op, "\u2A01", "\\bigoplus");
defineSymbol(math, main, op, "\u2A00", "\\bigodot");
defineSymbol(math, main, op, "\u222E", "\\oint");
defineSymbol(math, main, op, "\u222F", "\\oiint");
defineSymbol(math, main, op, "\u2230", "\\oiiint");
defineSymbol(math, main, op, "\u2A06", "\\bigsqcup");
defineSymbol(math, main, op, "\u222B", "\\smallint");
defineSymbol(text2, main, inner, "\u2026", "\\textellipsis");
defineSymbol(math, main, inner, "\u2026", "\\mathellipsis");
defineSymbol(text2, main, inner, "\u2026", "\\ldots", true);
defineSymbol(math, main, inner, "\u2026", "\\ldots", true);
defineSymbol(math, main, inner, "\u22EF", "\\@cdots", true);
defineSymbol(math, main, inner, "\u22F1", "\\ddots", true);
defineSymbol(math, main, textord, "\u22EE", "\\varvdots");
defineSymbol(text2, main, textord, "\u22EE", "\\varvdots");
defineSymbol(math, main, accent, "\u02CA", "\\acute");
defineSymbol(math, main, accent, "\u02CB", "\\grave");
defineSymbol(math, main, accent, "\xA8", "\\ddot");
defineSymbol(math, main, accent, "~", "\\tilde");
defineSymbol(math, main, accent, "\u02C9", "\\bar");
defineSymbol(math, main, accent, "\u02D8", "\\breve");
defineSymbol(math, main, accent, "\u02C7", "\\check");
defineSymbol(math, main, accent, "^", "\\hat");
defineSymbol(math, main, accent, "\u20D7", "\\vec");
defineSymbol(math, main, accent, "\u02D9", "\\dot");
defineSymbol(math, main, accent, "\u02DA", "\\mathring");
defineSymbol(math, main, mathord, "\uE131", "\\@imath");
defineSymbol(math, main, mathord, "\uE237", "\\@jmath");
defineSymbol(math, main, textord, "\u0131", "\u0131");
defineSymbol(math, main, textord, "\u0237", "\u0237");
defineSymbol(text2, main, textord, "\u0131", "\\i", true);
defineSymbol(text2, main, textord, "\u0237", "\\j", true);
defineSymbol(text2, main, textord, "\xDF", "\\ss", true);
defineSymbol(text2, main, textord, "\xE6", "\\ae", true);
defineSymbol(text2, main, textord, "\u0153", "\\oe", true);
defineSymbol(text2, main, textord, "\xF8", "\\o", true);
defineSymbol(text2, main, textord, "\xC6", "\\AE", true);
defineSymbol(text2, main, textord, "\u0152", "\\OE", true);
defineSymbol(text2, main, textord, "\xD8", "\\O", true);
defineSymbol(text2, main, accent, "\u02CA", "\\'");
defineSymbol(text2, main, accent, "\u02CB", "\\`");
defineSymbol(text2, main, accent, "\u02C6", "\\^");
defineSymbol(text2, main, accent, "\u02DC", "\\~");
defineSymbol(text2, main, accent, "\u02C9", "\\=");
defineSymbol(text2, main, accent, "\u02D8", "\\u");
defineSymbol(text2, main, accent, "\u02D9", "\\.");
defineSymbol(text2, main, accent, "\xB8", "\\c");
defineSymbol(text2, main, accent, "\u02DA", "\\r");
defineSymbol(text2, main, accent, "\u02C7", "\\v");
defineSymbol(text2, main, accent, "\xA8", '\\"');
defineSymbol(text2, main, accent, "\u02DD", "\\H");
defineSymbol(text2, main, accent, "\u25EF", "\\textcircled");
var ligatures = {
  "--": true,
  "---": true,
  "``": true,
  "''": true
};
defineSymbol(text2, main, textord, "\u2013", "--", true);
defineSymbol(text2, main, textord, "\u2013", "\\textendash");
defineSymbol(text2, main, textord, "\u2014", "---", true);
defineSymbol(text2, main, textord, "\u2014", "\\textemdash");
defineSymbol(text2, main, textord, "\u2018", "`", true);
defineSymbol(text2, main, textord, "\u2018", "\\textquoteleft");
defineSymbol(text2, main, textord, "\u2019", "'", true);
defineSymbol(text2, main, textord, "\u2019", "\\textquoteright");
defineSymbol(text2, main, textord, "\u201C", "``", true);
defineSymbol(text2, main, textord, "\u201C", "\\textquotedblleft");
defineSymbol(text2, main, textord, "\u201D", "''", true);
defineSymbol(text2, main, textord, "\u201D", "\\textquotedblright");
defineSymbol(math, main, textord, "\xB0", "\\degree", true);
defineSymbol(text2, main, textord, "\xB0", "\\degree");
defineSymbol(text2, main, textord, "\xB0", "\\textdegree", true);
defineSymbol(math, main, textord, "\xA3", "\\pounds");
defineSymbol(math, main, textord, "\xA3", "\\mathsterling", true);
defineSymbol(text2, main, textord, "\xA3", "\\pounds");
defineSymbol(text2, main, textord, "\xA3", "\\textsterling", true);
defineSymbol(math, ams, textord, "\u2720", "\\maltese");
defineSymbol(text2, ams, textord, "\u2720", "\\maltese");
var mathTextSymbols = '0123456789/@."';
for (i7 = 0; i7 < mathTextSymbols.length; i7++) {
  ch = mathTextSymbols.charAt(i7);
  defineSymbol(math, main, textord, ch, ch);
}
var ch;
var i7;
var textSymbols = '0123456789!@*()-=+";:?/.,';
for (_i = 0; _i < textSymbols.length; _i++) {
  _ch = textSymbols.charAt(_i);
  defineSymbol(text2, main, textord, _ch, _ch);
}
var _ch;
var _i;
var letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
for (_i2 = 0; _i2 < letters.length; _i2++) {
  _ch2 = letters.charAt(_i2);
  defineSymbol(math, main, mathord, _ch2, _ch2);
  defineSymbol(text2, main, textord, _ch2, _ch2);
}
var _ch2;
var _i2;
defineSymbol(math, ams, textord, "C", "\u2102");
defineSymbol(text2, ams, textord, "C", "\u2102");
defineSymbol(math, ams, textord, "H", "\u210D");
defineSymbol(text2, ams, textord, "H", "\u210D");
defineSymbol(math, ams, textord, "N", "\u2115");
defineSymbol(text2, ams, textord, "N", "\u2115");
defineSymbol(math, ams, textord, "P", "\u2119");
defineSymbol(text2, ams, textord, "P", "\u2119");
defineSymbol(math, ams, textord, "Q", "\u211A");
defineSymbol(text2, ams, textord, "Q", "\u211A");
defineSymbol(math, ams, textord, "R", "\u211D");
defineSymbol(text2, ams, textord, "R", "\u211D");
defineSymbol(math, ams, textord, "Z", "\u2124");
defineSymbol(text2, ams, textord, "Z", "\u2124");
defineSymbol(math, main, mathord, "h", "\u210E");
defineSymbol(text2, main, mathord, "h", "\u210E");
var wideChar = "";
for (_i3 = 0; _i3 < letters.length; _i3++) {
  _ch3 = letters.charAt(_i3);
  wideChar = String.fromCharCode(55349, 56320 + _i3);
  defineSymbol(math, main, mathord, _ch3, wideChar);
  defineSymbol(text2, main, textord, _ch3, wideChar);
  wideChar = String.fromCharCode(55349, 56372 + _i3);
  defineSymbol(math, main, mathord, _ch3, wideChar);
  defineSymbol(text2, main, textord, _ch3, wideChar);
  wideChar = String.fromCharCode(55349, 56424 + _i3);
  defineSymbol(math, main, mathord, _ch3, wideChar);
  defineSymbol(text2, main, textord, _ch3, wideChar);
  wideChar = String.fromCharCode(55349, 56580 + _i3);
  defineSymbol(math, main, mathord, _ch3, wideChar);
  defineSymbol(text2, main, textord, _ch3, wideChar);
  wideChar = String.fromCharCode(55349, 56684 + _i3);
  defineSymbol(math, main, mathord, _ch3, wideChar);
  defineSymbol(text2, main, textord, _ch3, wideChar);
  wideChar = String.fromCharCode(55349, 56736 + _i3);
  defineSymbol(math, main, mathord, _ch3, wideChar);
  defineSymbol(text2, main, textord, _ch3, wideChar);
  wideChar = String.fromCharCode(55349, 56788 + _i3);
  defineSymbol(math, main, mathord, _ch3, wideChar);
  defineSymbol(text2, main, textord, _ch3, wideChar);
  wideChar = String.fromCharCode(55349, 56840 + _i3);
  defineSymbol(math, main, mathord, _ch3, wideChar);
  defineSymbol(text2, main, textord, _ch3, wideChar);
  wideChar = String.fromCharCode(55349, 56944 + _i3);
  defineSymbol(math, main, mathord, _ch3, wideChar);
  defineSymbol(text2, main, textord, _ch3, wideChar);
  if (_i3 < 26) {
    wideChar = String.fromCharCode(55349, 56632 + _i3);
    defineSymbol(math, main, mathord, _ch3, wideChar);
    defineSymbol(text2, main, textord, _ch3, wideChar);
    wideChar = String.fromCharCode(55349, 56476 + _i3);
    defineSymbol(math, main, mathord, _ch3, wideChar);
    defineSymbol(text2, main, textord, _ch3, wideChar);
  }
}
var _ch3;
var _i3;
wideChar = String.fromCharCode(55349, 56668);
defineSymbol(math, main, mathord, "k", wideChar);
defineSymbol(text2, main, textord, "k", wideChar);
for (_i4 = 0; _i4 < 10; _i4++) {
  _ch4 = _i4.toString();
  wideChar = String.fromCharCode(55349, 57294 + _i4);
  defineSymbol(math, main, mathord, _ch4, wideChar);
  defineSymbol(text2, main, textord, _ch4, wideChar);
  wideChar = String.fromCharCode(55349, 57314 + _i4);
  defineSymbol(math, main, mathord, _ch4, wideChar);
  defineSymbol(text2, main, textord, _ch4, wideChar);
  wideChar = String.fromCharCode(55349, 57324 + _i4);
  defineSymbol(math, main, mathord, _ch4, wideChar);
  defineSymbol(text2, main, textord, _ch4, wideChar);
  wideChar = String.fromCharCode(55349, 57334 + _i4);
  defineSymbol(math, main, mathord, _ch4, wideChar);
  defineSymbol(text2, main, textord, _ch4, wideChar);
}
var _ch4;
var _i4;
var extraLatin = "\xD0\xDE\xFE";
for (_i5 = 0; _i5 < extraLatin.length; _i5++) {
  _ch5 = extraLatin.charAt(_i5);
  defineSymbol(math, main, mathord, _ch5, _ch5);
  defineSymbol(text2, main, textord, _ch5, _ch5);
}
var _ch5;
var _i5;
var wideLatinLetterData = [
  ["mathbf", "textbf", "Main-Bold"],
  // A-Z bold upright
  ["mathbf", "textbf", "Main-Bold"],
  // a-z bold upright
  ["mathnormal", "textit", "Math-Italic"],
  // A-Z italic
  ["mathnormal", "textit", "Math-Italic"],
  // a-z italic
  ["boldsymbol", "boldsymbol", "Main-BoldItalic"],
  // A-Z bold italic
  ["boldsymbol", "boldsymbol", "Main-BoldItalic"],
  // a-z bold italic
  // Map fancy A-Z letters to script, not calligraphic.
  // This aligns with unicode-math and math fonts (except Cambria Math).
  ["mathscr", "textscr", "Script-Regular"],
  // A-Z script
  ["", "", ""],
  // a-z script.  No font
  ["", "", ""],
  // A-Z bold script. No font
  ["", "", ""],
  // a-z bold script. No font
  ["mathfrak", "textfrak", "Fraktur-Regular"],
  // A-Z Fraktur
  ["mathfrak", "textfrak", "Fraktur-Regular"],
  // a-z Fraktur
  ["mathbb", "textbb", "AMS-Regular"],
  // A-Z double-struck
  ["mathbb", "textbb", "AMS-Regular"],
  // k double-struck
  // Note that we are using a bold font, but font metrics for regular Fraktur.
  ["mathboldfrak", "textboldfrak", "Fraktur-Regular"],
  // A-Z bold Fraktur
  ["mathboldfrak", "textboldfrak", "Fraktur-Regular"],
  // a-z bold Fraktur
  ["mathsf", "textsf", "SansSerif-Regular"],
  // A-Z sans-serif
  ["mathsf", "textsf", "SansSerif-Regular"],
  // a-z sans-serif
  ["mathboldsf", "textboldsf", "SansSerif-Bold"],
  // A-Z bold sans-serif
  ["mathboldsf", "textboldsf", "SansSerif-Bold"],
  // a-z bold sans-serif
  ["mathitsf", "textitsf", "SansSerif-Italic"],
  // A-Z italic sans-serif
  ["mathitsf", "textitsf", "SansSerif-Italic"],
  // a-z italic sans-serif
  ["", "", ""],
  // A-Z bold italic sans. No font
  ["", "", ""],
  // a-z bold italic sans. No font
  ["mathtt", "texttt", "Typewriter-Regular"],
  // A-Z monospace
  ["mathtt", "texttt", "Typewriter-Regular"]
  // a-z monospace
];
var wideNumeralData = [
  ["mathbf", "textbf", "Main-Bold"],
  // 0-9 bold
  ["", "", ""],
  // 0-9 double-struck. No KaTeX font.
  ["mathsf", "textsf", "SansSerif-Regular"],
  // 0-9 sans-serif
  ["mathboldsf", "textboldsf", "SansSerif-Bold"],
  // 0-9 bold sans-serif
  ["mathtt", "texttt", "Typewriter-Regular"]
  // 0-9 monospace
];
var wideCharacterFont = function wideCharacterFont2(wideChar2, mode) {
  var H2 = wideChar2.charCodeAt(0);
  var L3 = wideChar2.charCodeAt(1);
  var codePoint = (H2 - 55296) * 1024 + (L3 - 56320) + 65536;
  var j3 = mode === "math" ? 0 : 1;
  if (119808 <= codePoint && codePoint < 120484) {
    var i7 = Math.floor((codePoint - 119808) / 26);
    return [wideLatinLetterData[i7][2], wideLatinLetterData[i7][j3]];
  } else if (120782 <= codePoint && codePoint <= 120831) {
    var _i = Math.floor((codePoint - 120782) / 10);
    return [wideNumeralData[_i][2], wideNumeralData[_i][j3]];
  } else if (codePoint === 120485 || codePoint === 120486) {
    return [wideLatinLetterData[0][2], wideLatinLetterData[0][j3]];
  } else if (120486 < codePoint && codePoint < 120782) {
    return ["", ""];
  } else {
    throw new ParseError("Unsupported character: " + wideChar2);
  }
};
var lookupSymbol = function lookupSymbol2(value, fontName, mode) {
  if (symbols[mode][value] && symbols[mode][value].replace) {
    value = symbols[mode][value].replace;
  }
  return {
    value,
    metrics: getCharacterMetrics(value, fontName, mode)
  };
};
var makeSymbol = function makeSymbol2(value, fontName, mode, options, classes) {
  var lookup = lookupSymbol(value, fontName, mode);
  var metrics = lookup.metrics;
  value = lookup.value;
  var symbolNode;
  if (metrics) {
    var italic = metrics.italic;
    if (mode === "text" || options && options.font === "mathit") {
      italic = 0;
    }
    symbolNode = new SymbolNode(value, metrics.height, metrics.depth, italic, metrics.skew, metrics.width, classes);
  } else {
    typeof console !== "undefined" && console.warn("No character metrics " + ("for '" + value + "' in style '" + fontName + "' and mode '" + mode + "'"));
    symbolNode = new SymbolNode(value, 0, 0, 0, 0, 0, classes);
  }
  if (options) {
    symbolNode.maxFontSize = options.sizeMultiplier;
    if (options.style.isTight()) {
      symbolNode.classes.push("mtight");
    }
    var color = options.getColor();
    if (color) {
      symbolNode.style.color = color;
    }
  }
  return symbolNode;
};
var mathsym = function mathsym2(value, mode, options, classes) {
  if (classes === void 0) {
    classes = [];
  }
  if (options.font === "boldsymbol" && lookupSymbol(value, "Main-Bold", mode).metrics) {
    return makeSymbol(value, "Main-Bold", mode, options, classes.concat(["mathbf"]));
  } else if (value === "\\" || symbols[mode][value].font === "main") {
    return makeSymbol(value, "Main-Regular", mode, options, classes);
  } else {
    return makeSymbol(value, "AMS-Regular", mode, options, classes.concat(["amsrm"]));
  }
};
var boldsymbol = function boldsymbol2(value, mode, options, classes, type) {
  if (type !== "textord" && lookupSymbol(value, "Math-BoldItalic", mode).metrics) {
    return {
      fontName: "Math-BoldItalic",
      fontClass: "boldsymbol"
    };
  } else {
    return {
      fontName: "Main-Bold",
      fontClass: "mathbf"
    };
  }
};
var makeOrd = function makeOrd2(group, options, type) {
  var mode = group.mode;
  var text3 = group.text;
  var classes = ["mord"];
  var isFont = mode === "math" || mode === "text" && options.font;
  var fontOrFamily = isFont ? options.font : options.fontFamily;
  var wideFontName = "";
  var wideFontClass = "";
  if (text3.charCodeAt(0) === 55349) {
    [wideFontName, wideFontClass] = wideCharacterFont(text3, mode);
  }
  if (wideFontName.length > 0) {
    return makeSymbol(text3, wideFontName, mode, options, classes.concat(wideFontClass));
  } else if (fontOrFamily) {
    var fontName;
    var fontClasses;
    if (fontOrFamily === "boldsymbol") {
      var fontData = boldsymbol(text3, mode, options, classes, type);
      fontName = fontData.fontName;
      fontClasses = [fontData.fontClass];
    } else if (isFont) {
      fontName = fontMap[fontOrFamily].fontName;
      fontClasses = [fontOrFamily];
    } else {
      fontName = retrieveTextFontName(fontOrFamily, options.fontWeight, options.fontShape);
      fontClasses = [fontOrFamily, options.fontWeight, options.fontShape];
    }
    if (lookupSymbol(text3, fontName, mode).metrics) {
      return makeSymbol(text3, fontName, mode, options, classes.concat(fontClasses));
    } else if (ligatures.hasOwnProperty(text3) && fontName.slice(0, 10) === "Typewriter") {
      var parts = [];
      for (var i7 = 0; i7 < text3.length; i7++) {
        parts.push(makeSymbol(text3[i7], fontName, mode, options, classes.concat(fontClasses)));
      }
      return makeFragment(parts);
    }
  }
  if (type === "mathord") {
    return makeSymbol(text3, "Math-Italic", mode, options, classes.concat(["mathnormal"]));
  } else if (type === "textord") {
    var font = symbols[mode][text3] && symbols[mode][text3].font;
    if (font === "ams") {
      var _fontName = retrieveTextFontName("amsrm", options.fontWeight, options.fontShape);
      return makeSymbol(text3, _fontName, mode, options, classes.concat("amsrm", options.fontWeight, options.fontShape));
    } else if (font === "main" || !font) {
      var _fontName2 = retrieveTextFontName("textrm", options.fontWeight, options.fontShape);
      return makeSymbol(text3, _fontName2, mode, options, classes.concat(options.fontWeight, options.fontShape));
    } else {
      var _fontName3 = retrieveTextFontName(font, options.fontWeight, options.fontShape);
      return makeSymbol(text3, _fontName3, mode, options, classes.concat(_fontName3, options.fontWeight, options.fontShape));
    }
  } else {
    throw new Error("unexpected type: " + type + " in makeOrd");
  }
};
var canCombine = (prev, next) => {
  if (createClass(prev.classes) !== createClass(next.classes) || prev.skew !== next.skew || prev.maxFontSize !== next.maxFontSize) {
    return false;
  }
  if (prev.classes.length === 1) {
    var cls = prev.classes[0];
    if (cls === "mbin" || cls === "mord") {
      return false;
    }
  }
  for (var style in prev.style) {
    if (prev.style.hasOwnProperty(style) && prev.style[style] !== next.style[style]) {
      return false;
    }
  }
  for (var _style in next.style) {
    if (next.style.hasOwnProperty(_style) && prev.style[_style] !== next.style[_style]) {
      return false;
    }
  }
  return true;
};
var tryCombineChars = (chars) => {
  for (var i7 = 0; i7 < chars.length - 1; i7++) {
    var prev = chars[i7];
    var next = chars[i7 + 1];
    if (prev instanceof SymbolNode && next instanceof SymbolNode && canCombine(prev, next)) {
      prev.text += next.text;
      prev.height = Math.max(prev.height, next.height);
      prev.depth = Math.max(prev.depth, next.depth);
      prev.italic = next.italic;
      chars.splice(i7 + 1, 1);
      i7--;
    }
  }
  return chars;
};
var sizeElementFromChildren = function sizeElementFromChildren2(elem) {
  var height = 0;
  var depth = 0;
  var maxFontSize = 0;
  for (var i7 = 0; i7 < elem.children.length; i7++) {
    var child = elem.children[i7];
    if (child.height > height) {
      height = child.height;
    }
    if (child.depth > depth) {
      depth = child.depth;
    }
    if (child.maxFontSize > maxFontSize) {
      maxFontSize = child.maxFontSize;
    }
  }
  elem.height = height;
  elem.depth = depth;
  elem.maxFontSize = maxFontSize;
};
var makeSpan$2 = function makeSpan(classes, children, options, style) {
  var span = new Span(classes, children, options, style);
  sizeElementFromChildren(span);
  return span;
};
var makeSvgSpan = (classes, children, options, style) => new Span(classes, children, options, style);
var makeLineSpan = function makeLineSpan2(className, options, thickness) {
  var line = makeSpan$2([className], [], options);
  line.height = Math.max(thickness || options.fontMetrics().defaultRuleThickness, options.minRuleThickness);
  line.style.borderBottomWidth = makeEm(line.height);
  line.maxFontSize = 1;
  return line;
};
var makeAnchor = function makeAnchor2(href, classes, children, options) {
  var anchor = new Anchor(href, classes, children, options);
  sizeElementFromChildren(anchor);
  return anchor;
};
var makeFragment = function makeFragment2(children) {
  var fragment = new DocumentFragment2(children);
  sizeElementFromChildren(fragment);
  return fragment;
};
var wrapFragment = function wrapFragment2(group, options) {
  if (group instanceof DocumentFragment2) {
    return makeSpan$2([], [group], options);
  }
  return group;
};
var getVListChildrenAndDepth = function getVListChildrenAndDepth2(params) {
  if (params.positionType === "individualShift") {
    var oldChildren = params.children;
    var children = [oldChildren[0]];
    var _depth = -oldChildren[0].shift - oldChildren[0].elem.depth;
    var currPos = _depth;
    for (var i7 = 1; i7 < oldChildren.length; i7++) {
      var diff = -oldChildren[i7].shift - currPos - oldChildren[i7].elem.depth;
      var size = diff - (oldChildren[i7 - 1].elem.height + oldChildren[i7 - 1].elem.depth);
      currPos = currPos + diff;
      children.push({
        type: "kern",
        size
      });
      children.push(oldChildren[i7]);
    }
    return {
      children,
      depth: _depth
    };
  }
  var depth;
  if (params.positionType === "top") {
    var bottom = params.positionData;
    for (var _i = 0; _i < params.children.length; _i++) {
      var child = params.children[_i];
      bottom -= child.type === "kern" ? child.size : child.elem.height + child.elem.depth;
    }
    depth = bottom;
  } else if (params.positionType === "bottom") {
    depth = -params.positionData;
  } else {
    var firstChild = params.children[0];
    if (firstChild.type !== "elem") {
      throw new Error('First child must have type "elem".');
    }
    if (params.positionType === "shift") {
      depth = -firstChild.elem.depth - params.positionData;
    } else if (params.positionType === "firstBaseline") {
      depth = -firstChild.elem.depth;
    } else {
      throw new Error("Invalid positionType " + params.positionType + ".");
    }
  }
  return {
    children: params.children,
    depth
  };
};
var makeVList = function makeVList2(params, options) {
  var {
    children,
    depth
  } = getVListChildrenAndDepth(params);
  var pstrutSize = 0;
  for (var i7 = 0; i7 < children.length; i7++) {
    var child = children[i7];
    if (child.type === "elem") {
      var elem = child.elem;
      pstrutSize = Math.max(pstrutSize, elem.maxFontSize, elem.height);
    }
  }
  pstrutSize += 2;
  var pstrut = makeSpan$2(["pstrut"], []);
  pstrut.style.height = makeEm(pstrutSize);
  var realChildren = [];
  var minPos = depth;
  var maxPos = depth;
  var currPos = depth;
  for (var _i2 = 0; _i2 < children.length; _i2++) {
    var _child = children[_i2];
    if (_child.type === "kern") {
      currPos += _child.size;
    } else {
      var _elem = _child.elem;
      var classes = _child.wrapperClasses || [];
      var style = _child.wrapperStyle || {};
      var childWrap = makeSpan$2(classes, [pstrut, _elem], void 0, style);
      childWrap.style.top = makeEm(-pstrutSize - currPos - _elem.depth);
      if (_child.marginLeft) {
        childWrap.style.marginLeft = _child.marginLeft;
      }
      if (_child.marginRight) {
        childWrap.style.marginRight = _child.marginRight;
      }
      realChildren.push(childWrap);
      currPos += _elem.height + _elem.depth;
    }
    minPos = Math.min(minPos, currPos);
    maxPos = Math.max(maxPos, currPos);
  }
  var vlist = makeSpan$2(["vlist"], realChildren);
  vlist.style.height = makeEm(maxPos);
  var rows;
  if (minPos < 0) {
    var emptySpan = makeSpan$2([], []);
    var depthStrut = makeSpan$2(["vlist"], [emptySpan]);
    depthStrut.style.height = makeEm(-minPos);
    var topStrut = makeSpan$2(["vlist-s"], [new SymbolNode("\u200B")]);
    rows = [makeSpan$2(["vlist-r"], [vlist, topStrut]), makeSpan$2(["vlist-r"], [depthStrut])];
  } else {
    rows = [makeSpan$2(["vlist-r"], [vlist])];
  }
  var vtable = makeSpan$2(["vlist-t"], rows);
  if (rows.length === 2) {
    vtable.classes.push("vlist-t2");
  }
  vtable.height = maxPos;
  vtable.depth = -minPos;
  return vtable;
};
var makeGlue = (measurement, options) => {
  var rule = makeSpan$2(["mspace"], [], options);
  var size = calculateSize(measurement, options);
  rule.style.marginRight = makeEm(size);
  return rule;
};
var retrieveTextFontName = function retrieveTextFontName2(fontFamily, fontWeight, fontShape) {
  var baseFontName = "";
  switch (fontFamily) {
    case "amsrm":
      baseFontName = "AMS";
      break;
    case "textrm":
      baseFontName = "Main";
      break;
    case "textsf":
      baseFontName = "SansSerif";
      break;
    case "texttt":
      baseFontName = "Typewriter";
      break;
    default:
      baseFontName = fontFamily;
  }
  var fontStylesName;
  if (fontWeight === "textbf" && fontShape === "textit") {
    fontStylesName = "BoldItalic";
  } else if (fontWeight === "textbf") {
    fontStylesName = "Bold";
  } else if (fontWeight === "textit") {
    fontStylesName = "Italic";
  } else {
    fontStylesName = "Regular";
  }
  return baseFontName + "-" + fontStylesName;
};
var fontMap = {
  // styles
  "mathbf": {
    variant: "bold",
    fontName: "Main-Bold"
  },
  "mathrm": {
    variant: "normal",
    fontName: "Main-Regular"
  },
  "textit": {
    variant: "italic",
    fontName: "Main-Italic"
  },
  "mathit": {
    variant: "italic",
    fontName: "Main-Italic"
  },
  "mathnormal": {
    variant: "italic",
    fontName: "Math-Italic"
  },
  "mathsfit": {
    variant: "sans-serif-italic",
    fontName: "SansSerif-Italic"
  },
  // "boldsymbol" is missing because they require the use of multiple fonts:
  // Math-BoldItalic and Main-Bold.  This is handled by a special case in
  // makeOrd which ends up calling boldsymbol.
  // families
  "mathbb": {
    variant: "double-struck",
    fontName: "AMS-Regular"
  },
  "mathcal": {
    variant: "script",
    fontName: "Caligraphic-Regular"
  },
  "mathfrak": {
    variant: "fraktur",
    fontName: "Fraktur-Regular"
  },
  "mathscr": {
    variant: "script",
    fontName: "Script-Regular"
  },
  "mathsf": {
    variant: "sans-serif",
    fontName: "SansSerif-Regular"
  },
  "mathtt": {
    variant: "monospace",
    fontName: "Typewriter-Regular"
  }
};
var svgData = {
  //   path, width, height
  vec: ["vec", 0.471, 0.714],
  // values from the font glyph
  oiintSize1: ["oiintSize1", 0.957, 0.499],
  // oval to overlay the integrand
  oiintSize2: ["oiintSize2", 1.472, 0.659],
  oiiintSize1: ["oiiintSize1", 1.304, 0.499],
  oiiintSize2: ["oiiintSize2", 1.98, 0.659]
};
var staticSvg = function staticSvg2(value, options) {
  var [pathName, width, height] = svgData[value];
  var path6 = new PathNode(pathName);
  var svgNode = new SvgNode([path6], {
    "width": makeEm(width),
    "height": makeEm(height),
    // Override CSS rule `.katex svg { width: 100% }`
    "style": "width:" + makeEm(width),
    "viewBox": "0 0 " + 1e3 * width + " " + 1e3 * height,
    "preserveAspectRatio": "xMinYMin"
  });
  var span = makeSvgSpan(["overlay"], [svgNode], options);
  span.height = height;
  span.style.height = makeEm(height);
  span.style.width = makeEm(width);
  return span;
};
var buildCommon = {
  fontMap,
  makeSymbol,
  mathsym,
  makeSpan: makeSpan$2,
  makeSvgSpan,
  makeLineSpan,
  makeAnchor,
  makeFragment,
  wrapFragment,
  makeVList,
  makeOrd,
  makeGlue,
  staticSvg,
  svgData,
  tryCombineChars
};
var thinspace = {
  number: 3,
  unit: "mu"
};
var mediumspace = {
  number: 4,
  unit: "mu"
};
var thickspace = {
  number: 5,
  unit: "mu"
};
var spacings = {
  mord: {
    mop: thinspace,
    mbin: mediumspace,
    mrel: thickspace,
    minner: thinspace
  },
  mop: {
    mord: thinspace,
    mop: thinspace,
    mrel: thickspace,
    minner: thinspace
  },
  mbin: {
    mord: mediumspace,
    mop: mediumspace,
    mopen: mediumspace,
    minner: mediumspace
  },
  mrel: {
    mord: thickspace,
    mop: thickspace,
    mopen: thickspace,
    minner: thickspace
  },
  mopen: {},
  mclose: {
    mop: thinspace,
    mbin: mediumspace,
    mrel: thickspace,
    minner: thinspace
  },
  mpunct: {
    mord: thinspace,
    mop: thinspace,
    mrel: thickspace,
    mopen: thinspace,
    mclose: thinspace,
    mpunct: thinspace,
    minner: thinspace
  },
  minner: {
    mord: thinspace,
    mop: thinspace,
    mbin: mediumspace,
    mrel: thickspace,
    mopen: thinspace,
    mpunct: thinspace,
    minner: thinspace
  }
};
var tightSpacings = {
  mord: {
    mop: thinspace
  },
  mop: {
    mord: thinspace,
    mop: thinspace
  },
  mbin: {},
  mrel: {},
  mopen: {},
  mclose: {
    mop: thinspace
  },
  mpunct: {},
  minner: {
    mop: thinspace
  }
};
var _functions = {};
var _htmlGroupBuilders = {};
var _mathmlGroupBuilders = {};
function defineFunction(_ref) {
  var {
    type,
    names,
    props,
    handler,
    htmlBuilder: htmlBuilder3,
    mathmlBuilder: mathmlBuilder3
  } = _ref;
  var data = {
    type,
    numArgs: props.numArgs,
    argTypes: props.argTypes,
    allowedInArgument: !!props.allowedInArgument,
    allowedInText: !!props.allowedInText,
    allowedInMath: props.allowedInMath === void 0 ? true : props.allowedInMath,
    numOptionalArgs: props.numOptionalArgs || 0,
    infix: !!props.infix,
    primitive: !!props.primitive,
    handler
  };
  for (var i7 = 0; i7 < names.length; ++i7) {
    _functions[names[i7]] = data;
  }
  if (type) {
    if (htmlBuilder3) {
      _htmlGroupBuilders[type] = htmlBuilder3;
    }
    if (mathmlBuilder3) {
      _mathmlGroupBuilders[type] = mathmlBuilder3;
    }
  }
}
function defineFunctionBuilders(_ref2) {
  var {
    type,
    htmlBuilder: htmlBuilder3,
    mathmlBuilder: mathmlBuilder3
  } = _ref2;
  defineFunction({
    type,
    names: [],
    props: {
      numArgs: 0
    },
    handler() {
      throw new Error("Should never be called.");
    },
    htmlBuilder: htmlBuilder3,
    mathmlBuilder: mathmlBuilder3
  });
}
var normalizeArgument = function normalizeArgument2(arg) {
  return arg.type === "ordgroup" && arg.body.length === 1 ? arg.body[0] : arg;
};
var ordargument = function ordargument2(arg) {
  return arg.type === "ordgroup" ? arg.body : [arg];
};
var makeSpan$1 = buildCommon.makeSpan;
var binLeftCanceller = ["leftmost", "mbin", "mopen", "mrel", "mop", "mpunct"];
var binRightCanceller = ["rightmost", "mrel", "mclose", "mpunct"];
var styleMap$1 = {
  "display": Style$1.DISPLAY,
  "text": Style$1.TEXT,
  "script": Style$1.SCRIPT,
  "scriptscript": Style$1.SCRIPTSCRIPT
};
var DomEnum = {
  mord: "mord",
  mop: "mop",
  mbin: "mbin",
  mrel: "mrel",
  mopen: "mopen",
  mclose: "mclose",
  mpunct: "mpunct",
  minner: "minner"
};
var buildExpression$1 = function buildExpression(expression, options, isRealGroup, surrounding) {
  if (surrounding === void 0) {
    surrounding = [null, null];
  }
  var groups = [];
  for (var i7 = 0; i7 < expression.length; i7++) {
    var output = buildGroup$1(expression[i7], options);
    if (output instanceof DocumentFragment2) {
      var children = output.children;
      groups.push(...children);
    } else {
      groups.push(output);
    }
  }
  buildCommon.tryCombineChars(groups);
  if (!isRealGroup) {
    return groups;
  }
  var glueOptions = options;
  if (expression.length === 1) {
    var node = expression[0];
    if (node.type === "sizing") {
      glueOptions = options.havingSize(node.size);
    } else if (node.type === "styling") {
      glueOptions = options.havingStyle(styleMap$1[node.style]);
    }
  }
  var dummyPrev = makeSpan$1([surrounding[0] || "leftmost"], [], options);
  var dummyNext = makeSpan$1([surrounding[1] || "rightmost"], [], options);
  var isRoot = isRealGroup === "root";
  traverseNonSpaceNodes(groups, (node2, prev) => {
    var prevType = prev.classes[0];
    var type = node2.classes[0];
    if (prevType === "mbin" && utils2.contains(binRightCanceller, type)) {
      prev.classes[0] = "mord";
    } else if (type === "mbin" && utils2.contains(binLeftCanceller, prevType)) {
      node2.classes[0] = "mord";
    }
  }, {
    node: dummyPrev
  }, dummyNext, isRoot);
  traverseNonSpaceNodes(groups, (node2, prev) => {
    var prevType = getTypeOfDomTree(prev);
    var type = getTypeOfDomTree(node2);
    var space = prevType && type ? node2.hasClass("mtight") ? tightSpacings[prevType][type] : spacings[prevType][type] : null;
    if (space) {
      return buildCommon.makeGlue(space, glueOptions);
    }
  }, {
    node: dummyPrev
  }, dummyNext, isRoot);
  return groups;
};
var traverseNonSpaceNodes = function traverseNonSpaceNodes2(nodes, callback, prev, next, isRoot) {
  if (next) {
    nodes.push(next);
  }
  var i7 = 0;
  for (; i7 < nodes.length; i7++) {
    var node = nodes[i7];
    var partialGroup = checkPartialGroup(node);
    if (partialGroup) {
      traverseNonSpaceNodes2(partialGroup.children, callback, prev, null, isRoot);
      continue;
    }
    var nonspace = !node.hasClass("mspace");
    if (nonspace) {
      var result = callback(node, prev.node);
      if (result) {
        if (prev.insertAfter) {
          prev.insertAfter(result);
        } else {
          nodes.unshift(result);
          i7++;
        }
      }
    }
    if (nonspace) {
      prev.node = node;
    } else if (isRoot && node.hasClass("newline")) {
      prev.node = makeSpan$1(["leftmost"]);
    }
    prev.insertAfter = /* @__PURE__ */ ((index) => (n7) => {
      nodes.splice(index + 1, 0, n7);
      i7++;
    })(i7);
  }
  if (next) {
    nodes.pop();
  }
};
var checkPartialGroup = function checkPartialGroup2(node) {
  if (node instanceof DocumentFragment2 || node instanceof Anchor || node instanceof Span && node.hasClass("enclosing")) {
    return node;
  }
  return null;
};
var getOutermostNode = function getOutermostNode2(node, side) {
  var partialGroup = checkPartialGroup(node);
  if (partialGroup) {
    var children = partialGroup.children;
    if (children.length) {
      if (side === "right") {
        return getOutermostNode2(children[children.length - 1], "right");
      } else if (side === "left") {
        return getOutermostNode2(children[0], "left");
      }
    }
  }
  return node;
};
var getTypeOfDomTree = function getTypeOfDomTree2(node, side) {
  if (!node) {
    return null;
  }
  if (side) {
    node = getOutermostNode(node, side);
  }
  return DomEnum[node.classes[0]] || null;
};
var makeNullDelimiter = function makeNullDelimiter2(options, classes) {
  var moreClasses = ["nulldelimiter"].concat(options.baseSizingClasses());
  return makeSpan$1(classes.concat(moreClasses));
};
var buildGroup$1 = function buildGroup(group, options, baseOptions) {
  if (!group) {
    return makeSpan$1();
  }
  if (_htmlGroupBuilders[group.type]) {
    var groupNode = _htmlGroupBuilders[group.type](group, options);
    if (baseOptions && options.size !== baseOptions.size) {
      groupNode = makeSpan$1(options.sizingClasses(baseOptions), [groupNode], options);
      var multiplier = options.sizeMultiplier / baseOptions.sizeMultiplier;
      groupNode.height *= multiplier;
      groupNode.depth *= multiplier;
    }
    return groupNode;
  } else {
    throw new ParseError("Got group of unknown type: '" + group.type + "'");
  }
};
function buildHTMLUnbreakable(children, options) {
  var body = makeSpan$1(["base"], children, options);
  var strut = makeSpan$1(["strut"]);
  strut.style.height = makeEm(body.height + body.depth);
  if (body.depth) {
    strut.style.verticalAlign = makeEm(-body.depth);
  }
  body.children.unshift(strut);
  return body;
}
function buildHTML(tree, options) {
  var tag = null;
  if (tree.length === 1 && tree[0].type === "tag") {
    tag = tree[0].tag;
    tree = tree[0].body;
  }
  var expression = buildExpression$1(tree, options, "root");
  var eqnNum;
  if (expression.length === 2 && expression[1].hasClass("tag")) {
    eqnNum = expression.pop();
  }
  var children = [];
  var parts = [];
  for (var i7 = 0; i7 < expression.length; i7++) {
    parts.push(expression[i7]);
    if (expression[i7].hasClass("mbin") || expression[i7].hasClass("mrel") || expression[i7].hasClass("allowbreak")) {
      var nobreak = false;
      while (i7 < expression.length - 1 && expression[i7 + 1].hasClass("mspace") && !expression[i7 + 1].hasClass("newline")) {
        i7++;
        parts.push(expression[i7]);
        if (expression[i7].hasClass("nobreak")) {
          nobreak = true;
        }
      }
      if (!nobreak) {
        children.push(buildHTMLUnbreakable(parts, options));
        parts = [];
      }
    } else if (expression[i7].hasClass("newline")) {
      parts.pop();
      if (parts.length > 0) {
        children.push(buildHTMLUnbreakable(parts, options));
        parts = [];
      }
      children.push(expression[i7]);
    }
  }
  if (parts.length > 0) {
    children.push(buildHTMLUnbreakable(parts, options));
  }
  var tagChild;
  if (tag) {
    tagChild = buildHTMLUnbreakable(buildExpression$1(tag, options, true));
    tagChild.classes = ["tag"];
    children.push(tagChild);
  } else if (eqnNum) {
    children.push(eqnNum);
  }
  var htmlNode = makeSpan$1(["katex-html"], children);
  htmlNode.setAttribute("aria-hidden", "true");
  if (tagChild) {
    var strut = tagChild.children[0];
    strut.style.height = makeEm(htmlNode.height + htmlNode.depth);
    if (htmlNode.depth) {
      strut.style.verticalAlign = makeEm(-htmlNode.depth);
    }
  }
  return htmlNode;
}
function newDocumentFragment(children) {
  return new DocumentFragment2(children);
}
var MathNode = class {
  constructor(type, children, classes) {
    this.type = void 0;
    this.attributes = void 0;
    this.children = void 0;
    this.classes = void 0;
    this.type = type;
    this.attributes = {};
    this.children = children || [];
    this.classes = classes || [];
  }
  /**
   * Sets an attribute on a MathML node. MathML depends on attributes to convey a
   * semantic content, so this is used heavily.
   */
  setAttribute(name, value) {
    this.attributes[name] = value;
  }
  /**
   * Gets an attribute on a MathML node.
   */
  getAttribute(name) {
    return this.attributes[name];
  }
  /**
   * Converts the math node into a MathML-namespaced DOM element.
   */
  toNode() {
    var node = document.createElementNS("http://www.w3.org/1998/Math/MathML", this.type);
    for (var attr in this.attributes) {
      if (Object.prototype.hasOwnProperty.call(this.attributes, attr)) {
        node.setAttribute(attr, this.attributes[attr]);
      }
    }
    if (this.classes.length > 0) {
      node.className = createClass(this.classes);
    }
    for (var i7 = 0; i7 < this.children.length; i7++) {
      if (this.children[i7] instanceof TextNode && this.children[i7 + 1] instanceof TextNode) {
        var text3 = this.children[i7].toText() + this.children[++i7].toText();
        while (this.children[i7 + 1] instanceof TextNode) {
          text3 += this.children[++i7].toText();
        }
        node.appendChild(new TextNode(text3).toNode());
      } else {
        node.appendChild(this.children[i7].toNode());
      }
    }
    return node;
  }
  /**
   * Converts the math node into an HTML markup string.
   */
  toMarkup() {
    var markup = "<" + this.type;
    for (var attr in this.attributes) {
      if (Object.prototype.hasOwnProperty.call(this.attributes, attr)) {
        markup += " " + attr + '="';
        markup += utils2.escape(this.attributes[attr]);
        markup += '"';
      }
    }
    if (this.classes.length > 0) {
      markup += ' class ="' + utils2.escape(createClass(this.classes)) + '"';
    }
    markup += ">";
    for (var i7 = 0; i7 < this.children.length; i7++) {
      markup += this.children[i7].toMarkup();
    }
    markup += "</" + this.type + ">";
    return markup;
  }
  /**
   * Converts the math node into a string, similar to innerText, but escaped.
   */
  toText() {
    return this.children.map((child) => child.toText()).join("");
  }
};
var TextNode = class {
  constructor(text3) {
    this.text = void 0;
    this.text = text3;
  }
  /**
   * Converts the text node into a DOM text node.
   */
  toNode() {
    return document.createTextNode(this.text);
  }
  /**
   * Converts the text node into escaped HTML markup
   * (representing the text itself).
   */
  toMarkup() {
    return utils2.escape(this.toText());
  }
  /**
   * Converts the text node into a string
   * (representing the text itself).
   */
  toText() {
    return this.text;
  }
};
var SpaceNode = class {
  /**
   * Create a Space node with width given in CSS ems.
   */
  constructor(width) {
    this.width = void 0;
    this.character = void 0;
    this.width = width;
    if (width >= 0.05555 && width <= 0.05556) {
      this.character = "\u200A";
    } else if (width >= 0.1666 && width <= 0.1667) {
      this.character = "\u2009";
    } else if (width >= 0.2222 && width <= 0.2223) {
      this.character = "\u2005";
    } else if (width >= 0.2777 && width <= 0.2778) {
      this.character = "\u2005\u200A";
    } else if (width >= -0.05556 && width <= -0.05555) {
      this.character = "\u200A\u2063";
    } else if (width >= -0.1667 && width <= -0.1666) {
      this.character = "\u2009\u2063";
    } else if (width >= -0.2223 && width <= -0.2222) {
      this.character = "\u205F\u2063";
    } else if (width >= -0.2778 && width <= -0.2777) {
      this.character = "\u2005\u2063";
    } else {
      this.character = null;
    }
  }
  /**
   * Converts the math node into a MathML-namespaced DOM element.
   */
  toNode() {
    if (this.character) {
      return document.createTextNode(this.character);
    } else {
      var node = document.createElementNS("http://www.w3.org/1998/Math/MathML", "mspace");
      node.setAttribute("width", makeEm(this.width));
      return node;
    }
  }
  /**
   * Converts the math node into an HTML markup string.
   */
  toMarkup() {
    if (this.character) {
      return "<mtext>" + this.character + "</mtext>";
    } else {
      return '<mspace width="' + makeEm(this.width) + '"/>';
    }
  }
  /**
   * Converts the math node into a string, similar to innerText.
   */
  toText() {
    if (this.character) {
      return this.character;
    } else {
      return " ";
    }
  }
};
var mathMLTree = {
  MathNode,
  TextNode,
  SpaceNode,
  newDocumentFragment
};
var makeText = function makeText2(text3, mode, options) {
  if (symbols[mode][text3] && symbols[mode][text3].replace && text3.charCodeAt(0) !== 55349 && !(ligatures.hasOwnProperty(text3) && options && (options.fontFamily && options.fontFamily.slice(4, 6) === "tt" || options.font && options.font.slice(4, 6) === "tt"))) {
    text3 = symbols[mode][text3].replace;
  }
  return new mathMLTree.TextNode(text3);
};
var makeRow = function makeRow2(body) {
  if (body.length === 1) {
    return body[0];
  } else {
    return new mathMLTree.MathNode("mrow", body);
  }
};
var getVariant = function getVariant2(group, options) {
  if (options.fontFamily === "texttt") {
    return "monospace";
  } else if (options.fontFamily === "textsf") {
    if (options.fontShape === "textit" && options.fontWeight === "textbf") {
      return "sans-serif-bold-italic";
    } else if (options.fontShape === "textit") {
      return "sans-serif-italic";
    } else if (options.fontWeight === "textbf") {
      return "bold-sans-serif";
    } else {
      return "sans-serif";
    }
  } else if (options.fontShape === "textit" && options.fontWeight === "textbf") {
    return "bold-italic";
  } else if (options.fontShape === "textit") {
    return "italic";
  } else if (options.fontWeight === "textbf") {
    return "bold";
  }
  var font = options.font;
  if (!font || font === "mathnormal") {
    return null;
  }
  var mode = group.mode;
  if (font === "mathit") {
    return "italic";
  } else if (font === "boldsymbol") {
    return group.type === "textord" ? "bold" : "bold-italic";
  } else if (font === "mathbf") {
    return "bold";
  } else if (font === "mathbb") {
    return "double-struck";
  } else if (font === "mathsfit") {
    return "sans-serif-italic";
  } else if (font === "mathfrak") {
    return "fraktur";
  } else if (font === "mathscr" || font === "mathcal") {
    return "script";
  } else if (font === "mathsf") {
    return "sans-serif";
  } else if (font === "mathtt") {
    return "monospace";
  }
  var text3 = group.text;
  if (utils2.contains(["\\imath", "\\jmath"], text3)) {
    return null;
  }
  if (symbols[mode][text3] && symbols[mode][text3].replace) {
    text3 = symbols[mode][text3].replace;
  }
  var fontName = buildCommon.fontMap[font].fontName;
  if (getCharacterMetrics(text3, fontName, mode)) {
    return buildCommon.fontMap[font].variant;
  }
  return null;
};
function isNumberPunctuation(group) {
  if (!group) {
    return false;
  }
  if (group.type === "mi" && group.children.length === 1) {
    var child = group.children[0];
    return child instanceof TextNode && child.text === ".";
  } else if (group.type === "mo" && group.children.length === 1 && group.getAttribute("separator") === "true" && group.getAttribute("lspace") === "0em" && group.getAttribute("rspace") === "0em") {
    var _child = group.children[0];
    return _child instanceof TextNode && _child.text === ",";
  } else {
    return false;
  }
}
var buildExpression2 = function buildExpression3(expression, options, isOrdgroup) {
  if (expression.length === 1) {
    var group = buildGroup2(expression[0], options);
    if (isOrdgroup && group instanceof MathNode && group.type === "mo") {
      group.setAttribute("lspace", "0em");
      group.setAttribute("rspace", "0em");
    }
    return [group];
  }
  var groups = [];
  var lastGroup;
  for (var i7 = 0; i7 < expression.length; i7++) {
    var _group = buildGroup2(expression[i7], options);
    if (_group instanceof MathNode && lastGroup instanceof MathNode) {
      if (_group.type === "mtext" && lastGroup.type === "mtext" && _group.getAttribute("mathvariant") === lastGroup.getAttribute("mathvariant")) {
        lastGroup.children.push(..._group.children);
        continue;
      } else if (_group.type === "mn" && lastGroup.type === "mn") {
        lastGroup.children.push(..._group.children);
        continue;
      } else if (isNumberPunctuation(_group) && lastGroup.type === "mn") {
        lastGroup.children.push(..._group.children);
        continue;
      } else if (_group.type === "mn" && isNumberPunctuation(lastGroup)) {
        _group.children = [...lastGroup.children, ..._group.children];
        groups.pop();
      } else if ((_group.type === "msup" || _group.type === "msub") && _group.children.length >= 1 && (lastGroup.type === "mn" || isNumberPunctuation(lastGroup))) {
        var base = _group.children[0];
        if (base instanceof MathNode && base.type === "mn") {
          base.children = [...lastGroup.children, ...base.children];
          groups.pop();
        }
      } else if (lastGroup.type === "mi" && lastGroup.children.length === 1) {
        var lastChild = lastGroup.children[0];
        if (lastChild instanceof TextNode && lastChild.text === "\u0338" && (_group.type === "mo" || _group.type === "mi" || _group.type === "mn")) {
          var child = _group.children[0];
          if (child instanceof TextNode && child.text.length > 0) {
            child.text = child.text.slice(0, 1) + "\u0338" + child.text.slice(1);
            groups.pop();
          }
        }
      }
    }
    groups.push(_group);
    lastGroup = _group;
  }
  return groups;
};
var buildExpressionRow = function buildExpressionRow2(expression, options, isOrdgroup) {
  return makeRow(buildExpression2(expression, options, isOrdgroup));
};
var buildGroup2 = function buildGroup3(group, options) {
  if (!group) {
    return new mathMLTree.MathNode("mrow");
  }
  if (_mathmlGroupBuilders[group.type]) {
    var result = _mathmlGroupBuilders[group.type](group, options);
    return result;
  } else {
    throw new ParseError("Got group of unknown type: '" + group.type + "'");
  }
};
function buildMathML(tree, texExpression, options, isDisplayMode, forMathmlOnly) {
  var expression = buildExpression2(tree, options);
  var wrapper;
  if (expression.length === 1 && expression[0] instanceof MathNode && utils2.contains(["mrow", "mtable"], expression[0].type)) {
    wrapper = expression[0];
  } else {
    wrapper = new mathMLTree.MathNode("mrow", expression);
  }
  var annotation = new mathMLTree.MathNode("annotation", [new mathMLTree.TextNode(texExpression)]);
  annotation.setAttribute("encoding", "application/x-tex");
  var semantics = new mathMLTree.MathNode("semantics", [wrapper, annotation]);
  var math2 = new mathMLTree.MathNode("math", [semantics]);
  math2.setAttribute("xmlns", "http://www.w3.org/1998/Math/MathML");
  if (isDisplayMode) {
    math2.setAttribute("display", "block");
  }
  var wrapperClass = forMathmlOnly ? "katex" : "katex-mathml";
  return buildCommon.makeSpan([wrapperClass], [math2]);
}
var optionsFromSettings = function optionsFromSettings2(settings) {
  return new Options({
    style: settings.displayMode ? Style$1.DISPLAY : Style$1.TEXT,
    maxSize: settings.maxSize,
    minRuleThickness: settings.minRuleThickness
  });
};
var displayWrap = function displayWrap2(node, settings) {
  if (settings.displayMode) {
    var classes = ["katex-display"];
    if (settings.leqno) {
      classes.push("leqno");
    }
    if (settings.fleqn) {
      classes.push("fleqn");
    }
    node = buildCommon.makeSpan(classes, [node]);
  }
  return node;
};
var buildTree = function buildTree2(tree, expression, settings) {
  var options = optionsFromSettings(settings);
  var katexNode;
  if (settings.output === "mathml") {
    return buildMathML(tree, expression, options, settings.displayMode, true);
  } else if (settings.output === "html") {
    var htmlNode = buildHTML(tree, options);
    katexNode = buildCommon.makeSpan(["katex"], [htmlNode]);
  } else {
    var mathMLNode = buildMathML(tree, expression, options, settings.displayMode, false);
    var _htmlNode = buildHTML(tree, options);
    katexNode = buildCommon.makeSpan(["katex"], [mathMLNode, _htmlNode]);
  }
  return displayWrap(katexNode, settings);
};
var buildHTMLTree = function buildHTMLTree2(tree, expression, settings) {
  var options = optionsFromSettings(settings);
  var htmlNode = buildHTML(tree, options);
  var katexNode = buildCommon.makeSpan(["katex"], [htmlNode]);
  return displayWrap(katexNode, settings);
};
var stretchyCodePoint = {
  widehat: "^",
  widecheck: "\u02C7",
  widetilde: "~",
  utilde: "~",
  overleftarrow: "\u2190",
  underleftarrow: "\u2190",
  xleftarrow: "\u2190",
  overrightarrow: "\u2192",
  underrightarrow: "\u2192",
  xrightarrow: "\u2192",
  underbrace: "\u23DF",
  overbrace: "\u23DE",
  overgroup: "\u23E0",
  undergroup: "\u23E1",
  overleftrightarrow: "\u2194",
  underleftrightarrow: "\u2194",
  xleftrightarrow: "\u2194",
  Overrightarrow: "\u21D2",
  xRightarrow: "\u21D2",
  overleftharpoon: "\u21BC",
  xleftharpoonup: "\u21BC",
  overrightharpoon: "\u21C0",
  xrightharpoonup: "\u21C0",
  xLeftarrow: "\u21D0",
  xLeftrightarrow: "\u21D4",
  xhookleftarrow: "\u21A9",
  xhookrightarrow: "\u21AA",
  xmapsto: "\u21A6",
  xrightharpoondown: "\u21C1",
  xleftharpoondown: "\u21BD",
  xrightleftharpoons: "\u21CC",
  xleftrightharpoons: "\u21CB",
  xtwoheadleftarrow: "\u219E",
  xtwoheadrightarrow: "\u21A0",
  xlongequal: "=",
  xtofrom: "\u21C4",
  xrightleftarrows: "\u21C4",
  xrightequilibrium: "\u21CC",
  // Not a perfect match.
  xleftequilibrium: "\u21CB",
  // None better available.
  "\\cdrightarrow": "\u2192",
  "\\cdleftarrow": "\u2190",
  "\\cdlongequal": "="
};
var mathMLnode = function mathMLnode2(label) {
  var node = new mathMLTree.MathNode("mo", [new mathMLTree.TextNode(stretchyCodePoint[label.replace(/^\\/, "")])]);
  node.setAttribute("stretchy", "true");
  return node;
};
var katexImagesData = {
  //   path(s), minWidth, height, align
  overrightarrow: [["rightarrow"], 0.888, 522, "xMaxYMin"],
  overleftarrow: [["leftarrow"], 0.888, 522, "xMinYMin"],
  underrightarrow: [["rightarrow"], 0.888, 522, "xMaxYMin"],
  underleftarrow: [["leftarrow"], 0.888, 522, "xMinYMin"],
  xrightarrow: [["rightarrow"], 1.469, 522, "xMaxYMin"],
  "\\cdrightarrow": [["rightarrow"], 3, 522, "xMaxYMin"],
  // CD minwwidth2.5pc
  xleftarrow: [["leftarrow"], 1.469, 522, "xMinYMin"],
  "\\cdleftarrow": [["leftarrow"], 3, 522, "xMinYMin"],
  Overrightarrow: [["doublerightarrow"], 0.888, 560, "xMaxYMin"],
  xRightarrow: [["doublerightarrow"], 1.526, 560, "xMaxYMin"],
  xLeftarrow: [["doubleleftarrow"], 1.526, 560, "xMinYMin"],
  overleftharpoon: [["leftharpoon"], 0.888, 522, "xMinYMin"],
  xleftharpoonup: [["leftharpoon"], 0.888, 522, "xMinYMin"],
  xleftharpoondown: [["leftharpoondown"], 0.888, 522, "xMinYMin"],
  overrightharpoon: [["rightharpoon"], 0.888, 522, "xMaxYMin"],
  xrightharpoonup: [["rightharpoon"], 0.888, 522, "xMaxYMin"],
  xrightharpoondown: [["rightharpoondown"], 0.888, 522, "xMaxYMin"],
  xlongequal: [["longequal"], 0.888, 334, "xMinYMin"],
  "\\cdlongequal": [["longequal"], 3, 334, "xMinYMin"],
  xtwoheadleftarrow: [["twoheadleftarrow"], 0.888, 334, "xMinYMin"],
  xtwoheadrightarrow: [["twoheadrightarrow"], 0.888, 334, "xMaxYMin"],
  overleftrightarrow: [["leftarrow", "rightarrow"], 0.888, 522],
  overbrace: [["leftbrace", "midbrace", "rightbrace"], 1.6, 548],
  underbrace: [["leftbraceunder", "midbraceunder", "rightbraceunder"], 1.6, 548],
  underleftrightarrow: [["leftarrow", "rightarrow"], 0.888, 522],
  xleftrightarrow: [["leftarrow", "rightarrow"], 1.75, 522],
  xLeftrightarrow: [["doubleleftarrow", "doublerightarrow"], 1.75, 560],
  xrightleftharpoons: [["leftharpoondownplus", "rightharpoonplus"], 1.75, 716],
  xleftrightharpoons: [["leftharpoonplus", "rightharpoondownplus"], 1.75, 716],
  xhookleftarrow: [["leftarrow", "righthook"], 1.08, 522],
  xhookrightarrow: [["lefthook", "rightarrow"], 1.08, 522],
  overlinesegment: [["leftlinesegment", "rightlinesegment"], 0.888, 522],
  underlinesegment: [["leftlinesegment", "rightlinesegment"], 0.888, 522],
  overgroup: [["leftgroup", "rightgroup"], 0.888, 342],
  undergroup: [["leftgroupunder", "rightgroupunder"], 0.888, 342],
  xmapsto: [["leftmapsto", "rightarrow"], 1.5, 522],
  xtofrom: [["leftToFrom", "rightToFrom"], 1.75, 528],
  // The next three arrows are from the mhchem package.
  // In mhchem.sty, min-length is 2.0em. But these arrows might appear in the
  // document as \xrightarrow or \xrightleftharpoons. Those have
  // min-length = 1.75em, so we set min-length on these next three to match.
  xrightleftarrows: [["baraboveleftarrow", "rightarrowabovebar"], 1.75, 901],
  xrightequilibrium: [["baraboveshortleftharpoon", "rightharpoonaboveshortbar"], 1.75, 716],
  xleftequilibrium: [["shortbaraboveleftharpoon", "shortrightharpoonabovebar"], 1.75, 716]
};
var groupLength = function groupLength2(arg) {
  if (arg.type === "ordgroup") {
    return arg.body.length;
  } else {
    return 1;
  }
};
var svgSpan = function svgSpan2(group, options) {
  function buildSvgSpan_() {
    var viewBoxWidth = 4e5;
    var label = group.label.slice(1);
    if (utils2.contains(["widehat", "widecheck", "widetilde", "utilde"], label)) {
      var grp = group;
      var numChars = groupLength(grp.base);
      var viewBoxHeight;
      var pathName;
      var _height;
      if (numChars > 5) {
        if (label === "widehat" || label === "widecheck") {
          viewBoxHeight = 420;
          viewBoxWidth = 2364;
          _height = 0.42;
          pathName = label + "4";
        } else {
          viewBoxHeight = 312;
          viewBoxWidth = 2340;
          _height = 0.34;
          pathName = "tilde4";
        }
      } else {
        var imgIndex = [1, 1, 2, 2, 3, 3][numChars];
        if (label === "widehat" || label === "widecheck") {
          viewBoxWidth = [0, 1062, 2364, 2364, 2364][imgIndex];
          viewBoxHeight = [0, 239, 300, 360, 420][imgIndex];
          _height = [0, 0.24, 0.3, 0.3, 0.36, 0.42][imgIndex];
          pathName = label + imgIndex;
        } else {
          viewBoxWidth = [0, 600, 1033, 2339, 2340][imgIndex];
          viewBoxHeight = [0, 260, 286, 306, 312][imgIndex];
          _height = [0, 0.26, 0.286, 0.3, 0.306, 0.34][imgIndex];
          pathName = "tilde" + imgIndex;
        }
      }
      var path6 = new PathNode(pathName);
      var svgNode = new SvgNode([path6], {
        "width": "100%",
        "height": makeEm(_height),
        "viewBox": "0 0 " + viewBoxWidth + " " + viewBoxHeight,
        "preserveAspectRatio": "none"
      });
      return {
        span: buildCommon.makeSvgSpan([], [svgNode], options),
        minWidth: 0,
        height: _height
      };
    } else {
      var spans = [];
      var data = katexImagesData[label];
      var [paths, _minWidth, _viewBoxHeight] = data;
      var _height2 = _viewBoxHeight / 1e3;
      var numSvgChildren = paths.length;
      var widthClasses;
      var aligns;
      if (numSvgChildren === 1) {
        var align1 = data[3];
        widthClasses = ["hide-tail"];
        aligns = [align1];
      } else if (numSvgChildren === 2) {
        widthClasses = ["halfarrow-left", "halfarrow-right"];
        aligns = ["xMinYMin", "xMaxYMin"];
      } else if (numSvgChildren === 3) {
        widthClasses = ["brace-left", "brace-center", "brace-right"];
        aligns = ["xMinYMin", "xMidYMin", "xMaxYMin"];
      } else {
        throw new Error("Correct katexImagesData or update code here to support\n                    " + numSvgChildren + " children.");
      }
      for (var i7 = 0; i7 < numSvgChildren; i7++) {
        var _path = new PathNode(paths[i7]);
        var _svgNode = new SvgNode([_path], {
          "width": "400em",
          "height": makeEm(_height2),
          "viewBox": "0 0 " + viewBoxWidth + " " + _viewBoxHeight,
          "preserveAspectRatio": aligns[i7] + " slice"
        });
        var _span = buildCommon.makeSvgSpan([widthClasses[i7]], [_svgNode], options);
        if (numSvgChildren === 1) {
          return {
            span: _span,
            minWidth: _minWidth,
            height: _height2
          };
        } else {
          _span.style.height = makeEm(_height2);
          spans.push(_span);
        }
      }
      return {
        span: buildCommon.makeSpan(["stretchy"], spans, options),
        minWidth: _minWidth,
        height: _height2
      };
    }
  }
  var {
    span,
    minWidth,
    height
  } = buildSvgSpan_();
  span.height = height;
  span.style.height = makeEm(height);
  if (minWidth > 0) {
    span.style.minWidth = makeEm(minWidth);
  }
  return span;
};
var encloseSpan = function encloseSpan2(inner2, label, topPad, bottomPad, options) {
  var img;
  var totalHeight = inner2.height + inner2.depth + topPad + bottomPad;
  if (/fbox|color|angl/.test(label)) {
    img = buildCommon.makeSpan(["stretchy", label], [], options);
    if (label === "fbox") {
      var color = options.color && options.getColor();
      if (color) {
        img.style.borderColor = color;
      }
    }
  } else {
    var lines = [];
    if (/^[bx]cancel$/.test(label)) {
      lines.push(new LineNode({
        "x1": "0",
        "y1": "0",
        "x2": "100%",
        "y2": "100%",
        "stroke-width": "0.046em"
      }));
    }
    if (/^x?cancel$/.test(label)) {
      lines.push(new LineNode({
        "x1": "0",
        "y1": "100%",
        "x2": "100%",
        "y2": "0",
        "stroke-width": "0.046em"
      }));
    }
    var svgNode = new SvgNode(lines, {
      "width": "100%",
      "height": makeEm(totalHeight)
    });
    img = buildCommon.makeSvgSpan([], [svgNode], options);
  }
  img.height = totalHeight;
  img.style.height = makeEm(totalHeight);
  return img;
};
var stretchy = {
  encloseSpan,
  mathMLnode,
  svgSpan
};
function assertNodeType(node, type) {
  if (!node || node.type !== type) {
    throw new Error("Expected node of type " + type + ", but got " + (node ? "node of type " + node.type : String(node)));
  }
  return node;
}
function assertSymbolNodeType(node) {
  var typedNode = checkSymbolNodeType(node);
  if (!typedNode) {
    throw new Error("Expected node of symbol group type, but got " + (node ? "node of type " + node.type : String(node)));
  }
  return typedNode;
}
function checkSymbolNodeType(node) {
  if (node && (node.type === "atom" || NON_ATOMS.hasOwnProperty(node.type))) {
    return node;
  }
  return null;
}
var htmlBuilder$a = (grp, options) => {
  var base;
  var group;
  var supSubGroup;
  if (grp && grp.type === "supsub") {
    group = assertNodeType(grp.base, "accent");
    base = group.base;
    grp.base = base;
    supSubGroup = assertSpan(buildGroup$1(grp, options));
    grp.base = group;
  } else {
    group = assertNodeType(grp, "accent");
    base = group.base;
  }
  var body = buildGroup$1(base, options.havingCrampedStyle());
  var mustShift = group.isShifty && utils2.isCharacterBox(base);
  var skew = 0;
  if (mustShift) {
    var baseChar = utils2.getBaseElem(base);
    var baseGroup = buildGroup$1(baseChar, options.havingCrampedStyle());
    skew = assertSymbolDomNode(baseGroup).skew;
  }
  var accentBelow = group.label === "\\c";
  var clearance = accentBelow ? body.height + body.depth : Math.min(body.height, options.fontMetrics().xHeight);
  var accentBody;
  if (!group.isStretchy) {
    var accent2;
    var width;
    if (group.label === "\\vec") {
      accent2 = buildCommon.staticSvg("vec", options);
      width = buildCommon.svgData.vec[1];
    } else {
      accent2 = buildCommon.makeOrd({
        mode: group.mode,
        text: group.label
      }, options, "textord");
      accent2 = assertSymbolDomNode(accent2);
      accent2.italic = 0;
      width = accent2.width;
      if (accentBelow) {
        clearance += accent2.depth;
      }
    }
    accentBody = buildCommon.makeSpan(["accent-body"], [accent2]);
    var accentFull = group.label === "\\textcircled";
    if (accentFull) {
      accentBody.classes.push("accent-full");
      clearance = body.height;
    }
    var left = skew;
    if (!accentFull) {
      left -= width / 2;
    }
    accentBody.style.left = makeEm(left);
    if (group.label === "\\textcircled") {
      accentBody.style.top = ".2em";
    }
    accentBody = buildCommon.makeVList({
      positionType: "firstBaseline",
      children: [{
        type: "elem",
        elem: body
      }, {
        type: "kern",
        size: -clearance
      }, {
        type: "elem",
        elem: accentBody
      }]
    }, options);
  } else {
    accentBody = stretchy.svgSpan(group, options);
    accentBody = buildCommon.makeVList({
      positionType: "firstBaseline",
      children: [{
        type: "elem",
        elem: body
      }, {
        type: "elem",
        elem: accentBody,
        wrapperClasses: ["svg-align"],
        wrapperStyle: skew > 0 ? {
          width: "calc(100% - " + makeEm(2 * skew) + ")",
          marginLeft: makeEm(2 * skew)
        } : void 0
      }]
    }, options);
  }
  var accentWrap = buildCommon.makeSpan(["mord", "accent"], [accentBody], options);
  if (supSubGroup) {
    supSubGroup.children[0] = accentWrap;
    supSubGroup.height = Math.max(accentWrap.height, supSubGroup.height);
    supSubGroup.classes[0] = "mord";
    return supSubGroup;
  } else {
    return accentWrap;
  }
};
var mathmlBuilder$9 = (group, options) => {
  var accentNode = group.isStretchy ? stretchy.mathMLnode(group.label) : new mathMLTree.MathNode("mo", [makeText(group.label, group.mode)]);
  var node = new mathMLTree.MathNode("mover", [buildGroup2(group.base, options), accentNode]);
  node.setAttribute("accent", "true");
  return node;
};
var NON_STRETCHY_ACCENT_REGEX = new RegExp(["\\acute", "\\grave", "\\ddot", "\\tilde", "\\bar", "\\breve", "\\check", "\\hat", "\\vec", "\\dot", "\\mathring"].map((accent2) => "\\" + accent2).join("|"));
defineFunction({
  type: "accent",
  names: ["\\acute", "\\grave", "\\ddot", "\\tilde", "\\bar", "\\breve", "\\check", "\\hat", "\\vec", "\\dot", "\\mathring", "\\widecheck", "\\widehat", "\\widetilde", "\\overrightarrow", "\\overleftarrow", "\\Overrightarrow", "\\overleftrightarrow", "\\overgroup", "\\overlinesegment", "\\overleftharpoon", "\\overrightharpoon"],
  props: {
    numArgs: 1
  },
  handler: (context, args) => {
    var base = normalizeArgument(args[0]);
    var isStretchy = !NON_STRETCHY_ACCENT_REGEX.test(context.funcName);
    var isShifty = !isStretchy || context.funcName === "\\widehat" || context.funcName === "\\widetilde" || context.funcName === "\\widecheck";
    return {
      type: "accent",
      mode: context.parser.mode,
      label: context.funcName,
      isStretchy,
      isShifty,
      base
    };
  },
  htmlBuilder: htmlBuilder$a,
  mathmlBuilder: mathmlBuilder$9
});
defineFunction({
  type: "accent",
  names: ["\\'", "\\`", "\\^", "\\~", "\\=", "\\u", "\\.", '\\"', "\\c", "\\r", "\\H", "\\v", "\\textcircled"],
  props: {
    numArgs: 1,
    allowedInText: true,
    allowedInMath: true,
    // unless in strict mode
    argTypes: ["primitive"]
  },
  handler: (context, args) => {
    var base = args[0];
    var mode = context.parser.mode;
    if (mode === "math") {
      context.parser.settings.reportNonstrict("mathVsTextAccents", "LaTeX's accent " + context.funcName + " works only in text mode");
      mode = "text";
    }
    return {
      type: "accent",
      mode,
      label: context.funcName,
      isStretchy: false,
      isShifty: true,
      base
    };
  },
  htmlBuilder: htmlBuilder$a,
  mathmlBuilder: mathmlBuilder$9
});
defineFunction({
  type: "accentUnder",
  names: ["\\underleftarrow", "\\underrightarrow", "\\underleftrightarrow", "\\undergroup", "\\underlinesegment", "\\utilde"],
  props: {
    numArgs: 1
  },
  handler: (_ref, args) => {
    var {
      parser,
      funcName
    } = _ref;
    var base = args[0];
    return {
      type: "accentUnder",
      mode: parser.mode,
      label: funcName,
      base
    };
  },
  htmlBuilder: (group, options) => {
    var innerGroup = buildGroup$1(group.base, options);
    var accentBody = stretchy.svgSpan(group, options);
    var kern = group.label === "\\utilde" ? 0.12 : 0;
    var vlist = buildCommon.makeVList({
      positionType: "top",
      positionData: innerGroup.height,
      children: [{
        type: "elem",
        elem: accentBody,
        wrapperClasses: ["svg-align"]
      }, {
        type: "kern",
        size: kern
      }, {
        type: "elem",
        elem: innerGroup
      }]
    }, options);
    return buildCommon.makeSpan(["mord", "accentunder"], [vlist], options);
  },
  mathmlBuilder: (group, options) => {
    var accentNode = stretchy.mathMLnode(group.label);
    var node = new mathMLTree.MathNode("munder", [buildGroup2(group.base, options), accentNode]);
    node.setAttribute("accentunder", "true");
    return node;
  }
});
var paddedNode = (group) => {
  var node = new mathMLTree.MathNode("mpadded", group ? [group] : []);
  node.setAttribute("width", "+0.6em");
  node.setAttribute("lspace", "0.3em");
  return node;
};
defineFunction({
  type: "xArrow",
  names: [
    "\\xleftarrow",
    "\\xrightarrow",
    "\\xLeftarrow",
    "\\xRightarrow",
    "\\xleftrightarrow",
    "\\xLeftrightarrow",
    "\\xhookleftarrow",
    "\\xhookrightarrow",
    "\\xmapsto",
    "\\xrightharpoondown",
    "\\xrightharpoonup",
    "\\xleftharpoondown",
    "\\xleftharpoonup",
    "\\xrightleftharpoons",
    "\\xleftrightharpoons",
    "\\xlongequal",
    "\\xtwoheadrightarrow",
    "\\xtwoheadleftarrow",
    "\\xtofrom",
    // The next 3 functions are here to support the mhchem extension.
    // Direct use of these functions is discouraged and may break someday.
    "\\xrightleftarrows",
    "\\xrightequilibrium",
    "\\xleftequilibrium",
    // The next 3 functions are here only to support the {CD} environment.
    "\\\\cdrightarrow",
    "\\\\cdleftarrow",
    "\\\\cdlongequal"
  ],
  props: {
    numArgs: 1,
    numOptionalArgs: 1
  },
  handler(_ref, args, optArgs) {
    var {
      parser,
      funcName
    } = _ref;
    return {
      type: "xArrow",
      mode: parser.mode,
      label: funcName,
      body: args[0],
      below: optArgs[0]
    };
  },
  // Flow is unable to correctly infer the type of `group`, even though it's
  // unambiguously determined from the passed-in `type` above.
  htmlBuilder(group, options) {
    var style = options.style;
    var newOptions = options.havingStyle(style.sup());
    var upperGroup = buildCommon.wrapFragment(buildGroup$1(group.body, newOptions, options), options);
    var arrowPrefix = group.label.slice(0, 2) === "\\x" ? "x" : "cd";
    upperGroup.classes.push(arrowPrefix + "-arrow-pad");
    var lowerGroup;
    if (group.below) {
      newOptions = options.havingStyle(style.sub());
      lowerGroup = buildCommon.wrapFragment(buildGroup$1(group.below, newOptions, options), options);
      lowerGroup.classes.push(arrowPrefix + "-arrow-pad");
    }
    var arrowBody = stretchy.svgSpan(group, options);
    var arrowShift = -options.fontMetrics().axisHeight + 0.5 * arrowBody.height;
    var upperShift = -options.fontMetrics().axisHeight - 0.5 * arrowBody.height - 0.111;
    if (upperGroup.depth > 0.25 || group.label === "\\xleftequilibrium") {
      upperShift -= upperGroup.depth;
    }
    var vlist;
    if (lowerGroup) {
      var lowerShift = -options.fontMetrics().axisHeight + lowerGroup.height + 0.5 * arrowBody.height + 0.111;
      vlist = buildCommon.makeVList({
        positionType: "individualShift",
        children: [{
          type: "elem",
          elem: upperGroup,
          shift: upperShift
        }, {
          type: "elem",
          elem: arrowBody,
          shift: arrowShift
        }, {
          type: "elem",
          elem: lowerGroup,
          shift: lowerShift
        }]
      }, options);
    } else {
      vlist = buildCommon.makeVList({
        positionType: "individualShift",
        children: [{
          type: "elem",
          elem: upperGroup,
          shift: upperShift
        }, {
          type: "elem",
          elem: arrowBody,
          shift: arrowShift
        }]
      }, options);
    }
    vlist.children[0].children[0].children[1].classes.push("svg-align");
    return buildCommon.makeSpan(["mrel", "x-arrow"], [vlist], options);
  },
  mathmlBuilder(group, options) {
    var arrowNode = stretchy.mathMLnode(group.label);
    arrowNode.setAttribute("minsize", group.label.charAt(0) === "x" ? "1.75em" : "3.0em");
    var node;
    if (group.body) {
      var upperNode = paddedNode(buildGroup2(group.body, options));
      if (group.below) {
        var lowerNode = paddedNode(buildGroup2(group.below, options));
        node = new mathMLTree.MathNode("munderover", [arrowNode, lowerNode, upperNode]);
      } else {
        node = new mathMLTree.MathNode("mover", [arrowNode, upperNode]);
      }
    } else if (group.below) {
      var _lowerNode = paddedNode(buildGroup2(group.below, options));
      node = new mathMLTree.MathNode("munder", [arrowNode, _lowerNode]);
    } else {
      node = paddedNode();
      node = new mathMLTree.MathNode("mover", [arrowNode, node]);
    }
    return node;
  }
});
var makeSpan2 = buildCommon.makeSpan;
function htmlBuilder$9(group, options) {
  var elements = buildExpression$1(group.body, options, true);
  return makeSpan2([group.mclass], elements, options);
}
function mathmlBuilder$8(group, options) {
  var node;
  var inner2 = buildExpression2(group.body, options);
  if (group.mclass === "minner") {
    node = new mathMLTree.MathNode("mpadded", inner2);
  } else if (group.mclass === "mord") {
    if (group.isCharacterBox) {
      node = inner2[0];
      node.type = "mi";
    } else {
      node = new mathMLTree.MathNode("mi", inner2);
    }
  } else {
    if (group.isCharacterBox) {
      node = inner2[0];
      node.type = "mo";
    } else {
      node = new mathMLTree.MathNode("mo", inner2);
    }
    if (group.mclass === "mbin") {
      node.attributes.lspace = "0.22em";
      node.attributes.rspace = "0.22em";
    } else if (group.mclass === "mpunct") {
      node.attributes.lspace = "0em";
      node.attributes.rspace = "0.17em";
    } else if (group.mclass === "mopen" || group.mclass === "mclose") {
      node.attributes.lspace = "0em";
      node.attributes.rspace = "0em";
    } else if (group.mclass === "minner") {
      node.attributes.lspace = "0.0556em";
      node.attributes.width = "+0.1111em";
    }
  }
  return node;
}
defineFunction({
  type: "mclass",
  names: ["\\mathord", "\\mathbin", "\\mathrel", "\\mathopen", "\\mathclose", "\\mathpunct", "\\mathinner"],
  props: {
    numArgs: 1,
    primitive: true
  },
  handler(_ref, args) {
    var {
      parser,
      funcName
    } = _ref;
    var body = args[0];
    return {
      type: "mclass",
      mode: parser.mode,
      mclass: "m" + funcName.slice(5),
      // TODO(kevinb): don't prefix with 'm'
      body: ordargument(body),
      isCharacterBox: utils2.isCharacterBox(body)
    };
  },
  htmlBuilder: htmlBuilder$9,
  mathmlBuilder: mathmlBuilder$8
});
var binrelClass = (arg) => {
  var atom = arg.type === "ordgroup" && arg.body.length ? arg.body[0] : arg;
  if (atom.type === "atom" && (atom.family === "bin" || atom.family === "rel")) {
    return "m" + atom.family;
  } else {
    return "mord";
  }
};
defineFunction({
  type: "mclass",
  names: ["\\@binrel"],
  props: {
    numArgs: 2
  },
  handler(_ref2, args) {
    var {
      parser
    } = _ref2;
    return {
      type: "mclass",
      mode: parser.mode,
      mclass: binrelClass(args[0]),
      body: ordargument(args[1]),
      isCharacterBox: utils2.isCharacterBox(args[1])
    };
  }
});
defineFunction({
  type: "mclass",
  names: ["\\stackrel", "\\overset", "\\underset"],
  props: {
    numArgs: 2
  },
  handler(_ref3, args) {
    var {
      parser,
      funcName
    } = _ref3;
    var baseArg = args[1];
    var shiftedArg = args[0];
    var mclass;
    if (funcName !== "\\stackrel") {
      mclass = binrelClass(baseArg);
    } else {
      mclass = "mrel";
    }
    var baseOp = {
      type: "op",
      mode: baseArg.mode,
      limits: true,
      alwaysHandleSupSub: true,
      parentIsSupSub: false,
      symbol: false,
      suppressBaseShift: funcName !== "\\stackrel",
      body: ordargument(baseArg)
    };
    var supsub = {
      type: "supsub",
      mode: shiftedArg.mode,
      base: baseOp,
      sup: funcName === "\\underset" ? null : shiftedArg,
      sub: funcName === "\\underset" ? shiftedArg : null
    };
    return {
      type: "mclass",
      mode: parser.mode,
      mclass,
      body: [supsub],
      isCharacterBox: utils2.isCharacterBox(supsub)
    };
  },
  htmlBuilder: htmlBuilder$9,
  mathmlBuilder: mathmlBuilder$8
});
defineFunction({
  type: "pmb",
  names: ["\\pmb"],
  props: {
    numArgs: 1,
    allowedInText: true
  },
  handler(_ref, args) {
    var {
      parser
    } = _ref;
    return {
      type: "pmb",
      mode: parser.mode,
      mclass: binrelClass(args[0]),
      body: ordargument(args[0])
    };
  },
  htmlBuilder(group, options) {
    var elements = buildExpression$1(group.body, options, true);
    var node = buildCommon.makeSpan([group.mclass], elements, options);
    node.style.textShadow = "0.02em 0.01em 0.04px";
    return node;
  },
  mathmlBuilder(group, style) {
    var inner2 = buildExpression2(group.body, style);
    var node = new mathMLTree.MathNode("mstyle", inner2);
    node.setAttribute("style", "text-shadow: 0.02em 0.01em 0.04px");
    return node;
  }
});
var cdArrowFunctionName = {
  ">": "\\\\cdrightarrow",
  "<": "\\\\cdleftarrow",
  "=": "\\\\cdlongequal",
  "A": "\\uparrow",
  "V": "\\downarrow",
  "|": "\\Vert",
  ".": "no arrow"
};
var newCell = () => {
  return {
    type: "styling",
    body: [],
    mode: "math",
    style: "display"
  };
};
var isStartOfArrow = (node) => {
  return node.type === "textord" && node.text === "@";
};
var isLabelEnd = (node, endChar) => {
  return (node.type === "mathord" || node.type === "atom") && node.text === endChar;
};
function cdArrow(arrowChar, labels, parser) {
  var funcName = cdArrowFunctionName[arrowChar];
  switch (funcName) {
    case "\\\\cdrightarrow":
    case "\\\\cdleftarrow":
      return parser.callFunction(funcName, [labels[0]], [labels[1]]);
    case "\\uparrow":
    case "\\downarrow": {
      var leftLabel = parser.callFunction("\\\\cdleft", [labels[0]], []);
      var bareArrow = {
        type: "atom",
        text: funcName,
        mode: "math",
        family: "rel"
      };
      var sizedArrow = parser.callFunction("\\Big", [bareArrow], []);
      var rightLabel = parser.callFunction("\\\\cdright", [labels[1]], []);
      var arrowGroup = {
        type: "ordgroup",
        mode: "math",
        body: [leftLabel, sizedArrow, rightLabel]
      };
      return parser.callFunction("\\\\cdparent", [arrowGroup], []);
    }
    case "\\\\cdlongequal":
      return parser.callFunction("\\\\cdlongequal", [], []);
    case "\\Vert": {
      var arrow = {
        type: "textord",
        text: "\\Vert",
        mode: "math"
      };
      return parser.callFunction("\\Big", [arrow], []);
    }
    default:
      return {
        type: "textord",
        text: " ",
        mode: "math"
      };
  }
}
function parseCD(parser) {
  var parsedRows = [];
  parser.gullet.beginGroup();
  parser.gullet.macros.set("\\cr", "\\\\\\relax");
  parser.gullet.beginGroup();
  while (true) {
    parsedRows.push(parser.parseExpression(false, "\\\\"));
    parser.gullet.endGroup();
    parser.gullet.beginGroup();
    var next = parser.fetch().text;
    if (next === "&" || next === "\\\\") {
      parser.consume();
    } else if (next === "\\end") {
      if (parsedRows[parsedRows.length - 1].length === 0) {
        parsedRows.pop();
      }
      break;
    } else {
      throw new ParseError("Expected \\\\ or \\cr or \\end", parser.nextToken);
    }
  }
  var row = [];
  var body = [row];
  for (var i7 = 0; i7 < parsedRows.length; i7++) {
    var rowNodes = parsedRows[i7];
    var cell = newCell();
    for (var j3 = 0; j3 < rowNodes.length; j3++) {
      if (!isStartOfArrow(rowNodes[j3])) {
        cell.body.push(rowNodes[j3]);
      } else {
        row.push(cell);
        j3 += 1;
        var arrowChar = assertSymbolNodeType(rowNodes[j3]).text;
        var labels = new Array(2);
        labels[0] = {
          type: "ordgroup",
          mode: "math",
          body: []
        };
        labels[1] = {
          type: "ordgroup",
          mode: "math",
          body: []
        };
        if ("=|.".indexOf(arrowChar) > -1) ;
        else if ("<>AV".indexOf(arrowChar) > -1) {
          for (var labelNum = 0; labelNum < 2; labelNum++) {
            var inLabel = true;
            for (var k2 = j3 + 1; k2 < rowNodes.length; k2++) {
              if (isLabelEnd(rowNodes[k2], arrowChar)) {
                inLabel = false;
                j3 = k2;
                break;
              }
              if (isStartOfArrow(rowNodes[k2])) {
                throw new ParseError("Missing a " + arrowChar + " character to complete a CD arrow.", rowNodes[k2]);
              }
              labels[labelNum].body.push(rowNodes[k2]);
            }
            if (inLabel) {
              throw new ParseError("Missing a " + arrowChar + " character to complete a CD arrow.", rowNodes[j3]);
            }
          }
        } else {
          throw new ParseError('Expected one of "<>AV=|." after @', rowNodes[j3]);
        }
        var arrow = cdArrow(arrowChar, labels, parser);
        var wrappedArrow = {
          type: "styling",
          body: [arrow],
          mode: "math",
          style: "display"
          // CD is always displaystyle.
        };
        row.push(wrappedArrow);
        cell = newCell();
      }
    }
    if (i7 % 2 === 0) {
      row.push(cell);
    } else {
      row.shift();
    }
    row = [];
    body.push(row);
  }
  parser.gullet.endGroup();
  parser.gullet.endGroup();
  var cols = new Array(body[0].length).fill({
    type: "align",
    align: "c",
    pregap: 0.25,
    // CD package sets \enskip between columns.
    postgap: 0.25
    // So pre and post each get half an \enskip, i.e. 0.25em.
  });
  return {
    type: "array",
    mode: "math",
    body,
    arraystretch: 1,
    addJot: true,
    rowGaps: [null],
    cols,
    colSeparationType: "CD",
    hLinesBeforeRow: new Array(body.length + 1).fill([])
  };
}
defineFunction({
  type: "cdlabel",
  names: ["\\\\cdleft", "\\\\cdright"],
  props: {
    numArgs: 1
  },
  handler(_ref, args) {
    var {
      parser,
      funcName
    } = _ref;
    return {
      type: "cdlabel",
      mode: parser.mode,
      side: funcName.slice(4),
      label: args[0]
    };
  },
  htmlBuilder(group, options) {
    var newOptions = options.havingStyle(options.style.sup());
    var label = buildCommon.wrapFragment(buildGroup$1(group.label, newOptions, options), options);
    label.classes.push("cd-label-" + group.side);
    label.style.bottom = makeEm(0.8 - label.depth);
    label.height = 0;
    label.depth = 0;
    return label;
  },
  mathmlBuilder(group, options) {
    var label = new mathMLTree.MathNode("mrow", [buildGroup2(group.label, options)]);
    label = new mathMLTree.MathNode("mpadded", [label]);
    label.setAttribute("width", "0");
    if (group.side === "left") {
      label.setAttribute("lspace", "-1width");
    }
    label.setAttribute("voffset", "0.7em");
    label = new mathMLTree.MathNode("mstyle", [label]);
    label.setAttribute("displaystyle", "false");
    label.setAttribute("scriptlevel", "1");
    return label;
  }
});
defineFunction({
  type: "cdlabelparent",
  names: ["\\\\cdparent"],
  props: {
    numArgs: 1
  },
  handler(_ref2, args) {
    var {
      parser
    } = _ref2;
    return {
      type: "cdlabelparent",
      mode: parser.mode,
      fragment: args[0]
    };
  },
  htmlBuilder(group, options) {
    var parent = buildCommon.wrapFragment(buildGroup$1(group.fragment, options), options);
    parent.classes.push("cd-vert-arrow");
    return parent;
  },
  mathmlBuilder(group, options) {
    return new mathMLTree.MathNode("mrow", [buildGroup2(group.fragment, options)]);
  }
});
defineFunction({
  type: "textord",
  names: ["\\@char"],
  props: {
    numArgs: 1,
    allowedInText: true
  },
  handler(_ref, args) {
    var {
      parser
    } = _ref;
    var arg = assertNodeType(args[0], "ordgroup");
    var group = arg.body;
    var number = "";
    for (var i7 = 0; i7 < group.length; i7++) {
      var node = assertNodeType(group[i7], "textord");
      number += node.text;
    }
    var code = parseInt(number);
    var text3;
    if (isNaN(code)) {
      throw new ParseError("\\@char has non-numeric argument " + number);
    } else if (code < 0 || code >= 1114111) {
      throw new ParseError("\\@char with invalid code point " + number);
    } else if (code <= 65535) {
      text3 = String.fromCharCode(code);
    } else {
      code -= 65536;
      text3 = String.fromCharCode((code >> 10) + 55296, (code & 1023) + 56320);
    }
    return {
      type: "textord",
      mode: parser.mode,
      text: text3
    };
  }
});
var htmlBuilder$8 = (group, options) => {
  var elements = buildExpression$1(group.body, options.withColor(group.color), false);
  return buildCommon.makeFragment(elements);
};
var mathmlBuilder$7 = (group, options) => {
  var inner2 = buildExpression2(group.body, options.withColor(group.color));
  var node = new mathMLTree.MathNode("mstyle", inner2);
  node.setAttribute("mathcolor", group.color);
  return node;
};
defineFunction({
  type: "color",
  names: ["\\textcolor"],
  props: {
    numArgs: 2,
    allowedInText: true,
    argTypes: ["color", "original"]
  },
  handler(_ref, args) {
    var {
      parser
    } = _ref;
    var color = assertNodeType(args[0], "color-token").color;
    var body = args[1];
    return {
      type: "color",
      mode: parser.mode,
      color,
      body: ordargument(body)
    };
  },
  htmlBuilder: htmlBuilder$8,
  mathmlBuilder: mathmlBuilder$7
});
defineFunction({
  type: "color",
  names: ["\\color"],
  props: {
    numArgs: 1,
    allowedInText: true,
    argTypes: ["color"]
  },
  handler(_ref2, args) {
    var {
      parser,
      breakOnTokenText
    } = _ref2;
    var color = assertNodeType(args[0], "color-token").color;
    parser.gullet.macros.set("\\current@color", color);
    var body = parser.parseExpression(true, breakOnTokenText);
    return {
      type: "color",
      mode: parser.mode,
      color,
      body
    };
  },
  htmlBuilder: htmlBuilder$8,
  mathmlBuilder: mathmlBuilder$7
});
defineFunction({
  type: "cr",
  names: ["\\\\"],
  props: {
    numArgs: 0,
    numOptionalArgs: 0,
    allowedInText: true
  },
  handler(_ref, args, optArgs) {
    var {
      parser
    } = _ref;
    var size = parser.gullet.future().text === "[" ? parser.parseSizeGroup(true) : null;
    var newLine = !parser.settings.displayMode || !parser.settings.useStrictBehavior("newLineInDisplayMode", "In LaTeX, \\\\ or \\newline does nothing in display mode");
    return {
      type: "cr",
      mode: parser.mode,
      newLine,
      size: size && assertNodeType(size, "size").value
    };
  },
  // The following builders are called only at the top level,
  // not within tabular/array environments.
  htmlBuilder(group, options) {
    var span = buildCommon.makeSpan(["mspace"], [], options);
    if (group.newLine) {
      span.classes.push("newline");
      if (group.size) {
        span.style.marginTop = makeEm(calculateSize(group.size, options));
      }
    }
    return span;
  },
  mathmlBuilder(group, options) {
    var node = new mathMLTree.MathNode("mspace");
    if (group.newLine) {
      node.setAttribute("linebreak", "newline");
      if (group.size) {
        node.setAttribute("height", makeEm(calculateSize(group.size, options)));
      }
    }
    return node;
  }
});
var globalMap = {
  "\\global": "\\global",
  "\\long": "\\\\globallong",
  "\\\\globallong": "\\\\globallong",
  "\\def": "\\gdef",
  "\\gdef": "\\gdef",
  "\\edef": "\\xdef",
  "\\xdef": "\\xdef",
  "\\let": "\\\\globallet",
  "\\futurelet": "\\\\globalfuture"
};
var checkControlSequence = (tok) => {
  var name = tok.text;
  if (/^(?:[\\{}$&#^_]|EOF)$/.test(name)) {
    throw new ParseError("Expected a control sequence", tok);
  }
  return name;
};
var getRHS = (parser) => {
  var tok = parser.gullet.popToken();
  if (tok.text === "=") {
    tok = parser.gullet.popToken();
    if (tok.text === " ") {
      tok = parser.gullet.popToken();
    }
  }
  return tok;
};
var letCommand = (parser, name, tok, global2) => {
  var macro = parser.gullet.macros.get(tok.text);
  if (macro == null) {
    tok.noexpand = true;
    macro = {
      tokens: [tok],
      numArgs: 0,
      // reproduce the same behavior in expansion
      unexpandable: !parser.gullet.isExpandable(tok.text)
    };
  }
  parser.gullet.macros.set(name, macro, global2);
};
defineFunction({
  type: "internal",
  names: [
    "\\global",
    "\\long",
    "\\\\globallong"
    // can’t be entered directly
  ],
  props: {
    numArgs: 0,
    allowedInText: true
  },
  handler(_ref) {
    var {
      parser,
      funcName
    } = _ref;
    parser.consumeSpaces();
    var token = parser.fetch();
    if (globalMap[token.text]) {
      if (funcName === "\\global" || funcName === "\\\\globallong") {
        token.text = globalMap[token.text];
      }
      return assertNodeType(parser.parseFunction(), "internal");
    }
    throw new ParseError("Invalid token after macro prefix", token);
  }
});
defineFunction({
  type: "internal",
  names: ["\\def", "\\gdef", "\\edef", "\\xdef"],
  props: {
    numArgs: 0,
    allowedInText: true,
    primitive: true
  },
  handler(_ref2) {
    var {
      parser,
      funcName
    } = _ref2;
    var tok = parser.gullet.popToken();
    var name = tok.text;
    if (/^(?:[\\{}$&#^_]|EOF)$/.test(name)) {
      throw new ParseError("Expected a control sequence", tok);
    }
    var numArgs = 0;
    var insert;
    var delimiters2 = [[]];
    while (parser.gullet.future().text !== "{") {
      tok = parser.gullet.popToken();
      if (tok.text === "#") {
        if (parser.gullet.future().text === "{") {
          insert = parser.gullet.future();
          delimiters2[numArgs].push("{");
          break;
        }
        tok = parser.gullet.popToken();
        if (!/^[1-9]$/.test(tok.text)) {
          throw new ParseError('Invalid argument number "' + tok.text + '"');
        }
        if (parseInt(tok.text) !== numArgs + 1) {
          throw new ParseError('Argument number "' + tok.text + '" out of order');
        }
        numArgs++;
        delimiters2.push([]);
      } else if (tok.text === "EOF") {
        throw new ParseError("Expected a macro definition");
      } else {
        delimiters2[numArgs].push(tok.text);
      }
    }
    var {
      tokens
    } = parser.gullet.consumeArg();
    if (insert) {
      tokens.unshift(insert);
    }
    if (funcName === "\\edef" || funcName === "\\xdef") {
      tokens = parser.gullet.expandTokens(tokens);
      tokens.reverse();
    }
    parser.gullet.macros.set(name, {
      tokens,
      numArgs,
      delimiters: delimiters2
    }, funcName === globalMap[funcName]);
    return {
      type: "internal",
      mode: parser.mode
    };
  }
});
defineFunction({
  type: "internal",
  names: [
    "\\let",
    "\\\\globallet"
    // can’t be entered directly
  ],
  props: {
    numArgs: 0,
    allowedInText: true,
    primitive: true
  },
  handler(_ref3) {
    var {
      parser,
      funcName
    } = _ref3;
    var name = checkControlSequence(parser.gullet.popToken());
    parser.gullet.consumeSpaces();
    var tok = getRHS(parser);
    letCommand(parser, name, tok, funcName === "\\\\globallet");
    return {
      type: "internal",
      mode: parser.mode
    };
  }
});
defineFunction({
  type: "internal",
  names: [
    "\\futurelet",
    "\\\\globalfuture"
    // can’t be entered directly
  ],
  props: {
    numArgs: 0,
    allowedInText: true,
    primitive: true
  },
  handler(_ref4) {
    var {
      parser,
      funcName
    } = _ref4;
    var name = checkControlSequence(parser.gullet.popToken());
    var middle = parser.gullet.popToken();
    var tok = parser.gullet.popToken();
    letCommand(parser, name, tok, funcName === "\\\\globalfuture");
    parser.gullet.pushToken(tok);
    parser.gullet.pushToken(middle);
    return {
      type: "internal",
      mode: parser.mode
    };
  }
});
var getMetrics = function getMetrics2(symbol, font, mode) {
  var replace = symbols.math[symbol] && symbols.math[symbol].replace;
  var metrics = getCharacterMetrics(replace || symbol, font, mode);
  if (!metrics) {
    throw new Error("Unsupported symbol " + symbol + " and font size " + font + ".");
  }
  return metrics;
};
var styleWrap = function styleWrap2(delim, toStyle, options, classes) {
  var newOptions = options.havingBaseStyle(toStyle);
  var span = buildCommon.makeSpan(classes.concat(newOptions.sizingClasses(options)), [delim], options);
  var delimSizeMultiplier = newOptions.sizeMultiplier / options.sizeMultiplier;
  span.height *= delimSizeMultiplier;
  span.depth *= delimSizeMultiplier;
  span.maxFontSize = newOptions.sizeMultiplier;
  return span;
};
var centerSpan = function centerSpan2(span, options, style) {
  var newOptions = options.havingBaseStyle(style);
  var shift = (1 - options.sizeMultiplier / newOptions.sizeMultiplier) * options.fontMetrics().axisHeight;
  span.classes.push("delimcenter");
  span.style.top = makeEm(shift);
  span.height -= shift;
  span.depth += shift;
};
var makeSmallDelim = function makeSmallDelim2(delim, style, center, options, mode, classes) {
  var text3 = buildCommon.makeSymbol(delim, "Main-Regular", mode, options);
  var span = styleWrap(text3, style, options, classes);
  if (center) {
    centerSpan(span, options, style);
  }
  return span;
};
var mathrmSize = function mathrmSize2(value, size, mode, options) {
  return buildCommon.makeSymbol(value, "Size" + size + "-Regular", mode, options);
};
var makeLargeDelim = function makeLargeDelim2(delim, size, center, options, mode, classes) {
  var inner2 = mathrmSize(delim, size, mode, options);
  var span = styleWrap(buildCommon.makeSpan(["delimsizing", "size" + size], [inner2], options), Style$1.TEXT, options, classes);
  if (center) {
    centerSpan(span, options, Style$1.TEXT);
  }
  return span;
};
var makeGlyphSpan = function makeGlyphSpan2(symbol, font, mode) {
  var sizeClass;
  if (font === "Size1-Regular") {
    sizeClass = "delim-size1";
  } else {
    sizeClass = "delim-size4";
  }
  var corner = buildCommon.makeSpan(["delimsizinginner", sizeClass], [buildCommon.makeSpan([], [buildCommon.makeSymbol(symbol, font, mode)])]);
  return {
    type: "elem",
    elem: corner
  };
};
var makeInner = function makeInner2(ch, height, options) {
  var width = fontMetricsData["Size4-Regular"][ch.charCodeAt(0)] ? fontMetricsData["Size4-Regular"][ch.charCodeAt(0)][4] : fontMetricsData["Size1-Regular"][ch.charCodeAt(0)][4];
  var path6 = new PathNode("inner", innerPath(ch, Math.round(1e3 * height)));
  var svgNode = new SvgNode([path6], {
    "width": makeEm(width),
    "height": makeEm(height),
    // Override CSS rule `.katex svg { width: 100% }`
    "style": "width:" + makeEm(width),
    "viewBox": "0 0 " + 1e3 * width + " " + Math.round(1e3 * height),
    "preserveAspectRatio": "xMinYMin"
  });
  var span = buildCommon.makeSvgSpan([], [svgNode], options);
  span.height = height;
  span.style.height = makeEm(height);
  span.style.width = makeEm(width);
  return {
    type: "elem",
    elem: span
  };
};
var lapInEms = 8e-3;
var lap = {
  type: "kern",
  size: -1 * lapInEms
};
var verts = ["|", "\\lvert", "\\rvert", "\\vert"];
var doubleVerts = ["\\|", "\\lVert", "\\rVert", "\\Vert"];
var makeStackedDelim = function makeStackedDelim2(delim, heightTotal, center, options, mode, classes) {
  var top;
  var middle;
  var repeat;
  var bottom;
  var svgLabel = "";
  var viewBoxWidth = 0;
  top = repeat = bottom = delim;
  middle = null;
  var font = "Size1-Regular";
  if (delim === "\\uparrow") {
    repeat = bottom = "\u23D0";
  } else if (delim === "\\Uparrow") {
    repeat = bottom = "\u2016";
  } else if (delim === "\\downarrow") {
    top = repeat = "\u23D0";
  } else if (delim === "\\Downarrow") {
    top = repeat = "\u2016";
  } else if (delim === "\\updownarrow") {
    top = "\\uparrow";
    repeat = "\u23D0";
    bottom = "\\downarrow";
  } else if (delim === "\\Updownarrow") {
    top = "\\Uparrow";
    repeat = "\u2016";
    bottom = "\\Downarrow";
  } else if (utils2.contains(verts, delim)) {
    repeat = "\u2223";
    svgLabel = "vert";
    viewBoxWidth = 333;
  } else if (utils2.contains(doubleVerts, delim)) {
    repeat = "\u2225";
    svgLabel = "doublevert";
    viewBoxWidth = 556;
  } else if (delim === "[" || delim === "\\lbrack") {
    top = "\u23A1";
    repeat = "\u23A2";
    bottom = "\u23A3";
    font = "Size4-Regular";
    svgLabel = "lbrack";
    viewBoxWidth = 667;
  } else if (delim === "]" || delim === "\\rbrack") {
    top = "\u23A4";
    repeat = "\u23A5";
    bottom = "\u23A6";
    font = "Size4-Regular";
    svgLabel = "rbrack";
    viewBoxWidth = 667;
  } else if (delim === "\\lfloor" || delim === "\u230A") {
    repeat = top = "\u23A2";
    bottom = "\u23A3";
    font = "Size4-Regular";
    svgLabel = "lfloor";
    viewBoxWidth = 667;
  } else if (delim === "\\lceil" || delim === "\u2308") {
    top = "\u23A1";
    repeat = bottom = "\u23A2";
    font = "Size4-Regular";
    svgLabel = "lceil";
    viewBoxWidth = 667;
  } else if (delim === "\\rfloor" || delim === "\u230B") {
    repeat = top = "\u23A5";
    bottom = "\u23A6";
    font = "Size4-Regular";
    svgLabel = "rfloor";
    viewBoxWidth = 667;
  } else if (delim === "\\rceil" || delim === "\u2309") {
    top = "\u23A4";
    repeat = bottom = "\u23A5";
    font = "Size4-Regular";
    svgLabel = "rceil";
    viewBoxWidth = 667;
  } else if (delim === "(" || delim === "\\lparen") {
    top = "\u239B";
    repeat = "\u239C";
    bottom = "\u239D";
    font = "Size4-Regular";
    svgLabel = "lparen";
    viewBoxWidth = 875;
  } else if (delim === ")" || delim === "\\rparen") {
    top = "\u239E";
    repeat = "\u239F";
    bottom = "\u23A0";
    font = "Size4-Regular";
    svgLabel = "rparen";
    viewBoxWidth = 875;
  } else if (delim === "\\{" || delim === "\\lbrace") {
    top = "\u23A7";
    middle = "\u23A8";
    bottom = "\u23A9";
    repeat = "\u23AA";
    font = "Size4-Regular";
  } else if (delim === "\\}" || delim === "\\rbrace") {
    top = "\u23AB";
    middle = "\u23AC";
    bottom = "\u23AD";
    repeat = "\u23AA";
    font = "Size4-Regular";
  } else if (delim === "\\lgroup" || delim === "\u27EE") {
    top = "\u23A7";
    bottom = "\u23A9";
    repeat = "\u23AA";
    font = "Size4-Regular";
  } else if (delim === "\\rgroup" || delim === "\u27EF") {
    top = "\u23AB";
    bottom = "\u23AD";
    repeat = "\u23AA";
    font = "Size4-Regular";
  } else if (delim === "\\lmoustache" || delim === "\u23B0") {
    top = "\u23A7";
    bottom = "\u23AD";
    repeat = "\u23AA";
    font = "Size4-Regular";
  } else if (delim === "\\rmoustache" || delim === "\u23B1") {
    top = "\u23AB";
    bottom = "\u23A9";
    repeat = "\u23AA";
    font = "Size4-Regular";
  }
  var topMetrics = getMetrics(top, font, mode);
  var topHeightTotal = topMetrics.height + topMetrics.depth;
  var repeatMetrics = getMetrics(repeat, font, mode);
  var repeatHeightTotal = repeatMetrics.height + repeatMetrics.depth;
  var bottomMetrics = getMetrics(bottom, font, mode);
  var bottomHeightTotal = bottomMetrics.height + bottomMetrics.depth;
  var middleHeightTotal = 0;
  var middleFactor = 1;
  if (middle !== null) {
    var middleMetrics = getMetrics(middle, font, mode);
    middleHeightTotal = middleMetrics.height + middleMetrics.depth;
    middleFactor = 2;
  }
  var minHeight = topHeightTotal + bottomHeightTotal + middleHeightTotal;
  var repeatCount = Math.max(0, Math.ceil((heightTotal - minHeight) / (middleFactor * repeatHeightTotal)));
  var realHeightTotal = minHeight + repeatCount * middleFactor * repeatHeightTotal;
  var axisHeight = options.fontMetrics().axisHeight;
  if (center) {
    axisHeight *= options.sizeMultiplier;
  }
  var depth = realHeightTotal / 2 - axisHeight;
  var stack = [];
  if (svgLabel.length > 0) {
    var midHeight = realHeightTotal - topHeightTotal - bottomHeightTotal;
    var viewBoxHeight = Math.round(realHeightTotal * 1e3);
    var pathStr = tallDelim(svgLabel, Math.round(midHeight * 1e3));
    var path6 = new PathNode(svgLabel, pathStr);
    var width = (viewBoxWidth / 1e3).toFixed(3) + "em";
    var height = (viewBoxHeight / 1e3).toFixed(3) + "em";
    var svg = new SvgNode([path6], {
      "width": width,
      "height": height,
      "viewBox": "0 0 " + viewBoxWidth + " " + viewBoxHeight
    });
    var wrapper = buildCommon.makeSvgSpan([], [svg], options);
    wrapper.height = viewBoxHeight / 1e3;
    wrapper.style.width = width;
    wrapper.style.height = height;
    stack.push({
      type: "elem",
      elem: wrapper
    });
  } else {
    stack.push(makeGlyphSpan(bottom, font, mode));
    stack.push(lap);
    if (middle === null) {
      var innerHeight = realHeightTotal - topHeightTotal - bottomHeightTotal + 2 * lapInEms;
      stack.push(makeInner(repeat, innerHeight, options));
    } else {
      var _innerHeight = (realHeightTotal - topHeightTotal - bottomHeightTotal - middleHeightTotal) / 2 + 2 * lapInEms;
      stack.push(makeInner(repeat, _innerHeight, options));
      stack.push(lap);
      stack.push(makeGlyphSpan(middle, font, mode));
      stack.push(lap);
      stack.push(makeInner(repeat, _innerHeight, options));
    }
    stack.push(lap);
    stack.push(makeGlyphSpan(top, font, mode));
  }
  var newOptions = options.havingBaseStyle(Style$1.TEXT);
  var inner2 = buildCommon.makeVList({
    positionType: "bottom",
    positionData: depth,
    children: stack
  }, newOptions);
  return styleWrap(buildCommon.makeSpan(["delimsizing", "mult"], [inner2], newOptions), Style$1.TEXT, options, classes);
};
var vbPad = 80;
var emPad = 0.08;
var sqrtSvg = function sqrtSvg2(sqrtName, height, viewBoxHeight, extraVinculum, options) {
  var path6 = sqrtPath(sqrtName, extraVinculum, viewBoxHeight);
  var pathNode = new PathNode(sqrtName, path6);
  var svg = new SvgNode([pathNode], {
    // Note: 1000:1 ratio of viewBox to document em width.
    "width": "400em",
    "height": makeEm(height),
    "viewBox": "0 0 400000 " + viewBoxHeight,
    "preserveAspectRatio": "xMinYMin slice"
  });
  return buildCommon.makeSvgSpan(["hide-tail"], [svg], options);
};
var makeSqrtImage = function makeSqrtImage2(height, options) {
  var newOptions = options.havingBaseSizing();
  var delim = traverseSequence("\\surd", height * newOptions.sizeMultiplier, stackLargeDelimiterSequence, newOptions);
  var sizeMultiplier = newOptions.sizeMultiplier;
  var extraVinculum = Math.max(0, options.minRuleThickness - options.fontMetrics().sqrtRuleThickness);
  var span;
  var spanHeight = 0;
  var texHeight = 0;
  var viewBoxHeight = 0;
  var advanceWidth;
  if (delim.type === "small") {
    viewBoxHeight = 1e3 + 1e3 * extraVinculum + vbPad;
    if (height < 1) {
      sizeMultiplier = 1;
    } else if (height < 1.4) {
      sizeMultiplier = 0.7;
    }
    spanHeight = (1 + extraVinculum + emPad) / sizeMultiplier;
    texHeight = (1 + extraVinculum) / sizeMultiplier;
    span = sqrtSvg("sqrtMain", spanHeight, viewBoxHeight, extraVinculum, options);
    span.style.minWidth = "0.853em";
    advanceWidth = 0.833 / sizeMultiplier;
  } else if (delim.type === "large") {
    viewBoxHeight = (1e3 + vbPad) * sizeToMaxHeight[delim.size];
    texHeight = (sizeToMaxHeight[delim.size] + extraVinculum) / sizeMultiplier;
    spanHeight = (sizeToMaxHeight[delim.size] + extraVinculum + emPad) / sizeMultiplier;
    span = sqrtSvg("sqrtSize" + delim.size, spanHeight, viewBoxHeight, extraVinculum, options);
    span.style.minWidth = "1.02em";
    advanceWidth = 1 / sizeMultiplier;
  } else {
    spanHeight = height + extraVinculum + emPad;
    texHeight = height + extraVinculum;
    viewBoxHeight = Math.floor(1e3 * height + extraVinculum) + vbPad;
    span = sqrtSvg("sqrtTall", spanHeight, viewBoxHeight, extraVinculum, options);
    span.style.minWidth = "0.742em";
    advanceWidth = 1.056;
  }
  span.height = texHeight;
  span.style.height = makeEm(spanHeight);
  return {
    span,
    advanceWidth,
    // Calculate the actual line width.
    // This actually should depend on the chosen font -- e.g. \boldmath
    // should use the thicker surd symbols from e.g. KaTeX_Main-Bold, and
    // have thicker rules.
    ruleWidth: (options.fontMetrics().sqrtRuleThickness + extraVinculum) * sizeMultiplier
  };
};
var stackLargeDelimiters = ["(", "\\lparen", ")", "\\rparen", "[", "\\lbrack", "]", "\\rbrack", "\\{", "\\lbrace", "\\}", "\\rbrace", "\\lfloor", "\\rfloor", "\u230A", "\u230B", "\\lceil", "\\rceil", "\u2308", "\u2309", "\\surd"];
var stackAlwaysDelimiters = ["\\uparrow", "\\downarrow", "\\updownarrow", "\\Uparrow", "\\Downarrow", "\\Updownarrow", "|", "\\|", "\\vert", "\\Vert", "\\lvert", "\\rvert", "\\lVert", "\\rVert", "\\lgroup", "\\rgroup", "\u27EE", "\u27EF", "\\lmoustache", "\\rmoustache", "\u23B0", "\u23B1"];
var stackNeverDelimiters = ["<", ">", "\\langle", "\\rangle", "/", "\\backslash", "\\lt", "\\gt"];
var sizeToMaxHeight = [0, 1.2, 1.8, 2.4, 3];
var makeSizedDelim = function makeSizedDelim2(delim, size, options, mode, classes) {
  if (delim === "<" || delim === "\\lt" || delim === "\u27E8") {
    delim = "\\langle";
  } else if (delim === ">" || delim === "\\gt" || delim === "\u27E9") {
    delim = "\\rangle";
  }
  if (utils2.contains(stackLargeDelimiters, delim) || utils2.contains(stackNeverDelimiters, delim)) {
    return makeLargeDelim(delim, size, false, options, mode, classes);
  } else if (utils2.contains(stackAlwaysDelimiters, delim)) {
    return makeStackedDelim(delim, sizeToMaxHeight[size], false, options, mode, classes);
  } else {
    throw new ParseError("Illegal delimiter: '" + delim + "'");
  }
};
var stackNeverDelimiterSequence = [{
  type: "small",
  style: Style$1.SCRIPTSCRIPT
}, {
  type: "small",
  style: Style$1.SCRIPT
}, {
  type: "small",
  style: Style$1.TEXT
}, {
  type: "large",
  size: 1
}, {
  type: "large",
  size: 2
}, {
  type: "large",
  size: 3
}, {
  type: "large",
  size: 4
}];
var stackAlwaysDelimiterSequence = [{
  type: "small",
  style: Style$1.SCRIPTSCRIPT
}, {
  type: "small",
  style: Style$1.SCRIPT
}, {
  type: "small",
  style: Style$1.TEXT
}, {
  type: "stack"
}];
var stackLargeDelimiterSequence = [{
  type: "small",
  style: Style$1.SCRIPTSCRIPT
}, {
  type: "small",
  style: Style$1.SCRIPT
}, {
  type: "small",
  style: Style$1.TEXT
}, {
  type: "large",
  size: 1
}, {
  type: "large",
  size: 2
}, {
  type: "large",
  size: 3
}, {
  type: "large",
  size: 4
}, {
  type: "stack"
}];
var delimTypeToFont = function delimTypeToFont2(type) {
  if (type.type === "small") {
    return "Main-Regular";
  } else if (type.type === "large") {
    return "Size" + type.size + "-Regular";
  } else if (type.type === "stack") {
    return "Size4-Regular";
  } else {
    throw new Error("Add support for delim type '" + type.type + "' here.");
  }
};
var traverseSequence = function traverseSequence2(delim, height, sequence, options) {
  var start = Math.min(2, 3 - options.style.size);
  for (var i7 = start; i7 < sequence.length; i7++) {
    if (sequence[i7].type === "stack") {
      break;
    }
    var metrics = getMetrics(delim, delimTypeToFont(sequence[i7]), "math");
    var heightDepth = metrics.height + metrics.depth;
    if (sequence[i7].type === "small") {
      var newOptions = options.havingBaseStyle(sequence[i7].style);
      heightDepth *= newOptions.sizeMultiplier;
    }
    if (heightDepth > height) {
      return sequence[i7];
    }
  }
  return sequence[sequence.length - 1];
};
var makeCustomSizedDelim = function makeCustomSizedDelim2(delim, height, center, options, mode, classes) {
  if (delim === "<" || delim === "\\lt" || delim === "\u27E8") {
    delim = "\\langle";
  } else if (delim === ">" || delim === "\\gt" || delim === "\u27E9") {
    delim = "\\rangle";
  }
  var sequence;
  if (utils2.contains(stackNeverDelimiters, delim)) {
    sequence = stackNeverDelimiterSequence;
  } else if (utils2.contains(stackLargeDelimiters, delim)) {
    sequence = stackLargeDelimiterSequence;
  } else {
    sequence = stackAlwaysDelimiterSequence;
  }
  var delimType = traverseSequence(delim, height, sequence, options);
  if (delimType.type === "small") {
    return makeSmallDelim(delim, delimType.style, center, options, mode, classes);
  } else if (delimType.type === "large") {
    return makeLargeDelim(delim, delimType.size, center, options, mode, classes);
  } else {
    return makeStackedDelim(delim, height, center, options, mode, classes);
  }
};
var makeLeftRightDelim = function makeLeftRightDelim2(delim, height, depth, options, mode, classes) {
  var axisHeight = options.fontMetrics().axisHeight * options.sizeMultiplier;
  var delimiterFactor = 901;
  var delimiterExtend = 5 / options.fontMetrics().ptPerEm;
  var maxDistFromAxis = Math.max(height - axisHeight, depth + axisHeight);
  var totalHeight = Math.max(
    // In real TeX, calculations are done using integral values which are
    // 65536 per pt, or 655360 per em. So, the division here truncates in
    // TeX but doesn't here, producing different results. If we wanted to
    // exactly match TeX's calculation, we could do
    //   Math.floor(655360 * maxDistFromAxis / 500) *
    //    delimiterFactor / 655360
    // (To see the difference, compare
    //    x^{x^{\left(\rule{0.1em}{0.68em}\right)}}
    // in TeX and KaTeX)
    maxDistFromAxis / 500 * delimiterFactor,
    2 * maxDistFromAxis - delimiterExtend
  );
  return makeCustomSizedDelim(delim, totalHeight, true, options, mode, classes);
};
var delimiter = {
  sqrtImage: makeSqrtImage,
  sizedDelim: makeSizedDelim,
  sizeToMaxHeight,
  customSizedDelim: makeCustomSizedDelim,
  leftRightDelim: makeLeftRightDelim
};
var delimiterSizes = {
  "\\bigl": {
    mclass: "mopen",
    size: 1
  },
  "\\Bigl": {
    mclass: "mopen",
    size: 2
  },
  "\\biggl": {
    mclass: "mopen",
    size: 3
  },
  "\\Biggl": {
    mclass: "mopen",
    size: 4
  },
  "\\bigr": {
    mclass: "mclose",
    size: 1
  },
  "\\Bigr": {
    mclass: "mclose",
    size: 2
  },
  "\\biggr": {
    mclass: "mclose",
    size: 3
  },
  "\\Biggr": {
    mclass: "mclose",
    size: 4
  },
  "\\bigm": {
    mclass: "mrel",
    size: 1
  },
  "\\Bigm": {
    mclass: "mrel",
    size: 2
  },
  "\\biggm": {
    mclass: "mrel",
    size: 3
  },
  "\\Biggm": {
    mclass: "mrel",
    size: 4
  },
  "\\big": {
    mclass: "mord",
    size: 1
  },
  "\\Big": {
    mclass: "mord",
    size: 2
  },
  "\\bigg": {
    mclass: "mord",
    size: 3
  },
  "\\Bigg": {
    mclass: "mord",
    size: 4
  }
};
var delimiters = ["(", "\\lparen", ")", "\\rparen", "[", "\\lbrack", "]", "\\rbrack", "\\{", "\\lbrace", "\\}", "\\rbrace", "\\lfloor", "\\rfloor", "\u230A", "\u230B", "\\lceil", "\\rceil", "\u2308", "\u2309", "<", ">", "\\langle", "\u27E8", "\\rangle", "\u27E9", "\\lt", "\\gt", "\\lvert", "\\rvert", "\\lVert", "\\rVert", "\\lgroup", "\\rgroup", "\u27EE", "\u27EF", "\\lmoustache", "\\rmoustache", "\u23B0", "\u23B1", "/", "\\backslash", "|", "\\vert", "\\|", "\\Vert", "\\uparrow", "\\Uparrow", "\\downarrow", "\\Downarrow", "\\updownarrow", "\\Updownarrow", "."];
function checkDelimiter(delim, context) {
  var symDelim = checkSymbolNodeType(delim);
  if (symDelim && utils2.contains(delimiters, symDelim.text)) {
    return symDelim;
  } else if (symDelim) {
    throw new ParseError("Invalid delimiter '" + symDelim.text + "' after '" + context.funcName + "'", delim);
  } else {
    throw new ParseError("Invalid delimiter type '" + delim.type + "'", delim);
  }
}
defineFunction({
  type: "delimsizing",
  names: ["\\bigl", "\\Bigl", "\\biggl", "\\Biggl", "\\bigr", "\\Bigr", "\\biggr", "\\Biggr", "\\bigm", "\\Bigm", "\\biggm", "\\Biggm", "\\big", "\\Big", "\\bigg", "\\Bigg"],
  props: {
    numArgs: 1,
    argTypes: ["primitive"]
  },
  handler: (context, args) => {
    var delim = checkDelimiter(args[0], context);
    return {
      type: "delimsizing",
      mode: context.parser.mode,
      size: delimiterSizes[context.funcName].size,
      mclass: delimiterSizes[context.funcName].mclass,
      delim: delim.text
    };
  },
  htmlBuilder: (group, options) => {
    if (group.delim === ".") {
      return buildCommon.makeSpan([group.mclass]);
    }
    return delimiter.sizedDelim(group.delim, group.size, options, group.mode, [group.mclass]);
  },
  mathmlBuilder: (group) => {
    var children = [];
    if (group.delim !== ".") {
      children.push(makeText(group.delim, group.mode));
    }
    var node = new mathMLTree.MathNode("mo", children);
    if (group.mclass === "mopen" || group.mclass === "mclose") {
      node.setAttribute("fence", "true");
    } else {
      node.setAttribute("fence", "false");
    }
    node.setAttribute("stretchy", "true");
    var size = makeEm(delimiter.sizeToMaxHeight[group.size]);
    node.setAttribute("minsize", size);
    node.setAttribute("maxsize", size);
    return node;
  }
});
function assertParsed(group) {
  if (!group.body) {
    throw new Error("Bug: The leftright ParseNode wasn't fully parsed.");
  }
}
defineFunction({
  type: "leftright-right",
  names: ["\\right"],
  props: {
    numArgs: 1,
    primitive: true
  },
  handler: (context, args) => {
    var color = context.parser.gullet.macros.get("\\current@color");
    if (color && typeof color !== "string") {
      throw new ParseError("\\current@color set to non-string in \\right");
    }
    return {
      type: "leftright-right",
      mode: context.parser.mode,
      delim: checkDelimiter(args[0], context).text,
      color
      // undefined if not set via \color
    };
  }
});
defineFunction({
  type: "leftright",
  names: ["\\left"],
  props: {
    numArgs: 1,
    primitive: true
  },
  handler: (context, args) => {
    var delim = checkDelimiter(args[0], context);
    var parser = context.parser;
    ++parser.leftrightDepth;
    var body = parser.parseExpression(false);
    --parser.leftrightDepth;
    parser.expect("\\right", false);
    var right = assertNodeType(parser.parseFunction(), "leftright-right");
    return {
      type: "leftright",
      mode: parser.mode,
      body,
      left: delim.text,
      right: right.delim,
      rightColor: right.color
    };
  },
  htmlBuilder: (group, options) => {
    assertParsed(group);
    var inner2 = buildExpression$1(group.body, options, true, ["mopen", "mclose"]);
    var innerHeight = 0;
    var innerDepth = 0;
    var hadMiddle = false;
    for (var i7 = 0; i7 < inner2.length; i7++) {
      if (inner2[i7].isMiddle) {
        hadMiddle = true;
      } else {
        innerHeight = Math.max(inner2[i7].height, innerHeight);
        innerDepth = Math.max(inner2[i7].depth, innerDepth);
      }
    }
    innerHeight *= options.sizeMultiplier;
    innerDepth *= options.sizeMultiplier;
    var leftDelim;
    if (group.left === ".") {
      leftDelim = makeNullDelimiter(options, ["mopen"]);
    } else {
      leftDelim = delimiter.leftRightDelim(group.left, innerHeight, innerDepth, options, group.mode, ["mopen"]);
    }
    inner2.unshift(leftDelim);
    if (hadMiddle) {
      for (var _i = 1; _i < inner2.length; _i++) {
        var middleDelim = inner2[_i];
        var isMiddle = middleDelim.isMiddle;
        if (isMiddle) {
          inner2[_i] = delimiter.leftRightDelim(isMiddle.delim, innerHeight, innerDepth, isMiddle.options, group.mode, []);
        }
      }
    }
    var rightDelim;
    if (group.right === ".") {
      rightDelim = makeNullDelimiter(options, ["mclose"]);
    } else {
      var colorOptions = group.rightColor ? options.withColor(group.rightColor) : options;
      rightDelim = delimiter.leftRightDelim(group.right, innerHeight, innerDepth, colorOptions, group.mode, ["mclose"]);
    }
    inner2.push(rightDelim);
    return buildCommon.makeSpan(["minner"], inner2, options);
  },
  mathmlBuilder: (group, options) => {
    assertParsed(group);
    var inner2 = buildExpression2(group.body, options);
    if (group.left !== ".") {
      var leftNode = new mathMLTree.MathNode("mo", [makeText(group.left, group.mode)]);
      leftNode.setAttribute("fence", "true");
      inner2.unshift(leftNode);
    }
    if (group.right !== ".") {
      var rightNode = new mathMLTree.MathNode("mo", [makeText(group.right, group.mode)]);
      rightNode.setAttribute("fence", "true");
      if (group.rightColor) {
        rightNode.setAttribute("mathcolor", group.rightColor);
      }
      inner2.push(rightNode);
    }
    return makeRow(inner2);
  }
});
defineFunction({
  type: "middle",
  names: ["\\middle"],
  props: {
    numArgs: 1,
    primitive: true
  },
  handler: (context, args) => {
    var delim = checkDelimiter(args[0], context);
    if (!context.parser.leftrightDepth) {
      throw new ParseError("\\middle without preceding \\left", delim);
    }
    return {
      type: "middle",
      mode: context.parser.mode,
      delim: delim.text
    };
  },
  htmlBuilder: (group, options) => {
    var middleDelim;
    if (group.delim === ".") {
      middleDelim = makeNullDelimiter(options, []);
    } else {
      middleDelim = delimiter.sizedDelim(group.delim, 1, options, group.mode, []);
      var isMiddle = {
        delim: group.delim,
        options
      };
      middleDelim.isMiddle = isMiddle;
    }
    return middleDelim;
  },
  mathmlBuilder: (group, options) => {
    var textNode = group.delim === "\\vert" || group.delim === "|" ? makeText("|", "text") : makeText(group.delim, group.mode);
    var middleNode = new mathMLTree.MathNode("mo", [textNode]);
    middleNode.setAttribute("fence", "true");
    middleNode.setAttribute("lspace", "0.05em");
    middleNode.setAttribute("rspace", "0.05em");
    return middleNode;
  }
});
var htmlBuilder$7 = (group, options) => {
  var inner2 = buildCommon.wrapFragment(buildGroup$1(group.body, options), options);
  var label = group.label.slice(1);
  var scale = options.sizeMultiplier;
  var img;
  var imgShift = 0;
  var isSingleChar = utils2.isCharacterBox(group.body);
  if (label === "sout") {
    img = buildCommon.makeSpan(["stretchy", "sout"]);
    img.height = options.fontMetrics().defaultRuleThickness / scale;
    imgShift = -0.5 * options.fontMetrics().xHeight;
  } else if (label === "phase") {
    var lineWeight = calculateSize({
      number: 0.6,
      unit: "pt"
    }, options);
    var clearance = calculateSize({
      number: 0.35,
      unit: "ex"
    }, options);
    var newOptions = options.havingBaseSizing();
    scale = scale / newOptions.sizeMultiplier;
    var angleHeight = inner2.height + inner2.depth + lineWeight + clearance;
    inner2.style.paddingLeft = makeEm(angleHeight / 2 + lineWeight);
    var viewBoxHeight = Math.floor(1e3 * angleHeight * scale);
    var path6 = phasePath(viewBoxHeight);
    var svgNode = new SvgNode([new PathNode("phase", path6)], {
      "width": "400em",
      "height": makeEm(viewBoxHeight / 1e3),
      "viewBox": "0 0 400000 " + viewBoxHeight,
      "preserveAspectRatio": "xMinYMin slice"
    });
    img = buildCommon.makeSvgSpan(["hide-tail"], [svgNode], options);
    img.style.height = makeEm(angleHeight);
    imgShift = inner2.depth + lineWeight + clearance;
  } else {
    if (/cancel/.test(label)) {
      if (!isSingleChar) {
        inner2.classes.push("cancel-pad");
      }
    } else if (label === "angl") {
      inner2.classes.push("anglpad");
    } else {
      inner2.classes.push("boxpad");
    }
    var topPad = 0;
    var bottomPad = 0;
    var ruleThickness = 0;
    if (/box/.test(label)) {
      ruleThickness = Math.max(
        options.fontMetrics().fboxrule,
        // default
        options.minRuleThickness
        // User override.
      );
      topPad = options.fontMetrics().fboxsep + (label === "colorbox" ? 0 : ruleThickness);
      bottomPad = topPad;
    } else if (label === "angl") {
      ruleThickness = Math.max(options.fontMetrics().defaultRuleThickness, options.minRuleThickness);
      topPad = 4 * ruleThickness;
      bottomPad = Math.max(0, 0.25 - inner2.depth);
    } else {
      topPad = isSingleChar ? 0.2 : 0;
      bottomPad = topPad;
    }
    img = stretchy.encloseSpan(inner2, label, topPad, bottomPad, options);
    if (/fbox|boxed|fcolorbox/.test(label)) {
      img.style.borderStyle = "solid";
      img.style.borderWidth = makeEm(ruleThickness);
    } else if (label === "angl" && ruleThickness !== 0.049) {
      img.style.borderTopWidth = makeEm(ruleThickness);
      img.style.borderRightWidth = makeEm(ruleThickness);
    }
    imgShift = inner2.depth + bottomPad;
    if (group.backgroundColor) {
      img.style.backgroundColor = group.backgroundColor;
      if (group.borderColor) {
        img.style.borderColor = group.borderColor;
      }
    }
  }
  var vlist;
  if (group.backgroundColor) {
    vlist = buildCommon.makeVList({
      positionType: "individualShift",
      children: [
        // Put the color background behind inner;
        {
          type: "elem",
          elem: img,
          shift: imgShift
        },
        {
          type: "elem",
          elem: inner2,
          shift: 0
        }
      ]
    }, options);
  } else {
    var classes = /cancel|phase/.test(label) ? ["svg-align"] : [];
    vlist = buildCommon.makeVList({
      positionType: "individualShift",
      children: [
        // Write the \cancel stroke on top of inner.
        {
          type: "elem",
          elem: inner2,
          shift: 0
        },
        {
          type: "elem",
          elem: img,
          shift: imgShift,
          wrapperClasses: classes
        }
      ]
    }, options);
  }
  if (/cancel/.test(label)) {
    vlist.height = inner2.height;
    vlist.depth = inner2.depth;
  }
  if (/cancel/.test(label) && !isSingleChar) {
    return buildCommon.makeSpan(["mord", "cancel-lap"], [vlist], options);
  } else {
    return buildCommon.makeSpan(["mord"], [vlist], options);
  }
};
var mathmlBuilder$6 = (group, options) => {
  var fboxsep = 0;
  var node = new mathMLTree.MathNode(group.label.indexOf("colorbox") > -1 ? "mpadded" : "menclose", [buildGroup2(group.body, options)]);
  switch (group.label) {
    case "\\cancel":
      node.setAttribute("notation", "updiagonalstrike");
      break;
    case "\\bcancel":
      node.setAttribute("notation", "downdiagonalstrike");
      break;
    case "\\phase":
      node.setAttribute("notation", "phasorangle");
      break;
    case "\\sout":
      node.setAttribute("notation", "horizontalstrike");
      break;
    case "\\fbox":
      node.setAttribute("notation", "box");
      break;
    case "\\angl":
      node.setAttribute("notation", "actuarial");
      break;
    case "\\fcolorbox":
    case "\\colorbox":
      fboxsep = options.fontMetrics().fboxsep * options.fontMetrics().ptPerEm;
      node.setAttribute("width", "+" + 2 * fboxsep + "pt");
      node.setAttribute("height", "+" + 2 * fboxsep + "pt");
      node.setAttribute("lspace", fboxsep + "pt");
      node.setAttribute("voffset", fboxsep + "pt");
      if (group.label === "\\fcolorbox") {
        var thk = Math.max(
          options.fontMetrics().fboxrule,
          // default
          options.minRuleThickness
          // user override
        );
        node.setAttribute("style", "border: " + thk + "em solid " + String(group.borderColor));
      }
      break;
    case "\\xcancel":
      node.setAttribute("notation", "updiagonalstrike downdiagonalstrike");
      break;
  }
  if (group.backgroundColor) {
    node.setAttribute("mathbackground", group.backgroundColor);
  }
  return node;
};
defineFunction({
  type: "enclose",
  names: ["\\colorbox"],
  props: {
    numArgs: 2,
    allowedInText: true,
    argTypes: ["color", "text"]
  },
  handler(_ref, args, optArgs) {
    var {
      parser,
      funcName
    } = _ref;
    var color = assertNodeType(args[0], "color-token").color;
    var body = args[1];
    return {
      type: "enclose",
      mode: parser.mode,
      label: funcName,
      backgroundColor: color,
      body
    };
  },
  htmlBuilder: htmlBuilder$7,
  mathmlBuilder: mathmlBuilder$6
});
defineFunction({
  type: "enclose",
  names: ["\\fcolorbox"],
  props: {
    numArgs: 3,
    allowedInText: true,
    argTypes: ["color", "color", "text"]
  },
  handler(_ref2, args, optArgs) {
    var {
      parser,
      funcName
    } = _ref2;
    var borderColor = assertNodeType(args[0], "color-token").color;
    var backgroundColor = assertNodeType(args[1], "color-token").color;
    var body = args[2];
    return {
      type: "enclose",
      mode: parser.mode,
      label: funcName,
      backgroundColor,
      borderColor,
      body
    };
  },
  htmlBuilder: htmlBuilder$7,
  mathmlBuilder: mathmlBuilder$6
});
defineFunction({
  type: "enclose",
  names: ["\\fbox"],
  props: {
    numArgs: 1,
    argTypes: ["hbox"],
    allowedInText: true
  },
  handler(_ref3, args) {
    var {
      parser
    } = _ref3;
    return {
      type: "enclose",
      mode: parser.mode,
      label: "\\fbox",
      body: args[0]
    };
  }
});
defineFunction({
  type: "enclose",
  names: ["\\cancel", "\\bcancel", "\\xcancel", "\\sout", "\\phase"],
  props: {
    numArgs: 1
  },
  handler(_ref4, args) {
    var {
      parser,
      funcName
    } = _ref4;
    var body = args[0];
    return {
      type: "enclose",
      mode: parser.mode,
      label: funcName,
      body
    };
  },
  htmlBuilder: htmlBuilder$7,
  mathmlBuilder: mathmlBuilder$6
});
defineFunction({
  type: "enclose",
  names: ["\\angl"],
  props: {
    numArgs: 1,
    argTypes: ["hbox"],
    allowedInText: false
  },
  handler(_ref5, args) {
    var {
      parser
    } = _ref5;
    return {
      type: "enclose",
      mode: parser.mode,
      label: "\\angl",
      body: args[0]
    };
  }
});
var _environments = {};
function defineEnvironment(_ref) {
  var {
    type,
    names,
    props,
    handler,
    htmlBuilder: htmlBuilder3,
    mathmlBuilder: mathmlBuilder3
  } = _ref;
  var data = {
    type,
    numArgs: props.numArgs || 0,
    allowedInText: false,
    numOptionalArgs: 0,
    handler
  };
  for (var i7 = 0; i7 < names.length; ++i7) {
    _environments[names[i7]] = data;
  }
  if (htmlBuilder3) {
    _htmlGroupBuilders[type] = htmlBuilder3;
  }
  if (mathmlBuilder3) {
    _mathmlGroupBuilders[type] = mathmlBuilder3;
  }
}
var _macros = {};
function defineMacro(name, body) {
  _macros[name] = body;
}
function getHLines(parser) {
  var hlineInfo = [];
  parser.consumeSpaces();
  var nxt = parser.fetch().text;
  if (nxt === "\\relax") {
    parser.consume();
    parser.consumeSpaces();
    nxt = parser.fetch().text;
  }
  while (nxt === "\\hline" || nxt === "\\hdashline") {
    parser.consume();
    hlineInfo.push(nxt === "\\hdashline");
    parser.consumeSpaces();
    nxt = parser.fetch().text;
  }
  return hlineInfo;
}
var validateAmsEnvironmentContext = (context) => {
  var settings = context.parser.settings;
  if (!settings.displayMode) {
    throw new ParseError("{" + context.envName + "} can be used only in display mode.");
  }
};
function getAutoTag(name) {
  if (name.indexOf("ed") === -1) {
    return name.indexOf("*") === -1;
  }
}
function parseArray(parser, _ref, style) {
  var {
    hskipBeforeAndAfter,
    addJot,
    cols,
    arraystretch,
    colSeparationType,
    autoTag,
    singleRow,
    emptySingleRow,
    maxNumCols,
    leqno
  } = _ref;
  parser.gullet.beginGroup();
  if (!singleRow) {
    parser.gullet.macros.set("\\cr", "\\\\\\relax");
  }
  if (!arraystretch) {
    var stretch = parser.gullet.expandMacroAsText("\\arraystretch");
    if (stretch == null) {
      arraystretch = 1;
    } else {
      arraystretch = parseFloat(stretch);
      if (!arraystretch || arraystretch < 0) {
        throw new ParseError("Invalid \\arraystretch: " + stretch);
      }
    }
  }
  parser.gullet.beginGroup();
  var row = [];
  var body = [row];
  var rowGaps = [];
  var hLinesBeforeRow = [];
  var tags = autoTag != null ? [] : void 0;
  function beginRow() {
    if (autoTag) {
      parser.gullet.macros.set("\\@eqnsw", "1", true);
    }
  }
  function endRow() {
    if (tags) {
      if (parser.gullet.macros.get("\\df@tag")) {
        tags.push(parser.subparse([new Token("\\df@tag")]));
        parser.gullet.macros.set("\\df@tag", void 0, true);
      } else {
        tags.push(Boolean(autoTag) && parser.gullet.macros.get("\\@eqnsw") === "1");
      }
    }
  }
  beginRow();
  hLinesBeforeRow.push(getHLines(parser));
  while (true) {
    var cell = parser.parseExpression(false, singleRow ? "\\end" : "\\\\");
    parser.gullet.endGroup();
    parser.gullet.beginGroup();
    cell = {
      type: "ordgroup",
      mode: parser.mode,
      body: cell
    };
    if (style) {
      cell = {
        type: "styling",
        mode: parser.mode,
        style,
        body: [cell]
      };
    }
    row.push(cell);
    var next = parser.fetch().text;
    if (next === "&") {
      if (maxNumCols && row.length === maxNumCols) {
        if (singleRow || colSeparationType) {
          throw new ParseError("Too many tab characters: &", parser.nextToken);
        } else {
          parser.settings.reportNonstrict("textEnv", "Too few columns specified in the {array} column argument.");
        }
      }
      parser.consume();
    } else if (next === "\\end") {
      endRow();
      if (row.length === 1 && cell.type === "styling" && cell.body[0].body.length === 0 && (body.length > 1 || !emptySingleRow)) {
        body.pop();
      }
      if (hLinesBeforeRow.length < body.length + 1) {
        hLinesBeforeRow.push([]);
      }
      break;
    } else if (next === "\\\\") {
      parser.consume();
      var size = void 0;
      if (parser.gullet.future().text !== " ") {
        size = parser.parseSizeGroup(true);
      }
      rowGaps.push(size ? size.value : null);
      endRow();
      hLinesBeforeRow.push(getHLines(parser));
      row = [];
      body.push(row);
      beginRow();
    } else {
      throw new ParseError("Expected & or \\\\ or \\cr or \\end", parser.nextToken);
    }
  }
  parser.gullet.endGroup();
  parser.gullet.endGroup();
  return {
    type: "array",
    mode: parser.mode,
    addJot,
    arraystretch,
    body,
    cols,
    rowGaps,
    hskipBeforeAndAfter,
    hLinesBeforeRow,
    colSeparationType,
    tags,
    leqno
  };
}
function dCellStyle(envName) {
  if (envName.slice(0, 1) === "d") {
    return "display";
  } else {
    return "text";
  }
}
var htmlBuilder$6 = function htmlBuilder(group, options) {
  var r8;
  var c6;
  var nr = group.body.length;
  var hLinesBeforeRow = group.hLinesBeforeRow;
  var nc = 0;
  var body = new Array(nr);
  var hlines = [];
  var ruleThickness = Math.max(
    // From LaTeX \showthe\arrayrulewidth. Equals 0.04 em.
    options.fontMetrics().arrayRuleWidth,
    options.minRuleThickness
    // User override.
  );
  var pt = 1 / options.fontMetrics().ptPerEm;
  var arraycolsep = 5 * pt;
  if (group.colSeparationType && group.colSeparationType === "small") {
    var localMultiplier = options.havingStyle(Style$1.SCRIPT).sizeMultiplier;
    arraycolsep = 0.2778 * (localMultiplier / options.sizeMultiplier);
  }
  var baselineskip = group.colSeparationType === "CD" ? calculateSize({
    number: 3,
    unit: "ex"
  }, options) : 12 * pt;
  var jot = 3 * pt;
  var arrayskip = group.arraystretch * baselineskip;
  var arstrutHeight = 0.7 * arrayskip;
  var arstrutDepth = 0.3 * arrayskip;
  var totalHeight = 0;
  function setHLinePos(hlinesInGap) {
    for (var i7 = 0; i7 < hlinesInGap.length; ++i7) {
      if (i7 > 0) {
        totalHeight += 0.25;
      }
      hlines.push({
        pos: totalHeight,
        isDashed: hlinesInGap[i7]
      });
    }
  }
  setHLinePos(hLinesBeforeRow[0]);
  for (r8 = 0; r8 < group.body.length; ++r8) {
    var inrow = group.body[r8];
    var height = arstrutHeight;
    var depth = arstrutDepth;
    if (nc < inrow.length) {
      nc = inrow.length;
    }
    var outrow = new Array(inrow.length);
    for (c6 = 0; c6 < inrow.length; ++c6) {
      var elt = buildGroup$1(inrow[c6], options);
      if (depth < elt.depth) {
        depth = elt.depth;
      }
      if (height < elt.height) {
        height = elt.height;
      }
      outrow[c6] = elt;
    }
    var rowGap = group.rowGaps[r8];
    var gap = 0;
    if (rowGap) {
      gap = calculateSize(rowGap, options);
      if (gap > 0) {
        gap += arstrutDepth;
        if (depth < gap) {
          depth = gap;
        }
        gap = 0;
      }
    }
    if (group.addJot) {
      depth += jot;
    }
    outrow.height = height;
    outrow.depth = depth;
    totalHeight += height;
    outrow.pos = totalHeight;
    totalHeight += depth + gap;
    body[r8] = outrow;
    setHLinePos(hLinesBeforeRow[r8 + 1]);
  }
  var offset = totalHeight / 2 + options.fontMetrics().axisHeight;
  var colDescriptions = group.cols || [];
  var cols = [];
  var colSep;
  var colDescrNum;
  var tagSpans = [];
  if (group.tags && group.tags.some((tag2) => tag2)) {
    for (r8 = 0; r8 < nr; ++r8) {
      var rw = body[r8];
      var shift = rw.pos - offset;
      var tag = group.tags[r8];
      var tagSpan = void 0;
      if (tag === true) {
        tagSpan = buildCommon.makeSpan(["eqn-num"], [], options);
      } else if (tag === false) {
        tagSpan = buildCommon.makeSpan([], [], options);
      } else {
        tagSpan = buildCommon.makeSpan([], buildExpression$1(tag, options, true), options);
      }
      tagSpan.depth = rw.depth;
      tagSpan.height = rw.height;
      tagSpans.push({
        type: "elem",
        elem: tagSpan,
        shift
      });
    }
  }
  for (
    c6 = 0, colDescrNum = 0;
    // Continue while either there are more columns or more column
    // descriptions, so trailing separators don't get lost.
    c6 < nc || colDescrNum < colDescriptions.length;
    ++c6, ++colDescrNum
  ) {
    var colDescr = colDescriptions[colDescrNum] || {};
    var firstSeparator = true;
    while (colDescr.type === "separator") {
      if (!firstSeparator) {
        colSep = buildCommon.makeSpan(["arraycolsep"], []);
        colSep.style.width = makeEm(options.fontMetrics().doubleRuleSep);
        cols.push(colSep);
      }
      if (colDescr.separator === "|" || colDescr.separator === ":") {
        var lineType = colDescr.separator === "|" ? "solid" : "dashed";
        var separator = buildCommon.makeSpan(["vertical-separator"], [], options);
        separator.style.height = makeEm(totalHeight);
        separator.style.borderRightWidth = makeEm(ruleThickness);
        separator.style.borderRightStyle = lineType;
        separator.style.margin = "0 " + makeEm(-ruleThickness / 2);
        var _shift = totalHeight - offset;
        if (_shift) {
          separator.style.verticalAlign = makeEm(-_shift);
        }
        cols.push(separator);
      } else {
        throw new ParseError("Invalid separator type: " + colDescr.separator);
      }
      colDescrNum++;
      colDescr = colDescriptions[colDescrNum] || {};
      firstSeparator = false;
    }
    if (c6 >= nc) {
      continue;
    }
    var sepwidth = void 0;
    if (c6 > 0 || group.hskipBeforeAndAfter) {
      sepwidth = utils2.deflt(colDescr.pregap, arraycolsep);
      if (sepwidth !== 0) {
        colSep = buildCommon.makeSpan(["arraycolsep"], []);
        colSep.style.width = makeEm(sepwidth);
        cols.push(colSep);
      }
    }
    var col = [];
    for (r8 = 0; r8 < nr; ++r8) {
      var row = body[r8];
      var elem = row[c6];
      if (!elem) {
        continue;
      }
      var _shift2 = row.pos - offset;
      elem.depth = row.depth;
      elem.height = row.height;
      col.push({
        type: "elem",
        elem,
        shift: _shift2
      });
    }
    col = buildCommon.makeVList({
      positionType: "individualShift",
      children: col
    }, options);
    col = buildCommon.makeSpan(["col-align-" + (colDescr.align || "c")], [col]);
    cols.push(col);
    if (c6 < nc - 1 || group.hskipBeforeAndAfter) {
      sepwidth = utils2.deflt(colDescr.postgap, arraycolsep);
      if (sepwidth !== 0) {
        colSep = buildCommon.makeSpan(["arraycolsep"], []);
        colSep.style.width = makeEm(sepwidth);
        cols.push(colSep);
      }
    }
  }
  body = buildCommon.makeSpan(["mtable"], cols);
  if (hlines.length > 0) {
    var line = buildCommon.makeLineSpan("hline", options, ruleThickness);
    var dashes = buildCommon.makeLineSpan("hdashline", options, ruleThickness);
    var vListElems = [{
      type: "elem",
      elem: body,
      shift: 0
    }];
    while (hlines.length > 0) {
      var hline = hlines.pop();
      var lineShift = hline.pos - offset;
      if (hline.isDashed) {
        vListElems.push({
          type: "elem",
          elem: dashes,
          shift: lineShift
        });
      } else {
        vListElems.push({
          type: "elem",
          elem: line,
          shift: lineShift
        });
      }
    }
    body = buildCommon.makeVList({
      positionType: "individualShift",
      children: vListElems
    }, options);
  }
  if (tagSpans.length === 0) {
    return buildCommon.makeSpan(["mord"], [body], options);
  } else {
    var eqnNumCol = buildCommon.makeVList({
      positionType: "individualShift",
      children: tagSpans
    }, options);
    eqnNumCol = buildCommon.makeSpan(["tag"], [eqnNumCol], options);
    return buildCommon.makeFragment([body, eqnNumCol]);
  }
};
var alignMap = {
  c: "center ",
  l: "left ",
  r: "right "
};
var mathmlBuilder$5 = function mathmlBuilder(group, options) {
  var tbl = [];
  var glue = new mathMLTree.MathNode("mtd", [], ["mtr-glue"]);
  var tag = new mathMLTree.MathNode("mtd", [], ["mml-eqn-num"]);
  for (var i7 = 0; i7 < group.body.length; i7++) {
    var rw = group.body[i7];
    var row = [];
    for (var j3 = 0; j3 < rw.length; j3++) {
      row.push(new mathMLTree.MathNode("mtd", [buildGroup2(rw[j3], options)]));
    }
    if (group.tags && group.tags[i7]) {
      row.unshift(glue);
      row.push(glue);
      if (group.leqno) {
        row.unshift(tag);
      } else {
        row.push(tag);
      }
    }
    tbl.push(new mathMLTree.MathNode("mtr", row));
  }
  var table = new mathMLTree.MathNode("mtable", tbl);
  var gap = group.arraystretch === 0.5 ? 0.1 : 0.16 + group.arraystretch - 1 + (group.addJot ? 0.09 : 0);
  table.setAttribute("rowspacing", makeEm(gap));
  var menclose = "";
  var align = "";
  if (group.cols && group.cols.length > 0) {
    var cols = group.cols;
    var columnLines = "";
    var prevTypeWasAlign = false;
    var iStart = 0;
    var iEnd = cols.length;
    if (cols[0].type === "separator") {
      menclose += "top ";
      iStart = 1;
    }
    if (cols[cols.length - 1].type === "separator") {
      menclose += "bottom ";
      iEnd -= 1;
    }
    for (var _i = iStart; _i < iEnd; _i++) {
      if (cols[_i].type === "align") {
        align += alignMap[cols[_i].align];
        if (prevTypeWasAlign) {
          columnLines += "none ";
        }
        prevTypeWasAlign = true;
      } else if (cols[_i].type === "separator") {
        if (prevTypeWasAlign) {
          columnLines += cols[_i].separator === "|" ? "solid " : "dashed ";
          prevTypeWasAlign = false;
        }
      }
    }
    table.setAttribute("columnalign", align.trim());
    if (/[sd]/.test(columnLines)) {
      table.setAttribute("columnlines", columnLines.trim());
    }
  }
  if (group.colSeparationType === "align") {
    var _cols = group.cols || [];
    var spacing2 = "";
    for (var _i2 = 1; _i2 < _cols.length; _i2++) {
      spacing2 += _i2 % 2 ? "0em " : "1em ";
    }
    table.setAttribute("columnspacing", spacing2.trim());
  } else if (group.colSeparationType === "alignat" || group.colSeparationType === "gather") {
    table.setAttribute("columnspacing", "0em");
  } else if (group.colSeparationType === "small") {
    table.setAttribute("columnspacing", "0.2778em");
  } else if (group.colSeparationType === "CD") {
    table.setAttribute("columnspacing", "0.5em");
  } else {
    table.setAttribute("columnspacing", "1em");
  }
  var rowLines = "";
  var hlines = group.hLinesBeforeRow;
  menclose += hlines[0].length > 0 ? "left " : "";
  menclose += hlines[hlines.length - 1].length > 0 ? "right " : "";
  for (var _i3 = 1; _i3 < hlines.length - 1; _i3++) {
    rowLines += hlines[_i3].length === 0 ? "none " : hlines[_i3][0] ? "dashed " : "solid ";
  }
  if (/[sd]/.test(rowLines)) {
    table.setAttribute("rowlines", rowLines.trim());
  }
  if (menclose !== "") {
    table = new mathMLTree.MathNode("menclose", [table]);
    table.setAttribute("notation", menclose.trim());
  }
  if (group.arraystretch && group.arraystretch < 1) {
    table = new mathMLTree.MathNode("mstyle", [table]);
    table.setAttribute("scriptlevel", "1");
  }
  return table;
};
var alignedHandler = function alignedHandler2(context, args) {
  if (context.envName.indexOf("ed") === -1) {
    validateAmsEnvironmentContext(context);
  }
  var cols = [];
  var separationType = context.envName.indexOf("at") > -1 ? "alignat" : "align";
  var isSplit = context.envName === "split";
  var res = parseArray(context.parser, {
    cols,
    addJot: true,
    autoTag: isSplit ? void 0 : getAutoTag(context.envName),
    emptySingleRow: true,
    colSeparationType: separationType,
    maxNumCols: isSplit ? 2 : void 0,
    leqno: context.parser.settings.leqno
  }, "display");
  var numMaths;
  var numCols = 0;
  var emptyGroup = {
    type: "ordgroup",
    mode: context.mode,
    body: []
  };
  if (args[0] && args[0].type === "ordgroup") {
    var arg0 = "";
    for (var i7 = 0; i7 < args[0].body.length; i7++) {
      var textord2 = assertNodeType(args[0].body[i7], "textord");
      arg0 += textord2.text;
    }
    numMaths = Number(arg0);
    numCols = numMaths * 2;
  }
  var isAligned = !numCols;
  res.body.forEach(function(row) {
    for (var _i4 = 1; _i4 < row.length; _i4 += 2) {
      var styling = assertNodeType(row[_i4], "styling");
      var ordgroup = assertNodeType(styling.body[0], "ordgroup");
      ordgroup.body.unshift(emptyGroup);
    }
    if (!isAligned) {
      var curMaths = row.length / 2;
      if (numMaths < curMaths) {
        throw new ParseError("Too many math in a row: " + ("expected " + numMaths + ", but got " + curMaths), row[0]);
      }
    } else if (numCols < row.length) {
      numCols = row.length;
    }
  });
  for (var _i5 = 0; _i5 < numCols; ++_i5) {
    var align = "r";
    var pregap = 0;
    if (_i5 % 2 === 1) {
      align = "l";
    } else if (_i5 > 0 && isAligned) {
      pregap = 1;
    }
    cols[_i5] = {
      type: "align",
      align,
      pregap,
      postgap: 0
    };
  }
  res.colSeparationType = isAligned ? "align" : "alignat";
  return res;
};
defineEnvironment({
  type: "array",
  names: ["array", "darray"],
  props: {
    numArgs: 1
  },
  handler(context, args) {
    var symNode = checkSymbolNodeType(args[0]);
    var colalign = symNode ? [args[0]] : assertNodeType(args[0], "ordgroup").body;
    var cols = colalign.map(function(nde) {
      var node = assertSymbolNodeType(nde);
      var ca = node.text;
      if ("lcr".indexOf(ca) !== -1) {
        return {
          type: "align",
          align: ca
        };
      } else if (ca === "|") {
        return {
          type: "separator",
          separator: "|"
        };
      } else if (ca === ":") {
        return {
          type: "separator",
          separator: ":"
        };
      }
      throw new ParseError("Unknown column alignment: " + ca, nde);
    });
    var res = {
      cols,
      hskipBeforeAndAfter: true,
      // \@preamble in lttab.dtx
      maxNumCols: cols.length
    };
    return parseArray(context.parser, res, dCellStyle(context.envName));
  },
  htmlBuilder: htmlBuilder$6,
  mathmlBuilder: mathmlBuilder$5
});
defineEnvironment({
  type: "array",
  names: ["matrix", "pmatrix", "bmatrix", "Bmatrix", "vmatrix", "Vmatrix", "matrix*", "pmatrix*", "bmatrix*", "Bmatrix*", "vmatrix*", "Vmatrix*"],
  props: {
    numArgs: 0
  },
  handler(context) {
    var delimiters2 = {
      "matrix": null,
      "pmatrix": ["(", ")"],
      "bmatrix": ["[", "]"],
      "Bmatrix": ["\\{", "\\}"],
      "vmatrix": ["|", "|"],
      "Vmatrix": ["\\Vert", "\\Vert"]
    }[context.envName.replace("*", "")];
    var colAlign = "c";
    var payload = {
      hskipBeforeAndAfter: false,
      cols: [{
        type: "align",
        align: colAlign
      }]
    };
    if (context.envName.charAt(context.envName.length - 1) === "*") {
      var parser = context.parser;
      parser.consumeSpaces();
      if (parser.fetch().text === "[") {
        parser.consume();
        parser.consumeSpaces();
        colAlign = parser.fetch().text;
        if ("lcr".indexOf(colAlign) === -1) {
          throw new ParseError("Expected l or c or r", parser.nextToken);
        }
        parser.consume();
        parser.consumeSpaces();
        parser.expect("]");
        parser.consume();
        payload.cols = [{
          type: "align",
          align: colAlign
        }];
      }
    }
    var res = parseArray(context.parser, payload, dCellStyle(context.envName));
    var numCols = Math.max(0, ...res.body.map((row) => row.length));
    res.cols = new Array(numCols).fill({
      type: "align",
      align: colAlign
    });
    return delimiters2 ? {
      type: "leftright",
      mode: context.mode,
      body: [res],
      left: delimiters2[0],
      right: delimiters2[1],
      rightColor: void 0
      // \right uninfluenced by \color in array
    } : res;
  },
  htmlBuilder: htmlBuilder$6,
  mathmlBuilder: mathmlBuilder$5
});
defineEnvironment({
  type: "array",
  names: ["smallmatrix"],
  props: {
    numArgs: 0
  },
  handler(context) {
    var payload = {
      arraystretch: 0.5
    };
    var res = parseArray(context.parser, payload, "script");
    res.colSeparationType = "small";
    return res;
  },
  htmlBuilder: htmlBuilder$6,
  mathmlBuilder: mathmlBuilder$5
});
defineEnvironment({
  type: "array",
  names: ["subarray"],
  props: {
    numArgs: 1
  },
  handler(context, args) {
    var symNode = checkSymbolNodeType(args[0]);
    var colalign = symNode ? [args[0]] : assertNodeType(args[0], "ordgroup").body;
    var cols = colalign.map(function(nde) {
      var node = assertSymbolNodeType(nde);
      var ca = node.text;
      if ("lc".indexOf(ca) !== -1) {
        return {
          type: "align",
          align: ca
        };
      }
      throw new ParseError("Unknown column alignment: " + ca, nde);
    });
    if (cols.length > 1) {
      throw new ParseError("{subarray} can contain only one column");
    }
    var res = {
      cols,
      hskipBeforeAndAfter: false,
      arraystretch: 0.5
    };
    res = parseArray(context.parser, res, "script");
    if (res.body.length > 0 && res.body[0].length > 1) {
      throw new ParseError("{subarray} can contain only one column");
    }
    return res;
  },
  htmlBuilder: htmlBuilder$6,
  mathmlBuilder: mathmlBuilder$5
});
defineEnvironment({
  type: "array",
  names: ["cases", "dcases", "rcases", "drcases"],
  props: {
    numArgs: 0
  },
  handler(context) {
    var payload = {
      arraystretch: 1.2,
      cols: [{
        type: "align",
        align: "l",
        pregap: 0,
        // TODO(kevinb) get the current style.
        // For now we use the metrics for TEXT style which is what we were
        // doing before.  Before attempting to get the current style we
        // should look at TeX's behavior especially for \over and matrices.
        postgap: 1
        /* 1em quad */
      }, {
        type: "align",
        align: "l",
        pregap: 0,
        postgap: 0
      }]
    };
    var res = parseArray(context.parser, payload, dCellStyle(context.envName));
    return {
      type: "leftright",
      mode: context.mode,
      body: [res],
      left: context.envName.indexOf("r") > -1 ? "." : "\\{",
      right: context.envName.indexOf("r") > -1 ? "\\}" : ".",
      rightColor: void 0
    };
  },
  htmlBuilder: htmlBuilder$6,
  mathmlBuilder: mathmlBuilder$5
});
defineEnvironment({
  type: "array",
  names: ["align", "align*", "aligned", "split"],
  props: {
    numArgs: 0
  },
  handler: alignedHandler,
  htmlBuilder: htmlBuilder$6,
  mathmlBuilder: mathmlBuilder$5
});
defineEnvironment({
  type: "array",
  names: ["gathered", "gather", "gather*"],
  props: {
    numArgs: 0
  },
  handler(context) {
    if (utils2.contains(["gather", "gather*"], context.envName)) {
      validateAmsEnvironmentContext(context);
    }
    var res = {
      cols: [{
        type: "align",
        align: "c"
      }],
      addJot: true,
      colSeparationType: "gather",
      autoTag: getAutoTag(context.envName),
      emptySingleRow: true,
      leqno: context.parser.settings.leqno
    };
    return parseArray(context.parser, res, "display");
  },
  htmlBuilder: htmlBuilder$6,
  mathmlBuilder: mathmlBuilder$5
});
defineEnvironment({
  type: "array",
  names: ["alignat", "alignat*", "alignedat"],
  props: {
    numArgs: 1
  },
  handler: alignedHandler,
  htmlBuilder: htmlBuilder$6,
  mathmlBuilder: mathmlBuilder$5
});
defineEnvironment({
  type: "array",
  names: ["equation", "equation*"],
  props: {
    numArgs: 0
  },
  handler(context) {
    validateAmsEnvironmentContext(context);
    var res = {
      autoTag: getAutoTag(context.envName),
      emptySingleRow: true,
      singleRow: true,
      maxNumCols: 1,
      leqno: context.parser.settings.leqno
    };
    return parseArray(context.parser, res, "display");
  },
  htmlBuilder: htmlBuilder$6,
  mathmlBuilder: mathmlBuilder$5
});
defineEnvironment({
  type: "array",
  names: ["CD"],
  props: {
    numArgs: 0
  },
  handler(context) {
    validateAmsEnvironmentContext(context);
    return parseCD(context.parser);
  },
  htmlBuilder: htmlBuilder$6,
  mathmlBuilder: mathmlBuilder$5
});
defineMacro("\\nonumber", "\\gdef\\@eqnsw{0}");
defineMacro("\\notag", "\\nonumber");
defineFunction({
  type: "text",
  // Doesn't matter what this is.
  names: ["\\hline", "\\hdashline"],
  props: {
    numArgs: 0,
    allowedInText: true,
    allowedInMath: true
  },
  handler(context, args) {
    throw new ParseError(context.funcName + " valid only within array environment");
  }
});
var environments = _environments;
defineFunction({
  type: "environment",
  names: ["\\begin", "\\end"],
  props: {
    numArgs: 1,
    argTypes: ["text"]
  },
  handler(_ref, args) {
    var {
      parser,
      funcName
    } = _ref;
    var nameGroup = args[0];
    if (nameGroup.type !== "ordgroup") {
      throw new ParseError("Invalid environment name", nameGroup);
    }
    var envName = "";
    for (var i7 = 0; i7 < nameGroup.body.length; ++i7) {
      envName += assertNodeType(nameGroup.body[i7], "textord").text;
    }
    if (funcName === "\\begin") {
      if (!environments.hasOwnProperty(envName)) {
        throw new ParseError("No such environment: " + envName, nameGroup);
      }
      var env = environments[envName];
      var {
        args: _args,
        optArgs
      } = parser.parseArguments("\\begin{" + envName + "}", env);
      var context = {
        mode: parser.mode,
        envName,
        parser
      };
      var result = env.handler(context, _args, optArgs);
      parser.expect("\\end", false);
      var endNameToken = parser.nextToken;
      var end = assertNodeType(parser.parseFunction(), "environment");
      if (end.name !== envName) {
        throw new ParseError("Mismatch: \\begin{" + envName + "} matched by \\end{" + end.name + "}", endNameToken);
      }
      return result;
    }
    return {
      type: "environment",
      mode: parser.mode,
      name: envName,
      nameGroup
    };
  }
});
var htmlBuilder$5 = (group, options) => {
  var font = group.font;
  var newOptions = options.withFont(font);
  return buildGroup$1(group.body, newOptions);
};
var mathmlBuilder$4 = (group, options) => {
  var font = group.font;
  var newOptions = options.withFont(font);
  return buildGroup2(group.body, newOptions);
};
var fontAliases = {
  "\\Bbb": "\\mathbb",
  "\\bold": "\\mathbf",
  "\\frak": "\\mathfrak",
  "\\bm": "\\boldsymbol"
};
defineFunction({
  type: "font",
  names: [
    // styles, except \boldsymbol defined below
    "\\mathrm",
    "\\mathit",
    "\\mathbf",
    "\\mathnormal",
    "\\mathsfit",
    // families
    "\\mathbb",
    "\\mathcal",
    "\\mathfrak",
    "\\mathscr",
    "\\mathsf",
    "\\mathtt",
    // aliases, except \bm defined below
    "\\Bbb",
    "\\bold",
    "\\frak"
  ],
  props: {
    numArgs: 1,
    allowedInArgument: true
  },
  handler: (_ref, args) => {
    var {
      parser,
      funcName
    } = _ref;
    var body = normalizeArgument(args[0]);
    var func = funcName;
    if (func in fontAliases) {
      func = fontAliases[func];
    }
    return {
      type: "font",
      mode: parser.mode,
      font: func.slice(1),
      body
    };
  },
  htmlBuilder: htmlBuilder$5,
  mathmlBuilder: mathmlBuilder$4
});
defineFunction({
  type: "mclass",
  names: ["\\boldsymbol", "\\bm"],
  props: {
    numArgs: 1
  },
  handler: (_ref2, args) => {
    var {
      parser
    } = _ref2;
    var body = args[0];
    var isCharacterBox3 = utils2.isCharacterBox(body);
    return {
      type: "mclass",
      mode: parser.mode,
      mclass: binrelClass(body),
      body: [{
        type: "font",
        mode: parser.mode,
        font: "boldsymbol",
        body
      }],
      isCharacterBox: isCharacterBox3
    };
  }
});
defineFunction({
  type: "font",
  names: ["\\rm", "\\sf", "\\tt", "\\bf", "\\it", "\\cal"],
  props: {
    numArgs: 0,
    allowedInText: true
  },
  handler: (_ref3, args) => {
    var {
      parser,
      funcName,
      breakOnTokenText
    } = _ref3;
    var {
      mode
    } = parser;
    var body = parser.parseExpression(true, breakOnTokenText);
    var style = "math" + funcName.slice(1);
    return {
      type: "font",
      mode,
      font: style,
      body: {
        type: "ordgroup",
        mode: parser.mode,
        body
      }
    };
  },
  htmlBuilder: htmlBuilder$5,
  mathmlBuilder: mathmlBuilder$4
});
var adjustStyle = (size, originalStyle) => {
  var style = originalStyle;
  if (size === "display") {
    style = style.id >= Style$1.SCRIPT.id ? style.text() : Style$1.DISPLAY;
  } else if (size === "text" && style.size === Style$1.DISPLAY.size) {
    style = Style$1.TEXT;
  } else if (size === "script") {
    style = Style$1.SCRIPT;
  } else if (size === "scriptscript") {
    style = Style$1.SCRIPTSCRIPT;
  }
  return style;
};
var htmlBuilder$4 = (group, options) => {
  var style = adjustStyle(group.size, options.style);
  var nstyle = style.fracNum();
  var dstyle = style.fracDen();
  var newOptions;
  newOptions = options.havingStyle(nstyle);
  var numerm = buildGroup$1(group.numer, newOptions, options);
  if (group.continued) {
    var hStrut = 8.5 / options.fontMetrics().ptPerEm;
    var dStrut = 3.5 / options.fontMetrics().ptPerEm;
    numerm.height = numerm.height < hStrut ? hStrut : numerm.height;
    numerm.depth = numerm.depth < dStrut ? dStrut : numerm.depth;
  }
  newOptions = options.havingStyle(dstyle);
  var denomm = buildGroup$1(group.denom, newOptions, options);
  var rule;
  var ruleWidth;
  var ruleSpacing;
  if (group.hasBarLine) {
    if (group.barSize) {
      ruleWidth = calculateSize(group.barSize, options);
      rule = buildCommon.makeLineSpan("frac-line", options, ruleWidth);
    } else {
      rule = buildCommon.makeLineSpan("frac-line", options);
    }
    ruleWidth = rule.height;
    ruleSpacing = rule.height;
  } else {
    rule = null;
    ruleWidth = 0;
    ruleSpacing = options.fontMetrics().defaultRuleThickness;
  }
  var numShift;
  var clearance;
  var denomShift;
  if (style.size === Style$1.DISPLAY.size || group.size === "display") {
    numShift = options.fontMetrics().num1;
    if (ruleWidth > 0) {
      clearance = 3 * ruleSpacing;
    } else {
      clearance = 7 * ruleSpacing;
    }
    denomShift = options.fontMetrics().denom1;
  } else {
    if (ruleWidth > 0) {
      numShift = options.fontMetrics().num2;
      clearance = ruleSpacing;
    } else {
      numShift = options.fontMetrics().num3;
      clearance = 3 * ruleSpacing;
    }
    denomShift = options.fontMetrics().denom2;
  }
  var frac;
  if (!rule) {
    var candidateClearance = numShift - numerm.depth - (denomm.height - denomShift);
    if (candidateClearance < clearance) {
      numShift += 0.5 * (clearance - candidateClearance);
      denomShift += 0.5 * (clearance - candidateClearance);
    }
    frac = buildCommon.makeVList({
      positionType: "individualShift",
      children: [{
        type: "elem",
        elem: denomm,
        shift: denomShift
      }, {
        type: "elem",
        elem: numerm,
        shift: -numShift
      }]
    }, options);
  } else {
    var axisHeight = options.fontMetrics().axisHeight;
    if (numShift - numerm.depth - (axisHeight + 0.5 * ruleWidth) < clearance) {
      numShift += clearance - (numShift - numerm.depth - (axisHeight + 0.5 * ruleWidth));
    }
    if (axisHeight - 0.5 * ruleWidth - (denomm.height - denomShift) < clearance) {
      denomShift += clearance - (axisHeight - 0.5 * ruleWidth - (denomm.height - denomShift));
    }
    var midShift = -(axisHeight - 0.5 * ruleWidth);
    frac = buildCommon.makeVList({
      positionType: "individualShift",
      children: [{
        type: "elem",
        elem: denomm,
        shift: denomShift
      }, {
        type: "elem",
        elem: rule,
        shift: midShift
      }, {
        type: "elem",
        elem: numerm,
        shift: -numShift
      }]
    }, options);
  }
  newOptions = options.havingStyle(style);
  frac.height *= newOptions.sizeMultiplier / options.sizeMultiplier;
  frac.depth *= newOptions.sizeMultiplier / options.sizeMultiplier;
  var delimSize;
  if (style.size === Style$1.DISPLAY.size) {
    delimSize = options.fontMetrics().delim1;
  } else if (style.size === Style$1.SCRIPTSCRIPT.size) {
    delimSize = options.havingStyle(Style$1.SCRIPT).fontMetrics().delim2;
  } else {
    delimSize = options.fontMetrics().delim2;
  }
  var leftDelim;
  var rightDelim;
  if (group.leftDelim == null) {
    leftDelim = makeNullDelimiter(options, ["mopen"]);
  } else {
    leftDelim = delimiter.customSizedDelim(group.leftDelim, delimSize, true, options.havingStyle(style), group.mode, ["mopen"]);
  }
  if (group.continued) {
    rightDelim = buildCommon.makeSpan([]);
  } else if (group.rightDelim == null) {
    rightDelim = makeNullDelimiter(options, ["mclose"]);
  } else {
    rightDelim = delimiter.customSizedDelim(group.rightDelim, delimSize, true, options.havingStyle(style), group.mode, ["mclose"]);
  }
  return buildCommon.makeSpan(["mord"].concat(newOptions.sizingClasses(options)), [leftDelim, buildCommon.makeSpan(["mfrac"], [frac]), rightDelim], options);
};
var mathmlBuilder$3 = (group, options) => {
  var node = new mathMLTree.MathNode("mfrac", [buildGroup2(group.numer, options), buildGroup2(group.denom, options)]);
  if (!group.hasBarLine) {
    node.setAttribute("linethickness", "0px");
  } else if (group.barSize) {
    var ruleWidth = calculateSize(group.barSize, options);
    node.setAttribute("linethickness", makeEm(ruleWidth));
  }
  var style = adjustStyle(group.size, options.style);
  if (style.size !== options.style.size) {
    node = new mathMLTree.MathNode("mstyle", [node]);
    var isDisplay = style.size === Style$1.DISPLAY.size ? "true" : "false";
    node.setAttribute("displaystyle", isDisplay);
    node.setAttribute("scriptlevel", "0");
  }
  if (group.leftDelim != null || group.rightDelim != null) {
    var withDelims = [];
    if (group.leftDelim != null) {
      var leftOp = new mathMLTree.MathNode("mo", [new mathMLTree.TextNode(group.leftDelim.replace("\\", ""))]);
      leftOp.setAttribute("fence", "true");
      withDelims.push(leftOp);
    }
    withDelims.push(node);
    if (group.rightDelim != null) {
      var rightOp = new mathMLTree.MathNode("mo", [new mathMLTree.TextNode(group.rightDelim.replace("\\", ""))]);
      rightOp.setAttribute("fence", "true");
      withDelims.push(rightOp);
    }
    return makeRow(withDelims);
  }
  return node;
};
defineFunction({
  type: "genfrac",
  names: [
    "\\dfrac",
    "\\frac",
    "\\tfrac",
    "\\dbinom",
    "\\binom",
    "\\tbinom",
    "\\\\atopfrac",
    // can’t be entered directly
    "\\\\bracefrac",
    "\\\\brackfrac"
    // ditto
  ],
  props: {
    numArgs: 2,
    allowedInArgument: true
  },
  handler: (_ref, args) => {
    var {
      parser,
      funcName
    } = _ref;
    var numer = args[0];
    var denom = args[1];
    var hasBarLine;
    var leftDelim = null;
    var rightDelim = null;
    var size = "auto";
    switch (funcName) {
      case "\\dfrac":
      case "\\frac":
      case "\\tfrac":
        hasBarLine = true;
        break;
      case "\\\\atopfrac":
        hasBarLine = false;
        break;
      case "\\dbinom":
      case "\\binom":
      case "\\tbinom":
        hasBarLine = false;
        leftDelim = "(";
        rightDelim = ")";
        break;
      case "\\\\bracefrac":
        hasBarLine = false;
        leftDelim = "\\{";
        rightDelim = "\\}";
        break;
      case "\\\\brackfrac":
        hasBarLine = false;
        leftDelim = "[";
        rightDelim = "]";
        break;
      default:
        throw new Error("Unrecognized genfrac command");
    }
    switch (funcName) {
      case "\\dfrac":
      case "\\dbinom":
        size = "display";
        break;
      case "\\tfrac":
      case "\\tbinom":
        size = "text";
        break;
    }
    return {
      type: "genfrac",
      mode: parser.mode,
      continued: false,
      numer,
      denom,
      hasBarLine,
      leftDelim,
      rightDelim,
      size,
      barSize: null
    };
  },
  htmlBuilder: htmlBuilder$4,
  mathmlBuilder: mathmlBuilder$3
});
defineFunction({
  type: "genfrac",
  names: ["\\cfrac"],
  props: {
    numArgs: 2
  },
  handler: (_ref2, args) => {
    var {
      parser,
      funcName
    } = _ref2;
    var numer = args[0];
    var denom = args[1];
    return {
      type: "genfrac",
      mode: parser.mode,
      continued: true,
      numer,
      denom,
      hasBarLine: true,
      leftDelim: null,
      rightDelim: null,
      size: "display",
      barSize: null
    };
  }
});
defineFunction({
  type: "infix",
  names: ["\\over", "\\choose", "\\atop", "\\brace", "\\brack"],
  props: {
    numArgs: 0,
    infix: true
  },
  handler(_ref3) {
    var {
      parser,
      funcName,
      token
    } = _ref3;
    var replaceWith;
    switch (funcName) {
      case "\\over":
        replaceWith = "\\frac";
        break;
      case "\\choose":
        replaceWith = "\\binom";
        break;
      case "\\atop":
        replaceWith = "\\\\atopfrac";
        break;
      case "\\brace":
        replaceWith = "\\\\bracefrac";
        break;
      case "\\brack":
        replaceWith = "\\\\brackfrac";
        break;
      default:
        throw new Error("Unrecognized infix genfrac command");
    }
    return {
      type: "infix",
      mode: parser.mode,
      replaceWith,
      token
    };
  }
});
var stylArray = ["display", "text", "script", "scriptscript"];
var delimFromValue = function delimFromValue2(delimString) {
  var delim = null;
  if (delimString.length > 0) {
    delim = delimString;
    delim = delim === "." ? null : delim;
  }
  return delim;
};
defineFunction({
  type: "genfrac",
  names: ["\\genfrac"],
  props: {
    numArgs: 6,
    allowedInArgument: true,
    argTypes: ["math", "math", "size", "text", "math", "math"]
  },
  handler(_ref4, args) {
    var {
      parser
    } = _ref4;
    var numer = args[4];
    var denom = args[5];
    var leftNode = normalizeArgument(args[0]);
    var leftDelim = leftNode.type === "atom" && leftNode.family === "open" ? delimFromValue(leftNode.text) : null;
    var rightNode = normalizeArgument(args[1]);
    var rightDelim = rightNode.type === "atom" && rightNode.family === "close" ? delimFromValue(rightNode.text) : null;
    var barNode = assertNodeType(args[2], "size");
    var hasBarLine;
    var barSize = null;
    if (barNode.isBlank) {
      hasBarLine = true;
    } else {
      barSize = barNode.value;
      hasBarLine = barSize.number > 0;
    }
    var size = "auto";
    var styl = args[3];
    if (styl.type === "ordgroup") {
      if (styl.body.length > 0) {
        var textOrd = assertNodeType(styl.body[0], "textord");
        size = stylArray[Number(textOrd.text)];
      }
    } else {
      styl = assertNodeType(styl, "textord");
      size = stylArray[Number(styl.text)];
    }
    return {
      type: "genfrac",
      mode: parser.mode,
      numer,
      denom,
      continued: false,
      hasBarLine,
      barSize,
      leftDelim,
      rightDelim,
      size
    };
  },
  htmlBuilder: htmlBuilder$4,
  mathmlBuilder: mathmlBuilder$3
});
defineFunction({
  type: "infix",
  names: ["\\above"],
  props: {
    numArgs: 1,
    argTypes: ["size"],
    infix: true
  },
  handler(_ref5, args) {
    var {
      parser,
      funcName,
      token
    } = _ref5;
    return {
      type: "infix",
      mode: parser.mode,
      replaceWith: "\\\\abovefrac",
      size: assertNodeType(args[0], "size").value,
      token
    };
  }
});
defineFunction({
  type: "genfrac",
  names: ["\\\\abovefrac"],
  props: {
    numArgs: 3,
    argTypes: ["math", "size", "math"]
  },
  handler: (_ref6, args) => {
    var {
      parser,
      funcName
    } = _ref6;
    var numer = args[0];
    var barSize = assert2(assertNodeType(args[1], "infix").size);
    var denom = args[2];
    var hasBarLine = barSize.number > 0;
    return {
      type: "genfrac",
      mode: parser.mode,
      numer,
      denom,
      continued: false,
      hasBarLine,
      barSize,
      leftDelim: null,
      rightDelim: null,
      size: "auto"
    };
  },
  htmlBuilder: htmlBuilder$4,
  mathmlBuilder: mathmlBuilder$3
});
var htmlBuilder$3 = (grp, options) => {
  var style = options.style;
  var supSubGroup;
  var group;
  if (grp.type === "supsub") {
    supSubGroup = grp.sup ? buildGroup$1(grp.sup, options.havingStyle(style.sup()), options) : buildGroup$1(grp.sub, options.havingStyle(style.sub()), options);
    group = assertNodeType(grp.base, "horizBrace");
  } else {
    group = assertNodeType(grp, "horizBrace");
  }
  var body = buildGroup$1(group.base, options.havingBaseStyle(Style$1.DISPLAY));
  var braceBody = stretchy.svgSpan(group, options);
  var vlist;
  if (group.isOver) {
    vlist = buildCommon.makeVList({
      positionType: "firstBaseline",
      children: [{
        type: "elem",
        elem: body
      }, {
        type: "kern",
        size: 0.1
      }, {
        type: "elem",
        elem: braceBody
      }]
    }, options);
    vlist.children[0].children[0].children[1].classes.push("svg-align");
  } else {
    vlist = buildCommon.makeVList({
      positionType: "bottom",
      positionData: body.depth + 0.1 + braceBody.height,
      children: [{
        type: "elem",
        elem: braceBody
      }, {
        type: "kern",
        size: 0.1
      }, {
        type: "elem",
        elem: body
      }]
    }, options);
    vlist.children[0].children[0].children[0].classes.push("svg-align");
  }
  if (supSubGroup) {
    var vSpan = buildCommon.makeSpan(["mord", group.isOver ? "mover" : "munder"], [vlist], options);
    if (group.isOver) {
      vlist = buildCommon.makeVList({
        positionType: "firstBaseline",
        children: [{
          type: "elem",
          elem: vSpan
        }, {
          type: "kern",
          size: 0.2
        }, {
          type: "elem",
          elem: supSubGroup
        }]
      }, options);
    } else {
      vlist = buildCommon.makeVList({
        positionType: "bottom",
        positionData: vSpan.depth + 0.2 + supSubGroup.height + supSubGroup.depth,
        children: [{
          type: "elem",
          elem: supSubGroup
        }, {
          type: "kern",
          size: 0.2
        }, {
          type: "elem",
          elem: vSpan
        }]
      }, options);
    }
  }
  return buildCommon.makeSpan(["mord", group.isOver ? "mover" : "munder"], [vlist], options);
};
var mathmlBuilder$2 = (group, options) => {
  var accentNode = stretchy.mathMLnode(group.label);
  return new mathMLTree.MathNode(group.isOver ? "mover" : "munder", [buildGroup2(group.base, options), accentNode]);
};
defineFunction({
  type: "horizBrace",
  names: ["\\overbrace", "\\underbrace"],
  props: {
    numArgs: 1
  },
  handler(_ref, args) {
    var {
      parser,
      funcName
    } = _ref;
    return {
      type: "horizBrace",
      mode: parser.mode,
      label: funcName,
      isOver: /^\\over/.test(funcName),
      base: args[0]
    };
  },
  htmlBuilder: htmlBuilder$3,
  mathmlBuilder: mathmlBuilder$2
});
defineFunction({
  type: "href",
  names: ["\\href"],
  props: {
    numArgs: 2,
    argTypes: ["url", "original"],
    allowedInText: true
  },
  handler: (_ref, args) => {
    var {
      parser
    } = _ref;
    var body = args[1];
    var href = assertNodeType(args[0], "url").url;
    if (!parser.settings.isTrusted({
      command: "\\href",
      url: href
    })) {
      return parser.formatUnsupportedCmd("\\href");
    }
    return {
      type: "href",
      mode: parser.mode,
      href,
      body: ordargument(body)
    };
  },
  htmlBuilder: (group, options) => {
    var elements = buildExpression$1(group.body, options, false);
    return buildCommon.makeAnchor(group.href, [], elements, options);
  },
  mathmlBuilder: (group, options) => {
    var math2 = buildExpressionRow(group.body, options);
    if (!(math2 instanceof MathNode)) {
      math2 = new MathNode("mrow", [math2]);
    }
    math2.setAttribute("href", group.href);
    return math2;
  }
});
defineFunction({
  type: "href",
  names: ["\\url"],
  props: {
    numArgs: 1,
    argTypes: ["url"],
    allowedInText: true
  },
  handler: (_ref2, args) => {
    var {
      parser
    } = _ref2;
    var href = assertNodeType(args[0], "url").url;
    if (!parser.settings.isTrusted({
      command: "\\url",
      url: href
    })) {
      return parser.formatUnsupportedCmd("\\url");
    }
    var chars = [];
    for (var i7 = 0; i7 < href.length; i7++) {
      var c6 = href[i7];
      if (c6 === "~") {
        c6 = "\\textasciitilde";
      }
      chars.push({
        type: "textord",
        mode: "text",
        text: c6
      });
    }
    var body = {
      type: "text",
      mode: parser.mode,
      font: "\\texttt",
      body: chars
    };
    return {
      type: "href",
      mode: parser.mode,
      href,
      body: ordargument(body)
    };
  }
});
defineFunction({
  type: "hbox",
  names: ["\\hbox"],
  props: {
    numArgs: 1,
    argTypes: ["text"],
    allowedInText: true,
    primitive: true
  },
  handler(_ref, args) {
    var {
      parser
    } = _ref;
    return {
      type: "hbox",
      mode: parser.mode,
      body: ordargument(args[0])
    };
  },
  htmlBuilder(group, options) {
    var elements = buildExpression$1(group.body, options, false);
    return buildCommon.makeFragment(elements);
  },
  mathmlBuilder(group, options) {
    return new mathMLTree.MathNode("mrow", buildExpression2(group.body, options));
  }
});
defineFunction({
  type: "html",
  names: ["\\htmlClass", "\\htmlId", "\\htmlStyle", "\\htmlData"],
  props: {
    numArgs: 2,
    argTypes: ["raw", "original"],
    allowedInText: true
  },
  handler: (_ref, args) => {
    var {
      parser,
      funcName,
      token
    } = _ref;
    var value = assertNodeType(args[0], "raw").string;
    var body = args[1];
    if (parser.settings.strict) {
      parser.settings.reportNonstrict("htmlExtension", "HTML extension is disabled on strict mode");
    }
    var trustContext;
    var attributes = {};
    switch (funcName) {
      case "\\htmlClass":
        attributes.class = value;
        trustContext = {
          command: "\\htmlClass",
          class: value
        };
        break;
      case "\\htmlId":
        attributes.id = value;
        trustContext = {
          command: "\\htmlId",
          id: value
        };
        break;
      case "\\htmlStyle":
        attributes.style = value;
        trustContext = {
          command: "\\htmlStyle",
          style: value
        };
        break;
      case "\\htmlData": {
        var data = value.split(",");
        for (var i7 = 0; i7 < data.length; i7++) {
          var keyVal = data[i7].split("=");
          if (keyVal.length !== 2) {
            throw new ParseError("Error parsing key-value for \\htmlData");
          }
          attributes["data-" + keyVal[0].trim()] = keyVal[1].trim();
        }
        trustContext = {
          command: "\\htmlData",
          attributes
        };
        break;
      }
      default:
        throw new Error("Unrecognized html command");
    }
    if (!parser.settings.isTrusted(trustContext)) {
      return parser.formatUnsupportedCmd(funcName);
    }
    return {
      type: "html",
      mode: parser.mode,
      attributes,
      body: ordargument(body)
    };
  },
  htmlBuilder: (group, options) => {
    var elements = buildExpression$1(group.body, options, false);
    var classes = ["enclosing"];
    if (group.attributes.class) {
      classes.push(...group.attributes.class.trim().split(/\s+/));
    }
    var span = buildCommon.makeSpan(classes, elements, options);
    for (var attr in group.attributes) {
      if (attr !== "class" && group.attributes.hasOwnProperty(attr)) {
        span.setAttribute(attr, group.attributes[attr]);
      }
    }
    return span;
  },
  mathmlBuilder: (group, options) => {
    return buildExpressionRow(group.body, options);
  }
});
defineFunction({
  type: "htmlmathml",
  names: ["\\html@mathml"],
  props: {
    numArgs: 2,
    allowedInText: true
  },
  handler: (_ref, args) => {
    var {
      parser
    } = _ref;
    return {
      type: "htmlmathml",
      mode: parser.mode,
      html: ordargument(args[0]),
      mathml: ordargument(args[1])
    };
  },
  htmlBuilder: (group, options) => {
    var elements = buildExpression$1(group.html, options, false);
    return buildCommon.makeFragment(elements);
  },
  mathmlBuilder: (group, options) => {
    return buildExpressionRow(group.mathml, options);
  }
});
var sizeData = function sizeData2(str2) {
  if (/^[-+]? *(\d+(\.\d*)?|\.\d+)$/.test(str2)) {
    return {
      number: +str2,
      unit: "bp"
    };
  } else {
    var match2 = /([-+]?) *(\d+(?:\.\d*)?|\.\d+) *([a-z]{2})/.exec(str2);
    if (!match2) {
      throw new ParseError("Invalid size: '" + str2 + "' in \\includegraphics");
    }
    var data = {
      number: +(match2[1] + match2[2]),
      // sign + magnitude, cast to number
      unit: match2[3]
    };
    if (!validUnit(data)) {
      throw new ParseError("Invalid unit: '" + data.unit + "' in \\includegraphics.");
    }
    return data;
  }
};
defineFunction({
  type: "includegraphics",
  names: ["\\includegraphics"],
  props: {
    numArgs: 1,
    numOptionalArgs: 1,
    argTypes: ["raw", "url"],
    allowedInText: false
  },
  handler: (_ref, args, optArgs) => {
    var {
      parser
    } = _ref;
    var width = {
      number: 0,
      unit: "em"
    };
    var height = {
      number: 0.9,
      unit: "em"
    };
    var totalheight = {
      number: 0,
      unit: "em"
    };
    var alt = "";
    if (optArgs[0]) {
      var attributeStr = assertNodeType(optArgs[0], "raw").string;
      var attributes = attributeStr.split(",");
      for (var i7 = 0; i7 < attributes.length; i7++) {
        var keyVal = attributes[i7].split("=");
        if (keyVal.length === 2) {
          var str2 = keyVal[1].trim();
          switch (keyVal[0].trim()) {
            case "alt":
              alt = str2;
              break;
            case "width":
              width = sizeData(str2);
              break;
            case "height":
              height = sizeData(str2);
              break;
            case "totalheight":
              totalheight = sizeData(str2);
              break;
            default:
              throw new ParseError("Invalid key: '" + keyVal[0] + "' in \\includegraphics.");
          }
        }
      }
    }
    var src = assertNodeType(args[0], "url").url;
    if (alt === "") {
      alt = src;
      alt = alt.replace(/^.*[\\/]/, "");
      alt = alt.substring(0, alt.lastIndexOf("."));
    }
    if (!parser.settings.isTrusted({
      command: "\\includegraphics",
      url: src
    })) {
      return parser.formatUnsupportedCmd("\\includegraphics");
    }
    return {
      type: "includegraphics",
      mode: parser.mode,
      alt,
      width,
      height,
      totalheight,
      src
    };
  },
  htmlBuilder: (group, options) => {
    var height = calculateSize(group.height, options);
    var depth = 0;
    if (group.totalheight.number > 0) {
      depth = calculateSize(group.totalheight, options) - height;
    }
    var width = 0;
    if (group.width.number > 0) {
      width = calculateSize(group.width, options);
    }
    var style = {
      height: makeEm(height + depth)
    };
    if (width > 0) {
      style.width = makeEm(width);
    }
    if (depth > 0) {
      style.verticalAlign = makeEm(-depth);
    }
    var node = new Img(group.src, group.alt, style);
    node.height = height;
    node.depth = depth;
    return node;
  },
  mathmlBuilder: (group, options) => {
    var node = new mathMLTree.MathNode("mglyph", []);
    node.setAttribute("alt", group.alt);
    var height = calculateSize(group.height, options);
    var depth = 0;
    if (group.totalheight.number > 0) {
      depth = calculateSize(group.totalheight, options) - height;
      node.setAttribute("valign", makeEm(-depth));
    }
    node.setAttribute("height", makeEm(height + depth));
    if (group.width.number > 0) {
      var width = calculateSize(group.width, options);
      node.setAttribute("width", makeEm(width));
    }
    node.setAttribute("src", group.src);
    return node;
  }
});
defineFunction({
  type: "kern",
  names: ["\\kern", "\\mkern", "\\hskip", "\\mskip"],
  props: {
    numArgs: 1,
    argTypes: ["size"],
    primitive: true,
    allowedInText: true
  },
  handler(_ref, args) {
    var {
      parser,
      funcName
    } = _ref;
    var size = assertNodeType(args[0], "size");
    if (parser.settings.strict) {
      var mathFunction = funcName[1] === "m";
      var muUnit = size.value.unit === "mu";
      if (mathFunction) {
        if (!muUnit) {
          parser.settings.reportNonstrict("mathVsTextUnits", "LaTeX's " + funcName + " supports only mu units, " + ("not " + size.value.unit + " units"));
        }
        if (parser.mode !== "math") {
          parser.settings.reportNonstrict("mathVsTextUnits", "LaTeX's " + funcName + " works only in math mode");
        }
      } else {
        if (muUnit) {
          parser.settings.reportNonstrict("mathVsTextUnits", "LaTeX's " + funcName + " doesn't support mu units");
        }
      }
    }
    return {
      type: "kern",
      mode: parser.mode,
      dimension: size.value
    };
  },
  htmlBuilder(group, options) {
    return buildCommon.makeGlue(group.dimension, options);
  },
  mathmlBuilder(group, options) {
    var dimension = calculateSize(group.dimension, options);
    return new mathMLTree.SpaceNode(dimension);
  }
});
defineFunction({
  type: "lap",
  names: ["\\mathllap", "\\mathrlap", "\\mathclap"],
  props: {
    numArgs: 1,
    allowedInText: true
  },
  handler: (_ref, args) => {
    var {
      parser,
      funcName
    } = _ref;
    var body = args[0];
    return {
      type: "lap",
      mode: parser.mode,
      alignment: funcName.slice(5),
      body
    };
  },
  htmlBuilder: (group, options) => {
    var inner2;
    if (group.alignment === "clap") {
      inner2 = buildCommon.makeSpan([], [buildGroup$1(group.body, options)]);
      inner2 = buildCommon.makeSpan(["inner"], [inner2], options);
    } else {
      inner2 = buildCommon.makeSpan(["inner"], [buildGroup$1(group.body, options)]);
    }
    var fix = buildCommon.makeSpan(["fix"], []);
    var node = buildCommon.makeSpan([group.alignment], [inner2, fix], options);
    var strut = buildCommon.makeSpan(["strut"]);
    strut.style.height = makeEm(node.height + node.depth);
    if (node.depth) {
      strut.style.verticalAlign = makeEm(-node.depth);
    }
    node.children.unshift(strut);
    node = buildCommon.makeSpan(["thinbox"], [node], options);
    return buildCommon.makeSpan(["mord", "vbox"], [node], options);
  },
  mathmlBuilder: (group, options) => {
    var node = new mathMLTree.MathNode("mpadded", [buildGroup2(group.body, options)]);
    if (group.alignment !== "rlap") {
      var offset = group.alignment === "llap" ? "-1" : "-0.5";
      node.setAttribute("lspace", offset + "width");
    }
    node.setAttribute("width", "0px");
    return node;
  }
});
defineFunction({
  type: "styling",
  names: ["\\(", "$"],
  props: {
    numArgs: 0,
    allowedInText: true,
    allowedInMath: false
  },
  handler(_ref, args) {
    var {
      funcName,
      parser
    } = _ref;
    var outerMode = parser.mode;
    parser.switchMode("math");
    var close2 = funcName === "\\(" ? "\\)" : "$";
    var body = parser.parseExpression(false, close2);
    parser.expect(close2);
    parser.switchMode(outerMode);
    return {
      type: "styling",
      mode: parser.mode,
      style: "text",
      body
    };
  }
});
defineFunction({
  type: "text",
  // Doesn't matter what this is.
  names: ["\\)", "\\]"],
  props: {
    numArgs: 0,
    allowedInText: true,
    allowedInMath: false
  },
  handler(context, args) {
    throw new ParseError("Mismatched " + context.funcName);
  }
});
var chooseMathStyle = (group, options) => {
  switch (options.style.size) {
    case Style$1.DISPLAY.size:
      return group.display;
    case Style$1.TEXT.size:
      return group.text;
    case Style$1.SCRIPT.size:
      return group.script;
    case Style$1.SCRIPTSCRIPT.size:
      return group.scriptscript;
    default:
      return group.text;
  }
};
defineFunction({
  type: "mathchoice",
  names: ["\\mathchoice"],
  props: {
    numArgs: 4,
    primitive: true
  },
  handler: (_ref, args) => {
    var {
      parser
    } = _ref;
    return {
      type: "mathchoice",
      mode: parser.mode,
      display: ordargument(args[0]),
      text: ordargument(args[1]),
      script: ordargument(args[2]),
      scriptscript: ordargument(args[3])
    };
  },
  htmlBuilder: (group, options) => {
    var body = chooseMathStyle(group, options);
    var elements = buildExpression$1(body, options, false);
    return buildCommon.makeFragment(elements);
  },
  mathmlBuilder: (group, options) => {
    var body = chooseMathStyle(group, options);
    return buildExpressionRow(body, options);
  }
});
var assembleSupSub = (base, supGroup, subGroup, options, style, slant, baseShift) => {
  base = buildCommon.makeSpan([], [base]);
  var subIsSingleCharacter = subGroup && utils2.isCharacterBox(subGroup);
  var sub2;
  var sup2;
  if (supGroup) {
    var elem = buildGroup$1(supGroup, options.havingStyle(style.sup()), options);
    sup2 = {
      elem,
      kern: Math.max(options.fontMetrics().bigOpSpacing1, options.fontMetrics().bigOpSpacing3 - elem.depth)
    };
  }
  if (subGroup) {
    var _elem = buildGroup$1(subGroup, options.havingStyle(style.sub()), options);
    sub2 = {
      elem: _elem,
      kern: Math.max(options.fontMetrics().bigOpSpacing2, options.fontMetrics().bigOpSpacing4 - _elem.height)
    };
  }
  var finalGroup;
  if (sup2 && sub2) {
    var bottom = options.fontMetrics().bigOpSpacing5 + sub2.elem.height + sub2.elem.depth + sub2.kern + base.depth + baseShift;
    finalGroup = buildCommon.makeVList({
      positionType: "bottom",
      positionData: bottom,
      children: [{
        type: "kern",
        size: options.fontMetrics().bigOpSpacing5
      }, {
        type: "elem",
        elem: sub2.elem,
        marginLeft: makeEm(-slant)
      }, {
        type: "kern",
        size: sub2.kern
      }, {
        type: "elem",
        elem: base
      }, {
        type: "kern",
        size: sup2.kern
      }, {
        type: "elem",
        elem: sup2.elem,
        marginLeft: makeEm(slant)
      }, {
        type: "kern",
        size: options.fontMetrics().bigOpSpacing5
      }]
    }, options);
  } else if (sub2) {
    var top = base.height - baseShift;
    finalGroup = buildCommon.makeVList({
      positionType: "top",
      positionData: top,
      children: [{
        type: "kern",
        size: options.fontMetrics().bigOpSpacing5
      }, {
        type: "elem",
        elem: sub2.elem,
        marginLeft: makeEm(-slant)
      }, {
        type: "kern",
        size: sub2.kern
      }, {
        type: "elem",
        elem: base
      }]
    }, options);
  } else if (sup2) {
    var _bottom = base.depth + baseShift;
    finalGroup = buildCommon.makeVList({
      positionType: "bottom",
      positionData: _bottom,
      children: [{
        type: "elem",
        elem: base
      }, {
        type: "kern",
        size: sup2.kern
      }, {
        type: "elem",
        elem: sup2.elem,
        marginLeft: makeEm(slant)
      }, {
        type: "kern",
        size: options.fontMetrics().bigOpSpacing5
      }]
    }, options);
  } else {
    return base;
  }
  var parts = [finalGroup];
  if (sub2 && slant !== 0 && !subIsSingleCharacter) {
    var spacer = buildCommon.makeSpan(["mspace"], [], options);
    spacer.style.marginRight = makeEm(slant);
    parts.unshift(spacer);
  }
  return buildCommon.makeSpan(["mop", "op-limits"], parts, options);
};
var noSuccessor = ["\\smallint"];
var htmlBuilder$2 = (grp, options) => {
  var supGroup;
  var subGroup;
  var hasLimits = false;
  var group;
  if (grp.type === "supsub") {
    supGroup = grp.sup;
    subGroup = grp.sub;
    group = assertNodeType(grp.base, "op");
    hasLimits = true;
  } else {
    group = assertNodeType(grp, "op");
  }
  var style = options.style;
  var large = false;
  if (style.size === Style$1.DISPLAY.size && group.symbol && !utils2.contains(noSuccessor, group.name)) {
    large = true;
  }
  var base;
  if (group.symbol) {
    var fontName = large ? "Size2-Regular" : "Size1-Regular";
    var stash = "";
    if (group.name === "\\oiint" || group.name === "\\oiiint") {
      stash = group.name.slice(1);
      group.name = stash === "oiint" ? "\\iint" : "\\iiint";
    }
    base = buildCommon.makeSymbol(group.name, fontName, "math", options, ["mop", "op-symbol", large ? "large-op" : "small-op"]);
    if (stash.length > 0) {
      var italic = base.italic;
      var oval = buildCommon.staticSvg(stash + "Size" + (large ? "2" : "1"), options);
      base = buildCommon.makeVList({
        positionType: "individualShift",
        children: [{
          type: "elem",
          elem: base,
          shift: 0
        }, {
          type: "elem",
          elem: oval,
          shift: large ? 0.08 : 0
        }]
      }, options);
      group.name = "\\" + stash;
      base.classes.unshift("mop");
      base.italic = italic;
    }
  } else if (group.body) {
    var inner2 = buildExpression$1(group.body, options, true);
    if (inner2.length === 1 && inner2[0] instanceof SymbolNode) {
      base = inner2[0];
      base.classes[0] = "mop";
    } else {
      base = buildCommon.makeSpan(["mop"], inner2, options);
    }
  } else {
    var output = [];
    for (var i7 = 1; i7 < group.name.length; i7++) {
      output.push(buildCommon.mathsym(group.name[i7], group.mode, options));
    }
    base = buildCommon.makeSpan(["mop"], output, options);
  }
  var baseShift = 0;
  var slant = 0;
  if ((base instanceof SymbolNode || group.name === "\\oiint" || group.name === "\\oiiint") && !group.suppressBaseShift) {
    baseShift = (base.height - base.depth) / 2 - options.fontMetrics().axisHeight;
    slant = base.italic;
  }
  if (hasLimits) {
    return assembleSupSub(base, supGroup, subGroup, options, style, slant, baseShift);
  } else {
    if (baseShift) {
      base.style.position = "relative";
      base.style.top = makeEm(baseShift);
    }
    return base;
  }
};
var mathmlBuilder$1 = (group, options) => {
  var node;
  if (group.symbol) {
    node = new MathNode("mo", [makeText(group.name, group.mode)]);
    if (utils2.contains(noSuccessor, group.name)) {
      node.setAttribute("largeop", "false");
    }
  } else if (group.body) {
    node = new MathNode("mo", buildExpression2(group.body, options));
  } else {
    node = new MathNode("mi", [new TextNode(group.name.slice(1))]);
    var operator = new MathNode("mo", [makeText("\u2061", "text")]);
    if (group.parentIsSupSub) {
      node = new MathNode("mrow", [node, operator]);
    } else {
      node = newDocumentFragment([node, operator]);
    }
  }
  return node;
};
var singleCharBigOps = {
  "\u220F": "\\prod",
  "\u2210": "\\coprod",
  "\u2211": "\\sum",
  "\u22C0": "\\bigwedge",
  "\u22C1": "\\bigvee",
  "\u22C2": "\\bigcap",
  "\u22C3": "\\bigcup",
  "\u2A00": "\\bigodot",
  "\u2A01": "\\bigoplus",
  "\u2A02": "\\bigotimes",
  "\u2A04": "\\biguplus",
  "\u2A06": "\\bigsqcup"
};
defineFunction({
  type: "op",
  names: ["\\coprod", "\\bigvee", "\\bigwedge", "\\biguplus", "\\bigcap", "\\bigcup", "\\intop", "\\prod", "\\sum", "\\bigotimes", "\\bigoplus", "\\bigodot", "\\bigsqcup", "\\smallint", "\u220F", "\u2210", "\u2211", "\u22C0", "\u22C1", "\u22C2", "\u22C3", "\u2A00", "\u2A01", "\u2A02", "\u2A04", "\u2A06"],
  props: {
    numArgs: 0
  },
  handler: (_ref, args) => {
    var {
      parser,
      funcName
    } = _ref;
    var fName = funcName;
    if (fName.length === 1) {
      fName = singleCharBigOps[fName];
    }
    return {
      type: "op",
      mode: parser.mode,
      limits: true,
      parentIsSupSub: false,
      symbol: true,
      name: fName
    };
  },
  htmlBuilder: htmlBuilder$2,
  mathmlBuilder: mathmlBuilder$1
});
defineFunction({
  type: "op",
  names: ["\\mathop"],
  props: {
    numArgs: 1,
    primitive: true
  },
  handler: (_ref2, args) => {
    var {
      parser
    } = _ref2;
    var body = args[0];
    return {
      type: "op",
      mode: parser.mode,
      limits: false,
      parentIsSupSub: false,
      symbol: false,
      body: ordargument(body)
    };
  },
  htmlBuilder: htmlBuilder$2,
  mathmlBuilder: mathmlBuilder$1
});
var singleCharIntegrals = {
  "\u222B": "\\int",
  "\u222C": "\\iint",
  "\u222D": "\\iiint",
  "\u222E": "\\oint",
  "\u222F": "\\oiint",
  "\u2230": "\\oiiint"
};
defineFunction({
  type: "op",
  names: ["\\arcsin", "\\arccos", "\\arctan", "\\arctg", "\\arcctg", "\\arg", "\\ch", "\\cos", "\\cosec", "\\cosh", "\\cot", "\\cotg", "\\coth", "\\csc", "\\ctg", "\\cth", "\\deg", "\\dim", "\\exp", "\\hom", "\\ker", "\\lg", "\\ln", "\\log", "\\sec", "\\sin", "\\sinh", "\\sh", "\\tan", "\\tanh", "\\tg", "\\th"],
  props: {
    numArgs: 0
  },
  handler(_ref3) {
    var {
      parser,
      funcName
    } = _ref3;
    return {
      type: "op",
      mode: parser.mode,
      limits: false,
      parentIsSupSub: false,
      symbol: false,
      name: funcName
    };
  },
  htmlBuilder: htmlBuilder$2,
  mathmlBuilder: mathmlBuilder$1
});
defineFunction({
  type: "op",
  names: ["\\det", "\\gcd", "\\inf", "\\lim", "\\max", "\\min", "\\Pr", "\\sup"],
  props: {
    numArgs: 0
  },
  handler(_ref4) {
    var {
      parser,
      funcName
    } = _ref4;
    return {
      type: "op",
      mode: parser.mode,
      limits: true,
      parentIsSupSub: false,
      symbol: false,
      name: funcName
    };
  },
  htmlBuilder: htmlBuilder$2,
  mathmlBuilder: mathmlBuilder$1
});
defineFunction({
  type: "op",
  names: ["\\int", "\\iint", "\\iiint", "\\oint", "\\oiint", "\\oiiint", "\u222B", "\u222C", "\u222D", "\u222E", "\u222F", "\u2230"],
  props: {
    numArgs: 0
  },
  handler(_ref5) {
    var {
      parser,
      funcName
    } = _ref5;
    var fName = funcName;
    if (fName.length === 1) {
      fName = singleCharIntegrals[fName];
    }
    return {
      type: "op",
      mode: parser.mode,
      limits: false,
      parentIsSupSub: false,
      symbol: true,
      name: fName
    };
  },
  htmlBuilder: htmlBuilder$2,
  mathmlBuilder: mathmlBuilder$1
});
var htmlBuilder$1 = (grp, options) => {
  var supGroup;
  var subGroup;
  var hasLimits = false;
  var group;
  if (grp.type === "supsub") {
    supGroup = grp.sup;
    subGroup = grp.sub;
    group = assertNodeType(grp.base, "operatorname");
    hasLimits = true;
  } else {
    group = assertNodeType(grp, "operatorname");
  }
  var base;
  if (group.body.length > 0) {
    var body = group.body.map((child2) => {
      var childText = child2.text;
      if (typeof childText === "string") {
        return {
          type: "textord",
          mode: child2.mode,
          text: childText
        };
      } else {
        return child2;
      }
    });
    var expression = buildExpression$1(body, options.withFont("mathrm"), true);
    for (var i7 = 0; i7 < expression.length; i7++) {
      var child = expression[i7];
      if (child instanceof SymbolNode) {
        child.text = child.text.replace(/\u2212/, "-").replace(/\u2217/, "*");
      }
    }
    base = buildCommon.makeSpan(["mop"], expression, options);
  } else {
    base = buildCommon.makeSpan(["mop"], [], options);
  }
  if (hasLimits) {
    return assembleSupSub(base, supGroup, subGroup, options, options.style, 0, 0);
  } else {
    return base;
  }
};
var mathmlBuilder2 = (group, options) => {
  var expression = buildExpression2(group.body, options.withFont("mathrm"));
  var isAllString = true;
  for (var i7 = 0; i7 < expression.length; i7++) {
    var node = expression[i7];
    if (node instanceof mathMLTree.SpaceNode) ;
    else if (node instanceof mathMLTree.MathNode) {
      switch (node.type) {
        case "mi":
        case "mn":
        case "ms":
        case "mspace":
        case "mtext":
          break;
        // Do nothing yet.
        case "mo": {
          var child = node.children[0];
          if (node.children.length === 1 && child instanceof mathMLTree.TextNode) {
            child.text = child.text.replace(/\u2212/, "-").replace(/\u2217/, "*");
          } else {
            isAllString = false;
          }
          break;
        }
        default:
          isAllString = false;
      }
    } else {
      isAllString = false;
    }
  }
  if (isAllString) {
    var word = expression.map((node2) => node2.toText()).join("");
    expression = [new mathMLTree.TextNode(word)];
  }
  var identifier = new mathMLTree.MathNode("mi", expression);
  identifier.setAttribute("mathvariant", "normal");
  var operator = new mathMLTree.MathNode("mo", [makeText("\u2061", "text")]);
  if (group.parentIsSupSub) {
    return new mathMLTree.MathNode("mrow", [identifier, operator]);
  } else {
    return mathMLTree.newDocumentFragment([identifier, operator]);
  }
};
defineFunction({
  type: "operatorname",
  names: ["\\operatorname@", "\\operatornamewithlimits"],
  props: {
    numArgs: 1
  },
  handler: (_ref, args) => {
    var {
      parser,
      funcName
    } = _ref;
    var body = args[0];
    return {
      type: "operatorname",
      mode: parser.mode,
      body: ordargument(body),
      alwaysHandleSupSub: funcName === "\\operatornamewithlimits",
      limits: false,
      parentIsSupSub: false
    };
  },
  htmlBuilder: htmlBuilder$1,
  mathmlBuilder: mathmlBuilder2
});
defineMacro("\\operatorname", "\\@ifstar\\operatornamewithlimits\\operatorname@");
defineFunctionBuilders({
  type: "ordgroup",
  htmlBuilder(group, options) {
    if (group.semisimple) {
      return buildCommon.makeFragment(buildExpression$1(group.body, options, false));
    }
    return buildCommon.makeSpan(["mord"], buildExpression$1(group.body, options, true), options);
  },
  mathmlBuilder(group, options) {
    return buildExpressionRow(group.body, options, true);
  }
});
defineFunction({
  type: "overline",
  names: ["\\overline"],
  props: {
    numArgs: 1
  },
  handler(_ref, args) {
    var {
      parser
    } = _ref;
    var body = args[0];
    return {
      type: "overline",
      mode: parser.mode,
      body
    };
  },
  htmlBuilder(group, options) {
    var innerGroup = buildGroup$1(group.body, options.havingCrampedStyle());
    var line = buildCommon.makeLineSpan("overline-line", options);
    var defaultRuleThickness = options.fontMetrics().defaultRuleThickness;
    var vlist = buildCommon.makeVList({
      positionType: "firstBaseline",
      children: [{
        type: "elem",
        elem: innerGroup
      }, {
        type: "kern",
        size: 3 * defaultRuleThickness
      }, {
        type: "elem",
        elem: line
      }, {
        type: "kern",
        size: defaultRuleThickness
      }]
    }, options);
    return buildCommon.makeSpan(["mord", "overline"], [vlist], options);
  },
  mathmlBuilder(group, options) {
    var operator = new mathMLTree.MathNode("mo", [new mathMLTree.TextNode("\u203E")]);
    operator.setAttribute("stretchy", "true");
    var node = new mathMLTree.MathNode("mover", [buildGroup2(group.body, options), operator]);
    node.setAttribute("accent", "true");
    return node;
  }
});
defineFunction({
  type: "phantom",
  names: ["\\phantom"],
  props: {
    numArgs: 1,
    allowedInText: true
  },
  handler: (_ref, args) => {
    var {
      parser
    } = _ref;
    var body = args[0];
    return {
      type: "phantom",
      mode: parser.mode,
      body: ordargument(body)
    };
  },
  htmlBuilder: (group, options) => {
    var elements = buildExpression$1(group.body, options.withPhantom(), false);
    return buildCommon.makeFragment(elements);
  },
  mathmlBuilder: (group, options) => {
    var inner2 = buildExpression2(group.body, options);
    return new mathMLTree.MathNode("mphantom", inner2);
  }
});
defineFunction({
  type: "hphantom",
  names: ["\\hphantom"],
  props: {
    numArgs: 1,
    allowedInText: true
  },
  handler: (_ref2, args) => {
    var {
      parser
    } = _ref2;
    var body = args[0];
    return {
      type: "hphantom",
      mode: parser.mode,
      body
    };
  },
  htmlBuilder: (group, options) => {
    var node = buildCommon.makeSpan([], [buildGroup$1(group.body, options.withPhantom())]);
    node.height = 0;
    node.depth = 0;
    if (node.children) {
      for (var i7 = 0; i7 < node.children.length; i7++) {
        node.children[i7].height = 0;
        node.children[i7].depth = 0;
      }
    }
    node = buildCommon.makeVList({
      positionType: "firstBaseline",
      children: [{
        type: "elem",
        elem: node
      }]
    }, options);
    return buildCommon.makeSpan(["mord"], [node], options);
  },
  mathmlBuilder: (group, options) => {
    var inner2 = buildExpression2(ordargument(group.body), options);
    var phantom = new mathMLTree.MathNode("mphantom", inner2);
    var node = new mathMLTree.MathNode("mpadded", [phantom]);
    node.setAttribute("height", "0px");
    node.setAttribute("depth", "0px");
    return node;
  }
});
defineFunction({
  type: "vphantom",
  names: ["\\vphantom"],
  props: {
    numArgs: 1,
    allowedInText: true
  },
  handler: (_ref3, args) => {
    var {
      parser
    } = _ref3;
    var body = args[0];
    return {
      type: "vphantom",
      mode: parser.mode,
      body
    };
  },
  htmlBuilder: (group, options) => {
    var inner2 = buildCommon.makeSpan(["inner"], [buildGroup$1(group.body, options.withPhantom())]);
    var fix = buildCommon.makeSpan(["fix"], []);
    return buildCommon.makeSpan(["mord", "rlap"], [inner2, fix], options);
  },
  mathmlBuilder: (group, options) => {
    var inner2 = buildExpression2(ordargument(group.body), options);
    var phantom = new mathMLTree.MathNode("mphantom", inner2);
    var node = new mathMLTree.MathNode("mpadded", [phantom]);
    node.setAttribute("width", "0px");
    return node;
  }
});
defineFunction({
  type: "raisebox",
  names: ["\\raisebox"],
  props: {
    numArgs: 2,
    argTypes: ["size", "hbox"],
    allowedInText: true
  },
  handler(_ref, args) {
    var {
      parser
    } = _ref;
    var amount = assertNodeType(args[0], "size").value;
    var body = args[1];
    return {
      type: "raisebox",
      mode: parser.mode,
      dy: amount,
      body
    };
  },
  htmlBuilder(group, options) {
    var body = buildGroup$1(group.body, options);
    var dy = calculateSize(group.dy, options);
    return buildCommon.makeVList({
      positionType: "shift",
      positionData: -dy,
      children: [{
        type: "elem",
        elem: body
      }]
    }, options);
  },
  mathmlBuilder(group, options) {
    var node = new mathMLTree.MathNode("mpadded", [buildGroup2(group.body, options)]);
    var dy = group.dy.number + group.dy.unit;
    node.setAttribute("voffset", dy);
    return node;
  }
});
defineFunction({
  type: "internal",
  names: ["\\relax"],
  props: {
    numArgs: 0,
    allowedInText: true,
    allowedInArgument: true
  },
  handler(_ref) {
    var {
      parser
    } = _ref;
    return {
      type: "internal",
      mode: parser.mode
    };
  }
});
defineFunction({
  type: "rule",
  names: ["\\rule"],
  props: {
    numArgs: 2,
    numOptionalArgs: 1,
    allowedInText: true,
    allowedInMath: true,
    argTypes: ["size", "size", "size"]
  },
  handler(_ref, args, optArgs) {
    var {
      parser
    } = _ref;
    var shift = optArgs[0];
    var width = assertNodeType(args[0], "size");
    var height = assertNodeType(args[1], "size");
    return {
      type: "rule",
      mode: parser.mode,
      shift: shift && assertNodeType(shift, "size").value,
      width: width.value,
      height: height.value
    };
  },
  htmlBuilder(group, options) {
    var rule = buildCommon.makeSpan(["mord", "rule"], [], options);
    var width = calculateSize(group.width, options);
    var height = calculateSize(group.height, options);
    var shift = group.shift ? calculateSize(group.shift, options) : 0;
    rule.style.borderRightWidth = makeEm(width);
    rule.style.borderTopWidth = makeEm(height);
    rule.style.bottom = makeEm(shift);
    rule.width = width;
    rule.height = height + shift;
    rule.depth = -shift;
    rule.maxFontSize = height * 1.125 * options.sizeMultiplier;
    return rule;
  },
  mathmlBuilder(group, options) {
    var width = calculateSize(group.width, options);
    var height = calculateSize(group.height, options);
    var shift = group.shift ? calculateSize(group.shift, options) : 0;
    var color = options.color && options.getColor() || "black";
    var rule = new mathMLTree.MathNode("mspace");
    rule.setAttribute("mathbackground", color);
    rule.setAttribute("width", makeEm(width));
    rule.setAttribute("height", makeEm(height));
    var wrapper = new mathMLTree.MathNode("mpadded", [rule]);
    if (shift >= 0) {
      wrapper.setAttribute("height", makeEm(shift));
    } else {
      wrapper.setAttribute("height", makeEm(shift));
      wrapper.setAttribute("depth", makeEm(-shift));
    }
    wrapper.setAttribute("voffset", makeEm(shift));
    return wrapper;
  }
});
function sizingGroup(value, options, baseOptions) {
  var inner2 = buildExpression$1(value, options, false);
  var multiplier = options.sizeMultiplier / baseOptions.sizeMultiplier;
  for (var i7 = 0; i7 < inner2.length; i7++) {
    var pos = inner2[i7].classes.indexOf("sizing");
    if (pos < 0) {
      Array.prototype.push.apply(inner2[i7].classes, options.sizingClasses(baseOptions));
    } else if (inner2[i7].classes[pos + 1] === "reset-size" + options.size) {
      inner2[i7].classes[pos + 1] = "reset-size" + baseOptions.size;
    }
    inner2[i7].height *= multiplier;
    inner2[i7].depth *= multiplier;
  }
  return buildCommon.makeFragment(inner2);
}
var sizeFuncs = ["\\tiny", "\\sixptsize", "\\scriptsize", "\\footnotesize", "\\small", "\\normalsize", "\\large", "\\Large", "\\LARGE", "\\huge", "\\Huge"];
var htmlBuilder2 = (group, options) => {
  var newOptions = options.havingSize(group.size);
  return sizingGroup(group.body, newOptions, options);
};
defineFunction({
  type: "sizing",
  names: sizeFuncs,
  props: {
    numArgs: 0,
    allowedInText: true
  },
  handler: (_ref, args) => {
    var {
      breakOnTokenText,
      funcName,
      parser
    } = _ref;
    var body = parser.parseExpression(false, breakOnTokenText);
    return {
      type: "sizing",
      mode: parser.mode,
      // Figure out what size to use based on the list of functions above
      size: sizeFuncs.indexOf(funcName) + 1,
      body
    };
  },
  htmlBuilder: htmlBuilder2,
  mathmlBuilder: (group, options) => {
    var newOptions = options.havingSize(group.size);
    var inner2 = buildExpression2(group.body, newOptions);
    var node = new mathMLTree.MathNode("mstyle", inner2);
    node.setAttribute("mathsize", makeEm(newOptions.sizeMultiplier));
    return node;
  }
});
defineFunction({
  type: "smash",
  names: ["\\smash"],
  props: {
    numArgs: 1,
    numOptionalArgs: 1,
    allowedInText: true
  },
  handler: (_ref, args, optArgs) => {
    var {
      parser
    } = _ref;
    var smashHeight = false;
    var smashDepth = false;
    var tbArg = optArgs[0] && assertNodeType(optArgs[0], "ordgroup");
    if (tbArg) {
      var letter = "";
      for (var i7 = 0; i7 < tbArg.body.length; ++i7) {
        var node = tbArg.body[i7];
        letter = node.text;
        if (letter === "t") {
          smashHeight = true;
        } else if (letter === "b") {
          smashDepth = true;
        } else {
          smashHeight = false;
          smashDepth = false;
          break;
        }
      }
    } else {
      smashHeight = true;
      smashDepth = true;
    }
    var body = args[0];
    return {
      type: "smash",
      mode: parser.mode,
      body,
      smashHeight,
      smashDepth
    };
  },
  htmlBuilder: (group, options) => {
    var node = buildCommon.makeSpan([], [buildGroup$1(group.body, options)]);
    if (!group.smashHeight && !group.smashDepth) {
      return node;
    }
    if (group.smashHeight) {
      node.height = 0;
      if (node.children) {
        for (var i7 = 0; i7 < node.children.length; i7++) {
          node.children[i7].height = 0;
        }
      }
    }
    if (group.smashDepth) {
      node.depth = 0;
      if (node.children) {
        for (var _i = 0; _i < node.children.length; _i++) {
          node.children[_i].depth = 0;
        }
      }
    }
    var smashedNode = buildCommon.makeVList({
      positionType: "firstBaseline",
      children: [{
        type: "elem",
        elem: node
      }]
    }, options);
    return buildCommon.makeSpan(["mord"], [smashedNode], options);
  },
  mathmlBuilder: (group, options) => {
    var node = new mathMLTree.MathNode("mpadded", [buildGroup2(group.body, options)]);
    if (group.smashHeight) {
      node.setAttribute("height", "0px");
    }
    if (group.smashDepth) {
      node.setAttribute("depth", "0px");
    }
    return node;
  }
});
defineFunction({
  type: "sqrt",
  names: ["\\sqrt"],
  props: {
    numArgs: 1,
    numOptionalArgs: 1
  },
  handler(_ref, args, optArgs) {
    var {
      parser
    } = _ref;
    var index = optArgs[0];
    var body = args[0];
    return {
      type: "sqrt",
      mode: parser.mode,
      body,
      index
    };
  },
  htmlBuilder(group, options) {
    var inner2 = buildGroup$1(group.body, options.havingCrampedStyle());
    if (inner2.height === 0) {
      inner2.height = options.fontMetrics().xHeight;
    }
    inner2 = buildCommon.wrapFragment(inner2, options);
    var metrics = options.fontMetrics();
    var theta = metrics.defaultRuleThickness;
    var phi = theta;
    if (options.style.id < Style$1.TEXT.id) {
      phi = options.fontMetrics().xHeight;
    }
    var lineClearance = theta + phi / 4;
    var minDelimiterHeight = inner2.height + inner2.depth + lineClearance + theta;
    var {
      span: img,
      ruleWidth,
      advanceWidth
    } = delimiter.sqrtImage(minDelimiterHeight, options);
    var delimDepth = img.height - ruleWidth;
    if (delimDepth > inner2.height + inner2.depth + lineClearance) {
      lineClearance = (lineClearance + delimDepth - inner2.height - inner2.depth) / 2;
    }
    var imgShift = img.height - inner2.height - lineClearance - ruleWidth;
    inner2.style.paddingLeft = makeEm(advanceWidth);
    var body = buildCommon.makeVList({
      positionType: "firstBaseline",
      children: [{
        type: "elem",
        elem: inner2,
        wrapperClasses: ["svg-align"]
      }, {
        type: "kern",
        size: -(inner2.height + imgShift)
      }, {
        type: "elem",
        elem: img
      }, {
        type: "kern",
        size: ruleWidth
      }]
    }, options);
    if (!group.index) {
      return buildCommon.makeSpan(["mord", "sqrt"], [body], options);
    } else {
      var newOptions = options.havingStyle(Style$1.SCRIPTSCRIPT);
      var rootm = buildGroup$1(group.index, newOptions, options);
      var toShift = 0.6 * (body.height - body.depth);
      var rootVList = buildCommon.makeVList({
        positionType: "shift",
        positionData: -toShift,
        children: [{
          type: "elem",
          elem: rootm
        }]
      }, options);
      var rootVListWrap = buildCommon.makeSpan(["root"], [rootVList]);
      return buildCommon.makeSpan(["mord", "sqrt"], [rootVListWrap, body], options);
    }
  },
  mathmlBuilder(group, options) {
    var {
      body,
      index
    } = group;
    return index ? new mathMLTree.MathNode("mroot", [buildGroup2(body, options), buildGroup2(index, options)]) : new mathMLTree.MathNode("msqrt", [buildGroup2(body, options)]);
  }
});
var styleMap = {
  "display": Style$1.DISPLAY,
  "text": Style$1.TEXT,
  "script": Style$1.SCRIPT,
  "scriptscript": Style$1.SCRIPTSCRIPT
};
defineFunction({
  type: "styling",
  names: ["\\displaystyle", "\\textstyle", "\\scriptstyle", "\\scriptscriptstyle"],
  props: {
    numArgs: 0,
    allowedInText: true,
    primitive: true
  },
  handler(_ref, args) {
    var {
      breakOnTokenText,
      funcName,
      parser
    } = _ref;
    var body = parser.parseExpression(true, breakOnTokenText);
    var style = funcName.slice(1, funcName.length - 5);
    return {
      type: "styling",
      mode: parser.mode,
      // Figure out what style to use by pulling out the style from
      // the function name
      style,
      body
    };
  },
  htmlBuilder(group, options) {
    var newStyle = styleMap[group.style];
    var newOptions = options.havingStyle(newStyle).withFont("");
    return sizingGroup(group.body, newOptions, options);
  },
  mathmlBuilder(group, options) {
    var newStyle = styleMap[group.style];
    var newOptions = options.havingStyle(newStyle);
    var inner2 = buildExpression2(group.body, newOptions);
    var node = new mathMLTree.MathNode("mstyle", inner2);
    var styleAttributes = {
      "display": ["0", "true"],
      "text": ["0", "false"],
      "script": ["1", "false"],
      "scriptscript": ["2", "false"]
    };
    var attr = styleAttributes[group.style];
    node.setAttribute("scriptlevel", attr[0]);
    node.setAttribute("displaystyle", attr[1]);
    return node;
  }
});
var htmlBuilderDelegate = function htmlBuilderDelegate2(group, options) {
  var base = group.base;
  if (!base) {
    return null;
  } else if (base.type === "op") {
    var delegate = base.limits && (options.style.size === Style$1.DISPLAY.size || base.alwaysHandleSupSub);
    return delegate ? htmlBuilder$2 : null;
  } else if (base.type === "operatorname") {
    var _delegate = base.alwaysHandleSupSub && (options.style.size === Style$1.DISPLAY.size || base.limits);
    return _delegate ? htmlBuilder$1 : null;
  } else if (base.type === "accent") {
    return utils2.isCharacterBox(base.base) ? htmlBuilder$a : null;
  } else if (base.type === "horizBrace") {
    var isSup = !group.sub;
    return isSup === base.isOver ? htmlBuilder$3 : null;
  } else {
    return null;
  }
};
defineFunctionBuilders({
  type: "supsub",
  htmlBuilder(group, options) {
    var builderDelegate = htmlBuilderDelegate(group, options);
    if (builderDelegate) {
      return builderDelegate(group, options);
    }
    var {
      base: valueBase,
      sup: valueSup,
      sub: valueSub
    } = group;
    var base = buildGroup$1(valueBase, options);
    var supm;
    var subm;
    var metrics = options.fontMetrics();
    var supShift = 0;
    var subShift = 0;
    var isCharacterBox3 = valueBase && utils2.isCharacterBox(valueBase);
    if (valueSup) {
      var newOptions = options.havingStyle(options.style.sup());
      supm = buildGroup$1(valueSup, newOptions, options);
      if (!isCharacterBox3) {
        supShift = base.height - newOptions.fontMetrics().supDrop * newOptions.sizeMultiplier / options.sizeMultiplier;
      }
    }
    if (valueSub) {
      var _newOptions = options.havingStyle(options.style.sub());
      subm = buildGroup$1(valueSub, _newOptions, options);
      if (!isCharacterBox3) {
        subShift = base.depth + _newOptions.fontMetrics().subDrop * _newOptions.sizeMultiplier / options.sizeMultiplier;
      }
    }
    var minSupShift;
    if (options.style === Style$1.DISPLAY) {
      minSupShift = metrics.sup1;
    } else if (options.style.cramped) {
      minSupShift = metrics.sup3;
    } else {
      minSupShift = metrics.sup2;
    }
    var multiplier = options.sizeMultiplier;
    var marginRight = makeEm(0.5 / metrics.ptPerEm / multiplier);
    var marginLeft = null;
    if (subm) {
      var isOiint = group.base && group.base.type === "op" && group.base.name && (group.base.name === "\\oiint" || group.base.name === "\\oiiint");
      if (base instanceof SymbolNode || isOiint) {
        marginLeft = makeEm(-base.italic);
      }
    }
    var supsub;
    if (supm && subm) {
      supShift = Math.max(supShift, minSupShift, supm.depth + 0.25 * metrics.xHeight);
      subShift = Math.max(subShift, metrics.sub2);
      var ruleWidth = metrics.defaultRuleThickness;
      var maxWidth = 4 * ruleWidth;
      if (supShift - supm.depth - (subm.height - subShift) < maxWidth) {
        subShift = maxWidth - (supShift - supm.depth) + subm.height;
        var psi = 0.8 * metrics.xHeight - (supShift - supm.depth);
        if (psi > 0) {
          supShift += psi;
          subShift -= psi;
        }
      }
      var vlistElem = [{
        type: "elem",
        elem: subm,
        shift: subShift,
        marginRight,
        marginLeft
      }, {
        type: "elem",
        elem: supm,
        shift: -supShift,
        marginRight
      }];
      supsub = buildCommon.makeVList({
        positionType: "individualShift",
        children: vlistElem
      }, options);
    } else if (subm) {
      subShift = Math.max(subShift, metrics.sub1, subm.height - 0.8 * metrics.xHeight);
      var _vlistElem = [{
        type: "elem",
        elem: subm,
        marginLeft,
        marginRight
      }];
      supsub = buildCommon.makeVList({
        positionType: "shift",
        positionData: subShift,
        children: _vlistElem
      }, options);
    } else if (supm) {
      supShift = Math.max(supShift, minSupShift, supm.depth + 0.25 * metrics.xHeight);
      supsub = buildCommon.makeVList({
        positionType: "shift",
        positionData: -supShift,
        children: [{
          type: "elem",
          elem: supm,
          marginRight
        }]
      }, options);
    } else {
      throw new Error("supsub must have either sup or sub.");
    }
    var mclass = getTypeOfDomTree(base, "right") || "mord";
    return buildCommon.makeSpan([mclass], [base, buildCommon.makeSpan(["msupsub"], [supsub])], options);
  },
  mathmlBuilder(group, options) {
    var isBrace = false;
    var isOver;
    var isSup;
    if (group.base && group.base.type === "horizBrace") {
      isSup = !!group.sup;
      if (isSup === group.base.isOver) {
        isBrace = true;
        isOver = group.base.isOver;
      }
    }
    if (group.base && (group.base.type === "op" || group.base.type === "operatorname")) {
      group.base.parentIsSupSub = true;
    }
    var children = [buildGroup2(group.base, options)];
    if (group.sub) {
      children.push(buildGroup2(group.sub, options));
    }
    if (group.sup) {
      children.push(buildGroup2(group.sup, options));
    }
    var nodeType;
    if (isBrace) {
      nodeType = isOver ? "mover" : "munder";
    } else if (!group.sub) {
      var base = group.base;
      if (base && base.type === "op" && base.limits && (options.style === Style$1.DISPLAY || base.alwaysHandleSupSub)) {
        nodeType = "mover";
      } else if (base && base.type === "operatorname" && base.alwaysHandleSupSub && (base.limits || options.style === Style$1.DISPLAY)) {
        nodeType = "mover";
      } else {
        nodeType = "msup";
      }
    } else if (!group.sup) {
      var _base = group.base;
      if (_base && _base.type === "op" && _base.limits && (options.style === Style$1.DISPLAY || _base.alwaysHandleSupSub)) {
        nodeType = "munder";
      } else if (_base && _base.type === "operatorname" && _base.alwaysHandleSupSub && (_base.limits || options.style === Style$1.DISPLAY)) {
        nodeType = "munder";
      } else {
        nodeType = "msub";
      }
    } else {
      var _base2 = group.base;
      if (_base2 && _base2.type === "op" && _base2.limits && options.style === Style$1.DISPLAY) {
        nodeType = "munderover";
      } else if (_base2 && _base2.type === "operatorname" && _base2.alwaysHandleSupSub && (options.style === Style$1.DISPLAY || _base2.limits)) {
        nodeType = "munderover";
      } else {
        nodeType = "msubsup";
      }
    }
    return new mathMLTree.MathNode(nodeType, children);
  }
});
defineFunctionBuilders({
  type: "atom",
  htmlBuilder(group, options) {
    return buildCommon.mathsym(group.text, group.mode, options, ["m" + group.family]);
  },
  mathmlBuilder(group, options) {
    var node = new mathMLTree.MathNode("mo", [makeText(group.text, group.mode)]);
    if (group.family === "bin") {
      var variant = getVariant(group, options);
      if (variant === "bold-italic") {
        node.setAttribute("mathvariant", variant);
      }
    } else if (group.family === "punct") {
      node.setAttribute("separator", "true");
    } else if (group.family === "open" || group.family === "close") {
      node.setAttribute("stretchy", "false");
    }
    return node;
  }
});
var defaultVariant = {
  "mi": "italic",
  "mn": "normal",
  "mtext": "normal"
};
defineFunctionBuilders({
  type: "mathord",
  htmlBuilder(group, options) {
    return buildCommon.makeOrd(group, options, "mathord");
  },
  mathmlBuilder(group, options) {
    var node = new mathMLTree.MathNode("mi", [makeText(group.text, group.mode, options)]);
    var variant = getVariant(group, options) || "italic";
    if (variant !== defaultVariant[node.type]) {
      node.setAttribute("mathvariant", variant);
    }
    return node;
  }
});
defineFunctionBuilders({
  type: "textord",
  htmlBuilder(group, options) {
    return buildCommon.makeOrd(group, options, "textord");
  },
  mathmlBuilder(group, options) {
    var text3 = makeText(group.text, group.mode, options);
    var variant = getVariant(group, options) || "normal";
    var node;
    if (group.mode === "text") {
      node = new mathMLTree.MathNode("mtext", [text3]);
    } else if (/[0-9]/.test(group.text)) {
      node = new mathMLTree.MathNode("mn", [text3]);
    } else if (group.text === "\\prime") {
      node = new mathMLTree.MathNode("mo", [text3]);
    } else {
      node = new mathMLTree.MathNode("mi", [text3]);
    }
    if (variant !== defaultVariant[node.type]) {
      node.setAttribute("mathvariant", variant);
    }
    return node;
  }
});
var cssSpace = {
  "\\nobreak": "nobreak",
  "\\allowbreak": "allowbreak"
};
var regularSpace = {
  " ": {},
  "\\ ": {},
  "~": {
    className: "nobreak"
  },
  "\\space": {},
  "\\nobreakspace": {
    className: "nobreak"
  }
};
defineFunctionBuilders({
  type: "spacing",
  htmlBuilder(group, options) {
    if (regularSpace.hasOwnProperty(group.text)) {
      var className = regularSpace[group.text].className || "";
      if (group.mode === "text") {
        var ord = buildCommon.makeOrd(group, options, "textord");
        ord.classes.push(className);
        return ord;
      } else {
        return buildCommon.makeSpan(["mspace", className], [buildCommon.mathsym(group.text, group.mode, options)], options);
      }
    } else if (cssSpace.hasOwnProperty(group.text)) {
      return buildCommon.makeSpan(["mspace", cssSpace[group.text]], [], options);
    } else {
      throw new ParseError('Unknown type of space "' + group.text + '"');
    }
  },
  mathmlBuilder(group, options) {
    var node;
    if (regularSpace.hasOwnProperty(group.text)) {
      node = new mathMLTree.MathNode("mtext", [new mathMLTree.TextNode("\xA0")]);
    } else if (cssSpace.hasOwnProperty(group.text)) {
      return new mathMLTree.MathNode("mspace");
    } else {
      throw new ParseError('Unknown type of space "' + group.text + '"');
    }
    return node;
  }
});
var pad = () => {
  var padNode = new mathMLTree.MathNode("mtd", []);
  padNode.setAttribute("width", "50%");
  return padNode;
};
defineFunctionBuilders({
  type: "tag",
  mathmlBuilder(group, options) {
    var table = new mathMLTree.MathNode("mtable", [new mathMLTree.MathNode("mtr", [pad(), new mathMLTree.MathNode("mtd", [buildExpressionRow(group.body, options)]), pad(), new mathMLTree.MathNode("mtd", [buildExpressionRow(group.tag, options)])])]);
    table.setAttribute("width", "100%");
    return table;
  }
});
var textFontFamilies = {
  "\\text": void 0,
  "\\textrm": "textrm",
  "\\textsf": "textsf",
  "\\texttt": "texttt",
  "\\textnormal": "textrm"
};
var textFontWeights = {
  "\\textbf": "textbf",
  "\\textmd": "textmd"
};
var textFontShapes = {
  "\\textit": "textit",
  "\\textup": "textup"
};
var optionsWithFont = (group, options) => {
  var font = group.font;
  if (!font) {
    return options;
  } else if (textFontFamilies[font]) {
    return options.withTextFontFamily(textFontFamilies[font]);
  } else if (textFontWeights[font]) {
    return options.withTextFontWeight(textFontWeights[font]);
  } else if (font === "\\emph") {
    return options.fontShape === "textit" ? options.withTextFontShape("textup") : options.withTextFontShape("textit");
  }
  return options.withTextFontShape(textFontShapes[font]);
};
defineFunction({
  type: "text",
  names: [
    // Font families
    "\\text",
    "\\textrm",
    "\\textsf",
    "\\texttt",
    "\\textnormal",
    // Font weights
    "\\textbf",
    "\\textmd",
    // Font Shapes
    "\\textit",
    "\\textup",
    "\\emph"
  ],
  props: {
    numArgs: 1,
    argTypes: ["text"],
    allowedInArgument: true,
    allowedInText: true
  },
  handler(_ref, args) {
    var {
      parser,
      funcName
    } = _ref;
    var body = args[0];
    return {
      type: "text",
      mode: parser.mode,
      body: ordargument(body),
      font: funcName
    };
  },
  htmlBuilder(group, options) {
    var newOptions = optionsWithFont(group, options);
    var inner2 = buildExpression$1(group.body, newOptions, true);
    return buildCommon.makeSpan(["mord", "text"], inner2, newOptions);
  },
  mathmlBuilder(group, options) {
    var newOptions = optionsWithFont(group, options);
    return buildExpressionRow(group.body, newOptions);
  }
});
defineFunction({
  type: "underline",
  names: ["\\underline"],
  props: {
    numArgs: 1,
    allowedInText: true
  },
  handler(_ref, args) {
    var {
      parser
    } = _ref;
    return {
      type: "underline",
      mode: parser.mode,
      body: args[0]
    };
  },
  htmlBuilder(group, options) {
    var innerGroup = buildGroup$1(group.body, options);
    var line = buildCommon.makeLineSpan("underline-line", options);
    var defaultRuleThickness = options.fontMetrics().defaultRuleThickness;
    var vlist = buildCommon.makeVList({
      positionType: "top",
      positionData: innerGroup.height,
      children: [{
        type: "kern",
        size: defaultRuleThickness
      }, {
        type: "elem",
        elem: line
      }, {
        type: "kern",
        size: 3 * defaultRuleThickness
      }, {
        type: "elem",
        elem: innerGroup
      }]
    }, options);
    return buildCommon.makeSpan(["mord", "underline"], [vlist], options);
  },
  mathmlBuilder(group, options) {
    var operator = new mathMLTree.MathNode("mo", [new mathMLTree.TextNode("\u203E")]);
    operator.setAttribute("stretchy", "true");
    var node = new mathMLTree.MathNode("munder", [buildGroup2(group.body, options), operator]);
    node.setAttribute("accentunder", "true");
    return node;
  }
});
defineFunction({
  type: "vcenter",
  names: ["\\vcenter"],
  props: {
    numArgs: 1,
    argTypes: ["original"],
    // In LaTeX, \vcenter can act only on a box.
    allowedInText: false
  },
  handler(_ref, args) {
    var {
      parser
    } = _ref;
    return {
      type: "vcenter",
      mode: parser.mode,
      body: args[0]
    };
  },
  htmlBuilder(group, options) {
    var body = buildGroup$1(group.body, options);
    var axisHeight = options.fontMetrics().axisHeight;
    var dy = 0.5 * (body.height - axisHeight - (body.depth + axisHeight));
    return buildCommon.makeVList({
      positionType: "shift",
      positionData: dy,
      children: [{
        type: "elem",
        elem: body
      }]
    }, options);
  },
  mathmlBuilder(group, options) {
    return new mathMLTree.MathNode("mpadded", [buildGroup2(group.body, options)], ["vcenter"]);
  }
});
defineFunction({
  type: "verb",
  names: ["\\verb"],
  props: {
    numArgs: 0,
    allowedInText: true
  },
  handler(context, args, optArgs) {
    throw new ParseError("\\verb ended by end of line instead of matching delimiter");
  },
  htmlBuilder(group, options) {
    var text3 = makeVerb(group);
    var body = [];
    var newOptions = options.havingStyle(options.style.text());
    for (var i7 = 0; i7 < text3.length; i7++) {
      var c6 = text3[i7];
      if (c6 === "~") {
        c6 = "\\textasciitilde";
      }
      body.push(buildCommon.makeSymbol(c6, "Typewriter-Regular", group.mode, newOptions, ["mord", "texttt"]));
    }
    return buildCommon.makeSpan(["mord", "text"].concat(newOptions.sizingClasses(options)), buildCommon.tryCombineChars(body), newOptions);
  },
  mathmlBuilder(group, options) {
    var text3 = new mathMLTree.TextNode(makeVerb(group));
    var node = new mathMLTree.MathNode("mtext", [text3]);
    node.setAttribute("mathvariant", "monospace");
    return node;
  }
});
var makeVerb = (group) => group.body.replace(/ /g, group.star ? "\u2423" : "\xA0");
var functions = _functions;
var spaceRegexString = "[ \r\n	]";
var controlWordRegexString = "\\\\[a-zA-Z@]+";
var controlSymbolRegexString = "\\\\[^\uD800-\uDFFF]";
var controlWordWhitespaceRegexString = "(" + controlWordRegexString + ")" + spaceRegexString + "*";
var controlSpaceRegexString = "\\\\(\n|[ \r	]+\n?)[ \r	]*";
var combiningDiacriticalMarkString = "[\u0300-\u036F]";
var combiningDiacriticalMarksEndRegex = new RegExp(combiningDiacriticalMarkString + "+$");
var tokenRegexString = "(" + spaceRegexString + "+)|" + // whitespace
(controlSpaceRegexString + "|") + // \whitespace
"([!-\\[\\]-\u2027\u202A-\uD7FF\uF900-\uFFFF]" + // single codepoint
(combiningDiacriticalMarkString + "*") + // ...plus accents
"|[\uD800-\uDBFF][\uDC00-\uDFFF]" + // surrogate pair
(combiningDiacriticalMarkString + "*") + // ...plus accents
"|\\\\verb\\*([^]).*?\\4|\\\\verb([^*a-zA-Z]).*?\\5" + // \verb unstarred
("|" + controlWordWhitespaceRegexString) + // \macroName + spaces
("|" + controlSymbolRegexString + ")");
var Lexer = class {
  // Category codes. The lexer only supports comment characters (14) for now.
  // MacroExpander additionally distinguishes active (13).
  constructor(input, settings) {
    this.input = void 0;
    this.settings = void 0;
    this.tokenRegex = void 0;
    this.catcodes = void 0;
    this.input = input;
    this.settings = settings;
    this.tokenRegex = new RegExp(tokenRegexString, "g");
    this.catcodes = {
      "%": 14,
      // comment character
      "~": 13
      // active character
    };
  }
  setCatcode(char, code) {
    this.catcodes[char] = code;
  }
  /**
   * This function lexes a single token.
   */
  lex() {
    var input = this.input;
    var pos = this.tokenRegex.lastIndex;
    if (pos === input.length) {
      return new Token("EOF", new SourceLocation(this, pos, pos));
    }
    var match2 = this.tokenRegex.exec(input);
    if (match2 === null || match2.index !== pos) {
      throw new ParseError("Unexpected character: '" + input[pos] + "'", new Token(input[pos], new SourceLocation(this, pos, pos + 1)));
    }
    var text3 = match2[6] || match2[3] || (match2[2] ? "\\ " : " ");
    if (this.catcodes[text3] === 14) {
      var nlIndex = input.indexOf("\n", this.tokenRegex.lastIndex);
      if (nlIndex === -1) {
        this.tokenRegex.lastIndex = input.length;
        this.settings.reportNonstrict("commentAtEnd", "% comment has no terminating newline; LaTeX would fail because of commenting the end of math mode (e.g. $)");
      } else {
        this.tokenRegex.lastIndex = nlIndex + 1;
      }
      return this.lex();
    }
    return new Token(text3, new SourceLocation(this, pos, this.tokenRegex.lastIndex));
  }
};
var Namespace = class {
  /**
   * Both arguments are optional.  The first argument is an object of
   * built-in mappings which never change.  The second argument is an object
   * of initial (global-level) mappings, which will constantly change
   * according to any global/top-level `set`s done.
   */
  constructor(builtins, globalMacros) {
    if (builtins === void 0) {
      builtins = {};
    }
    if (globalMacros === void 0) {
      globalMacros = {};
    }
    this.current = void 0;
    this.builtins = void 0;
    this.undefStack = void 0;
    this.current = globalMacros;
    this.builtins = builtins;
    this.undefStack = [];
  }
  /**
   * Start a new nested group, affecting future local `set`s.
   */
  beginGroup() {
    this.undefStack.push({});
  }
  /**
   * End current nested group, restoring values before the group began.
   */
  endGroup() {
    if (this.undefStack.length === 0) {
      throw new ParseError("Unbalanced namespace destruction: attempt to pop global namespace; please report this as a bug");
    }
    var undefs = this.undefStack.pop();
    for (var undef in undefs) {
      if (undefs.hasOwnProperty(undef)) {
        if (undefs[undef] == null) {
          delete this.current[undef];
        } else {
          this.current[undef] = undefs[undef];
        }
      }
    }
  }
  /**
   * Ends all currently nested groups (if any), restoring values before the
   * groups began.  Useful in case of an error in the middle of parsing.
   */
  endGroups() {
    while (this.undefStack.length > 0) {
      this.endGroup();
    }
  }
  /**
   * Detect whether `name` has a definition.  Equivalent to
   * `get(name) != null`.
   */
  has(name) {
    return this.current.hasOwnProperty(name) || this.builtins.hasOwnProperty(name);
  }
  /**
   * Get the current value of a name, or `undefined` if there is no value.
   *
   * Note: Do not use `if (namespace.get(...))` to detect whether a macro
   * is defined, as the definition may be the empty string which evaluates
   * to `false` in JavaScript.  Use `if (namespace.get(...) != null)` or
   * `if (namespace.has(...))`.
   */
  get(name) {
    if (this.current.hasOwnProperty(name)) {
      return this.current[name];
    } else {
      return this.builtins[name];
    }
  }
  /**
   * Set the current value of a name, and optionally set it globally too.
   * Local set() sets the current value and (when appropriate) adds an undo
   * operation to the undo stack.  Global set() may change the undo
   * operation at every level, so takes time linear in their number.
   * A value of undefined means to delete existing definitions.
   */
  set(name, value, global2) {
    if (global2 === void 0) {
      global2 = false;
    }
    if (global2) {
      for (var i7 = 0; i7 < this.undefStack.length; i7++) {
        delete this.undefStack[i7][name];
      }
      if (this.undefStack.length > 0) {
        this.undefStack[this.undefStack.length - 1][name] = value;
      }
    } else {
      var top = this.undefStack[this.undefStack.length - 1];
      if (top && !top.hasOwnProperty(name)) {
        top[name] = this.current[name];
      }
    }
    if (value == null) {
      delete this.current[name];
    } else {
      this.current[name] = value;
    }
  }
};
var macros = _macros;
defineMacro("\\noexpand", function(context) {
  var t6 = context.popToken();
  if (context.isExpandable(t6.text)) {
    t6.noexpand = true;
    t6.treatAsRelax = true;
  }
  return {
    tokens: [t6],
    numArgs: 0
  };
});
defineMacro("\\expandafter", function(context) {
  var t6 = context.popToken();
  context.expandOnce(true);
  return {
    tokens: [t6],
    numArgs: 0
  };
});
defineMacro("\\@firstoftwo", function(context) {
  var args = context.consumeArgs(2);
  return {
    tokens: args[0],
    numArgs: 0
  };
});
defineMacro("\\@secondoftwo", function(context) {
  var args = context.consumeArgs(2);
  return {
    tokens: args[1],
    numArgs: 0
  };
});
defineMacro("\\@ifnextchar", function(context) {
  var args = context.consumeArgs(3);
  context.consumeSpaces();
  var nextToken = context.future();
  if (args[0].length === 1 && args[0][0].text === nextToken.text) {
    return {
      tokens: args[1],
      numArgs: 0
    };
  } else {
    return {
      tokens: args[2],
      numArgs: 0
    };
  }
});
defineMacro("\\@ifstar", "\\@ifnextchar *{\\@firstoftwo{#1}}");
defineMacro("\\TextOrMath", function(context) {
  var args = context.consumeArgs(2);
  if (context.mode === "text") {
    return {
      tokens: args[0],
      numArgs: 0
    };
  } else {
    return {
      tokens: args[1],
      numArgs: 0
    };
  }
});
var digitToNumber = {
  "0": 0,
  "1": 1,
  "2": 2,
  "3": 3,
  "4": 4,
  "5": 5,
  "6": 6,
  "7": 7,
  "8": 8,
  "9": 9,
  "a": 10,
  "A": 10,
  "b": 11,
  "B": 11,
  "c": 12,
  "C": 12,
  "d": 13,
  "D": 13,
  "e": 14,
  "E": 14,
  "f": 15,
  "F": 15
};
defineMacro("\\char", function(context) {
  var token = context.popToken();
  var base;
  var number = "";
  if (token.text === "'") {
    base = 8;
    token = context.popToken();
  } else if (token.text === '"') {
    base = 16;
    token = context.popToken();
  } else if (token.text === "`") {
    token = context.popToken();
    if (token.text[0] === "\\") {
      number = token.text.charCodeAt(1);
    } else if (token.text === "EOF") {
      throw new ParseError("\\char` missing argument");
    } else {
      number = token.text.charCodeAt(0);
    }
  } else {
    base = 10;
  }
  if (base) {
    number = digitToNumber[token.text];
    if (number == null || number >= base) {
      throw new ParseError("Invalid base-" + base + " digit " + token.text);
    }
    var digit;
    while ((digit = digitToNumber[context.future().text]) != null && digit < base) {
      number *= base;
      number += digit;
      context.popToken();
    }
  }
  return "\\@char{" + number + "}";
});
var newcommand = (context, existsOK, nonexistsOK, skipIfExists) => {
  var arg = context.consumeArg().tokens;
  if (arg.length !== 1) {
    throw new ParseError("\\newcommand's first argument must be a macro name");
  }
  var name = arg[0].text;
  var exists = context.isDefined(name);
  if (exists && !existsOK) {
    throw new ParseError("\\newcommand{" + name + "} attempting to redefine " + (name + "; use \\renewcommand"));
  }
  if (!exists && !nonexistsOK) {
    throw new ParseError("\\renewcommand{" + name + "} when command " + name + " does not yet exist; use \\newcommand");
  }
  var numArgs = 0;
  arg = context.consumeArg().tokens;
  if (arg.length === 1 && arg[0].text === "[") {
    var argText = "";
    var token = context.expandNextToken();
    while (token.text !== "]" && token.text !== "EOF") {
      argText += token.text;
      token = context.expandNextToken();
    }
    if (!argText.match(/^\s*[0-9]+\s*$/)) {
      throw new ParseError("Invalid number of arguments: " + argText);
    }
    numArgs = parseInt(argText);
    arg = context.consumeArg().tokens;
  }
  if (!(exists && skipIfExists)) {
    context.macros.set(name, {
      tokens: arg,
      numArgs
    });
  }
  return "";
};
defineMacro("\\newcommand", (context) => newcommand(context, false, true, false));
defineMacro("\\renewcommand", (context) => newcommand(context, true, false, false));
defineMacro("\\providecommand", (context) => newcommand(context, true, true, true));
defineMacro("\\message", (context) => {
  var arg = context.consumeArgs(1)[0];
  console.log(arg.reverse().map((token) => token.text).join(""));
  return "";
});
defineMacro("\\errmessage", (context) => {
  var arg = context.consumeArgs(1)[0];
  console.error(arg.reverse().map((token) => token.text).join(""));
  return "";
});
defineMacro("\\show", (context) => {
  var tok = context.popToken();
  var name = tok.text;
  console.log(tok, context.macros.get(name), functions[name], symbols.math[name], symbols.text[name]);
  return "";
});
defineMacro("\\bgroup", "{");
defineMacro("\\egroup", "}");
defineMacro("~", "\\nobreakspace");
defineMacro("\\lq", "`");
defineMacro("\\rq", "'");
defineMacro("\\aa", "\\r a");
defineMacro("\\AA", "\\r A");
defineMacro("\\textcopyright", "\\html@mathml{\\textcircled{c}}{\\char`\xA9}");
defineMacro("\\copyright", "\\TextOrMath{\\textcopyright}{\\text{\\textcopyright}}");
defineMacro("\\textregistered", "\\html@mathml{\\textcircled{\\scriptsize R}}{\\char`\xAE}");
defineMacro("\u212C", "\\mathscr{B}");
defineMacro("\u2130", "\\mathscr{E}");
defineMacro("\u2131", "\\mathscr{F}");
defineMacro("\u210B", "\\mathscr{H}");
defineMacro("\u2110", "\\mathscr{I}");
defineMacro("\u2112", "\\mathscr{L}");
defineMacro("\u2133", "\\mathscr{M}");
defineMacro("\u211B", "\\mathscr{R}");
defineMacro("\u212D", "\\mathfrak{C}");
defineMacro("\u210C", "\\mathfrak{H}");
defineMacro("\u2128", "\\mathfrak{Z}");
defineMacro("\\Bbbk", "\\Bbb{k}");
defineMacro("\xB7", "\\cdotp");
defineMacro("\\llap", "\\mathllap{\\textrm{#1}}");
defineMacro("\\rlap", "\\mathrlap{\\textrm{#1}}");
defineMacro("\\clap", "\\mathclap{\\textrm{#1}}");
defineMacro("\\mathstrut", "\\vphantom{(}");
defineMacro("\\underbar", "\\underline{\\text{#1}}");
defineMacro("\\not", '\\html@mathml{\\mathrel{\\mathrlap\\@not}}{\\char"338}');
defineMacro("\\neq", "\\html@mathml{\\mathrel{\\not=}}{\\mathrel{\\char`\u2260}}");
defineMacro("\\ne", "\\neq");
defineMacro("\u2260", "\\neq");
defineMacro("\\notin", "\\html@mathml{\\mathrel{{\\in}\\mathllap{/\\mskip1mu}}}{\\mathrel{\\char`\u2209}}");
defineMacro("\u2209", "\\notin");
defineMacro("\u2258", "\\html@mathml{\\mathrel{=\\kern{-1em}\\raisebox{0.4em}{$\\scriptsize\\frown$}}}{\\mathrel{\\char`\u2258}}");
defineMacro("\u2259", "\\html@mathml{\\stackrel{\\tiny\\wedge}{=}}{\\mathrel{\\char`\u2258}}");
defineMacro("\u225A", "\\html@mathml{\\stackrel{\\tiny\\vee}{=}}{\\mathrel{\\char`\u225A}}");
defineMacro("\u225B", "\\html@mathml{\\stackrel{\\scriptsize\\star}{=}}{\\mathrel{\\char`\u225B}}");
defineMacro("\u225D", "\\html@mathml{\\stackrel{\\tiny\\mathrm{def}}{=}}{\\mathrel{\\char`\u225D}}");
defineMacro("\u225E", "\\html@mathml{\\stackrel{\\tiny\\mathrm{m}}{=}}{\\mathrel{\\char`\u225E}}");
defineMacro("\u225F", "\\html@mathml{\\stackrel{\\tiny?}{=}}{\\mathrel{\\char`\u225F}}");
defineMacro("\u27C2", "\\perp");
defineMacro("\u203C", "\\mathclose{!\\mkern-0.8mu!}");
defineMacro("\u220C", "\\notni");
defineMacro("\u231C", "\\ulcorner");
defineMacro("\u231D", "\\urcorner");
defineMacro("\u231E", "\\llcorner");
defineMacro("\u231F", "\\lrcorner");
defineMacro("\xA9", "\\copyright");
defineMacro("\xAE", "\\textregistered");
defineMacro("\uFE0F", "\\textregistered");
defineMacro("\\ulcorner", '\\html@mathml{\\@ulcorner}{\\mathop{\\char"231c}}');
defineMacro("\\urcorner", '\\html@mathml{\\@urcorner}{\\mathop{\\char"231d}}');
defineMacro("\\llcorner", '\\html@mathml{\\@llcorner}{\\mathop{\\char"231e}}');
defineMacro("\\lrcorner", '\\html@mathml{\\@lrcorner}{\\mathop{\\char"231f}}');
defineMacro("\\vdots", "{\\varvdots\\rule{0pt}{15pt}}");
defineMacro("\u22EE", "\\vdots");
defineMacro("\\varGamma", "\\mathit{\\Gamma}");
defineMacro("\\varDelta", "\\mathit{\\Delta}");
defineMacro("\\varTheta", "\\mathit{\\Theta}");
defineMacro("\\varLambda", "\\mathit{\\Lambda}");
defineMacro("\\varXi", "\\mathit{\\Xi}");
defineMacro("\\varPi", "\\mathit{\\Pi}");
defineMacro("\\varSigma", "\\mathit{\\Sigma}");
defineMacro("\\varUpsilon", "\\mathit{\\Upsilon}");
defineMacro("\\varPhi", "\\mathit{\\Phi}");
defineMacro("\\varPsi", "\\mathit{\\Psi}");
defineMacro("\\varOmega", "\\mathit{\\Omega}");
defineMacro("\\substack", "\\begin{subarray}{c}#1\\end{subarray}");
defineMacro("\\colon", "\\nobreak\\mskip2mu\\mathpunct{}\\mathchoice{\\mkern-3mu}{\\mkern-3mu}{}{}{:}\\mskip6mu\\relax");
defineMacro("\\boxed", "\\fbox{$\\displaystyle{#1}$}");
defineMacro("\\iff", "\\DOTSB\\;\\Longleftrightarrow\\;");
defineMacro("\\implies", "\\DOTSB\\;\\Longrightarrow\\;");
defineMacro("\\impliedby", "\\DOTSB\\;\\Longleftarrow\\;");
defineMacro("\\dddot", "{\\overset{\\raisebox{-0.1ex}{\\normalsize ...}}{#1}}");
defineMacro("\\ddddot", "{\\overset{\\raisebox{-0.1ex}{\\normalsize ....}}{#1}}");
var dotsByToken = {
  ",": "\\dotsc",
  "\\not": "\\dotsb",
  // \keybin@ checks for the following:
  "+": "\\dotsb",
  "=": "\\dotsb",
  "<": "\\dotsb",
  ">": "\\dotsb",
  "-": "\\dotsb",
  "*": "\\dotsb",
  ":": "\\dotsb",
  // Symbols whose definition starts with \DOTSB:
  "\\DOTSB": "\\dotsb",
  "\\coprod": "\\dotsb",
  "\\bigvee": "\\dotsb",
  "\\bigwedge": "\\dotsb",
  "\\biguplus": "\\dotsb",
  "\\bigcap": "\\dotsb",
  "\\bigcup": "\\dotsb",
  "\\prod": "\\dotsb",
  "\\sum": "\\dotsb",
  "\\bigotimes": "\\dotsb",
  "\\bigoplus": "\\dotsb",
  "\\bigodot": "\\dotsb",
  "\\bigsqcup": "\\dotsb",
  "\\And": "\\dotsb",
  "\\longrightarrow": "\\dotsb",
  "\\Longrightarrow": "\\dotsb",
  "\\longleftarrow": "\\dotsb",
  "\\Longleftarrow": "\\dotsb",
  "\\longleftrightarrow": "\\dotsb",
  "\\Longleftrightarrow": "\\dotsb",
  "\\mapsto": "\\dotsb",
  "\\longmapsto": "\\dotsb",
  "\\hookrightarrow": "\\dotsb",
  "\\doteq": "\\dotsb",
  // Symbols whose definition starts with \mathbin:
  "\\mathbin": "\\dotsb",
  // Symbols whose definition starts with \mathrel:
  "\\mathrel": "\\dotsb",
  "\\relbar": "\\dotsb",
  "\\Relbar": "\\dotsb",
  "\\xrightarrow": "\\dotsb",
  "\\xleftarrow": "\\dotsb",
  // Symbols whose definition starts with \DOTSI:
  "\\DOTSI": "\\dotsi",
  "\\int": "\\dotsi",
  "\\oint": "\\dotsi",
  "\\iint": "\\dotsi",
  "\\iiint": "\\dotsi",
  "\\iiiint": "\\dotsi",
  "\\idotsint": "\\dotsi",
  // Symbols whose definition starts with \DOTSX:
  "\\DOTSX": "\\dotsx"
};
defineMacro("\\dots", function(context) {
  var thedots = "\\dotso";
  var next = context.expandAfterFuture().text;
  if (next in dotsByToken) {
    thedots = dotsByToken[next];
  } else if (next.slice(0, 4) === "\\not") {
    thedots = "\\dotsb";
  } else if (next in symbols.math) {
    if (utils2.contains(["bin", "rel"], symbols.math[next].group)) {
      thedots = "\\dotsb";
    }
  }
  return thedots;
});
var spaceAfterDots = {
  // \rightdelim@ checks for the following:
  ")": true,
  "]": true,
  "\\rbrack": true,
  "\\}": true,
  "\\rbrace": true,
  "\\rangle": true,
  "\\rceil": true,
  "\\rfloor": true,
  "\\rgroup": true,
  "\\rmoustache": true,
  "\\right": true,
  "\\bigr": true,
  "\\biggr": true,
  "\\Bigr": true,
  "\\Biggr": true,
  // \extra@ also tests for the following:
  "$": true,
  // \extrap@ checks for the following:
  ";": true,
  ".": true,
  ",": true
};
defineMacro("\\dotso", function(context) {
  var next = context.future().text;
  if (next in spaceAfterDots) {
    return "\\ldots\\,";
  } else {
    return "\\ldots";
  }
});
defineMacro("\\dotsc", function(context) {
  var next = context.future().text;
  if (next in spaceAfterDots && next !== ",") {
    return "\\ldots\\,";
  } else {
    return "\\ldots";
  }
});
defineMacro("\\cdots", function(context) {
  var next = context.future().text;
  if (next in spaceAfterDots) {
    return "\\@cdots\\,";
  } else {
    return "\\@cdots";
  }
});
defineMacro("\\dotsb", "\\cdots");
defineMacro("\\dotsm", "\\cdots");
defineMacro("\\dotsi", "\\!\\cdots");
defineMacro("\\dotsx", "\\ldots\\,");
defineMacro("\\DOTSI", "\\relax");
defineMacro("\\DOTSB", "\\relax");
defineMacro("\\DOTSX", "\\relax");
defineMacro("\\tmspace", "\\TextOrMath{\\kern#1#3}{\\mskip#1#2}\\relax");
defineMacro("\\,", "\\tmspace+{3mu}{.1667em}");
defineMacro("\\thinspace", "\\,");
defineMacro("\\>", "\\mskip{4mu}");
defineMacro("\\:", "\\tmspace+{4mu}{.2222em}");
defineMacro("\\medspace", "\\:");
defineMacro("\\;", "\\tmspace+{5mu}{.2777em}");
defineMacro("\\thickspace", "\\;");
defineMacro("\\!", "\\tmspace-{3mu}{.1667em}");
defineMacro("\\negthinspace", "\\!");
defineMacro("\\negmedspace", "\\tmspace-{4mu}{.2222em}");
defineMacro("\\negthickspace", "\\tmspace-{5mu}{.277em}");
defineMacro("\\enspace", "\\kern.5em ");
defineMacro("\\enskip", "\\hskip.5em\\relax");
defineMacro("\\quad", "\\hskip1em\\relax");
defineMacro("\\qquad", "\\hskip2em\\relax");
defineMacro("\\tag", "\\@ifstar\\tag@literal\\tag@paren");
defineMacro("\\tag@paren", "\\tag@literal{({#1})}");
defineMacro("\\tag@literal", (context) => {
  if (context.macros.get("\\df@tag")) {
    throw new ParseError("Multiple \\tag");
  }
  return "\\gdef\\df@tag{\\text{#1}}";
});
defineMacro("\\bmod", "\\mathchoice{\\mskip1mu}{\\mskip1mu}{\\mskip5mu}{\\mskip5mu}\\mathbin{\\rm mod}\\mathchoice{\\mskip1mu}{\\mskip1mu}{\\mskip5mu}{\\mskip5mu}");
defineMacro("\\pod", "\\allowbreak\\mathchoice{\\mkern18mu}{\\mkern8mu}{\\mkern8mu}{\\mkern8mu}(#1)");
defineMacro("\\pmod", "\\pod{{\\rm mod}\\mkern6mu#1}");
defineMacro("\\mod", "\\allowbreak\\mathchoice{\\mkern18mu}{\\mkern12mu}{\\mkern12mu}{\\mkern12mu}{\\rm mod}\\,\\,#1");
defineMacro("\\newline", "\\\\\\relax");
defineMacro("\\TeX", "\\textrm{\\html@mathml{T\\kern-.1667em\\raisebox{-.5ex}{E}\\kern-.125emX}{TeX}}");
var latexRaiseA = makeEm(fontMetricsData["Main-Regular"]["T".charCodeAt(0)][1] - 0.7 * fontMetricsData["Main-Regular"]["A".charCodeAt(0)][1]);
defineMacro("\\LaTeX", "\\textrm{\\html@mathml{" + ("L\\kern-.36em\\raisebox{" + latexRaiseA + "}{\\scriptstyle A}") + "\\kern-.15em\\TeX}{LaTeX}}");
defineMacro("\\KaTeX", "\\textrm{\\html@mathml{" + ("K\\kern-.17em\\raisebox{" + latexRaiseA + "}{\\scriptstyle A}") + "\\kern-.15em\\TeX}{KaTeX}}");
defineMacro("\\hspace", "\\@ifstar\\@hspacer\\@hspace");
defineMacro("\\@hspace", "\\hskip #1\\relax");
defineMacro("\\@hspacer", "\\rule{0pt}{0pt}\\hskip #1\\relax");
defineMacro("\\ordinarycolon", ":");
defineMacro("\\vcentcolon", "\\mathrel{\\mathop\\ordinarycolon}");
defineMacro("\\dblcolon", '\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-.9mu}\\vcentcolon}}{\\mathop{\\char"2237}}');
defineMacro("\\coloneqq", '\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}=}}{\\mathop{\\char"2254}}');
defineMacro("\\Coloneqq", '\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}=}}{\\mathop{\\char"2237\\char"3d}}');
defineMacro("\\coloneq", '\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}\\mathrel{-}}}{\\mathop{\\char"3a\\char"2212}}');
defineMacro("\\Coloneq", '\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}\\mathrel{-}}}{\\mathop{\\char"2237\\char"2212}}');
defineMacro("\\eqqcolon", '\\html@mathml{\\mathrel{=\\mathrel{\\mkern-1.2mu}\\vcentcolon}}{\\mathop{\\char"2255}}');
defineMacro("\\Eqqcolon", '\\html@mathml{\\mathrel{=\\mathrel{\\mkern-1.2mu}\\dblcolon}}{\\mathop{\\char"3d\\char"2237}}');
defineMacro("\\eqcolon", '\\html@mathml{\\mathrel{\\mathrel{-}\\mathrel{\\mkern-1.2mu}\\vcentcolon}}{\\mathop{\\char"2239}}');
defineMacro("\\Eqcolon", '\\html@mathml{\\mathrel{\\mathrel{-}\\mathrel{\\mkern-1.2mu}\\dblcolon}}{\\mathop{\\char"2212\\char"2237}}');
defineMacro("\\colonapprox", '\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}\\approx}}{\\mathop{\\char"3a\\char"2248}}');
defineMacro("\\Colonapprox", '\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}\\approx}}{\\mathop{\\char"2237\\char"2248}}');
defineMacro("\\colonsim", '\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}\\sim}}{\\mathop{\\char"3a\\char"223c}}');
defineMacro("\\Colonsim", '\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}\\sim}}{\\mathop{\\char"2237\\char"223c}}');
defineMacro("\u2237", "\\dblcolon");
defineMacro("\u2239", "\\eqcolon");
defineMacro("\u2254", "\\coloneqq");
defineMacro("\u2255", "\\eqqcolon");
defineMacro("\u2A74", "\\Coloneqq");
defineMacro("\\ratio", "\\vcentcolon");
defineMacro("\\coloncolon", "\\dblcolon");
defineMacro("\\colonequals", "\\coloneqq");
defineMacro("\\coloncolonequals", "\\Coloneqq");
defineMacro("\\equalscolon", "\\eqqcolon");
defineMacro("\\equalscoloncolon", "\\Eqqcolon");
defineMacro("\\colonminus", "\\coloneq");
defineMacro("\\coloncolonminus", "\\Coloneq");
defineMacro("\\minuscolon", "\\eqcolon");
defineMacro("\\minuscoloncolon", "\\Eqcolon");
defineMacro("\\coloncolonapprox", "\\Colonapprox");
defineMacro("\\coloncolonsim", "\\Colonsim");
defineMacro("\\simcolon", "\\mathrel{\\sim\\mathrel{\\mkern-1.2mu}\\vcentcolon}");
defineMacro("\\simcoloncolon", "\\mathrel{\\sim\\mathrel{\\mkern-1.2mu}\\dblcolon}");
defineMacro("\\approxcolon", "\\mathrel{\\approx\\mathrel{\\mkern-1.2mu}\\vcentcolon}");
defineMacro("\\approxcoloncolon", "\\mathrel{\\approx\\mathrel{\\mkern-1.2mu}\\dblcolon}");
defineMacro("\\notni", "\\html@mathml{\\not\\ni}{\\mathrel{\\char`\u220C}}");
defineMacro("\\limsup", "\\DOTSB\\operatorname*{lim\\,sup}");
defineMacro("\\liminf", "\\DOTSB\\operatorname*{lim\\,inf}");
defineMacro("\\injlim", "\\DOTSB\\operatorname*{inj\\,lim}");
defineMacro("\\projlim", "\\DOTSB\\operatorname*{proj\\,lim}");
defineMacro("\\varlimsup", "\\DOTSB\\operatorname*{\\overline{lim}}");
defineMacro("\\varliminf", "\\DOTSB\\operatorname*{\\underline{lim}}");
defineMacro("\\varinjlim", "\\DOTSB\\operatorname*{\\underrightarrow{lim}}");
defineMacro("\\varprojlim", "\\DOTSB\\operatorname*{\\underleftarrow{lim}}");
defineMacro("\\gvertneqq", "\\html@mathml{\\@gvertneqq}{\u2269}");
defineMacro("\\lvertneqq", "\\html@mathml{\\@lvertneqq}{\u2268}");
defineMacro("\\ngeqq", "\\html@mathml{\\@ngeqq}{\u2271}");
defineMacro("\\ngeqslant", "\\html@mathml{\\@ngeqslant}{\u2271}");
defineMacro("\\nleqq", "\\html@mathml{\\@nleqq}{\u2270}");
defineMacro("\\nleqslant", "\\html@mathml{\\@nleqslant}{\u2270}");
defineMacro("\\nshortmid", "\\html@mathml{\\@nshortmid}{\u2224}");
defineMacro("\\nshortparallel", "\\html@mathml{\\@nshortparallel}{\u2226}");
defineMacro("\\nsubseteqq", "\\html@mathml{\\@nsubseteqq}{\u2288}");
defineMacro("\\nsupseteqq", "\\html@mathml{\\@nsupseteqq}{\u2289}");
defineMacro("\\varsubsetneq", "\\html@mathml{\\@varsubsetneq}{\u228A}");
defineMacro("\\varsubsetneqq", "\\html@mathml{\\@varsubsetneqq}{\u2ACB}");
defineMacro("\\varsupsetneq", "\\html@mathml{\\@varsupsetneq}{\u228B}");
defineMacro("\\varsupsetneqq", "\\html@mathml{\\@varsupsetneqq}{\u2ACC}");
defineMacro("\\imath", "\\html@mathml{\\@imath}{\u0131}");
defineMacro("\\jmath", "\\html@mathml{\\@jmath}{\u0237}");
defineMacro("\\llbracket", "\\html@mathml{\\mathopen{[\\mkern-3.2mu[}}{\\mathopen{\\char`\u27E6}}");
defineMacro("\\rrbracket", "\\html@mathml{\\mathclose{]\\mkern-3.2mu]}}{\\mathclose{\\char`\u27E7}}");
defineMacro("\u27E6", "\\llbracket");
defineMacro("\u27E7", "\\rrbracket");
defineMacro("\\lBrace", "\\html@mathml{\\mathopen{\\{\\mkern-3.2mu[}}{\\mathopen{\\char`\u2983}}");
defineMacro("\\rBrace", "\\html@mathml{\\mathclose{]\\mkern-3.2mu\\}}}{\\mathclose{\\char`\u2984}}");
defineMacro("\u2983", "\\lBrace");
defineMacro("\u2984", "\\rBrace");
defineMacro("\\minuso", "\\mathbin{\\html@mathml{{\\mathrlap{\\mathchoice{\\kern{0.145em}}{\\kern{0.145em}}{\\kern{0.1015em}}{\\kern{0.0725em}}\\circ}{-}}}{\\char`\u29B5}}");
defineMacro("\u29B5", "\\minuso");
defineMacro("\\darr", "\\downarrow");
defineMacro("\\dArr", "\\Downarrow");
defineMacro("\\Darr", "\\Downarrow");
defineMacro("\\lang", "\\langle");
defineMacro("\\rang", "\\rangle");
defineMacro("\\uarr", "\\uparrow");
defineMacro("\\uArr", "\\Uparrow");
defineMacro("\\Uarr", "\\Uparrow");
defineMacro("\\N", "\\mathbb{N}");
defineMacro("\\R", "\\mathbb{R}");
defineMacro("\\Z", "\\mathbb{Z}");
defineMacro("\\alef", "\\aleph");
defineMacro("\\alefsym", "\\aleph");
defineMacro("\\Alpha", "\\mathrm{A}");
defineMacro("\\Beta", "\\mathrm{B}");
defineMacro("\\bull", "\\bullet");
defineMacro("\\Chi", "\\mathrm{X}");
defineMacro("\\clubs", "\\clubsuit");
defineMacro("\\cnums", "\\mathbb{C}");
defineMacro("\\Complex", "\\mathbb{C}");
defineMacro("\\Dagger", "\\ddagger");
defineMacro("\\diamonds", "\\diamondsuit");
defineMacro("\\empty", "\\emptyset");
defineMacro("\\Epsilon", "\\mathrm{E}");
defineMacro("\\Eta", "\\mathrm{H}");
defineMacro("\\exist", "\\exists");
defineMacro("\\harr", "\\leftrightarrow");
defineMacro("\\hArr", "\\Leftrightarrow");
defineMacro("\\Harr", "\\Leftrightarrow");
defineMacro("\\hearts", "\\heartsuit");
defineMacro("\\image", "\\Im");
defineMacro("\\infin", "\\infty");
defineMacro("\\Iota", "\\mathrm{I}");
defineMacro("\\isin", "\\in");
defineMacro("\\Kappa", "\\mathrm{K}");
defineMacro("\\larr", "\\leftarrow");
defineMacro("\\lArr", "\\Leftarrow");
defineMacro("\\Larr", "\\Leftarrow");
defineMacro("\\lrarr", "\\leftrightarrow");
defineMacro("\\lrArr", "\\Leftrightarrow");
defineMacro("\\Lrarr", "\\Leftrightarrow");
defineMacro("\\Mu", "\\mathrm{M}");
defineMacro("\\natnums", "\\mathbb{N}");
defineMacro("\\Nu", "\\mathrm{N}");
defineMacro("\\Omicron", "\\mathrm{O}");
defineMacro("\\plusmn", "\\pm");
defineMacro("\\rarr", "\\rightarrow");
defineMacro("\\rArr", "\\Rightarrow");
defineMacro("\\Rarr", "\\Rightarrow");
defineMacro("\\real", "\\Re");
defineMacro("\\reals", "\\mathbb{R}");
defineMacro("\\Reals", "\\mathbb{R}");
defineMacro("\\Rho", "\\mathrm{P}");
defineMacro("\\sdot", "\\cdot");
defineMacro("\\sect", "\\S");
defineMacro("\\spades", "\\spadesuit");
defineMacro("\\sub", "\\subset");
defineMacro("\\sube", "\\subseteq");
defineMacro("\\supe", "\\supseteq");
defineMacro("\\Tau", "\\mathrm{T}");
defineMacro("\\thetasym", "\\vartheta");
defineMacro("\\weierp", "\\wp");
defineMacro("\\Zeta", "\\mathrm{Z}");
defineMacro("\\argmin", "\\DOTSB\\operatorname*{arg\\,min}");
defineMacro("\\argmax", "\\DOTSB\\operatorname*{arg\\,max}");
defineMacro("\\plim", "\\DOTSB\\mathop{\\operatorname{plim}}\\limits");
defineMacro("\\bra", "\\mathinner{\\langle{#1}|}");
defineMacro("\\ket", "\\mathinner{|{#1}\\rangle}");
defineMacro("\\braket", "\\mathinner{\\langle{#1}\\rangle}");
defineMacro("\\Bra", "\\left\\langle#1\\right|");
defineMacro("\\Ket", "\\left|#1\\right\\rangle");
var braketHelper = (one) => (context) => {
  var left = context.consumeArg().tokens;
  var middle = context.consumeArg().tokens;
  var middleDouble = context.consumeArg().tokens;
  var right = context.consumeArg().tokens;
  var oldMiddle = context.macros.get("|");
  var oldMiddleDouble = context.macros.get("\\|");
  context.macros.beginGroup();
  var midMacro = (double2) => (context2) => {
    if (one) {
      context2.macros.set("|", oldMiddle);
      if (middleDouble.length) {
        context2.macros.set("\\|", oldMiddleDouble);
      }
    }
    var doubled = double2;
    if (!double2 && middleDouble.length) {
      var nextToken = context2.future();
      if (nextToken.text === "|") {
        context2.popToken();
        doubled = true;
      }
    }
    return {
      tokens: doubled ? middleDouble : middle,
      numArgs: 0
    };
  };
  context.macros.set("|", midMacro(false));
  if (middleDouble.length) {
    context.macros.set("\\|", midMacro(true));
  }
  var arg = context.consumeArg().tokens;
  var expanded = context.expandTokens([
    ...right,
    ...arg,
    ...left
    // reversed
  ]);
  context.macros.endGroup();
  return {
    tokens: expanded.reverse(),
    numArgs: 0
  };
};
defineMacro("\\bra@ket", braketHelper(false));
defineMacro("\\bra@set", braketHelper(true));
defineMacro("\\Braket", "\\bra@ket{\\left\\langle}{\\,\\middle\\vert\\,}{\\,\\middle\\vert\\,}{\\right\\rangle}");
defineMacro("\\Set", "\\bra@set{\\left\\{\\:}{\\;\\middle\\vert\\;}{\\;\\middle\\Vert\\;}{\\:\\right\\}}");
defineMacro("\\set", "\\bra@set{\\{\\,}{\\mid}{}{\\,\\}}");
defineMacro("\\angln", "{\\angl n}");
defineMacro("\\blue", "\\textcolor{##6495ed}{#1}");
defineMacro("\\orange", "\\textcolor{##ffa500}{#1}");
defineMacro("\\pink", "\\textcolor{##ff00af}{#1}");
defineMacro("\\red", "\\textcolor{##df0030}{#1}");
defineMacro("\\green", "\\textcolor{##28ae7b}{#1}");
defineMacro("\\gray", "\\textcolor{gray}{#1}");
defineMacro("\\purple", "\\textcolor{##9d38bd}{#1}");
defineMacro("\\blueA", "\\textcolor{##ccfaff}{#1}");
defineMacro("\\blueB", "\\textcolor{##80f6ff}{#1}");
defineMacro("\\blueC", "\\textcolor{##63d9ea}{#1}");
defineMacro("\\blueD", "\\textcolor{##11accd}{#1}");
defineMacro("\\blueE", "\\textcolor{##0c7f99}{#1}");
defineMacro("\\tealA", "\\textcolor{##94fff5}{#1}");
defineMacro("\\tealB", "\\textcolor{##26edd5}{#1}");
defineMacro("\\tealC", "\\textcolor{##01d1c1}{#1}");
defineMacro("\\tealD", "\\textcolor{##01a995}{#1}");
defineMacro("\\tealE", "\\textcolor{##208170}{#1}");
defineMacro("\\greenA", "\\textcolor{##b6ffb0}{#1}");
defineMacro("\\greenB", "\\textcolor{##8af281}{#1}");
defineMacro("\\greenC", "\\textcolor{##74cf70}{#1}");
defineMacro("\\greenD", "\\textcolor{##1fab54}{#1}");
defineMacro("\\greenE", "\\textcolor{##0d923f}{#1}");
defineMacro("\\goldA", "\\textcolor{##ffd0a9}{#1}");
defineMacro("\\goldB", "\\textcolor{##ffbb71}{#1}");
defineMacro("\\goldC", "\\textcolor{##ff9c39}{#1}");
defineMacro("\\goldD", "\\textcolor{##e07d10}{#1}");
defineMacro("\\goldE", "\\textcolor{##a75a05}{#1}");
defineMacro("\\redA", "\\textcolor{##fca9a9}{#1}");
defineMacro("\\redB", "\\textcolor{##ff8482}{#1}");
defineMacro("\\redC", "\\textcolor{##f9685d}{#1}");
defineMacro("\\redD", "\\textcolor{##e84d39}{#1}");
defineMacro("\\redE", "\\textcolor{##bc2612}{#1}");
defineMacro("\\maroonA", "\\textcolor{##ffbde0}{#1}");
defineMacro("\\maroonB", "\\textcolor{##ff92c6}{#1}");
defineMacro("\\maroonC", "\\textcolor{##ed5fa6}{#1}");
defineMacro("\\maroonD", "\\textcolor{##ca337c}{#1}");
defineMacro("\\maroonE", "\\textcolor{##9e034e}{#1}");
defineMacro("\\purpleA", "\\textcolor{##ddd7ff}{#1}");
defineMacro("\\purpleB", "\\textcolor{##c6b9fc}{#1}");
defineMacro("\\purpleC", "\\textcolor{##aa87ff}{#1}");
defineMacro("\\purpleD", "\\textcolor{##7854ab}{#1}");
defineMacro("\\purpleE", "\\textcolor{##543b78}{#1}");
defineMacro("\\mintA", "\\textcolor{##f5f9e8}{#1}");
defineMacro("\\mintB", "\\textcolor{##edf2df}{#1}");
defineMacro("\\mintC", "\\textcolor{##e0e5cc}{#1}");
defineMacro("\\grayA", "\\textcolor{##f6f7f7}{#1}");
defineMacro("\\grayB", "\\textcolor{##f0f1f2}{#1}");
defineMacro("\\grayC", "\\textcolor{##e3e5e6}{#1}");
defineMacro("\\grayD", "\\textcolor{##d6d8da}{#1}");
defineMacro("\\grayE", "\\textcolor{##babec2}{#1}");
defineMacro("\\grayF", "\\textcolor{##888d93}{#1}");
defineMacro("\\grayG", "\\textcolor{##626569}{#1}");
defineMacro("\\grayH", "\\textcolor{##3b3e40}{#1}");
defineMacro("\\grayI", "\\textcolor{##21242c}{#1}");
defineMacro("\\kaBlue", "\\textcolor{##314453}{#1}");
defineMacro("\\kaGreen", "\\textcolor{##71B307}{#1}");
var implicitCommands = {
  "^": true,
  // Parser.js
  "_": true,
  // Parser.js
  "\\limits": true,
  // Parser.js
  "\\nolimits": true
  // Parser.js
};
var MacroExpander = class {
  constructor(input, settings, mode) {
    this.settings = void 0;
    this.expansionCount = void 0;
    this.lexer = void 0;
    this.macros = void 0;
    this.stack = void 0;
    this.mode = void 0;
    this.settings = settings;
    this.expansionCount = 0;
    this.feed(input);
    this.macros = new Namespace(macros, settings.macros);
    this.mode = mode;
    this.stack = [];
  }
  /**
   * Feed a new input string to the same MacroExpander
   * (with existing macros etc.).
   */
  feed(input) {
    this.lexer = new Lexer(input, this.settings);
  }
  /**
   * Switches between "text" and "math" modes.
   */
  switchMode(newMode) {
    this.mode = newMode;
  }
  /**
   * Start a new group nesting within all namespaces.
   */
  beginGroup() {
    this.macros.beginGroup();
  }
  /**
   * End current group nesting within all namespaces.
   */
  endGroup() {
    this.macros.endGroup();
  }
  /**
   * Ends all currently nested groups (if any), restoring values before the
   * groups began.  Useful in case of an error in the middle of parsing.
   */
  endGroups() {
    this.macros.endGroups();
  }
  /**
   * Returns the topmost token on the stack, without expanding it.
   * Similar in behavior to TeX's `\futurelet`.
   */
  future() {
    if (this.stack.length === 0) {
      this.pushToken(this.lexer.lex());
    }
    return this.stack[this.stack.length - 1];
  }
  /**
   * Remove and return the next unexpanded token.
   */
  popToken() {
    this.future();
    return this.stack.pop();
  }
  /**
   * Add a given token to the token stack.  In particular, this get be used
   * to put back a token returned from one of the other methods.
   */
  pushToken(token) {
    this.stack.push(token);
  }
  /**
   * Append an array of tokens to the token stack.
   */
  pushTokens(tokens) {
    this.stack.push(...tokens);
  }
  /**
   * Find an macro argument without expanding tokens and append the array of
   * tokens to the token stack. Uses Token as a container for the result.
   */
  scanArgument(isOptional) {
    var start;
    var end;
    var tokens;
    if (isOptional) {
      this.consumeSpaces();
      if (this.future().text !== "[") {
        return null;
      }
      start = this.popToken();
      ({
        tokens,
        end
      } = this.consumeArg(["]"]));
    } else {
      ({
        tokens,
        start,
        end
      } = this.consumeArg());
    }
    this.pushToken(new Token("EOF", end.loc));
    this.pushTokens(tokens);
    return start.range(end, "");
  }
  /**
   * Consume all following space tokens, without expansion.
   */
  consumeSpaces() {
    for (; ; ) {
      var token = this.future();
      if (token.text === " ") {
        this.stack.pop();
      } else {
        break;
      }
    }
  }
  /**
   * Consume an argument from the token stream, and return the resulting array
   * of tokens and start/end token.
   */
  consumeArg(delims) {
    var tokens = [];
    var isDelimited = delims && delims.length > 0;
    if (!isDelimited) {
      this.consumeSpaces();
    }
    var start = this.future();
    var tok;
    var depth = 0;
    var match2 = 0;
    do {
      tok = this.popToken();
      tokens.push(tok);
      if (tok.text === "{") {
        ++depth;
      } else if (tok.text === "}") {
        --depth;
        if (depth === -1) {
          throw new ParseError("Extra }", tok);
        }
      } else if (tok.text === "EOF") {
        throw new ParseError("Unexpected end of input in a macro argument, expected '" + (delims && isDelimited ? delims[match2] : "}") + "'", tok);
      }
      if (delims && isDelimited) {
        if ((depth === 0 || depth === 1 && delims[match2] === "{") && tok.text === delims[match2]) {
          ++match2;
          if (match2 === delims.length) {
            tokens.splice(-match2, match2);
            break;
          }
        } else {
          match2 = 0;
        }
      }
    } while (depth !== 0 || isDelimited);
    if (start.text === "{" && tokens[tokens.length - 1].text === "}") {
      tokens.pop();
      tokens.shift();
    }
    tokens.reverse();
    return {
      tokens,
      start,
      end: tok
    };
  }
  /**
   * Consume the specified number of (delimited) arguments from the token
   * stream and return the resulting array of arguments.
   */
  consumeArgs(numArgs, delimiters2) {
    if (delimiters2) {
      if (delimiters2.length !== numArgs + 1) {
        throw new ParseError("The length of delimiters doesn't match the number of args!");
      }
      var delims = delimiters2[0];
      for (var i7 = 0; i7 < delims.length; i7++) {
        var tok = this.popToken();
        if (delims[i7] !== tok.text) {
          throw new ParseError("Use of the macro doesn't match its definition", tok);
        }
      }
    }
    var args = [];
    for (var _i = 0; _i < numArgs; _i++) {
      args.push(this.consumeArg(delimiters2 && delimiters2[_i + 1]).tokens);
    }
    return args;
  }
  /**
   * Increment `expansionCount` by the specified amount.
   * Throw an error if it exceeds `maxExpand`.
   */
  countExpansion(amount) {
    this.expansionCount += amount;
    if (this.expansionCount > this.settings.maxExpand) {
      throw new ParseError("Too many expansions: infinite loop or need to increase maxExpand setting");
    }
  }
  /**
   * Expand the next token only once if possible.
   *
   * If the token is expanded, the resulting tokens will be pushed onto
   * the stack in reverse order, and the number of such tokens will be
   * returned.  This number might be zero or positive.
   *
   * If not, the return value is `false`, and the next token remains at the
   * top of the stack.
   *
   * In either case, the next token will be on the top of the stack,
   * or the stack will be empty (in case of empty expansion
   * and no other tokens).
   *
   * Used to implement `expandAfterFuture` and `expandNextToken`.
   *
   * If expandableOnly, only expandable tokens are expanded and
   * an undefined control sequence results in an error.
   */
  expandOnce(expandableOnly) {
    var topToken = this.popToken();
    var name = topToken.text;
    var expansion = !topToken.noexpand ? this._getExpansion(name) : null;
    if (expansion == null || expandableOnly && expansion.unexpandable) {
      if (expandableOnly && expansion == null && name[0] === "\\" && !this.isDefined(name)) {
        throw new ParseError("Undefined control sequence: " + name);
      }
      this.pushToken(topToken);
      return false;
    }
    this.countExpansion(1);
    var tokens = expansion.tokens;
    var args = this.consumeArgs(expansion.numArgs, expansion.delimiters);
    if (expansion.numArgs) {
      tokens = tokens.slice();
      for (var i7 = tokens.length - 1; i7 >= 0; --i7) {
        var tok = tokens[i7];
        if (tok.text === "#") {
          if (i7 === 0) {
            throw new ParseError("Incomplete placeholder at end of macro body", tok);
          }
          tok = tokens[--i7];
          if (tok.text === "#") {
            tokens.splice(i7 + 1, 1);
          } else if (/^[1-9]$/.test(tok.text)) {
            tokens.splice(i7, 2, ...args[+tok.text - 1]);
          } else {
            throw new ParseError("Not a valid argument number", tok);
          }
        }
      }
    }
    this.pushTokens(tokens);
    return tokens.length;
  }
  /**
   * Expand the next token only once (if possible), and return the resulting
   * top token on the stack (without removing anything from the stack).
   * Similar in behavior to TeX's `\expandafter\futurelet`.
   * Equivalent to expandOnce() followed by future().
   */
  expandAfterFuture() {
    this.expandOnce();
    return this.future();
  }
  /**
   * Recursively expand first token, then return first non-expandable token.
   */
  expandNextToken() {
    for (; ; ) {
      if (this.expandOnce() === false) {
        var token = this.stack.pop();
        if (token.treatAsRelax) {
          token.text = "\\relax";
        }
        return token;
      }
    }
    throw new Error();
  }
  /**
   * Fully expand the given macro name and return the resulting list of
   * tokens, or return `undefined` if no such macro is defined.
   */
  expandMacro(name) {
    return this.macros.has(name) ? this.expandTokens([new Token(name)]) : void 0;
  }
  /**
   * Fully expand the given token stream and return the resulting list of
   * tokens.  Note that the input tokens are in reverse order, but the
   * output tokens are in forward order.
   */
  expandTokens(tokens) {
    var output = [];
    var oldStackLength = this.stack.length;
    this.pushTokens(tokens);
    while (this.stack.length > oldStackLength) {
      if (this.expandOnce(true) === false) {
        var token = this.stack.pop();
        if (token.treatAsRelax) {
          token.noexpand = false;
          token.treatAsRelax = false;
        }
        output.push(token);
      }
    }
    this.countExpansion(output.length);
    return output;
  }
  /**
   * Fully expand the given macro name and return the result as a string,
   * or return `undefined` if no such macro is defined.
   */
  expandMacroAsText(name) {
    var tokens = this.expandMacro(name);
    if (tokens) {
      return tokens.map((token) => token.text).join("");
    } else {
      return tokens;
    }
  }
  /**
   * Returns the expanded macro as a reversed array of tokens and a macro
   * argument count.  Or returns `null` if no such macro.
   */
  _getExpansion(name) {
    var definition = this.macros.get(name);
    if (definition == null) {
      return definition;
    }
    if (name.length === 1) {
      var catcode = this.lexer.catcodes[name];
      if (catcode != null && catcode !== 13) {
        return;
      }
    }
    var expansion = typeof definition === "function" ? definition(this) : definition;
    if (typeof expansion === "string") {
      var numArgs = 0;
      if (expansion.indexOf("#") !== -1) {
        var stripped = expansion.replace(/##/g, "");
        while (stripped.indexOf("#" + (numArgs + 1)) !== -1) {
          ++numArgs;
        }
      }
      var bodyLexer = new Lexer(expansion, this.settings);
      var tokens = [];
      var tok = bodyLexer.lex();
      while (tok.text !== "EOF") {
        tokens.push(tok);
        tok = bodyLexer.lex();
      }
      tokens.reverse();
      var expanded = {
        tokens,
        numArgs
      };
      return expanded;
    }
    return expansion;
  }
  /**
   * Determine whether a command is currently "defined" (has some
   * functionality), meaning that it's a macro (in the current group),
   * a function, a symbol, or one of the special commands listed in
   * `implicitCommands`.
   */
  isDefined(name) {
    return this.macros.has(name) || functions.hasOwnProperty(name) || symbols.math.hasOwnProperty(name) || symbols.text.hasOwnProperty(name) || implicitCommands.hasOwnProperty(name);
  }
  /**
   * Determine whether a command is expandable.
   */
  isExpandable(name) {
    var macro = this.macros.get(name);
    return macro != null ? typeof macro === "string" || typeof macro === "function" || !macro.unexpandable : functions.hasOwnProperty(name) && !functions[name].primitive;
  }
};
var unicodeSubRegEx = /^[₊₋₌₍₎₀₁₂₃₄₅₆₇₈₉ₐₑₕᵢⱼₖₗₘₙₒₚᵣₛₜᵤᵥₓᵦᵧᵨᵩᵪ]/;
var uSubsAndSups = Object.freeze({
  "\u208A": "+",
  "\u208B": "-",
  "\u208C": "=",
  "\u208D": "(",
  "\u208E": ")",
  "\u2080": "0",
  "\u2081": "1",
  "\u2082": "2",
  "\u2083": "3",
  "\u2084": "4",
  "\u2085": "5",
  "\u2086": "6",
  "\u2087": "7",
  "\u2088": "8",
  "\u2089": "9",
  "\u2090": "a",
  "\u2091": "e",
  "\u2095": "h",
  "\u1D62": "i",
  "\u2C7C": "j",
  "\u2096": "k",
  "\u2097": "l",
  "\u2098": "m",
  "\u2099": "n",
  "\u2092": "o",
  "\u209A": "p",
  "\u1D63": "r",
  "\u209B": "s",
  "\u209C": "t",
  "\u1D64": "u",
  "\u1D65": "v",
  "\u2093": "x",
  "\u1D66": "\u03B2",
  "\u1D67": "\u03B3",
  "\u1D68": "\u03C1",
  "\u1D69": "\u03D5",
  "\u1D6A": "\u03C7",
  "\u207A": "+",
  "\u207B": "-",
  "\u207C": "=",
  "\u207D": "(",
  "\u207E": ")",
  "\u2070": "0",
  "\xB9": "1",
  "\xB2": "2",
  "\xB3": "3",
  "\u2074": "4",
  "\u2075": "5",
  "\u2076": "6",
  "\u2077": "7",
  "\u2078": "8",
  "\u2079": "9",
  "\u1D2C": "A",
  "\u1D2E": "B",
  "\u1D30": "D",
  "\u1D31": "E",
  "\u1D33": "G",
  "\u1D34": "H",
  "\u1D35": "I",
  "\u1D36": "J",
  "\u1D37": "K",
  "\u1D38": "L",
  "\u1D39": "M",
  "\u1D3A": "N",
  "\u1D3C": "O",
  "\u1D3E": "P",
  "\u1D3F": "R",
  "\u1D40": "T",
  "\u1D41": "U",
  "\u2C7D": "V",
  "\u1D42": "W",
  "\u1D43": "a",
  "\u1D47": "b",
  "\u1D9C": "c",
  "\u1D48": "d",
  "\u1D49": "e",
  "\u1DA0": "f",
  "\u1D4D": "g",
  "\u02B0": "h",
  "\u2071": "i",
  "\u02B2": "j",
  "\u1D4F": "k",
  "\u02E1": "l",
  "\u1D50": "m",
  "\u207F": "n",
  "\u1D52": "o",
  "\u1D56": "p",
  "\u02B3": "r",
  "\u02E2": "s",
  "\u1D57": "t",
  "\u1D58": "u",
  "\u1D5B": "v",
  "\u02B7": "w",
  "\u02E3": "x",
  "\u02B8": "y",
  "\u1DBB": "z",
  "\u1D5D": "\u03B2",
  "\u1D5E": "\u03B3",
  "\u1D5F": "\u03B4",
  "\u1D60": "\u03D5",
  "\u1D61": "\u03C7",
  "\u1DBF": "\u03B8"
});
var unicodeAccents = {
  "\u0301": {
    "text": "\\'",
    "math": "\\acute"
  },
  "\u0300": {
    "text": "\\`",
    "math": "\\grave"
  },
  "\u0308": {
    "text": '\\"',
    "math": "\\ddot"
  },
  "\u0303": {
    "text": "\\~",
    "math": "\\tilde"
  },
  "\u0304": {
    "text": "\\=",
    "math": "\\bar"
  },
  "\u0306": {
    "text": "\\u",
    "math": "\\breve"
  },
  "\u030C": {
    "text": "\\v",
    "math": "\\check"
  },
  "\u0302": {
    "text": "\\^",
    "math": "\\hat"
  },
  "\u0307": {
    "text": "\\.",
    "math": "\\dot"
  },
  "\u030A": {
    "text": "\\r",
    "math": "\\mathring"
  },
  "\u030B": {
    "text": "\\H"
  },
  "\u0327": {
    "text": "\\c"
  }
};
var unicodeSymbols = {
  "\xE1": "a\u0301",
  "\xE0": "a\u0300",
  "\xE4": "a\u0308",
  "\u01DF": "a\u0308\u0304",
  "\xE3": "a\u0303",
  "\u0101": "a\u0304",
  "\u0103": "a\u0306",
  "\u1EAF": "a\u0306\u0301",
  "\u1EB1": "a\u0306\u0300",
  "\u1EB5": "a\u0306\u0303",
  "\u01CE": "a\u030C",
  "\xE2": "a\u0302",
  "\u1EA5": "a\u0302\u0301",
  "\u1EA7": "a\u0302\u0300",
  "\u1EAB": "a\u0302\u0303",
  "\u0227": "a\u0307",
  "\u01E1": "a\u0307\u0304",
  "\xE5": "a\u030A",
  "\u01FB": "a\u030A\u0301",
  "\u1E03": "b\u0307",
  "\u0107": "c\u0301",
  "\u1E09": "c\u0327\u0301",
  "\u010D": "c\u030C",
  "\u0109": "c\u0302",
  "\u010B": "c\u0307",
  "\xE7": "c\u0327",
  "\u010F": "d\u030C",
  "\u1E0B": "d\u0307",
  "\u1E11": "d\u0327",
  "\xE9": "e\u0301",
  "\xE8": "e\u0300",
  "\xEB": "e\u0308",
  "\u1EBD": "e\u0303",
  "\u0113": "e\u0304",
  "\u1E17": "e\u0304\u0301",
  "\u1E15": "e\u0304\u0300",
  "\u0115": "e\u0306",
  "\u1E1D": "e\u0327\u0306",
  "\u011B": "e\u030C",
  "\xEA": "e\u0302",
  "\u1EBF": "e\u0302\u0301",
  "\u1EC1": "e\u0302\u0300",
  "\u1EC5": "e\u0302\u0303",
  "\u0117": "e\u0307",
  "\u0229": "e\u0327",
  "\u1E1F": "f\u0307",
  "\u01F5": "g\u0301",
  "\u1E21": "g\u0304",
  "\u011F": "g\u0306",
  "\u01E7": "g\u030C",
  "\u011D": "g\u0302",
  "\u0121": "g\u0307",
  "\u0123": "g\u0327",
  "\u1E27": "h\u0308",
  "\u021F": "h\u030C",
  "\u0125": "h\u0302",
  "\u1E23": "h\u0307",
  "\u1E29": "h\u0327",
  "\xED": "i\u0301",
  "\xEC": "i\u0300",
  "\xEF": "i\u0308",
  "\u1E2F": "i\u0308\u0301",
  "\u0129": "i\u0303",
  "\u012B": "i\u0304",
  "\u012D": "i\u0306",
  "\u01D0": "i\u030C",
  "\xEE": "i\u0302",
  "\u01F0": "j\u030C",
  "\u0135": "j\u0302",
  "\u1E31": "k\u0301",
  "\u01E9": "k\u030C",
  "\u0137": "k\u0327",
  "\u013A": "l\u0301",
  "\u013E": "l\u030C",
  "\u013C": "l\u0327",
  "\u1E3F": "m\u0301",
  "\u1E41": "m\u0307",
  "\u0144": "n\u0301",
  "\u01F9": "n\u0300",
  "\xF1": "n\u0303",
  "\u0148": "n\u030C",
  "\u1E45": "n\u0307",
  "\u0146": "n\u0327",
  "\xF3": "o\u0301",
  "\xF2": "o\u0300",
  "\xF6": "o\u0308",
  "\u022B": "o\u0308\u0304",
  "\xF5": "o\u0303",
  "\u1E4D": "o\u0303\u0301",
  "\u1E4F": "o\u0303\u0308",
  "\u022D": "o\u0303\u0304",
  "\u014D": "o\u0304",
  "\u1E53": "o\u0304\u0301",
  "\u1E51": "o\u0304\u0300",
  "\u014F": "o\u0306",
  "\u01D2": "o\u030C",
  "\xF4": "o\u0302",
  "\u1ED1": "o\u0302\u0301",
  "\u1ED3": "o\u0302\u0300",
  "\u1ED7": "o\u0302\u0303",
  "\u022F": "o\u0307",
  "\u0231": "o\u0307\u0304",
  "\u0151": "o\u030B",
  "\u1E55": "p\u0301",
  "\u1E57": "p\u0307",
  "\u0155": "r\u0301",
  "\u0159": "r\u030C",
  "\u1E59": "r\u0307",
  "\u0157": "r\u0327",
  "\u015B": "s\u0301",
  "\u1E65": "s\u0301\u0307",
  "\u0161": "s\u030C",
  "\u1E67": "s\u030C\u0307",
  "\u015D": "s\u0302",
  "\u1E61": "s\u0307",
  "\u015F": "s\u0327",
  "\u1E97": "t\u0308",
  "\u0165": "t\u030C",
  "\u1E6B": "t\u0307",
  "\u0163": "t\u0327",
  "\xFA": "u\u0301",
  "\xF9": "u\u0300",
  "\xFC": "u\u0308",
  "\u01D8": "u\u0308\u0301",
  "\u01DC": "u\u0308\u0300",
  "\u01D6": "u\u0308\u0304",
  "\u01DA": "u\u0308\u030C",
  "\u0169": "u\u0303",
  "\u1E79": "u\u0303\u0301",
  "\u016B": "u\u0304",
  "\u1E7B": "u\u0304\u0308",
  "\u016D": "u\u0306",
  "\u01D4": "u\u030C",
  "\xFB": "u\u0302",
  "\u016F": "u\u030A",
  "\u0171": "u\u030B",
  "\u1E7D": "v\u0303",
  "\u1E83": "w\u0301",
  "\u1E81": "w\u0300",
  "\u1E85": "w\u0308",
  "\u0175": "w\u0302",
  "\u1E87": "w\u0307",
  "\u1E98": "w\u030A",
  "\u1E8D": "x\u0308",
  "\u1E8B": "x\u0307",
  "\xFD": "y\u0301",
  "\u1EF3": "y\u0300",
  "\xFF": "y\u0308",
  "\u1EF9": "y\u0303",
  "\u0233": "y\u0304",
  "\u0177": "y\u0302",
  "\u1E8F": "y\u0307",
  "\u1E99": "y\u030A",
  "\u017A": "z\u0301",
  "\u017E": "z\u030C",
  "\u1E91": "z\u0302",
  "\u017C": "z\u0307",
  "\xC1": "A\u0301",
  "\xC0": "A\u0300",
  "\xC4": "A\u0308",
  "\u01DE": "A\u0308\u0304",
  "\xC3": "A\u0303",
  "\u0100": "A\u0304",
  "\u0102": "A\u0306",
  "\u1EAE": "A\u0306\u0301",
  "\u1EB0": "A\u0306\u0300",
  "\u1EB4": "A\u0306\u0303",
  "\u01CD": "A\u030C",
  "\xC2": "A\u0302",
  "\u1EA4": "A\u0302\u0301",
  "\u1EA6": "A\u0302\u0300",
  "\u1EAA": "A\u0302\u0303",
  "\u0226": "A\u0307",
  "\u01E0": "A\u0307\u0304",
  "\xC5": "A\u030A",
  "\u01FA": "A\u030A\u0301",
  "\u1E02": "B\u0307",
  "\u0106": "C\u0301",
  "\u1E08": "C\u0327\u0301",
  "\u010C": "C\u030C",
  "\u0108": "C\u0302",
  "\u010A": "C\u0307",
  "\xC7": "C\u0327",
  "\u010E": "D\u030C",
  "\u1E0A": "D\u0307",
  "\u1E10": "D\u0327",
  "\xC9": "E\u0301",
  "\xC8": "E\u0300",
  "\xCB": "E\u0308",
  "\u1EBC": "E\u0303",
  "\u0112": "E\u0304",
  "\u1E16": "E\u0304\u0301",
  "\u1E14": "E\u0304\u0300",
  "\u0114": "E\u0306",
  "\u1E1C": "E\u0327\u0306",
  "\u011A": "E\u030C",
  "\xCA": "E\u0302",
  "\u1EBE": "E\u0302\u0301",
  "\u1EC0": "E\u0302\u0300",
  "\u1EC4": "E\u0302\u0303",
  "\u0116": "E\u0307",
  "\u0228": "E\u0327",
  "\u1E1E": "F\u0307",
  "\u01F4": "G\u0301",
  "\u1E20": "G\u0304",
  "\u011E": "G\u0306",
  "\u01E6": "G\u030C",
  "\u011C": "G\u0302",
  "\u0120": "G\u0307",
  "\u0122": "G\u0327",
  "\u1E26": "H\u0308",
  "\u021E": "H\u030C",
  "\u0124": "H\u0302",
  "\u1E22": "H\u0307",
  "\u1E28": "H\u0327",
  "\xCD": "I\u0301",
  "\xCC": "I\u0300",
  "\xCF": "I\u0308",
  "\u1E2E": "I\u0308\u0301",
  "\u0128": "I\u0303",
  "\u012A": "I\u0304",
  "\u012C": "I\u0306",
  "\u01CF": "I\u030C",
  "\xCE": "I\u0302",
  "\u0130": "I\u0307",
  "\u0134": "J\u0302",
  "\u1E30": "K\u0301",
  "\u01E8": "K\u030C",
  "\u0136": "K\u0327",
  "\u0139": "L\u0301",
  "\u013D": "L\u030C",
  "\u013B": "L\u0327",
  "\u1E3E": "M\u0301",
  "\u1E40": "M\u0307",
  "\u0143": "N\u0301",
  "\u01F8": "N\u0300",
  "\xD1": "N\u0303",
  "\u0147": "N\u030C",
  "\u1E44": "N\u0307",
  "\u0145": "N\u0327",
  "\xD3": "O\u0301",
  "\xD2": "O\u0300",
  "\xD6": "O\u0308",
  "\u022A": "O\u0308\u0304",
  "\xD5": "O\u0303",
  "\u1E4C": "O\u0303\u0301",
  "\u1E4E": "O\u0303\u0308",
  "\u022C": "O\u0303\u0304",
  "\u014C": "O\u0304",
  "\u1E52": "O\u0304\u0301",
  "\u1E50": "O\u0304\u0300",
  "\u014E": "O\u0306",
  "\u01D1": "O\u030C",
  "\xD4": "O\u0302",
  "\u1ED0": "O\u0302\u0301",
  "\u1ED2": "O\u0302\u0300",
  "\u1ED6": "O\u0302\u0303",
  "\u022E": "O\u0307",
  "\u0230": "O\u0307\u0304",
  "\u0150": "O\u030B",
  "\u1E54": "P\u0301",
  "\u1E56": "P\u0307",
  "\u0154": "R\u0301",
  "\u0158": "R\u030C",
  "\u1E58": "R\u0307",
  "\u0156": "R\u0327",
  "\u015A": "S\u0301",
  "\u1E64": "S\u0301\u0307",
  "\u0160": "S\u030C",
  "\u1E66": "S\u030C\u0307",
  "\u015C": "S\u0302",
  "\u1E60": "S\u0307",
  "\u015E": "S\u0327",
  "\u0164": "T\u030C",
  "\u1E6A": "T\u0307",
  "\u0162": "T\u0327",
  "\xDA": "U\u0301",
  "\xD9": "U\u0300",
  "\xDC": "U\u0308",
  "\u01D7": "U\u0308\u0301",
  "\u01DB": "U\u0308\u0300",
  "\u01D5": "U\u0308\u0304",
  "\u01D9": "U\u0308\u030C",
  "\u0168": "U\u0303",
  "\u1E78": "U\u0303\u0301",
  "\u016A": "U\u0304",
  "\u1E7A": "U\u0304\u0308",
  "\u016C": "U\u0306",
  "\u01D3": "U\u030C",
  "\xDB": "U\u0302",
  "\u016E": "U\u030A",
  "\u0170": "U\u030B",
  "\u1E7C": "V\u0303",
  "\u1E82": "W\u0301",
  "\u1E80": "W\u0300",
  "\u1E84": "W\u0308",
  "\u0174": "W\u0302",
  "\u1E86": "W\u0307",
  "\u1E8C": "X\u0308",
  "\u1E8A": "X\u0307",
  "\xDD": "Y\u0301",
  "\u1EF2": "Y\u0300",
  "\u0178": "Y\u0308",
  "\u1EF8": "Y\u0303",
  "\u0232": "Y\u0304",
  "\u0176": "Y\u0302",
  "\u1E8E": "Y\u0307",
  "\u0179": "Z\u0301",
  "\u017D": "Z\u030C",
  "\u1E90": "Z\u0302",
  "\u017B": "Z\u0307",
  "\u03AC": "\u03B1\u0301",
  "\u1F70": "\u03B1\u0300",
  "\u1FB1": "\u03B1\u0304",
  "\u1FB0": "\u03B1\u0306",
  "\u03AD": "\u03B5\u0301",
  "\u1F72": "\u03B5\u0300",
  "\u03AE": "\u03B7\u0301",
  "\u1F74": "\u03B7\u0300",
  "\u03AF": "\u03B9\u0301",
  "\u1F76": "\u03B9\u0300",
  "\u03CA": "\u03B9\u0308",
  "\u0390": "\u03B9\u0308\u0301",
  "\u1FD2": "\u03B9\u0308\u0300",
  "\u1FD1": "\u03B9\u0304",
  "\u1FD0": "\u03B9\u0306",
  "\u03CC": "\u03BF\u0301",
  "\u1F78": "\u03BF\u0300",
  "\u03CD": "\u03C5\u0301",
  "\u1F7A": "\u03C5\u0300",
  "\u03CB": "\u03C5\u0308",
  "\u03B0": "\u03C5\u0308\u0301",
  "\u1FE2": "\u03C5\u0308\u0300",
  "\u1FE1": "\u03C5\u0304",
  "\u1FE0": "\u03C5\u0306",
  "\u03CE": "\u03C9\u0301",
  "\u1F7C": "\u03C9\u0300",
  "\u038E": "\u03A5\u0301",
  "\u1FEA": "\u03A5\u0300",
  "\u03AB": "\u03A5\u0308",
  "\u1FE9": "\u03A5\u0304",
  "\u1FE8": "\u03A5\u0306",
  "\u038F": "\u03A9\u0301",
  "\u1FFA": "\u03A9\u0300"
};
var Parser = class _Parser {
  constructor(input, settings) {
    this.mode = void 0;
    this.gullet = void 0;
    this.settings = void 0;
    this.leftrightDepth = void 0;
    this.nextToken = void 0;
    this.mode = "math";
    this.gullet = new MacroExpander(input, settings, this.mode);
    this.settings = settings;
    this.leftrightDepth = 0;
  }
  /**
   * Checks a result to make sure it has the right type, and throws an
   * appropriate error otherwise.
   */
  expect(text3, consume) {
    if (consume === void 0) {
      consume = true;
    }
    if (this.fetch().text !== text3) {
      throw new ParseError("Expected '" + text3 + "', got '" + this.fetch().text + "'", this.fetch());
    }
    if (consume) {
      this.consume();
    }
  }
  /**
   * Discards the current lookahead token, considering it consumed.
   */
  consume() {
    this.nextToken = null;
  }
  /**
   * Return the current lookahead token, or if there isn't one (at the
   * beginning, or if the previous lookahead token was consume()d),
   * fetch the next token as the new lookahead token and return it.
   */
  fetch() {
    if (this.nextToken == null) {
      this.nextToken = this.gullet.expandNextToken();
    }
    return this.nextToken;
  }
  /**
   * Switches between "text" and "math" modes.
   */
  switchMode(newMode) {
    this.mode = newMode;
    this.gullet.switchMode(newMode);
  }
  /**
   * Main parsing function, which parses an entire input.
   */
  parse() {
    if (!this.settings.globalGroup) {
      this.gullet.beginGroup();
    }
    if (this.settings.colorIsTextColor) {
      this.gullet.macros.set("\\color", "\\textcolor");
    }
    try {
      var parse = this.parseExpression(false);
      this.expect("EOF");
      if (!this.settings.globalGroup) {
        this.gullet.endGroup();
      }
      return parse;
    } finally {
      this.gullet.endGroups();
    }
  }
  /**
   * Fully parse a separate sequence of tokens as a separate job.
   * Tokens should be specified in reverse order, as in a MacroDefinition.
   */
  subparse(tokens) {
    var oldToken = this.nextToken;
    this.consume();
    this.gullet.pushToken(new Token("}"));
    this.gullet.pushTokens(tokens);
    var parse = this.parseExpression(false);
    this.expect("}");
    this.nextToken = oldToken;
    return parse;
  }
  /**
   * Parses an "expression", which is a list of atoms.
   *
   * `breakOnInfix`: Should the parsing stop when we hit infix nodes? This
   *                 happens when functions have higher precedence han infix
   *                 nodes in implicit parses.
   *
   * `breakOnTokenText`: The text of the token that the expression should end
   *                     with, or `null` if something else should end the
   *                     expression.
   */
  parseExpression(breakOnInfix, breakOnTokenText) {
    var body = [];
    while (true) {
      if (this.mode === "math") {
        this.consumeSpaces();
      }
      var lex = this.fetch();
      if (_Parser.endOfExpression.indexOf(lex.text) !== -1) {
        break;
      }
      if (breakOnTokenText && lex.text === breakOnTokenText) {
        break;
      }
      if (breakOnInfix && functions[lex.text] && functions[lex.text].infix) {
        break;
      }
      var atom = this.parseAtom(breakOnTokenText);
      if (!atom) {
        break;
      } else if (atom.type === "internal") {
        continue;
      }
      body.push(atom);
    }
    if (this.mode === "text") {
      this.formLigatures(body);
    }
    return this.handleInfixNodes(body);
  }
  /**
   * Rewrites infix operators such as \over with corresponding commands such
   * as \frac.
   *
   * There can only be one infix operator per group.  If there's more than one
   * then the expression is ambiguous.  This can be resolved by adding {}.
   */
  handleInfixNodes(body) {
    var overIndex = -1;
    var funcName;
    for (var i7 = 0; i7 < body.length; i7++) {
      if (body[i7].type === "infix") {
        if (overIndex !== -1) {
          throw new ParseError("only one infix operator per group", body[i7].token);
        }
        overIndex = i7;
        funcName = body[i7].replaceWith;
      }
    }
    if (overIndex !== -1 && funcName) {
      var numerNode;
      var denomNode;
      var numerBody = body.slice(0, overIndex);
      var denomBody = body.slice(overIndex + 1);
      if (numerBody.length === 1 && numerBody[0].type === "ordgroup") {
        numerNode = numerBody[0];
      } else {
        numerNode = {
          type: "ordgroup",
          mode: this.mode,
          body: numerBody
        };
      }
      if (denomBody.length === 1 && denomBody[0].type === "ordgroup") {
        denomNode = denomBody[0];
      } else {
        denomNode = {
          type: "ordgroup",
          mode: this.mode,
          body: denomBody
        };
      }
      var node;
      if (funcName === "\\\\abovefrac") {
        node = this.callFunction(funcName, [numerNode, body[overIndex], denomNode], []);
      } else {
        node = this.callFunction(funcName, [numerNode, denomNode], []);
      }
      return [node];
    } else {
      return body;
    }
  }
  /**
   * Handle a subscript or superscript with nice errors.
   */
  handleSupSubscript(name) {
    var symbolToken = this.fetch();
    var symbol = symbolToken.text;
    this.consume();
    this.consumeSpaces();
    var group;
    do {
      var _group;
      group = this.parseGroup(name);
    } while (((_group = group) == null ? void 0 : _group.type) === "internal");
    if (!group) {
      throw new ParseError("Expected group after '" + symbol + "'", symbolToken);
    }
    return group;
  }
  /**
   * Converts the textual input of an unsupported command into a text node
   * contained within a color node whose color is determined by errorColor
   */
  formatUnsupportedCmd(text3) {
    var textordArray = [];
    for (var i7 = 0; i7 < text3.length; i7++) {
      textordArray.push({
        type: "textord",
        mode: "text",
        text: text3[i7]
      });
    }
    var textNode = {
      type: "text",
      mode: this.mode,
      body: textordArray
    };
    var colorNode = {
      type: "color",
      mode: this.mode,
      color: this.settings.errorColor,
      body: [textNode]
    };
    return colorNode;
  }
  /**
   * Parses a group with optional super/subscripts.
   */
  parseAtom(breakOnTokenText) {
    var base = this.parseGroup("atom", breakOnTokenText);
    if ((base == null ? void 0 : base.type) === "internal") {
      return base;
    }
    if (this.mode === "text") {
      return base;
    }
    var superscript;
    var subscript;
    while (true) {
      this.consumeSpaces();
      var lex = this.fetch();
      if (lex.text === "\\limits" || lex.text === "\\nolimits") {
        if (base && base.type === "op") {
          var limits = lex.text === "\\limits";
          base.limits = limits;
          base.alwaysHandleSupSub = true;
        } else if (base && base.type === "operatorname") {
          if (base.alwaysHandleSupSub) {
            base.limits = lex.text === "\\limits";
          }
        } else {
          throw new ParseError("Limit controls must follow a math operator", lex);
        }
        this.consume();
      } else if (lex.text === "^") {
        if (superscript) {
          throw new ParseError("Double superscript", lex);
        }
        superscript = this.handleSupSubscript("superscript");
      } else if (lex.text === "_") {
        if (subscript) {
          throw new ParseError("Double subscript", lex);
        }
        subscript = this.handleSupSubscript("subscript");
      } else if (lex.text === "'") {
        if (superscript) {
          throw new ParseError("Double superscript", lex);
        }
        var prime = {
          type: "textord",
          mode: this.mode,
          text: "\\prime"
        };
        var primes = [prime];
        this.consume();
        while (this.fetch().text === "'") {
          primes.push(prime);
          this.consume();
        }
        if (this.fetch().text === "^") {
          primes.push(this.handleSupSubscript("superscript"));
        }
        superscript = {
          type: "ordgroup",
          mode: this.mode,
          body: primes
        };
      } else if (uSubsAndSups[lex.text]) {
        var isSub = unicodeSubRegEx.test(lex.text);
        var subsupTokens = [];
        subsupTokens.push(new Token(uSubsAndSups[lex.text]));
        this.consume();
        while (true) {
          var token = this.fetch().text;
          if (!uSubsAndSups[token]) {
            break;
          }
          if (unicodeSubRegEx.test(token) !== isSub) {
            break;
          }
          subsupTokens.unshift(new Token(uSubsAndSups[token]));
          this.consume();
        }
        var body = this.subparse(subsupTokens);
        if (isSub) {
          subscript = {
            type: "ordgroup",
            mode: "math",
            body
          };
        } else {
          superscript = {
            type: "ordgroup",
            mode: "math",
            body
          };
        }
      } else {
        break;
      }
    }
    if (superscript || subscript) {
      return {
        type: "supsub",
        mode: this.mode,
        base,
        sup: superscript,
        sub: subscript
      };
    } else {
      return base;
    }
  }
  /**
   * Parses an entire function, including its base and all of its arguments.
   */
  parseFunction(breakOnTokenText, name) {
    var token = this.fetch();
    var func = token.text;
    var funcData = functions[func];
    if (!funcData) {
      return null;
    }
    this.consume();
    if (name && name !== "atom" && !funcData.allowedInArgument) {
      throw new ParseError("Got function '" + func + "' with no arguments" + (name ? " as " + name : ""), token);
    } else if (this.mode === "text" && !funcData.allowedInText) {
      throw new ParseError("Can't use function '" + func + "' in text mode", token);
    } else if (this.mode === "math" && funcData.allowedInMath === false) {
      throw new ParseError("Can't use function '" + func + "' in math mode", token);
    }
    var {
      args,
      optArgs
    } = this.parseArguments(func, funcData);
    return this.callFunction(func, args, optArgs, token, breakOnTokenText);
  }
  /**
   * Call a function handler with a suitable context and arguments.
   */
  callFunction(name, args, optArgs, token, breakOnTokenText) {
    var context = {
      funcName: name,
      parser: this,
      token,
      breakOnTokenText
    };
    var func = functions[name];
    if (func && func.handler) {
      return func.handler(context, args, optArgs);
    } else {
      throw new ParseError("No function handler for " + name);
    }
  }
  /**
   * Parses the arguments of a function or environment
   */
  parseArguments(func, funcData) {
    var totalArgs = funcData.numArgs + funcData.numOptionalArgs;
    if (totalArgs === 0) {
      return {
        args: [],
        optArgs: []
      };
    }
    var args = [];
    var optArgs = [];
    for (var i7 = 0; i7 < totalArgs; i7++) {
      var argType = funcData.argTypes && funcData.argTypes[i7];
      var isOptional = i7 < funcData.numOptionalArgs;
      if (funcData.primitive && argType == null || // \sqrt expands into primitive if optional argument doesn't exist
      funcData.type === "sqrt" && i7 === 1 && optArgs[0] == null) {
        argType = "primitive";
      }
      var arg = this.parseGroupOfType("argument to '" + func + "'", argType, isOptional);
      if (isOptional) {
        optArgs.push(arg);
      } else if (arg != null) {
        args.push(arg);
      } else {
        throw new ParseError("Null argument, please report this as a bug");
      }
    }
    return {
      args,
      optArgs
    };
  }
  /**
   * Parses a group when the mode is changing.
   */
  parseGroupOfType(name, type, optional) {
    switch (type) {
      case "color":
        return this.parseColorGroup(optional);
      case "size":
        return this.parseSizeGroup(optional);
      case "url":
        return this.parseUrlGroup(optional);
      case "math":
      case "text":
        return this.parseArgumentGroup(optional, type);
      case "hbox": {
        var group = this.parseArgumentGroup(optional, "text");
        return group != null ? {
          type: "styling",
          mode: group.mode,
          body: [group],
          style: "text"
          // simulate \textstyle
        } : null;
      }
      case "raw": {
        var token = this.parseStringGroup("raw", optional);
        return token != null ? {
          type: "raw",
          mode: "text",
          string: token.text
        } : null;
      }
      case "primitive": {
        if (optional) {
          throw new ParseError("A primitive argument cannot be optional");
        }
        var _group2 = this.parseGroup(name);
        if (_group2 == null) {
          throw new ParseError("Expected group as " + name, this.fetch());
        }
        return _group2;
      }
      case "original":
      case null:
      case void 0:
        return this.parseArgumentGroup(optional);
      default:
        throw new ParseError("Unknown group type as " + name, this.fetch());
    }
  }
  /**
   * Discard any space tokens, fetching the next non-space token.
   */
  consumeSpaces() {
    while (this.fetch().text === " ") {
      this.consume();
    }
  }
  /**
   * Parses a group, essentially returning the string formed by the
   * brace-enclosed tokens plus some position information.
   */
  parseStringGroup(modeName, optional) {
    var argToken = this.gullet.scanArgument(optional);
    if (argToken == null) {
      return null;
    }
    var str2 = "";
    var nextToken;
    while ((nextToken = this.fetch()).text !== "EOF") {
      str2 += nextToken.text;
      this.consume();
    }
    this.consume();
    argToken.text = str2;
    return argToken;
  }
  /**
   * Parses a regex-delimited group: the largest sequence of tokens
   * whose concatenated strings match `regex`. Returns the string
   * formed by the tokens plus some position information.
   */
  parseRegexGroup(regex, modeName) {
    var firstToken = this.fetch();
    var lastToken = firstToken;
    var str2 = "";
    var nextToken;
    while ((nextToken = this.fetch()).text !== "EOF" && regex.test(str2 + nextToken.text)) {
      lastToken = nextToken;
      str2 += lastToken.text;
      this.consume();
    }
    if (str2 === "") {
      throw new ParseError("Invalid " + modeName + ": '" + firstToken.text + "'", firstToken);
    }
    return firstToken.range(lastToken, str2);
  }
  /**
   * Parses a color description.
   */
  parseColorGroup(optional) {
    var res = this.parseStringGroup("color", optional);
    if (res == null) {
      return null;
    }
    var match2 = /^(#[a-f0-9]{3}|#?[a-f0-9]{6}|[a-z]+)$/i.exec(res.text);
    if (!match2) {
      throw new ParseError("Invalid color: '" + res.text + "'", res);
    }
    var color = match2[0];
    if (/^[0-9a-f]{6}$/i.test(color)) {
      color = "#" + color;
    }
    return {
      type: "color-token",
      mode: this.mode,
      color
    };
  }
  /**
   * Parses a size specification, consisting of magnitude and unit.
   */
  parseSizeGroup(optional) {
    var res;
    var isBlank = false;
    this.gullet.consumeSpaces();
    if (!optional && this.gullet.future().text !== "{") {
      res = this.parseRegexGroup(/^[-+]? *(?:$|\d+|\d+\.\d*|\.\d*) *[a-z]{0,2} *$/, "size");
    } else {
      res = this.parseStringGroup("size", optional);
    }
    if (!res) {
      return null;
    }
    if (!optional && res.text.length === 0) {
      res.text = "0pt";
      isBlank = true;
    }
    var match2 = /([-+]?) *(\d+(?:\.\d*)?|\.\d+) *([a-z]{2})/.exec(res.text);
    if (!match2) {
      throw new ParseError("Invalid size: '" + res.text + "'", res);
    }
    var data = {
      number: +(match2[1] + match2[2]),
      // sign + magnitude, cast to number
      unit: match2[3]
    };
    if (!validUnit(data)) {
      throw new ParseError("Invalid unit: '" + data.unit + "'", res);
    }
    return {
      type: "size",
      mode: this.mode,
      value: data,
      isBlank
    };
  }
  /**
   * Parses an URL, checking escaped letters and allowed protocols,
   * and setting the catcode of % as an active character (as in \hyperref).
   */
  parseUrlGroup(optional) {
    this.gullet.lexer.setCatcode("%", 13);
    this.gullet.lexer.setCatcode("~", 12);
    var res = this.parseStringGroup("url", optional);
    this.gullet.lexer.setCatcode("%", 14);
    this.gullet.lexer.setCatcode("~", 13);
    if (res == null) {
      return null;
    }
    var url = res.text.replace(/\\([#$%&~_^{}])/g, "$1");
    return {
      type: "url",
      mode: this.mode,
      url
    };
  }
  /**
   * Parses an argument with the mode specified.
   */
  parseArgumentGroup(optional, mode) {
    var argToken = this.gullet.scanArgument(optional);
    if (argToken == null) {
      return null;
    }
    var outerMode = this.mode;
    if (mode) {
      this.switchMode(mode);
    }
    this.gullet.beginGroup();
    var expression = this.parseExpression(false, "EOF");
    this.expect("EOF");
    this.gullet.endGroup();
    var result = {
      type: "ordgroup",
      mode: this.mode,
      loc: argToken.loc,
      body: expression
    };
    if (mode) {
      this.switchMode(outerMode);
    }
    return result;
  }
  /**
   * Parses an ordinary group, which is either a single nucleus (like "x")
   * or an expression in braces (like "{x+y}") or an implicit group, a group
   * that starts at the current position, and ends right before a higher explicit
   * group ends, or at EOF.
   */
  parseGroup(name, breakOnTokenText) {
    var firstToken = this.fetch();
    var text3 = firstToken.text;
    var result;
    if (text3 === "{" || text3 === "\\begingroup") {
      this.consume();
      var groupEnd = text3 === "{" ? "}" : "\\endgroup";
      this.gullet.beginGroup();
      var expression = this.parseExpression(false, groupEnd);
      var lastToken = this.fetch();
      this.expect(groupEnd);
      this.gullet.endGroup();
      result = {
        type: "ordgroup",
        mode: this.mode,
        loc: SourceLocation.range(firstToken, lastToken),
        body: expression,
        // A group formed by \begingroup...\endgroup is a semi-simple group
        // which doesn't affect spacing in math mode, i.e., is transparent.
        // https://tex.stackexchange.com/questions/1930/when-should-one-
        // use-begingroup-instead-of-bgroup
        semisimple: text3 === "\\begingroup" || void 0
      };
    } else {
      result = this.parseFunction(breakOnTokenText, name) || this.parseSymbol();
      if (result == null && text3[0] === "\\" && !implicitCommands.hasOwnProperty(text3)) {
        if (this.settings.throwOnError) {
          throw new ParseError("Undefined control sequence: " + text3, firstToken);
        }
        result = this.formatUnsupportedCmd(text3);
        this.consume();
      }
    }
    return result;
  }
  /**
   * Form ligature-like combinations of characters for text mode.
   * This includes inputs like "--", "---", "``" and "''".
   * The result will simply replace multiple textord nodes with a single
   * character in each value by a single textord node having multiple
   * characters in its value.  The representation is still ASCII source.
   * The group will be modified in place.
   */
  formLigatures(group) {
    var n7 = group.length - 1;
    for (var i7 = 0; i7 < n7; ++i7) {
      var a3 = group[i7];
      var v4 = a3.text;
      if (v4 === "-" && group[i7 + 1].text === "-") {
        if (i7 + 1 < n7 && group[i7 + 2].text === "-") {
          group.splice(i7, 3, {
            type: "textord",
            mode: "text",
            loc: SourceLocation.range(a3, group[i7 + 2]),
            text: "---"
          });
          n7 -= 2;
        } else {
          group.splice(i7, 2, {
            type: "textord",
            mode: "text",
            loc: SourceLocation.range(a3, group[i7 + 1]),
            text: "--"
          });
          n7 -= 1;
        }
      }
      if ((v4 === "'" || v4 === "`") && group[i7 + 1].text === v4) {
        group.splice(i7, 2, {
          type: "textord",
          mode: "text",
          loc: SourceLocation.range(a3, group[i7 + 1]),
          text: v4 + v4
        });
        n7 -= 1;
      }
    }
  }
  /**
   * Parse a single symbol out of the string. Here, we handle single character
   * symbols and special functions like \verb.
   */
  parseSymbol() {
    var nucleus = this.fetch();
    var text3 = nucleus.text;
    if (/^\\verb[^a-zA-Z]/.test(text3)) {
      this.consume();
      var arg = text3.slice(5);
      var star3 = arg.charAt(0) === "*";
      if (star3) {
        arg = arg.slice(1);
      }
      if (arg.length < 2 || arg.charAt(0) !== arg.slice(-1)) {
        throw new ParseError("\\verb assertion failed --\n                    please report what input caused this bug");
      }
      arg = arg.slice(1, -1);
      return {
        type: "verb",
        mode: "text",
        body: arg,
        star: star3
      };
    }
    if (unicodeSymbols.hasOwnProperty(text3[0]) && !symbols[this.mode][text3[0]]) {
      if (this.settings.strict && this.mode === "math") {
        this.settings.reportNonstrict("unicodeTextInMathMode", 'Accented Unicode text character "' + text3[0] + '" used in math mode', nucleus);
      }
      text3 = unicodeSymbols[text3[0]] + text3.slice(1);
    }
    var match2 = combiningDiacriticalMarksEndRegex.exec(text3);
    if (match2) {
      text3 = text3.substring(0, match2.index);
      if (text3 === "i") {
        text3 = "\u0131";
      } else if (text3 === "j") {
        text3 = "\u0237";
      }
    }
    var symbol;
    if (symbols[this.mode][text3]) {
      if (this.settings.strict && this.mode === "math" && extraLatin.indexOf(text3) >= 0) {
        this.settings.reportNonstrict("unicodeTextInMathMode", 'Latin-1/Unicode text character "' + text3[0] + '" used in math mode', nucleus);
      }
      var group = symbols[this.mode][text3].group;
      var loc = SourceLocation.range(nucleus);
      var s6;
      if (ATOMS.hasOwnProperty(group)) {
        var family = group;
        s6 = {
          type: "atom",
          mode: this.mode,
          family,
          loc,
          text: text3
        };
      } else {
        s6 = {
          type: group,
          mode: this.mode,
          loc,
          text: text3
        };
      }
      symbol = s6;
    } else if (text3.charCodeAt(0) >= 128) {
      if (this.settings.strict) {
        if (!supportedCodepoint(text3.charCodeAt(0))) {
          this.settings.reportNonstrict("unknownSymbol", 'Unrecognized Unicode character "' + text3[0] + '"' + (" (" + text3.charCodeAt(0) + ")"), nucleus);
        } else if (this.mode === "math") {
          this.settings.reportNonstrict("unicodeTextInMathMode", 'Unicode text character "' + text3[0] + '" used in math mode', nucleus);
        }
      }
      symbol = {
        type: "textord",
        mode: "text",
        loc: SourceLocation.range(nucleus),
        text: text3
      };
    } else {
      return null;
    }
    this.consume();
    if (match2) {
      for (var i7 = 0; i7 < match2[0].length; i7++) {
        var accent2 = match2[0][i7];
        if (!unicodeAccents[accent2]) {
          throw new ParseError("Unknown accent ' " + accent2 + "'", nucleus);
        }
        var command = unicodeAccents[accent2][this.mode] || unicodeAccents[accent2].text;
        if (!command) {
          throw new ParseError("Accent " + accent2 + " unsupported in " + this.mode + " mode", nucleus);
        }
        symbol = {
          type: "accent",
          mode: this.mode,
          loc: SourceLocation.range(nucleus),
          label: command,
          isStretchy: false,
          isShifty: true,
          // $FlowFixMe
          base: symbol
        };
      }
    }
    return symbol;
  }
};
Parser.endOfExpression = ["}", "\\endgroup", "\\end", "\\right", "&"];
var parseTree = function parseTree2(toParse, settings) {
  if (!(typeof toParse === "string" || toParse instanceof String)) {
    throw new TypeError("KaTeX can only parse string typed expression");
  }
  var parser = new Parser(toParse, settings);
  delete parser.gullet.macros.current["\\df@tag"];
  var tree = parser.parse();
  delete parser.gullet.macros.current["\\current@color"];
  delete parser.gullet.macros.current["\\color"];
  if (parser.gullet.macros.get("\\df@tag")) {
    if (!settings.displayMode) {
      throw new ParseError("\\tag works only in display equations");
    }
    tree = [{
      type: "tag",
      mode: "text",
      body: tree,
      tag: parser.subparse([new Token("\\df@tag")])
    }];
  }
  return tree;
};
var render = function render2(expression, baseNode, options) {
  baseNode.textContent = "";
  var node = renderToDomTree(expression, options).toNode();
  baseNode.appendChild(node);
};
if (typeof document !== "undefined") {
  if (document.compatMode !== "CSS1Compat") {
    typeof console !== "undefined" && console.warn("Warning: KaTeX doesn't work in quirks mode. Make sure your website has a suitable doctype.");
    render = function render3() {
      throw new ParseError("KaTeX doesn't work in quirks mode.");
    };
  }
}
var renderToString = function renderToString2(expression, options) {
  var markup = renderToDomTree(expression, options).toMarkup();
  return markup;
};
var generateParseTree = function generateParseTree2(expression, options) {
  var settings = new Settings(options);
  return parseTree(expression, settings);
};
var renderError = function renderError2(error, expression, options) {
  if (options.throwOnError || !(error instanceof ParseError)) {
    throw error;
  }
  var node = buildCommon.makeSpan(["katex-error"], [new SymbolNode(expression)]);
  node.setAttribute("title", error.toString());
  node.setAttribute("style", "color:" + options.errorColor);
  return node;
};
var renderToDomTree = function renderToDomTree2(expression, options) {
  var settings = new Settings(options);
  try {
    var tree = parseTree(expression, settings);
    return buildTree(tree, expression, settings);
  } catch (error) {
    return renderError(error, expression, settings);
  }
};
var renderToHTMLTree = function renderToHTMLTree2(expression, options) {
  var settings = new Settings(options);
  try {
    var tree = parseTree(expression, settings);
    return buildHTMLTree(tree, expression, settings);
  } catch (error) {
    return renderError(error, expression, settings);
  }
};
var version4 = "0.16.22";
var __domTree = {
  Span,
  Anchor,
  SymbolNode,
  SvgNode,
  PathNode,
  LineNode
};
var katex = {
  /**
   * Current KaTeX version
   */
  version: version4,
  /**
   * Renders the given LaTeX into an HTML+MathML combination, and adds
   * it as a child to the specified DOM node.
   */
  render,
  /**
   * Renders the given LaTeX into an HTML+MathML combination string,
   * for sending to the client.
   */
  renderToString,
  /**
   * KaTeX error, usually during parsing.
   */
  ParseError,
  /**
   * The schema of Settings
   */
  SETTINGS_SCHEMA,
  /**
   * Parses the given LaTeX into KaTeX's internal parse tree structure,
   * without rendering to HTML or MathML.
   *
   * NOTE: This method is not currently recommended for public use.
   * The internal tree representation is unstable and is very likely
   * to change. Use at your own risk.
   */
  __parse: generateParseTree,
  /**
   * Renders the given LaTeX into an HTML+MathML internal DOM tree
   * representation, without flattening that representation to a string.
   *
   * NOTE: This method is not currently recommended for public use.
   * The internal tree representation is unstable and is very likely
   * to change. Use at your own risk.
   */
  __renderToDomTree: renderToDomTree,
  /**
   * Renders the given LaTeX into an HTML internal DOM tree representation,
   * without MathML and without flattening that representation to a string.
   *
   * NOTE: This method is not currently recommended for public use.
   * The internal tree representation is unstable and is very likely
   * to change. Use at your own risk.
   */
  __renderToHTMLTree: renderToHTMLTree,
  /**
   * extends internal font metrics object with a new object
   * each key in the new object represents a font name
  */
  __setFontMetrics: setFontMetrics,
  /**
   * adds a new symbol to builtin symbols table
   */
  __defineSymbol: defineSymbol,
  /**
   * adds a new function to builtin function list,
   * which directly produce parse tree elements
   * and have their own html/mathml builders
   */
  __defineFunction: defineFunction,
  /**
   * adds a new macro to builtin macro list
   */
  __defineMacro: defineMacro,
  /**
   * Expose the dom tree node types, which can be useful for type checking nodes.
   *
   * NOTE: These methods are not currently recommended for public use.
   * The internal tree representation is unstable and is very likely
   * to change. Use at your own risk.
   */
  __domTree
};

// ../mini-lit/node_modules/marked/lib/marked.esm.js
init_process_shim();
function L2() {
  return { async: false, breaks: false, extensions: null, gfm: true, hooks: null, pedantic: false, renderer: null, silent: false, tokenizer: null, walkTokens: null };
}
var O = L2();
function G(l5) {
  O = l5;
}
var E2 = { exec: () => null };
function h6(l5, e9 = "") {
  let t6 = typeof l5 == "string" ? l5 : l5.source, n7 = { replace: (r8, i7) => {
    let s6 = typeof i7 == "string" ? i7 : i7.source;
    return s6 = s6.replace(m3.caret, "$1"), t6 = t6.replace(r8, s6), n7;
  }, getRegex: () => new RegExp(t6, e9) };
  return n7;
}
var m3 = { codeRemoveIndent: /^(?: {1,4}| {0,3}\t)/gm, outputLinkReplace: /\\([\[\]])/g, indentCodeCompensation: /^(\s+)(?:```)/, beginningSpace: /^\s+/, endingHash: /#$/, startingSpaceChar: /^ /, endingSpaceChar: / $/, nonSpaceChar: /[^ ]/, newLineCharGlobal: /\n/g, tabCharGlobal: /\t/g, multipleSpaceGlobal: /\s+/g, blankLine: /^[ \t]*$/, doubleBlankLine: /\n[ \t]*\n[ \t]*$/, blockquoteStart: /^ {0,3}>/, blockquoteSetextReplace: /\n {0,3}((?:=+|-+) *)(?=\n|$)/g, blockquoteSetextReplace2: /^ {0,3}>[ \t]?/gm, listReplaceTabs: /^\t+/, listReplaceNesting: /^ {1,4}(?=( {4})*[^ ])/g, listIsTask: /^\[[ xX]\] /, listReplaceTask: /^\[[ xX]\] +/, anyLine: /\n.*\n/, hrefBrackets: /^<(.*)>$/, tableDelimiter: /[:|]/, tableAlignChars: /^\||\| *$/g, tableRowBlankLine: /\n[ \t]*$/, tableAlignRight: /^ *-+: *$/, tableAlignCenter: /^ *:-+: *$/, tableAlignLeft: /^ *:-+ *$/, startATag: /^<a /i, endATag: /^<\/a>/i, startPreScriptTag: /^<(pre|code|kbd|script)(\s|>)/i, endPreScriptTag: /^<\/(pre|code|kbd|script)(\s|>)/i, startAngleBracket: /^</, endAngleBracket: />$/, pedanticHrefTitle: /^([^'"]*[^\s])\s+(['"])(.*)\2/, unicodeAlphaNumeric: /[\p{L}\p{N}]/u, escapeTest: /[&<>"']/, escapeReplace: /[&<>"']/g, escapeTestNoEncode: /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/, escapeReplaceNoEncode: /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g, unescapeTest: /&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig, caret: /(^|[^\[])\^/g, percentDecode: /%25/g, findPipe: /\|/g, splitPipe: / \|/, slashPipe: /\\\|/g, carriageReturn: /\r\n|\r/g, spaceLine: /^ +$/gm, notSpaceStart: /^\S*/, endingNewline: /\n$/, listItemRegex: (l5) => new RegExp(`^( {0,3}${l5})((?:[	 ][^\\n]*)?(?:\\n|$))`), nextBulletRegex: (l5) => new RegExp(`^ {0,${Math.min(3, l5 - 1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ 	][^\\n]*)?(?:\\n|$))`), hrRegex: (l5) => new RegExp(`^ {0,${Math.min(3, l5 - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`), fencesBeginRegex: (l5) => new RegExp(`^ {0,${Math.min(3, l5 - 1)}}(?:\`\`\`|~~~)`), headingBeginRegex: (l5) => new RegExp(`^ {0,${Math.min(3, l5 - 1)}}#`), htmlBeginRegex: (l5) => new RegExp(`^ {0,${Math.min(3, l5 - 1)}}<(?:[a-z].*>|!--)`, "i") };
var xe = /^(?:[ \t]*(?:\n|$))+/;
var be = /^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/;
var Re = /^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/;
var C2 = /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/;
var Oe = /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/;
var j2 = /(?:[*+-]|\d{1,9}[.)])/;
var se = /^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/;
var ie = h6(se).replace(/bull/g, j2).replace(/blockCode/g, /(?: {4}| {0,3}\t)/).replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g, / {0,3}>/).replace(/heading/g, / {0,3}#{1,6}/).replace(/html/g, / {0,3}<[^\n>]+>\n/).replace(/\|table/g, "").getRegex();
var Te = h6(se).replace(/bull/g, j2).replace(/blockCode/g, /(?: {4}| {0,3}\t)/).replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g, / {0,3}>/).replace(/heading/g, / {0,3}#{1,6}/).replace(/html/g, / {0,3}<[^\n>]+>\n/).replace(/table/g, / {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex();
var F = /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/;
var we = /^[^\n]+/;
var Q = /(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/;
var ye = h6(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label", Q).replace("title", /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex();
var Pe = h6(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g, j2).getRegex();
var v3 = "address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul";
var U = /<!--(?:-?>|[\s\S]*?(?:-->|$))/;
var Se = h6("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ 	]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ 	]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ 	]*)+\\n|$))", "i").replace("comment", U).replace("tag", v3).replace("attribute", / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex();
var oe = h6(F).replace("hr", C2).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("|lheading", "").replace("|table", "").replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", "</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", v3).getRegex();
var $e = h6(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph", oe).getRegex();
var K = { blockquote: $e, code: be, def: ye, fences: Re, heading: Oe, hr: C2, html: Se, lheading: ie, list: Pe, newline: xe, paragraph: oe, table: E2, text: we };
var re = h6("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr", C2).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("blockquote", " {0,3}>").replace("code", "(?: {4}| {0,3}	)[^\\n]").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", "</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", v3).getRegex();
var _e = { ...K, lheading: Te, table: re, paragraph: h6(F).replace("hr", C2).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("|lheading", "").replace("table", re).replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", "</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", v3).getRegex() };
var Le = { ...K, html: h6(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment", U).replace(/tag/g, "(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(), def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/, heading: /^(#{1,6})(.*)(?:\n+|$)/, fences: E2, lheading: /^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/, paragraph: h6(F).replace("hr", C2).replace("heading", ` *#{1,6} *[^
]`).replace("lheading", ie).replace("|table", "").replace("blockquote", " {0,3}>").replace("|fences", "").replace("|list", "").replace("|html", "").replace("|tag", "").getRegex() };
var Me = /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/;
var ze = /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/;
var ae = /^( {2,}|\\)\n(?!\s*$)/;
var Ae = /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/;
var D3 = /[\p{P}\p{S}]/u;
var W = /[\s\p{P}\p{S}]/u;
var le = /[^\s\p{P}\p{S}]/u;
var Ee = h6(/^((?![*_])punctSpace)/, "u").replace(/punctSpace/g, W).getRegex();
var ue = /(?!~)[\p{P}\p{S}]/u;
var Ce = /(?!~)[\s\p{P}\p{S}]/u;
var Ie = /(?:[^\s\p{P}\p{S}]|~)/u;
var Be = /\[[^\[\]]*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)|`[^`]*?`|<(?! )[^<>]*?>/g;
var pe = /^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/;
var qe = h6(pe, "u").replace(/punct/g, D3).getRegex();
var ve = h6(pe, "u").replace(/punct/g, ue).getRegex();
var ce = "^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)";
var De = h6(ce, "gu").replace(/notPunctSpace/g, le).replace(/punctSpace/g, W).replace(/punct/g, D3).getRegex();
var He = h6(ce, "gu").replace(/notPunctSpace/g, Ie).replace(/punctSpace/g, Ce).replace(/punct/g, ue).getRegex();
var Ze = h6("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)", "gu").replace(/notPunctSpace/g, le).replace(/punctSpace/g, W).replace(/punct/g, D3).getRegex();
var Ge = h6(/\\(punct)/, "gu").replace(/punct/g, D3).getRegex();
var Ne = h6(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme", /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email", /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex();
var je = h6(U).replace("(?:-->|$)", "-->").getRegex();
var Fe = h6("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment", je).replace("attribute", /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex();
var q = /(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`[^`]*`|[^\[\]\\`])*?/;
var Qe = h6(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label", q).replace("href", /<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title", /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex();
var he = h6(/^!?\[(label)\]\[(ref)\]/).replace("label", q).replace("ref", Q).getRegex();
var de = h6(/^!?\[(ref)\](?:\[\])?/).replace("ref", Q).getRegex();
var Ue = h6("reflink|nolink(?!\\()", "g").replace("reflink", he).replace("nolink", de).getRegex();
var X2 = { _backpedal: E2, anyPunctuation: Ge, autolink: Ne, blockSkip: Be, br: ae, code: ze, del: E2, emStrongLDelim: qe, emStrongRDelimAst: De, emStrongRDelimUnd: Ze, escape: Me, link: Qe, nolink: de, punctuation: Ee, reflink: he, reflinkSearch: Ue, tag: Fe, text: Ae, url: E2 };
var Ke = { ...X2, link: h6(/^!?\[(label)\]\((.*?)\)/).replace("label", q).getRegex(), reflink: h6(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label", q).getRegex() };
var N2 = { ...X2, emStrongRDelimAst: He, emStrongLDelim: ve, url: h6(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/, "i").replace("email", /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(), _backpedal: /(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/, del: /^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/, text: /^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/ };
var We = { ...N2, br: h6(ae).replace("{2,}", "*").getRegex(), text: h6(N2.text).replace("\\b_", "\\b_| {2,}\\n").replace(/\{2,\}/g, "*").getRegex() };
var I2 = { normal: K, gfm: _e, pedantic: Le };
var M3 = { normal: X2, gfm: N2, breaks: We, pedantic: Ke };
var Xe = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" };
var ke = (l5) => Xe[l5];
function w2(l5, e9) {
  if (e9) {
    if (m3.escapeTest.test(l5)) return l5.replace(m3.escapeReplace, ke);
  } else if (m3.escapeTestNoEncode.test(l5)) return l5.replace(m3.escapeReplaceNoEncode, ke);
  return l5;
}
function J(l5) {
  try {
    l5 = encodeURI(l5).replace(m3.percentDecode, "%");
  } catch {
    return null;
  }
  return l5;
}
function V2(l5, e9) {
  let t6 = l5.replace(m3.findPipe, (i7, s6, o9) => {
    let a3 = false, u5 = s6;
    for (; --u5 >= 0 && o9[u5] === "\\"; ) a3 = !a3;
    return a3 ? "|" : " |";
  }), n7 = t6.split(m3.splitPipe), r8 = 0;
  if (n7[0].trim() || n7.shift(), n7.length > 0 && !n7.at(-1)?.trim() && n7.pop(), e9) if (n7.length > e9) n7.splice(e9);
  else for (; n7.length < e9; ) n7.push("");
  for (; r8 < n7.length; r8++) n7[r8] = n7[r8].trim().replace(m3.slashPipe, "|");
  return n7;
}
function z2(l5, e9, t6) {
  let n7 = l5.length;
  if (n7 === 0) return "";
  let r8 = 0;
  for (; r8 < n7; ) {
    let i7 = l5.charAt(n7 - r8 - 1);
    if (i7 === e9 && !t6) r8++;
    else if (i7 !== e9 && t6) r8++;
    else break;
  }
  return l5.slice(0, n7 - r8);
}
function ge(l5, e9) {
  if (l5.indexOf(e9[1]) === -1) return -1;
  let t6 = 0;
  for (let n7 = 0; n7 < l5.length; n7++) if (l5[n7] === "\\") n7++;
  else if (l5[n7] === e9[0]) t6++;
  else if (l5[n7] === e9[1] && (t6--, t6 < 0)) return n7;
  return t6 > 0 ? -2 : -1;
}
function fe(l5, e9, t6, n7, r8) {
  let i7 = e9.href, s6 = e9.title || null, o9 = l5[1].replace(r8.other.outputLinkReplace, "$1");
  n7.state.inLink = true;
  let a3 = { type: l5[0].charAt(0) === "!" ? "image" : "link", raw: t6, href: i7, title: s6, text: o9, tokens: n7.inlineTokens(o9) };
  return n7.state.inLink = false, a3;
}
function Je(l5, e9, t6) {
  let n7 = l5.match(t6.other.indentCodeCompensation);
  if (n7 === null) return e9;
  let r8 = n7[1];
  return e9.split(`
`).map((i7) => {
    let s6 = i7.match(t6.other.beginningSpace);
    if (s6 === null) return i7;
    let [o9] = s6;
    return o9.length >= r8.length ? i7.slice(r8.length) : i7;
  }).join(`
`);
}
var y3 = class {
  options;
  rules;
  lexer;
  constructor(e9) {
    this.options = e9 || O;
  }
  space(e9) {
    let t6 = this.rules.block.newline.exec(e9);
    if (t6 && t6[0].length > 0) return { type: "space", raw: t6[0] };
  }
  code(e9) {
    let t6 = this.rules.block.code.exec(e9);
    if (t6) {
      let n7 = t6[0].replace(this.rules.other.codeRemoveIndent, "");
      return { type: "code", raw: t6[0], codeBlockStyle: "indented", text: this.options.pedantic ? n7 : z2(n7, `
`) };
    }
  }
  fences(e9) {
    let t6 = this.rules.block.fences.exec(e9);
    if (t6) {
      let n7 = t6[0], r8 = Je(n7, t6[3] || "", this.rules);
      return { type: "code", raw: n7, lang: t6[2] ? t6[2].trim().replace(this.rules.inline.anyPunctuation, "$1") : t6[2], text: r8 };
    }
  }
  heading(e9) {
    let t6 = this.rules.block.heading.exec(e9);
    if (t6) {
      let n7 = t6[2].trim();
      if (this.rules.other.endingHash.test(n7)) {
        let r8 = z2(n7, "#");
        (this.options.pedantic || !r8 || this.rules.other.endingSpaceChar.test(r8)) && (n7 = r8.trim());
      }
      return { type: "heading", raw: t6[0], depth: t6[1].length, text: n7, tokens: this.lexer.inline(n7) };
    }
  }
  hr(e9) {
    let t6 = this.rules.block.hr.exec(e9);
    if (t6) return { type: "hr", raw: z2(t6[0], `
`) };
  }
  blockquote(e9) {
    let t6 = this.rules.block.blockquote.exec(e9);
    if (t6) {
      let n7 = z2(t6[0], `
`).split(`
`), r8 = "", i7 = "", s6 = [];
      for (; n7.length > 0; ) {
        let o9 = false, a3 = [], u5;
        for (u5 = 0; u5 < n7.length; u5++) if (this.rules.other.blockquoteStart.test(n7[u5])) a3.push(n7[u5]), o9 = true;
        else if (!o9) a3.push(n7[u5]);
        else break;
        n7 = n7.slice(u5);
        let p4 = a3.join(`
`), c6 = p4.replace(this.rules.other.blockquoteSetextReplace, `
    $1`).replace(this.rules.other.blockquoteSetextReplace2, "");
        r8 = r8 ? `${r8}
${p4}` : p4, i7 = i7 ? `${i7}
${c6}` : c6;
        let f4 = this.lexer.state.top;
        if (this.lexer.state.top = true, this.lexer.blockTokens(c6, s6, true), this.lexer.state.top = f4, n7.length === 0) break;
        let k2 = s6.at(-1);
        if (k2?.type === "code") break;
        if (k2?.type === "blockquote") {
          let x2 = k2, g3 = x2.raw + `
` + n7.join(`
`), T3 = this.blockquote(g3);
          s6[s6.length - 1] = T3, r8 = r8.substring(0, r8.length - x2.raw.length) + T3.raw, i7 = i7.substring(0, i7.length - x2.text.length) + T3.text;
          break;
        } else if (k2?.type === "list") {
          let x2 = k2, g3 = x2.raw + `
` + n7.join(`
`), T3 = this.list(g3);
          s6[s6.length - 1] = T3, r8 = r8.substring(0, r8.length - k2.raw.length) + T3.raw, i7 = i7.substring(0, i7.length - x2.raw.length) + T3.raw, n7 = g3.substring(s6.at(-1).raw.length).split(`
`);
          continue;
        }
      }
      return { type: "blockquote", raw: r8, tokens: s6, text: i7 };
    }
  }
  list(e9) {
    let t6 = this.rules.block.list.exec(e9);
    if (t6) {
      let n7 = t6[1].trim(), r8 = n7.length > 1, i7 = { type: "list", raw: "", ordered: r8, start: r8 ? +n7.slice(0, -1) : "", loose: false, items: [] };
      n7 = r8 ? `\\d{1,9}\\${n7.slice(-1)}` : `\\${n7}`, this.options.pedantic && (n7 = r8 ? n7 : "[*+-]");
      let s6 = this.rules.other.listItemRegex(n7), o9 = false;
      for (; e9; ) {
        let u5 = false, p4 = "", c6 = "";
        if (!(t6 = s6.exec(e9)) || this.rules.block.hr.test(e9)) break;
        p4 = t6[0], e9 = e9.substring(p4.length);
        let f4 = t6[2].split(`
`, 1)[0].replace(this.rules.other.listReplaceTabs, (H2) => " ".repeat(3 * H2.length)), k2 = e9.split(`
`, 1)[0], x2 = !f4.trim(), g3 = 0;
        if (this.options.pedantic ? (g3 = 2, c6 = f4.trimStart()) : x2 ? g3 = t6[1].length + 1 : (g3 = t6[2].search(this.rules.other.nonSpaceChar), g3 = g3 > 4 ? 1 : g3, c6 = f4.slice(g3), g3 += t6[1].length), x2 && this.rules.other.blankLine.test(k2) && (p4 += k2 + `
`, e9 = e9.substring(k2.length + 1), u5 = true), !u5) {
          let H2 = this.rules.other.nextBulletRegex(g3), ee = this.rules.other.hrRegex(g3), te = this.rules.other.fencesBeginRegex(g3), ne = this.rules.other.headingBeginRegex(g3), me = this.rules.other.htmlBeginRegex(g3);
          for (; e9; ) {
            let Z2 = e9.split(`
`, 1)[0], A2;
            if (k2 = Z2, this.options.pedantic ? (k2 = k2.replace(this.rules.other.listReplaceNesting, "  "), A2 = k2) : A2 = k2.replace(this.rules.other.tabCharGlobal, "    "), te.test(k2) || ne.test(k2) || me.test(k2) || H2.test(k2) || ee.test(k2)) break;
            if (A2.search(this.rules.other.nonSpaceChar) >= g3 || !k2.trim()) c6 += `
` + A2.slice(g3);
            else {
              if (x2 || f4.replace(this.rules.other.tabCharGlobal, "    ").search(this.rules.other.nonSpaceChar) >= 4 || te.test(f4) || ne.test(f4) || ee.test(f4)) break;
              c6 += `
` + k2;
            }
            !x2 && !k2.trim() && (x2 = true), p4 += Z2 + `
`, e9 = e9.substring(Z2.length + 1), f4 = A2.slice(g3);
          }
        }
        i7.loose || (o9 ? i7.loose = true : this.rules.other.doubleBlankLine.test(p4) && (o9 = true));
        let T3 = null, Y;
        this.options.gfm && (T3 = this.rules.other.listIsTask.exec(c6), T3 && (Y = T3[0] !== "[ ] ", c6 = c6.replace(this.rules.other.listReplaceTask, ""))), i7.items.push({ type: "list_item", raw: p4, task: !!T3, checked: Y, loose: false, text: c6, tokens: [] }), i7.raw += p4;
      }
      let a3 = i7.items.at(-1);
      if (a3) a3.raw = a3.raw.trimEnd(), a3.text = a3.text.trimEnd();
      else return;
      i7.raw = i7.raw.trimEnd();
      for (let u5 = 0; u5 < i7.items.length; u5++) if (this.lexer.state.top = false, i7.items[u5].tokens = this.lexer.blockTokens(i7.items[u5].text, []), !i7.loose) {
        let p4 = i7.items[u5].tokens.filter((f4) => f4.type === "space"), c6 = p4.length > 0 && p4.some((f4) => this.rules.other.anyLine.test(f4.raw));
        i7.loose = c6;
      }
      if (i7.loose) for (let u5 = 0; u5 < i7.items.length; u5++) i7.items[u5].loose = true;
      return i7;
    }
  }
  html(e9) {
    let t6 = this.rules.block.html.exec(e9);
    if (t6) return { type: "html", block: true, raw: t6[0], pre: t6[1] === "pre" || t6[1] === "script" || t6[1] === "style", text: t6[0] };
  }
  def(e9) {
    let t6 = this.rules.block.def.exec(e9);
    if (t6) {
      let n7 = t6[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal, " "), r8 = t6[2] ? t6[2].replace(this.rules.other.hrefBrackets, "$1").replace(this.rules.inline.anyPunctuation, "$1") : "", i7 = t6[3] ? t6[3].substring(1, t6[3].length - 1).replace(this.rules.inline.anyPunctuation, "$1") : t6[3];
      return { type: "def", tag: n7, raw: t6[0], href: r8, title: i7 };
    }
  }
  table(e9) {
    let t6 = this.rules.block.table.exec(e9);
    if (!t6 || !this.rules.other.tableDelimiter.test(t6[2])) return;
    let n7 = V2(t6[1]), r8 = t6[2].replace(this.rules.other.tableAlignChars, "").split("|"), i7 = t6[3]?.trim() ? t6[3].replace(this.rules.other.tableRowBlankLine, "").split(`
`) : [], s6 = { type: "table", raw: t6[0], header: [], align: [], rows: [] };
    if (n7.length === r8.length) {
      for (let o9 of r8) this.rules.other.tableAlignRight.test(o9) ? s6.align.push("right") : this.rules.other.tableAlignCenter.test(o9) ? s6.align.push("center") : this.rules.other.tableAlignLeft.test(o9) ? s6.align.push("left") : s6.align.push(null);
      for (let o9 = 0; o9 < n7.length; o9++) s6.header.push({ text: n7[o9], tokens: this.lexer.inline(n7[o9]), header: true, align: s6.align[o9] });
      for (let o9 of i7) s6.rows.push(V2(o9, s6.header.length).map((a3, u5) => ({ text: a3, tokens: this.lexer.inline(a3), header: false, align: s6.align[u5] })));
      return s6;
    }
  }
  lheading(e9) {
    let t6 = this.rules.block.lheading.exec(e9);
    if (t6) return { type: "heading", raw: t6[0], depth: t6[2].charAt(0) === "=" ? 1 : 2, text: t6[1], tokens: this.lexer.inline(t6[1]) };
  }
  paragraph(e9) {
    let t6 = this.rules.block.paragraph.exec(e9);
    if (t6) {
      let n7 = t6[1].charAt(t6[1].length - 1) === `
` ? t6[1].slice(0, -1) : t6[1];
      return { type: "paragraph", raw: t6[0], text: n7, tokens: this.lexer.inline(n7) };
    }
  }
  text(e9) {
    let t6 = this.rules.block.text.exec(e9);
    if (t6) return { type: "text", raw: t6[0], text: t6[0], tokens: this.lexer.inline(t6[0]) };
  }
  escape(e9) {
    let t6 = this.rules.inline.escape.exec(e9);
    if (t6) return { type: "escape", raw: t6[0], text: t6[1] };
  }
  tag(e9) {
    let t6 = this.rules.inline.tag.exec(e9);
    if (t6) return !this.lexer.state.inLink && this.rules.other.startATag.test(t6[0]) ? this.lexer.state.inLink = true : this.lexer.state.inLink && this.rules.other.endATag.test(t6[0]) && (this.lexer.state.inLink = false), !this.lexer.state.inRawBlock && this.rules.other.startPreScriptTag.test(t6[0]) ? this.lexer.state.inRawBlock = true : this.lexer.state.inRawBlock && this.rules.other.endPreScriptTag.test(t6[0]) && (this.lexer.state.inRawBlock = false), { type: "html", raw: t6[0], inLink: this.lexer.state.inLink, inRawBlock: this.lexer.state.inRawBlock, block: false, text: t6[0] };
  }
  link(e9) {
    let t6 = this.rules.inline.link.exec(e9);
    if (t6) {
      let n7 = t6[2].trim();
      if (!this.options.pedantic && this.rules.other.startAngleBracket.test(n7)) {
        if (!this.rules.other.endAngleBracket.test(n7)) return;
        let s6 = z2(n7.slice(0, -1), "\\");
        if ((n7.length - s6.length) % 2 === 0) return;
      } else {
        let s6 = ge(t6[2], "()");
        if (s6 === -2) return;
        if (s6 > -1) {
          let a3 = (t6[0].indexOf("!") === 0 ? 5 : 4) + t6[1].length + s6;
          t6[2] = t6[2].substring(0, s6), t6[0] = t6[0].substring(0, a3).trim(), t6[3] = "";
        }
      }
      let r8 = t6[2], i7 = "";
      if (this.options.pedantic) {
        let s6 = this.rules.other.pedanticHrefTitle.exec(r8);
        s6 && (r8 = s6[1], i7 = s6[3]);
      } else i7 = t6[3] ? t6[3].slice(1, -1) : "";
      return r8 = r8.trim(), this.rules.other.startAngleBracket.test(r8) && (this.options.pedantic && !this.rules.other.endAngleBracket.test(n7) ? r8 = r8.slice(1) : r8 = r8.slice(1, -1)), fe(t6, { href: r8 && r8.replace(this.rules.inline.anyPunctuation, "$1"), title: i7 && i7.replace(this.rules.inline.anyPunctuation, "$1") }, t6[0], this.lexer, this.rules);
    }
  }
  reflink(e9, t6) {
    let n7;
    if ((n7 = this.rules.inline.reflink.exec(e9)) || (n7 = this.rules.inline.nolink.exec(e9))) {
      let r8 = (n7[2] || n7[1]).replace(this.rules.other.multipleSpaceGlobal, " "), i7 = t6[r8.toLowerCase()];
      if (!i7) {
        let s6 = n7[0].charAt(0);
        return { type: "text", raw: s6, text: s6 };
      }
      return fe(n7, i7, n7[0], this.lexer, this.rules);
    }
  }
  emStrong(e9, t6, n7 = "") {
    let r8 = this.rules.inline.emStrongLDelim.exec(e9);
    if (!r8 || r8[3] && n7.match(this.rules.other.unicodeAlphaNumeric)) return;
    if (!(r8[1] || r8[2] || "") || !n7 || this.rules.inline.punctuation.exec(n7)) {
      let s6 = [...r8[0]].length - 1, o9, a3, u5 = s6, p4 = 0, c6 = r8[0][0] === "*" ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd;
      for (c6.lastIndex = 0, t6 = t6.slice(-1 * e9.length + s6); (r8 = c6.exec(t6)) != null; ) {
        if (o9 = r8[1] || r8[2] || r8[3] || r8[4] || r8[5] || r8[6], !o9) continue;
        if (a3 = [...o9].length, r8[3] || r8[4]) {
          u5 += a3;
          continue;
        } else if ((r8[5] || r8[6]) && s6 % 3 && !((s6 + a3) % 3)) {
          p4 += a3;
          continue;
        }
        if (u5 -= a3, u5 > 0) continue;
        a3 = Math.min(a3, a3 + u5 + p4);
        let f4 = [...r8[0]][0].length, k2 = e9.slice(0, s6 + r8.index + f4 + a3);
        if (Math.min(s6, a3) % 2) {
          let g3 = k2.slice(1, -1);
          return { type: "em", raw: k2, text: g3, tokens: this.lexer.inlineTokens(g3) };
        }
        let x2 = k2.slice(2, -2);
        return { type: "strong", raw: k2, text: x2, tokens: this.lexer.inlineTokens(x2) };
      }
    }
  }
  codespan(e9) {
    let t6 = this.rules.inline.code.exec(e9);
    if (t6) {
      let n7 = t6[2].replace(this.rules.other.newLineCharGlobal, " "), r8 = this.rules.other.nonSpaceChar.test(n7), i7 = this.rules.other.startingSpaceChar.test(n7) && this.rules.other.endingSpaceChar.test(n7);
      return r8 && i7 && (n7 = n7.substring(1, n7.length - 1)), { type: "codespan", raw: t6[0], text: n7 };
    }
  }
  br(e9) {
    let t6 = this.rules.inline.br.exec(e9);
    if (t6) return { type: "br", raw: t6[0] };
  }
  del(e9) {
    let t6 = this.rules.inline.del.exec(e9);
    if (t6) return { type: "del", raw: t6[0], text: t6[2], tokens: this.lexer.inlineTokens(t6[2]) };
  }
  autolink(e9) {
    let t6 = this.rules.inline.autolink.exec(e9);
    if (t6) {
      let n7, r8;
      return t6[2] === "@" ? (n7 = t6[1], r8 = "mailto:" + n7) : (n7 = t6[1], r8 = n7), { type: "link", raw: t6[0], text: n7, href: r8, tokens: [{ type: "text", raw: n7, text: n7 }] };
    }
  }
  url(e9) {
    let t6;
    if (t6 = this.rules.inline.url.exec(e9)) {
      let n7, r8;
      if (t6[2] === "@") n7 = t6[0], r8 = "mailto:" + n7;
      else {
        let i7;
        do
          i7 = t6[0], t6[0] = this.rules.inline._backpedal.exec(t6[0])?.[0] ?? "";
        while (i7 !== t6[0]);
        n7 = t6[0], t6[1] === "www." ? r8 = "http://" + t6[0] : r8 = t6[0];
      }
      return { type: "link", raw: t6[0], text: n7, href: r8, tokens: [{ type: "text", raw: n7, text: n7 }] };
    }
  }
  inlineText(e9) {
    let t6 = this.rules.inline.text.exec(e9);
    if (t6) {
      let n7 = this.lexer.state.inRawBlock;
      return { type: "text", raw: t6[0], text: t6[0], escaped: n7 };
    }
  }
};
var b3 = class l3 {
  tokens;
  options;
  state;
  tokenizer;
  inlineQueue;
  constructor(e9) {
    this.tokens = [], this.tokens.links = /* @__PURE__ */ Object.create(null), this.options = e9 || O, this.options.tokenizer = this.options.tokenizer || new y3(), this.tokenizer = this.options.tokenizer, this.tokenizer.options = this.options, this.tokenizer.lexer = this, this.inlineQueue = [], this.state = { inLink: false, inRawBlock: false, top: true };
    let t6 = { other: m3, block: I2.normal, inline: M3.normal };
    this.options.pedantic ? (t6.block = I2.pedantic, t6.inline = M3.pedantic) : this.options.gfm && (t6.block = I2.gfm, this.options.breaks ? t6.inline = M3.breaks : t6.inline = M3.gfm), this.tokenizer.rules = t6;
  }
  static get rules() {
    return { block: I2, inline: M3 };
  }
  static lex(e9, t6) {
    return new l3(t6).lex(e9);
  }
  static lexInline(e9, t6) {
    return new l3(t6).inlineTokens(e9);
  }
  lex(e9) {
    e9 = e9.replace(m3.carriageReturn, `
`), this.blockTokens(e9, this.tokens);
    for (let t6 = 0; t6 < this.inlineQueue.length; t6++) {
      let n7 = this.inlineQueue[t6];
      this.inlineTokens(n7.src, n7.tokens);
    }
    return this.inlineQueue = [], this.tokens;
  }
  blockTokens(e9, t6 = [], n7 = false) {
    for (this.options.pedantic && (e9 = e9.replace(m3.tabCharGlobal, "    ").replace(m3.spaceLine, "")); e9; ) {
      let r8;
      if (this.options.extensions?.block?.some((s6) => (r8 = s6.call({ lexer: this }, e9, t6)) ? (e9 = e9.substring(r8.raw.length), t6.push(r8), true) : false)) continue;
      if (r8 = this.tokenizer.space(e9)) {
        e9 = e9.substring(r8.raw.length);
        let s6 = t6.at(-1);
        r8.raw.length === 1 && s6 !== void 0 ? s6.raw += `
` : t6.push(r8);
        continue;
      }
      if (r8 = this.tokenizer.code(e9)) {
        e9 = e9.substring(r8.raw.length);
        let s6 = t6.at(-1);
        s6?.type === "paragraph" || s6?.type === "text" ? (s6.raw += (s6.raw.endsWith(`
`) ? "" : `
`) + r8.raw, s6.text += `
` + r8.text, this.inlineQueue.at(-1).src = s6.text) : t6.push(r8);
        continue;
      }
      if (r8 = this.tokenizer.fences(e9)) {
        e9 = e9.substring(r8.raw.length), t6.push(r8);
        continue;
      }
      if (r8 = this.tokenizer.heading(e9)) {
        e9 = e9.substring(r8.raw.length), t6.push(r8);
        continue;
      }
      if (r8 = this.tokenizer.hr(e9)) {
        e9 = e9.substring(r8.raw.length), t6.push(r8);
        continue;
      }
      if (r8 = this.tokenizer.blockquote(e9)) {
        e9 = e9.substring(r8.raw.length), t6.push(r8);
        continue;
      }
      if (r8 = this.tokenizer.list(e9)) {
        e9 = e9.substring(r8.raw.length), t6.push(r8);
        continue;
      }
      if (r8 = this.tokenizer.html(e9)) {
        e9 = e9.substring(r8.raw.length), t6.push(r8);
        continue;
      }
      if (r8 = this.tokenizer.def(e9)) {
        e9 = e9.substring(r8.raw.length);
        let s6 = t6.at(-1);
        s6?.type === "paragraph" || s6?.type === "text" ? (s6.raw += (s6.raw.endsWith(`
`) ? "" : `
`) + r8.raw, s6.text += `
` + r8.raw, this.inlineQueue.at(-1).src = s6.text) : this.tokens.links[r8.tag] || (this.tokens.links[r8.tag] = { href: r8.href, title: r8.title }, t6.push(r8));
        continue;
      }
      if (r8 = this.tokenizer.table(e9)) {
        e9 = e9.substring(r8.raw.length), t6.push(r8);
        continue;
      }
      if (r8 = this.tokenizer.lheading(e9)) {
        e9 = e9.substring(r8.raw.length), t6.push(r8);
        continue;
      }
      let i7 = e9;
      if (this.options.extensions?.startBlock) {
        let s6 = 1 / 0, o9 = e9.slice(1), a3;
        this.options.extensions.startBlock.forEach((u5) => {
          a3 = u5.call({ lexer: this }, o9), typeof a3 == "number" && a3 >= 0 && (s6 = Math.min(s6, a3));
        }), s6 < 1 / 0 && s6 >= 0 && (i7 = e9.substring(0, s6 + 1));
      }
      if (this.state.top && (r8 = this.tokenizer.paragraph(i7))) {
        let s6 = t6.at(-1);
        n7 && s6?.type === "paragraph" ? (s6.raw += (s6.raw.endsWith(`
`) ? "" : `
`) + r8.raw, s6.text += `
` + r8.text, this.inlineQueue.pop(), this.inlineQueue.at(-1).src = s6.text) : t6.push(r8), n7 = i7.length !== e9.length, e9 = e9.substring(r8.raw.length);
        continue;
      }
      if (r8 = this.tokenizer.text(e9)) {
        e9 = e9.substring(r8.raw.length);
        let s6 = t6.at(-1);
        s6?.type === "text" ? (s6.raw += (s6.raw.endsWith(`
`) ? "" : `
`) + r8.raw, s6.text += `
` + r8.text, this.inlineQueue.pop(), this.inlineQueue.at(-1).src = s6.text) : t6.push(r8);
        continue;
      }
      if (e9) {
        let s6 = "Infinite loop on byte: " + e9.charCodeAt(0);
        if (this.options.silent) {
          console.error(s6);
          break;
        } else throw new Error(s6);
      }
    }
    return this.state.top = true, t6;
  }
  inline(e9, t6 = []) {
    return this.inlineQueue.push({ src: e9, tokens: t6 }), t6;
  }
  inlineTokens(e9, t6 = []) {
    let n7 = e9, r8 = null;
    if (this.tokens.links) {
      let o9 = Object.keys(this.tokens.links);
      if (o9.length > 0) for (; (r8 = this.tokenizer.rules.inline.reflinkSearch.exec(n7)) != null; ) o9.includes(r8[0].slice(r8[0].lastIndexOf("[") + 1, -1)) && (n7 = n7.slice(0, r8.index) + "[" + "a".repeat(r8[0].length - 2) + "]" + n7.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex));
    }
    for (; (r8 = this.tokenizer.rules.inline.anyPunctuation.exec(n7)) != null; ) n7 = n7.slice(0, r8.index) + "++" + n7.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);
    for (; (r8 = this.tokenizer.rules.inline.blockSkip.exec(n7)) != null; ) n7 = n7.slice(0, r8.index) + "[" + "a".repeat(r8[0].length - 2) + "]" + n7.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);
    n7 = this.options.hooks?.emStrongMask?.call({ lexer: this }, n7) ?? n7;
    let i7 = false, s6 = "";
    for (; e9; ) {
      i7 || (s6 = ""), i7 = false;
      let o9;
      if (this.options.extensions?.inline?.some((u5) => (o9 = u5.call({ lexer: this }, e9, t6)) ? (e9 = e9.substring(o9.raw.length), t6.push(o9), true) : false)) continue;
      if (o9 = this.tokenizer.escape(e9)) {
        e9 = e9.substring(o9.raw.length), t6.push(o9);
        continue;
      }
      if (o9 = this.tokenizer.tag(e9)) {
        e9 = e9.substring(o9.raw.length), t6.push(o9);
        continue;
      }
      if (o9 = this.tokenizer.link(e9)) {
        e9 = e9.substring(o9.raw.length), t6.push(o9);
        continue;
      }
      if (o9 = this.tokenizer.reflink(e9, this.tokens.links)) {
        e9 = e9.substring(o9.raw.length);
        let u5 = t6.at(-1);
        o9.type === "text" && u5?.type === "text" ? (u5.raw += o9.raw, u5.text += o9.text) : t6.push(o9);
        continue;
      }
      if (o9 = this.tokenizer.emStrong(e9, n7, s6)) {
        e9 = e9.substring(o9.raw.length), t6.push(o9);
        continue;
      }
      if (o9 = this.tokenizer.codespan(e9)) {
        e9 = e9.substring(o9.raw.length), t6.push(o9);
        continue;
      }
      if (o9 = this.tokenizer.br(e9)) {
        e9 = e9.substring(o9.raw.length), t6.push(o9);
        continue;
      }
      if (o9 = this.tokenizer.del(e9)) {
        e9 = e9.substring(o9.raw.length), t6.push(o9);
        continue;
      }
      if (o9 = this.tokenizer.autolink(e9)) {
        e9 = e9.substring(o9.raw.length), t6.push(o9);
        continue;
      }
      if (!this.state.inLink && (o9 = this.tokenizer.url(e9))) {
        e9 = e9.substring(o9.raw.length), t6.push(o9);
        continue;
      }
      let a3 = e9;
      if (this.options.extensions?.startInline) {
        let u5 = 1 / 0, p4 = e9.slice(1), c6;
        this.options.extensions.startInline.forEach((f4) => {
          c6 = f4.call({ lexer: this }, p4), typeof c6 == "number" && c6 >= 0 && (u5 = Math.min(u5, c6));
        }), u5 < 1 / 0 && u5 >= 0 && (a3 = e9.substring(0, u5 + 1));
      }
      if (o9 = this.tokenizer.inlineText(a3)) {
        e9 = e9.substring(o9.raw.length), o9.raw.slice(-1) !== "_" && (s6 = o9.raw.slice(-1)), i7 = true;
        let u5 = t6.at(-1);
        u5?.type === "text" ? (u5.raw += o9.raw, u5.text += o9.text) : t6.push(o9);
        continue;
      }
      if (e9) {
        let u5 = "Infinite loop on byte: " + e9.charCodeAt(0);
        if (this.options.silent) {
          console.error(u5);
          break;
        } else throw new Error(u5);
      }
    }
    return t6;
  }
};
var P2 = class {
  options;
  parser;
  constructor(e9) {
    this.options = e9 || O;
  }
  space(e9) {
    return "";
  }
  code({ text: e9, lang: t6, escaped: n7 }) {
    let r8 = (t6 || "").match(m3.notSpaceStart)?.[0], i7 = e9.replace(m3.endingNewline, "") + `
`;
    return r8 ? '<pre><code class="language-' + w2(r8) + '">' + (n7 ? i7 : w2(i7, true)) + `</code></pre>
` : "<pre><code>" + (n7 ? i7 : w2(i7, true)) + `</code></pre>
`;
  }
  blockquote({ tokens: e9 }) {
    return `<blockquote>
${this.parser.parse(e9)}</blockquote>
`;
  }
  html({ text: e9 }) {
    return e9;
  }
  def(e9) {
    return "";
  }
  heading({ tokens: e9, depth: t6 }) {
    return `<h${t6}>${this.parser.parseInline(e9)}</h${t6}>
`;
  }
  hr(e9) {
    return `<hr>
`;
  }
  list(e9) {
    let t6 = e9.ordered, n7 = e9.start, r8 = "";
    for (let o9 = 0; o9 < e9.items.length; o9++) {
      let a3 = e9.items[o9];
      r8 += this.listitem(a3);
    }
    let i7 = t6 ? "ol" : "ul", s6 = t6 && n7 !== 1 ? ' start="' + n7 + '"' : "";
    return "<" + i7 + s6 + `>
` + r8 + "</" + i7 + `>
`;
  }
  listitem(e9) {
    let t6 = "";
    if (e9.task) {
      let n7 = this.checkbox({ checked: !!e9.checked });
      e9.loose ? e9.tokens[0]?.type === "paragraph" ? (e9.tokens[0].text = n7 + " " + e9.tokens[0].text, e9.tokens[0].tokens && e9.tokens[0].tokens.length > 0 && e9.tokens[0].tokens[0].type === "text" && (e9.tokens[0].tokens[0].text = n7 + " " + w2(e9.tokens[0].tokens[0].text), e9.tokens[0].tokens[0].escaped = true)) : e9.tokens.unshift({ type: "text", raw: n7 + " ", text: n7 + " ", escaped: true }) : t6 += n7 + " ";
    }
    return t6 += this.parser.parse(e9.tokens, !!e9.loose), `<li>${t6}</li>
`;
  }
  checkbox({ checked: e9 }) {
    return "<input " + (e9 ? 'checked="" ' : "") + 'disabled="" type="checkbox">';
  }
  paragraph({ tokens: e9 }) {
    return `<p>${this.parser.parseInline(e9)}</p>
`;
  }
  table(e9) {
    let t6 = "", n7 = "";
    for (let i7 = 0; i7 < e9.header.length; i7++) n7 += this.tablecell(e9.header[i7]);
    t6 += this.tablerow({ text: n7 });
    let r8 = "";
    for (let i7 = 0; i7 < e9.rows.length; i7++) {
      let s6 = e9.rows[i7];
      n7 = "";
      for (let o9 = 0; o9 < s6.length; o9++) n7 += this.tablecell(s6[o9]);
      r8 += this.tablerow({ text: n7 });
    }
    return r8 && (r8 = `<tbody>${r8}</tbody>`), `<table>
<thead>
` + t6 + `</thead>
` + r8 + `</table>
`;
  }
  tablerow({ text: e9 }) {
    return `<tr>
${e9}</tr>
`;
  }
  tablecell(e9) {
    let t6 = this.parser.parseInline(e9.tokens), n7 = e9.header ? "th" : "td";
    return (e9.align ? `<${n7} align="${e9.align}">` : `<${n7}>`) + t6 + `</${n7}>
`;
  }
  strong({ tokens: e9 }) {
    return `<strong>${this.parser.parseInline(e9)}</strong>`;
  }
  em({ tokens: e9 }) {
    return `<em>${this.parser.parseInline(e9)}</em>`;
  }
  codespan({ text: e9 }) {
    return `<code>${w2(e9, true)}</code>`;
  }
  br(e9) {
    return "<br>";
  }
  del({ tokens: e9 }) {
    return `<del>${this.parser.parseInline(e9)}</del>`;
  }
  link({ href: e9, title: t6, tokens: n7 }) {
    let r8 = this.parser.parseInline(n7), i7 = J(e9);
    if (i7 === null) return r8;
    e9 = i7;
    let s6 = '<a href="' + e9 + '"';
    return t6 && (s6 += ' title="' + w2(t6) + '"'), s6 += ">" + r8 + "</a>", s6;
  }
  image({ href: e9, title: t6, text: n7, tokens: r8 }) {
    r8 && (n7 = this.parser.parseInline(r8, this.parser.textRenderer));
    let i7 = J(e9);
    if (i7 === null) return w2(n7);
    e9 = i7;
    let s6 = `<img src="${e9}" alt="${n7}"`;
    return t6 && (s6 += ` title="${w2(t6)}"`), s6 += ">", s6;
  }
  text(e9) {
    return "tokens" in e9 && e9.tokens ? this.parser.parseInline(e9.tokens) : "escaped" in e9 && e9.escaped ? e9.text : w2(e9.text);
  }
};
var $3 = class {
  strong({ text: e9 }) {
    return e9;
  }
  em({ text: e9 }) {
    return e9;
  }
  codespan({ text: e9 }) {
    return e9;
  }
  del({ text: e9 }) {
    return e9;
  }
  html({ text: e9 }) {
    return e9;
  }
  text({ text: e9 }) {
    return e9;
  }
  link({ text: e9 }) {
    return "" + e9;
  }
  image({ text: e9 }) {
    return "" + e9;
  }
  br() {
    return "";
  }
};
var R2 = class l4 {
  options;
  renderer;
  textRenderer;
  constructor(e9) {
    this.options = e9 || O, this.options.renderer = this.options.renderer || new P2(), this.renderer = this.options.renderer, this.renderer.options = this.options, this.renderer.parser = this, this.textRenderer = new $3();
  }
  static parse(e9, t6) {
    return new l4(t6).parse(e9);
  }
  static parseInline(e9, t6) {
    return new l4(t6).parseInline(e9);
  }
  parse(e9, t6 = true) {
    let n7 = "";
    for (let r8 = 0; r8 < e9.length; r8++) {
      let i7 = e9[r8];
      if (this.options.extensions?.renderers?.[i7.type]) {
        let o9 = i7, a3 = this.options.extensions.renderers[o9.type].call({ parser: this }, o9);
        if (a3 !== false || !["space", "hr", "heading", "code", "table", "blockquote", "list", "html", "def", "paragraph", "text"].includes(o9.type)) {
          n7 += a3 || "";
          continue;
        }
      }
      let s6 = i7;
      switch (s6.type) {
        case "space": {
          n7 += this.renderer.space(s6);
          continue;
        }
        case "hr": {
          n7 += this.renderer.hr(s6);
          continue;
        }
        case "heading": {
          n7 += this.renderer.heading(s6);
          continue;
        }
        case "code": {
          n7 += this.renderer.code(s6);
          continue;
        }
        case "table": {
          n7 += this.renderer.table(s6);
          continue;
        }
        case "blockquote": {
          n7 += this.renderer.blockquote(s6);
          continue;
        }
        case "list": {
          n7 += this.renderer.list(s6);
          continue;
        }
        case "html": {
          n7 += this.renderer.html(s6);
          continue;
        }
        case "def": {
          n7 += this.renderer.def(s6);
          continue;
        }
        case "paragraph": {
          n7 += this.renderer.paragraph(s6);
          continue;
        }
        case "text": {
          let o9 = s6, a3 = this.renderer.text(o9);
          for (; r8 + 1 < e9.length && e9[r8 + 1].type === "text"; ) o9 = e9[++r8], a3 += `
` + this.renderer.text(o9);
          t6 ? n7 += this.renderer.paragraph({ type: "paragraph", raw: a3, text: a3, tokens: [{ type: "text", raw: a3, text: a3, escaped: true }] }) : n7 += a3;
          continue;
        }
        default: {
          let o9 = 'Token with "' + s6.type + '" type was not found.';
          if (this.options.silent) return console.error(o9), "";
          throw new Error(o9);
        }
      }
    }
    return n7;
  }
  parseInline(e9, t6 = this.renderer) {
    let n7 = "";
    for (let r8 = 0; r8 < e9.length; r8++) {
      let i7 = e9[r8];
      if (this.options.extensions?.renderers?.[i7.type]) {
        let o9 = this.options.extensions.renderers[i7.type].call({ parser: this }, i7);
        if (o9 !== false || !["escape", "html", "link", "image", "strong", "em", "codespan", "br", "del", "text"].includes(i7.type)) {
          n7 += o9 || "";
          continue;
        }
      }
      let s6 = i7;
      switch (s6.type) {
        case "escape": {
          n7 += t6.text(s6);
          break;
        }
        case "html": {
          n7 += t6.html(s6);
          break;
        }
        case "link": {
          n7 += t6.link(s6);
          break;
        }
        case "image": {
          n7 += t6.image(s6);
          break;
        }
        case "strong": {
          n7 += t6.strong(s6);
          break;
        }
        case "em": {
          n7 += t6.em(s6);
          break;
        }
        case "codespan": {
          n7 += t6.codespan(s6);
          break;
        }
        case "br": {
          n7 += t6.br(s6);
          break;
        }
        case "del": {
          n7 += t6.del(s6);
          break;
        }
        case "text": {
          n7 += t6.text(s6);
          break;
        }
        default: {
          let o9 = 'Token with "' + s6.type + '" type was not found.';
          if (this.options.silent) return console.error(o9), "";
          throw new Error(o9);
        }
      }
    }
    return n7;
  }
};
var S4 = class {
  options;
  block;
  constructor(e9) {
    this.options = e9 || O;
  }
  static passThroughHooks = /* @__PURE__ */ new Set(["preprocess", "postprocess", "processAllTokens", "emStrongMask"]);
  static passThroughHooksRespectAsync = /* @__PURE__ */ new Set(["preprocess", "postprocess", "processAllTokens"]);
  preprocess(e9) {
    return e9;
  }
  postprocess(e9) {
    return e9;
  }
  processAllTokens(e9) {
    return e9;
  }
  emStrongMask(e9) {
    return e9;
  }
  provideLexer() {
    return this.block ? b3.lex : b3.lexInline;
  }
  provideParser() {
    return this.block ? R2.parse : R2.parseInline;
  }
};
var B2 = class {
  defaults = L2();
  options = this.setOptions;
  parse = this.parseMarkdown(true);
  parseInline = this.parseMarkdown(false);
  Parser = R2;
  Renderer = P2;
  TextRenderer = $3;
  Lexer = b3;
  Tokenizer = y3;
  Hooks = S4;
  constructor(...e9) {
    this.use(...e9);
  }
  walkTokens(e9, t6) {
    let n7 = [];
    for (let r8 of e9) switch (n7 = n7.concat(t6.call(this, r8)), r8.type) {
      case "table": {
        let i7 = r8;
        for (let s6 of i7.header) n7 = n7.concat(this.walkTokens(s6.tokens, t6));
        for (let s6 of i7.rows) for (let o9 of s6) n7 = n7.concat(this.walkTokens(o9.tokens, t6));
        break;
      }
      case "list": {
        let i7 = r8;
        n7 = n7.concat(this.walkTokens(i7.items, t6));
        break;
      }
      default: {
        let i7 = r8;
        this.defaults.extensions?.childTokens?.[i7.type] ? this.defaults.extensions.childTokens[i7.type].forEach((s6) => {
          let o9 = i7[s6].flat(1 / 0);
          n7 = n7.concat(this.walkTokens(o9, t6));
        }) : i7.tokens && (n7 = n7.concat(this.walkTokens(i7.tokens, t6)));
      }
    }
    return n7;
  }
  use(...e9) {
    let t6 = this.defaults.extensions || { renderers: {}, childTokens: {} };
    return e9.forEach((n7) => {
      let r8 = { ...n7 };
      if (r8.async = this.defaults.async || r8.async || false, n7.extensions && (n7.extensions.forEach((i7) => {
        if (!i7.name) throw new Error("extension name required");
        if ("renderer" in i7) {
          let s6 = t6.renderers[i7.name];
          s6 ? t6.renderers[i7.name] = function(...o9) {
            let a3 = i7.renderer.apply(this, o9);
            return a3 === false && (a3 = s6.apply(this, o9)), a3;
          } : t6.renderers[i7.name] = i7.renderer;
        }
        if ("tokenizer" in i7) {
          if (!i7.level || i7.level !== "block" && i7.level !== "inline") throw new Error("extension level must be 'block' or 'inline'");
          let s6 = t6[i7.level];
          s6 ? s6.unshift(i7.tokenizer) : t6[i7.level] = [i7.tokenizer], i7.start && (i7.level === "block" ? t6.startBlock ? t6.startBlock.push(i7.start) : t6.startBlock = [i7.start] : i7.level === "inline" && (t6.startInline ? t6.startInline.push(i7.start) : t6.startInline = [i7.start]));
        }
        "childTokens" in i7 && i7.childTokens && (t6.childTokens[i7.name] = i7.childTokens);
      }), r8.extensions = t6), n7.renderer) {
        let i7 = this.defaults.renderer || new P2(this.defaults);
        for (let s6 in n7.renderer) {
          if (!(s6 in i7)) throw new Error(`renderer '${s6}' does not exist`);
          if (["options", "parser"].includes(s6)) continue;
          let o9 = s6, a3 = n7.renderer[o9], u5 = i7[o9];
          i7[o9] = (...p4) => {
            let c6 = a3.apply(i7, p4);
            return c6 === false && (c6 = u5.apply(i7, p4)), c6 || "";
          };
        }
        r8.renderer = i7;
      }
      if (n7.tokenizer) {
        let i7 = this.defaults.tokenizer || new y3(this.defaults);
        for (let s6 in n7.tokenizer) {
          if (!(s6 in i7)) throw new Error(`tokenizer '${s6}' does not exist`);
          if (["options", "rules", "lexer"].includes(s6)) continue;
          let o9 = s6, a3 = n7.tokenizer[o9], u5 = i7[o9];
          i7[o9] = (...p4) => {
            let c6 = a3.apply(i7, p4);
            return c6 === false && (c6 = u5.apply(i7, p4)), c6;
          };
        }
        r8.tokenizer = i7;
      }
      if (n7.hooks) {
        let i7 = this.defaults.hooks || new S4();
        for (let s6 in n7.hooks) {
          if (!(s6 in i7)) throw new Error(`hook '${s6}' does not exist`);
          if (["options", "block"].includes(s6)) continue;
          let o9 = s6, a3 = n7.hooks[o9], u5 = i7[o9];
          S4.passThroughHooks.has(s6) ? i7[o9] = (p4) => {
            if (this.defaults.async && S4.passThroughHooksRespectAsync.has(s6)) return Promise.resolve(a3.call(i7, p4)).then((f4) => u5.call(i7, f4));
            let c6 = a3.call(i7, p4);
            return u5.call(i7, c6);
          } : i7[o9] = (...p4) => {
            let c6 = a3.apply(i7, p4);
            return c6 === false && (c6 = u5.apply(i7, p4)), c6;
          };
        }
        r8.hooks = i7;
      }
      if (n7.walkTokens) {
        let i7 = this.defaults.walkTokens, s6 = n7.walkTokens;
        r8.walkTokens = function(o9) {
          let a3 = [];
          return a3.push(s6.call(this, o9)), i7 && (a3 = a3.concat(i7.call(this, o9))), a3;
        };
      }
      this.defaults = { ...this.defaults, ...r8 };
    }), this;
  }
  setOptions(e9) {
    return this.defaults = { ...this.defaults, ...e9 }, this;
  }
  lexer(e9, t6) {
    return b3.lex(e9, t6 ?? this.defaults);
  }
  parser(e9, t6) {
    return R2.parse(e9, t6 ?? this.defaults);
  }
  parseMarkdown(e9) {
    return (n7, r8) => {
      let i7 = { ...r8 }, s6 = { ...this.defaults, ...i7 }, o9 = this.onError(!!s6.silent, !!s6.async);
      if (this.defaults.async === true && i7.async === false) return o9(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));
      if (typeof n7 > "u" || n7 === null) return o9(new Error("marked(): input parameter is undefined or null"));
      if (typeof n7 != "string") return o9(new Error("marked(): input parameter is of type " + Object.prototype.toString.call(n7) + ", string expected"));
      s6.hooks && (s6.hooks.options = s6, s6.hooks.block = e9);
      let a3 = s6.hooks ? s6.hooks.provideLexer() : e9 ? b3.lex : b3.lexInline, u5 = s6.hooks ? s6.hooks.provideParser() : e9 ? R2.parse : R2.parseInline;
      if (s6.async) return Promise.resolve(s6.hooks ? s6.hooks.preprocess(n7) : n7).then((p4) => a3(p4, s6)).then((p4) => s6.hooks ? s6.hooks.processAllTokens(p4) : p4).then((p4) => s6.walkTokens ? Promise.all(this.walkTokens(p4, s6.walkTokens)).then(() => p4) : p4).then((p4) => u5(p4, s6)).then((p4) => s6.hooks ? s6.hooks.postprocess(p4) : p4).catch(o9);
      try {
        s6.hooks && (n7 = s6.hooks.preprocess(n7));
        let p4 = a3(n7, s6);
        s6.hooks && (p4 = s6.hooks.processAllTokens(p4)), s6.walkTokens && this.walkTokens(p4, s6.walkTokens);
        let c6 = u5(p4, s6);
        return s6.hooks && (c6 = s6.hooks.postprocess(c6)), c6;
      } catch (p4) {
        return o9(p4);
      }
    };
  }
  onError(e9, t6) {
    return (n7) => {
      if (n7.message += `
Please report this to https://github.com/markedjs/marked.`, e9) {
        let r8 = "<p>An error occurred:</p><pre>" + w2(n7.message + "", true) + "</pre>";
        return t6 ? Promise.resolve(r8) : r8;
      }
      if (t6) return Promise.reject(n7);
      throw n7;
    };
  }
};
var _2 = new B2();
function d3(l5, e9) {
  return _2.parse(l5, e9);
}
d3.options = d3.setOptions = function(l5) {
  return _2.setOptions(l5), d3.defaults = _2.defaults, G(d3.defaults), d3;
};
d3.getDefaults = L2;
d3.defaults = O;
d3.use = function(...l5) {
  return _2.use(...l5), d3.defaults = _2.defaults, G(d3.defaults), d3;
};
d3.walkTokens = function(l5, e9) {
  return _2.walkTokens(l5, e9);
};
d3.parseInline = _2.parseInline;
d3.Parser = R2;
d3.parser = R2.parse;
d3.Renderer = P2;
d3.TextRenderer = $3;
d3.Lexer = b3;
d3.lexer = b3.lex;
d3.Tokenizer = y3;
d3.Hooks = S4;
d3.parse = d3;
var Dt = d3.options;
var Ht = d3.setOptions;
var Zt = d3.use;
var Gt = d3.walkTokens;
var Nt = d3.parseInline;
var Ft = R2.parse;
var Qt = b3.lex;

// ../mini-lit/dist/MarkdownBlock.js
var __decorate12 = function(decorators, target, key, desc) {
  var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc);
  else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8;
  return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8;
};
var MarkdownBlock = class MarkdownBlock2 extends i4 {
  constructor() {
    super(...arguments);
    this.content = "";
    this.isThinking = false;
    this.escapeHtml = true;
  }
  createRenderRoot() {
    return this;
  }
  connectedCallback() {
    super.connectedCallback();
    this.classList.add("markdown-content");
    this.style.display = "block";
  }
  render() {
    if (!this.content) {
      return b2``;
    }
    let preservedContent = this.content;
    if (this.escapeHtml) {
      const codeBlocks = [];
      preservedContent = this.content.replace(/```[\s\S]*?```|`[^`\n]+`/g, (match2) => {
        const index = codeBlocks.length;
        codeBlocks.push(match2);
        return `__CODE_BLOCK_${index}__`;
      });
      preservedContent = preservedContent.replace(/<(\w+)([^>]*)>/g, "&lt;$1$2&gt;").replace(/<\/(\w+)>/g, "&lt;/$1&gt;").replace(/<(\w+)([^>]*)\s*\/>/g, "&lt;$1$2/&gt;").replace(/<(?![^\s])/g, "&lt;");
      codeBlocks.forEach((block, index) => {
        preservedContent = preservedContent.replace(`__CODE_BLOCK_${index}__`, block);
      });
    }
    const katexMode = "html";
    d3.use({
      extensions: [
        // Inline math with $...$
        {
          name: "inlineMathDollar",
          level: "inline",
          start(src) {
            return src.indexOf("$");
          },
          tokenizer(src) {
            const match2 = /^\$([^$\n]+?)\$/s.exec(src);
            if (match2) {
              return {
                type: "inlineMathDollar",
                raw: match2[0],
                text: match2[1].trim()
              };
            }
            return void 0;
          },
          renderer(token) {
            try {
              return katex.renderToString(token.text, {
                throwOnError: false,
                displayMode: false,
                output: katexMode
              });
            } catch (e9) {
              console.error("KaTeX error:", e9);
              return `<span class="text-red-500 font-mono">$${token.text}$</span>`;
            }
          }
        },
        // Block math with $$...$$
        {
          name: "blockMathDollar",
          level: "block",
          start(src) {
            return src.indexOf("$$");
          },
          tokenizer(src) {
            const match2 = /^\$\$([^$]+?)\$\$/s.exec(src);
            if (match2) {
              return {
                type: "blockMathDollar",
                raw: match2[0],
                text: match2[1].trim()
              };
            }
            return void 0;
          },
          renderer(token) {
            try {
              return `<div class="my-4">${katex.renderToString(token.text, {
                throwOnError: false,
                displayMode: true,
                output: katexMode
              })}</div>`;
            } catch (e9) {
              console.error("KaTeX error:", e9);
              return `<div class="my-4 text-red-500 font-mono">$$${token.text}$$</div>`;
            }
          }
        },
        // Inline math with \(...\)
        {
          name: "inlineMathLatex",
          level: "inline",
          start(src) {
            return src.indexOf("\\(");
          },
          tokenizer(src) {
            const match2 = /^\\\((.+?)\\\)/s.exec(src);
            if (match2) {
              return {
                type: "inlineMathLatex",
                raw: match2[0],
                text: match2[1].trim()
              };
            }
            return void 0;
          },
          renderer(token) {
            try {
              return katex.renderToString(token.text, {
                throwOnError: false,
                displayMode: false,
                output: katexMode
              });
            } catch (e9) {
              console.error("KaTeX error:", e9);
              return `<span class="text-red-500 font-mono">\\(${token.text}\\)</span>`;
            }
          }
        },
        // Block math with \[...\]
        {
          name: "blockMathLatex",
          level: "block",
          start(src) {
            return src.indexOf("\\[");
          },
          tokenizer(src) {
            const match2 = /^\\\[(.+?)\\\]/s.exec(src);
            if (match2) {
              return {
                type: "blockMathLatex",
                raw: match2[0],
                text: match2[1].trim()
              };
            }
            return void 0;
          },
          renderer(token) {
            try {
              return `<div class="my-4">${katex.renderToString(token.text, {
                throwOnError: false,
                displayMode: true,
                output: katexMode
              })}</div>`;
            } catch (e9) {
              console.error("KaTeX error:", e9);
              return `<div class="my-4 text-red-500 font-mono">\\[${token.text}\\]</div>`;
            }
          }
        }
      ]
    });
    const renderer = new d3.Renderer();
    const originalLink = renderer.link;
    renderer.link = function(token) {
      const link = originalLink.call(this, token);
      return link.replace("<a ", '<a target="_blank" rel="noopener noreferrer" ');
    };
    const originalTable = renderer.table;
    renderer.table = function(token) {
      const table = originalTable.call(this, token);
      return `<div class="overflow-x-auto my-2 border border-border rounded">${table}</div>`;
    };
    const parsedContent = d3.parse(preservedContent, {
      async: false,
      renderer
    });
    let highlightedContent = parsedContent.replace(/<pre><code class="language-(\w+)">([\s\S]+?)<\/code><\/pre>/g, (_match, lang, code) => {
      const unescaped = code.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&#x27;/g, "'").replace(/&amp;/g, "&");
      const base64Code = btoa(unescape(encodeURIComponent(unescaped)));
      return `<div class="mt-2"><code-block language="${lang}" code="${base64Code}"></code-block></div>`;
    });
    highlightedContent = highlightedContent.replace(/<pre><code>([\s\S]+?)<\/code><\/pre>/g, (_match, code) => {
      const unescaped = code.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&#x27;/g, "'").replace(/&amp;/g, "&");
      const base64Code = btoa(unescape(encodeURIComponent(unescaped)));
      return `<div class="mt-2"><code-block language="text" code="${base64Code}"></code-block></div>`;
    });
    const containerClasses = this.isThinking ? "text-muted-foreground italic max-w-none break-words overflow-wrap-anywhere text-sm [&>*:last-child]:!mb-0" : "text-foreground max-w-none break-words overflow-wrap-anywhere [&>*:last-child]:!mb-0";
    return b2` <div class="${containerClasses}">${o7(highlightedContent)}</div> `;
  }
};
__decorate12([
  n6()
], MarkdownBlock.prototype, "content", void 0);
__decorate12([
  n6()
], MarkdownBlock.prototype, "isThinking", void 0);
__decorate12([
  n6()
], MarkdownBlock.prototype, "escapeHtml", void 0);
MarkdownBlock = __decorate12([
  t5("markdown-block")
], MarkdownBlock);

// ../pi-mono/packages/web-ui/dist/tools/artifacts/DocxArtifact.js
init_process_shim();

// ../mini-lit/dist/DownloadButton.js
init_process_shim();
function DownloadButton({ content, filename, mimeType = "text/plain", title = i18n("Download"), showText = false, size = "sm", variant = "ghost", iconSize = "sm", isBase64 = false }) {
  const handleDownload = () => {
    let blobContent;
    if (content instanceof Uint8Array) {
      blobContent = content.buffer.slice(content.byteOffset, content.byteOffset + content.byteLength);
    } else if (typeof content === "string") {
      const base64Regex3 = /^[A-Za-z0-9+/]*={0,2}$/;
      const isBase64String = isBase64 || content.length >= 4 && content.length % 4 === 0 && base64Regex3.test(content);
      if (isBase64String) {
        try {
          const binaryString = atob(content);
          const bytes = new Uint8Array(binaryString.length);
          for (let i7 = 0; i7 < binaryString.length; i7++) {
            bytes[i7] = binaryString.charCodeAt(i7);
          }
          blobContent = bytes;
        } catch {
          blobContent = content;
        }
      } else {
        blobContent = content;
      }
    } else {
      blobContent = "";
    }
    const blob = new Blob([blobContent], { type: mimeType });
    const url = URL.createObjectURL(blob);
    const a3 = document.createElement("a");
    a3.href = url;
    a3.download = filename;
    a3.click();
    URL.revokeObjectURL(url);
  };
  return Button({
    variant,
    size,
    onClick: handleDownload,
    title,
    children: b2` ${icon(Download, iconSize)} ${showText ? b2`<span>${i18n("Download")}</span>` : ""} `
  });
}

// ../pi-mono/packages/web-ui/dist/tools/artifacts/DocxArtifact.js
var __decorate13 = function(decorators, target, key, desc) {
  var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc);
  else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8;
  return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8;
};
var DocxArtifact = class DocxArtifact2 extends ArtifactElement {
  constructor() {
    super(...arguments);
    this._content = "";
    this.error = null;
  }
  get content() {
    return this._content;
  }
  set content(value) {
    this._content = value;
    this.error = null;
    this.requestUpdate();
  }
  createRenderRoot() {
    return this;
  }
  connectedCallback() {
    super.connectedCallback();
    this.style.display = "block";
    this.style.height = "100%";
  }
  base64ToArrayBuffer(base64) {
    let base64Data = base64;
    if (base64.startsWith("data:")) {
      const base64Match = base64.match(/base64,(.+)/);
      if (base64Match) {
        base64Data = base64Match[1];
      }
    }
    const binaryString = atob(base64Data);
    const bytes = new Uint8Array(binaryString.length);
    for (let i7 = 0; i7 < binaryString.length; i7++) {
      bytes[i7] = binaryString.charCodeAt(i7);
    }
    return bytes.buffer;
  }
  decodeBase64() {
    let base64Data = this._content;
    if (this._content.startsWith("data:")) {
      const base64Match = this._content.match(/base64,(.+)/);
      if (base64Match) {
        base64Data = base64Match[1];
      }
    }
    const binaryString = atob(base64Data);
    const bytes = new Uint8Array(binaryString.length);
    for (let i7 = 0; i7 < binaryString.length; i7++) {
      bytes[i7] = binaryString.charCodeAt(i7);
    }
    return bytes;
  }
  getHeaderButtons() {
    return b2`
			<div class="flex items-center gap-1">
				${DownloadButton({
      content: this.decodeBase64(),
      filename: this.filename,
      mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      title: i18n("Download")
    })}
			</div>
		`;
  }
  async updated(changedProperties) {
    super.updated(changedProperties);
    if (changedProperties.has("_content") && this._content && !this.error) {
      await this.renderDocx();
    }
  }
  async renderDocx() {
    const container = this.querySelector("#docx-container");
    if (!container || !this._content)
      return;
    try {
      const arrayBuffer = this.base64ToArrayBuffer(this._content);
      container.innerHTML = "";
      const wrapper = document.createElement("div");
      wrapper.className = "docx-wrapper-custom";
      container.appendChild(wrapper);
      await renderAsync(arrayBuffer, wrapper, void 0, {
        className: "docx",
        inWrapper: true,
        ignoreWidth: true,
        ignoreHeight: false,
        ignoreFonts: false,
        breakPages: true,
        ignoreLastRenderedPageBreak: true,
        experimental: false,
        trimXmlDeclaration: true,
        useBase64URL: false,
        renderHeaders: true,
        renderFooters: true,
        renderFootnotes: true,
        renderEndnotes: true
      });
      const style = document.createElement("style");
      style.textContent = `
				#docx-container {
					padding: 0;
				}

				#docx-container .docx-wrapper-custom {
					max-width: 100%;
					overflow-x: auto;
				}

				#docx-container .docx-wrapper {
					max-width: 100% !important;
					margin: 0 !important;
					background: transparent !important;
					padding: 0em !important;
				}

				#docx-container .docx-wrapper > section.docx {
					box-shadow: none !important;
					border: none !important;
					border-radius: 0 !important;
					margin: 0 !important;
					padding: 2em !important;
					background: white !important;
					color: black !important;
					max-width: 100% !important;
					width: 100% !important;
					min-width: 0 !important;
					overflow-x: auto !important;
				}

				/* Fix tables and wide content */
				#docx-container table {
					max-width: 100% !important;
					width: auto !important;
					overflow-x: auto !important;
					display: block !important;
				}

				#docx-container img {
					max-width: 100% !important;
					height: auto !important;
				}

				/* Fix paragraphs and text */
				#docx-container p,
				#docx-container span,
				#docx-container div {
					max-width: 100% !important;
					word-wrap: break-word !important;
					overflow-wrap: break-word !important;
				}

				/* Hide page breaks in web view */
				#docx-container .docx-page-break {
					display: none !important;
				}
			`;
      container.appendChild(style);
    } catch (error) {
      console.error("Error rendering DOCX:", error);
      this.error = error?.message || i18n("Failed to load document");
    }
  }
  render() {
    if (this.error) {
      return b2`
				<div class="h-full flex items-center justify-center bg-background p-4">
					<div class="bg-destructive/10 border border-destructive text-destructive p-4 rounded-lg max-w-2xl">
						<div class="font-medium mb-1">${i18n("Error loading document")}</div>
						<div class="text-sm opacity-90">${this.error}</div>
					</div>
				</div>
			`;
    }
    return b2`
			<div class="h-full flex flex-col bg-background overflow-auto">
				<div id="docx-container" class="flex-1 overflow-auto"></div>
			</div>
		`;
  }
};
__decorate13([
  n6({ type: String })
], DocxArtifact.prototype, "_content", void 0);
__decorate13([
  r7()
], DocxArtifact.prototype, "error", void 0);
DocxArtifact = __decorate13([
  t5("docx-artifact")
], DocxArtifact);

// ../pi-mono/packages/web-ui/dist/tools/artifacts/ExcelArtifact.js
init_process_shim();
var __decorate14 = function(decorators, target, key, desc) {
  var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc);
  else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8;
  return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8;
};
var ExcelArtifact = class ExcelArtifact2 extends ArtifactElement {
  constructor() {
    super(...arguments);
    this._content = "";
    this.error = null;
  }
  get content() {
    return this._content;
  }
  set content(value) {
    this._content = value;
    this.error = null;
    this.requestUpdate();
  }
  createRenderRoot() {
    return this;
  }
  connectedCallback() {
    super.connectedCallback();
    this.style.display = "block";
    this.style.height = "100%";
  }
  base64ToArrayBuffer(base64) {
    let base64Data = base64;
    if (base64.startsWith("data:")) {
      const base64Match = base64.match(/base64,(.+)/);
      if (base64Match) {
        base64Data = base64Match[1];
      }
    }
    const binaryString = atob(base64Data);
    const bytes = new Uint8Array(binaryString.length);
    for (let i7 = 0; i7 < binaryString.length; i7++) {
      bytes[i7] = binaryString.charCodeAt(i7);
    }
    return bytes.buffer;
  }
  decodeBase64() {
    let base64Data = this._content;
    if (this._content.startsWith("data:")) {
      const base64Match = this._content.match(/base64,(.+)/);
      if (base64Match) {
        base64Data = base64Match[1];
      }
    }
    const binaryString = atob(base64Data);
    const bytes = new Uint8Array(binaryString.length);
    for (let i7 = 0; i7 < binaryString.length; i7++) {
      bytes[i7] = binaryString.charCodeAt(i7);
    }
    return bytes;
  }
  getMimeType() {
    const ext2 = this.filename.split(".").pop()?.toLowerCase();
    if (ext2 === "xls")
      return "application/vnd.ms-excel";
    return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
  }
  getHeaderButtons() {
    return b2`
			<div class="flex items-center gap-1">
				${DownloadButton({
      content: this.decodeBase64(),
      filename: this.filename,
      mimeType: this.getMimeType(),
      title: i18n("Download")
    })}
			</div>
		`;
  }
  async updated(changedProperties) {
    super.updated(changedProperties);
    if (changedProperties.has("_content") && this._content && !this.error) {
      await this.renderExcel();
    }
  }
  async renderExcel() {
    const container = this.querySelector("#excel-container");
    if (!container || !this._content)
      return;
    try {
      const arrayBuffer = this.base64ToArrayBuffer(this._content);
      const workbook = readSync(arrayBuffer, { type: "array" });
      container.innerHTML = "";
      const wrapper = document.createElement("div");
      wrapper.className = "overflow-auto h-full flex flex-col";
      container.appendChild(wrapper);
      if (workbook.SheetNames.length > 1) {
        const tabContainer = document.createElement("div");
        tabContainer.className = "flex gap-2 mb-4 border-b border-border sticky top-0 bg-background z-10";
        const sheetContents = [];
        workbook.SheetNames.forEach((sheetName, index) => {
          const tab = document.createElement("button");
          tab.textContent = sheetName;
          tab.className = index === 0 ? "px-4 py-2 text-sm font-medium border-b-2 border-primary text-primary" : "px-4 py-2 text-sm font-medium text-muted-foreground hover:text-foreground hover:border-b-2 hover:border-border transition-colors";
          const sheetDiv = document.createElement("div");
          sheetDiv.style.display = index === 0 ? "flex" : "none";
          sheetDiv.className = "flex-1 overflow-auto";
          sheetDiv.appendChild(this.renderExcelSheet(workbook.Sheets[sheetName], sheetName));
          sheetContents.push(sheetDiv);
          tab.onclick = () => {
            tabContainer.querySelectorAll("button").forEach((btn, btnIndex) => {
              if (btnIndex === index) {
                btn.className = "px-4 py-2 text-sm font-medium border-b-2 border-primary text-primary";
              } else {
                btn.className = "px-4 py-2 text-sm font-medium text-muted-foreground hover:text-foreground hover:border-b-2 hover:border-border transition-colors";
              }
            });
            sheetContents.forEach((content, contentIndex) => {
              content.style.display = contentIndex === index ? "flex" : "none";
            });
          };
          tabContainer.appendChild(tab);
        });
        wrapper.appendChild(tabContainer);
        sheetContents.forEach((content) => {
          wrapper.appendChild(content);
        });
      } else {
        const sheetName = workbook.SheetNames[0];
        wrapper.appendChild(this.renderExcelSheet(workbook.Sheets[sheetName], sheetName));
      }
    } catch (error) {
      console.error("Error rendering Excel:", error);
      this.error = error?.message || i18n("Failed to load spreadsheet");
    }
  }
  renderExcelSheet(worksheet, sheetName) {
    const sheetDiv = document.createElement("div");
    const htmlTable = utils.sheet_to_html(worksheet, { id: `sheet-${sheetName}` });
    const tempDiv = document.createElement("div");
    tempDiv.innerHTML = htmlTable;
    const table = tempDiv.querySelector("table");
    if (table) {
      table.className = "w-full border-collapse text-foreground";
      table.querySelectorAll("td, th").forEach((cell) => {
        const cellEl = cell;
        cellEl.className = "border border-border px-3 py-2 text-sm text-left";
      });
      const headerCells = table.querySelectorAll("thead th, tr:first-child td");
      if (headerCells.length > 0) {
        headerCells.forEach((th) => {
          const thEl = th;
          thEl.className = "border border-border px-3 py-2 text-sm font-semibold bg-muted text-foreground sticky top-0";
        });
      }
      table.querySelectorAll("tbody tr:nth-child(even)").forEach((row) => {
        const rowEl = row;
        rowEl.className = "bg-muted/30";
      });
      sheetDiv.appendChild(table);
    }
    return sheetDiv;
  }
  render() {
    if (this.error) {
      return b2`
				<div class="h-full flex items-center justify-center bg-background p-4">
					<div class="bg-destructive/10 border border-destructive text-destructive p-4 rounded-lg max-w-2xl">
						<div class="font-medium mb-1">${i18n("Error loading spreadsheet")}</div>
						<div class="text-sm opacity-90">${this.error}</div>
					</div>
				</div>
			`;
    }
    return b2`
			<div class="h-full flex flex-col bg-background overflow-auto">
				<div id="excel-container" class="flex-1 overflow-auto"></div>
			</div>
		`;
  }
};
__decorate14([
  n6({ type: String })
], ExcelArtifact.prototype, "_content", void 0);
__decorate14([
  r7()
], ExcelArtifact.prototype, "error", void 0);
ExcelArtifact = __decorate14([
  t5("excel-artifact")
], ExcelArtifact);

// ../pi-mono/packages/web-ui/dist/tools/artifacts/GenericArtifact.js
init_process_shim();
var __decorate15 = function(decorators, target, key, desc) {
  var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc);
  else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8;
  return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8;
};
var GenericArtifact = class GenericArtifact2 extends ArtifactElement {
  constructor() {
    super(...arguments);
    this._content = "";
  }
  get content() {
    return this._content;
  }
  set content(value) {
    this._content = value;
    this.requestUpdate();
  }
  createRenderRoot() {
    return this;
  }
  connectedCallback() {
    super.connectedCallback();
    this.style.display = "block";
    this.style.height = "100%";
  }
  decodeBase64() {
    let base64Data = this._content;
    if (this._content.startsWith("data:")) {
      const base64Match = this._content.match(/base64,(.+)/);
      if (base64Match) {
        base64Data = base64Match[1];
      }
    }
    const binaryString = atob(base64Data);
    const bytes = new Uint8Array(binaryString.length);
    for (let i7 = 0; i7 < binaryString.length; i7++) {
      bytes[i7] = binaryString.charCodeAt(i7);
    }
    return bytes;
  }
  getMimeType() {
    const ext2 = this.filename.split(".").pop()?.toLowerCase();
    const mimeTypes = {
      pdf: "application/pdf",
      zip: "application/zip",
      tar: "application/x-tar",
      gz: "application/gzip",
      rar: "application/vnd.rar",
      "7z": "application/x-7z-compressed",
      mp3: "audio/mpeg",
      mp4: "video/mp4",
      avi: "video/x-msvideo",
      mov: "video/quicktime",
      wav: "audio/wav",
      ogg: "audio/ogg",
      json: "application/json",
      xml: "application/xml",
      bin: "application/octet-stream"
    };
    return mimeTypes[ext2 || ""] || "application/octet-stream";
  }
  getHeaderButtons() {
    return b2`
			<div class="flex items-center gap-1">
				${DownloadButton({
      content: this.decodeBase64(),
      filename: this.filename,
      mimeType: this.getMimeType(),
      title: i18n("Download")
    })}
			</div>
		`;
  }
  render() {
    return b2`
			<div class="h-full flex items-center justify-center bg-background p-8">
				<div class="text-center max-w-md">
					<div class="text-muted-foreground text-lg mb-4">
						<svg
							xmlns="http://www.w3.org/2000/svg"
							class="h-16 w-16 mx-auto mb-4 text-muted-foreground/50"
							fill="none"
							viewBox="0 0 24 24"
							stroke="currentColor"
						>
							<path
								stroke-linecap="round"
								stroke-linejoin="round"
								stroke-width="1.5"
								d="M7 21h10a2 2 0 002-2V9.414a1 1 0 00-.293-.707l-5.414-5.414A1 1 0 0012.586 3H7a2 2 0 00-2 2v14a2 2 0 002 2z"
							/>
						</svg>
						<div class="font-medium text-foreground mb-2">${this.filename}</div>
						<p class="text-sm">
							${i18n("Preview not available for this file type.")} ${i18n("Click the download button above to view it on your computer.")}
						</p>
					</div>
				</div>
			</div>
		`;
  }
};
__decorate15([
  n6({ type: String })
], GenericArtifact.prototype, "_content", void 0);
GenericArtifact = __decorate15([
  t5("generic-artifact")
], GenericArtifact);

// ../pi-mono/packages/web-ui/dist/tools/artifacts/HtmlArtifact.js
init_process_shim();
var import_highlight = __toESM(require_lib(), 1);

// ../pi-mono/packages/web-ui/dist/tools/artifacts/Console.js
init_process_shim();

// ../mini-lit/dist/CopyButton.js
init_process_shim();
var __decorate16 = function(decorators, target, key, desc) {
  var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc);
  else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8;
  return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8;
};
var CopyButton = class CopyButton2 extends i4 {
  constructor() {
    super(...arguments);
    this.text = "";
    this.title = i18n("Copy");
    this.showText = false;
    this.copied = false;
  }
  createRenderRoot() {
    return this;
  }
  async handleCopy() {
    try {
      await navigator.clipboard.writeText(this.text);
      this.copied = true;
      setTimeout(() => {
        this.copied = false;
      }, 2e3);
    } catch (err) {
      console.error("Failed to copy:", err);
    }
  }
  render() {
    return Button({
      variant: "ghost",
      size: "sm",
      onClick: () => this.handleCopy(),
      title: this.title,
      children: b2`
            ${this.copied ? icon(Check, "sm") : icon(Copy, "sm")}
            ${this.copied && this.showText ? b2`<span>${i18n("Copied!")}</span>` : ""}
         `
    });
  }
};
__decorate16([
  n6()
], CopyButton.prototype, "text", void 0);
__decorate16([
  n6()
], CopyButton.prototype, "title", void 0);
__decorate16([
  n6({ type: Boolean, attribute: "show-text" })
], CopyButton.prototype, "showText", void 0);
__decorate16([
  r7()
], CopyButton.prototype, "copied", void 0);
CopyButton = __decorate16([
  t5("copy-button")
], CopyButton);

// ../pi-mono/packages/web-ui/dist/tools/artifacts/Console.js
var __decorate17 = function(decorators, target, key, desc) {
  var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc);
  else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8;
  return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8;
};
var Console = class Console2 extends i4 {
  constructor() {
    super(...arguments);
    this.logs = [];
    this.expanded = false;
    this.autoscroll = true;
    this.logsContainerRef = e5();
  }
  createRenderRoot() {
    return this;
  }
  updated() {
    if (this.autoscroll && this.expanded && this.logsContainerRef.value) {
      this.logsContainerRef.value.scrollTop = this.logsContainerRef.value.scrollHeight;
    }
  }
  getLogsText() {
    return this.logs.map((l5) => `[${l5.type}] ${l5.text}`).join("\n");
  }
  render() {
    const errorCount = this.logs.filter((l5) => l5.type === "error").length;
    const summary = errorCount > 0 ? `${i18n("console")} (${errorCount} ${errorCount === 1 ? "error" : "errors"})` : `${i18n("console")} (${this.logs.length})`;
    return b2`
			<div class="border-t border-border p-2">
				<div class="flex items-center gap-2 w-full">
					<button
						@click=${() => {
      this.expanded = !this.expanded;
    }}
						class="flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground transition-colors flex-1 text-left"
					>
						${icon(this.expanded ? ChevronDown : ChevronRight, "sm")}
						<span>${summary}</span>
					</button>
					${this.expanded ? b2`
							<button
								@click=${() => {
      this.autoscroll = !this.autoscroll;
    }}
								class="p-1 rounded transition-colors ${this.autoscroll ? "bg-accent text-accent-foreground" : "hover:bg-muted"}"
								title=${this.autoscroll ? i18n("Autoscroll enabled") : i18n("Autoscroll disabled")}
							>
								${icon(this.autoscroll ? ChevronsDown : Lock, "sm")}
							</button>
							<copy-button .text=${this.getLogsText()} title=${i18n("Copy logs")} .showText=${false} class="!bg-transparent hover:!bg-accent"></copy-button>
						` : ""}
				</div>
				${this.expanded ? b2`
						<div class="max-h-48 overflow-y-auto space-y-1 mt-2" ${n5(this.logsContainerRef)}>
							${c5(this.logs, (_log, index) => index, (log) => b2`
									<div class="text-xs font-mono ${log.type === "error" ? "text-destructive" : "text-muted-foreground"}">
										[${log.type}] ${log.text}
									</div>
								`)}
						</div>
					` : ""}
			</div>
		`;
  }
};
__decorate17([
  n6({ attribute: false })
], Console.prototype, "logs", void 0);
__decorate17([
  r7()
], Console.prototype, "expanded", void 0);
__decorate17([
  r7()
], Console.prototype, "autoscroll", void 0);
Console = __decorate17([
  t5("artifact-console")
], Console);

// ../mini-lit/dist/PreviewCodeToggle.js
init_process_shim();
var __decorate18 = function(decorators, target, key, desc) {
  var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc);
  else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8;
  return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8;
};
var PreviewCodeToggle = class PreviewCodeToggle2 extends i4 {
  constructor() {
    super(...arguments);
    this.mode = "preview";
  }
  createRenderRoot() {
    return this;
  }
  setMode(mode) {
    if (this.mode !== mode) {
      this.mode = mode;
      this.dispatchEvent(new CustomEvent("mode-change", { detail: this.mode, bubbles: true }));
    }
  }
  render() {
    const isPreview = this.mode === "preview";
    return b2`
         <div class="inline-flex items-center h-7 rounded-md overflow-hidden border border-border bg-muted/60">
            <button
               class="px-2 h-full flex items-center ${isPreview ? "bg-card text-foreground" : "text-muted-foreground hover:text-accent-foreground"}"
               @click=${() => this.setMode("preview")}
               title="${i18n("Preview")}"
            >
               ${icon(Eye, "sm")}
            </button>
            <button
               class="px-2 h-full flex items-center ${!isPreview ? "bg-card text-foreground" : "text-muted-foreground hover:text-accent-foreground"}"
               @click=${() => this.setMode("code")}
               title="${i18n("Code")}"
            >
               ${icon(Code, "sm")}
            </button>
         </div>
      `;
  }
};
__decorate18([
  n6({ reflect: false })
], PreviewCodeToggle.prototype, "mode", void 0);
PreviewCodeToggle = __decorate18([
  t5("preview-code-toggle")
], PreviewCodeToggle);

// ../pi-mono/packages/web-ui/dist/tools/artifacts/HtmlArtifact.js
var __decorate19 = function(decorators, target, key, desc) {
  var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc);
  else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8;
  return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8;
};
var HtmlArtifact = class HtmlArtifact2 extends ArtifactElement {
  constructor() {
    super(...arguments);
    this.filename = "";
    this.runtimeProviders = [];
    this._content = "";
    this.logs = [];
    this.sandboxIframeRef = e5();
    this.consoleRef = e5();
    this.viewMode = "preview";
  }
  setViewMode(mode) {
    this.viewMode = mode;
  }
  getHeaderButtons() {
    const toggle = new PreviewCodeToggle();
    toggle.mode = this.viewMode;
    toggle.addEventListener("mode-change", (e9) => {
      this.setViewMode(e9.detail);
    });
    const copyButton = new CopyButton();
    copyButton.text = this._content;
    copyButton.title = i18n("Copy HTML");
    copyButton.showText = false;
    const sandbox = this.sandboxIframeRef.value;
    const sandboxId = `artifact-${this.filename}`;
    const downloadContent = sandbox?.prepareHtmlDocument(sandboxId, this._content, this.runtimeProviders || [], {
      isHtmlArtifact: true,
      isStandalone: true
      // Skip runtime bridge and navigation interceptor for standalone downloads
    }) || this._content;
    return b2`
			<div class="flex items-center gap-2">
				${toggle}
				${Button({
      variant: "ghost",
      size: "sm",
      onClick: () => {
        this.logs = [];
        this.executeContent(this._content);
      },
      title: i18n("Reload HTML"),
      children: icon(RefreshCw, "sm")
    })}
				${copyButton}
				${DownloadButton({ content: downloadContent, filename: this.filename, mimeType: "text/html", title: i18n("Download HTML") })}
			</div>
		`;
  }
  set content(value) {
    const oldValue = this._content;
    this._content = value;
    if (oldValue !== value) {
      this.logs = [];
      this.requestUpdate();
      if (this.sandboxIframeRef.value && value) {
        this.executeContent(value);
      }
    }
  }
  executeContent(html) {
    const sandbox = this.sandboxIframeRef.value;
    if (!sandbox)
      return;
    if (this.sandboxUrlProvider) {
      sandbox.sandboxUrlProvider = this.sandboxUrlProvider;
    }
    const sandboxId = `artifact-${this.filename}`;
    const consumer = {
      handleMessage: async (message) => {
        if (message.type === "console") {
          this.logs = [
            ...this.logs,
            {
              type: message.method === "error" ? "error" : "log",
              text: message.text
            }
          ];
          this.requestUpdate();
        }
      }
    };
    let modifiedHtml = html;
    if (modifiedHtml.includes("</html>")) {
      modifiedHtml = modifiedHtml.replace("</html>", "<script>if (window.complete) window.complete();<\/script></html>");
    } else {
      modifiedHtml += "<script>if (window.complete) window.complete();<\/script>";
    }
    sandbox.loadContent(sandboxId, modifiedHtml, this.runtimeProviders, [consumer]);
  }
  get content() {
    return this._content;
  }
  disconnectedCallback() {
    super.disconnectedCallback();
    const sandboxId = `artifact-${this.filename}`;
    RUNTIME_MESSAGE_ROUTER.unregisterSandbox(sandboxId);
  }
  firstUpdated() {
    if (this._content && this.sandboxIframeRef.value) {
      this.executeContent(this._content);
    }
  }
  updated(changedProperties) {
    super.updated(changedProperties);
    if (this._content && this.sandboxIframeRef.value && this.logs.length === 0) {
      this.executeContent(this._content);
    }
  }
  getLogs() {
    if (this.logs.length === 0)
      return i18n("No logs for {filename}").replace("{filename}", this.filename);
    return this.logs.map((l5) => `[${l5.type}] ${l5.text}`).join("\n");
  }
  render() {
    return b2`
			<div class="h-full flex flex-col">
				<div class="flex-1 overflow-hidden relative">
					<!-- Preview container - always in DOM, just hidden when not active -->
					<div class="absolute inset-0 flex flex-col" style="display: ${this.viewMode === "preview" ? "flex" : "none"}">
						<sandbox-iframe class="flex-1" ${n5(this.sandboxIframeRef)}></sandbox-iframe>
						${this.logs.length > 0 ? b2`<artifact-console .logs=${this.logs} ${n5(this.consoleRef)}></artifact-console>` : ""}
					</div>

					<!-- Code view - always in DOM, just hidden when not active -->
					<div class="absolute inset-0 overflow-auto bg-background" style="display: ${this.viewMode === "code" ? "block" : "none"}">
						<pre class="m-0 p-4 text-xs"><code class="hljs language-html">${o7(import_highlight.default.highlight(this._content, { language: "html" }).value)}</code></pre>
					</div>
				</div>
			</div>
		`;
  }
};
__decorate19([
  n6()
], HtmlArtifact.prototype, "filename", void 0);
__decorate19([
  n6({ attribute: false })
], HtmlArtifact.prototype, "runtimeProviders", void 0);
__decorate19([
  n6({ attribute: false })
], HtmlArtifact.prototype, "sandboxUrlProvider", void 0);
__decorate19([
  r7()
], HtmlArtifact.prototype, "viewMode", void 0);
HtmlArtifact = __decorate19([
  t5("html-artifact")
], HtmlArtifact);

// ../pi-mono/packages/web-ui/dist/tools/artifacts/ImageArtifact.js
init_process_shim();
var __decorate20 = function(decorators, target, key, desc) {
  var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc);
  else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8;
  return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8;
};
var ImageArtifact = class ImageArtifact2 extends ArtifactElement {
  constructor() {
    super(...arguments);
    this._content = "";
  }
  get content() {
    return this._content;
  }
  set content(value) {
    this._content = value;
    this.requestUpdate();
  }
  createRenderRoot() {
    return this;
  }
  connectedCallback() {
    super.connectedCallback();
    this.style.display = "block";
    this.style.height = "100%";
  }
  getMimeType() {
    const ext2 = this.filename.split(".").pop()?.toLowerCase();
    if (ext2 === "jpg" || ext2 === "jpeg")
      return "image/jpeg";
    if (ext2 === "gif")
      return "image/gif";
    if (ext2 === "webp")
      return "image/webp";
    if (ext2 === "svg")
      return "image/svg+xml";
    if (ext2 === "bmp")
      return "image/bmp";
    if (ext2 === "ico")
      return "image/x-icon";
    return "image/png";
  }
  getImageUrl() {
    if (this._content.startsWith("data:")) {
      return this._content;
    }
    return `data:${this.getMimeType()};base64,${this._content}`;
  }
  decodeBase64() {
    let base64Data;
    if (this._content.startsWith("data:")) {
      const base64Match = this._content.match(/base64,(.+)/);
      if (base64Match) {
        base64Data = base64Match[1];
      } else {
        return new Uint8Array(0);
      }
    } else {
      base64Data = this._content;
    }
    const binaryString = atob(base64Data);
    const bytes = new Uint8Array(binaryString.length);
    for (let i7 = 0; i7 < binaryString.length; i7++) {
      bytes[i7] = binaryString.charCodeAt(i7);
    }
    return bytes;
  }
  getHeaderButtons() {
    return b2`
			<div class="flex items-center gap-1">
				${DownloadButton({
      content: this.decodeBase64(),
      filename: this.filename,
      mimeType: this.getMimeType(),
      title: i18n("Download")
    })}
			</div>
		`;
  }
  render() {
    return b2`
			<div class="h-full flex flex-col bg-background overflow-auto">
				<div class="flex-1 flex items-center justify-center p-4">
					<img
						src="${this.getImageUrl()}"
						alt="${this.filename}"
						class="max-w-full max-h-full object-contain"
						@error=${(e9) => {
      const target = e9.target;
      target.src = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Ctext x='50' y='50' text-anchor='middle' dominant-baseline='middle' fill='%23999'%3EImage Error%3C/text%3E%3C/svg%3E";
    }}
					/>
				</div>
			</div>
		`;
  }
};
__decorate20([
  n6({ type: String })
], ImageArtifact.prototype, "_content", void 0);
ImageArtifact = __decorate20([
  t5("image-artifact")
], ImageArtifact);

// ../pi-mono/packages/web-ui/dist/tools/artifacts/MarkdownArtifact.js
init_process_shim();
var import_highlight2 = __toESM(require_lib(), 1);
var __decorate21 = function(decorators, target, key, desc) {
  var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc);
  else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8;
  return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8;
};
var MarkdownArtifact = class MarkdownArtifact2 extends ArtifactElement {
  constructor() {
    super(...arguments);
    this.filename = "";
    this._content = "";
    this.viewMode = "preview";
  }
  get content() {
    return this._content;
  }
  set content(value) {
    this._content = value;
    this.requestUpdate();
  }
  createRenderRoot() {
    return this;
  }
  setViewMode(mode) {
    this.viewMode = mode;
  }
  getHeaderButtons() {
    const toggle = new PreviewCodeToggle();
    toggle.mode = this.viewMode;
    toggle.addEventListener("mode-change", (e9) => {
      this.setViewMode(e9.detail);
    });
    const copyButton = new CopyButton();
    copyButton.text = this._content;
    copyButton.title = i18n("Copy Markdown");
    copyButton.showText = false;
    return b2`
			<div class="flex items-center gap-2">
				${toggle}
				${copyButton}
				${DownloadButton({
      content: this._content,
      filename: this.filename,
      mimeType: "text/markdown",
      title: i18n("Download Markdown")
    })}
			</div>
		`;
  }
  render() {
    return b2`
			<div class="h-full flex flex-col">
				<div class="flex-1 overflow-auto">
					${this.viewMode === "preview" ? b2`<div class="p-4"><markdown-block .content=${this.content}></markdown-block></div>` : b2`<pre class="m-0 p-4 text-xs whitespace-pre-wrap break-words"><code class="hljs language-markdown">${o7(import_highlight2.default.highlight(this.content, { language: "markdown", ignoreIllegals: true }).value)}</code></pre>`}
				</div>
			</div>
		`;
  }
};
__decorate21([
  n6()
], MarkdownArtifact.prototype, "filename", void 0);
__decorate21([
  r7()
], MarkdownArtifact.prototype, "viewMode", void 0);
MarkdownArtifact = __decorate21([
  t5("markdown-artifact")
], MarkdownArtifact);

// ../pi-mono/packages/web-ui/dist/tools/artifacts/PdfArtifact.js
init_process_shim();
var __decorate22 = function(decorators, target, key, desc) {
  var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc);
  else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8;
  return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8;
};
GlobalWorkerOptions.workerSrc = new URL("pdfjs-dist/build/pdf.worker.min.mjs", import.meta.url).toString();
var PdfArtifact = class PdfArtifact2 extends ArtifactElement {
  constructor() {
    super(...arguments);
    this._content = "";
    this.error = null;
    this.currentLoadingTask = null;
  }
  get content() {
    return this._content;
  }
  set content(value) {
    this._content = value;
    this.error = null;
    this.requestUpdate();
  }
  createRenderRoot() {
    return this;
  }
  connectedCallback() {
    super.connectedCallback();
    this.style.display = "block";
    this.style.height = "100%";
  }
  disconnectedCallback() {
    super.disconnectedCallback();
    this.cleanup();
  }
  cleanup() {
    if (this.currentLoadingTask) {
      this.currentLoadingTask.destroy();
      this.currentLoadingTask = null;
    }
  }
  base64ToArrayBuffer(base64) {
    let base64Data = base64;
    if (base64.startsWith("data:")) {
      const base64Match = base64.match(/base64,(.+)/);
      if (base64Match) {
        base64Data = base64Match[1];
      }
    }
    const binaryString = atob(base64Data);
    const bytes = new Uint8Array(binaryString.length);
    for (let i7 = 0; i7 < binaryString.length; i7++) {
      bytes[i7] = binaryString.charCodeAt(i7);
    }
    return bytes.buffer;
  }
  decodeBase64() {
    let base64Data = this._content;
    if (this._content.startsWith("data:")) {
      const base64Match = this._content.match(/base64,(.+)/);
      if (base64Match) {
        base64Data = base64Match[1];
      }
    }
    const binaryString = atob(base64Data);
    const bytes = new Uint8Array(binaryString.length);
    for (let i7 = 0; i7 < binaryString.length; i7++) {
      bytes[i7] = binaryString.charCodeAt(i7);
    }
    return bytes;
  }
  getHeaderButtons() {
    return b2`
			<div class="flex items-center gap-1">
				${DownloadButton({
      content: this.decodeBase64(),
      filename: this.filename,
      mimeType: "application/pdf",
      title: i18n("Download")
    })}
			</div>
		`;
  }
  async updated(changedProperties) {
    super.updated(changedProperties);
    if (changedProperties.has("_content") && this._content && !this.error) {
      await this.renderPdf();
    }
  }
  async renderPdf() {
    const container = this.querySelector("#pdf-container");
    if (!container || !this._content)
      return;
    let pdf = null;
    try {
      const arrayBuffer = this.base64ToArrayBuffer(this._content);
      if (this.currentLoadingTask) {
        this.currentLoadingTask.destroy();
      }
      this.currentLoadingTask = getDocument({ data: arrayBuffer });
      pdf = await this.currentLoadingTask.promise;
      this.currentLoadingTask = null;
      container.innerHTML = "";
      const wrapper = document.createElement("div");
      wrapper.className = "p-4";
      container.appendChild(wrapper);
      for (let pageNum = 1; pageNum <= pdf.numPages; pageNum++) {
        const page = await pdf.getPage(pageNum);
        const pageContainer = document.createElement("div");
        pageContainer.className = "mb-4 last:mb-0";
        const canvas = document.createElement("canvas");
        const context = canvas.getContext("2d");
        const viewport = page.getViewport({ scale: 1.5 });
        canvas.height = viewport.height;
        canvas.width = viewport.width;
        canvas.className = "w-full max-w-full h-auto block mx-auto bg-white rounded shadow-sm border border-border";
        if (context) {
          context.fillStyle = "white";
          context.fillRect(0, 0, canvas.width, canvas.height);
        }
        await page.render({
          canvasContext: context,
          viewport,
          canvas
        }).promise;
        pageContainer.appendChild(canvas);
        if (pageNum < pdf.numPages) {
          const separator = document.createElement("div");
          separator.className = "h-px bg-border my-4";
          pageContainer.appendChild(separator);
        }
        wrapper.appendChild(pageContainer);
      }
    } catch (error) {
      console.error("Error rendering PDF:", error);
      this.error = error?.message || i18n("Failed to load PDF");
    } finally {
      if (pdf) {
        pdf.destroy();
      }
    }
  }
  render() {
    if (this.error) {
      return b2`
				<div class="h-full flex items-center justify-center bg-background p-4">
					<div class="bg-destructive/10 border border-destructive text-destructive p-4 rounded-lg max-w-2xl">
						<div class="font-medium mb-1">${i18n("Error loading PDF")}</div>
						<div class="text-sm opacity-90">${this.error}</div>
					</div>
				</div>
			`;
    }
    return b2`
			<div class="h-full flex flex-col bg-background overflow-auto">
				<div id="pdf-container" class="flex-1 overflow-auto"></div>
			</div>
		`;
  }
};
__decorate22([
  n6({ type: String })
], PdfArtifact.prototype, "_content", void 0);
__decorate22([
  r7()
], PdfArtifact.prototype, "error", void 0);
PdfArtifact = __decorate22([
  t5("pdf-artifact")
], PdfArtifact);

// ../pi-mono/packages/web-ui/dist/tools/artifacts/SvgArtifact.js
init_process_shim();
var import_highlight3 = __toESM(require_lib(), 1);
var __decorate23 = function(decorators, target, key, desc) {
  var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc);
  else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8;
  return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8;
};
var SvgArtifact = class SvgArtifact2 extends ArtifactElement {
  constructor() {
    super(...arguments);
    this.filename = "";
    this._content = "";
    this.viewMode = "preview";
  }
  get content() {
    return this._content;
  }
  set content(value) {
    this._content = value;
    this.requestUpdate();
  }
  createRenderRoot() {
    return this;
  }
  setViewMode(mode) {
    this.viewMode = mode;
  }
  getHeaderButtons() {
    const toggle = new PreviewCodeToggle();
    toggle.mode = this.viewMode;
    toggle.addEventListener("mode-change", (e9) => {
      this.setViewMode(e9.detail);
    });
    const copyButton = new CopyButton();
    copyButton.text = this._content;
    copyButton.title = i18n("Copy SVG");
    copyButton.showText = false;
    return b2`
			<div class="flex items-center gap-2">
				${toggle}
				${copyButton}
				${DownloadButton({ content: this._content, filename: this.filename, mimeType: "image/svg+xml", title: i18n("Download SVG") })}
			</div>
		`;
  }
  render() {
    return b2`
			<div class="h-full flex flex-col">
				<div class="flex-1 overflow-auto">
					${this.viewMode === "preview" ? b2`<div class="h-full flex items-center justify-center">
								${o7(this.content.replace(/<svg(\s|>)/i, (_m, p1) => `<svg class="w-full h-full"${p1}`))}
							</div>` : b2`<pre class="m-0 p-4 text-xs"><code class="hljs language-xml">${o7(import_highlight3.default.highlight(this.content, { language: "xml", ignoreIllegals: true }).value)}</code></pre>`}
				</div>
			</div>
		`;
  }
};
__decorate23([
  n6()
], SvgArtifact.prototype, "filename", void 0);
__decorate23([
  r7()
], SvgArtifact.prototype, "viewMode", void 0);
SvgArtifact = __decorate23([
  t5("svg-artifact")
], SvgArtifact);

// ../pi-mono/packages/web-ui/dist/tools/artifacts/TextArtifact.js
init_process_shim();
var import_highlight4 = __toESM(require_lib(), 1);
var __decorate24 = function(decorators, target, key, desc) {
  var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc);
  else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8;
  return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8;
};
var CODE_EXTENSIONS = [
  "js",
  "javascript",
  "ts",
  "typescript",
  "jsx",
  "tsx",
  "py",
  "python",
  "java",
  "c",
  "cpp",
  "cs",
  "php",
  "rb",
  "ruby",
  "go",
  "rust",
  "swift",
  "kotlin",
  "scala",
  "dart",
  "html",
  "css",
  "scss",
  "sass",
  "less",
  "json",
  "xml",
  "yaml",
  "yml",
  "toml",
  "sql",
  "sh",
  "bash",
  "ps1",
  "bat",
  "r",
  "matlab",
  "julia",
  "lua",
  "perl",
  "vue",
  "svelte"
];
var TextArtifact = class TextArtifact2 extends ArtifactElement {
  constructor() {
    super(...arguments);
    this.filename = "";
    this._content = "";
  }
  get content() {
    return this._content;
  }
  set content(value) {
    this._content = value;
    this.requestUpdate();
  }
  createRenderRoot() {
    return this;
  }
  isCode() {
    const ext2 = this.filename.split(".").pop()?.toLowerCase() || "";
    return CODE_EXTENSIONS.includes(ext2);
  }
  getLanguageFromExtension(ext2) {
    const languageMap = {
      js: "javascript",
      ts: "typescript",
      py: "python",
      rb: "ruby",
      yml: "yaml",
      ps1: "powershell",
      bat: "batch"
    };
    return languageMap[ext2] || ext2;
  }
  getMimeType() {
    const ext2 = this.filename.split(".").pop()?.toLowerCase() || "";
    if (ext2 === "svg")
      return "image/svg+xml";
    if (ext2 === "md" || ext2 === "markdown")
      return "text/markdown";
    return "text/plain";
  }
  getHeaderButtons() {
    const copyButton = new CopyButton();
    copyButton.text = this.content;
    copyButton.title = i18n("Copy");
    copyButton.showText = false;
    return b2`
			<div class="flex items-center gap-1">
				${copyButton}
				${DownloadButton({
      content: this.content,
      filename: this.filename,
      mimeType: this.getMimeType(),
      title: i18n("Download")
    })}
			</div>
		`;
  }
  render() {
    const isCode = this.isCode();
    const ext2 = this.filename.split(".").pop() || "";
    return b2`
			<div class="h-full flex flex-col">
				<div class="flex-1 overflow-auto">
					${isCode ? b2`
								<pre class="m-0 p-4 text-xs"><code class="hljs language-${this.getLanguageFromExtension(ext2.toLowerCase())}">${o7(import_highlight4.default.highlight(this.content, {
      language: this.getLanguageFromExtension(ext2.toLowerCase()),
      ignoreIllegals: true
    }).value)}</code></pre>
							` : b2` <pre class="m-0 p-4 text-xs font-mono">${this.content}</pre> `}
				</div>
			</div>
		`;
  }
};
__decorate24([
  n6()
], TextArtifact.prototype, "filename", void 0);
TextArtifact = __decorate24([
  t5("text-artifact")
], TextArtifact);

// ../pi-mono/packages/web-ui/dist/tools/artifacts/artifacts.js
var __decorate25 = function(decorators, target, key, desc) {
  var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc);
  else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8;
  return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8;
};
var artifactsParamsSchema = Type.Object({
  command: StringEnum(["create", "update", "rewrite", "get", "delete", "logs"], {
    description: "The operation to perform"
  }),
  filename: Type.String({ description: "Filename including extension (e.g., 'index.html', 'script.js')" }),
  content: Type.Optional(Type.String({ description: "File content" })),
  old_str: Type.Optional(Type.String({ description: "String to replace (for update command)" })),
  new_str: Type.Optional(Type.String({ description: "Replacement string (for update command)" }))
});
var ArtifactsPanel = class ArtifactsPanel2 extends i4 {
  constructor() {
    super(...arguments);
    this._artifacts = /* @__PURE__ */ new Map();
    this._activeFilename = null;
    this.artifactElements = /* @__PURE__ */ new Map();
    this.contentRef = e5();
    this.collapsed = false;
    this.overlay = false;
  }
  // Public getter for artifacts
  get artifacts() {
    return this._artifacts;
  }
  // Get runtime providers for HTML artifacts (read-only: attachments + artifacts)
  getHtmlArtifactRuntimeProviders() {
    const providers = [];
    if (this.agent) {
      const attachments = [];
      for (const message of this.agent.state.messages) {
        if (message.role === "user-with-attachments" && message.attachments) {
          attachments.push(...message.attachments);
        }
      }
      if (attachments.length > 0) {
        providers.push(new AttachmentsRuntimeProvider(attachments));
      }
    }
    providers.push(new ArtifactsRuntimeProvider(this, this.agent, false));
    return providers;
  }
  createRenderRoot() {
    return this;
  }
  connectedCallback() {
    super.connectedCallback();
    this.style.display = "block";
    this.style.height = "100%";
    requestAnimationFrame(() => {
      const container = this.contentRef.value;
      if (!container)
        return;
      if (!this._activeFilename && this._artifacts.size > 0) {
        this._activeFilename = Array.from(this._artifacts.keys())[0];
      }
      this.artifactElements.forEach((element, name) => {
        if (!element.parentElement)
          container.appendChild(element);
        element.style.display = name === this._activeFilename ? "block" : "none";
      });
    });
  }
  disconnectedCallback() {
    super.disconnectedCallback();
  }
  // Helper to determine file type from extension
  getFileType(filename) {
    const ext2 = filename.split(".").pop()?.toLowerCase();
    if (ext2 === "html")
      return "html";
    if (ext2 === "svg")
      return "svg";
    if (ext2 === "md" || ext2 === "markdown")
      return "markdown";
    if (ext2 === "pdf")
      return "pdf";
    if (ext2 === "xlsx" || ext2 === "xls")
      return "excel";
    if (ext2 === "docx")
      return "docx";
    if (ext2 === "png" || ext2 === "jpg" || ext2 === "jpeg" || ext2 === "gif" || ext2 === "webp" || ext2 === "bmp" || ext2 === "ico")
      return "image";
    if (ext2 === "txt" || ext2 === "json" || ext2 === "xml" || ext2 === "yaml" || ext2 === "yml" || ext2 === "csv" || ext2 === "js" || ext2 === "ts" || ext2 === "jsx" || ext2 === "tsx" || ext2 === "py" || ext2 === "java" || ext2 === "c" || ext2 === "cpp" || ext2 === "h" || ext2 === "css" || ext2 === "scss" || ext2 === "sass" || ext2 === "less" || ext2 === "sh")
      return "text";
    return "generic";
  }
  // Get or create artifact element
  getOrCreateArtifactElement(filename, content) {
    let element = this.artifactElements.get(filename);
    if (!element) {
      const type = this.getFileType(filename);
      if (type === "html") {
        element = new HtmlArtifact();
        element.runtimeProviders = this.getHtmlArtifactRuntimeProviders();
        if (this.sandboxUrlProvider) {
          element.sandboxUrlProvider = this.sandboxUrlProvider;
        }
      } else if (type === "svg") {
        element = new SvgArtifact();
      } else if (type === "markdown") {
        element = new MarkdownArtifact();
      } else if (type === "image") {
        element = new ImageArtifact();
      } else if (type === "pdf") {
        element = new PdfArtifact();
      } else if (type === "excel") {
        element = new ExcelArtifact();
      } else if (type === "docx") {
        element = new DocxArtifact();
      } else if (type === "text") {
        element = new TextArtifact();
      } else {
        element = new GenericArtifact();
      }
      element.filename = filename;
      element.content = content;
      element.style.display = "none";
      element.style.height = "100%";
      this.artifactElements.set(filename, element);
      const newElement = element;
      if (this.contentRef.value) {
        this.contentRef.value.appendChild(newElement);
      } else {
        requestAnimationFrame(() => {
          if (this.contentRef.value && !newElement.parentElement) {
            this.contentRef.value.appendChild(newElement);
          }
        });
      }
    } else {
      element.content = content;
      if (element instanceof HtmlArtifact) {
        element.runtimeProviders = this.getHtmlArtifactRuntimeProviders();
      }
    }
    return element;
  }
  // Show/hide artifact elements
  showArtifact(filename) {
    requestAnimationFrame(() => {
      this.artifactElements.forEach((element, name) => {
        if (this.contentRef.value && !element.parentElement) {
          this.contentRef.value.appendChild(element);
        }
        element.style.display = name === filename ? "block" : "none";
      });
    });
    this._activeFilename = filename;
    this.requestUpdate();
    requestAnimationFrame(() => {
      const activeButton = this.querySelector(`button[data-filename="${filename}"]`);
      if (activeButton) {
        activeButton.scrollIntoView({ behavior: "smooth", block: "nearest", inline: "center" });
      }
    });
  }
  // Open panel and focus an artifact tab by filename
  openArtifact(filename) {
    if (this._artifacts.has(filename)) {
      this.showArtifact(filename);
      this.onOpen?.();
    }
  }
  // Build the AgentTool (no details payload; return only output strings)
  get tool() {
    return {
      label: "Artifacts",
      name: "artifacts",
      get description() {
        const runtimeProviderDescriptions = [
          ATTACHMENTS_RUNTIME_DESCRIPTION,
          ARTIFACTS_RUNTIME_PROVIDER_DESCRIPTION_RO
        ];
        return ARTIFACTS_TOOL_DESCRIPTION(runtimeProviderDescriptions);
      },
      parameters: artifactsParamsSchema,
      // Execute mutates our local store and returns a plain output
      execute: async (_toolCallId, args, _signal) => {
        const output = await this.executeCommand(args);
        return { content: [{ type: "text", text: output }], details: void 0 };
      }
    };
  }
  // Re-apply artifacts by scanning a message list (optional utility)
  async reconstructFromMessages(messages) {
    const toolCalls = /* @__PURE__ */ new Map();
    const artifactToolName = "artifacts";
    for (const message of messages) {
      if (message.role === "assistant") {
        for (const block of message.content) {
          if (block.type === "toolCall" && block.name === artifactToolName) {
            toolCalls.set(block.id, block);
          }
        }
      }
    }
    const operations = [];
    for (const m4 of messages) {
      if (m4.role === "artifact") {
        const artifactMsg = m4;
        switch (artifactMsg.action) {
          case "create":
            operations.push({
              command: "create",
              filename: artifactMsg.filename,
              content: artifactMsg.content
            });
            break;
          case "update":
            operations.push({
              command: "rewrite",
              filename: artifactMsg.filename,
              content: artifactMsg.content
            });
            break;
          case "delete":
            operations.push({
              command: "delete",
              filename: artifactMsg.filename
            });
            break;
        }
      } else if (m4.role === "toolResult" && m4.toolName === artifactToolName && !m4.isError) {
        const toolCallId = m4.toolCallId;
        const call = toolCalls.get(toolCallId);
        if (!call)
          continue;
        const params = call.arguments;
        if (params.command === "get" || params.command === "logs")
          continue;
        operations.push(params);
      }
    }
    const finalArtifacts = /* @__PURE__ */ new Map();
    for (const op2 of operations) {
      const filename = op2.filename;
      switch (op2.command) {
        case "create": {
          if (op2.content) {
            finalArtifacts.set(filename, op2.content);
          }
          break;
        }
        case "rewrite": {
          if (op2.content) {
            finalArtifacts.set(filename, op2.content);
          }
          break;
        }
        case "update": {
          let existing = finalArtifacts.get(filename);
          if (!existing)
            break;
          if (op2.old_str !== void 0 && op2.new_str !== void 0) {
            existing = existing.replace(op2.old_str, op2.new_str);
            finalArtifacts.set(filename, existing);
          }
          break;
        }
        case "delete": {
          finalArtifacts.delete(filename);
          break;
        }
        case "get":
        case "logs":
          break;
      }
    }
    this._artifacts.clear();
    this.artifactElements.forEach((el) => {
      el.remove();
    });
    this.artifactElements.clear();
    this._activeFilename = null;
    this._artifacts = new Map(this._artifacts);
    for (const [filename, content] of finalArtifacts.entries()) {
      const createParams = { command: "create", filename, content };
      try {
        await this.createArtifact(createParams, { skipWait: true, silent: true });
      } catch {
      }
    }
    if (!this._activeFilename && this._artifacts.size > 0) {
      this.showArtifact(Array.from(this._artifacts.keys())[0]);
    }
    this.onArtifactsChange?.();
    this.requestUpdate();
  }
  // Core command executor
  async executeCommand(params, options = {}) {
    switch (params.command) {
      case "create":
        return await this.createArtifact(params, options);
      case "update":
        return await this.updateArtifact(params, options);
      case "rewrite":
        return await this.rewriteArtifact(params, options);
      case "get":
        return this.getArtifact(params);
      case "delete":
        return this.deleteArtifact(params);
      case "logs":
        return this.getLogs(params);
      default:
        return `Error: Unknown command ${params.command}`;
    }
  }
  // Wait for HTML artifact execution and get logs
  async waitForHtmlExecution(filename) {
    const element = this.artifactElements.get(filename);
    if (!(element instanceof HtmlArtifact)) {
      return "";
    }
    return new Promise((resolve) => {
      setTimeout(() => {
        const logs = element.getLogs();
        resolve(logs);
      }, 1500);
    });
  }
  // Reload all HTML artifacts (called when any artifact changes)
  reloadAllHtmlArtifacts() {
    this.artifactElements.forEach((element) => {
      if (element instanceof HtmlArtifact && element.sandboxIframeRef.value) {
        element.runtimeProviders = this.getHtmlArtifactRuntimeProviders();
        element.executeContent(element.content);
      }
    });
  }
  async createArtifact(params, options = {}) {
    if (!params.filename || !params.content) {
      return "Error: create command requires filename and content";
    }
    if (this._artifacts.has(params.filename)) {
      return `Error: File ${params.filename} already exists`;
    }
    const artifact = {
      filename: params.filename,
      content: params.content,
      createdAt: /* @__PURE__ */ new Date(),
      updatedAt: /* @__PURE__ */ new Date()
    };
    this._artifacts.set(params.filename, artifact);
    this._artifacts = new Map(this._artifacts);
    this.getOrCreateArtifactElement(params.filename, params.content);
    if (!options.silent) {
      this.showArtifact(params.filename);
      this.onArtifactsChange?.();
      this.requestUpdate();
    }
    this.reloadAllHtmlArtifacts();
    let result = `Created file ${params.filename}`;
    if (this.getFileType(params.filename) === "html" && !options.skipWait) {
      const logs = await this.waitForHtmlExecution(params.filename);
      result += `
${logs}`;
    }
    return result;
  }
  async updateArtifact(params, options = {}) {
    const artifact = this._artifacts.get(params.filename);
    if (!artifact) {
      const files = Array.from(this._artifacts.keys());
      if (files.length === 0)
        return `Error: File ${params.filename} not found. No files have been created yet.`;
      return `Error: File ${params.filename} not found. Available files: ${files.join(", ")}`;
    }
    if (!params.old_str || params.new_str === void 0) {
      return "Error: update command requires old_str and new_str";
    }
    if (!artifact.content.includes(params.old_str)) {
      return `Error: String not found in file. Here is the full content:

${artifact.content}`;
    }
    artifact.content = artifact.content.replace(params.old_str, params.new_str);
    artifact.updatedAt = /* @__PURE__ */ new Date();
    this._artifacts.set(params.filename, artifact);
    this.getOrCreateArtifactElement(params.filename, artifact.content);
    if (!options.silent) {
      this.onArtifactsChange?.();
      this.requestUpdate();
    }
    this.showArtifact(params.filename);
    this.reloadAllHtmlArtifacts();
    let result = `Updated file ${params.filename}`;
    if (this.getFileType(params.filename) === "html" && !options.skipWait) {
      const logs = await this.waitForHtmlExecution(params.filename);
      result += `
${logs}`;
    }
    return result;
  }
  async rewriteArtifact(params, options = {}) {
    const artifact = this._artifacts.get(params.filename);
    if (!artifact) {
      const files = Array.from(this._artifacts.keys());
      if (files.length === 0)
        return `Error: File ${params.filename} not found. No files have been created yet.`;
      return `Error: File ${params.filename} not found. Available files: ${files.join(", ")}`;
    }
    if (!params.content) {
      return "Error: rewrite command requires content";
    }
    artifact.content = params.content;
    artifact.updatedAt = /* @__PURE__ */ new Date();
    this._artifacts.set(params.filename, artifact);
    this.getOrCreateArtifactElement(params.filename, artifact.content);
    if (!options.silent) {
      this.onArtifactsChange?.();
    }
    this.showArtifact(params.filename);
    this.reloadAllHtmlArtifacts();
    let result = "";
    if (this.getFileType(params.filename) === "html" && !options.skipWait) {
      const logs = await this.waitForHtmlExecution(params.filename);
      result += `
${logs}`;
    }
    return result;
  }
  getArtifact(params) {
    const artifact = this._artifacts.get(params.filename);
    if (!artifact) {
      const files = Array.from(this._artifacts.keys());
      if (files.length === 0)
        return `Error: File ${params.filename} not found. No files have been created yet.`;
      return `Error: File ${params.filename} not found. Available files: ${files.join(", ")}`;
    }
    return artifact.content;
  }
  deleteArtifact(params) {
    const artifact = this._artifacts.get(params.filename);
    if (!artifact) {
      const files = Array.from(this._artifacts.keys());
      if (files.length === 0)
        return `Error: File ${params.filename} not found. No files have been created yet.`;
      return `Error: File ${params.filename} not found. Available files: ${files.join(", ")}`;
    }
    this._artifacts.delete(params.filename);
    this._artifacts = new Map(this._artifacts);
    const element = this.artifactElements.get(params.filename);
    if (element) {
      element.remove();
      this.artifactElements.delete(params.filename);
    }
    if (this._activeFilename === params.filename) {
      const remaining = Array.from(this._artifacts.keys());
      if (remaining.length > 0) {
        this.showArtifact(remaining[0]);
      } else {
        this._activeFilename = null;
        this.requestUpdate();
      }
    }
    this.onArtifactsChange?.();
    this.requestUpdate();
    this.reloadAllHtmlArtifacts();
    return `Deleted file ${params.filename}`;
  }
  getLogs(params) {
    const element = this.artifactElements.get(params.filename);
    if (!element) {
      const files = Array.from(this._artifacts.keys());
      if (files.length === 0)
        return `Error: File ${params.filename} not found. No files have been created yet.`;
      return `Error: File ${params.filename} not found. Available files: ${files.join(", ")}`;
    }
    if (!(element instanceof HtmlArtifact)) {
      return `Error: File ${params.filename} is not an HTML file. Logs are only available for HTML files.`;
    }
    return element.getLogs();
  }
  render() {
    const artifacts = Array.from(this._artifacts.values());
    const showPanel = artifacts.length > 0 && !this.collapsed;
    return b2`
			<div
				class="${showPanel ? "" : "hidden"} ${this.overlay ? "fixed inset-0 z-40 pointer-events-auto backdrop-blur-sm bg-background/95" : "relative"} h-full flex flex-col bg-background text-card-foreground ${!this.overlay ? "border-l border-border" : ""} overflow-hidden shadow-xl"
			>
				<!-- Tab bar (always shown when there are artifacts) -->
				<div class="flex items-center justify-between border-b border-border bg-background">
					<div class="flex overflow-x-auto">
						${artifacts.map((a3) => {
      const isActive = a3.filename === this._activeFilename;
      const activeClass = isActive ? "border-primary text-primary" : "border-transparent text-muted-foreground hover:text-foreground";
      return b2`
								<button
									class="px-3 py-2 whitespace-nowrap border-b-2 ${activeClass}"
									data-filename="${a3.filename}"
									@click=${() => this.showArtifact(a3.filename)}
								>
									<span class="font-mono text-xs">${a3.filename}</span>
								</button>
							`;
    })}
					</div>
					<div class="flex items-center gap-1 px-2">
						${(() => {
      const active = this._activeFilename ? this.artifactElements.get(this._activeFilename) : void 0;
      return active ? active.getHeaderButtons() : "";
    })()}
						${Button({
      variant: "ghost",
      size: "sm",
      onClick: () => this.onClose?.(),
      title: i18n("Close artifacts"),
      children: icon(X, "sm")
    })}
					</div>
				</div>

				<!-- Content area where artifact elements are added programmatically -->
				<div class="flex-1 overflow-hidden" ${n5(this.contentRef)}></div>
			</div>
		`;
  }
};
__decorate25([
  r7()
], ArtifactsPanel.prototype, "_artifacts", void 0);
__decorate25([
  r7()
], ArtifactsPanel.prototype, "_activeFilename", void 0);
__decorate25([
  n6({ attribute: false })
], ArtifactsPanel.prototype, "agent", void 0);
__decorate25([
  n6({ attribute: false })
], ArtifactsPanel.prototype, "sandboxUrlProvider", void 0);
__decorate25([
  n6({ attribute: false })
], ArtifactsPanel.prototype, "onArtifactsChange", void 0);
__decorate25([
  n6({ attribute: false })
], ArtifactsPanel.prototype, "onClose", void 0);
__decorate25([
  n6({ attribute: false })
], ArtifactsPanel.prototype, "onOpen", void 0);
__decorate25([
  n6({ type: Boolean })
], ArtifactsPanel.prototype, "collapsed", void 0);
__decorate25([
  n6({ type: Boolean })
], ArtifactsPanel.prototype, "overlay", void 0);
ArtifactsPanel = __decorate25([
  t5("artifacts-panel")
], ArtifactsPanel);

// ../pi-mono/packages/web-ui/dist/tools/artifacts/artifacts-tool-renderer.js
init_process_shim();

// ../mini-lit/dist/CodeBlock.js
init_process_shim();

// ../mini-lit/node_modules/highlight.js/es/core.js
init_process_shim();
var import_core = __toESM(require_core4(), 1);
var core_default = import_core.default;

// ../mini-lit/node_modules/highlight.js/es/languages/bash.js
init_process_shim();
function bash(hljs5) {
  const regex = hljs5.regex;
  const VAR = {};
  const BRACED_VAR = {
    begin: /\$\{/,
    end: /\}/,
    contains: [
      "self",
      {
        begin: /:-/,
        contains: [VAR]
      }
      // default values
    ]
  };
  Object.assign(VAR, {
    className: "variable",
    variants: [
      { begin: regex.concat(
        /\$[\w\d#@][\w\d_]*/,
        // negative look-ahead tries to avoid matching patterns that are not
        // Perl at all like $ident$, @ident@, etc.
        `(?![\\w\\d])(?![$])`
      ) },
      BRACED_VAR
    ]
  });
  const SUBST = {
    className: "subst",
    begin: /\$\(/,
    end: /\)/,
    contains: [hljs5.BACKSLASH_ESCAPE]
  };
  const COMMENT = hljs5.inherit(
    hljs5.COMMENT(),
    {
      match: [
        /(^|\s)/,
        /#.*$/
      ],
      scope: {
        2: "comment"
      }
    }
  );
  const HERE_DOC = {
    begin: /<<-?\s*(?=\w+)/,
    starts: { contains: [
      hljs5.END_SAME_AS_BEGIN({
        begin: /(\w+)/,
        end: /(\w+)/,
        className: "string"
      })
    ] }
  };
  const QUOTE_STRING = {
    className: "string",
    begin: /"/,
    end: /"/,
    contains: [
      hljs5.BACKSLASH_ESCAPE,
      VAR,
      SUBST
    ]
  };
  SUBST.contains.push(QUOTE_STRING);
  const ESCAPED_QUOTE = {
    match: /\\"/
  };
  const APOS_STRING = {
    className: "string",
    begin: /'/,
    end: /'/
  };
  const ESCAPED_APOS = {
    match: /\\'/
  };
  const ARITHMETIC = {
    begin: /\$?\(\(/,
    end: /\)\)/,
    contains: [
      {
        begin: /\d+#[0-9a-f]+/,
        className: "number"
      },
      hljs5.NUMBER_MODE,
      VAR
    ]
  };
  const SH_LIKE_SHELLS = [
    "fish",
    "bash",
    "zsh",
    "sh",
    "csh",
    "ksh",
    "tcsh",
    "dash",
    "scsh"
  ];
  const KNOWN_SHEBANG = hljs5.SHEBANG({
    binary: `(${SH_LIKE_SHELLS.join("|")})`,
    relevance: 10
  });
  const FUNCTION = {
    className: "function",
    begin: /\w[\w\d_]*\s*\(\s*\)\s*\{/,
    returnBegin: true,
    contains: [hljs5.inherit(hljs5.TITLE_MODE, { begin: /\w[\w\d_]*/ })],
    relevance: 0
  };
  const KEYWORDS3 = [
    "if",
    "then",
    "else",
    "elif",
    "fi",
    "time",
    "for",
    "while",
    "until",
    "in",
    "do",
    "done",
    "case",
    "esac",
    "coproc",
    "function",
    "select"
  ];
  const LITERALS3 = [
    "true",
    "false"
  ];
  const PATH_MODE = { match: /(\/[a-z._-]+)+/ };
  const SHELL_BUILT_INS = [
    "break",
    "cd",
    "continue",
    "eval",
    "exec",
    "exit",
    "export",
    "getopts",
    "hash",
    "pwd",
    "readonly",
    "return",
    "shift",
    "test",
    "times",
    "trap",
    "umask",
    "unset"
  ];
  const BASH_BUILT_INS = [
    "alias",
    "bind",
    "builtin",
    "caller",
    "command",
    "declare",
    "echo",
    "enable",
    "help",
    "let",
    "local",
    "logout",
    "mapfile",
    "printf",
    "read",
    "readarray",
    "source",
    "sudo",
    "type",
    "typeset",
    "ulimit",
    "unalias"
  ];
  const ZSH_BUILT_INS = [
    "autoload",
    "bg",
    "bindkey",
    "bye",
    "cap",
    "chdir",
    "clone",
    "comparguments",
    "compcall",
    "compctl",
    "compdescribe",
    "compfiles",
    "compgroups",
    "compquote",
    "comptags",
    "comptry",
    "compvalues",
    "dirs",
    "disable",
    "disown",
    "echotc",
    "echoti",
    "emulate",
    "fc",
    "fg",
    "float",
    "functions",
    "getcap",
    "getln",
    "history",
    "integer",
    "jobs",
    "kill",
    "limit",
    "log",
    "noglob",
    "popd",
    "print",
    "pushd",
    "pushln",
    "rehash",
    "sched",
    "setcap",
    "setopt",
    "stat",
    "suspend",
    "ttyctl",
    "unfunction",
    "unhash",
    "unlimit",
    "unsetopt",
    "vared",
    "wait",
    "whence",
    "where",
    "which",
    "zcompile",
    "zformat",
    "zftp",
    "zle",
    "zmodload",
    "zparseopts",
    "zprof",
    "zpty",
    "zregexparse",
    "zsocket",
    "zstyle",
    "ztcp"
  ];
  const GNU_CORE_UTILS = [
    "chcon",
    "chgrp",
    "chown",
    "chmod",
    "cp",
    "dd",
    "df",
    "dir",
    "dircolors",
    "ln",
    "ls",
    "mkdir",
    "mkfifo",
    "mknod",
    "mktemp",
    "mv",
    "realpath",
    "rm",
    "rmdir",
    "shred",
    "sync",
    "touch",
    "truncate",
    "vdir",
    "b2sum",
    "base32",
    "base64",
    "cat",
    "cksum",
    "comm",
    "csplit",
    "cut",
    "expand",
    "fmt",
    "fold",
    "head",
    "join",
    "md5sum",
    "nl",
    "numfmt",
    "od",
    "paste",
    "ptx",
    "pr",
    "sha1sum",
    "sha224sum",
    "sha256sum",
    "sha384sum",
    "sha512sum",
    "shuf",
    "sort",
    "split",
    "sum",
    "tac",
    "tail",
    "tr",
    "tsort",
    "unexpand",
    "uniq",
    "wc",
    "arch",
    "basename",
    "chroot",
    "date",
    "dirname",
    "du",
    "echo",
    "env",
    "expr",
    "factor",
    // "false", // keyword literal already
    "groups",
    "hostid",
    "id",
    "link",
    "logname",
    "nice",
    "nohup",
    "nproc",
    "pathchk",
    "pinky",
    "printenv",
    "printf",
    "pwd",
    "readlink",
    "runcon",
    "seq",
    "sleep",
    "stat",
    "stdbuf",
    "stty",
    "tee",
    "test",
    "timeout",
    // "true", // keyword literal already
    "tty",
    "uname",
    "unlink",
    "uptime",
    "users",
    "who",
    "whoami",
    "yes"
  ];
  return {
    name: "Bash",
    aliases: [
      "sh",
      "zsh"
    ],
    keywords: {
      $pattern: /\b[a-z][a-z0-9._-]+\b/,
      keyword: KEYWORDS3,
      literal: LITERALS3,
      built_in: [
        ...SHELL_BUILT_INS,
        ...BASH_BUILT_INS,
        // Shell modifiers
        "set",
        "shopt",
        ...ZSH_BUILT_INS,
        ...GNU_CORE_UTILS
      ]
    },
    contains: [
      KNOWN_SHEBANG,
      // to catch known shells and boost relevancy
      hljs5.SHEBANG(),
      // to catch unknown shells but still highlight the shebang
      FUNCTION,
      ARITHMETIC,
      COMMENT,
      HERE_DOC,
      PATH_MODE,
      QUOTE_STRING,
      ESCAPED_QUOTE,
      APOS_STRING,
      ESCAPED_APOS,
      VAR
    ]
  };
}

// ../mini-lit/node_modules/highlight.js/es/languages/css.js
init_process_shim();
var MODES = (hljs5) => {
  return {
    IMPORTANT: {
      scope: "meta",
      begin: "!important"
    },
    BLOCK_COMMENT: hljs5.C_BLOCK_COMMENT_MODE,
    HEXCOLOR: {
      scope: "number",
      begin: /#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/
    },
    FUNCTION_DISPATCH: {
      className: "built_in",
      begin: /[\w-]+(?=\()/
    },
    ATTRIBUTE_SELECTOR_MODE: {
      scope: "selector-attr",
      begin: /\[/,
      end: /\]/,
      illegal: "$",
      contains: [
        hljs5.APOS_STRING_MODE,
        hljs5.QUOTE_STRING_MODE
      ]
    },
    CSS_NUMBER_MODE: {
      scope: "number",
      begin: hljs5.NUMBER_RE + "(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",
      relevance: 0
    },
    CSS_VARIABLE: {
      className: "attr",
      begin: /--[A-Za-z_][A-Za-z0-9_-]*/
    }
  };
};
var HTML_TAGS = [
  "a",
  "abbr",
  "address",
  "article",
  "aside",
  "audio",
  "b",
  "blockquote",
  "body",
  "button",
  "canvas",
  "caption",
  "cite",
  "code",
  "dd",
  "del",
  "details",
  "dfn",
  "div",
  "dl",
  "dt",
  "em",
  "fieldset",
  "figcaption",
  "figure",
  "footer",
  "form",
  "h1",
  "h2",
  "h3",
  "h4",
  "h5",
  "h6",
  "header",
  "hgroup",
  "html",
  "i",
  "iframe",
  "img",
  "input",
  "ins",
  "kbd",
  "label",
  "legend",
  "li",
  "main",
  "mark",
  "menu",
  "nav",
  "object",
  "ol",
  "optgroup",
  "option",
  "p",
  "picture",
  "q",
  "quote",
  "samp",
  "section",
  "select",
  "source",
  "span",
  "strong",
  "summary",
  "sup",
  "table",
  "tbody",
  "td",
  "textarea",
  "tfoot",
  "th",
  "thead",
  "time",
  "tr",
  "ul",
  "var",
  "video"
];
var SVG_TAGS = [
  "defs",
  "g",
  "marker",
  "mask",
  "pattern",
  "svg",
  "switch",
  "symbol",
  "feBlend",
  "feColorMatrix",
  "feComponentTransfer",
  "feComposite",
  "feConvolveMatrix",
  "feDiffuseLighting",
  "feDisplacementMap",
  "feFlood",
  "feGaussianBlur",
  "feImage",
  "feMerge",
  "feMorphology",
  "feOffset",
  "feSpecularLighting",
  "feTile",
  "feTurbulence",
  "linearGradient",
  "radialGradient",
  "stop",
  "circle",
  "ellipse",
  "image",
  "line",
  "path",
  "polygon",
  "polyline",
  "rect",
  "text",
  "use",
  "textPath",
  "tspan",
  "foreignObject",
  "clipPath"
];
var TAGS = [
  ...HTML_TAGS,
  ...SVG_TAGS
];
var MEDIA_FEATURES = [
  "any-hover",
  "any-pointer",
  "aspect-ratio",
  "color",
  "color-gamut",
  "color-index",
  "device-aspect-ratio",
  "device-height",
  "device-width",
  "display-mode",
  "forced-colors",
  "grid",
  "height",
  "hover",
  "inverted-colors",
  "monochrome",
  "orientation",
  "overflow-block",
  "overflow-inline",
  "pointer",
  "prefers-color-scheme",
  "prefers-contrast",
  "prefers-reduced-motion",
  "prefers-reduced-transparency",
  "resolution",
  "scan",
  "scripting",
  "update",
  "width",
  // TODO: find a better solution?
  "min-width",
  "max-width",
  "min-height",
  "max-height"
].sort().reverse();
var PSEUDO_CLASSES = [
  "active",
  "any-link",
  "blank",
  "checked",
  "current",
  "default",
  "defined",
  "dir",
  // dir()
  "disabled",
  "drop",
  "empty",
  "enabled",
  "first",
  "first-child",
  "first-of-type",
  "fullscreen",
  "future",
  "focus",
  "focus-visible",
  "focus-within",
  "has",
  // has()
  "host",
  // host or host()
  "host-context",
  // host-context()
  "hover",
  "indeterminate",
  "in-range",
  "invalid",
  "is",
  // is()
  "lang",
  // lang()
  "last-child",
  "last-of-type",
  "left",
  "link",
  "local-link",
  "not",
  // not()
  "nth-child",
  // nth-child()
  "nth-col",
  // nth-col()
  "nth-last-child",
  // nth-last-child()
  "nth-last-col",
  // nth-last-col()
  "nth-last-of-type",
  //nth-last-of-type()
  "nth-of-type",
  //nth-of-type()
  "only-child",
  "only-of-type",
  "optional",
  "out-of-range",
  "past",
  "placeholder-shown",
  "read-only",
  "read-write",
  "required",
  "right",
  "root",
  "scope",
  "target",
  "target-within",
  "user-invalid",
  "valid",
  "visited",
  "where"
  // where()
].sort().reverse();
var PSEUDO_ELEMENTS = [
  "after",
  "backdrop",
  "before",
  "cue",
  "cue-region",
  "first-letter",
  "first-line",
  "grammar-error",
  "marker",
  "part",
  "placeholder",
  "selection",
  "slotted",
  "spelling-error"
].sort().reverse();
var ATTRIBUTES = [
  "accent-color",
  "align-content",
  "align-items",
  "align-self",
  "alignment-baseline",
  "all",
  "anchor-name",
  "animation",
  "animation-composition",
  "animation-delay",
  "animation-direction",
  "animation-duration",
  "animation-fill-mode",
  "animation-iteration-count",
  "animation-name",
  "animation-play-state",
  "animation-range",
  "animation-range-end",
  "animation-range-start",
  "animation-timeline",
  "animation-timing-function",
  "appearance",
  "aspect-ratio",
  "backdrop-filter",
  "backface-visibility",
  "background",
  "background-attachment",
  "background-blend-mode",
  "background-clip",
  "background-color",
  "background-image",
  "background-origin",
  "background-position",
  "background-position-x",
  "background-position-y",
  "background-repeat",
  "background-size",
  "baseline-shift",
  "block-size",
  "border",
  "border-block",
  "border-block-color",
  "border-block-end",
  "border-block-end-color",
  "border-block-end-style",
  "border-block-end-width",
  "border-block-start",
  "border-block-start-color",
  "border-block-start-style",
  "border-block-start-width",
  "border-block-style",
  "border-block-width",
  "border-bottom",
  "border-bottom-color",
  "border-bottom-left-radius",
  "border-bottom-right-radius",
  "border-bottom-style",
  "border-bottom-width",
  "border-collapse",
  "border-color",
  "border-end-end-radius",
  "border-end-start-radius",
  "border-image",
  "border-image-outset",
  "border-image-repeat",
  "border-image-slice",
  "border-image-source",
  "border-image-width",
  "border-inline",
  "border-inline-color",
  "border-inline-end",
  "border-inline-end-color",
  "border-inline-end-style",
  "border-inline-end-width",
  "border-inline-start",
  "border-inline-start-color",
  "border-inline-start-style",
  "border-inline-start-width",
  "border-inline-style",
  "border-inline-width",
  "border-left",
  "border-left-color",
  "border-left-style",
  "border-left-width",
  "border-radius",
  "border-right",
  "border-right-color",
  "border-right-style",
  "border-right-width",
  "border-spacing",
  "border-start-end-radius",
  "border-start-start-radius",
  "border-style",
  "border-top",
  "border-top-color",
  "border-top-left-radius",
  "border-top-right-radius",
  "border-top-style",
  "border-top-width",
  "border-width",
  "bottom",
  "box-align",
  "box-decoration-break",
  "box-direction",
  "box-flex",
  "box-flex-group",
  "box-lines",
  "box-ordinal-group",
  "box-orient",
  "box-pack",
  "box-shadow",
  "box-sizing",
  "break-after",
  "break-before",
  "break-inside",
  "caption-side",
  "caret-color",
  "clear",
  "clip",
  "clip-path",
  "clip-rule",
  "color",
  "color-interpolation",
  "color-interpolation-filters",
  "color-profile",
  "color-rendering",
  "color-scheme",
  "column-count",
  "column-fill",
  "column-gap",
  "column-rule",
  "column-rule-color",
  "column-rule-style",
  "column-rule-width",
  "column-span",
  "column-width",
  "columns",
  "contain",
  "contain-intrinsic-block-size",
  "contain-intrinsic-height",
  "contain-intrinsic-inline-size",
  "contain-intrinsic-size",
  "contain-intrinsic-width",
  "container",
  "container-name",
  "container-type",
  "content",
  "content-visibility",
  "counter-increment",
  "counter-reset",
  "counter-set",
  "cue",
  "cue-after",
  "cue-before",
  "cursor",
  "cx",
  "cy",
  "direction",
  "display",
  "dominant-baseline",
  "empty-cells",
  "enable-background",
  "field-sizing",
  "fill",
  "fill-opacity",
  "fill-rule",
  "filter",
  "flex",
  "flex-basis",
  "flex-direction",
  "flex-flow",
  "flex-grow",
  "flex-shrink",
  "flex-wrap",
  "float",
  "flood-color",
  "flood-opacity",
  "flow",
  "font",
  "font-display",
  "font-family",
  "font-feature-settings",
  "font-kerning",
  "font-language-override",
  "font-optical-sizing",
  "font-palette",
  "font-size",
  "font-size-adjust",
  "font-smooth",
  "font-smoothing",
  "font-stretch",
  "font-style",
  "font-synthesis",
  "font-synthesis-position",
  "font-synthesis-small-caps",
  "font-synthesis-style",
  "font-synthesis-weight",
  "font-variant",
  "font-variant-alternates",
  "font-variant-caps",
  "font-variant-east-asian",
  "font-variant-emoji",
  "font-variant-ligatures",
  "font-variant-numeric",
  "font-variant-position",
  "font-variation-settings",
  "font-weight",
  "forced-color-adjust",
  "gap",
  "glyph-orientation-horizontal",
  "glyph-orientation-vertical",
  "grid",
  "grid-area",
  "grid-auto-columns",
  "grid-auto-flow",
  "grid-auto-rows",
  "grid-column",
  "grid-column-end",
  "grid-column-start",
  "grid-gap",
  "grid-row",
  "grid-row-end",
  "grid-row-start",
  "grid-template",
  "grid-template-areas",
  "grid-template-columns",
  "grid-template-rows",
  "hanging-punctuation",
  "height",
  "hyphenate-character",
  "hyphenate-limit-chars",
  "hyphens",
  "icon",
  "image-orientation",
  "image-rendering",
  "image-resolution",
  "ime-mode",
  "initial-letter",
  "initial-letter-align",
  "inline-size",
  "inset",
  "inset-area",
  "inset-block",
  "inset-block-end",
  "inset-block-start",
  "inset-inline",
  "inset-inline-end",
  "inset-inline-start",
  "isolation",
  "justify-content",
  "justify-items",
  "justify-self",
  "kerning",
  "left",
  "letter-spacing",
  "lighting-color",
  "line-break",
  "line-height",
  "line-height-step",
  "list-style",
  "list-style-image",
  "list-style-position",
  "list-style-type",
  "margin",
  "margin-block",
  "margin-block-end",
  "margin-block-start",
  "margin-bottom",
  "margin-inline",
  "margin-inline-end",
  "margin-inline-start",
  "margin-left",
  "margin-right",
  "margin-top",
  "margin-trim",
  "marker",
  "marker-end",
  "marker-mid",
  "marker-start",
  "marks",
  "mask",
  "mask-border",
  "mask-border-mode",
  "mask-border-outset",
  "mask-border-repeat",
  "mask-border-slice",
  "mask-border-source",
  "mask-border-width",
  "mask-clip",
  "mask-composite",
  "mask-image",
  "mask-mode",
  "mask-origin",
  "mask-position",
  "mask-repeat",
  "mask-size",
  "mask-type",
  "masonry-auto-flow",
  "math-depth",
  "math-shift",
  "math-style",
  "max-block-size",
  "max-height",
  "max-inline-size",
  "max-width",
  "min-block-size",
  "min-height",
  "min-inline-size",
  "min-width",
  "mix-blend-mode",
  "nav-down",
  "nav-index",
  "nav-left",
  "nav-right",
  "nav-up",
  "none",
  "normal",
  "object-fit",
  "object-position",
  "offset",
  "offset-anchor",
  "offset-distance",
  "offset-path",
  "offset-position",
  "offset-rotate",
  "opacity",
  "order",
  "orphans",
  "outline",
  "outline-color",
  "outline-offset",
  "outline-style",
  "outline-width",
  "overflow",
  "overflow-anchor",
  "overflow-block",
  "overflow-clip-margin",
  "overflow-inline",
  "overflow-wrap",
  "overflow-x",
  "overflow-y",
  "overlay",
  "overscroll-behavior",
  "overscroll-behavior-block",
  "overscroll-behavior-inline",
  "overscroll-behavior-x",
  "overscroll-behavior-y",
  "padding",
  "padding-block",
  "padding-block-end",
  "padding-block-start",
  "padding-bottom",
  "padding-inline",
  "padding-inline-end",
  "padding-inline-start",
  "padding-left",
  "padding-right",
  "padding-top",
  "page",
  "page-break-after",
  "page-break-before",
  "page-break-inside",
  "paint-order",
  "pause",
  "pause-after",
  "pause-before",
  "perspective",
  "perspective-origin",
  "place-content",
  "place-items",
  "place-self",
  "pointer-events",
  "position",
  "position-anchor",
  "position-visibility",
  "print-color-adjust",
  "quotes",
  "r",
  "resize",
  "rest",
  "rest-after",
  "rest-before",
  "right",
  "rotate",
  "row-gap",
  "ruby-align",
  "ruby-position",
  "scale",
  "scroll-behavior",
  "scroll-margin",
  "scroll-margin-block",
  "scroll-margin-block-end",
  "scroll-margin-block-start",
  "scroll-margin-bottom",
  "scroll-margin-inline",
  "scroll-margin-inline-end",
  "scroll-margin-inline-start",
  "scroll-margin-left",
  "scroll-margin-right",
  "scroll-margin-top",
  "scroll-padding",
  "scroll-padding-block",
  "scroll-padding-block-end",
  "scroll-padding-block-start",
  "scroll-padding-bottom",
  "scroll-padding-inline",
  "scroll-padding-inline-end",
  "scroll-padding-inline-start",
  "scroll-padding-left",
  "scroll-padding-right",
  "scroll-padding-top",
  "scroll-snap-align",
  "scroll-snap-stop",
  "scroll-snap-type",
  "scroll-timeline",
  "scroll-timeline-axis",
  "scroll-timeline-name",
  "scrollbar-color",
  "scrollbar-gutter",
  "scrollbar-width",
  "shape-image-threshold",
  "shape-margin",
  "shape-outside",
  "shape-rendering",
  "speak",
  "speak-as",
  "src",
  // @font-face
  "stop-color",
  "stop-opacity",
  "stroke",
  "stroke-dasharray",
  "stroke-dashoffset",
  "stroke-linecap",
  "stroke-linejoin",
  "stroke-miterlimit",
  "stroke-opacity",
  "stroke-width",
  "tab-size",
  "table-layout",
  "text-align",
  "text-align-all",
  "text-align-last",
  "text-anchor",
  "text-combine-upright",
  "text-decoration",
  "text-decoration-color",
  "text-decoration-line",
  "text-decoration-skip",
  "text-decoration-skip-ink",
  "text-decoration-style",
  "text-decoration-thickness",
  "text-emphasis",
  "text-emphasis-color",
  "text-emphasis-position",
  "text-emphasis-style",
  "text-indent",
  "text-justify",
  "text-orientation",
  "text-overflow",
  "text-rendering",
  "text-shadow",
  "text-size-adjust",
  "text-transform",
  "text-underline-offset",
  "text-underline-position",
  "text-wrap",
  "text-wrap-mode",
  "text-wrap-style",
  "timeline-scope",
  "top",
  "touch-action",
  "transform",
  "transform-box",
  "transform-origin",
  "transform-style",
  "transition",
  "transition-behavior",
  "transition-delay",
  "transition-duration",
  "transition-property",
  "transition-timing-function",
  "translate",
  "unicode-bidi",
  "user-modify",
  "user-select",
  "vector-effect",
  "vertical-align",
  "view-timeline",
  "view-timeline-axis",
  "view-timeline-inset",
  "view-timeline-name",
  "view-transition-name",
  "visibility",
  "voice-balance",
  "voice-duration",
  "voice-family",
  "voice-pitch",
  "voice-range",
  "voice-rate",
  "voice-stress",
  "voice-volume",
  "white-space",
  "white-space-collapse",
  "widows",
  "width",
  "will-change",
  "word-break",
  "word-spacing",
  "word-wrap",
  "writing-mode",
  "x",
  "y",
  "z-index",
  "zoom"
].sort().reverse();
function css(hljs5) {
  const regex = hljs5.regex;
  const modes = MODES(hljs5);
  const VENDOR_PREFIX = { begin: /-(webkit|moz|ms|o)-(?=[a-z])/ };
  const AT_MODIFIERS = "and or not only";
  const AT_PROPERTY_RE = /@-?\w[\w]*(-\w+)*/;
  const IDENT_RE3 = "[a-zA-Z-][a-zA-Z0-9_-]*";
  const STRINGS = [
    hljs5.APOS_STRING_MODE,
    hljs5.QUOTE_STRING_MODE
  ];
  return {
    name: "CSS",
    case_insensitive: true,
    illegal: /[=|'\$]/,
    keywords: { keyframePosition: "from to" },
    classNameAliases: {
      // for visual continuity with `tag {}` and because we
      // don't have a great class for this?
      keyframePosition: "selector-tag"
    },
    contains: [
      modes.BLOCK_COMMENT,
      VENDOR_PREFIX,
      // to recognize keyframe 40% etc which are outside the scope of our
      // attribute value mode
      modes.CSS_NUMBER_MODE,
      {
        className: "selector-id",
        begin: /#[A-Za-z0-9_-]+/,
        relevance: 0
      },
      {
        className: "selector-class",
        begin: "\\." + IDENT_RE3,
        relevance: 0
      },
      modes.ATTRIBUTE_SELECTOR_MODE,
      {
        className: "selector-pseudo",
        variants: [
          { begin: ":(" + PSEUDO_CLASSES.join("|") + ")" },
          { begin: ":(:)?(" + PSEUDO_ELEMENTS.join("|") + ")" }
        ]
      },
      // we may actually need this (12/2020)
      // { // pseudo-selector params
      //   begin: /\(/,
      //   end: /\)/,
      //   contains: [ hljs.CSS_NUMBER_MODE ]
      // },
      modes.CSS_VARIABLE,
      {
        className: "attribute",
        begin: "\\b(" + ATTRIBUTES.join("|") + ")\\b"
      },
      // attribute values
      {
        begin: /:/,
        end: /[;}{]/,
        contains: [
          modes.BLOCK_COMMENT,
          modes.HEXCOLOR,
          modes.IMPORTANT,
          modes.CSS_NUMBER_MODE,
          ...STRINGS,
          // needed to highlight these as strings and to avoid issues with
          // illegal characters that might be inside urls that would tigger the
          // languages illegal stack
          {
            begin: /(url|data-uri)\(/,
            end: /\)/,
            relevance: 0,
            // from keywords
            keywords: { built_in: "url data-uri" },
            contains: [
              ...STRINGS,
              {
                className: "string",
                // any character other than `)` as in `url()` will be the start
                // of a string, which ends with `)` (from the parent mode)
                begin: /[^)]/,
                endsWithParent: true,
                excludeEnd: true
              }
            ]
          },
          modes.FUNCTION_DISPATCH
        ]
      },
      {
        begin: regex.lookahead(/@/),
        end: "[{;]",
        relevance: 0,
        illegal: /:/,
        // break on Less variables @var: ...
        contains: [
          {
            className: "keyword",
            begin: AT_PROPERTY_RE
          },
          {
            begin: /\s/,
            endsWithParent: true,
            excludeEnd: true,
            relevance: 0,
            keywords: {
              $pattern: /[a-z-]+/,
              keyword: AT_MODIFIERS,
              attribute: MEDIA_FEATURES.join(" ")
            },
            contains: [
              {
                begin: /[a-z-]+(?=:)/,
                className: "attribute"
              },
              ...STRINGS,
              modes.CSS_NUMBER_MODE
            ]
          }
        ]
      },
      {
        className: "selector-tag",
        begin: "\\b(" + TAGS.join("|") + ")\\b"
      }
    ]
  };
}

// ../mini-lit/node_modules/highlight.js/es/languages/javascript.js
init_process_shim();
var IDENT_RE = "[A-Za-z$_][0-9A-Za-z$_]*";
var KEYWORDS = [
  "as",
  // for exports
  "in",
  "of",
  "if",
  "for",
  "while",
  "finally",
  "var",
  "new",
  "function",
  "do",
  "return",
  "void",
  "else",
  "break",
  "catch",
  "instanceof",
  "with",
  "throw",
  "case",
  "default",
  "try",
  "switch",
  "continue",
  "typeof",
  "delete",
  "let",
  "yield",
  "const",
  "class",
  // JS handles these with a special rule
  // "get",
  // "set",
  "debugger",
  "async",
  "await",
  "static",
  "import",
  "from",
  "export",
  "extends",
  // It's reached stage 3, which is "recommended for implementation":
  "using"
];
var LITERALS = [
  "true",
  "false",
  "null",
  "undefined",
  "NaN",
  "Infinity"
];
var TYPES = [
  // Fundamental objects
  "Object",
  "Function",
  "Boolean",
  "Symbol",
  // numbers and dates
  "Math",
  "Date",
  "Number",
  "BigInt",
  // text
  "String",
  "RegExp",
  // Indexed collections
  "Array",
  "Float32Array",
  "Float64Array",
  "Int8Array",
  "Uint8Array",
  "Uint8ClampedArray",
  "Int16Array",
  "Int32Array",
  "Uint16Array",
  "Uint32Array",
  "BigInt64Array",
  "BigUint64Array",
  // Keyed collections
  "Set",
  "Map",
  "WeakSet",
  "WeakMap",
  // Structured data
  "ArrayBuffer",
  "SharedArrayBuffer",
  "Atomics",
  "DataView",
  "JSON",
  // Control abstraction objects
  "Promise",
  "Generator",
  "GeneratorFunction",
  "AsyncFunction",
  // Reflection
  "Reflect",
  "Proxy",
  // Internationalization
  "Intl",
  // WebAssembly
  "WebAssembly"
];
var ERROR_TYPES = [
  "Error",
  "EvalError",
  "InternalError",
  "RangeError",
  "ReferenceError",
  "SyntaxError",
  "TypeError",
  "URIError"
];
var BUILT_IN_GLOBALS = [
  "setInterval",
  "setTimeout",
  "clearInterval",
  "clearTimeout",
  "require",
  "exports",
  "eval",
  "isFinite",
  "isNaN",
  "parseFloat",
  "parseInt",
  "decodeURI",
  "decodeURIComponent",
  "encodeURI",
  "encodeURIComponent",
  "escape",
  "unescape"
];
var BUILT_IN_VARIABLES = [
  "arguments",
  "this",
  "super",
  "console",
  "window",
  "document",
  "localStorage",
  "sessionStorage",
  "module",
  "global"
  // Node.js
];
var BUILT_INS = [].concat(
  BUILT_IN_GLOBALS,
  TYPES,
  ERROR_TYPES
);
function javascript(hljs5) {
  const regex = hljs5.regex;
  const hasClosingTag = (match2, { after }) => {
    const tag = "</" + match2[0].slice(1);
    const pos = match2.input.indexOf(tag, after);
    return pos !== -1;
  };
  const IDENT_RE$1 = IDENT_RE;
  const FRAGMENT = {
    begin: "<>",
    end: "</>"
  };
  const XML_SELF_CLOSING = /<[A-Za-z0-9\\._:-]+\s*\/>/;
  const XML_TAG = {
    begin: /<[A-Za-z0-9\\._:-]+/,
    end: /\/[A-Za-z0-9\\._:-]+>|\/>/,
    /**
     * @param {RegExpMatchArray} match
     * @param {CallbackResponse} response
     */
    isTrulyOpeningTag: (match2, response) => {
      const afterMatchIndex = match2[0].length + match2.index;
      const nextChar = match2.input[afterMatchIndex];
      if (
        // HTML should not include another raw `<` inside a tag
        // nested type?
        // `<Array<Array<number>>`, etc.
        nextChar === "<" || // the , gives away that this is not HTML
        // `<T, A extends keyof T, V>`
        nextChar === ","
      ) {
        response.ignoreMatch();
        return;
      }
      if (nextChar === ">") {
        if (!hasClosingTag(match2, { after: afterMatchIndex })) {
          response.ignoreMatch();
        }
      }
      let m4;
      const afterMatch = match2.input.substring(afterMatchIndex);
      if (m4 = afterMatch.match(/^\s*=/)) {
        response.ignoreMatch();
        return;
      }
      if (m4 = afterMatch.match(/^\s+extends\s+/)) {
        if (m4.index === 0) {
          response.ignoreMatch();
          return;
        }
      }
    }
  };
  const KEYWORDS$1 = {
    $pattern: IDENT_RE,
    keyword: KEYWORDS,
    literal: LITERALS,
    built_in: BUILT_INS,
    "variable.language": BUILT_IN_VARIABLES
  };
  const decimalDigits = "[0-9](_?[0-9])*";
  const frac = `\\.(${decimalDigits})`;
  const decimalInteger = `0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*`;
  const NUMBER = {
    className: "number",
    variants: [
      // DecimalLiteral
      { begin: `(\\b(${decimalInteger})((${frac})|\\.)?|(${frac}))[eE][+-]?(${decimalDigits})\\b` },
      { begin: `\\b(${decimalInteger})\\b((${frac})\\b|\\.)?|(${frac})\\b` },
      // DecimalBigIntegerLiteral
      { begin: `\\b(0|[1-9](_?[0-9])*)n\\b` },
      // NonDecimalIntegerLiteral
      { begin: "\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b" },
      { begin: "\\b0[bB][0-1](_?[0-1])*n?\\b" },
      { begin: "\\b0[oO][0-7](_?[0-7])*n?\\b" },
      // LegacyOctalIntegerLiteral (does not include underscore separators)
      // https://tc39.es/ecma262/#sec-additional-syntax-numeric-literals
      { begin: "\\b0[0-7]+n?\\b" }
    ],
    relevance: 0
  };
  const SUBST = {
    className: "subst",
    begin: "\\$\\{",
    end: "\\}",
    keywords: KEYWORDS$1,
    contains: []
    // defined later
  };
  const HTML_TEMPLATE = {
    begin: ".?html`",
    end: "",
    starts: {
      end: "`",
      returnEnd: false,
      contains: [
        hljs5.BACKSLASH_ESCAPE,
        SUBST
      ],
      subLanguage: "xml"
    }
  };
  const CSS_TEMPLATE = {
    begin: ".?css`",
    end: "",
    starts: {
      end: "`",
      returnEnd: false,
      contains: [
        hljs5.BACKSLASH_ESCAPE,
        SUBST
      ],
      subLanguage: "css"
    }
  };
  const GRAPHQL_TEMPLATE = {
    begin: ".?gql`",
    end: "",
    starts: {
      end: "`",
      returnEnd: false,
      contains: [
        hljs5.BACKSLASH_ESCAPE,
        SUBST
      ],
      subLanguage: "graphql"
    }
  };
  const TEMPLATE_STRING = {
    className: "string",
    begin: "`",
    end: "`",
    contains: [
      hljs5.BACKSLASH_ESCAPE,
      SUBST
    ]
  };
  const JSDOC_COMMENT = hljs5.COMMENT(
    /\/\*\*(?!\/)/,
    "\\*/",
    {
      relevance: 0,
      contains: [
        {
          begin: "(?=@[A-Za-z]+)",
          relevance: 0,
          contains: [
            {
              className: "doctag",
              begin: "@[A-Za-z]+"
            },
            {
              className: "type",
              begin: "\\{",
              end: "\\}",
              excludeEnd: true,
              excludeBegin: true,
              relevance: 0
            },
            {
              className: "variable",
              begin: IDENT_RE$1 + "(?=\\s*(-)|$)",
              endsParent: true,
              relevance: 0
            },
            // eat spaces (not newlines) so we can find
            // types or variables
            {
              begin: /(?=[^\n])\s/,
              relevance: 0
            }
          ]
        }
      ]
    }
  );
  const COMMENT = {
    className: "comment",
    variants: [
      JSDOC_COMMENT,
      hljs5.C_BLOCK_COMMENT_MODE,
      hljs5.C_LINE_COMMENT_MODE
    ]
  };
  const SUBST_INTERNALS = [
    hljs5.APOS_STRING_MODE,
    hljs5.QUOTE_STRING_MODE,
    HTML_TEMPLATE,
    CSS_TEMPLATE,
    GRAPHQL_TEMPLATE,
    TEMPLATE_STRING,
    // Skip numbers when they are part of a variable name
    { match: /\$\d+/ },
    NUMBER
    // This is intentional:
    // See https://github.com/highlightjs/highlight.js/issues/3288
    // hljs.REGEXP_MODE
  ];
  SUBST.contains = SUBST_INTERNALS.concat({
    // we need to pair up {} inside our subst to prevent
    // it from ending too early by matching another }
    begin: /\{/,
    end: /\}/,
    keywords: KEYWORDS$1,
    contains: [
      "self"
    ].concat(SUBST_INTERNALS)
  });
  const SUBST_AND_COMMENTS = [].concat(COMMENT, SUBST.contains);
  const PARAMS_CONTAINS = SUBST_AND_COMMENTS.concat([
    // eat recursive parens in sub expressions
    {
      begin: /(\s*)\(/,
      end: /\)/,
      keywords: KEYWORDS$1,
      contains: ["self"].concat(SUBST_AND_COMMENTS)
    }
  ]);
  const PARAMS = {
    className: "params",
    // convert this to negative lookbehind in v12
    begin: /(\s*)\(/,
    // to match the parms with
    end: /\)/,
    excludeBegin: true,
    excludeEnd: true,
    keywords: KEYWORDS$1,
    contains: PARAMS_CONTAINS
  };
  const CLASS_OR_EXTENDS = {
    variants: [
      // class Car extends vehicle
      {
        match: [
          /class/,
          /\s+/,
          IDENT_RE$1,
          /\s+/,
          /extends/,
          /\s+/,
          regex.concat(IDENT_RE$1, "(", regex.concat(/\./, IDENT_RE$1), ")*")
        ],
        scope: {
          1: "keyword",
          3: "title.class",
          5: "keyword",
          7: "title.class.inherited"
        }
      },
      // class Car
      {
        match: [
          /class/,
          /\s+/,
          IDENT_RE$1
        ],
        scope: {
          1: "keyword",
          3: "title.class"
        }
      }
    ]
  };
  const CLASS_REFERENCE = {
    relevance: 0,
    match: regex.either(
      // Hard coded exceptions
      /\bJSON/,
      // Float32Array, OutT
      /\b[A-Z][a-z]+([A-Z][a-z]*|\d)*/,
      // CSSFactory, CSSFactoryT
      /\b[A-Z]{2,}([A-Z][a-z]+|\d)+([A-Z][a-z]*)*/,
      // FPs, FPsT
      /\b[A-Z]{2,}[a-z]+([A-Z][a-z]+|\d)*([A-Z][a-z]*)*/
      // P
      // single letters are not highlighted
      // BLAH
      // this will be flagged as a UPPER_CASE_CONSTANT instead
    ),
    className: "title.class",
    keywords: {
      _: [
        // se we still get relevance credit for JS library classes
        ...TYPES,
        ...ERROR_TYPES
      ]
    }
  };
  const USE_STRICT = {
    label: "use_strict",
    className: "meta",
    relevance: 10,
    begin: /^\s*['"]use (strict|asm)['"]/
  };
  const FUNCTION_DEFINITION = {
    variants: [
      {
        match: [
          /function/,
          /\s+/,
          IDENT_RE$1,
          /(?=\s*\()/
        ]
      },
      // anonymous function
      {
        match: [
          /function/,
          /\s*(?=\()/
        ]
      }
    ],
    className: {
      1: "keyword",
      3: "title.function"
    },
    label: "func.def",
    contains: [PARAMS],
    illegal: /%/
  };
  const UPPER_CASE_CONSTANT = {
    relevance: 0,
    match: /\b[A-Z][A-Z_0-9]+\b/,
    className: "variable.constant"
  };
  function noneOf(list) {
    return regex.concat("(?!", list.join("|"), ")");
  }
  const FUNCTION_CALL = {
    match: regex.concat(
      /\b/,
      noneOf([
        ...BUILT_IN_GLOBALS,
        "super",
        "import"
      ].map((x2) => `${x2}\\s*\\(`)),
      IDENT_RE$1,
      regex.lookahead(/\s*\(/)
    ),
    className: "title.function",
    relevance: 0
  };
  const PROPERTY_ACCESS = {
    begin: regex.concat(/\./, regex.lookahead(
      regex.concat(IDENT_RE$1, /(?![0-9A-Za-z$_(])/)
    )),
    end: IDENT_RE$1,
    excludeBegin: true,
    keywords: "prototype",
    className: "property",
    relevance: 0
  };
  const GETTER_OR_SETTER = {
    match: [
      /get|set/,
      /\s+/,
      IDENT_RE$1,
      /(?=\()/
    ],
    className: {
      1: "keyword",
      3: "title.function"
    },
    contains: [
      {
        // eat to avoid empty params
        begin: /\(\)/
      },
      PARAMS
    ]
  };
  const FUNC_LEAD_IN_RE = "(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|" + hljs5.UNDERSCORE_IDENT_RE + ")\\s*=>";
  const FUNCTION_VARIABLE = {
    match: [
      /const|var|let/,
      /\s+/,
      IDENT_RE$1,
      /\s*/,
      /=\s*/,
      /(async\s*)?/,
      // async is optional
      regex.lookahead(FUNC_LEAD_IN_RE)
    ],
    keywords: "async",
    className: {
      1: "keyword",
      3: "title.function"
    },
    contains: [
      PARAMS
    ]
  };
  return {
    name: "JavaScript",
    aliases: ["js", "jsx", "mjs", "cjs"],
    keywords: KEYWORDS$1,
    // this will be extended by TypeScript
    exports: { PARAMS_CONTAINS, CLASS_REFERENCE },
    illegal: /#(?![$_A-z])/,
    contains: [
      hljs5.SHEBANG({
        label: "shebang",
        binary: "node",
        relevance: 5
      }),
      USE_STRICT,
      hljs5.APOS_STRING_MODE,
      hljs5.QUOTE_STRING_MODE,
      HTML_TEMPLATE,
      CSS_TEMPLATE,
      GRAPHQL_TEMPLATE,
      TEMPLATE_STRING,
      COMMENT,
      // Skip numbers when they are part of a variable name
      { match: /\$\d+/ },
      NUMBER,
      CLASS_REFERENCE,
      {
        scope: "attr",
        match: IDENT_RE$1 + regex.lookahead(":"),
        relevance: 0
      },
      FUNCTION_VARIABLE,
      {
        // "value" container
        begin: "(" + hljs5.RE_STARTERS_RE + "|\\b(case|return|throw)\\b)\\s*",
        keywords: "return throw case",
        relevance: 0,
        contains: [
          COMMENT,
          hljs5.REGEXP_MODE,
          {
            className: "function",
            // we have to count the parens to make sure we actually have the
            // correct bounding ( ) before the =>.  There could be any number of
            // sub-expressions inside also surrounded by parens.
            begin: FUNC_LEAD_IN_RE,
            returnBegin: true,
            end: "\\s*=>",
            contains: [
              {
                className: "params",
                variants: [
                  {
                    begin: hljs5.UNDERSCORE_IDENT_RE,
                    relevance: 0
                  },
                  {
                    className: null,
                    begin: /\(\s*\)/,
                    skip: true
                  },
                  {
                    begin: /(\s*)\(/,
                    end: /\)/,
                    excludeBegin: true,
                    excludeEnd: true,
                    keywords: KEYWORDS$1,
                    contains: PARAMS_CONTAINS
                  }
                ]
              }
            ]
          },
          {
            // could be a comma delimited list of params to a function call
            begin: /,/,
            relevance: 0
          },
          {
            match: /\s+/,
            relevance: 0
          },
          {
            // JSX
            variants: [
              { begin: FRAGMENT.begin, end: FRAGMENT.end },
              { match: XML_SELF_CLOSING },
              {
                begin: XML_TAG.begin,
                // we carefully check the opening tag to see if it truly
                // is a tag and not a false positive
                "on:begin": XML_TAG.isTrulyOpeningTag,
                end: XML_TAG.end
              }
            ],
            subLanguage: "xml",
            contains: [
              {
                begin: XML_TAG.begin,
                end: XML_TAG.end,
                skip: true,
                contains: ["self"]
              }
            ]
          }
        ]
      },
      FUNCTION_DEFINITION,
      {
        // prevent this from getting swallowed up by function
        // since they appear "function like"
        beginKeywords: "while if switch catch for"
      },
      {
        // we have to count the parens to make sure we actually have the correct
        // bounding ( ).  There could be any number of sub-expressions inside
        // also surrounded by parens.
        begin: "\\b(?!function)" + hljs5.UNDERSCORE_IDENT_RE + "\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",
        // end parens
        returnBegin: true,
        label: "func.def",
        contains: [
          PARAMS,
          hljs5.inherit(hljs5.TITLE_MODE, { begin: IDENT_RE$1, className: "title.function" })
        ]
      },
      // catch ... so it won't trigger the property rule below
      {
        match: /\.\.\./,
        relevance: 0
      },
      PROPERTY_ACCESS,
      // hack: prevents detection of keywords in some circumstances
      // .keyword()
      // $keyword = x
      {
        match: "\\$" + IDENT_RE$1,
        relevance: 0
      },
      {
        match: [/\bconstructor(?=\s*\()/],
        className: { 1: "title.function" },
        contains: [PARAMS]
      },
      FUNCTION_CALL,
      UPPER_CASE_CONSTANT,
      CLASS_OR_EXTENDS,
      GETTER_OR_SETTER,
      {
        match: /\$[(.]/
        // relevance booster for a pattern common to JS libs: `$(something)` and `$.something`
      }
    ]
  };
}

// ../mini-lit/node_modules/highlight.js/es/languages/json.js
init_process_shim();
function json(hljs5) {
  const ATTRIBUTE = {
    className: "attr",
    begin: /"(\\.|[^\\"\r\n])*"(?=\s*:)/,
    relevance: 1.01
  };
  const PUNCTUATION = {
    match: /[{}[\],:]/,
    className: "punctuation",
    relevance: 0
  };
  const LITERALS3 = [
    "true",
    "false",
    "null"
  ];
  const LITERALS_MODE = {
    scope: "literal",
    beginKeywords: LITERALS3.join(" ")
  };
  return {
    name: "JSON",
    aliases: ["jsonc"],
    keywords: {
      literal: LITERALS3
    },
    contains: [
      ATTRIBUTE,
      PUNCTUATION,
      hljs5.QUOTE_STRING_MODE,
      LITERALS_MODE,
      hljs5.C_NUMBER_MODE,
      hljs5.C_LINE_COMMENT_MODE,
      hljs5.C_BLOCK_COMMENT_MODE
    ],
    illegal: "\\S"
  };
}

// ../mini-lit/node_modules/highlight.js/es/languages/python.js
init_process_shim();
function python(hljs5) {
  const regex = hljs5.regex;
  const IDENT_RE3 = new RegExp("[\\p{XID_Start}_]\\p{XID_Continue}*", "u");
  const RESERVED_WORDS = [
    "and",
    "as",
    "assert",
    "async",
    "await",
    "break",
    "case",
    "class",
    "continue",
    "def",
    "del",
    "elif",
    "else",
    "except",
    "finally",
    "for",
    "from",
    "global",
    "if",
    "import",
    "in",
    "is",
    "lambda",
    "match",
    "nonlocal|10",
    "not",
    "or",
    "pass",
    "raise",
    "return",
    "try",
    "while",
    "with",
    "yield"
  ];
  const BUILT_INS3 = [
    "__import__",
    "abs",
    "all",
    "any",
    "ascii",
    "bin",
    "bool",
    "breakpoint",
    "bytearray",
    "bytes",
    "callable",
    "chr",
    "classmethod",
    "compile",
    "complex",
    "delattr",
    "dict",
    "dir",
    "divmod",
    "enumerate",
    "eval",
    "exec",
    "filter",
    "float",
    "format",
    "frozenset",
    "getattr",
    "globals",
    "hasattr",
    "hash",
    "help",
    "hex",
    "id",
    "input",
    "int",
    "isinstance",
    "issubclass",
    "iter",
    "len",
    "list",
    "locals",
    "map",
    "max",
    "memoryview",
    "min",
    "next",
    "object",
    "oct",
    "open",
    "ord",
    "pow",
    "print",
    "property",
    "range",
    "repr",
    "reversed",
    "round",
    "set",
    "setattr",
    "slice",
    "sorted",
    "staticmethod",
    "str",
    "sum",
    "super",
    "tuple",
    "type",
    "vars",
    "zip"
  ];
  const LITERALS3 = [
    "__debug__",
    "Ellipsis",
    "False",
    "None",
    "NotImplemented",
    "True"
  ];
  const TYPES3 = [
    "Any",
    "Callable",
    "Coroutine",
    "Dict",
    "List",
    "Literal",
    "Generic",
    "Optional",
    "Sequence",
    "Set",
    "Tuple",
    "Type",
    "Union"
  ];
  const KEYWORDS3 = {
    $pattern: /[A-Za-z]\w+|__\w+__/,
    keyword: RESERVED_WORDS,
    built_in: BUILT_INS3,
    literal: LITERALS3,
    type: TYPES3
  };
  const PROMPT = {
    className: "meta",
    begin: /^(>>>|\.\.\.) /
  };
  const SUBST = {
    className: "subst",
    begin: /\{/,
    end: /\}/,
    keywords: KEYWORDS3,
    illegal: /#/
  };
  const LITERAL_BRACKET = {
    begin: /\{\{/,
    relevance: 0
  };
  const STRING = {
    className: "string",
    contains: [hljs5.BACKSLASH_ESCAPE],
    variants: [
      {
        begin: /([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?'''/,
        end: /'''/,
        contains: [
          hljs5.BACKSLASH_ESCAPE,
          PROMPT
        ],
        relevance: 10
      },
      {
        begin: /([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?"""/,
        end: /"""/,
        contains: [
          hljs5.BACKSLASH_ESCAPE,
          PROMPT
        ],
        relevance: 10
      },
      {
        begin: /([fF][rR]|[rR][fF]|[fF])'''/,
        end: /'''/,
        contains: [
          hljs5.BACKSLASH_ESCAPE,
          PROMPT,
          LITERAL_BRACKET,
          SUBST
        ]
      },
      {
        begin: /([fF][rR]|[rR][fF]|[fF])"""/,
        end: /"""/,
        contains: [
          hljs5.BACKSLASH_ESCAPE,
          PROMPT,
          LITERAL_BRACKET,
          SUBST
        ]
      },
      {
        begin: /([uU]|[rR])'/,
        end: /'/,
        relevance: 10
      },
      {
        begin: /([uU]|[rR])"/,
        end: /"/,
        relevance: 10
      },
      {
        begin: /([bB]|[bB][rR]|[rR][bB])'/,
        end: /'/
      },
      {
        begin: /([bB]|[bB][rR]|[rR][bB])"/,
        end: /"/
      },
      {
        begin: /([fF][rR]|[rR][fF]|[fF])'/,
        end: /'/,
        contains: [
          hljs5.BACKSLASH_ESCAPE,
          LITERAL_BRACKET,
          SUBST
        ]
      },
      {
        begin: /([fF][rR]|[rR][fF]|[fF])"/,
        end: /"/,
        contains: [
          hljs5.BACKSLASH_ESCAPE,
          LITERAL_BRACKET,
          SUBST
        ]
      },
      hljs5.APOS_STRING_MODE,
      hljs5.QUOTE_STRING_MODE
    ]
  };
  const digitpart = "[0-9](_?[0-9])*";
  const pointfloat = `(\\b(${digitpart}))?\\.(${digitpart})|\\b(${digitpart})\\.`;
  const lookahead = `\\b|${RESERVED_WORDS.join("|")}`;
  const NUMBER = {
    className: "number",
    relevance: 0,
    variants: [
      // exponentfloat, pointfloat
      // https://docs.python.org/3.9/reference/lexical_analysis.html#floating-point-literals
      // optionally imaginary
      // https://docs.python.org/3.9/reference/lexical_analysis.html#imaginary-literals
      // Note: no leading \b because floats can start with a decimal point
      // and we don't want to mishandle e.g. `fn(.5)`,
      // no trailing \b for pointfloat because it can end with a decimal point
      // and we don't want to mishandle e.g. `0..hex()`; this should be safe
      // because both MUST contain a decimal point and so cannot be confused with
      // the interior part of an identifier
      {
        begin: `(\\b(${digitpart})|(${pointfloat}))[eE][+-]?(${digitpart})[jJ]?(?=${lookahead})`
      },
      {
        begin: `(${pointfloat})[jJ]?`
      },
      // decinteger, bininteger, octinteger, hexinteger
      // https://docs.python.org/3.9/reference/lexical_analysis.html#integer-literals
      // optionally "long" in Python 2
      // https://docs.python.org/2.7/reference/lexical_analysis.html#integer-and-long-integer-literals
      // decinteger is optionally imaginary
      // https://docs.python.org/3.9/reference/lexical_analysis.html#imaginary-literals
      {
        begin: `\\b([1-9](_?[0-9])*|0+(_?0)*)[lLjJ]?(?=${lookahead})`
      },
      {
        begin: `\\b0[bB](_?[01])+[lL]?(?=${lookahead})`
      },
      {
        begin: `\\b0[oO](_?[0-7])+[lL]?(?=${lookahead})`
      },
      {
        begin: `\\b0[xX](_?[0-9a-fA-F])+[lL]?(?=${lookahead})`
      },
      // imagnumber (digitpart-based)
      // https://docs.python.org/3.9/reference/lexical_analysis.html#imaginary-literals
      {
        begin: `\\b(${digitpart})[jJ](?=${lookahead})`
      }
    ]
  };
  const COMMENT_TYPE = {
    className: "comment",
    begin: regex.lookahead(/# type:/),
    end: /$/,
    keywords: KEYWORDS3,
    contains: [
      {
        // prevent keywords from coloring `type`
        begin: /# type:/
      },
      // comment within a datatype comment includes no keywords
      {
        begin: /#/,
        end: /\b\B/,
        endsWithParent: true
      }
    ]
  };
  const PARAMS = {
    className: "params",
    variants: [
      // Exclude params in functions without params
      {
        className: "",
        begin: /\(\s*\)/,
        skip: true
      },
      {
        begin: /\(/,
        end: /\)/,
        excludeBegin: true,
        excludeEnd: true,
        keywords: KEYWORDS3,
        contains: [
          "self",
          PROMPT,
          NUMBER,
          STRING,
          hljs5.HASH_COMMENT_MODE
        ]
      }
    ]
  };
  SUBST.contains = [
    STRING,
    NUMBER,
    PROMPT
  ];
  return {
    name: "Python",
    aliases: [
      "py",
      "gyp",
      "ipython"
    ],
    unicodeRegex: true,
    keywords: KEYWORDS3,
    illegal: /(<\/|\?)|=>/,
    contains: [
      PROMPT,
      NUMBER,
      {
        // very common convention
        scope: "variable.language",
        match: /\bself\b/
      },
      {
        // eat "if" prior to string so that it won't accidentally be
        // labeled as an f-string
        beginKeywords: "if",
        relevance: 0
      },
      { match: /\bor\b/, scope: "keyword" },
      STRING,
      COMMENT_TYPE,
      hljs5.HASH_COMMENT_MODE,
      {
        match: [
          /\bdef/,
          /\s+/,
          IDENT_RE3
        ],
        scope: {
          1: "keyword",
          3: "title.function"
        },
        contains: [PARAMS]
      },
      {
        variants: [
          {
            match: [
              /\bclass/,
              /\s+/,
              IDENT_RE3,
              /\s*/,
              /\(\s*/,
              IDENT_RE3,
              /\s*\)/
            ]
          },
          {
            match: [
              /\bclass/,
              /\s+/,
              IDENT_RE3
            ]
          }
        ],
        scope: {
          1: "keyword",
          3: "title.class",
          6: "title.class.inherited"
        }
      },
      {
        className: "meta",
        begin: /^[\t ]*@/,
        end: /(?=#)|$/,
        contains: [
          NUMBER,
          PARAMS,
          STRING
        ]
      }
    ]
  };
}

// ../mini-lit/node_modules/highlight.js/es/languages/sql.js
init_process_shim();
function sql(hljs5) {
  const regex = hljs5.regex;
  const COMMENT_MODE = hljs5.COMMENT("--", "$");
  const STRING = {
    scope: "string",
    variants: [
      {
        begin: /'/,
        end: /'/,
        contains: [{ match: /''/ }]
      }
    ]
  };
  const QUOTED_IDENTIFIER = {
    begin: /"/,
    end: /"/,
    contains: [{ match: /""/ }]
  };
  const LITERALS3 = [
    "true",
    "false",
    // Not sure it's correct to call NULL literal, and clauses like IS [NOT] NULL look strange that way.
    // "null",
    "unknown"
  ];
  const MULTI_WORD_TYPES = [
    "double precision",
    "large object",
    "with timezone",
    "without timezone"
  ];
  const TYPES3 = [
    "bigint",
    "binary",
    "blob",
    "boolean",
    "char",
    "character",
    "clob",
    "date",
    "dec",
    "decfloat",
    "decimal",
    "float",
    "int",
    "integer",
    "interval",
    "nchar",
    "nclob",
    "national",
    "numeric",
    "real",
    "row",
    "smallint",
    "time",
    "timestamp",
    "varchar",
    "varying",
    // modifier (character varying)
    "varbinary"
  ];
  const NON_RESERVED_WORDS = [
    "add",
    "asc",
    "collation",
    "desc",
    "final",
    "first",
    "last",
    "view"
  ];
  const RESERVED_WORDS = [
    "abs",
    "acos",
    "all",
    "allocate",
    "alter",
    "and",
    "any",
    "are",
    "array",
    "array_agg",
    "array_max_cardinality",
    "as",
    "asensitive",
    "asin",
    "asymmetric",
    "at",
    "atan",
    "atomic",
    "authorization",
    "avg",
    "begin",
    "begin_frame",
    "begin_partition",
    "between",
    "bigint",
    "binary",
    "blob",
    "boolean",
    "both",
    "by",
    "call",
    "called",
    "cardinality",
    "cascaded",
    "case",
    "cast",
    "ceil",
    "ceiling",
    "char",
    "char_length",
    "character",
    "character_length",
    "check",
    "classifier",
    "clob",
    "close",
    "coalesce",
    "collate",
    "collect",
    "column",
    "commit",
    "condition",
    "connect",
    "constraint",
    "contains",
    "convert",
    "copy",
    "corr",
    "corresponding",
    "cos",
    "cosh",
    "count",
    "covar_pop",
    "covar_samp",
    "create",
    "cross",
    "cube",
    "cume_dist",
    "current",
    "current_catalog",
    "current_date",
    "current_default_transform_group",
    "current_path",
    "current_role",
    "current_row",
    "current_schema",
    "current_time",
    "current_timestamp",
    "current_path",
    "current_role",
    "current_transform_group_for_type",
    "current_user",
    "cursor",
    "cycle",
    "date",
    "day",
    "deallocate",
    "dec",
    "decimal",
    "decfloat",
    "declare",
    "default",
    "define",
    "delete",
    "dense_rank",
    "deref",
    "describe",
    "deterministic",
    "disconnect",
    "distinct",
    "double",
    "drop",
    "dynamic",
    "each",
    "element",
    "else",
    "empty",
    "end",
    "end_frame",
    "end_partition",
    "end-exec",
    "equals",
    "escape",
    "every",
    "except",
    "exec",
    "execute",
    "exists",
    "exp",
    "external",
    "extract",
    "false",
    "fetch",
    "filter",
    "first_value",
    "float",
    "floor",
    "for",
    "foreign",
    "frame_row",
    "free",
    "from",
    "full",
    "function",
    "fusion",
    "get",
    "global",
    "grant",
    "group",
    "grouping",
    "groups",
    "having",
    "hold",
    "hour",
    "identity",
    "in",
    "indicator",
    "initial",
    "inner",
    "inout",
    "insensitive",
    "insert",
    "int",
    "integer",
    "intersect",
    "intersection",
    "interval",
    "into",
    "is",
    "join",
    "json_array",
    "json_arrayagg",
    "json_exists",
    "json_object",
    "json_objectagg",
    "json_query",
    "json_table",
    "json_table_primitive",
    "json_value",
    "lag",
    "language",
    "large",
    "last_value",
    "lateral",
    "lead",
    "leading",
    "left",
    "like",
    "like_regex",
    "listagg",
    "ln",
    "local",
    "localtime",
    "localtimestamp",
    "log",
    "log10",
    "lower",
    "match",
    "match_number",
    "match_recognize",
    "matches",
    "max",
    "member",
    "merge",
    "method",
    "min",
    "minute",
    "mod",
    "modifies",
    "module",
    "month",
    "multiset",
    "national",
    "natural",
    "nchar",
    "nclob",
    "new",
    "no",
    "none",
    "normalize",
    "not",
    "nth_value",
    "ntile",
    "null",
    "nullif",
    "numeric",
    "octet_length",
    "occurrences_regex",
    "of",
    "offset",
    "old",
    "omit",
    "on",
    "one",
    "only",
    "open",
    "or",
    "order",
    "out",
    "outer",
    "over",
    "overlaps",
    "overlay",
    "parameter",
    "partition",
    "pattern",
    "per",
    "percent",
    "percent_rank",
    "percentile_cont",
    "percentile_disc",
    "period",
    "portion",
    "position",
    "position_regex",
    "power",
    "precedes",
    "precision",
    "prepare",
    "primary",
    "procedure",
    "ptf",
    "range",
    "rank",
    "reads",
    "real",
    "recursive",
    "ref",
    "references",
    "referencing",
    "regr_avgx",
    "regr_avgy",
    "regr_count",
    "regr_intercept",
    "regr_r2",
    "regr_slope",
    "regr_sxx",
    "regr_sxy",
    "regr_syy",
    "release",
    "result",
    "return",
    "returns",
    "revoke",
    "right",
    "rollback",
    "rollup",
    "row",
    "row_number",
    "rows",
    "running",
    "savepoint",
    "scope",
    "scroll",
    "search",
    "second",
    "seek",
    "select",
    "sensitive",
    "session_user",
    "set",
    "show",
    "similar",
    "sin",
    "sinh",
    "skip",
    "smallint",
    "some",
    "specific",
    "specifictype",
    "sql",
    "sqlexception",
    "sqlstate",
    "sqlwarning",
    "sqrt",
    "start",
    "static",
    "stddev_pop",
    "stddev_samp",
    "submultiset",
    "subset",
    "substring",
    "substring_regex",
    "succeeds",
    "sum",
    "symmetric",
    "system",
    "system_time",
    "system_user",
    "table",
    "tablesample",
    "tan",
    "tanh",
    "then",
    "time",
    "timestamp",
    "timezone_hour",
    "timezone_minute",
    "to",
    "trailing",
    "translate",
    "translate_regex",
    "translation",
    "treat",
    "trigger",
    "trim",
    "trim_array",
    "true",
    "truncate",
    "uescape",
    "union",
    "unique",
    "unknown",
    "unnest",
    "update",
    "upper",
    "user",
    "using",
    "value",
    "values",
    "value_of",
    "var_pop",
    "var_samp",
    "varbinary",
    "varchar",
    "varying",
    "versioning",
    "when",
    "whenever",
    "where",
    "width_bucket",
    "window",
    "with",
    "within",
    "without",
    "year"
  ];
  const RESERVED_FUNCTIONS = [
    "abs",
    "acos",
    "array_agg",
    "asin",
    "atan",
    "avg",
    "cast",
    "ceil",
    "ceiling",
    "coalesce",
    "corr",
    "cos",
    "cosh",
    "count",
    "covar_pop",
    "covar_samp",
    "cume_dist",
    "dense_rank",
    "deref",
    "element",
    "exp",
    "extract",
    "first_value",
    "floor",
    "json_array",
    "json_arrayagg",
    "json_exists",
    "json_object",
    "json_objectagg",
    "json_query",
    "json_table",
    "json_table_primitive",
    "json_value",
    "lag",
    "last_value",
    "lead",
    "listagg",
    "ln",
    "log",
    "log10",
    "lower",
    "max",
    "min",
    "mod",
    "nth_value",
    "ntile",
    "nullif",
    "percent_rank",
    "percentile_cont",
    "percentile_disc",
    "position",
    "position_regex",
    "power",
    "rank",
    "regr_avgx",
    "regr_avgy",
    "regr_count",
    "regr_intercept",
    "regr_r2",
    "regr_slope",
    "regr_sxx",
    "regr_sxy",
    "regr_syy",
    "row_number",
    "sin",
    "sinh",
    "sqrt",
    "stddev_pop",
    "stddev_samp",
    "substring",
    "substring_regex",
    "sum",
    "tan",
    "tanh",
    "translate",
    "translate_regex",
    "treat",
    "trim",
    "trim_array",
    "unnest",
    "upper",
    "value_of",
    "var_pop",
    "var_samp",
    "width_bucket"
  ];
  const POSSIBLE_WITHOUT_PARENS = [
    "current_catalog",
    "current_date",
    "current_default_transform_group",
    "current_path",
    "current_role",
    "current_schema",
    "current_transform_group_for_type",
    "current_user",
    "session_user",
    "system_time",
    "system_user",
    "current_time",
    "localtime",
    "current_timestamp",
    "localtimestamp"
  ];
  const COMBOS = [
    "create table",
    "insert into",
    "primary key",
    "foreign key",
    "not null",
    "alter table",
    "add constraint",
    "grouping sets",
    "on overflow",
    "character set",
    "respect nulls",
    "ignore nulls",
    "nulls first",
    "nulls last",
    "depth first",
    "breadth first"
  ];
  const FUNCTIONS = RESERVED_FUNCTIONS;
  const KEYWORDS3 = [
    ...RESERVED_WORDS,
    ...NON_RESERVED_WORDS
  ].filter((keyword) => {
    return !RESERVED_FUNCTIONS.includes(keyword);
  });
  const VARIABLE = {
    scope: "variable",
    match: /@[a-z0-9][a-z0-9_]*/
  };
  const OPERATOR = {
    scope: "operator",
    match: /[-+*/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?/,
    relevance: 0
  };
  const FUNCTION_CALL = {
    match: regex.concat(/\b/, regex.either(...FUNCTIONS), /\s*\(/),
    relevance: 0,
    keywords: { built_in: FUNCTIONS }
  };
  function kws_to_regex(list) {
    return regex.concat(
      /\b/,
      regex.either(...list.map((kw) => {
        return kw.replace(/\s+/, "\\s+");
      })),
      /\b/
    );
  }
  const MULTI_WORD_KEYWORDS = {
    scope: "keyword",
    match: kws_to_regex(COMBOS),
    relevance: 0
  };
  function reduceRelevancy(list, {
    exceptions,
    when
  } = {}) {
    const qualifyFn = when;
    exceptions = exceptions || [];
    return list.map((item) => {
      if (item.match(/\|\d+$/) || exceptions.includes(item)) {
        return item;
      } else if (qualifyFn(item)) {
        return `${item}|0`;
      } else {
        return item;
      }
    });
  }
  return {
    name: "SQL",
    case_insensitive: true,
    // does not include {} or HTML tags `</`
    illegal: /[{}]|<\//,
    keywords: {
      $pattern: /\b[\w\.]+/,
      keyword: reduceRelevancy(KEYWORDS3, { when: (x2) => x2.length < 3 }),
      literal: LITERALS3,
      type: TYPES3,
      built_in: POSSIBLE_WITHOUT_PARENS
    },
    contains: [
      {
        scope: "type",
        match: kws_to_regex(MULTI_WORD_TYPES)
      },
      MULTI_WORD_KEYWORDS,
      FUNCTION_CALL,
      VARIABLE,
      STRING,
      QUOTED_IDENTIFIER,
      hljs5.C_NUMBER_MODE,
      hljs5.C_BLOCK_COMMENT_MODE,
      COMMENT_MODE,
      OPERATOR
    ]
  };
}

// ../mini-lit/node_modules/highlight.js/es/languages/typescript.js
init_process_shim();
var IDENT_RE2 = "[A-Za-z$_][0-9A-Za-z$_]*";
var KEYWORDS2 = [
  "as",
  // for exports
  "in",
  "of",
  "if",
  "for",
  "while",
  "finally",
  "var",
  "new",
  "function",
  "do",
  "return",
  "void",
  "else",
  "break",
  "catch",
  "instanceof",
  "with",
  "throw",
  "case",
  "default",
  "try",
  "switch",
  "continue",
  "typeof",
  "delete",
  "let",
  "yield",
  "const",
  "class",
  // JS handles these with a special rule
  // "get",
  // "set",
  "debugger",
  "async",
  "await",
  "static",
  "import",
  "from",
  "export",
  "extends",
  // It's reached stage 3, which is "recommended for implementation":
  "using"
];
var LITERALS2 = [
  "true",
  "false",
  "null",
  "undefined",
  "NaN",
  "Infinity"
];
var TYPES2 = [
  // Fundamental objects
  "Object",
  "Function",
  "Boolean",
  "Symbol",
  // numbers and dates
  "Math",
  "Date",
  "Number",
  "BigInt",
  // text
  "String",
  "RegExp",
  // Indexed collections
  "Array",
  "Float32Array",
  "Float64Array",
  "Int8Array",
  "Uint8Array",
  "Uint8ClampedArray",
  "Int16Array",
  "Int32Array",
  "Uint16Array",
  "Uint32Array",
  "BigInt64Array",
  "BigUint64Array",
  // Keyed collections
  "Set",
  "Map",
  "WeakSet",
  "WeakMap",
  // Structured data
  "ArrayBuffer",
  "SharedArrayBuffer",
  "Atomics",
  "DataView",
  "JSON",
  // Control abstraction objects
  "Promise",
  "Generator",
  "GeneratorFunction",
  "AsyncFunction",
  // Reflection
  "Reflect",
  "Proxy",
  // Internationalization
  "Intl",
  // WebAssembly
  "WebAssembly"
];
var ERROR_TYPES2 = [
  "Error",
  "EvalError",
  "InternalError",
  "RangeError",
  "ReferenceError",
  "SyntaxError",
  "TypeError",
  "URIError"
];
var BUILT_IN_GLOBALS2 = [
  "setInterval",
  "setTimeout",
  "clearInterval",
  "clearTimeout",
  "require",
  "exports",
  "eval",
  "isFinite",
  "isNaN",
  "parseFloat",
  "parseInt",
  "decodeURI",
  "decodeURIComponent",
  "encodeURI",
  "encodeURIComponent",
  "escape",
  "unescape"
];
var BUILT_IN_VARIABLES2 = [
  "arguments",
  "this",
  "super",
  "console",
  "window",
  "document",
  "localStorage",
  "sessionStorage",
  "module",
  "global"
  // Node.js
];
var BUILT_INS2 = [].concat(
  BUILT_IN_GLOBALS2,
  TYPES2,
  ERROR_TYPES2
);
function javascript2(hljs5) {
  const regex = hljs5.regex;
  const hasClosingTag = (match2, { after }) => {
    const tag = "</" + match2[0].slice(1);
    const pos = match2.input.indexOf(tag, after);
    return pos !== -1;
  };
  const IDENT_RE$1 = IDENT_RE2;
  const FRAGMENT = {
    begin: "<>",
    end: "</>"
  };
  const XML_SELF_CLOSING = /<[A-Za-z0-9\\._:-]+\s*\/>/;
  const XML_TAG = {
    begin: /<[A-Za-z0-9\\._:-]+/,
    end: /\/[A-Za-z0-9\\._:-]+>|\/>/,
    /**
     * @param {RegExpMatchArray} match
     * @param {CallbackResponse} response
     */
    isTrulyOpeningTag: (match2, response) => {
      const afterMatchIndex = match2[0].length + match2.index;
      const nextChar = match2.input[afterMatchIndex];
      if (
        // HTML should not include another raw `<` inside a tag
        // nested type?
        // `<Array<Array<number>>`, etc.
        nextChar === "<" || // the , gives away that this is not HTML
        // `<T, A extends keyof T, V>`
        nextChar === ","
      ) {
        response.ignoreMatch();
        return;
      }
      if (nextChar === ">") {
        if (!hasClosingTag(match2, { after: afterMatchIndex })) {
          response.ignoreMatch();
        }
      }
      let m4;
      const afterMatch = match2.input.substring(afterMatchIndex);
      if (m4 = afterMatch.match(/^\s*=/)) {
        response.ignoreMatch();
        return;
      }
      if (m4 = afterMatch.match(/^\s+extends\s+/)) {
        if (m4.index === 0) {
          response.ignoreMatch();
          return;
        }
      }
    }
  };
  const KEYWORDS$1 = {
    $pattern: IDENT_RE2,
    keyword: KEYWORDS2,
    literal: LITERALS2,
    built_in: BUILT_INS2,
    "variable.language": BUILT_IN_VARIABLES2
  };
  const decimalDigits = "[0-9](_?[0-9])*";
  const frac = `\\.(${decimalDigits})`;
  const decimalInteger = `0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*`;
  const NUMBER = {
    className: "number",
    variants: [
      // DecimalLiteral
      { begin: `(\\b(${decimalInteger})((${frac})|\\.)?|(${frac}))[eE][+-]?(${decimalDigits})\\b` },
      { begin: `\\b(${decimalInteger})\\b((${frac})\\b|\\.)?|(${frac})\\b` },
      // DecimalBigIntegerLiteral
      { begin: `\\b(0|[1-9](_?[0-9])*)n\\b` },
      // NonDecimalIntegerLiteral
      { begin: "\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b" },
      { begin: "\\b0[bB][0-1](_?[0-1])*n?\\b" },
      { begin: "\\b0[oO][0-7](_?[0-7])*n?\\b" },
      // LegacyOctalIntegerLiteral (does not include underscore separators)
      // https://tc39.es/ecma262/#sec-additional-syntax-numeric-literals
      { begin: "\\b0[0-7]+n?\\b" }
    ],
    relevance: 0
  };
  const SUBST = {
    className: "subst",
    begin: "\\$\\{",
    end: "\\}",
    keywords: KEYWORDS$1,
    contains: []
    // defined later
  };
  const HTML_TEMPLATE = {
    begin: ".?html`",
    end: "",
    starts: {
      end: "`",
      returnEnd: false,
      contains: [
        hljs5.BACKSLASH_ESCAPE,
        SUBST
      ],
      subLanguage: "xml"
    }
  };
  const CSS_TEMPLATE = {
    begin: ".?css`",
    end: "",
    starts: {
      end: "`",
      returnEnd: false,
      contains: [
        hljs5.BACKSLASH_ESCAPE,
        SUBST
      ],
      subLanguage: "css"
    }
  };
  const GRAPHQL_TEMPLATE = {
    begin: ".?gql`",
    end: "",
    starts: {
      end: "`",
      returnEnd: false,
      contains: [
        hljs5.BACKSLASH_ESCAPE,
        SUBST
      ],
      subLanguage: "graphql"
    }
  };
  const TEMPLATE_STRING = {
    className: "string",
    begin: "`",
    end: "`",
    contains: [
      hljs5.BACKSLASH_ESCAPE,
      SUBST
    ]
  };
  const JSDOC_COMMENT = hljs5.COMMENT(
    /\/\*\*(?!\/)/,
    "\\*/",
    {
      relevance: 0,
      contains: [
        {
          begin: "(?=@[A-Za-z]+)",
          relevance: 0,
          contains: [
            {
              className: "doctag",
              begin: "@[A-Za-z]+"
            },
            {
              className: "type",
              begin: "\\{",
              end: "\\}",
              excludeEnd: true,
              excludeBegin: true,
              relevance: 0
            },
            {
              className: "variable",
              begin: IDENT_RE$1 + "(?=\\s*(-)|$)",
              endsParent: true,
              relevance: 0
            },
            // eat spaces (not newlines) so we can find
            // types or variables
            {
              begin: /(?=[^\n])\s/,
              relevance: 0
            }
          ]
        }
      ]
    }
  );
  const COMMENT = {
    className: "comment",
    variants: [
      JSDOC_COMMENT,
      hljs5.C_BLOCK_COMMENT_MODE,
      hljs5.C_LINE_COMMENT_MODE
    ]
  };
  const SUBST_INTERNALS = [
    hljs5.APOS_STRING_MODE,
    hljs5.QUOTE_STRING_MODE,
    HTML_TEMPLATE,
    CSS_TEMPLATE,
    GRAPHQL_TEMPLATE,
    TEMPLATE_STRING,
    // Skip numbers when they are part of a variable name
    { match: /\$\d+/ },
    NUMBER
    // This is intentional:
    // See https://github.com/highlightjs/highlight.js/issues/3288
    // hljs.REGEXP_MODE
  ];
  SUBST.contains = SUBST_INTERNALS.concat({
    // we need to pair up {} inside our subst to prevent
    // it from ending too early by matching another }
    begin: /\{/,
    end: /\}/,
    keywords: KEYWORDS$1,
    contains: [
      "self"
    ].concat(SUBST_INTERNALS)
  });
  const SUBST_AND_COMMENTS = [].concat(COMMENT, SUBST.contains);
  const PARAMS_CONTAINS = SUBST_AND_COMMENTS.concat([
    // eat recursive parens in sub expressions
    {
      begin: /(\s*)\(/,
      end: /\)/,
      keywords: KEYWORDS$1,
      contains: ["self"].concat(SUBST_AND_COMMENTS)
    }
  ]);
  const PARAMS = {
    className: "params",
    // convert this to negative lookbehind in v12
    begin: /(\s*)\(/,
    // to match the parms with
    end: /\)/,
    excludeBegin: true,
    excludeEnd: true,
    keywords: KEYWORDS$1,
    contains: PARAMS_CONTAINS
  };
  const CLASS_OR_EXTENDS = {
    variants: [
      // class Car extends vehicle
      {
        match: [
          /class/,
          /\s+/,
          IDENT_RE$1,
          /\s+/,
          /extends/,
          /\s+/,
          regex.concat(IDENT_RE$1, "(", regex.concat(/\./, IDENT_RE$1), ")*")
        ],
        scope: {
          1: "keyword",
          3: "title.class",
          5: "keyword",
          7: "title.class.inherited"
        }
      },
      // class Car
      {
        match: [
          /class/,
          /\s+/,
          IDENT_RE$1
        ],
        scope: {
          1: "keyword",
          3: "title.class"
        }
      }
    ]
  };
  const CLASS_REFERENCE = {
    relevance: 0,
    match: regex.either(
      // Hard coded exceptions
      /\bJSON/,
      // Float32Array, OutT
      /\b[A-Z][a-z]+([A-Z][a-z]*|\d)*/,
      // CSSFactory, CSSFactoryT
      /\b[A-Z]{2,}([A-Z][a-z]+|\d)+([A-Z][a-z]*)*/,
      // FPs, FPsT
      /\b[A-Z]{2,}[a-z]+([A-Z][a-z]+|\d)*([A-Z][a-z]*)*/
      // P
      // single letters are not highlighted
      // BLAH
      // this will be flagged as a UPPER_CASE_CONSTANT instead
    ),
    className: "title.class",
    keywords: {
      _: [
        // se we still get relevance credit for JS library classes
        ...TYPES2,
        ...ERROR_TYPES2
      ]
    }
  };
  const USE_STRICT = {
    label: "use_strict",
    className: "meta",
    relevance: 10,
    begin: /^\s*['"]use (strict|asm)['"]/
  };
  const FUNCTION_DEFINITION = {
    variants: [
      {
        match: [
          /function/,
          /\s+/,
          IDENT_RE$1,
          /(?=\s*\()/
        ]
      },
      // anonymous function
      {
        match: [
          /function/,
          /\s*(?=\()/
        ]
      }
    ],
    className: {
      1: "keyword",
      3: "title.function"
    },
    label: "func.def",
    contains: [PARAMS],
    illegal: /%/
  };
  const UPPER_CASE_CONSTANT = {
    relevance: 0,
    match: /\b[A-Z][A-Z_0-9]+\b/,
    className: "variable.constant"
  };
  function noneOf(list) {
    return regex.concat("(?!", list.join("|"), ")");
  }
  const FUNCTION_CALL = {
    match: regex.concat(
      /\b/,
      noneOf([
        ...BUILT_IN_GLOBALS2,
        "super",
        "import"
      ].map((x2) => `${x2}\\s*\\(`)),
      IDENT_RE$1,
      regex.lookahead(/\s*\(/)
    ),
    className: "title.function",
    relevance: 0
  };
  const PROPERTY_ACCESS = {
    begin: regex.concat(/\./, regex.lookahead(
      regex.concat(IDENT_RE$1, /(?![0-9A-Za-z$_(])/)
    )),
    end: IDENT_RE$1,
    excludeBegin: true,
    keywords: "prototype",
    className: "property",
    relevance: 0
  };
  const GETTER_OR_SETTER = {
    match: [
      /get|set/,
      /\s+/,
      IDENT_RE$1,
      /(?=\()/
    ],
    className: {
      1: "keyword",
      3: "title.function"
    },
    contains: [
      {
        // eat to avoid empty params
        begin: /\(\)/
      },
      PARAMS
    ]
  };
  const FUNC_LEAD_IN_RE = "(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|" + hljs5.UNDERSCORE_IDENT_RE + ")\\s*=>";
  const FUNCTION_VARIABLE = {
    match: [
      /const|var|let/,
      /\s+/,
      IDENT_RE$1,
      /\s*/,
      /=\s*/,
      /(async\s*)?/,
      // async is optional
      regex.lookahead(FUNC_LEAD_IN_RE)
    ],
    keywords: "async",
    className: {
      1: "keyword",
      3: "title.function"
    },
    contains: [
      PARAMS
    ]
  };
  return {
    name: "JavaScript",
    aliases: ["js", "jsx", "mjs", "cjs"],
    keywords: KEYWORDS$1,
    // this will be extended by TypeScript
    exports: { PARAMS_CONTAINS, CLASS_REFERENCE },
    illegal: /#(?![$_A-z])/,
    contains: [
      hljs5.SHEBANG({
        label: "shebang",
        binary: "node",
        relevance: 5
      }),
      USE_STRICT,
      hljs5.APOS_STRING_MODE,
      hljs5.QUOTE_STRING_MODE,
      HTML_TEMPLATE,
      CSS_TEMPLATE,
      GRAPHQL_TEMPLATE,
      TEMPLATE_STRING,
      COMMENT,
      // Skip numbers when they are part of a variable name
      { match: /\$\d+/ },
      NUMBER,
      CLASS_REFERENCE,
      {
        scope: "attr",
        match: IDENT_RE$1 + regex.lookahead(":"),
        relevance: 0
      },
      FUNCTION_VARIABLE,
      {
        // "value" container
        begin: "(" + hljs5.RE_STARTERS_RE + "|\\b(case|return|throw)\\b)\\s*",
        keywords: "return throw case",
        relevance: 0,
        contains: [
          COMMENT,
          hljs5.REGEXP_MODE,
          {
            className: "function",
            // we have to count the parens to make sure we actually have the
            // correct bounding ( ) before the =>.  There could be any number of
            // sub-expressions inside also surrounded by parens.
            begin: FUNC_LEAD_IN_RE,
            returnBegin: true,
            end: "\\s*=>",
            contains: [
              {
                className: "params",
                variants: [
                  {
                    begin: hljs5.UNDERSCORE_IDENT_RE,
                    relevance: 0
                  },
                  {
                    className: null,
                    begin: /\(\s*\)/,
                    skip: true
                  },
                  {
                    begin: /(\s*)\(/,
                    end: /\)/,
                    excludeBegin: true,
                    excludeEnd: true,
                    keywords: KEYWORDS$1,
                    contains: PARAMS_CONTAINS
                  }
                ]
              }
            ]
          },
          {
            // could be a comma delimited list of params to a function call
            begin: /,/,
            relevance: 0
          },
          {
            match: /\s+/,
            relevance: 0
          },
          {
            // JSX
            variants: [
              { begin: FRAGMENT.begin, end: FRAGMENT.end },
              { match: XML_SELF_CLOSING },
              {
                begin: XML_TAG.begin,
                // we carefully check the opening tag to see if it truly
                // is a tag and not a false positive
                "on:begin": XML_TAG.isTrulyOpeningTag,
                end: XML_TAG.end
              }
            ],
            subLanguage: "xml",
            contains: [
              {
                begin: XML_TAG.begin,
                end: XML_TAG.end,
                skip: true,
                contains: ["self"]
              }
            ]
          }
        ]
      },
      FUNCTION_DEFINITION,
      {
        // prevent this from getting swallowed up by function
        // since they appear "function like"
        beginKeywords: "while if switch catch for"
      },
      {
        // we have to count the parens to make sure we actually have the correct
        // bounding ( ).  There could be any number of sub-expressions inside
        // also surrounded by parens.
        begin: "\\b(?!function)" + hljs5.UNDERSCORE_IDENT_RE + "\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",
        // end parens
        returnBegin: true,
        label: "func.def",
        contains: [
          PARAMS,
          hljs5.inherit(hljs5.TITLE_MODE, { begin: IDENT_RE$1, className: "title.function" })
        ]
      },
      // catch ... so it won't trigger the property rule below
      {
        match: /\.\.\./,
        relevance: 0
      },
      PROPERTY_ACCESS,
      // hack: prevents detection of keywords in some circumstances
      // .keyword()
      // $keyword = x
      {
        match: "\\$" + IDENT_RE$1,
        relevance: 0
      },
      {
        match: [/\bconstructor(?=\s*\()/],
        className: { 1: "title.function" },
        contains: [PARAMS]
      },
      FUNCTION_CALL,
      UPPER_CASE_CONSTANT,
      CLASS_OR_EXTENDS,
      GETTER_OR_SETTER,
      {
        match: /\$[(.]/
        // relevance booster for a pattern common to JS libs: `$(something)` and `$.something`
      }
    ]
  };
}
function typescript(hljs5) {
  const regex = hljs5.regex;
  const tsLanguage = javascript2(hljs5);
  const IDENT_RE$1 = IDENT_RE2;
  const TYPES3 = [
    "any",
    "void",
    "number",
    "boolean",
    "string",
    "object",
    "never",
    "symbol",
    "bigint",
    "unknown"
  ];
  const NAMESPACE = {
    begin: [
      /namespace/,
      /\s+/,
      hljs5.IDENT_RE
    ],
    beginScope: {
      1: "keyword",
      3: "title.class"
    }
  };
  const INTERFACE = {
    beginKeywords: "interface",
    end: /\{/,
    excludeEnd: true,
    keywords: {
      keyword: "interface extends",
      built_in: TYPES3
    },
    contains: [tsLanguage.exports.CLASS_REFERENCE]
  };
  const USE_STRICT = {
    className: "meta",
    relevance: 10,
    begin: /^\s*['"]use strict['"]/
  };
  const TS_SPECIFIC_KEYWORDS = [
    "type",
    // "namespace",
    "interface",
    "public",
    "private",
    "protected",
    "implements",
    "declare",
    "abstract",
    "readonly",
    "enum",
    "override",
    "satisfies"
  ];
  const KEYWORDS$1 = {
    $pattern: IDENT_RE2,
    keyword: KEYWORDS2.concat(TS_SPECIFIC_KEYWORDS),
    literal: LITERALS2,
    built_in: BUILT_INS2.concat(TYPES3),
    "variable.language": BUILT_IN_VARIABLES2
  };
  const DECORATOR = {
    className: "meta",
    begin: "@" + IDENT_RE$1
  };
  const swapMode = (mode, label, replacement) => {
    const indx = mode.contains.findIndex((m4) => m4.label === label);
    if (indx === -1) {
      throw new Error("can not find mode to replace");
    }
    mode.contains.splice(indx, 1, replacement);
  };
  Object.assign(tsLanguage.keywords, KEYWORDS$1);
  tsLanguage.exports.PARAMS_CONTAINS.push(DECORATOR);
  const ATTRIBUTE_HIGHLIGHT = tsLanguage.contains.find((c6) => c6.scope === "attr");
  const OPTIONAL_KEY_OR_ARGUMENT = Object.assign(
    {},
    ATTRIBUTE_HIGHLIGHT,
    { match: regex.concat(IDENT_RE$1, regex.lookahead(/\s*\?:/)) }
  );
  tsLanguage.exports.PARAMS_CONTAINS.push([
    tsLanguage.exports.CLASS_REFERENCE,
    // class reference for highlighting the params types
    ATTRIBUTE_HIGHLIGHT,
    // highlight the params key
    OPTIONAL_KEY_OR_ARGUMENT
    // Added for optional property assignment highlighting
  ]);
  tsLanguage.contains = tsLanguage.contains.concat([
    DECORATOR,
    NAMESPACE,
    INTERFACE,
    OPTIONAL_KEY_OR_ARGUMENT
    // Added for optional property assignment highlighting
  ]);
  swapMode(tsLanguage, "shebang", hljs5.SHEBANG());
  swapMode(tsLanguage, "use_strict", USE_STRICT);
  const functionDeclaration = tsLanguage.contains.find((m4) => m4.label === "func.def");
  functionDeclaration.relevance = 0;
  Object.assign(tsLanguage, {
    name: "TypeScript",
    aliases: [
      "ts",
      "tsx",
      "mts",
      "cts"
    ]
  });
  return tsLanguage;
}

// ../mini-lit/node_modules/highlight.js/es/languages/xml.js
init_process_shim();
function xml(hljs5) {
  const regex = hljs5.regex;
  const TAG_NAME_RE = regex.concat(/[\p{L}_]/u, regex.optional(/[\p{L}0-9_.-]*:/u), /[\p{L}0-9_.-]*/u);
  const XML_IDENT_RE = /[\p{L}0-9._:-]+/u;
  const XML_ENTITIES = {
    className: "symbol",
    begin: /&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;/
  };
  const XML_META_KEYWORDS = {
    begin: /\s/,
    contains: [
      {
        className: "keyword",
        begin: /#?[a-z_][a-z1-9_-]+/,
        illegal: /\n/
      }
    ]
  };
  const XML_META_PAR_KEYWORDS = hljs5.inherit(XML_META_KEYWORDS, {
    begin: /\(/,
    end: /\)/
  });
  const APOS_META_STRING_MODE = hljs5.inherit(hljs5.APOS_STRING_MODE, { className: "string" });
  const QUOTE_META_STRING_MODE = hljs5.inherit(hljs5.QUOTE_STRING_MODE, { className: "string" });
  const TAG_INTERNALS = {
    endsWithParent: true,
    illegal: /</,
    relevance: 0,
    contains: [
      {
        className: "attr",
        begin: XML_IDENT_RE,
        relevance: 0
      },
      {
        begin: /=\s*/,
        relevance: 0,
        contains: [
          {
            className: "string",
            endsParent: true,
            variants: [
              {
                begin: /"/,
                end: /"/,
                contains: [XML_ENTITIES]
              },
              {
                begin: /'/,
                end: /'/,
                contains: [XML_ENTITIES]
              },
              { begin: /[^\s"'=<>`]+/ }
            ]
          }
        ]
      }
    ]
  };
  return {
    name: "HTML, XML",
    aliases: [
      "html",
      "xhtml",
      "rss",
      "atom",
      "xjb",
      "xsd",
      "xsl",
      "plist",
      "wsf",
      "svg"
    ],
    case_insensitive: true,
    unicodeRegex: true,
    contains: [
      {
        className: "meta",
        begin: /<![a-z]/,
        end: />/,
        relevance: 10,
        contains: [
          XML_META_KEYWORDS,
          QUOTE_META_STRING_MODE,
          APOS_META_STRING_MODE,
          XML_META_PAR_KEYWORDS,
          {
            begin: /\[/,
            end: /\]/,
            contains: [
              {
                className: "meta",
                begin: /<![a-z]/,
                end: />/,
                contains: [
                  XML_META_KEYWORDS,
                  XML_META_PAR_KEYWORDS,
                  QUOTE_META_STRING_MODE,
                  APOS_META_STRING_MODE
                ]
              }
            ]
          }
        ]
      },
      hljs5.COMMENT(
        /<!--/,
        /-->/,
        { relevance: 10 }
      ),
      {
        begin: /<!\[CDATA\[/,
        end: /\]\]>/,
        relevance: 10
      },
      XML_ENTITIES,
      // xml processing instructions
      {
        className: "meta",
        end: /\?>/,
        variants: [
          {
            begin: /<\?xml/,
            relevance: 10,
            contains: [
              QUOTE_META_STRING_MODE
            ]
          },
          {
            begin: /<\?[a-z][a-z0-9]+/
          }
        ]
      },
      {
        className: "tag",
        /*
        The lookahead pattern (?=...) ensures that 'begin' only matches
        '<style' as a single word, followed by a whitespace or an
        ending bracket.
        */
        begin: /<style(?=\s|>)/,
        end: />/,
        keywords: { name: "style" },
        contains: [TAG_INTERNALS],
        starts: {
          end: /<\/style>/,
          returnEnd: true,
          subLanguage: [
            "css",
            "xml"
          ]
        }
      },
      {
        className: "tag",
        // See the comment in the <style tag about the lookahead pattern
        begin: /<script(?=\s|>)/,
        end: />/,
        keywords: { name: "script" },
        contains: [TAG_INTERNALS],
        starts: {
          end: /<\/script>/,
          returnEnd: true,
          subLanguage: [
            "javascript",
            "handlebars",
            "xml"
          ]
        }
      },
      // we need this for now for jSX
      {
        className: "tag",
        begin: /<>|<\/>/
      },
      // open tag
      {
        className: "tag",
        begin: regex.concat(
          /</,
          regex.lookahead(regex.concat(
            TAG_NAME_RE,
            // <tag/>
            // <tag>
            // <tag ...
            regex.either(/\/>/, />/, /\s/)
          ))
        ),
        end: /\/?>/,
        contains: [
          {
            className: "name",
            begin: TAG_NAME_RE,
            relevance: 0,
            starts: TAG_INTERNALS
          }
        ]
      },
      // close tag
      {
        className: "tag",
        begin: regex.concat(
          /<\//,
          regex.lookahead(regex.concat(
            TAG_NAME_RE,
            />/
          ))
        ),
        contains: [
          {
            className: "name",
            begin: TAG_NAME_RE,
            relevance: 0
          },
          {
            begin: />/,
            relevance: 0,
            endsParent: true
          }
        ]
      }
    ]
  };
}

// ../mini-lit/dist/CodeBlock.js
var __decorate26 = function(decorators, target, key, desc) {
  var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc);
  else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8;
  return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8;
};
core_default.registerLanguage("javascript", javascript);
core_default.registerLanguage("typescript", typescript);
core_default.registerLanguage("python", python);
core_default.registerLanguage("html", xml);
core_default.registerLanguage("xml", xml);
core_default.registerLanguage("css", css);
core_default.registerLanguage("json", json);
core_default.registerLanguage("bash", bash);
core_default.registerLanguage("sql", sql);
var CodeBlock = class CodeBlock2 extends i4 {
  constructor() {
    super(...arguments);
    this.code = "";
    this.language = "";
  }
  createRenderRoot() {
    return this;
  }
  connectedCallback() {
    super.connectedCallback();
    this.style.display = "block";
  }
  getDecodedCode() {
    try {
      return decodeURIComponent(escape(atob(this.code)));
    } catch {
      return this.code;
    }
  }
  render() {
    const decodedCode = this.getDecodedCode();
    const highlighted = this.language && core_default.getLanguage(this.language) ? core_default.highlight(decodedCode, { language: this.language }).value : core_default.highlightAuto(decodedCode).value;
    const displayLanguage = this.language || "plaintext";
    return b2`
			<div class="border border-border rounded-lg overflow-hidden">
				<!-- Title bar -->
				<div class="flex items-center justify-between px-3 py-1">
					<span class="text-xs text-muted-foreground font-mono">${displayLanguage}</span>
					<copy-button class="[&>button]:!bg-transparent [&>button]:hover:!bg-accent" .text=${decodedCode} title="${i18n("Copy code")}" .showText=${true}></copy-button>
				</div>
				<!-- Code content -->
				<div class="overflow-auto max-h-96">
					<pre
						class="!bg-transparent !border-0 !rounded-none m-0 px-4 pb-4 text-xs text-foreground font-mono"
					><code class="hljs language-${this.language || "plaintext"}">${o7(highlighted)}</code></pre>
				</div>
			</div>
		`;
  }
};
__decorate26([
  n6()
], CodeBlock.prototype, "code", void 0);
__decorate26([
  n6()
], CodeBlock.prototype, "language", void 0);
CodeBlock = __decorate26([
  t5("code-block")
], CodeBlock);

// ../pi-mono/packages/web-ui/dist/components/ConsoleBlock.js
init_process_shim();
var __decorate27 = function(decorators, target, key, desc) {
  var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc);
  else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8;
  return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8;
};
var ConsoleBlock = class extends i4 {
  constructor() {
    super(...arguments);
    this.content = "";
    this.variant = "default";
    this.copied = false;
  }
  createRenderRoot() {
    return this;
  }
  connectedCallback() {
    super.connectedCallback();
    this.style.display = "block";
  }
  async copy() {
    try {
      await navigator.clipboard.writeText(this.content || "");
      this.copied = true;
      setTimeout(() => {
        this.copied = false;
      }, 1500);
    } catch (e9) {
      console.error("Copy failed", e9);
    }
  }
  updated() {
    const container = this.querySelector(".console-scroll");
    if (container) {
      container.scrollTop = container.scrollHeight;
    }
  }
  render() {
    const isError2 = this.variant === "error";
    const textClass = isError2 ? "text-destructive" : "text-foreground";
    return b2`
			<div class="border border-border rounded-lg overflow-hidden">
				<div class="flex items-center justify-between px-3 py-1.5 bg-muted border-b border-border">
					<span class="text-xs text-muted-foreground font-mono">${i18n("console")}</span>
					<button
						@click=${() => this.copy()}
						class="flex items-center gap-1 px-2 py-0.5 text-xs rounded hover:bg-accent text-muted-foreground hover:text-accent-foreground transition-colors"
						title="${i18n("Copy output")}"
					>
						${this.copied ? icon(Check2, "sm") : icon(Copy2, "sm")}
						${this.copied ? b2`<span>${i18n("Copied!")}</span>` : ""}
					</button>
				</div>
				<div class="console-scroll overflow-auto max-h-64">
					<pre class="!bg-background !border-0 !rounded-none m-0 p-3 text-xs ${textClass} font-mono whitespace-pre-wrap">
${this.content || ""}</pre
					>
				</div>
			</div>
		`;
  }
};
__decorate27([
  n6()
], ConsoleBlock.prototype, "content", void 0);
__decorate27([
  n6()
], ConsoleBlock.prototype, "variant", void 0);
__decorate27([
  r7()
], ConsoleBlock.prototype, "copied", void 0);
if (!customElements.get("console-block")) {
  customElements.define("console-block", ConsoleBlock);
}

// ../mini-lit/dist/Diff.js
init_process_shim();

// ../mini-lit/node_modules/diff/libesm/index.js
init_process_shim();

// ../mini-lit/node_modules/diff/libesm/diff/base.js
init_process_shim();
var Diff = class {
  diff(oldStr, newStr, options = {}) {
    let callback;
    if (typeof options === "function") {
      callback = options;
      options = {};
    } else if ("callback" in options) {
      callback = options.callback;
    }
    const oldString = this.castInput(oldStr, options);
    const newString = this.castInput(newStr, options);
    const oldTokens = this.removeEmpty(this.tokenize(oldString, options));
    const newTokens = this.removeEmpty(this.tokenize(newString, options));
    return this.diffWithOptionsObj(oldTokens, newTokens, options, callback);
  }
  diffWithOptionsObj(oldTokens, newTokens, options, callback) {
    var _a7;
    const done = (value) => {
      value = this.postProcess(value, options);
      if (callback) {
        setTimeout(function() {
          callback(value);
        }, 0);
        return void 0;
      } else {
        return value;
      }
    };
    const newLen = newTokens.length, oldLen = oldTokens.length;
    let editLength = 1;
    let maxEditLength = newLen + oldLen;
    if (options.maxEditLength != null) {
      maxEditLength = Math.min(maxEditLength, options.maxEditLength);
    }
    const maxExecutionTime = (_a7 = options.timeout) !== null && _a7 !== void 0 ? _a7 : Infinity;
    const abortAfterTimestamp = Date.now() + maxExecutionTime;
    const bestPath = [{ oldPos: -1, lastComponent: void 0 }];
    let newPos = this.extractCommon(bestPath[0], newTokens, oldTokens, 0, options);
    if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) {
      return done(this.buildValues(bestPath[0].lastComponent, newTokens, oldTokens));
    }
    let minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity;
    const execEditLength = () => {
      for (let diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) {
        let basePath;
        const removePath = bestPath[diagonalPath - 1], addPath = bestPath[diagonalPath + 1];
        if (removePath) {
          bestPath[diagonalPath - 1] = void 0;
        }
        let canAdd = false;
        if (addPath) {
          const addPathNewPos = addPath.oldPos - diagonalPath;
          canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen;
        }
        const canRemove = removePath && removePath.oldPos + 1 < oldLen;
        if (!canAdd && !canRemove) {
          bestPath[diagonalPath] = void 0;
          continue;
        }
        if (!canRemove || canAdd && removePath.oldPos < addPath.oldPos) {
          basePath = this.addToPath(addPath, true, false, 0, options);
        } else {
          basePath = this.addToPath(removePath, false, true, 1, options);
        }
        newPos = this.extractCommon(basePath, newTokens, oldTokens, diagonalPath, options);
        if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) {
          return done(this.buildValues(basePath.lastComponent, newTokens, oldTokens)) || true;
        } else {
          bestPath[diagonalPath] = basePath;
          if (basePath.oldPos + 1 >= oldLen) {
            maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1);
          }
          if (newPos + 1 >= newLen) {
            minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1);
          }
        }
      }
      editLength++;
    };
    if (callback) {
      (function exec() {
        setTimeout(function() {
          if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) {
            return callback(void 0);
          }
          if (!execEditLength()) {
            exec();
          }
        }, 0);
      })();
    } else {
      while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) {
        const ret = execEditLength();
        if (ret) {
          return ret;
        }
      }
    }
  }
  addToPath(path6, added, removed, oldPosInc, options) {
    const last = path6.lastComponent;
    if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
      return {
        oldPos: path6.oldPos + oldPosInc,
        lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
      };
    } else {
      return {
        oldPos: path6.oldPos + oldPosInc,
        lastComponent: { count: 1, added, removed, previousComponent: last }
      };
    }
  }
  extractCommon(basePath, newTokens, oldTokens, diagonalPath, options) {
    const newLen = newTokens.length, oldLen = oldTokens.length;
    let oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0;
    while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(oldTokens[oldPos + 1], newTokens[newPos + 1], options)) {
      newPos++;
      oldPos++;
      commonCount++;
      if (options.oneChangePerToken) {
        basePath.lastComponent = { count: 1, previousComponent: basePath.lastComponent, added: false, removed: false };
      }
    }
    if (commonCount && !options.oneChangePerToken) {
      basePath.lastComponent = { count: commonCount, previousComponent: basePath.lastComponent, added: false, removed: false };
    }
    basePath.oldPos = oldPos;
    return newPos;
  }
  equals(left, right, options) {
    if (options.comparator) {
      return options.comparator(left, right);
    } else {
      return left === right || !!options.ignoreCase && left.toLowerCase() === right.toLowerCase();
    }
  }
  removeEmpty(array) {
    const ret = [];
    for (let i7 = 0; i7 < array.length; i7++) {
      if (array[i7]) {
        ret.push(array[i7]);
      }
    }
    return ret;
  }
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  castInput(value, options) {
    return value;
  }
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  tokenize(value, options) {
    return Array.from(value);
  }
  join(chars) {
    return chars.join("");
  }
  postProcess(changeObjects, options) {
    return changeObjects;
  }
  get useLongestToken() {
    return false;
  }
  buildValues(lastComponent, newTokens, oldTokens) {
    const components = [];
    let nextComponent;
    while (lastComponent) {
      components.push(lastComponent);
      nextComponent = lastComponent.previousComponent;
      delete lastComponent.previousComponent;
      lastComponent = nextComponent;
    }
    components.reverse();
    const componentLen = components.length;
    let componentPos = 0, newPos = 0, oldPos = 0;
    for (; componentPos < componentLen; componentPos++) {
      const component = components[componentPos];
      if (!component.removed) {
        if (!component.added && this.useLongestToken) {
          let value = newTokens.slice(newPos, newPos + component.count);
          value = value.map(function(value2, i7) {
            const oldValue = oldTokens[oldPos + i7];
            return oldValue.length > value2.length ? oldValue : value2;
          });
          component.value = this.join(value);
        } else {
          component.value = this.join(newTokens.slice(newPos, newPos + component.count));
        }
        newPos += component.count;
        if (!component.added) {
          oldPos += component.count;
        }
      } else {
        component.value = this.join(oldTokens.slice(oldPos, oldPos + component.count));
        oldPos += component.count;
      }
    }
    return components;
  }
};

// ../mini-lit/node_modules/diff/libesm/diff/line.js
init_process_shim();
var LineDiff = class extends Diff {
  constructor() {
    super(...arguments);
    this.tokenize = tokenize2;
  }
  equals(left, right, options) {
    if (options.ignoreWhitespace) {
      if (!options.newlineIsToken || !left.includes("\n")) {
        left = left.trim();
      }
      if (!options.newlineIsToken || !right.includes("\n")) {
        right = right.trim();
      }
    } else if (options.ignoreNewlineAtEof && !options.newlineIsToken) {
      if (left.endsWith("\n")) {
        left = left.slice(0, -1);
      }
      if (right.endsWith("\n")) {
        right = right.slice(0, -1);
      }
    }
    return super.equals(left, right, options);
  }
};
var lineDiff = new LineDiff();
function diffLines(oldStr, newStr, options) {
  return lineDiff.diff(oldStr, newStr, options);
}
function tokenize2(value, options) {
  if (options.stripTrailingCr) {
    value = value.replace(/\r\n/g, "\n");
  }
  const retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/);
  if (!linesAndNewlines[linesAndNewlines.length - 1]) {
    linesAndNewlines.pop();
  }
  for (let i7 = 0; i7 < linesAndNewlines.length; i7++) {
    const line = linesAndNewlines[i7];
    if (i7 % 2 && !options.newlineIsToken) {
      retLines[retLines.length - 1] += line;
    } else {
      retLines.push(line);
    }
  }
  return retLines;
}

// ../mini-lit/dist/Diff.js
var Diff2 = fc(({ oldText, newText, title, className = "" }) => {
  const parts = diffLines(oldText ?? "", newText ?? "");
  const lines = [];
  let addedCount = 0;
  let removedCount = 0;
  for (const part of parts) {
    const raw = part.value.split("\n");
    if (raw[raw.length - 1] === "")
      raw.pop();
    for (const line of raw) {
      const prefix = part.added ? "+" : part.removed ? "-" : " ";
      const rowClass = part.added ? "bg-emerald-500/15" : part.removed ? "bg-red-500/15" : "";
      if (part.added)
        addedCount++;
      if (part.removed)
        removedCount++;
      lines.push(b2`<div class="${rowClass}">
               <pre class="m-0 px-4 py-0.5 text-xs font-mono text-foreground">${prefix} ${line}</pre>
            </div>`);
    }
  }
  const content = b2` <div class="overflow-auto max-h-96">${lines}</div> `;
  if (title) {
    return b2`
         <div class="border border-border rounded-lg overflow-hidden ${className}">
            <div class="flex items-center justify-between px-3 py-1.5 bg-muted border-b border-border">
               <span class="text-xs text-muted-foreground font-mono">${title}</span>
               <span class="text-xs text-muted-foreground">
                  <span class="text-emerald-600">+${addedCount}</span>
                  <span class="mx-1">/</span>
                  <span class="text-red-600">-${removedCount}</span>
               </span>
            </div>
            ${content}
         </div>
      `;
  }
  return b2`<div class="border border-border rounded-lg overflow-hidden ${className}">${content}</div>`;
});

// ../pi-mono/packages/web-ui/dist/tools/artifacts/ArtifactPill.js
init_process_shim();
function ArtifactPill(filename, artifactsPanel) {
  const handleClick = (e9) => {
    if (!artifactsPanel)
      return;
    e9.preventDefault();
    e9.stopPropagation();
    artifactsPanel.openArtifact(filename);
  };
  return b2`
		<span
			class="inline-flex items-center gap-1 px-2 py-0.5 text-xs bg-muted/50 border border-border rounded ${artifactsPanel ? "cursor-pointer hover:bg-muted transition-colors" : ""}"
			@click=${artifactsPanel ? handleClick : null}
		>
			${icon(FileCode2, "sm")}
			<span class="text-foreground">${filename}</span>
		</span>
	`;
}

// ../pi-mono/packages/web-ui/dist/tools/artifacts/artifacts-tool-renderer.js
function getTextOutput(result) {
  if (!result)
    return "";
  return result.content?.filter((c6) => c6.type === "text").map((c6) => c6.text).join("\n") || "";
}
function getLanguageFromFilename(filename) {
  if (!filename)
    return "text";
  const ext2 = filename.split(".").pop()?.toLowerCase();
  const languageMap = {
    js: "javascript",
    jsx: "javascript",
    ts: "typescript",
    tsx: "typescript",
    html: "html",
    css: "css",
    scss: "scss",
    json: "json",
    py: "python",
    md: "markdown",
    svg: "xml",
    xml: "xml",
    yaml: "yaml",
    yml: "yaml",
    sh: "bash",
    bash: "bash",
    sql: "sql",
    java: "java",
    c: "c",
    cpp: "cpp",
    cs: "csharp",
    go: "go",
    rs: "rust",
    php: "php",
    rb: "ruby",
    swift: "swift",
    kt: "kotlin",
    r: "r"
  };
  return languageMap[ext2 || ""] || "text";
}
var ArtifactsToolRenderer = class {
  constructor(artifactsPanel) {
    this.artifactsPanel = artifactsPanel;
  }
  render(params, result, isStreaming) {
    const state = result ? result.isError ? "error" : "complete" : isStreaming ? "inprogress" : "complete";
    const contentRef = e5();
    const chevronRef = e5();
    const getCommandLabels = (command) => {
      const labels = {
        create: { streaming: i18n("Creating artifact"), complete: i18n("Created artifact") },
        update: { streaming: i18n("Updating artifact"), complete: i18n("Updated artifact") },
        rewrite: { streaming: i18n("Rewriting artifact"), complete: i18n("Rewrote artifact") },
        get: { streaming: i18n("Getting artifact"), complete: i18n("Got artifact") },
        delete: { streaming: i18n("Deleting artifact"), complete: i18n("Deleted artifact") },
        logs: { streaming: i18n("Getting logs"), complete: i18n("Got logs") }
      };
      return labels[command] || { streaming: i18n("Processing artifact"), complete: i18n("Processed artifact") };
    };
    const renderHeaderWithPill = (labelText, filename) => {
      if (filename) {
        return b2`<span>${labelText} ${ArtifactPill(filename, this.artifactsPanel)}</span>`;
      }
      return b2`<span>${labelText}</span>`;
    };
    if (result?.isError) {
      const command = params?.command;
      const filename = params?.filename;
      const labels = command ? getCommandLabels(command) : { streaming: i18n("Processing artifact"), complete: i18n("Processed artifact") };
      const headerText = labels.streaming;
      if (command === "create" || command === "update" || command === "rewrite") {
        const content = params?.content || "";
        const { old_str, new_str } = params || {};
        const isDiff = command === "update";
        const diffContent = old_str !== void 0 && new_str !== void 0 ? Diff2({ oldText: old_str, newText: new_str }) : "";
        const isHtml = filename?.endsWith(".html");
        return {
          content: b2`
					<div>
						${renderCollapsibleHeader(state, FileCode2, renderHeaderWithPill(headerText, filename), contentRef, chevronRef, false)}
						<div ${n5(contentRef)} class="max-h-0 overflow-hidden transition-all duration-300 space-y-3">
							${isDiff ? diffContent : content ? b2`<code-block .code=${content} language=${getLanguageFromFilename(filename)}></code-block>` : ""}
							${isHtml ? b2`<console-block .content=${getTextOutput(result) || i18n("An error occurred")} variant="error"></console-block>` : b2`<div class="text-sm text-destructive">${getTextOutput(result) || i18n("An error occurred")}</div>`}
						</div>
					</div>
				`,
          isCustom: false
        };
      }
      return {
        content: b2`
				<div class="space-y-3">
					${renderHeader(state, FileCode2, headerText)}
					<div class="text-sm text-destructive">${getTextOutput(result) || i18n("An error occurred")}</div>
				</div>
			`,
        isCustom: false
      };
    }
    if (result && params) {
      const { command, filename, content } = params;
      const labels = command ? getCommandLabels(command) : { streaming: i18n("Processing artifact"), complete: i18n("Processed artifact") };
      const headerText = labels.complete;
      if (command === "get") {
        const fileContent = getTextOutput(result) || i18n("(no output)");
        return {
          content: b2`
					<div>
						${renderCollapsibleHeader(state, FileCode2, renderHeaderWithPill(headerText, filename), contentRef, chevronRef, false)}
						<div ${n5(contentRef)} class="max-h-0 overflow-hidden transition-all duration-300">
							<code-block .code=${fileContent} language=${getLanguageFromFilename(filename)}></code-block>
						</div>
					</div>
				`,
          isCustom: false
        };
      }
      if (command === "logs") {
        const logs = getTextOutput(result) || i18n("(no output)");
        return {
          content: b2`
					<div>
						${renderCollapsibleHeader(state, FileCode2, renderHeaderWithPill(headerText, filename), contentRef, chevronRef, false)}
						<div ${n5(contentRef)} class="max-h-0 overflow-hidden transition-all duration-300">
							<console-block .content=${logs}></console-block>
						</div>
					</div>
				`,
          isCustom: false
        };
      }
      if (command === "create" || command === "rewrite") {
        const codeContent = content || "";
        const isHtml = filename?.endsWith(".html");
        const logs = getTextOutput(result) || "";
        return {
          content: b2`
					<div>
						${renderCollapsibleHeader(state, FileCode2, renderHeaderWithPill(headerText, filename), contentRef, chevronRef, false)}
						<div ${n5(contentRef)} class="max-h-0 overflow-hidden transition-all duration-300 space-y-3">
							${codeContent ? b2`<code-block .code=${codeContent} language=${getLanguageFromFilename(filename)}></code-block>` : ""}
							${isHtml && logs ? b2`<console-block .content=${logs}></console-block>` : ""}
						</div>
					</div>
				`,
          isCustom: false
        };
      }
      if (command === "update") {
        const isHtml = filename?.endsWith(".html");
        const logs = getTextOutput(result) || "";
        return {
          content: b2`
					<div>
						${renderCollapsibleHeader(state, FileCode2, renderHeaderWithPill(headerText, filename), contentRef, chevronRef, false)}
						<div ${n5(contentRef)} class="max-h-0 overflow-hidden transition-all duration-300 space-y-3">
							${Diff2({ oldText: params.old_str || "", newText: params.new_str || "" })}
							${isHtml && logs ? b2`<console-block .content=${logs}></console-block>` : ""}
						</div>
					</div>
				`,
          isCustom: false
        };
      }
      return {
        content: b2`
				<div class="space-y-3">
					${renderHeader(state, FileCode2, renderHeaderWithPill(headerText, filename))}
				</div>
			`,
        isCustom: false
      };
    }
    if (params) {
      const { command, filename, content, old_str, new_str } = params;
      if (!command) {
        return { content: renderHeader(state, FileCode2, i18n("Preparing artifact...")), isCustom: false };
      }
      const labels = getCommandLabels(command);
      const headerText = labels.streaming;
      switch (command) {
        case "create":
        case "rewrite":
          return {
            content: b2`
						<div>
							${renderCollapsibleHeader(state, FileCode2, renderHeaderWithPill(headerText, filename), contentRef, chevronRef, false)}
							<div ${n5(contentRef)} class="max-h-0 overflow-hidden transition-all duration-300">
								${content ? b2`<code-block .code=${content} language=${getLanguageFromFilename(filename)}></code-block>` : ""}
							</div>
						</div>
					`,
            isCustom: false
          };
        case "update":
          return {
            content: b2`
						<div>
							${renderCollapsibleHeader(state, FileCode2, renderHeaderWithPill(headerText, filename), contentRef, chevronRef, false)}
							<div ${n5(contentRef)} class="max-h-0 overflow-hidden transition-all duration-300">
								${old_str !== void 0 && new_str !== void 0 ? Diff2({ oldText: old_str, newText: new_str }) : ""}
							</div>
						</div>
					`,
            isCustom: false
          };
        case "get":
        case "logs":
          return {
            content: b2`
						<div>
							${renderCollapsibleHeader(state, FileCode2, renderHeaderWithPill(headerText, filename), contentRef, chevronRef, false)}
							<div ${n5(contentRef)} class="max-h-0 overflow-hidden transition-all duration-300"></div>
						</div>
					`,
            isCustom: false
          };
        default:
          return {
            content: b2`
						<div>
							${renderHeader(state, FileCode2, renderHeaderWithPill(headerText, filename))}
						</div>
					`,
            isCustom: false
          };
      }
    }
    return { content: renderHeader(state, FileCode2, i18n("Preparing artifact...")), isCustom: false };
  }
};

// ../pi-mono/packages/web-ui/dist/ChatPanel.js
var __decorate28 = function(decorators, target, key, desc) {
  var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc);
  else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8;
  return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8;
};
var BREAKPOINT = 800;
var ChatPanel = class ChatPanel2 extends i4 {
  constructor() {
    super(...arguments);
    this.hasArtifacts = false;
    this.artifactCount = 0;
    this.showArtifactsPanel = false;
    this.windowWidth = 0;
    this.resizeHandler = () => {
      this.windowWidth = window.innerWidth;
      this.requestUpdate();
    };
  }
  createRenderRoot() {
    return this;
  }
  connectedCallback() {
    super.connectedCallback();
    this.windowWidth = window.innerWidth;
    window.addEventListener("resize", this.resizeHandler);
    this.style.display = "flex";
    this.style.flexDirection = "column";
    this.style.height = "100%";
    this.style.minHeight = "0";
    requestAnimationFrame(() => {
      this.windowWidth = window.innerWidth;
      this.requestUpdate();
    });
  }
  disconnectedCallback() {
    super.disconnectedCallback();
    window.removeEventListener("resize", this.resizeHandler);
  }
  async setAgent(agent, config) {
    this.agent = agent;
    this.agentInterface = document.createElement("agent-interface");
    this.agentInterface.session = agent;
    this.agentInterface.enableAttachments = true;
    this.agentInterface.enableModelSelector = true;
    this.agentInterface.enableThinkingSelector = true;
    this.agentInterface.showThemeToggle = false;
    this.agentInterface.onApiKeyRequired = config?.onApiKeyRequired;
    this.agentInterface.onModelSelect = config?.onModelSelect;
    this.agentInterface.onBeforeSend = config?.onBeforeSend;
    this.agentInterface.onCostClick = config?.onCostClick;
    this.artifactsPanel = new ArtifactsPanel();
    this.artifactsPanel.agent = agent;
    if (config?.sandboxUrlProvider) {
      this.artifactsPanel.sandboxUrlProvider = config.sandboxUrlProvider;
    }
    registerToolRenderer("artifacts", new ArtifactsToolRenderer(this.artifactsPanel));
    const runtimeProvidersFactory = () => {
      const attachments = [];
      for (const message of this.agent.state.messages) {
        if (message.role === "user-with-attachments") {
          message.attachments?.forEach((a3) => {
            attachments.push(a3);
          });
        }
      }
      const providers = [];
      if (attachments.length > 0) {
        providers.push(new AttachmentsRuntimeProvider(attachments));
      }
      providers.push(new ArtifactsRuntimeProvider(this.artifactsPanel, this.agent, true));
      return providers;
    };
    this.artifactsPanel.onArtifactsChange = () => {
      const count = this.artifactsPanel?.artifacts?.size ?? 0;
      const created = count > this.artifactCount;
      this.hasArtifacts = count > 0;
      this.artifactCount = count;
      if (this.hasArtifacts && created) {
        this.showArtifactsPanel = true;
      }
      this.requestUpdate();
    };
    this.artifactsPanel.onClose = () => {
      this.showArtifactsPanel = false;
      this.requestUpdate();
    };
    this.artifactsPanel.onOpen = () => {
      this.showArtifactsPanel = true;
      this.requestUpdate();
    };
    const additionalTools = config?.toolsFactory?.(agent, this.agentInterface, this.artifactsPanel, runtimeProvidersFactory) || [];
    const tools = [this.artifactsPanel.tool, ...additionalTools];
    this.agent.setTools(tools);
    const originalCallback = this.artifactsPanel.onArtifactsChange;
    this.artifactsPanel.onArtifactsChange = void 0;
    await this.artifactsPanel.reconstructFromMessages(this.agent.state.messages);
    this.artifactsPanel.onArtifactsChange = originalCallback;
    this.hasArtifacts = this.artifactsPanel.artifacts.size > 0;
    this.artifactCount = this.artifactsPanel.artifacts.size;
    this.requestUpdate();
  }
  render() {
    if (!this.agent || !this.agentInterface) {
      return b2`<div class="flex items-center justify-center h-full">
				<div class="text-muted-foreground">No agent set</div>
			</div>`;
    }
    const isMobile = this.windowWidth < BREAKPOINT;
    if (this.artifactsPanel) {
      this.artifactsPanel.collapsed = !this.showArtifactsPanel;
      this.artifactsPanel.overlay = isMobile;
    }
    return b2`
			<div class="relative w-full h-full overflow-hidden flex">
				<div class="h-full" style="${!isMobile && this.showArtifactsPanel && this.hasArtifacts ? "width: 50%;" : "width: 100%;"}">
						${this.agentInterface}
					</div>

					<!-- Floating pill when artifacts exist and panel is collapsed -->
					${this.hasArtifacts && !this.showArtifactsPanel ? b2`
								<button
									class="absolute z-30 top-4 left-1/2 -translate-x-1/2 pointer-events-auto"
									@click=${() => {
      this.showArtifactsPanel = true;
      this.requestUpdate();
    }}
									title=${i18n("Show artifacts")}
								>
									${Badge(b2`
										<span class="inline-flex items-center gap-1">
											<span>${i18n("Artifacts")}</span>
											<span class="text-[10px] leading-none bg-primary-foreground/20 text-primary-foreground rounded px-1 font-mono tabular-nums">${this.artifactCount}</span>
										</span>
									`)}
								</button>
							` : ""}

				<div class="h-full ${isMobile ? "absolute inset-0 pointer-events-none" : ""}" style="${!isMobile ? !this.hasArtifacts || !this.showArtifactsPanel ? "display: none;" : "width: 50%;" : ""}">
					${this.artifactsPanel}
				</div>
			</div>
		`;
  }
};
__decorate28([
  r7()
], ChatPanel.prototype, "agent", void 0);
__decorate28([
  r7()
], ChatPanel.prototype, "agentInterface", void 0);
__decorate28([
  r7()
], ChatPanel.prototype, "artifactsPanel", void 0);
__decorate28([
  r7()
], ChatPanel.prototype, "hasArtifacts", void 0);
__decorate28([
  r7()
], ChatPanel.prototype, "artifactCount", void 0);
__decorate28([
  r7()
], ChatPanel.prototype, "showArtifactsPanel", void 0);
__decorate28([
  r7()
], ChatPanel.prototype, "windowWidth", void 0);
ChatPanel = __decorate28([
  t5("pi-chat-panel")
], ChatPanel);

// ../pi-mono/packages/web-ui/dist/components/CustomProviderCard.js
init_process_shim();
var __decorate29 = function(decorators, target, key, desc) {
  var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc);
  else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8;
  return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8;
};
var CustomProviderCard = class CustomProviderCard2 extends i4 {
  constructor() {
    super(...arguments);
    this.isAutoDiscovery = false;
  }
  createRenderRoot() {
    return this;
  }
  renderStatus() {
    if (!this.isAutoDiscovery) {
      return b2`
				<div class="text-xs text-muted-foreground mt-1">
					${i18n("Models")}: ${this.provider.models?.length || 0}
				</div>
			`;
    }
    if (!this.status)
      return b2``;
    const statusIcon = this.status.status === "connected" ? b2`<span class="text-green-500">●</span>` : this.status.status === "checking" ? b2`<span class="text-yellow-500">●</span>` : b2`<span class="text-red-500">●</span>`;
    const statusText = this.status.status === "connected" ? `${this.status.modelCount} ${i18n("models")}` : this.status.status === "checking" ? i18n("Checking...") : i18n("Disconnected");
    return b2`
			<div class="text-xs text-muted-foreground mt-1 flex items-center gap-1">
				${statusIcon} ${statusText}
			</div>
		`;
  }
  render() {
    return b2`
			<div class="border border-border rounded-lg p-4 space-y-2">
				<div class="flex items-center justify-between">
					<div class="flex-1">
						<div class="font-medium text-sm text-foreground">${this.provider.name}</div>
						<div class="text-xs text-muted-foreground mt-1">
							<span class="capitalize">${this.provider.type}</span>
							${this.provider.baseUrl ? b2` • ${this.provider.baseUrl}` : ""}
						</div>
						${this.renderStatus()}
					</div>
					<div class="flex gap-2">
						${this.isAutoDiscovery && this.onRefresh ? Button({
      onClick: () => this.onRefresh?.(this.provider),
      variant: "ghost",
      size: "sm",
      children: i18n("Refresh")
    }) : ""}
						${this.onEdit ? Button({
      onClick: () => this.onEdit?.(this.provider),
      variant: "ghost",
      size: "sm",
      children: i18n("Edit")
    }) : ""}
						${this.onDelete ? Button({
      onClick: () => this.onDelete?.(this.provider),
      variant: "ghost",
      size: "sm",
      children: i18n("Delete")
    }) : ""}
					</div>
				</div>
			</div>
		`;
  }
};
__decorate29([
  n6({ type: Object })
], CustomProviderCard.prototype, "provider", void 0);
__decorate29([
  n6({ type: Boolean })
], CustomProviderCard.prototype, "isAutoDiscovery", void 0);
__decorate29([
  n6({ type: Object })
], CustomProviderCard.prototype, "status", void 0);
__decorate29([
  n6()
], CustomProviderCard.prototype, "onRefresh", void 0);
__decorate29([
  n6()
], CustomProviderCard.prototype, "onEdit", void 0);
__decorate29([
  n6()
], CustomProviderCard.prototype, "onDelete", void 0);
CustomProviderCard = __decorate29([
  t5("custom-provider-card")
], CustomProviderCard);

// ../pi-mono/packages/web-ui/dist/components/ExpandableSection.js
init_process_shim();
var __decorate30 = function(decorators, target, key, desc) {
  var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc);
  else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8;
  return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8;
};
var ExpandableSection = class ExpandableSection2 extends i4 {
  constructor() {
    super(...arguments);
    this.defaultExpanded = false;
    this.expanded = false;
    this.capturedChildren = [];
  }
  createRenderRoot() {
    return this;
  }
  connectedCallback() {
    super.connectedCallback();
    this.capturedChildren = Array.from(this.childNodes);
    this.innerHTML = "";
    this.expanded = this.defaultExpanded;
  }
  render() {
    return b2`
			<div>
				<button
					@click=${() => {
      this.expanded = !this.expanded;
    }}
					class="flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground transition-colors w-full text-left"
				>
					${icon(this.expanded ? ChevronDown : ChevronRight, "sm")}
					<span>${this.summary}</span>
				</button>
				${this.expanded ? b2`<div class="mt-2">${this.capturedChildren}</div>` : ""}
			</div>
		`;
  }
};
__decorate30([
  n6()
], ExpandableSection.prototype, "summary", void 0);
__decorate30([
  n6({ type: Boolean })
], ExpandableSection.prototype, "defaultExpanded", void 0);
__decorate30([
  r7()
], ExpandableSection.prototype, "expanded", void 0);
ExpandableSection = __decorate30([
  t5("expandable-section")
], ExpandableSection);

// ../pi-mono/packages/web-ui/dist/components/ProviderKeyInput.js
init_process_shim();
var __decorate31 = function(decorators, target, key, desc) {
  var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc);
  else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8;
  return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8;
};
var TEST_MODELS = {
  anthropic: "claude-haiku-4-5",
  openai: "gpt-4o-mini",
  google: "gemini-2.5-flash",
  groq: "openai/gpt-oss-20b",
  openrouter: "z-ai/glm-4.6",
  "vercel-ai-gateway": "anthropic/claude-opus-4.5",
  cerebras: "gpt-oss-120b",
  xai: "grok-4-fast-non-reasoning",
  zai: "glm-4.5-air"
};
var ProviderKeyInput = class ProviderKeyInput2 extends i4 {
  constructor() {
    super(...arguments);
    this.provider = "";
    this.keyInput = "";
    this.testing = false;
    this.failed = false;
    this.hasKey = false;
    this.inputChanged = false;
  }
  createRenderRoot() {
    return this;
  }
  async connectedCallback() {
    super.connectedCallback();
    await this.checkKeyStatus();
  }
  async checkKeyStatus() {
    try {
      const key = await getAppStorage().providerKeys.get(this.provider);
      this.hasKey = !!key;
    } catch (error) {
      console.error("Failed to check key status:", error);
    }
  }
  async testApiKey(provider, apiKey) {
    try {
      const modelId = TEST_MODELS[provider];
      if (!modelId)
        return true;
      let model = getModel(provider, modelId);
      if (!model)
        return false;
      const proxyEnabled = await getAppStorage().settings.get("proxy.enabled");
      const proxyUrl = await getAppStorage().settings.get("proxy.url");
      model = applyProxyIfNeeded(model, apiKey, proxyEnabled ? proxyUrl || void 0 : void 0);
      const context = {
        messages: [{ role: "user", content: "Reply with: ok", timestamp: Date.now() }]
      };
      const result = await complete(model, context, {
        apiKey,
        maxTokens: 200
      });
      return result.stopReason === "stop";
    } catch (error) {
      console.error(`API key test failed for ${provider}:`, error);
      return false;
    }
  }
  async saveKey() {
    if (!this.keyInput)
      return;
    this.testing = true;
    this.failed = false;
    const success = await this.testApiKey(this.provider, this.keyInput);
    this.testing = false;
    if (success) {
      try {
        await getAppStorage().providerKeys.set(this.provider, this.keyInput);
        this.hasKey = true;
        this.inputChanged = false;
        this.requestUpdate();
      } catch (error) {
        console.error("Failed to save API key:", error);
        this.failed = true;
        setTimeout(() => {
          this.failed = false;
          this.requestUpdate();
        }, 5e3);
      }
    } else {
      this.failed = true;
      setTimeout(() => {
        this.failed = false;
        this.requestUpdate();
      }, 5e3);
    }
  }
  render() {
    return b2`
			<div class="space-y-3">
				<div class="flex items-center gap-2">
					<span class="text-sm font-medium capitalize text-foreground">${this.provider}</span>
					${this.testing ? Badge({ children: i18n("Testing..."), variant: "secondary" }) : this.hasKey ? b2`<span class="text-green-600 dark:text-green-400">✓</span>` : ""}
					${this.failed ? Badge({ children: i18n("\u2717 Invalid"), variant: "destructive" }) : ""}
				</div>
				<div class="flex items-center gap-2">
					${Input({
      type: "password",
      placeholder: this.hasKey ? "\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022" : i18n("Enter API key"),
      value: this.keyInput,
      onInput: (e9) => {
        this.keyInput = e9.target.value;
        this.inputChanged = true;
        this.requestUpdate();
      },
      className: "flex-1"
    })}
					${Button({
      onClick: () => this.saveKey(),
      variant: "default",
      size: "sm",
      disabled: !this.keyInput || this.testing || this.hasKey && !this.inputChanged,
      children: i18n("Save")
    })}
				</div>
			</div>
		`;
  }
};
__decorate31([
  n6()
], ProviderKeyInput.prototype, "provider", void 0);
__decorate31([
  r7()
], ProviderKeyInput.prototype, "keyInput", void 0);
__decorate31([
  r7()
], ProviderKeyInput.prototype, "testing", void 0);
__decorate31([
  r7()
], ProviderKeyInput.prototype, "failed", void 0);
__decorate31([
  r7()
], ProviderKeyInput.prototype, "hasKey", void 0);
__decorate31([
  r7()
], ProviderKeyInput.prototype, "inputChanged", void 0);
ProviderKeyInput = __decorate31([
  t5("provider-key-input")
], ProviderKeyInput);

// ../pi-mono/packages/web-ui/dist/components/sandbox/FileDownloadRuntimeProvider.js
init_process_shim();

// ../pi-mono/packages/web-ui/dist/dialogs/ApiKeyPromptDialog.js
init_process_shim();
var __decorate32 = function(decorators, target, key, desc) {
  var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc);
  else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8;
  return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8;
};
var ApiKeyPromptDialog_1;
var ApiKeyPromptDialog = ApiKeyPromptDialog_1 = class ApiKeyPromptDialog2 extends DialogBase {
  constructor() {
    super(...arguments);
    this.provider = "";
    this.modalWidth = "min(500px, 90vw)";
    this.modalHeight = "auto";
  }
  static async prompt(provider) {
    const dialog = new ApiKeyPromptDialog_1();
    dialog.provider = provider;
    dialog.open();
    return new Promise((resolve) => {
      dialog.resolvePromise = resolve;
    });
  }
  async connectedCallback() {
    super.connectedCallback();
    const checkInterval = setInterval(async () => {
      const hasKey = !!await getAppStorage().providerKeys.get(this.provider);
      if (hasKey) {
        clearInterval(checkInterval);
        if (this.resolvePromise) {
          this.resolvePromise(true);
          this.resolvePromise = void 0;
        }
        this.close();
      }
    }, 500);
    this.unsubscribe = () => clearInterval(checkInterval);
  }
  disconnectedCallback() {
    super.disconnectedCallback();
    if (this.unsubscribe) {
      this.unsubscribe();
      this.unsubscribe = void 0;
    }
  }
  close() {
    super.close();
    if (this.resolvePromise) {
      this.resolvePromise(false);
    }
  }
  renderContent() {
    return b2`
			${DialogContent({
      children: b2`
					${DialogHeader({
        title: i18n("API Key Required")
      })}
					<provider-key-input .provider=${this.provider}></provider-key-input>
				`
    })}
		`;
  }
};
__decorate32([
  r7()
], ApiKeyPromptDialog.prototype, "provider", void 0);
ApiKeyPromptDialog = ApiKeyPromptDialog_1 = __decorate32([
  t5("api-key-prompt-dialog")
], ApiKeyPromptDialog);

// ../pi-mono/packages/web-ui/dist/dialogs/PersistentStorageDialog.js
init_process_shim();
var __decorate33 = function(decorators, target, key, desc) {
  var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc);
  else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8;
  return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8;
};
var PersistentStorageDialog_1;
var PersistentStorageDialog = PersistentStorageDialog_1 = class PersistentStorageDialog2 extends DialogBase {
  constructor() {
    super(...arguments);
    this.requesting = false;
    this.modalWidth = "min(500px, 90vw)";
    this.modalHeight = "auto";
  }
  /**
   * Request persistent storage permission.
   * Returns true if browser granted persistent storage, false otherwise.
   */
  static async request() {
    if (navigator.storage?.persisted) {
      const alreadyPersisted = await navigator.storage.persisted();
      if (alreadyPersisted) {
        console.log("\u2713 Persistent storage already granted");
        return true;
      }
    }
    const dialog = new PersistentStorageDialog_1();
    dialog.open();
    const userApproved = await new Promise((resolve) => {
      dialog.resolvePromise = resolve;
    });
    if (!userApproved) {
      console.warn("\u26A0 User declined persistent storage - sessions may be lost");
      return false;
    }
    if (!navigator.storage?.persist) {
      console.warn("\u26A0 Persistent storage API not available");
      return false;
    }
    try {
      const granted = await navigator.storage.persist();
      if (granted) {
        console.log("\u2713 Persistent storage granted - sessions will be preserved");
      } else {
        console.warn("\u26A0 Browser denied persistent storage - sessions may be lost under storage pressure");
      }
      return granted;
    } catch (error) {
      console.error("Failed to request persistent storage:", error);
      return false;
    }
  }
  handleGrant() {
    if (this.resolvePromise) {
      this.resolvePromise(true);
      this.resolvePromise = void 0;
    }
    this.close();
  }
  handleDeny() {
    if (this.resolvePromise) {
      this.resolvePromise(false);
      this.resolvePromise = void 0;
    }
    this.close();
  }
  close() {
    super.close();
    if (this.resolvePromise) {
      this.resolvePromise(false);
    }
  }
  renderContent() {
    return b2`
			${DialogContent({
      children: b2`
					${DialogHeader({
        title: i18n("Storage Permission Required"),
        description: i18n("This app needs persistent storage to save your conversations")
      })}

					<div class="mt-4 flex flex-col gap-4">
						<div class="flex gap-3 p-4 bg-warning/10 border border-warning/20 rounded-lg">
							<div class="flex-shrink-0 text-warning">
								<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
									<path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"></path>
									<line x1="12" y1="9" x2="12" y2="13"></line>
									<line x1="12" y1="17" x2="12.01" y2="17"></line>
								</svg>
							</div>
							<div class="text-sm">
								<p class="font-medium text-foreground mb-1">${i18n("Why is this needed?")}</p>
								<p class="text-muted-foreground">
									${i18n("Without persistent storage, your browser may delete saved conversations when it needs disk space. Granting this permission ensures your chat history is preserved.")}
								</p>
							</div>
						</div>

						<div class="text-sm text-muted-foreground">
							<p class="mb-2">${i18n("What this means:")}</p>
							<ul class="list-disc list-inside space-y-1 ml-2">
								<li>${i18n("Your conversations will be saved locally in your browser")}</li>
								<li>${i18n("Data will not be deleted automatically to free up space")}</li>
								<li>${i18n("You can still manually clear data at any time")}</li>
								<li>${i18n("No data is sent to external servers")}</li>
							</ul>
						</div>
					</div>

					<div class="mt-6 flex gap-3 justify-end">
						${Button({
        variant: "outline",
        onClick: () => this.handleDeny(),
        disabled: this.requesting,
        children: i18n("Continue Anyway")
      })}
						${Button({
        variant: "default",
        onClick: () => this.handleGrant(),
        disabled: this.requesting,
        children: this.requesting ? i18n("Requesting...") : i18n("Grant Permission")
      })}
					</div>
				`
    })}
		`;
  }
};
__decorate33([
  r7()
], PersistentStorageDialog.prototype, "requesting", void 0);
PersistentStorageDialog = PersistentStorageDialog_1 = __decorate33([
  t5("persistent-storage-dialog")
], PersistentStorageDialog);

// ../pi-mono/packages/web-ui/dist/dialogs/ProvidersModelsTab.js
init_process_shim();

// ../pi-mono/packages/web-ui/dist/dialogs/CustomProviderDialog.js
init_process_shim();

// ../mini-lit/dist/Input.js
init_process_shim();
var Input2 = fc(({ id = "", type = "text", size = "md", value = "", placeholder = "", label = "", error = "", disabled = false, readonly = false, required = false, name = "", autocomplete = "", min, max, step, inputRef, onInput, onChange, onKeyDown, onKeyUp, className = "" }) => {
  const sizeClasses2 = {
    sm: "h-8 px-3 py-1 text-sm",
    md: "h-9 px-3 py-1 text-sm md:text-sm",
    lg: "h-10 px-4 py-1 text-base"
  };
  const baseClasses = "flex w-full min-w-0 rounded-md border bg-transparent text-foreground shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium";
  const interactionClasses = "placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground";
  const focusClasses = "focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]";
  const darkClasses = "dark:bg-input/30";
  const stateClasses = error ? "border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40" : "border-input";
  const disabledClasses = "disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50";
  const handleInput = (e9) => {
    onInput?.(e9);
  };
  const handleChange = (e9) => {
    onChange?.(e9);
  };
  return b2`
         <div class="flex flex-col gap-1.5 ${className}">
            ${label ? b2`
                    <label class="text-sm font-medium text-foreground">
                       ${label} ${required ? b2`<span class="text-destructive">${i18n("*")}</span>` : ""}
                    </label>
                 ` : ""}
            <input
               id=${id}
               type="${type}"
               class="${baseClasses} ${sizeClasses2[size]} ${interactionClasses} ${focusClasses} ${darkClasses} ${stateClasses} ${disabledClasses}"
               .value=${value}
               placeholder="${placeholder}"
               ?disabled=${disabled}
               ?readonly=${readonly}
               ?required=${required}
               ?aria-invalid=${!!error}
               name="${name}"
               autocomplete="${autocomplete}"
               min="${min ?? ""}"
               max="${max ?? ""}"
               step="${step ?? ""}"
               @input=${handleInput}
               @change=${handleChange}
               @keydown=${onKeyDown}
               @keyup=${onKeyUp}
               ${inputRef ? n5(inputRef) : ""}
            />
            ${error ? b2`<span class="text-sm text-destructive">${error}</span>` : ""}
         </div>
      `;
});

// ../mini-lit/dist/Label.js
init_process_shim();
var _Label = fc(({ htmlFor = "", required = false, className = "", children }) => {
  const baseClasses = "inline-block text-sm font-medium leading-none text-foreground peer-disabled:cursor-not-allowed peer-disabled:opacity-70 mb-2";
  return b2`
      <label for="${htmlFor}" class="${baseClasses} ${className}">
         ${children} ${required ? b2`<span class="text-destructive ml-1">${i18n("*")}</span>` : ""}
      </label>
   `;
});
function Label(propsOrChildren, htmlFor = "", required = false, className = "") {
  if (typeof propsOrChildren === "object" && propsOrChildren !== null && "children" in propsOrChildren) {
    return _Label(propsOrChildren);
  }
  return _Label({ children: propsOrChildren, htmlFor, required, className });
}

// ../pi-mono/packages/web-ui/dist/dialogs/CustomProviderDialog.js
var __decorate34 = function(decorators, target, key, desc) {
  var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc);
  else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8;
  return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8;
};
var CustomProviderDialog = class _CustomProviderDialog extends DialogBase {
  constructor() {
    super(...arguments);
    this.name = "";
    this.type = "openai-completions";
    this.baseUrl = "";
    this.apiKey = "";
    this.testing = false;
    this.testError = "";
    this.discoveredModels = [];
    this.modalWidth = "min(800px, 90vw)";
    this.modalHeight = "min(700px, 90vh)";
  }
  static async open(provider, initialType, onSave) {
    const dialog = new _CustomProviderDialog();
    dialog.provider = provider;
    dialog.initialType = initialType;
    dialog.onSaveCallback = onSave;
    document.body.appendChild(dialog);
    dialog.initializeFromProvider();
    dialog.open();
    dialog.requestUpdate();
  }
  initializeFromProvider() {
    if (this.provider) {
      this.name = this.provider.name;
      this.type = this.provider.type;
      this.baseUrl = this.provider.baseUrl;
      this.apiKey = this.provider.apiKey || "";
      this.discoveredModels = this.provider.models || [];
    } else {
      this.name = "";
      this.type = this.initialType || "openai-completions";
      this.baseUrl = "";
      this.updateDefaultBaseUrl();
      this.apiKey = "";
      this.discoveredModels = [];
    }
    this.testError = "";
    this.testing = false;
  }
  updateDefaultBaseUrl() {
    if (this.baseUrl)
      return;
    const defaults3 = {
      ollama: "http://localhost:11434",
      "llama.cpp": "http://localhost:8080",
      vllm: "http://localhost:8000",
      lmstudio: "http://localhost:1234",
      "openai-completions": "",
      "openai-responses": "",
      "anthropic-messages": ""
    };
    this.baseUrl = defaults3[this.type] || "";
  }
  isAutoDiscoveryType() {
    return this.type === "ollama" || this.type === "llama.cpp" || this.type === "vllm" || this.type === "lmstudio";
  }
  async testConnection() {
    if (!this.isAutoDiscoveryType())
      return;
    this.testing = true;
    this.testError = "";
    this.discoveredModels = [];
    try {
      const models2 = await discoverModels(this.type, this.baseUrl, this.apiKey || void 0);
      this.discoveredModels = models2.map((model) => ({
        ...model,
        provider: this.name || this.type
      }));
      this.testError = "";
    } catch (error) {
      this.testError = error instanceof Error ? error.message : String(error);
      this.discoveredModels = [];
    } finally {
      this.testing = false;
      this.requestUpdate();
    }
  }
  async save() {
    if (!this.name || !this.baseUrl) {
      alert(i18n("Please fill in all required fields"));
      return;
    }
    try {
      const storage2 = getAppStorage();
      const provider = {
        id: this.provider?.id || crypto.randomUUID(),
        name: this.name,
        type: this.type,
        baseUrl: this.baseUrl,
        apiKey: this.apiKey || void 0,
        models: this.isAutoDiscoveryType() ? void 0 : this.provider?.models || []
      };
      await storage2.customProviders.set(provider);
      if (this.onSaveCallback) {
        this.onSaveCallback();
      }
      this.close();
    } catch (error) {
      console.error("Failed to save provider:", error);
      alert(i18n("Failed to save provider"));
    }
  }
  renderContent() {
    const providerTypes = [
      { value: "ollama", label: "Ollama (auto-discovery)" },
      { value: "llama.cpp", label: "llama.cpp (auto-discovery)" },
      { value: "vllm", label: "vLLM (auto-discovery)" },
      { value: "lmstudio", label: "LM Studio (auto-discovery)" },
      { value: "openai-completions", label: "OpenAI Completions Compatible" },
      { value: "openai-responses", label: "OpenAI Responses Compatible" },
      { value: "anthropic-messages", label: "Anthropic Messages Compatible" }
    ];
    return b2`
			<div class="flex flex-col h-full overflow-hidden">
				<div class="p-6 flex-shrink-0 border-b border-border">
					<h2 class="text-lg font-semibold text-foreground">
						${this.provider ? i18n("Edit Provider") : i18n("Add Provider")}
					</h2>
				</div>

				<div class="flex-1 overflow-y-auto p-6">
					<div class="flex flex-col gap-4">
						<div class="flex flex-col gap-2">
							${Label({ htmlFor: "provider-name", children: i18n("Provider Name") })}
							${Input2({
      value: this.name,
      placeholder: i18n("e.g., My Ollama Server"),
      onInput: (e9) => {
        this.name = e9.target.value;
        this.requestUpdate();
      }
    })}
						</div>

						<div class="flex flex-col gap-2">
							${Label({ htmlFor: "provider-type", children: i18n("Provider Type") })}
							${Select({
      value: this.type,
      options: providerTypes.map((pt) => ({
        value: pt.value,
        label: pt.label
      })),
      onChange: (value) => {
        this.type = value;
        this.baseUrl = "";
        this.updateDefaultBaseUrl();
        this.requestUpdate();
      },
      width: "100%"
    })}
						</div>

						<div class="flex flex-col gap-2">
							${Label({ htmlFor: "base-url", children: i18n("Base URL") })}
							${Input2({
      value: this.baseUrl,
      placeholder: i18n("e.g., http://localhost:11434"),
      onInput: (e9) => {
        this.baseUrl = e9.target.value;
        this.requestUpdate();
      }
    })}
						</div>

						<div class="flex flex-col gap-2">
							${Label({ htmlFor: "api-key", children: i18n("API Key (Optional)") })}
							${Input2({
      type: "password",
      value: this.apiKey,
      placeholder: i18n("Leave empty if not required"),
      onInput: (e9) => {
        this.apiKey = e9.target.value;
        this.requestUpdate();
      }
    })}
						</div>

						${this.isAutoDiscoveryType() ? b2`
									<div class="flex flex-col gap-2">
										${Button({
      onClick: () => this.testConnection(),
      variant: "outline",
      disabled: this.testing || !this.baseUrl,
      children: this.testing ? i18n("Testing...") : i18n("Test Connection")
    })}
										${this.testError ? b2` <div class="text-sm text-destructive">${this.testError}</div> ` : ""}
										${this.discoveredModels.length > 0 ? b2`
													<div class="text-sm text-muted-foreground">
														${i18n("Discovered")} ${this.discoveredModels.length} ${i18n("models")}:
														<ul class="list-disc list-inside mt-2">
															${this.discoveredModels.slice(0, 5).map((model) => b2`<li>${model.name}</li>`)}
															${this.discoveredModels.length > 5 ? b2`<li>...${i18n("and")} ${this.discoveredModels.length - 5} ${i18n("more")}</li>` : ""}
														</ul>
													</div>
												` : ""}
									</div>
								` : b2` <div class="text-sm text-muted-foreground">
									${i18n("For manual provider types, add models after saving the provider.")}
								</div>`}
					</div>
				</div>

				<div class="p-6 flex-shrink-0 border-t border-border flex justify-end gap-2">
					${Button({
      onClick: () => this.close(),
      variant: "ghost",
      children: i18n("Cancel")
    })}
					${Button({
      onClick: () => this.save(),
      variant: "default",
      disabled: !this.name || !this.baseUrl,
      children: i18n("Save")
    })}
				</div>
			</div>
		`;
  }
};
__decorate34([
  r7()
], CustomProviderDialog.prototype, "name", void 0);
__decorate34([
  r7()
], CustomProviderDialog.prototype, "type", void 0);
__decorate34([
  r7()
], CustomProviderDialog.prototype, "baseUrl", void 0);
__decorate34([
  r7()
], CustomProviderDialog.prototype, "apiKey", void 0);
__decorate34([
  r7()
], CustomProviderDialog.prototype, "testing", void 0);
__decorate34([
  r7()
], CustomProviderDialog.prototype, "testError", void 0);
__decorate34([
  r7()
], CustomProviderDialog.prototype, "discoveredModels", void 0);
customElements.define("custom-provider-dialog", CustomProviderDialog);

// ../pi-mono/packages/web-ui/dist/dialogs/SettingsDialog.js
init_process_shim();
var __decorate35 = function(decorators, target, key, desc) {
  var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc);
  else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8;
  return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8;
};
var SettingsDialog_1;
var SettingsTab = class extends i4 {
  createRenderRoot() {
    return this;
  }
};
var ApiKeysTab = class ApiKeysTab2 extends SettingsTab {
  getTabName() {
    return i18n("API Keys");
  }
  render() {
    const providers = getProviders();
    return b2`
			<div class="flex flex-col gap-6">
				<p class="text-sm text-muted-foreground">
					${i18n("Configure API keys for LLM providers. Keys are stored locally in your browser.")}
				</p>
				${providers.map((provider) => b2`<provider-key-input .provider=${provider}></provider-key-input>`)}
			</div>
		`;
  }
};
ApiKeysTab = __decorate35([
  t5("api-keys-tab")
], ApiKeysTab);
var ProxyTab = class ProxyTab2 extends SettingsTab {
  constructor() {
    super(...arguments);
    this.proxyEnabled = false;
    this.proxyUrl = "http://localhost:3001";
  }
  async connectedCallback() {
    super.connectedCallback();
    try {
      const storage2 = getAppStorage();
      const enabled = await storage2.settings.get("proxy.enabled");
      const url = await storage2.settings.get("proxy.url");
      if (enabled !== null)
        this.proxyEnabled = enabled;
      if (url !== null)
        this.proxyUrl = url;
    } catch (error) {
      console.error("Failed to load proxy settings:", error);
    }
  }
  async saveProxySettings() {
    try {
      const storage2 = getAppStorage();
      await storage2.settings.set("proxy.enabled", this.proxyEnabled);
      await storage2.settings.set("proxy.url", this.proxyUrl);
    } catch (error) {
      console.error("Failed to save proxy settings:", error);
    }
  }
  getTabName() {
    return i18n("Proxy");
  }
  render() {
    return b2`
			<div class="flex flex-col gap-4">
				<p class="text-sm text-muted-foreground">
					${i18n("Allows browser-based apps to bypass CORS restrictions when calling LLM providers. Required for Z-AI and Anthropic with OAuth token.")}
				</p>

				<div class="flex items-center justify-between">
					<span class="text-sm font-medium text-foreground">${i18n("Use CORS Proxy")}</span>
					${Switch({
      checked: this.proxyEnabled,
      onChange: (checked) => {
        this.proxyEnabled = checked;
        this.saveProxySettings();
      }
    })}
				</div>

				<div class="space-y-2">
					${Label({ children: i18n("Proxy URL") })}
					${Input2({
      type: "text",
      value: this.proxyUrl,
      disabled: !this.proxyEnabled,
      onInput: (e9) => {
        this.proxyUrl = e9.target.value;
      },
      onChange: () => this.saveProxySettings()
    })}
					<p class="text-xs text-muted-foreground">
						${i18n("Format: The proxy must accept requests as <proxy-url>/?url=<target-url>")}
					</p>
				</div>
			</div>
		`;
  }
};
__decorate35([
  r7()
], ProxyTab.prototype, "proxyEnabled", void 0);
__decorate35([
  r7()
], ProxyTab.prototype, "proxyUrl", void 0);
ProxyTab = __decorate35([
  t5("proxy-tab")
], ProxyTab);
var SettingsDialog = SettingsDialog_1 = class SettingsDialog2 extends i4 {
  constructor() {
    super(...arguments);
    this.tabs = [];
    this.isOpen = false;
    this.activeTabIndex = 0;
  }
  createRenderRoot() {
    return this;
  }
  static async open(tabs, onClose) {
    const dialog = new SettingsDialog_1();
    dialog.tabs = tabs;
    dialog.onCloseCallback = onClose;
    dialog.isOpen = true;
    document.body.appendChild(dialog);
  }
  setActiveTab(index) {
    this.activeTabIndex = index;
  }
  renderSidebarItem(tab, index) {
    const isActive = this.activeTabIndex === index;
    return b2`
			<button
				class="w-full text-left px-4 py-3 rounded-md transition-colors ${isActive ? "bg-secondary text-foreground font-medium" : "text-muted-foreground hover:bg-secondary/50 hover:text-foreground"}"
				@click=${() => this.setActiveTab(index)}
			>
				${tab.getTabName()}
			</button>
		`;
  }
  renderMobileTab(tab, index) {
    const isActive = this.activeTabIndex === index;
    return b2`
			<button
				class="px-3 py-2 text-sm font-medium transition-colors ${isActive ? "border-b-2 border-primary text-foreground" : "text-muted-foreground hover:text-foreground"}"
				@click=${() => this.setActiveTab(index)}
			>
				${tab.getTabName()}
			</button>
		`;
  }
  render() {
    if (this.tabs.length === 0) {
      return b2``;
    }
    return Dialog({
      isOpen: this.isOpen,
      onClose: () => {
        this.isOpen = false;
        this.remove();
        this.onCloseCallback?.();
      },
      width: "min(1000px, 90vw)",
      height: "min(800px, 90vh)",
      backdropClassName: "bg-black/50 backdrop-blur-sm",
      children: b2`
				${DialogContent({
        className: "h-full p-6",
        children: b2`
						<div class="flex flex-col h-full overflow-hidden">
							<!-- Header -->
							<div class="pb-4 flex-shrink-0">${DialogHeader({ title: i18n("Settings") })}</div>

							<!-- Mobile Tabs -->
							<div class="md:hidden flex flex-shrink-0 pb-4">
								${this.tabs.map((tab, index) => this.renderMobileTab(tab, index))}
							</div>

							<!-- Layout -->
							<div class="flex flex-1 overflow-hidden">
								<!-- Sidebar (desktop only) -->
								<div class="hidden md:block w-64 flex-shrink-0 space-y-1">
									${this.tabs.map((tab, index) => this.renderSidebarItem(tab, index))}
								</div>

								<!-- Content -->
								<div class="flex-1 overflow-y-auto md:pl-6">
									${this.tabs.map((tab, index) => b2`<div style="display: ${this.activeTabIndex === index ? "block" : "none"}">${tab}</div>`)}
								</div>
							</div>
						</div>
					`
      })}
			`
    });
  }
};
__decorate35([
  n6({ type: Array, attribute: false })
], SettingsDialog.prototype, "tabs", void 0);
__decorate35([
  r7()
], SettingsDialog.prototype, "isOpen", void 0);
__decorate35([
  r7()
], SettingsDialog.prototype, "activeTabIndex", void 0);
SettingsDialog = SettingsDialog_1 = __decorate35([
  t5("settings-dialog")
], SettingsDialog);

// ../pi-mono/packages/web-ui/dist/dialogs/ProvidersModelsTab.js
var __decorate36 = function(decorators, target, key, desc) {
  var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc);
  else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8;
  return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8;
};
var ProvidersModelsTab = class ProvidersModelsTab2 extends SettingsTab {
  constructor() {
    super(...arguments);
    this.customProviders = [];
    this.providerStatus = /* @__PURE__ */ new Map();
  }
  async connectedCallback() {
    super.connectedCallback();
    await this.loadCustomProviders();
  }
  async loadCustomProviders() {
    try {
      const storage2 = getAppStorage();
      this.customProviders = await storage2.customProviders.getAll();
      for (const provider of this.customProviders) {
        const isAutoDiscovery = provider.type === "ollama" || provider.type === "llama.cpp" || provider.type === "vllm" || provider.type === "lmstudio";
        if (isAutoDiscovery) {
          this.checkProviderStatus(provider);
        }
      }
    } catch (error) {
      console.error("Failed to load custom providers:", error);
    }
  }
  getTabName() {
    return "Providers & Models";
  }
  async checkProviderStatus(provider) {
    this.providerStatus.set(provider.id, { modelCount: 0, status: "checking" });
    this.requestUpdate();
    try {
      const models2 = await discoverModels(provider.type, provider.baseUrl, provider.apiKey);
      this.providerStatus.set(provider.id, { modelCount: models2.length, status: "connected" });
    } catch (_error) {
      this.providerStatus.set(provider.id, { modelCount: 0, status: "disconnected" });
    }
    this.requestUpdate();
  }
  renderKnownProviders() {
    const providers = getProviders();
    return b2`
			<div class="flex flex-col gap-6">
				<div>
					<h3 class="text-sm font-semibold text-foreground mb-2">Cloud Providers</h3>
					<p class="text-sm text-muted-foreground mb-4">
						Cloud LLM providers with predefined models. API keys are stored locally in your browser.
					</p>
				</div>
				<div class="flex flex-col gap-6">
					${providers.map((provider) => b2` <provider-key-input .provider=${provider}></provider-key-input> `)}
				</div>
			</div>
		`;
  }
  renderCustomProviders() {
    const isAutoDiscovery = (type) => type === "ollama" || type === "llama.cpp" || type === "vllm" || type === "lmstudio";
    return b2`
			<div class="flex flex-col gap-6">
				<div class="flex items-center justify-between">
					<div>
						<h3 class="text-sm font-semibold text-foreground mb-2">Custom Providers</h3>
						<p class="text-sm text-muted-foreground">
							User-configured servers with auto-discovered or manually defined models.
						</p>
					</div>
					${Select({
      placeholder: i18n("Add Provider"),
      options: [
        { value: "ollama", label: "Ollama" },
        { value: "llama.cpp", label: "llama.cpp" },
        { value: "vllm", label: "vLLM" },
        { value: "lmstudio", label: "LM Studio" },
        { value: "openai-completions", label: i18n("OpenAI Completions Compatible") },
        { value: "openai-responses", label: i18n("OpenAI Responses Compatible") },
        { value: "anthropic-messages", label: i18n("Anthropic Messages Compatible") }
      ],
      onChange: (value) => this.addCustomProvider(value),
      variant: "outline",
      size: "sm"
    })}
				</div>

				${this.customProviders.length === 0 ? b2`
							<div class="text-sm text-muted-foreground text-center py-8">
								No custom providers configured. Click 'Add Provider' to get started.
							</div>
						` : b2`
							<div class="flex flex-col gap-4">
								${this.customProviders.map((provider) => b2`
										<custom-provider-card
											.provider=${provider}
											.isAutoDiscovery=${isAutoDiscovery(provider.type)}
											.status=${this.providerStatus.get(provider.id)}
											.onRefresh=${(p4) => this.refreshProvider(p4)}
											.onEdit=${(p4) => this.editProvider(p4)}
											.onDelete=${(p4) => this.deleteProvider(p4)}
										></custom-provider-card>
									`)}
							</div>
						`}
			</div>
		`;
  }
  async addCustomProvider(type) {
    await CustomProviderDialog.open(void 0, type, async () => {
      await this.loadCustomProviders();
      this.requestUpdate();
    });
  }
  async editProvider(provider) {
    await CustomProviderDialog.open(provider, void 0, async () => {
      await this.loadCustomProviders();
      this.requestUpdate();
    });
  }
  async refreshProvider(provider) {
    this.providerStatus.set(provider.id, { modelCount: 0, status: "checking" });
    this.requestUpdate();
    try {
      const models2 = await discoverModels(provider.type, provider.baseUrl, provider.apiKey);
      this.providerStatus.set(provider.id, { modelCount: models2.length, status: "connected" });
      this.requestUpdate();
      console.log(`Refreshed ${models2.length} models from ${provider.name}`);
    } catch (error) {
      this.providerStatus.set(provider.id, { modelCount: 0, status: "disconnected" });
      this.requestUpdate();
      console.error(`Failed to refresh provider ${provider.name}:`, error);
      alert(`Failed to refresh provider: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
  async deleteProvider(provider) {
    if (!confirm("Are you sure you want to delete this provider?")) {
      return;
    }
    try {
      const storage2 = getAppStorage();
      await storage2.customProviders.delete(provider.id);
      await this.loadCustomProviders();
      this.requestUpdate();
    } catch (error) {
      console.error("Failed to delete provider:", error);
    }
  }
  render() {
    return b2`
			<div class="flex flex-col gap-8">
				${this.renderKnownProviders()}
				<div class="border-t border-border"></div>
				${this.renderCustomProviders()}
			</div>
		`;
  }
};
__decorate36([
  r7()
], ProvidersModelsTab.prototype, "customProviders", void 0);
__decorate36([
  r7()
], ProvidersModelsTab.prototype, "providerStatus", void 0);
ProvidersModelsTab = __decorate36([
  t5("providers-models-tab")
], ProvidersModelsTab);

// ../pi-mono/packages/web-ui/dist/dialogs/SessionListDialog.js
init_process_shim();
var __decorate37 = function(decorators, target, key, desc) {
  var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc);
  else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8;
  return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8;
};
var SessionListDialog_1;
var SessionListDialog = SessionListDialog_1 = class SessionListDialog2 extends DialogBase {
  constructor() {
    super(...arguments);
    this.sessions = [];
    this.loading = true;
    this.deletedSessions = /* @__PURE__ */ new Set();
    this.closedViaSelection = false;
    this.modalWidth = "min(600px, 90vw)";
    this.modalHeight = "min(700px, 90vh)";
  }
  static async open(onSelect, onDelete) {
    const dialog = new SessionListDialog_1();
    dialog.onSelectCallback = onSelect;
    dialog.onDeleteCallback = onDelete;
    dialog.open();
    await dialog.loadSessions();
  }
  async loadSessions() {
    this.loading = true;
    try {
      const storage2 = getAppStorage();
      this.sessions = await storage2.sessions.getAllMetadata();
    } catch (err) {
      console.error("Failed to load sessions:", err);
      this.sessions = [];
    } finally {
      this.loading = false;
    }
  }
  async handleDelete(sessionId, event) {
    event.stopPropagation();
    if (!confirm(i18n("Delete this session?"))) {
      return;
    }
    try {
      const storage2 = getAppStorage();
      if (!storage2.sessions)
        return;
      await storage2.sessions.deleteSession(sessionId);
      await this.loadSessions();
      this.deletedSessions.add(sessionId);
    } catch (err) {
      console.error("Failed to delete session:", err);
    }
  }
  close() {
    super.close();
    if (!this.closedViaSelection && this.onDeleteCallback && this.deletedSessions.size > 0) {
      for (const sessionId of this.deletedSessions) {
        this.onDeleteCallback(sessionId);
      }
    }
  }
  handleSelect(sessionId) {
    this.closedViaSelection = true;
    if (this.onSelectCallback) {
      this.onSelectCallback(sessionId);
    }
    this.close();
  }
  formatDate(isoString) {
    const date = new Date(isoString);
    const now = /* @__PURE__ */ new Date();
    const diff = now.getTime() - date.getTime();
    const days2 = Math.floor(diff / (1e3 * 60 * 60 * 24));
    if (days2 === 0) {
      return i18n("Today");
    } else if (days2 === 1) {
      return i18n("Yesterday");
    } else if (days2 < 7) {
      return i18n("{days} days ago").replace("{days}", days2.toString());
    } else {
      return date.toLocaleDateString();
    }
  }
  renderContent() {
    return b2`
			${DialogContent({
      className: "h-full flex flex-col",
      children: b2`
					${DialogHeader({
        title: i18n("Sessions"),
        description: i18n("Load a previous conversation")
      })}

					<div class="flex-1 overflow-y-auto mt-4 space-y-2">
						${this.loading ? b2`<div class="text-center py-8 text-muted-foreground">${i18n("Loading...")}</div>` : this.sessions.length === 0 ? b2`<div class="text-center py-8 text-muted-foreground">${i18n("No sessions yet")}</div>` : this.sessions.map((session) => b2`
											<div
												class="group flex items-start gap-3 p-3 rounded-lg border border-border hover:bg-secondary/50 cursor-pointer transition-colors"
												@click=${() => this.handleSelect(session.id)}
											>
												<div class="flex-1 min-w-0">
													<div class="font-medium text-sm text-foreground truncate">${session.title}</div>
													<div class="text-xs text-muted-foreground mt-1">${this.formatDate(session.lastModified)}</div>
													<div class="text-xs text-muted-foreground mt-1">
														${session.messageCount} ${i18n("messages")} · ${formatUsage(session.usage)}
													</div>
												</div>
												<button
													class="opacity-0 group-hover:opacity-100 p-1 rounded hover:bg-destructive/10 text-destructive transition-opacity"
													@click=${(e9) => this.handleDelete(session.id, e9)}
													title=${i18n("Delete")}
												>
													<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
														<path d="M3 6h18"></path>
														<path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"></path>
														<path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"></path>
													</svg>
												</button>
											</div>
										`)}
					</div>
				`
    })}
		`;
  }
};
__decorate37([
  r7()
], SessionListDialog.prototype, "sessions", void 0);
__decorate37([
  r7()
], SessionListDialog.prototype, "loading", void 0);
SessionListDialog = SessionListDialog_1 = __decorate37([
  t5("session-list-dialog")
], SessionListDialog);

// ../pi-mono/packages/web-ui/dist/storage/backends/indexeddb-storage-backend.js
init_process_shim();
var IndexedDBStorageBackend = class {
  constructor(config) {
    this.config = config;
    this.dbPromise = null;
  }
  async getDB() {
    if (!this.dbPromise) {
      this.dbPromise = new Promise((resolve, reject) => {
        const request = indexedDB.open(this.config.dbName, this.config.version);
        request.onerror = () => reject(request.error);
        request.onsuccess = () => resolve(request.result);
        request.onupgradeneeded = (_event) => {
          const db = request.result;
          for (const storeConfig of this.config.stores) {
            if (!db.objectStoreNames.contains(storeConfig.name)) {
              const store = db.createObjectStore(storeConfig.name, {
                keyPath: storeConfig.keyPath,
                autoIncrement: storeConfig.autoIncrement
              });
              if (storeConfig.indices) {
                for (const indexConfig of storeConfig.indices) {
                  store.createIndex(indexConfig.name, indexConfig.keyPath, {
                    unique: indexConfig.unique
                  });
                }
              }
            }
          }
        };
      });
    }
    return this.dbPromise;
  }
  promisifyRequest(request) {
    return new Promise((resolve, reject) => {
      request.onsuccess = () => resolve(request.result);
      request.onerror = () => reject(request.error);
    });
  }
  async get(storeName, key) {
    const db = await this.getDB();
    const tx = db.transaction(storeName, "readonly");
    const store = tx.objectStore(storeName);
    const result = await this.promisifyRequest(store.get(key));
    return result ?? null;
  }
  async set(storeName, key, value) {
    const db = await this.getDB();
    const tx = db.transaction(storeName, "readwrite");
    const store = tx.objectStore(storeName);
    if (store.keyPath) {
      await this.promisifyRequest(store.put(value));
    } else {
      await this.promisifyRequest(store.put(value, key));
    }
  }
  async delete(storeName, key) {
    const db = await this.getDB();
    const tx = db.transaction(storeName, "readwrite");
    const store = tx.objectStore(storeName);
    await this.promisifyRequest(store.delete(key));
  }
  async keys(storeName, prefix) {
    const db = await this.getDB();
    const tx = db.transaction(storeName, "readonly");
    const store = tx.objectStore(storeName);
    if (prefix) {
      const range2 = IDBKeyRange.bound(prefix, `${prefix}\uFFFF`, false, false);
      const keys2 = await this.promisifyRequest(store.getAllKeys(range2));
      return keys2.map((k2) => String(k2));
    } else {
      const keys2 = await this.promisifyRequest(store.getAllKeys());
      return keys2.map((k2) => String(k2));
    }
  }
  async getAllFromIndex(storeName, indexName, direction = "asc") {
    const db = await this.getDB();
    const tx = db.transaction(storeName, "readonly");
    const store = tx.objectStore(storeName);
    const index = store.index(indexName);
    return new Promise((resolve, reject) => {
      const results = [];
      const request = index.openCursor(null, direction === "desc" ? "prev" : "next");
      request.onsuccess = () => {
        const cursor = request.result;
        if (cursor) {
          results.push(cursor.value);
          cursor.continue();
        } else {
          resolve(results);
        }
      };
      request.onerror = () => reject(request.error);
    });
  }
  async clear(storeName) {
    const db = await this.getDB();
    const tx = db.transaction(storeName, "readwrite");
    const store = tx.objectStore(storeName);
    await this.promisifyRequest(store.clear());
  }
  async has(storeName, key) {
    const db = await this.getDB();
    const tx = db.transaction(storeName, "readonly");
    const store = tx.objectStore(storeName);
    const result = await this.promisifyRequest(store.getKey(key));
    return result !== void 0;
  }
  async transaction(storeNames, mode, operation) {
    const db = await this.getDB();
    const idbTx = db.transaction(storeNames, mode);
    const storageTx = {
      get: async (storeName, key) => {
        const store = idbTx.objectStore(storeName);
        const result = await this.promisifyRequest(store.get(key));
        return result ?? null;
      },
      set: async (storeName, key, value) => {
        const store = idbTx.objectStore(storeName);
        if (store.keyPath) {
          await this.promisifyRequest(store.put(value));
        } else {
          await this.promisifyRequest(store.put(value, key));
        }
      },
      delete: async (storeName, key) => {
        const store = idbTx.objectStore(storeName);
        await this.promisifyRequest(store.delete(key));
      }
    };
    return operation(storageTx);
  }
  async getQuotaInfo() {
    if (navigator.storage?.estimate) {
      const estimate = await navigator.storage.estimate();
      return {
        usage: estimate.usage || 0,
        quota: estimate.quota || 0,
        percent: estimate.quota ? (estimate.usage || 0) / estimate.quota * 100 : 0
      };
    }
    return { usage: 0, quota: 0, percent: 0 };
  }
  async requestPersistence() {
    if (navigator.storage?.persist) {
      return await navigator.storage.persist();
    }
    return false;
  }
};

// ../pi-mono/packages/web-ui/dist/storage/store.js
init_process_shim();
var Store = class {
  constructor() {
    this.backend = null;
  }
  /**
   * Sets the storage backend. Called by AppStorage after backend creation.
   */
  setBackend(backend) {
    this.backend = backend;
  }
  /**
   * Gets the storage backend. Throws if backend not set.
   * Concrete stores must use this to access the backend.
   */
  getBackend() {
    if (!this.backend) {
      throw new Error(`Backend not set on ${this.constructor.name}`);
    }
    return this.backend;
  }
};

// ../pi-mono/packages/web-ui/dist/storage/stores/custom-providers-store.js
init_process_shim();
var CustomProvidersStore = class extends Store {
  getConfig() {
    return {
      name: "custom-providers"
    };
  }
  async get(id) {
    return this.getBackend().get("custom-providers", id);
  }
  async set(provider) {
    await this.getBackend().set("custom-providers", provider.id, provider);
  }
  async delete(id) {
    await this.getBackend().delete("custom-providers", id);
  }
  async getAll() {
    const keys2 = await this.getBackend().keys("custom-providers");
    const providers = [];
    for (const key of keys2) {
      const provider = await this.get(key);
      if (provider) {
        providers.push(provider);
      }
    }
    return providers;
  }
  async has(id) {
    return this.getBackend().has("custom-providers", id);
  }
};

// ../pi-mono/packages/web-ui/dist/storage/stores/provider-keys-store.js
init_process_shim();
var ProviderKeysStore = class extends Store {
  getConfig() {
    return {
      name: "provider-keys"
    };
  }
  async get(provider) {
    return this.getBackend().get("provider-keys", provider);
  }
  async set(provider, key) {
    await this.getBackend().set("provider-keys", provider, key);
  }
  async delete(provider) {
    await this.getBackend().delete("provider-keys", provider);
  }
  async list() {
    return this.getBackend().keys("provider-keys");
  }
  async has(provider) {
    return this.getBackend().has("provider-keys", provider);
  }
};

// ../pi-mono/packages/web-ui/dist/storage/stores/sessions-store.js
init_process_shim();
var SessionsStore = class extends Store {
  getConfig() {
    return {
      name: "sessions",
      keyPath: "id",
      indices: [{ name: "lastModified", keyPath: "lastModified" }]
    };
  }
  /**
   * Additional config for sessions-metadata store.
   * Must be included when creating the backend.
   */
  static getMetadataConfig() {
    return {
      name: "sessions-metadata",
      keyPath: "id",
      indices: [{ name: "lastModified", keyPath: "lastModified" }]
    };
  }
  async save(data, metadata) {
    await this.getBackend().transaction(["sessions", "sessions-metadata"], "readwrite", async (tx) => {
      await tx.set("sessions", data.id, data);
      await tx.set("sessions-metadata", metadata.id, metadata);
    });
  }
  async get(id) {
    return this.getBackend().get("sessions", id);
  }
  async getMetadata(id) {
    return this.getBackend().get("sessions-metadata", id);
  }
  async getAllMetadata() {
    return this.getBackend().getAllFromIndex("sessions-metadata", "lastModified", "desc");
  }
  async delete(id) {
    await this.getBackend().transaction(["sessions", "sessions-metadata"], "readwrite", async (tx) => {
      await tx.delete("sessions", id);
      await tx.delete("sessions-metadata", id);
    });
  }
  // Alias for backward compatibility
  async deleteSession(id) {
    return this.delete(id);
  }
  async updateTitle(id, title) {
    const metadata = await this.getMetadata(id);
    if (metadata) {
      metadata.title = title;
      await this.getBackend().set("sessions-metadata", id, metadata);
    }
    const data = await this.get(id);
    if (data) {
      data.title = title;
      await this.getBackend().set("sessions", id, data);
    }
  }
  async getQuotaInfo() {
    return this.getBackend().getQuotaInfo();
  }
  async requestPersistence() {
    return this.getBackend().requestPersistence();
  }
  // Alias methods for backward compatibility
  async saveSession(id, state, metadata, title) {
    const meta = metadata || {
      id,
      title: title || "",
      createdAt: (/* @__PURE__ */ new Date()).toISOString(),
      lastModified: (/* @__PURE__ */ new Date()).toISOString(),
      messageCount: state.messages?.length || 0,
      usage: {
        input: 0,
        output: 0,
        cacheRead: 0,
        cacheWrite: 0,
        totalTokens: 0,
        cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
      },
      thinkingLevel: state.thinkingLevel || "off",
      preview: ""
    };
    const data = {
      id,
      title: title || meta.title,
      model: state.model,
      thinkingLevel: state.thinkingLevel,
      messages: state.messages || [],
      createdAt: meta.createdAt,
      lastModified: (/* @__PURE__ */ new Date()).toISOString()
    };
    await this.save(data, meta);
  }
  async loadSession(id) {
    return this.get(id);
  }
  async getLatestSessionId() {
    const allMetadata = await this.getAllMetadata();
    if (allMetadata.length === 0)
      return null;
    allMetadata.sort((a3, b4) => b4.lastModified.localeCompare(a3.lastModified));
    return allMetadata[0].id;
  }
};

// ../pi-mono/packages/web-ui/dist/storage/stores/settings-store.js
init_process_shim();
var SettingsStore = class extends Store {
  getConfig() {
    return {
      name: "settings"
      // No keyPath - uses out-of-line keys
    };
  }
  async get(key) {
    return this.getBackend().get("settings", key);
  }
  async set(key, value) {
    await this.getBackend().set("settings", key, value);
  }
  async delete(key) {
    await this.getBackend().delete("settings", key);
  }
  async list() {
    return this.getBackend().keys("settings");
  }
  async clear() {
    await this.getBackend().clear("settings");
  }
};

// ../pi-mono/packages/web-ui/dist/tools/renderers/CalculateRenderer.js
init_process_shim();

// ../pi-mono/packages/web-ui/dist/tools/renderers/GetCurrentTimeRenderer.js
init_process_shim();

// ../pi-mono/packages/web-ui/dist/utils/auth-token.js
init_process_shim();

// ../mini-lit/dist/PromptDialog.js
init_process_shim();

// node_modules/lit/decorators/custom-element.js
init_process_shim();

// node_modules/lit/decorators/property.js
init_process_shim();

// node_modules/lit/decorators/state.js
init_process_shim();

// ../mini-lit/dist/PromptDialog.js
var __decorate38 = function(decorators, target, key, desc) {
  var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc);
  else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8;
  return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8;
};
var PromptDialog_1;
var PromptDialog = PromptDialog_1 = class PromptDialog2 extends DialogBase {
  constructor() {
    super(...arguments);
    this.headerTitle = "";
    this.message = "";
    this.defaultValue = "";
    this.isPassword = false;
    this.inputValue = "";
    this.inputRef = e5();
    this.modalWidth = "min(400px, 90vw)";
    this.modalHeight = "auto";
  }
  static async ask(title, message, defaultValue = "", isPassword = false) {
    const dialog = new PromptDialog_1();
    dialog.headerTitle = title;
    dialog.message = message;
    dialog.defaultValue = defaultValue;
    dialog.isPassword = isPassword;
    dialog.inputValue = defaultValue;
    return new Promise((resolve) => {
      dialog.resolvePromise = resolve;
      dialog.open();
    });
  }
  firstUpdated(_changedProperties) {
    super.firstUpdated(_changedProperties);
    this.inputRef.value?.focus();
  }
  handleConfirm() {
    this.resolvePromise?.(this.inputValue);
    this.close();
  }
  handleCancel() {
    this.resolvePromise?.(void 0);
    this.close();
  }
  renderContent() {
    return DialogContent({
      children: b2`
				${DialogHeader({
        title: this.headerTitle || i18n("Input Required"),
        description: this.message
      })}
				${Input2({
        type: this.isPassword ? "password" : "text",
        value: this.inputValue,
        className: "w-full",
        inputRef: this.inputRef,
        onInput: (e9) => {
          this.inputValue = e9.target.value;
        },
        onKeyDown: (e9) => {
          if (e9.key === "Enter")
            this.handleConfirm();
          if (e9.key === "Escape")
            this.handleCancel();
        }
      })}
				${DialogFooter({
        children: b2`
						${Button({
          variant: "outline",
          onClick: () => this.handleCancel(),
          children: i18n("Cancel")
        })}
						${Button({
          variant: "default",
          onClick: () => this.handleConfirm(),
          children: i18n("Confirm")
        })}
					`
      })}
			`
    });
  }
};
__decorate38([
  n6()
], PromptDialog.prototype, "headerTitle", void 0);
__decorate38([
  n6()
], PromptDialog.prototype, "message", void 0);
__decorate38([
  n6()
], PromptDialog.prototype, "defaultValue", void 0);
__decorate38([
  n6()
], PromptDialog.prototype, "isPassword", void 0);
__decorate38([
  r7()
], PromptDialog.prototype, "inputValue", void 0);
PromptDialog = PromptDialog_1 = __decorate38([
  t5("prompt-dialog")
], PromptDialog);

// node_modules/lucide/dist/esm/lucide.js
init_process_shim();

// node_modules/lucide/dist/esm/icons/arrow-left.js
init_process_shim();
var ArrowLeft = [
  ["path", { d: "m12 19-7-7 7-7" }],
  ["path", { d: "M19 12H5" }]
];

// node_modules/lucide/dist/esm/icons/bug.js
init_process_shim();
var Bug = [
  ["path", { d: "M12 20v-9" }],
  ["path", { d: "M14 7a4 4 0 0 1 4 4v3a6 6 0 0 1-12 0v-3a4 4 0 0 1 4-4z" }],
  ["path", { d: "M14.12 3.88 16 2" }],
  ["path", { d: "M21 21a4 4 0 0 0-3.81-4" }],
  ["path", { d: "M21 5a4 4 0 0 1-3.55 3.97" }],
  ["path", { d: "M22 13h-4" }],
  ["path", { d: "M3 21a4 4 0 0 1 3.81-4" }],
  ["path", { d: "M3 5a4 4 0 0 0 3.55 3.97" }],
  ["path", { d: "M6 13H2" }],
  ["path", { d: "m8 2 1.88 1.88" }],
  ["path", { d: "M9 7.13V6a3 3 0 1 1 6 0v1.13" }]
];

// node_modules/lucide/dist/esm/icons/loader-circle.js
init_process_shim();
var LoaderCircle2 = [["path", { d: "M21 12a9 9 0 1 1-6.219-8.56" }]];

// node_modules/lucide/dist/esm/icons/mouse-pointer-2.js
init_process_shim();
var MousePointer2 = [
  [
    "path",
    {
      d: "M4.037 4.688a.495.495 0 0 1 .651-.651l16 6.5a.5.5 0 0 1-.063.947l-6.124 1.58a2 2 0 0 0-1.438 1.435l-1.579 6.126a.5.5 0 0 1-.947.063z"
    }
  ]
];

// node_modules/lucide/dist/esm/icons/play.js
init_process_shim();
var Play = [
  [
    "path",
    { d: "M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z" }
  ]
];

// node_modules/lucide/dist/esm/icons/sparkles.js
init_process_shim();
var Sparkles2 = [
  [
    "path",
    {
      d: "M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z"
    }
  ],
  ["path", { d: "M20 2v4" }],
  ["path", { d: "M22 4h-4" }],
  ["circle", { cx: "4", cy: "20", r: "2" }]
];

// node_modules/lucide/dist/esm/icons/square.js
init_process_shim();
var Square2 = [["rect", { width: "18", height: "18", x: "3", y: "3", rx: "2" }]];

// src/debug/ReplPanel.ts
init_process_shim();
var ReplPanel = class extends i4 {
  constructor() {
    super();
    this.code = "";
    this.output = "";
    this.isExecuting = false;
    this.artifactsPanel = new ArtifactsPanel();
    this.artifactsPanel.sandboxUrlProvider = () => chrome.runtime.getURL("sandbox.html");
    this.replTool = createJavaScriptReplTool();
    this.replTool.runtimeProvidersFactory = () => [new ArtifactsRuntimeProvider(this.artifactsPanel)];
    this.replTool.sandboxUrlProvider = () => chrome.runtime.getURL("sandbox.html");
  }
  createRenderRoot() {
    return this;
  }
  async executeCode() {
    if (!this.code.trim() || this.isExecuting) return;
    this.isExecuting = true;
    this.output = "Executing...";
    this.abortController = new AbortController();
    try {
      const result = await this.replTool.execute(
        "",
        { code: this.code, title: "Debug REPL" },
        this.abortController.signal
      );
      this.output = result.content.find((c6) => c6.type === "text")?.text || "No output";
    } catch (error) {
      if (error.message === "Execution aborted") {
        this.output = "Execution aborted by user";
      } else {
        this.output = `Error: ${error.message}`;
      }
    } finally {
      this.isExecuting = false;
      this.abortController = void 0;
    }
  }
  abortExecution() {
    if (this.abortController) {
      this.abortController.abort();
    }
  }
  render() {
    return b2`
			<div class="flex flex-col h-full bg-background">
				<div class="flex-1 flex gap-4 p-4 overflow-hidden">
					<!-- Left: Code Editor + Output -->
					<div class="flex-1 flex flex-col gap-4 min-w-0">
						<!-- Code Input -->
						<div class="flex-1 flex flex-col gap-2 min-h-0">
							<div class="flex items-center justify-between">
								<label class="text-sm font-medium">JavaScript Code</label>
								${this.isExecuting ? Button({
      variant: "destructive",
      size: "sm",
      children: b2`<span class="flex items-center gap-1.5">${icon(Square2, "sm")} Abort</span>`,
      onClick: () => this.abortExecution()
    }) : Button({
      variant: "default",
      size: "sm",
      children: b2`<span class="flex items-center gap-1.5">${icon(Play, "sm")} Run</span>`,
      onClick: () => this.executeCode(),
      disabled: !this.code.trim()
    })}
							</div>
							<textarea
								class="flex-1 p-3 font-mono text-sm bg-card border border-border rounded-lg resize-none focus:outline-none focus:ring-2 focus:ring-ring"
								placeholder="Enter JavaScript code here...&#10;&#10;Example:&#10;await createOrUpdateArtifact('test.md', '# Hello World');"
								.value=${this.code}
								@input=${(e9) => {
      this.code = e9.target.value;
    }}
								@keydown=${(e9) => {
      if ((e9.metaKey || e9.ctrlKey) && e9.key === "Enter") {
        e9.preventDefault();
        this.executeCode();
      }
    }}
							></textarea>
						</div>

						<!-- Output -->
						<div class="flex-1 flex flex-col gap-2 min-h-0">
							<label class="text-sm font-medium">Output</label>
							<pre
								class="flex-1 p-3 font-mono text-sm bg-card border border-border rounded-lg overflow-auto whitespace-pre-wrap"
							>${this.output || "No output yet"}</pre>
						</div>
					</div>

					<!-- Right: Artifacts Panel -->
					<div class="flex-1 border-l border-border pl-4 min-w-0">
						<div class="h-full flex flex-col gap-2">
							<label class="text-sm font-medium">Artifacts</label>
							<div class="flex-1 border border-border rounded-lg overflow-hidden">
								${this.artifactsPanel}
							</div>
						</div>
					</div>
				</div>
			</div>
		`;
  }
};
__decorateClass([
  r7()
], ReplPanel.prototype, "code", 2);
__decorateClass([
  r7()
], ReplPanel.prototype, "output", 2);
__decorateClass([
  r7()
], ReplPanel.prototype, "isExecuting", 2);
ReplPanel = __decorateClass([
  t5("repl-panel")
], ReplPanel);

// src/storage/app-storage.ts
init_process_shim();

// src/storage/stores/cost-store.ts
init_process_shim();
var CostStore = class {
  constructor() {
    this.storeName = "daily_costs";
  }
  setBackend(backend) {
    this.backend = backend;
  }
  getConfig() {
    return {
      name: this.storeName,
      keyPath: "date",
      // Use date as primary key
      indices: [{ name: "date", keyPath: "date", unique: true }]
    };
  }
  /**
   * Record cost atomically - prevents race conditions.
   */
  async recordCost(provider, modelId, cost) {
    const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
    await this.backend.transaction([this.storeName], "readwrite", async (tx) => {
      let aggregate = await tx.get(this.storeName, today);
      if (!aggregate) {
        aggregate = { date: today, total: 0, byProvider: {} };
      }
      if (!aggregate.byProvider[provider]) {
        aggregate.byProvider[provider] = {};
      }
      aggregate.total += cost;
      aggregate.byProvider[provider][modelId] = (aggregate.byProvider[provider][modelId] || 0) + cost;
      await tx.set(this.storeName, today, aggregate);
    });
  }
  /**
   * Get all daily aggregates.
   */
  async getAll() {
    return this.backend.getAllFromIndex(
      this.storeName,
      "date",
      "desc"
      // Most recent first
    );
  }
  /**
   * Get total cost (all time).
   */
  async getTotalCost() {
    const allDays = await this.getAll();
    return allDays.reduce((sum, day) => sum + day.total, 0);
  }
  /**
   * Get costs by provider (all time, aggregated).
   */
  async getCostsByProvider() {
    const allDays = await this.getAll();
    const byProvider = {};
    for (const day of allDays) {
      for (const [provider, models2] of Object.entries(day.byProvider)) {
        const providerTotal = Object.values(models2).reduce((sum, cost) => sum + cost, 0);
        byProvider[provider] = (byProvider[provider] || 0) + providerTotal;
      }
    }
    return byProvider;
  }
  /**
   * Get costs by model (all time, aggregated).
   */
  async getCostsByModel() {
    const allDays = await this.getAll();
    const byModel = {};
    for (const day of allDays) {
      for (const [provider, models2] of Object.entries(day.byProvider)) {
        for (const [modelId, cost] of Object.entries(models2)) {
          const key = `${provider}:${modelId}`;
          byModel[key] = (byModel[key] || 0) + cost;
        }
      }
    }
    return byModel;
  }
  /**
   * Get costs within date range.
   */
  async getCostsByDateRange(start, end) {
    const allDays = await this.getAll();
    const startStr = start.toISOString().split("T")[0];
    const endStr = end.toISOString().split("T")[0];
    return allDays.filter((day) => day.date >= startStr && day.date <= endStr);
  }
};

// src/storage/stores/sessions-store.ts
init_process_shim();
var SitegeistSessionsStore = class extends SessionsStore {
  async loadSession(id) {
    const session = await super.loadSession(id);
    if (session) {
      return this.migrateSession(session);
    }
    return session;
  }
  async get(id) {
    const session = await super.get(id);
    if (session) {
      return this.migrateSession(session);
    }
    return session;
  }
  migrateSession(session) {
    return {
      ...session,
      messages: this.migrateToolResultMessages(session.messages)
    };
  }
  migrateToolResultMessages(messages) {
    return messages.map((msg) => {
      if (msg.role === "toolResult" && "output" in msg && !msg.content) {
        const { output, ...rest } = msg;
        return {
          ...rest,
          content: [{ type: "text", text: output }]
        };
      }
      return msg;
    });
  }
};

// src/storage/stores/skills-store.ts
init_process_shim();

// node_modules/minimatch/dist/esm/index.js
init_process_shim();

// node_modules/brace-expansion/dist/esm/index.js
init_process_shim();

// node_modules/balanced-match/dist/esm/index.js
init_process_shim();
var balanced = (a3, b4, str2) => {
  const ma = a3 instanceof RegExp ? maybeMatch(a3, str2) : a3;
  const mb = b4 instanceof RegExp ? maybeMatch(b4, str2) : b4;
  const r8 = ma !== null && mb != null && range(ma, mb, str2);
  return r8 && {
    start: r8[0],
    end: r8[1],
    pre: str2.slice(0, r8[0]),
    body: str2.slice(r8[0] + ma.length, r8[1]),
    post: str2.slice(r8[1] + mb.length)
  };
};
var maybeMatch = (reg, str2) => {
  const m4 = str2.match(reg);
  return m4 ? m4[0] : null;
};
var range = (a3, b4, str2) => {
  let begs, beg, left, right = void 0, result;
  let ai = str2.indexOf(a3);
  let bi = str2.indexOf(b4, ai + 1);
  let i7 = ai;
  if (ai >= 0 && bi > 0) {
    if (a3 === b4) {
      return [ai, bi];
    }
    begs = [];
    left = str2.length;
    while (i7 >= 0 && !result) {
      if (i7 === ai) {
        begs.push(i7);
        ai = str2.indexOf(a3, i7 + 1);
      } else if (begs.length === 1) {
        const r8 = begs.pop();
        if (r8 !== void 0)
          result = [r8, bi];
      } else {
        beg = begs.pop();
        if (beg !== void 0 && beg < left) {
          left = beg;
          right = bi;
        }
        bi = str2.indexOf(b4, i7 + 1);
      }
      i7 = ai < bi && ai >= 0 ? ai : bi;
    }
    if (begs.length && right !== void 0) {
      result = [left, right];
    }
  }
  return result;
};

// node_modules/brace-expansion/dist/esm/index.js
var escSlash = "\0SLASH" + Math.random() + "\0";
var escOpen = "\0OPEN" + Math.random() + "\0";
var escClose = "\0CLOSE" + Math.random() + "\0";
var escComma = "\0COMMA" + Math.random() + "\0";
var escPeriod = "\0PERIOD" + Math.random() + "\0";
var escSlashPattern = new RegExp(escSlash, "g");
var escOpenPattern = new RegExp(escOpen, "g");
var escClosePattern = new RegExp(escClose, "g");
var escCommaPattern = new RegExp(escComma, "g");
var escPeriodPattern = new RegExp(escPeriod, "g");
var slashPattern = /\\\\/g;
var openPattern = /\\{/g;
var closePattern = /\\}/g;
var commaPattern = /\\,/g;
var periodPattern = /\\\./g;
var EXPANSION_MAX = 1e5;
function numeric(str2) {
  return !isNaN(str2) ? parseInt(str2, 10) : str2.charCodeAt(0);
}
function escapeBraces(str2) {
  return str2.replace(slashPattern, escSlash).replace(openPattern, escOpen).replace(closePattern, escClose).replace(commaPattern, escComma).replace(periodPattern, escPeriod);
}
function unescapeBraces(str2) {
  return str2.replace(escSlashPattern, "\\").replace(escOpenPattern, "{").replace(escClosePattern, "}").replace(escCommaPattern, ",").replace(escPeriodPattern, ".");
}
function parseCommaParts(str2) {
  if (!str2) {
    return [""];
  }
  const parts = [];
  const m4 = balanced("{", "}", str2);
  if (!m4) {
    return str2.split(",");
  }
  const { pre, body, post: post2 } = m4;
  const p4 = pre.split(",");
  p4[p4.length - 1] += "{" + body + "}";
  const postParts = parseCommaParts(post2);
  if (post2.length) {
    ;
    p4[p4.length - 1] += postParts.shift();
    p4.push.apply(p4, postParts);
  }
  parts.push.apply(parts, p4);
  return parts;
}
function expand(str2, options = {}) {
  if (!str2) {
    return [];
  }
  const { max = EXPANSION_MAX } = options;
  if (str2.slice(0, 2) === "{}") {
    str2 = "\\{\\}" + str2.slice(2);
  }
  return expand_(escapeBraces(str2), max, true).map(unescapeBraces);
}
function embrace(str2) {
  return "{" + str2 + "}";
}
function isPadded(el) {
  return /^-?0\d/.test(el);
}
function lte(i7, y4) {
  return i7 <= y4;
}
function gte(i7, y4) {
  return i7 >= y4;
}
function expand_(str2, max, isTop) {
  const expansions = [];
  const m4 = balanced("{", "}", str2);
  if (!m4)
    return [str2];
  const pre = m4.pre;
  const post2 = m4.post.length ? expand_(m4.post, max, false) : [""];
  if (/\$$/.test(m4.pre)) {
    for (let k2 = 0; k2 < post2.length && k2 < max; k2++) {
      const expansion = pre + "{" + m4.body + "}" + post2[k2];
      expansions.push(expansion);
    }
  } else {
    const isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m4.body);
    const isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m4.body);
    const isSequence = isNumericSequence || isAlphaSequence;
    const isOptions = m4.body.indexOf(",") >= 0;
    if (!isSequence && !isOptions) {
      if (m4.post.match(/,(?!,).*\}/)) {
        str2 = m4.pre + "{" + m4.body + escClose + m4.post;
        return expand_(str2, max, true);
      }
      return [str2];
    }
    let n7;
    if (isSequence) {
      n7 = m4.body.split(/\.\./);
    } else {
      n7 = parseCommaParts(m4.body);
      if (n7.length === 1 && n7[0] !== void 0) {
        n7 = expand_(n7[0], max, false).map(embrace);
        if (n7.length === 1) {
          return post2.map((p4) => m4.pre + n7[0] + p4);
        }
      }
    }
    let N3;
    if (isSequence && n7[0] !== void 0 && n7[1] !== void 0) {
      const x2 = numeric(n7[0]);
      const y4 = numeric(n7[1]);
      const width = Math.max(n7[0].length, n7[1].length);
      let incr = n7.length === 3 && n7[2] !== void 0 ? Math.abs(numeric(n7[2])) : 1;
      let test = lte;
      const reverse = y4 < x2;
      if (reverse) {
        incr *= -1;
        test = gte;
      }
      const pad2 = n7.some(isPadded);
      N3 = [];
      for (let i7 = x2; test(i7, y4); i7 += incr) {
        let c6;
        if (isAlphaSequence) {
          c6 = String.fromCharCode(i7);
          if (c6 === "\\") {
            c6 = "";
          }
        } else {
          c6 = String(i7);
          if (pad2) {
            const need = width - c6.length;
            if (need > 0) {
              const z3 = new Array(need + 1).join("0");
              if (i7 < 0) {
                c6 = "-" + z3 + c6.slice(1);
              } else {
                c6 = z3 + c6;
              }
            }
          }
        }
        N3.push(c6);
      }
    } else {
      N3 = [];
      for (let j3 = 0; j3 < n7.length; j3++) {
        N3.push.apply(N3, expand_(n7[j3], max, false));
      }
    }
    for (let j3 = 0; j3 < N3.length; j3++) {
      for (let k2 = 0; k2 < post2.length && expansions.length < max; k2++) {
        const expansion = pre + N3[j3] + post2[k2];
        if (!isTop || isSequence || expansion) {
          expansions.push(expansion);
        }
      }
    }
  }
  return expansions;
}

// node_modules/minimatch/dist/esm/assert-valid-pattern.js
init_process_shim();
var MAX_PATTERN_LENGTH = 1024 * 64;
var assertValidPattern = (pattern) => {
  if (typeof pattern !== "string") {
    throw new TypeError("invalid pattern");
  }
  if (pattern.length > MAX_PATTERN_LENGTH) {
    throw new TypeError("pattern is too long");
  }
};

// node_modules/minimatch/dist/esm/ast.js
init_process_shim();

// node_modules/minimatch/dist/esm/brace-expressions.js
init_process_shim();
var posixClasses = {
  "[:alnum:]": ["\\p{L}\\p{Nl}\\p{Nd}", true],
  "[:alpha:]": ["\\p{L}\\p{Nl}", true],
  "[:ascii:]": ["\\x00-\\x7f", false],
  "[:blank:]": ["\\p{Zs}\\t", true],
  "[:cntrl:]": ["\\p{Cc}", true],
  "[:digit:]": ["\\p{Nd}", true],
  "[:graph:]": ["\\p{Z}\\p{C}", true, true],
  "[:lower:]": ["\\p{Ll}", true],
  "[:print:]": ["\\p{C}", true],
  "[:punct:]": ["\\p{P}", true],
  "[:space:]": ["\\p{Z}\\t\\r\\n\\v\\f", true],
  "[:upper:]": ["\\p{Lu}", true],
  "[:word:]": ["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}", true],
  "[:xdigit:]": ["A-Fa-f0-9", false]
};
var braceEscape = (s6) => s6.replace(/[[\]\\-]/g, "\\$&");
var regexpEscape = (s6) => s6.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
var rangesToString = (ranges) => ranges.join("");
var parseClass = (glob, position) => {
  const pos = position;
  if (glob.charAt(pos) !== "[") {
    throw new Error("not in a brace expression");
  }
  const ranges = [];
  const negs = [];
  let i7 = pos + 1;
  let sawStart = false;
  let uflag = false;
  let escaping = false;
  let negate = false;
  let endPos = pos;
  let rangeStart = "";
  WHILE: while (i7 < glob.length) {
    const c6 = glob.charAt(i7);
    if ((c6 === "!" || c6 === "^") && i7 === pos + 1) {
      negate = true;
      i7++;
      continue;
    }
    if (c6 === "]" && sawStart && !escaping) {
      endPos = i7 + 1;
      break;
    }
    sawStart = true;
    if (c6 === "\\") {
      if (!escaping) {
        escaping = true;
        i7++;
        continue;
      }
    }
    if (c6 === "[" && !escaping) {
      for (const [cls, [unip, u5, neg]] of Object.entries(posixClasses)) {
        if (glob.startsWith(cls, i7)) {
          if (rangeStart) {
            return ["$.", false, glob.length - pos, true];
          }
          i7 += cls.length;
          if (neg)
            negs.push(unip);
          else
            ranges.push(unip);
          uflag = uflag || u5;
          continue WHILE;
        }
      }
    }
    escaping = false;
    if (rangeStart) {
      if (c6 > rangeStart) {
        ranges.push(braceEscape(rangeStart) + "-" + braceEscape(c6));
      } else if (c6 === rangeStart) {
        ranges.push(braceEscape(c6));
      }
      rangeStart = "";
      i7++;
      continue;
    }
    if (glob.startsWith("-]", i7 + 1)) {
      ranges.push(braceEscape(c6 + "-"));
      i7 += 2;
      continue;
    }
    if (glob.startsWith("-", i7 + 1)) {
      rangeStart = c6;
      i7 += 2;
      continue;
    }
    ranges.push(braceEscape(c6));
    i7++;
  }
  if (endPos < i7) {
    return ["", false, 0, false];
  }
  if (!ranges.length && !negs.length) {
    return ["$.", false, glob.length - pos, true];
  }
  if (negs.length === 0 && ranges.length === 1 && /^\\?.$/.test(ranges[0]) && !negate) {
    const r8 = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
    return [regexpEscape(r8), false, endPos - pos, false];
  }
  const sranges = "[" + (negate ? "^" : "") + rangesToString(ranges) + "]";
  const snegs = "[" + (negate ? "" : "^") + rangesToString(negs) + "]";
  const comb = ranges.length && negs.length ? "(" + sranges + "|" + snegs + ")" : ranges.length ? sranges : snegs;
  return [comb, uflag, endPos - pos, true];
};

// node_modules/minimatch/dist/esm/unescape.js
init_process_shim();
var unescape2 = (s6, { windowsPathsNoEscape = false, magicalBraces = true } = {}) => {
  if (magicalBraces) {
    return windowsPathsNoEscape ? s6.replace(/\[([^\/\\])\]/g, "$1") : s6.replace(/((?!\\).|^)\[([^\/\\])\]/g, "$1$2").replace(/\\([^\/])/g, "$1");
  }
  return windowsPathsNoEscape ? s6.replace(/\[([^\/\\{}])\]/g, "$1") : s6.replace(/((?!\\).|^)\[([^\/\\{}])\]/g, "$1$2").replace(/\\([^\/{}])/g, "$1");
};

// node_modules/minimatch/dist/esm/ast.js
var _a6;
var types = /* @__PURE__ */ new Set(["!", "?", "+", "*", "@"]);
var isExtglobType = (c6) => types.has(c6);
var isExtglobAST = (c6) => isExtglobType(c6.type);
var adoptionMap = /* @__PURE__ */ new Map([
  ["!", ["@"]],
  ["?", ["?", "@"]],
  ["@", ["@"]],
  ["*", ["*", "+", "?", "@"]],
  ["+", ["+", "@"]]
]);
var adoptionWithSpaceMap = /* @__PURE__ */ new Map([
  ["!", ["?"]],
  ["@", ["?"]],
  ["+", ["?", "*"]]
]);
var adoptionAnyMap = /* @__PURE__ */ new Map([
  ["!", ["?", "@"]],
  ["?", ["?", "@"]],
  ["@", ["?", "@"]],
  ["*", ["*", "+", "?", "@"]],
  ["+", ["+", "@", "?", "*"]]
]);
var usurpMap = /* @__PURE__ */ new Map([
  ["!", /* @__PURE__ */ new Map([["!", "@"]])],
  [
    "?",
    /* @__PURE__ */ new Map([
      ["*", "*"],
      ["+", "*"]
    ])
  ],
  [
    "@",
    /* @__PURE__ */ new Map([
      ["!", "!"],
      ["?", "?"],
      ["@", "@"],
      ["*", "*"],
      ["+", "+"]
    ])
  ],
  [
    "+",
    /* @__PURE__ */ new Map([
      ["?", "*"],
      ["*", "*"]
    ])
  ]
]);
var startNoTraversal = "(?!(?:^|/)\\.\\.?(?:$|/))";
var startNoDot = "(?!\\.)";
var addPatternStart = /* @__PURE__ */ new Set(["[", "."]);
var justDots = /* @__PURE__ */ new Set(["..", "."]);
var reSpecials = new Set("().*{}+?[]^$\\!");
var regExpEscape = (s6) => s6.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
var qmark = "[^/]";
var star = qmark + "*?";
var starNoEmpty = qmark + "+?";
var ID = 0;
var AST = class {
  type;
  #root;
  #hasMagic;
  #uflag = false;
  #parts = [];
  #parent;
  #parentIndex;
  #negs;
  #filledNegs = false;
  #options;
  #toString;
  // set to true if it's an extglob with no children
  // (which really means one child of '')
  #emptyExt = false;
  id = ++ID;
  get depth() {
    return (this.#parent?.depth ?? -1) + 1;
  }
  [Symbol.for("nodejs.util.inspect.custom")]() {
    return {
      "@@type": "AST",
      id: this.id,
      type: this.type,
      root: this.#root.id,
      parent: this.#parent?.id,
      depth: this.depth,
      partsLength: this.#parts.length,
      parts: this.#parts
    };
  }
  constructor(type, parent, options = {}) {
    this.type = type;
    if (type)
      this.#hasMagic = true;
    this.#parent = parent;
    this.#root = this.#parent ? this.#parent.#root : this;
    this.#options = this.#root === this ? options : this.#root.#options;
    this.#negs = this.#root === this ? [] : this.#root.#negs;
    if (type === "!" && !this.#root.#filledNegs)
      this.#negs.push(this);
    this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;
  }
  get hasMagic() {
    if (this.#hasMagic !== void 0)
      return this.#hasMagic;
    for (const p4 of this.#parts) {
      if (typeof p4 === "string")
        continue;
      if (p4.type || p4.hasMagic)
        return this.#hasMagic = true;
    }
    return this.#hasMagic;
  }
  // reconstructs the pattern
  toString() {
    if (this.#toString !== void 0)
      return this.#toString;
    if (!this.type) {
      return this.#toString = this.#parts.map((p4) => String(p4)).join("");
    } else {
      return this.#toString = this.type + "(" + this.#parts.map((p4) => String(p4)).join("|") + ")";
    }
  }
  #fillNegs() {
    if (this !== this.#root)
      throw new Error("should only call on root");
    if (this.#filledNegs)
      return this;
    this.toString();
    this.#filledNegs = true;
    let n7;
    while (n7 = this.#negs.pop()) {
      if (n7.type !== "!")
        continue;
      let p4 = n7;
      let pp = p4.#parent;
      while (pp) {
        for (let i7 = p4.#parentIndex + 1; !pp.type && i7 < pp.#parts.length; i7++) {
          for (const part of n7.#parts) {
            if (typeof part === "string") {
              throw new Error("string part in extglob AST??");
            }
            part.copyIn(pp.#parts[i7]);
          }
        }
        p4 = pp;
        pp = p4.#parent;
      }
    }
    return this;
  }
  push(...parts) {
    for (const p4 of parts) {
      if (p4 === "")
        continue;
      if (typeof p4 !== "string" && !(p4 instanceof _a6 && p4.#parent === this)) {
        throw new Error("invalid part: " + p4);
      }
      this.#parts.push(p4);
    }
  }
  toJSON() {
    const ret = this.type === null ? this.#parts.slice().map((p4) => typeof p4 === "string" ? p4 : p4.toJSON()) : [this.type, ...this.#parts.map((p4) => p4.toJSON())];
    if (this.isStart() && !this.type)
      ret.unshift([]);
    if (this.isEnd() && (this === this.#root || this.#root.#filledNegs && this.#parent?.type === "!")) {
      ret.push({});
    }
    return ret;
  }
  isStart() {
    if (this.#root === this)
      return true;
    if (!this.#parent?.isStart())
      return false;
    if (this.#parentIndex === 0)
      return true;
    const p4 = this.#parent;
    for (let i7 = 0; i7 < this.#parentIndex; i7++) {
      const pp = p4.#parts[i7];
      if (!(pp instanceof _a6 && pp.type === "!")) {
        return false;
      }
    }
    return true;
  }
  isEnd() {
    if (this.#root === this)
      return true;
    if (this.#parent?.type === "!")
      return true;
    if (!this.#parent?.isEnd())
      return false;
    if (!this.type)
      return this.#parent?.isEnd();
    const pl = this.#parent ? this.#parent.#parts.length : 0;
    return this.#parentIndex === pl - 1;
  }
  copyIn(part) {
    if (typeof part === "string")
      this.push(part);
    else
      this.push(part.clone(this));
  }
  clone(parent) {
    const c6 = new _a6(this.type, parent);
    for (const p4 of this.#parts) {
      c6.copyIn(p4);
    }
    return c6;
  }
  static #parseAST(str2, ast, pos, opt, extDepth) {
    const maxDepth = opt.maxExtglobRecursion ?? 2;
    let escaping = false;
    let inBrace = false;
    let braceStart = -1;
    let braceNeg = false;
    if (ast.type === null) {
      let i8 = pos;
      let acc2 = "";
      while (i8 < str2.length) {
        const c6 = str2.charAt(i8++);
        if (escaping || c6 === "\\") {
          escaping = !escaping;
          acc2 += c6;
          continue;
        }
        if (inBrace) {
          if (i8 === braceStart + 1) {
            if (c6 === "^" || c6 === "!") {
              braceNeg = true;
            }
          } else if (c6 === "]" && !(i8 === braceStart + 2 && braceNeg)) {
            inBrace = false;
          }
          acc2 += c6;
          continue;
        } else if (c6 === "[") {
          inBrace = true;
          braceStart = i8;
          braceNeg = false;
          acc2 += c6;
          continue;
        }
        const doRecurse = !opt.noext && isExtglobType(c6) && str2.charAt(i8) === "(" && extDepth <= maxDepth;
        if (doRecurse) {
          ast.push(acc2);
          acc2 = "";
          const ext2 = new _a6(c6, ast);
          i8 = _a6.#parseAST(str2, ext2, i8, opt, extDepth + 1);
          ast.push(ext2);
          continue;
        }
        acc2 += c6;
      }
      ast.push(acc2);
      return i8;
    }
    let i7 = pos + 1;
    let part = new _a6(null, ast);
    const parts = [];
    let acc = "";
    while (i7 < str2.length) {
      const c6 = str2.charAt(i7++);
      if (escaping || c6 === "\\") {
        escaping = !escaping;
        acc += c6;
        continue;
      }
      if (inBrace) {
        if (i7 === braceStart + 1) {
          if (c6 === "^" || c6 === "!") {
            braceNeg = true;
          }
        } else if (c6 === "]" && !(i7 === braceStart + 2 && braceNeg)) {
          inBrace = false;
        }
        acc += c6;
        continue;
      } else if (c6 === "[") {
        inBrace = true;
        braceStart = i7;
        braceNeg = false;
        acc += c6;
        continue;
      }
      const doRecurse = !opt.noext && isExtglobType(c6) && str2.charAt(i7) === "(" && /* c8 ignore start - the maxDepth is sufficient here */
      (extDepth <= maxDepth || ast && ast.#canAdoptType(c6));
      if (doRecurse) {
        const depthAdd = ast && ast.#canAdoptType(c6) ? 0 : 1;
        part.push(acc);
        acc = "";
        const ext2 = new _a6(c6, part);
        part.push(ext2);
        i7 = _a6.#parseAST(str2, ext2, i7, opt, extDepth + depthAdd);
        continue;
      }
      if (c6 === "|") {
        part.push(acc);
        acc = "";
        parts.push(part);
        part = new _a6(null, ast);
        continue;
      }
      if (c6 === ")") {
        if (acc === "" && ast.#parts.length === 0) {
          ast.#emptyExt = true;
        }
        part.push(acc);
        acc = "";
        ast.push(...parts, part);
        return i7;
      }
      acc += c6;
    }
    ast.type = null;
    ast.#hasMagic = void 0;
    ast.#parts = [str2.substring(pos - 1)];
    return i7;
  }
  #canAdoptWithSpace(child) {
    return this.#canAdopt(child, adoptionWithSpaceMap);
  }
  #canAdopt(child, map = adoptionMap) {
    if (!child || typeof child !== "object" || child.type !== null || child.#parts.length !== 1 || this.type === null) {
      return false;
    }
    const gc = child.#parts[0];
    if (!gc || typeof gc !== "object" || gc.type === null) {
      return false;
    }
    return this.#canAdoptType(gc.type, map);
  }
  #canAdoptType(c6, map = adoptionAnyMap) {
    return !!map.get(this.type)?.includes(c6);
  }
  #adoptWithSpace(child, index) {
    const gc = child.#parts[0];
    const blank = new _a6(null, gc, this.options);
    blank.#parts.push("");
    gc.push(blank);
    this.#adopt(child, index);
  }
  #adopt(child, index) {
    const gc = child.#parts[0];
    this.#parts.splice(index, 1, ...gc.#parts);
    for (const p4 of gc.#parts) {
      if (typeof p4 === "object")
        p4.#parent = this;
    }
    this.#toString = void 0;
  }
  #canUsurpType(c6) {
    const m4 = usurpMap.get(this.type);
    return !!m4?.has(c6);
  }
  #canUsurp(child) {
    if (!child || typeof child !== "object" || child.type !== null || child.#parts.length !== 1 || this.type === null || this.#parts.length !== 1) {
      return false;
    }
    const gc = child.#parts[0];
    if (!gc || typeof gc !== "object" || gc.type === null) {
      return false;
    }
    return this.#canUsurpType(gc.type);
  }
  #usurp(child) {
    const m4 = usurpMap.get(this.type);
    const gc = child.#parts[0];
    const nt = m4?.get(gc.type);
    if (!nt)
      return false;
    this.#parts = gc.#parts;
    for (const p4 of this.#parts) {
      if (typeof p4 === "object") {
        p4.#parent = this;
      }
    }
    this.type = nt;
    this.#toString = void 0;
    this.#emptyExt = false;
  }
  static fromGlob(pattern, options = {}) {
    const ast = new _a6(null, void 0, options);
    _a6.#parseAST(pattern, ast, 0, options, 0);
    return ast;
  }
  // returns the regular expression if there's magic, or the unescaped
  // string if not.
  toMMPattern() {
    if (this !== this.#root)
      return this.#root.toMMPattern();
    const glob = this.toString();
    const [re2, body, hasMagic, uflag] = this.toRegExpSource();
    const anyMagic = hasMagic || this.#hasMagic || this.#options.nocase && !this.#options.nocaseMagicOnly && glob.toUpperCase() !== glob.toLowerCase();
    if (!anyMagic) {
      return body;
    }
    const flags = (this.#options.nocase ? "i" : "") + (uflag ? "u" : "");
    return Object.assign(new RegExp(`^${re2}$`, flags), {
      _src: re2,
      _glob: glob
    });
  }
  get options() {
    return this.#options;
  }
  // returns the string match, the regexp source, whether there's magic
  // in the regexp (so a regular expression is required) and whether or
  // not the uflag is needed for the regular expression (for posix classes)
  // TODO: instead of injecting the start/end at this point, just return
  // the BODY of the regexp, along with the start/end portions suitable
  // for binding the start/end in either a joined full-path makeRe context
  // (where we bind to (^|/), or a standalone matchPart context (where
  // we bind to ^, and not /).  Otherwise slashes get duped!
  //
  // In part-matching mode, the start is:
  // - if not isStart: nothing
  // - if traversal possible, but not allowed: ^(?!\.\.?$)
  // - if dots allowed or not possible: ^
  // - if dots possible and not allowed: ^(?!\.)
  // end is:
  // - if not isEnd(): nothing
  // - else: $
  //
  // In full-path matching mode, we put the slash at the START of the
  // pattern, so start is:
  // - if first pattern: same as part-matching mode
  // - if not isStart(): nothing
  // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/))
  // - if dots allowed or not possible: /
  // - if dots possible and not allowed: /(?!\.)
  // end is:
  // - if last pattern, same as part-matching mode
  // - else nothing
  //
  // Always put the (?:$|/) on negated tails, though, because that has to be
  // there to bind the end of the negated pattern portion, and it's easier to
  // just stick it in now rather than try to inject it later in the middle of
  // the pattern.
  //
  // We can just always return the same end, and leave it up to the caller
  // to know whether it's going to be used joined or in parts.
  // And, if the start is adjusted slightly, can do the same there:
  // - if not isStart: nothing
  // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$)
  // - if dots allowed or not possible: (?:/|^)
  // - if dots possible and not allowed: (?:/|^)(?!\.)
  //
  // But it's better to have a simpler binding without a conditional, for
  // performance, so probably better to return both start options.
  //
  // Then the caller just ignores the end if it's not the first pattern,
  // and the start always gets applied.
  //
  // But that's always going to be $ if it's the ending pattern, or nothing,
  // so the caller can just attach $ at the end of the pattern when building.
  //
  // So the todo is:
  // - better detect what kind of start is needed
  // - return both flavors of starting pattern
  // - attach $ at the end of the pattern when creating the actual RegExp
  //
  // Ah, but wait, no, that all only applies to the root when the first pattern
  // is not an extglob. If the first pattern IS an extglob, then we need all
  // that dot prevention biz to live in the extglob portions, because eg
  // +(*|.x*) can match .xy but not .yx.
  //
  // So, return the two flavors if it's #root and the first child is not an
  // AST, otherwise leave it to the child AST to handle it, and there,
  // use the (?:^|/) style of start binding.
  //
  // Even simplified further:
  // - Since the start for a join is eg /(?!\.) and the start for a part
  // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root
  // or start or whatever) and prepend ^ or / at the Regexp construction.
  toRegExpSource(allowDot) {
    const dot = allowDot ?? !!this.#options.dot;
    if (this.#root === this) {
      this.#flatten();
      this.#fillNegs();
    }
    if (!isExtglobAST(this)) {
      const noEmpty = this.isStart() && this.isEnd() && !this.#parts.some((s6) => typeof s6 !== "string");
      const src = this.#parts.map((p4) => {
        const [re2, _3, hasMagic, uflag] = typeof p4 === "string" ? _a6.#parseGlob(p4, this.#hasMagic, noEmpty) : p4.toRegExpSource(allowDot);
        this.#hasMagic = this.#hasMagic || hasMagic;
        this.#uflag = this.#uflag || uflag;
        return re2;
      }).join("");
      let start2 = "";
      if (this.isStart()) {
        if (typeof this.#parts[0] === "string") {
          const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]);
          if (!dotTravAllowed) {
            const aps = addPatternStart;
            const needNoTrav = (
              // dots are allowed, and the pattern starts with [ or .
              dot && aps.has(src.charAt(0)) || // the pattern starts with \., and then [ or .
              src.startsWith("\\.") && aps.has(src.charAt(2)) || // the pattern starts with \.\., and then [ or .
              src.startsWith("\\.\\.") && aps.has(src.charAt(4))
            );
            const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));
            start2 = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : "";
          }
        }
      }
      let end = "";
      if (this.isEnd() && this.#root.#filledNegs && this.#parent?.type === "!") {
        end = "(?:$|\\/)";
      }
      const final2 = start2 + src + end;
      return [
        final2,
        unescape2(src),
        this.#hasMagic = !!this.#hasMagic,
        this.#uflag
      ];
    }
    const repeated = this.type === "*" || this.type === "+";
    const start = this.type === "!" ? "(?:(?!(?:" : "(?:";
    let body = this.#partsToRegExp(dot);
    if (this.isStart() && this.isEnd() && !body && this.type !== "!") {
      const s6 = this.toString();
      const me = this;
      me.#parts = [s6];
      me.type = null;
      me.#hasMagic = void 0;
      return [s6, unescape2(this.toString()), false, false];
    }
    let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot ? "" : this.#partsToRegExp(true);
    if (bodyDotAllowed === body) {
      bodyDotAllowed = "";
    }
    if (bodyDotAllowed) {
      body = `(?:${body})(?:${bodyDotAllowed})*?`;
    }
    let final = "";
    if (this.type === "!" && this.#emptyExt) {
      final = (this.isStart() && !dot ? startNoDot : "") + starNoEmpty;
    } else {
      const close2 = this.type === "!" ? (
        // !() must match something,but !(x) can match ''
        "))" + (this.isStart() && !dot && !allowDot ? startNoDot : "") + star + ")"
      ) : this.type === "@" ? ")" : this.type === "?" ? ")?" : this.type === "+" && bodyDotAllowed ? ")" : this.type === "*" && bodyDotAllowed ? `)?` : `)${this.type}`;
      final = start + body + close2;
    }
    return [
      final,
      unescape2(body),
      this.#hasMagic = !!this.#hasMagic,
      this.#uflag
    ];
  }
  #flatten() {
    if (!isExtglobAST(this)) {
      for (const p4 of this.#parts) {
        if (typeof p4 === "object") {
          p4.#flatten();
        }
      }
    } else {
      let iterations = 0;
      let done = false;
      do {
        done = true;
        for (let i7 = 0; i7 < this.#parts.length; i7++) {
          const c6 = this.#parts[i7];
          if (typeof c6 === "object") {
            c6.#flatten();
            if (this.#canAdopt(c6)) {
              done = false;
              this.#adopt(c6, i7);
            } else if (this.#canAdoptWithSpace(c6)) {
              done = false;
              this.#adoptWithSpace(c6, i7);
            } else if (this.#canUsurp(c6)) {
              done = false;
              this.#usurp(c6);
            }
          }
        }
      } while (!done && ++iterations < 10);
    }
    this.#toString = void 0;
  }
  #partsToRegExp(dot) {
    return this.#parts.map((p4) => {
      if (typeof p4 === "string") {
        throw new Error("string type in extglob ast??");
      }
      const [re2, _3, _hasMagic, uflag] = p4.toRegExpSource(dot);
      this.#uflag = this.#uflag || uflag;
      return re2;
    }).filter((p4) => !(this.isStart() && this.isEnd()) || !!p4).join("|");
  }
  static #parseGlob(glob, hasMagic, noEmpty = false) {
    let escaping = false;
    let re2 = "";
    let uflag = false;
    let inStar = false;
    for (let i7 = 0; i7 < glob.length; i7++) {
      const c6 = glob.charAt(i7);
      if (escaping) {
        escaping = false;
        re2 += (reSpecials.has(c6) ? "\\" : "") + c6;
        continue;
      }
      if (c6 === "*") {
        if (inStar)
          continue;
        inStar = true;
        re2 += noEmpty && /^[*]+$/.test(glob) ? starNoEmpty : star;
        hasMagic = true;
        continue;
      } else {
        inStar = false;
      }
      if (c6 === "\\") {
        if (i7 === glob.length - 1) {
          re2 += "\\\\";
        } else {
          escaping = true;
        }
        continue;
      }
      if (c6 === "[") {
        const [src, needUflag, consumed2, magic] = parseClass(glob, i7);
        if (consumed2) {
          re2 += src;
          uflag = uflag || needUflag;
          i7 += consumed2 - 1;
          hasMagic = hasMagic || magic;
          continue;
        }
      }
      if (c6 === "?") {
        re2 += qmark;
        hasMagic = true;
        continue;
      }
      re2 += regExpEscape(c6);
    }
    return [re2, unescape2(glob), !!hasMagic, uflag];
  }
};
_a6 = AST;

// node_modules/minimatch/dist/esm/escape.js
init_process_shim();
var escape3 = (s6, { windowsPathsNoEscape = false, magicalBraces = false } = {}) => {
  if (magicalBraces) {
    return windowsPathsNoEscape ? s6.replace(/[?*()[\]{}]/g, "[$&]") : s6.replace(/[?*()[\]\\{}]/g, "\\$&");
  }
  return windowsPathsNoEscape ? s6.replace(/[?*()[\]]/g, "[$&]") : s6.replace(/[?*()[\]\\]/g, "\\$&");
};

// node_modules/minimatch/dist/esm/index.js
var minimatch = (p4, pattern, options = {}) => {
  assertValidPattern(pattern);
  if (!options.nocomment && pattern.charAt(0) === "#") {
    return false;
  }
  return new Minimatch(pattern, options).match(p4);
};
var starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/;
var starDotExtTest = (ext2) => (f4) => !f4.startsWith(".") && f4.endsWith(ext2);
var starDotExtTestDot = (ext2) => (f4) => f4.endsWith(ext2);
var starDotExtTestNocase = (ext2) => {
  ext2 = ext2.toLowerCase();
  return (f4) => !f4.startsWith(".") && f4.toLowerCase().endsWith(ext2);
};
var starDotExtTestNocaseDot = (ext2) => {
  ext2 = ext2.toLowerCase();
  return (f4) => f4.toLowerCase().endsWith(ext2);
};
var starDotStarRE = /^\*+\.\*+$/;
var starDotStarTest = (f4) => !f4.startsWith(".") && f4.includes(".");
var starDotStarTestDot = (f4) => f4 !== "." && f4 !== ".." && f4.includes(".");
var dotStarRE = /^\.\*+$/;
var dotStarTest = (f4) => f4 !== "." && f4 !== ".." && f4.startsWith(".");
var starRE = /^\*+$/;
var starTest = (f4) => f4.length !== 0 && !f4.startsWith(".");
var starTestDot = (f4) => f4.length !== 0 && f4 !== "." && f4 !== "..";
var qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/;
var qmarksTestNocase = ([$0, ext2 = ""]) => {
  const noext = qmarksTestNoExt([$0]);
  if (!ext2)
    return noext;
  ext2 = ext2.toLowerCase();
  return (f4) => noext(f4) && f4.toLowerCase().endsWith(ext2);
};
var qmarksTestNocaseDot = ([$0, ext2 = ""]) => {
  const noext = qmarksTestNoExtDot([$0]);
  if (!ext2)
    return noext;
  ext2 = ext2.toLowerCase();
  return (f4) => noext(f4) && f4.toLowerCase().endsWith(ext2);
};
var qmarksTestDot = ([$0, ext2 = ""]) => {
  const noext = qmarksTestNoExtDot([$0]);
  return !ext2 ? noext : (f4) => noext(f4) && f4.endsWith(ext2);
};
var qmarksTest = ([$0, ext2 = ""]) => {
  const noext = qmarksTestNoExt([$0]);
  return !ext2 ? noext : (f4) => noext(f4) && f4.endsWith(ext2);
};
var qmarksTestNoExt = ([$0]) => {
  const len = $0.length;
  return (f4) => f4.length === len && !f4.startsWith(".");
};
var qmarksTestNoExtDot = ([$0]) => {
  const len = $0.length;
  return (f4) => f4.length === len && f4 !== "." && f4 !== "..";
};
var defaultPlatform = typeof process === "object" && process ? typeof process.env === "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix";
var path5 = {
  win32: { sep: "\\" },
  posix: { sep: "/" }
};
var sep = defaultPlatform === "win32" ? path5.win32.sep : path5.posix.sep;
minimatch.sep = sep;
var GLOBSTAR = Symbol("globstar **");
minimatch.GLOBSTAR = GLOBSTAR;
var qmark2 = "[^/]";
var star2 = qmark2 + "*?";
var twoStarDot = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?";
var twoStarNoDot = "(?:(?!(?:\\/|^)\\.).)*?";
var filter = (pattern, options = {}) => (p4) => minimatch(p4, pattern, options);
minimatch.filter = filter;
var ext = (a3, b4 = {}) => Object.assign({}, a3, b4);
var defaults2 = (def) => {
  if (!def || typeof def !== "object" || !Object.keys(def).length) {
    return minimatch;
  }
  const orig = minimatch;
  const m4 = (p4, pattern, options = {}) => orig(p4, pattern, ext(def, options));
  return Object.assign(m4, {
    Minimatch: class Minimatch extends orig.Minimatch {
      constructor(pattern, options = {}) {
        super(pattern, ext(def, options));
      }
      static defaults(options) {
        return orig.defaults(ext(def, options)).Minimatch;
      }
    },
    AST: class AST extends orig.AST {
      /* c8 ignore start */
      constructor(type, parent, options = {}) {
        super(type, parent, ext(def, options));
      }
      /* c8 ignore stop */
      static fromGlob(pattern, options = {}) {
        return orig.AST.fromGlob(pattern, ext(def, options));
      }
    },
    unescape: (s6, options = {}) => orig.unescape(s6, ext(def, options)),
    escape: (s6, options = {}) => orig.escape(s6, ext(def, options)),
    filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),
    defaults: (options) => orig.defaults(ext(def, options)),
    makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),
    braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),
    match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),
    sep: orig.sep,
    GLOBSTAR
  });
};
minimatch.defaults = defaults2;
var braceExpand = (pattern, options = {}) => {
  assertValidPattern(pattern);
  if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
    return [pattern];
  }
  return expand(pattern, { max: options.braceExpandMax });
};
minimatch.braceExpand = braceExpand;
var makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();
minimatch.makeRe = makeRe;
var match = (list, pattern, options = {}) => {
  const mm = new Minimatch(pattern, options);
  list = list.filter((f4) => mm.match(f4));
  if (mm.options.nonull && !list.length) {
    list.push(pattern);
  }
  return list;
};
minimatch.match = match;
var globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
var regExpEscape2 = (s6) => s6.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
var Minimatch = class {
  options;
  set;
  pattern;
  windowsPathsNoEscape;
  nonegate;
  negate;
  comment;
  empty;
  preserveMultipleSlashes;
  partial;
  globSet;
  globParts;
  nocase;
  isWindows;
  platform;
  windowsNoMagicRoot;
  maxGlobstarRecursion;
  regexp;
  constructor(pattern, options = {}) {
    assertValidPattern(pattern);
    options = options || {};
    this.options = options;
    this.maxGlobstarRecursion = options.maxGlobstarRecursion ?? 200;
    this.pattern = pattern;
    this.platform = options.platform || defaultPlatform;
    this.isWindows = this.platform === "win32";
    const awe = "allowWindowsEscape";
    this.windowsPathsNoEscape = !!options.windowsPathsNoEscape || options[awe] === false;
    if (this.windowsPathsNoEscape) {
      this.pattern = this.pattern.replace(/\\/g, "/");
    }
    this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;
    this.regexp = null;
    this.negate = false;
    this.nonegate = !!options.nonegate;
    this.comment = false;
    this.empty = false;
    this.partial = !!options.partial;
    this.nocase = !!this.options.nocase;
    this.windowsNoMagicRoot = options.windowsNoMagicRoot !== void 0 ? options.windowsNoMagicRoot : !!(this.isWindows && this.nocase);
    this.globSet = [];
    this.globParts = [];
    this.set = [];
    this.make();
  }
  hasMagic() {
    if (this.options.magicalBraces && this.set.length > 1) {
      return true;
    }
    for (const pattern of this.set) {
      for (const part of pattern) {
        if (typeof part !== "string")
          return true;
      }
    }
    return false;
  }
  debug(..._3) {
  }
  make() {
    const pattern = this.pattern;
    const options = this.options;
    if (!options.nocomment && pattern.charAt(0) === "#") {
      this.comment = true;
      return;
    }
    if (!pattern) {
      this.empty = true;
      return;
    }
    this.parseNegate();
    this.globSet = [...new Set(this.braceExpand())];
    if (options.debug) {
      this.debug = (...args) => console.error(...args);
    }
    this.debug(this.pattern, this.globSet);
    const rawGlobParts = this.globSet.map((s6) => this.slashSplit(s6));
    this.globParts = this.preprocess(rawGlobParts);
    this.debug(this.pattern, this.globParts);
    let set2 = this.globParts.map((s6, _3, __) => {
      if (this.isWindows && this.windowsNoMagicRoot) {
        const isUNC = s6[0] === "" && s6[1] === "" && (s6[2] === "?" || !globMagic.test(s6[2])) && !globMagic.test(s6[3]);
        const isDrive = /^[a-z]:/i.test(s6[0]);
        if (isUNC) {
          return [
            ...s6.slice(0, 4),
            ...s6.slice(4).map((ss) => this.parse(ss))
          ];
        } else if (isDrive) {
          return [s6[0], ...s6.slice(1).map((ss) => this.parse(ss))];
        }
      }
      return s6.map((ss) => this.parse(ss));
    });
    this.debug(this.pattern, set2);
    this.set = set2.filter((s6) => s6.indexOf(false) === -1);
    if (this.isWindows) {
      for (let i7 = 0; i7 < this.set.length; i7++) {
        const p4 = this.set[i7];
        if (p4[0] === "" && p4[1] === "" && this.globParts[i7][2] === "?" && typeof p4[3] === "string" && /^[a-z]:$/i.test(p4[3])) {
          p4[2] = "?";
        }
      }
    }
    this.debug(this.pattern, this.set);
  }
  // various transforms to equivalent pattern sets that are
  // faster to process in a filesystem walk.  The goal is to
  // eliminate what we can, and push all ** patterns as far
  // to the right as possible, even if it increases the number
  // of patterns that we have to process.
  preprocess(globParts) {
    if (this.options.noglobstar) {
      for (let i7 = 0; i7 < globParts.length; i7++) {
        for (let j3 = 0; j3 < globParts[i7].length; j3++) {
          if (globParts[i7][j3] === "**") {
            globParts[i7][j3] = "*";
          }
        }
      }
    }
    const { optimizationLevel = 1 } = this.options;
    if (optimizationLevel >= 2) {
      globParts = this.firstPhasePreProcess(globParts);
      globParts = this.secondPhasePreProcess(globParts);
    } else if (optimizationLevel >= 1) {
      globParts = this.levelOneOptimize(globParts);
    } else {
      globParts = this.adjascentGlobstarOptimize(globParts);
    }
    return globParts;
  }
  // just get rid of adjascent ** portions
  adjascentGlobstarOptimize(globParts) {
    return globParts.map((parts) => {
      let gs = -1;
      while (-1 !== (gs = parts.indexOf("**", gs + 1))) {
        let i7 = gs;
        while (parts[i7 + 1] === "**") {
          i7++;
        }
        if (i7 !== gs) {
          parts.splice(gs, i7 - gs);
        }
      }
      return parts;
    });
  }
  // get rid of adjascent ** and resolve .. portions
  levelOneOptimize(globParts) {
    return globParts.map((parts) => {
      parts = parts.reduce((set2, part) => {
        const prev = set2[set2.length - 1];
        if (part === "**" && prev === "**") {
          return set2;
        }
        if (part === "..") {
          if (prev && prev !== ".." && prev !== "." && prev !== "**") {
            set2.pop();
            return set2;
          }
        }
        set2.push(part);
        return set2;
      }, []);
      return parts.length === 0 ? [""] : parts;
    });
  }
  levelTwoFileOptimize(parts) {
    if (!Array.isArray(parts)) {
      parts = this.slashSplit(parts);
    }
    let didSomething = false;
    do {
      didSomething = false;
      if (!this.preserveMultipleSlashes) {
        for (let i7 = 1; i7 < parts.length - 1; i7++) {
          const p4 = parts[i7];
          if (i7 === 1 && p4 === "" && parts[0] === "")
            continue;
          if (p4 === "." || p4 === "") {
            didSomething = true;
            parts.splice(i7, 1);
            i7--;
          }
        }
        if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) {
          didSomething = true;
          parts.pop();
        }
      }
      let dd = 0;
      while (-1 !== (dd = parts.indexOf("..", dd + 1))) {
        const p4 = parts[dd - 1];
        if (p4 && p4 !== "." && p4 !== ".." && p4 !== "**") {
          didSomething = true;
          parts.splice(dd - 1, 2);
          dd -= 2;
        }
      }
    } while (didSomething);
    return parts.length === 0 ? [""] : parts;
  }
  // First phase: single-pattern processing
  // <pre> is 1 or more portions
  // <rest> is 1 or more portions
  // <p> is any portion other than ., .., '', or **
  // <e> is . or ''
  //
  // **/.. is *brutal* for filesystem walking performance, because
  // it effectively resets the recursive walk each time it occurs,
  // and ** cannot be reduced out by a .. pattern part like a regexp
  // or most strings (other than .., ., and '') can be.
  //
  // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
  // <pre>/<e>/<rest> -> <pre>/<rest>
  // <pre>/<p>/../<rest> -> <pre>/<rest>
  // **/**/<rest> -> **/<rest>
  //
  // **/*/<rest> -> */**/<rest> <== not valid because ** doesn't follow
  // this WOULD be allowed if ** did follow symlinks, or * didn't
  firstPhasePreProcess(globParts) {
    let didSomething = false;
    do {
      didSomething = false;
      for (let parts of globParts) {
        let gs = -1;
        while (-1 !== (gs = parts.indexOf("**", gs + 1))) {
          let gss = gs;
          while (parts[gss + 1] === "**") {
            gss++;
          }
          if (gss > gs) {
            parts.splice(gs + 1, gss - gs);
          }
          let next = parts[gs + 1];
          const p4 = parts[gs + 2];
          const p22 = parts[gs + 3];
          if (next !== "..")
            continue;
          if (!p4 || p4 === "." || p4 === ".." || !p22 || p22 === "." || p22 === "..") {
            continue;
          }
          didSomething = true;
          parts.splice(gs, 1);
          const other = parts.slice(0);
          other[gs] = "**";
          globParts.push(other);
          gs--;
        }
        if (!this.preserveMultipleSlashes) {
          for (let i7 = 1; i7 < parts.length - 1; i7++) {
            const p4 = parts[i7];
            if (i7 === 1 && p4 === "" && parts[0] === "")
              continue;
            if (p4 === "." || p4 === "") {
              didSomething = true;
              parts.splice(i7, 1);
              i7--;
            }
          }
          if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) {
            didSomething = true;
            parts.pop();
          }
        }
        let dd = 0;
        while (-1 !== (dd = parts.indexOf("..", dd + 1))) {
          const p4 = parts[dd - 1];
          if (p4 && p4 !== "." && p4 !== ".." && p4 !== "**") {
            didSomething = true;
            const needDot = dd === 1 && parts[dd + 1] === "**";
            const splin = needDot ? ["."] : [];
            parts.splice(dd - 1, 2, ...splin);
            if (parts.length === 0)
              parts.push("");
            dd -= 2;
          }
        }
      }
    } while (didSomething);
    return globParts;
  }
  // second phase: multi-pattern dedupes
  // {<pre>/*/<rest>,<pre>/<p>/<rest>} -> <pre>/*/<rest>
  // {<pre>/<rest>,<pre>/<rest>} -> <pre>/<rest>
  // {<pre>/**/<rest>,<pre>/<rest>} -> <pre>/**/<rest>
  //
  // {<pre>/**/<rest>,<pre>/**/<p>/<rest>} -> <pre>/**/<rest>
  // ^-- not valid because ** doens't follow symlinks
  secondPhasePreProcess(globParts) {
    for (let i7 = 0; i7 < globParts.length - 1; i7++) {
      for (let j3 = i7 + 1; j3 < globParts.length; j3++) {
        const matched = this.partsMatch(globParts[i7], globParts[j3], !this.preserveMultipleSlashes);
        if (matched) {
          globParts[i7] = [];
          globParts[j3] = matched;
          break;
        }
      }
    }
    return globParts.filter((gs) => gs.length);
  }
  partsMatch(a3, b4, emptyGSMatch = false) {
    let ai = 0;
    let bi = 0;
    let result = [];
    let which = "";
    while (ai < a3.length && bi < b4.length) {
      if (a3[ai] === b4[bi]) {
        result.push(which === "b" ? b4[bi] : a3[ai]);
        ai++;
        bi++;
      } else if (emptyGSMatch && a3[ai] === "**" && b4[bi] === a3[ai + 1]) {
        result.push(a3[ai]);
        ai++;
      } else if (emptyGSMatch && b4[bi] === "**" && a3[ai] === b4[bi + 1]) {
        result.push(b4[bi]);
        bi++;
      } else if (a3[ai] === "*" && b4[bi] && (this.options.dot || !b4[bi].startsWith(".")) && b4[bi] !== "**") {
        if (which === "b")
          return false;
        which = "a";
        result.push(a3[ai]);
        ai++;
        bi++;
      } else if (b4[bi] === "*" && a3[ai] && (this.options.dot || !a3[ai].startsWith(".")) && a3[ai] !== "**") {
        if (which === "a")
          return false;
        which = "b";
        result.push(b4[bi]);
        ai++;
        bi++;
      } else {
        return false;
      }
    }
    return a3.length === b4.length && result;
  }
  parseNegate() {
    if (this.nonegate)
      return;
    const pattern = this.pattern;
    let negate = false;
    let negateOffset = 0;
    for (let i7 = 0; i7 < pattern.length && pattern.charAt(i7) === "!"; i7++) {
      negate = !negate;
      negateOffset++;
    }
    if (negateOffset)
      this.pattern = pattern.slice(negateOffset);
    this.negate = negate;
  }
  // set partial to true to test if, for example,
  // "/a/b" matches the start of "/*/b/*/d"
  // Partial means, if you run out of file before you run
  // out of pattern, then that's fine, as long as all
  // the parts match.
  matchOne(file, pattern, partial = false) {
    let fileStartIndex = 0;
    let patternStartIndex = 0;
    if (this.isWindows) {
      const fileDrive = typeof file[0] === "string" && /^[a-z]:$/i.test(file[0]);
      const fileUNC = !fileDrive && file[0] === "" && file[1] === "" && file[2] === "?" && /^[a-z]:$/i.test(file[3]);
      const patternDrive = typeof pattern[0] === "string" && /^[a-z]:$/i.test(pattern[0]);
      const patternUNC = !patternDrive && pattern[0] === "" && pattern[1] === "" && pattern[2] === "?" && typeof pattern[3] === "string" && /^[a-z]:$/i.test(pattern[3]);
      const fdi = fileUNC ? 3 : fileDrive ? 0 : void 0;
      const pdi = patternUNC ? 3 : patternDrive ? 0 : void 0;
      if (typeof fdi === "number" && typeof pdi === "number") {
        const [fd, pd] = [
          file[fdi],
          pattern[pdi]
        ];
        if (fd.toLowerCase() === pd.toLowerCase()) {
          pattern[pdi] = fd;
          patternStartIndex = pdi;
          fileStartIndex = fdi;
        }
      }
    }
    const { optimizationLevel = 1 } = this.options;
    if (optimizationLevel >= 2) {
      file = this.levelTwoFileOptimize(file);
    }
    if (pattern.includes(GLOBSTAR)) {
      return this.#matchGlobstar(file, pattern, partial, fileStartIndex, patternStartIndex);
    }
    return this.#matchOne(file, pattern, partial, fileStartIndex, patternStartIndex);
  }
  #matchGlobstar(file, pattern, partial, fileIndex, patternIndex) {
    const firstgs = pattern.indexOf(GLOBSTAR, patternIndex);
    const lastgs = pattern.lastIndexOf(GLOBSTAR);
    const [head, body, tail] = partial ? [
      pattern.slice(patternIndex, firstgs),
      pattern.slice(firstgs + 1),
      []
    ] : [
      pattern.slice(patternIndex, firstgs),
      pattern.slice(firstgs + 1, lastgs),
      pattern.slice(lastgs + 1)
    ];
    if (head.length) {
      const fileHead = file.slice(fileIndex, fileIndex + head.length);
      if (!this.#matchOne(fileHead, head, partial, 0, 0)) {
        return false;
      }
      fileIndex += head.length;
      patternIndex += head.length;
    }
    let fileTailMatch = 0;
    if (tail.length) {
      if (tail.length + fileIndex > file.length)
        return false;
      let tailStart = file.length - tail.length;
      if (this.#matchOne(file, tail, partial, tailStart, 0)) {
        fileTailMatch = tail.length;
      } else {
        if (file[file.length - 1] !== "" || fileIndex + tail.length === file.length) {
          return false;
        }
        tailStart--;
        if (!this.#matchOne(file, tail, partial, tailStart, 0)) {
          return false;
        }
        fileTailMatch = tail.length + 1;
      }
    }
    if (!body.length) {
      let sawSome = !!fileTailMatch;
      for (let i8 = fileIndex; i8 < file.length - fileTailMatch; i8++) {
        const f4 = String(file[i8]);
        sawSome = true;
        if (f4 === "." || f4 === ".." || !this.options.dot && f4.startsWith(".")) {
          return false;
        }
      }
      return partial || sawSome;
    }
    const bodySegments = [[[], 0]];
    let currentBody = bodySegments[0];
    let nonGsParts = 0;
    const nonGsPartsSums = [0];
    for (const b4 of body) {
      if (b4 === GLOBSTAR) {
        nonGsPartsSums.push(nonGsParts);
        currentBody = [[], 0];
        bodySegments.push(currentBody);
      } else {
        currentBody[0].push(b4);
        nonGsParts++;
      }
    }
    let i7 = bodySegments.length - 1;
    const fileLength = file.length - fileTailMatch;
    for (const b4 of bodySegments) {
      b4[1] = fileLength - (nonGsPartsSums[i7--] + b4[0].length);
    }
    return !!this.#matchGlobStarBodySections(file, bodySegments, fileIndex, 0, partial, 0, !!fileTailMatch);
  }
  // return false for "nope, not matching"
  // return null for "not matching, cannot keep trying"
  #matchGlobStarBodySections(file, bodySegments, fileIndex, bodyIndex, partial, globStarDepth, sawTail) {
    const bs = bodySegments[bodyIndex];
    if (!bs) {
      for (let i7 = fileIndex; i7 < file.length; i7++) {
        sawTail = true;
        const f4 = file[i7];
        if (f4 === "." || f4 === ".." || !this.options.dot && f4.startsWith(".")) {
          return false;
        }
      }
      return sawTail;
    }
    const [body, after] = bs;
    while (fileIndex <= after) {
      const m4 = this.#matchOne(file.slice(0, fileIndex + body.length), body, partial, fileIndex, 0);
      if (m4 && globStarDepth < this.maxGlobstarRecursion) {
        const sub2 = this.#matchGlobStarBodySections(file, bodySegments, fileIndex + body.length, bodyIndex + 1, partial, globStarDepth + 1, sawTail);
        if (sub2 !== false) {
          return sub2;
        }
      }
      const f4 = file[fileIndex];
      if (f4 === "." || f4 === ".." || !this.options.dot && f4.startsWith(".")) {
        return false;
      }
      fileIndex++;
    }
    return partial || null;
  }
  #matchOne(file, pattern, partial, fileIndex, patternIndex) {
    let fi;
    let pi;
    let pl;
    let fl;
    for (fi = fileIndex, pi = patternIndex, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
      this.debug("matchOne loop");
      let p4 = pattern[pi];
      let f4 = file[fi];
      this.debug(pattern, p4, f4);
      if (p4 === false || p4 === GLOBSTAR) {
        return false;
      }
      let hit;
      if (typeof p4 === "string") {
        hit = f4 === p4;
        this.debug("string match", p4, f4, hit);
      } else {
        hit = p4.test(f4);
        this.debug("pattern match", p4, f4, hit);
      }
      if (!hit)
        return false;
    }
    if (fi === fl && pi === pl) {
      return true;
    } else if (fi === fl) {
      return partial;
    } else if (pi === pl) {
      return fi === fl - 1 && file[fi] === "";
    } else {
      throw new Error("wtf?");
    }
  }
  braceExpand() {
    return braceExpand(this.pattern, this.options);
  }
  parse(pattern) {
    assertValidPattern(pattern);
    const options = this.options;
    if (pattern === "**")
      return GLOBSTAR;
    if (pattern === "")
      return "";
    let m4;
    let fastTest = null;
    if (m4 = pattern.match(starRE)) {
      fastTest = options.dot ? starTestDot : starTest;
    } else if (m4 = pattern.match(starDotExtRE)) {
      fastTest = (options.nocase ? options.dot ? starDotExtTestNocaseDot : starDotExtTestNocase : options.dot ? starDotExtTestDot : starDotExtTest)(m4[1]);
    } else if (m4 = pattern.match(qmarksRE)) {
      fastTest = (options.nocase ? options.dot ? qmarksTestNocaseDot : qmarksTestNocase : options.dot ? qmarksTestDot : qmarksTest)(m4);
    } else if (m4 = pattern.match(starDotStarRE)) {
      fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
    } else if (m4 = pattern.match(dotStarRE)) {
      fastTest = dotStarTest;
    }
    const re2 = AST.fromGlob(pattern, this.options).toMMPattern();
    if (fastTest && typeof re2 === "object") {
      Reflect.defineProperty(re2, "test", { value: fastTest });
    }
    return re2;
  }
  makeRe() {
    if (this.regexp || this.regexp === false)
      return this.regexp;
    const set2 = this.set;
    if (!set2.length) {
      this.regexp = false;
      return this.regexp;
    }
    const options = this.options;
    const twoStar = options.noglobstar ? star2 : options.dot ? twoStarDot : twoStarNoDot;
    const flags = new Set(options.nocase ? ["i"] : []);
    let re2 = set2.map((pattern) => {
      const pp = pattern.map((p4) => {
        if (p4 instanceof RegExp) {
          for (const f4 of p4.flags.split(""))
            flags.add(f4);
        }
        return typeof p4 === "string" ? regExpEscape2(p4) : p4 === GLOBSTAR ? GLOBSTAR : p4._src;
      });
      pp.forEach((p4, i7) => {
        const next = pp[i7 + 1];
        const prev = pp[i7 - 1];
        if (p4 !== GLOBSTAR || prev === GLOBSTAR) {
          return;
        }
        if (prev === void 0) {
          if (next !== void 0 && next !== GLOBSTAR) {
            pp[i7 + 1] = "(?:\\/|" + twoStar + "\\/)?" + next;
          } else {
            pp[i7] = twoStar;
          }
        } else if (next === void 0) {
          pp[i7 - 1] = prev + "(?:\\/|\\/" + twoStar + ")?";
        } else if (next !== GLOBSTAR) {
          pp[i7 - 1] = prev + "(?:\\/|\\/" + twoStar + "\\/)" + next;
          pp[i7 + 1] = GLOBSTAR;
        }
      });
      const filtered = pp.filter((p4) => p4 !== GLOBSTAR);
      if (this.partial && filtered.length >= 1) {
        const prefixes = [];
        for (let i7 = 1; i7 <= filtered.length; i7++) {
          prefixes.push(filtered.slice(0, i7).join("/"));
        }
        return "(?:" + prefixes.join("|") + ")";
      }
      return filtered.join("/");
    }).join("|");
    const [open2, close2] = set2.length > 1 ? ["(?:", ")"] : ["", ""];
    re2 = "^" + open2 + re2 + close2 + "$";
    if (this.partial) {
      re2 = "^(?:\\/|" + open2 + re2.slice(1, -1) + close2 + ")$";
    }
    if (this.negate)
      re2 = "^(?!" + re2 + ").+$";
    try {
      this.regexp = new RegExp(re2, [...flags].join(""));
    } catch (ex) {
      this.regexp = false;
    }
    return this.regexp;
  }
  slashSplit(p4) {
    if (this.preserveMultipleSlashes) {
      return p4.split("/");
    } else if (this.isWindows && /^\/\/[^\/]+/.test(p4)) {
      return ["", ...p4.split(/\/+/)];
    } else {
      return p4.split(/\/+/);
    }
  }
  match(f4, partial = this.partial) {
    this.debug("match", f4, this.pattern);
    if (this.comment) {
      return false;
    }
    if (this.empty) {
      return f4 === "";
    }
    if (f4 === "/" && partial) {
      return true;
    }
    const options = this.options;
    if (this.isWindows) {
      f4 = f4.split("\\").join("/");
    }
    const ff = this.slashSplit(f4);
    this.debug(this.pattern, "split", ff);
    const set2 = this.set;
    this.debug(this.pattern, "set", set2);
    let filename = ff[ff.length - 1];
    if (!filename) {
      for (let i7 = ff.length - 2; !filename && i7 >= 0; i7--) {
        filename = ff[i7];
      }
    }
    for (let i7 = 0; i7 < set2.length; i7++) {
      const pattern = set2[i7];
      let file = ff;
      if (options.matchBase && pattern.length === 1) {
        file = [filename];
      }
      const hit = this.matchOne(file, pattern, partial);
      if (hit) {
        if (options.flipNegate) {
          return true;
        }
        return !this.negate;
      }
    }
    if (options.flipNegate) {
      return false;
    }
    return this.negate;
  }
  static defaults(def) {
    return minimatch.defaults(def).Minimatch;
  }
};
minimatch.AST = AST;
minimatch.Minimatch = Minimatch;
minimatch.escape = escape3;
minimatch.unescape = unescape2;

// src/storage/stores/skills-store.ts
var SkillsStore = class extends Store {
  getConfig() {
    return {
      name: "skills"
    };
  }
  async get(name) {
    return this.getBackend().get("skills", name);
  }
  async save(skill) {
    await this.getBackend().set("skills", skill.name, skill);
  }
  async delete(name) {
    await this.getBackend().delete("skills", name);
  }
  async list(currentUrl) {
    const keys2 = await this.getBackend().keys("skills");
    const skills = await Promise.all(keys2.map((key) => this.getBackend().get("skills", key)));
    const validSkills = skills.filter((s6) => s6 !== null);
    if (currentUrl) {
      return validSkills.filter((skill) => this.matchesAnyPattern(currentUrl, skill.domainPatterns));
    }
    return validSkills;
  }
  async getForUrl(url) {
    return this.list(url);
  }
  // Alias methods for backward compatibility
  async getSkillsForUrl(url) {
    return this.getForUrl(url);
  }
  async getSkill(name) {
    return this.get(name);
  }
  async saveSkill(skill) {
    return this.save(skill);
  }
  async deleteSkill(name) {
    return this.delete(name);
  }
  async listSkills(currentUrl) {
    return this.list(currentUrl);
  }
  /**
   * Check if URL matches any of the domain patterns using glob matching.
   */
  matchesAnyPattern(url, patterns) {
    try {
      const urlObj = new URL(url);
      const hostname = urlObj.hostname;
      const path6 = urlObj.pathname;
      for (const pattern of patterns) {
        const parts = pattern.split("/");
        const domainPattern = parts[0];
        const pathPattern = parts.length > 1 ? `/${parts.slice(1).join("/")}` : "";
        const normalizedHostname = hostname.replace(/^www\./, "");
        const normalizedPattern = domainPattern.replace(/^www\./, "");
        const domainMatches = minimatch(normalizedHostname, normalizedPattern, {
          nocase: true
        });
        if (!pathPattern || pathPattern === "/") {
          if (domainMatches) return true;
        } else {
          const pathMatches = minimatch(path6, pathPattern, { nocase: true });
          if (domainMatches && pathMatches) return true;
        }
      }
      return false;
    } catch {
      return false;
    }
  }
};

// src/storage/app-storage.ts
var SitegeistAppStorage = class extends AppStorage {
  constructor() {
    const settings = new SettingsStore();
    const providerKeys = new ProviderKeysStore();
    const sessions = new SitegeistSessionsStore();
    const customProviders = new CustomProvidersStore();
    const skills = new SkillsStore();
    const costs = new CostStore();
    const configs = [
      settings.getConfig(),
      SessionsStore.getMetadataConfig(),
      providerKeys.getConfig(),
      customProviders.getConfig(),
      sessions.getConfig(),
      skills.getConfig(),
      costs.getConfig()
    ];
    const backend = new IndexedDBStorageBackend({
      dbName: "sitegeist-storage",
      version: 3,
      // Increment version to add custom-providers store
      stores: configs
    });
    settings.setBackend(backend);
    providerKeys.setBackend(backend);
    customProviders.setBackend(backend);
    sessions.setBackend(backend);
    skills.setBackend(backend);
    costs.setBackend(backend);
    super(settings, providerKeys, sessions, customProviders, backend);
    this.skills = skills;
    this.costs = costs;
  }
};

// src/tools/ask-user-which-element.ts
init_process_shim();

// node_modules/@sinclair/typebox/build/esm/type/clone/type.mjs
init_process_shim();

// node_modules/@sinclair/typebox/build/esm/type/clone/value.mjs
init_process_shim();

// node_modules/@sinclair/typebox/build/esm/type/guard/value.mjs
var value_exports2 = {};
__export(value_exports2, {
  HasPropertyKey: () => HasPropertyKey2,
  IsArray: () => IsArray5,
  IsAsyncIterator: () => IsAsyncIterator4,
  IsBigInt: () => IsBigInt4,
  IsBoolean: () => IsBoolean4,
  IsDate: () => IsDate4,
  IsFunction: () => IsFunction4,
  IsIterator: () => IsIterator4,
  IsNull: () => IsNull4,
  IsNumber: () => IsNumber5,
  IsObject: () => IsObject5,
  IsRegExp: () => IsRegExp4,
  IsString: () => IsString4,
  IsSymbol: () => IsSymbol4,
  IsUint8Array: () => IsUint8Array4,
  IsUndefined: () => IsUndefined5
});
init_process_shim();
function HasPropertyKey2(value, key) {
  return key in value;
}
function IsAsyncIterator4(value) {
  return IsObject5(value) && !IsArray5(value) && !IsUint8Array4(value) && Symbol.asyncIterator in value;
}
function IsArray5(value) {
  return Array.isArray(value);
}
function IsBigInt4(value) {
  return typeof value === "bigint";
}
function IsBoolean4(value) {
  return typeof value === "boolean";
}
function IsDate4(value) {
  return value instanceof globalThis.Date;
}
function IsFunction4(value) {
  return typeof value === "function";
}
function IsIterator4(value) {
  return IsObject5(value) && !IsArray5(value) && !IsUint8Array4(value) && Symbol.iterator in value;
}
function IsNull4(value) {
  return value === null;
}
function IsNumber5(value) {
  return typeof value === "number";
}
function IsObject5(value) {
  return typeof value === "object" && value !== null;
}
function IsRegExp4(value) {
  return value instanceof globalThis.RegExp;
}
function IsString4(value) {
  return typeof value === "string";
}
function IsSymbol4(value) {
  return typeof value === "symbol";
}
function IsUint8Array4(value) {
  return value instanceof globalThis.Uint8Array;
}
function IsUndefined5(value) {
  return value === void 0;
}

// node_modules/@sinclair/typebox/build/esm/type/clone/value.mjs
function ArrayType2(value) {
  return value.map((value2) => Visit4(value2));
}
function DateType2(value) {
  return new Date(value.getTime());
}
function Uint8ArrayType2(value) {
  return new Uint8Array(value);
}
function RegExpType2(value) {
  return new RegExp(value.source, value.flags);
}
function ObjectType2(value) {
  const result = {};
  for (const key of Object.getOwnPropertyNames(value)) {
    result[key] = Visit4(value[key]);
  }
  for (const key of Object.getOwnPropertySymbols(value)) {
    result[key] = Visit4(value[key]);
  }
  return result;
}
function Visit4(value) {
  return IsArray5(value) ? ArrayType2(value) : IsDate4(value) ? DateType2(value) : IsUint8Array4(value) ? Uint8ArrayType2(value) : IsRegExp4(value) ? RegExpType2(value) : IsObject5(value) ? ObjectType2(value) : value;
}
function Clone2(value) {
  return Visit4(value);
}

// node_modules/@sinclair/typebox/build/esm/type/clone/type.mjs
function CloneType2(schema, options) {
  return options === void 0 ? Clone2(schema) : Clone2({ ...options, ...schema });
}

// node_modules/@sinclair/typebox/build/esm/type/create/type.mjs
init_process_shim();

// node_modules/@sinclair/typebox/build/esm/system/policy.mjs
init_process_shim();

// node_modules/@sinclair/typebox/build/esm/value/guard/guard.mjs
init_process_shim();
function IsObject6(value) {
  return value !== null && typeof value === "object";
}
function IsArray6(value) {
  return globalThis.Array.isArray(value) && !globalThis.ArrayBuffer.isView(value);
}
function IsUndefined6(value) {
  return value === void 0;
}
function IsNumber6(value) {
  return typeof value === "number";
}

// node_modules/@sinclair/typebox/build/esm/system/policy.mjs
var TypeSystemPolicy2;
(function(TypeSystemPolicy3) {
  TypeSystemPolicy3.InstanceMode = "default";
  TypeSystemPolicy3.ExactOptionalPropertyTypes = false;
  TypeSystemPolicy3.AllowArrayObject = false;
  TypeSystemPolicy3.AllowNaN = false;
  TypeSystemPolicy3.AllowNullVoid = false;
  function IsExactOptionalProperty(value, key) {
    return TypeSystemPolicy3.ExactOptionalPropertyTypes ? key in value : value[key] !== void 0;
  }
  TypeSystemPolicy3.IsExactOptionalProperty = IsExactOptionalProperty;
  function IsObjectLike(value) {
    const isObject2 = IsObject6(value);
    return TypeSystemPolicy3.AllowArrayObject ? isObject2 : isObject2 && !IsArray6(value);
  }
  TypeSystemPolicy3.IsObjectLike = IsObjectLike;
  function IsRecordLike(value) {
    return IsObjectLike(value) && !(value instanceof Date) && !(value instanceof Uint8Array);
  }
  TypeSystemPolicy3.IsRecordLike = IsRecordLike;
  function IsNumberLike(value) {
    return TypeSystemPolicy3.AllowNaN ? IsNumber6(value) : Number.isFinite(value);
  }
  TypeSystemPolicy3.IsNumberLike = IsNumberLike;
  function IsVoidLike(value) {
    const isUndefined2 = IsUndefined6(value);
    return TypeSystemPolicy3.AllowNullVoid ? isUndefined2 || value === null : isUndefined2;
  }
  TypeSystemPolicy3.IsVoidLike = IsVoidLike;
})(TypeSystemPolicy2 || (TypeSystemPolicy2 = {}));

// node_modules/@sinclair/typebox/build/esm/type/create/immutable.mjs
init_process_shim();
function ImmutableArray2(value) {
  return globalThis.Object.freeze(value).map((value2) => Immutable2(value2));
}
function ImmutableDate2(value) {
  return value;
}
function ImmutableUint8Array2(value) {
  return value;
}
function ImmutableRegExp2(value) {
  return value;
}
function ImmutableObject2(value) {
  const result = {};
  for (const key of Object.getOwnPropertyNames(value)) {
    result[key] = Immutable2(value[key]);
  }
  for (const key of Object.getOwnPropertySymbols(value)) {
    result[key] = Immutable2(value[key]);
  }
  return globalThis.Object.freeze(result);
}
function Immutable2(value) {
  return IsArray5(value) ? ImmutableArray2(value) : IsDate4(value) ? ImmutableDate2(value) : IsUint8Array4(value) ? ImmutableUint8Array2(value) : IsRegExp4(value) ? ImmutableRegExp2(value) : IsObject5(value) ? ImmutableObject2(value) : value;
}

// node_modules/@sinclair/typebox/build/esm/type/create/type.mjs
function CreateType2(schema, options) {
  const result = options !== void 0 ? { ...options, ...schema } : schema;
  switch (TypeSystemPolicy2.InstanceMode) {
    case "freeze":
      return Immutable2(result);
    case "clone":
      return Clone2(result);
    default:
      return result;
  }
}

// node_modules/@sinclair/typebox/build/esm/type/error/error.mjs
init_process_shim();
var TypeBoxError2 = class extends Error {
  constructor(message) {
    super(message);
  }
};

// node_modules/@sinclair/typebox/build/esm/type/guard/index.mjs
init_process_shim();

// node_modules/@sinclair/typebox/build/esm/type/guard/kind.mjs
init_process_shim();

// node_modules/@sinclair/typebox/build/esm/type/symbols/symbols.mjs
init_process_shim();
var TransformKind2 = Symbol.for("TypeBox.Transform");
var ReadonlyKind2 = Symbol.for("TypeBox.Readonly");
var OptionalKind2 = Symbol.for("TypeBox.Optional");
var Hint2 = Symbol.for("TypeBox.Hint");
var Kind2 = Symbol.for("TypeBox.Kind");

// node_modules/@sinclair/typebox/build/esm/type/guard/kind.mjs
function IsReadonly3(value) {
  return IsObject5(value) && value[ReadonlyKind2] === "Readonly";
}
function IsOptional3(value) {
  return IsObject5(value) && value[OptionalKind2] === "Optional";
}
function IsAny3(value) {
  return IsKindOf3(value, "Any");
}
function IsArgument3(value) {
  return IsKindOf3(value, "Argument");
}
function IsArray7(value) {
  return IsKindOf3(value, "Array");
}
function IsAsyncIterator5(value) {
  return IsKindOf3(value, "AsyncIterator");
}
function IsBigInt5(value) {
  return IsKindOf3(value, "BigInt");
}
function IsBoolean5(value) {
  return IsKindOf3(value, "Boolean");
}
function IsComputed3(value) {
  return IsKindOf3(value, "Computed");
}
function IsConstructor3(value) {
  return IsKindOf3(value, "Constructor");
}
function IsDate5(value) {
  return IsKindOf3(value, "Date");
}
function IsFunction5(value) {
  return IsKindOf3(value, "Function");
}
function IsInteger3(value) {
  return IsKindOf3(value, "Integer");
}
function IsIntersect3(value) {
  return IsKindOf3(value, "Intersect");
}
function IsIterator5(value) {
  return IsKindOf3(value, "Iterator");
}
function IsKindOf3(value, kind) {
  return IsObject5(value) && Kind2 in value && value[Kind2] === kind;
}
function IsLiteralValue3(value) {
  return IsBoolean4(value) || IsNumber5(value) || IsString4(value);
}
function IsLiteral3(value) {
  return IsKindOf3(value, "Literal");
}
function IsMappedKey3(value) {
  return IsKindOf3(value, "MappedKey");
}
function IsMappedResult3(value) {
  return IsKindOf3(value, "MappedResult");
}
function IsNever3(value) {
  return IsKindOf3(value, "Never");
}
function IsNot3(value) {
  return IsKindOf3(value, "Not");
}
function IsNull5(value) {
  return IsKindOf3(value, "Null");
}
function IsNumber7(value) {
  return IsKindOf3(value, "Number");
}
function IsObject7(value) {
  return IsKindOf3(value, "Object");
}
function IsPromise3(value) {
  return IsKindOf3(value, "Promise");
}
function IsRecord3(value) {
  return IsKindOf3(value, "Record");
}
function IsRef3(value) {
  return IsKindOf3(value, "Ref");
}
function IsRegExp5(value) {
  return IsKindOf3(value, "RegExp");
}
function IsString5(value) {
  return IsKindOf3(value, "String");
}
function IsSymbol5(value) {
  return IsKindOf3(value, "Symbol");
}
function IsTemplateLiteral3(value) {
  return IsKindOf3(value, "TemplateLiteral");
}
function IsThis3(value) {
  return IsKindOf3(value, "This");
}
function IsTransform3(value) {
  return IsObject5(value) && TransformKind2 in value;
}
function IsTuple3(value) {
  return IsKindOf3(value, "Tuple");
}
function IsUndefined7(value) {
  return IsKindOf3(value, "Undefined");
}
function IsUnion3(value) {
  return IsKindOf3(value, "Union");
}
function IsUint8Array5(value) {
  return IsKindOf3(value, "Uint8Array");
}
function IsUnknown3(value) {
  return IsKindOf3(value, "Unknown");
}
function IsUnsafe3(value) {
  return IsKindOf3(value, "Unsafe");
}
function IsVoid3(value) {
  return IsKindOf3(value, "Void");
}
function IsKind3(value) {
  return IsObject5(value) && Kind2 in value && IsString4(value[Kind2]);
}
function IsSchema3(value) {
  return IsAny3(value) || IsArgument3(value) || IsArray7(value) || IsBoolean5(value) || IsBigInt5(value) || IsAsyncIterator5(value) || IsComputed3(value) || IsConstructor3(value) || IsDate5(value) || IsFunction5(value) || IsInteger3(value) || IsIntersect3(value) || IsIterator5(value) || IsLiteral3(value) || IsMappedKey3(value) || IsMappedResult3(value) || IsNever3(value) || IsNot3(value) || IsNull5(value) || IsNumber7(value) || IsObject7(value) || IsPromise3(value) || IsRecord3(value) || IsRef3(value) || IsRegExp5(value) || IsString5(value) || IsSymbol5(value) || IsTemplateLiteral3(value) || IsThis3(value) || IsTuple3(value) || IsUndefined7(value) || IsUnion3(value) || IsUint8Array5(value) || IsUnknown3(value) || IsUnsafe3(value) || IsVoid3(value) || IsKind3(value);
}

// node_modules/@sinclair/typebox/build/esm/type/guard/type.mjs
var type_exports3 = {};
__export(type_exports3, {
  IsAny: () => IsAny4,
  IsArgument: () => IsArgument4,
  IsArray: () => IsArray8,
  IsAsyncIterator: () => IsAsyncIterator6,
  IsBigInt: () => IsBigInt6,
  IsBoolean: () => IsBoolean6,
  IsComputed: () => IsComputed4,
  IsConstructor: () => IsConstructor4,
  IsDate: () => IsDate6,
  IsFunction: () => IsFunction6,
  IsImport: () => IsImport2,
  IsInteger: () => IsInteger4,
  IsIntersect: () => IsIntersect4,
  IsIterator: () => IsIterator6,
  IsKind: () => IsKind4,
  IsKindOf: () => IsKindOf4,
  IsLiteral: () => IsLiteral4,
  IsLiteralBoolean: () => IsLiteralBoolean2,
  IsLiteralNumber: () => IsLiteralNumber2,
  IsLiteralString: () => IsLiteralString2,
  IsLiteralValue: () => IsLiteralValue4,
  IsMappedKey: () => IsMappedKey4,
  IsMappedResult: () => IsMappedResult4,
  IsNever: () => IsNever4,
  IsNot: () => IsNot4,
  IsNull: () => IsNull6,
  IsNumber: () => IsNumber8,
  IsObject: () => IsObject8,
  IsOptional: () => IsOptional4,
  IsPromise: () => IsPromise4,
  IsProperties: () => IsProperties2,
  IsReadonly: () => IsReadonly4,
  IsRecord: () => IsRecord4,
  IsRecursive: () => IsRecursive2,
  IsRef: () => IsRef4,
  IsRegExp: () => IsRegExp6,
  IsSchema: () => IsSchema4,
  IsString: () => IsString6,
  IsSymbol: () => IsSymbol6,
  IsTemplateLiteral: () => IsTemplateLiteral4,
  IsThis: () => IsThis4,
  IsTransform: () => IsTransform4,
  IsTuple: () => IsTuple4,
  IsUint8Array: () => IsUint8Array6,
  IsUndefined: () => IsUndefined8,
  IsUnion: () => IsUnion4,
  IsUnionLiteral: () => IsUnionLiteral2,
  IsUnknown: () => IsUnknown4,
  IsUnsafe: () => IsUnsafe4,
  IsVoid: () => IsVoid4,
  TypeGuardUnknownTypeError: () => TypeGuardUnknownTypeError2
});
init_process_shim();
var TypeGuardUnknownTypeError2 = class extends TypeBoxError2 {
};
var KnownTypes2 = [
  "Argument",
  "Any",
  "Array",
  "AsyncIterator",
  "BigInt",
  "Boolean",
  "Computed",
  "Constructor",
  "Date",
  "Enum",
  "Function",
  "Integer",
  "Intersect",
  "Iterator",
  "Literal",
  "MappedKey",
  "MappedResult",
  "Not",
  "Null",
  "Number",
  "Object",
  "Promise",
  "Record",
  "Ref",
  "RegExp",
  "String",
  "Symbol",
  "TemplateLiteral",
  "This",
  "Tuple",
  "Undefined",
  "Union",
  "Uint8Array",
  "Unknown",
  "Void"
];
function IsPattern2(value) {
  try {
    new RegExp(value);
    return true;
  } catch {
    return false;
  }
}
function IsControlCharacterFree2(value) {
  if (!IsString4(value))
    return false;
  for (let i7 = 0; i7 < value.length; i7++) {
    const code = value.charCodeAt(i7);
    if (code >= 7 && code <= 13 || code === 27 || code === 127) {
      return false;
    }
  }
  return true;
}
function IsAdditionalProperties2(value) {
  return IsOptionalBoolean2(value) || IsSchema4(value);
}
function IsOptionalBigInt2(value) {
  return IsUndefined5(value) || IsBigInt4(value);
}
function IsOptionalNumber2(value) {
  return IsUndefined5(value) || IsNumber5(value);
}
function IsOptionalBoolean2(value) {
  return IsUndefined5(value) || IsBoolean4(value);
}
function IsOptionalString2(value) {
  return IsUndefined5(value) || IsString4(value);
}
function IsOptionalPattern2(value) {
  return IsUndefined5(value) || IsString4(value) && IsControlCharacterFree2(value) && IsPattern2(value);
}
function IsOptionalFormat2(value) {
  return IsUndefined5(value) || IsString4(value) && IsControlCharacterFree2(value);
}
function IsOptionalSchema2(value) {
  return IsUndefined5(value) || IsSchema4(value);
}
function IsReadonly4(value) {
  return IsObject5(value) && value[ReadonlyKind2] === "Readonly";
}
function IsOptional4(value) {
  return IsObject5(value) && value[OptionalKind2] === "Optional";
}
function IsAny4(value) {
  return IsKindOf4(value, "Any") && IsOptionalString2(value.$id);
}
function IsArgument4(value) {
  return IsKindOf4(value, "Argument") && IsNumber5(value.index);
}
function IsArray8(value) {
  return IsKindOf4(value, "Array") && value.type === "array" && IsOptionalString2(value.$id) && IsSchema4(value.items) && IsOptionalNumber2(value.minItems) && IsOptionalNumber2(value.maxItems) && IsOptionalBoolean2(value.uniqueItems) && IsOptionalSchema2(value.contains) && IsOptionalNumber2(value.minContains) && IsOptionalNumber2(value.maxContains);
}
function IsAsyncIterator6(value) {
  return IsKindOf4(value, "AsyncIterator") && value.type === "AsyncIterator" && IsOptionalString2(value.$id) && IsSchema4(value.items);
}
function IsBigInt6(value) {
  return IsKindOf4(value, "BigInt") && value.type === "bigint" && IsOptionalString2(value.$id) && IsOptionalBigInt2(value.exclusiveMaximum) && IsOptionalBigInt2(value.exclusiveMinimum) && IsOptionalBigInt2(value.maximum) && IsOptionalBigInt2(value.minimum) && IsOptionalBigInt2(value.multipleOf);
}
function IsBoolean6(value) {
  return IsKindOf4(value, "Boolean") && value.type === "boolean" && IsOptionalString2(value.$id);
}
function IsComputed4(value) {
  return IsKindOf4(value, "Computed") && IsString4(value.target) && IsArray5(value.parameters) && value.parameters.every((schema) => IsSchema4(schema));
}
function IsConstructor4(value) {
  return IsKindOf4(value, "Constructor") && value.type === "Constructor" && IsOptionalString2(value.$id) && IsArray5(value.parameters) && value.parameters.every((schema) => IsSchema4(schema)) && IsSchema4(value.returns);
}
function IsDate6(value) {
  return IsKindOf4(value, "Date") && value.type === "Date" && IsOptionalString2(value.$id) && IsOptionalNumber2(value.exclusiveMaximumTimestamp) && IsOptionalNumber2(value.exclusiveMinimumTimestamp) && IsOptionalNumber2(value.maximumTimestamp) && IsOptionalNumber2(value.minimumTimestamp) && IsOptionalNumber2(value.multipleOfTimestamp);
}
function IsFunction6(value) {
  return IsKindOf4(value, "Function") && value.type === "Function" && IsOptionalString2(value.$id) && IsArray5(value.parameters) && value.parameters.every((schema) => IsSchema4(schema)) && IsSchema4(value.returns);
}
function IsImport2(value) {
  return IsKindOf4(value, "Import") && HasPropertyKey2(value, "$defs") && IsObject5(value.$defs) && IsProperties2(value.$defs) && HasPropertyKey2(value, "$ref") && IsString4(value.$ref) && value.$ref in value.$defs;
}
function IsInteger4(value) {
  return IsKindOf4(value, "Integer") && value.type === "integer" && IsOptionalString2(value.$id) && IsOptionalNumber2(value.exclusiveMaximum) && IsOptionalNumber2(value.exclusiveMinimum) && IsOptionalNumber2(value.maximum) && IsOptionalNumber2(value.minimum) && IsOptionalNumber2(value.multipleOf);
}
function IsProperties2(value) {
  return IsObject5(value) && Object.entries(value).every(([key, schema]) => IsControlCharacterFree2(key) && IsSchema4(schema));
}
function IsIntersect4(value) {
  return IsKindOf4(value, "Intersect") && (IsString4(value.type) && value.type !== "object" ? false : true) && IsArray5(value.allOf) && value.allOf.every((schema) => IsSchema4(schema) && !IsTransform4(schema)) && IsOptionalString2(value.type) && (IsOptionalBoolean2(value.unevaluatedProperties) || IsOptionalSchema2(value.unevaluatedProperties)) && IsOptionalString2(value.$id);
}
function IsIterator6(value) {
  return IsKindOf4(value, "Iterator") && value.type === "Iterator" && IsOptionalString2(value.$id) && IsSchema4(value.items);
}
function IsKindOf4(value, kind) {
  return IsObject5(value) && Kind2 in value && value[Kind2] === kind;
}
function IsLiteralString2(value) {
  return IsLiteral4(value) && IsString4(value.const);
}
function IsLiteralNumber2(value) {
  return IsLiteral4(value) && IsNumber5(value.const);
}
function IsLiteralBoolean2(value) {
  return IsLiteral4(value) && IsBoolean4(value.const);
}
function IsLiteral4(value) {
  return IsKindOf4(value, "Literal") && IsOptionalString2(value.$id) && IsLiteralValue4(value.const);
}
function IsLiteralValue4(value) {
  return IsBoolean4(value) || IsNumber5(value) || IsString4(value);
}
function IsMappedKey4(value) {
  return IsKindOf4(value, "MappedKey") && IsArray5(value.keys) && value.keys.every((key) => IsNumber5(key) || IsString4(key));
}
function IsMappedResult4(value) {
  return IsKindOf4(value, "MappedResult") && IsProperties2(value.properties);
}
function IsNever4(value) {
  return IsKindOf4(value, "Never") && IsObject5(value.not) && Object.getOwnPropertyNames(value.not).length === 0;
}
function IsNot4(value) {
  return IsKindOf4(value, "Not") && IsSchema4(value.not);
}
function IsNull6(value) {
  return IsKindOf4(value, "Null") && value.type === "null" && IsOptionalString2(value.$id);
}
function IsNumber8(value) {
  return IsKindOf4(value, "Number") && value.type === "number" && IsOptionalString2(value.$id) && IsOptionalNumber2(value.exclusiveMaximum) && IsOptionalNumber2(value.exclusiveMinimum) && IsOptionalNumber2(value.maximum) && IsOptionalNumber2(value.minimum) && IsOptionalNumber2(value.multipleOf);
}
function IsObject8(value) {
  return IsKindOf4(value, "Object") && value.type === "object" && IsOptionalString2(value.$id) && IsProperties2(value.properties) && IsAdditionalProperties2(value.additionalProperties) && IsOptionalNumber2(value.minProperties) && IsOptionalNumber2(value.maxProperties);
}
function IsPromise4(value) {
  return IsKindOf4(value, "Promise") && value.type === "Promise" && IsOptionalString2(value.$id) && IsSchema4(value.item);
}
function IsRecord4(value) {
  return IsKindOf4(value, "Record") && value.type === "object" && IsOptionalString2(value.$id) && IsAdditionalProperties2(value.additionalProperties) && IsObject5(value.patternProperties) && ((schema) => {
    const keys2 = Object.getOwnPropertyNames(schema.patternProperties);
    return keys2.length === 1 && IsPattern2(keys2[0]) && IsObject5(schema.patternProperties) && IsSchema4(schema.patternProperties[keys2[0]]);
  })(value);
}
function IsRecursive2(value) {
  return IsObject5(value) && Hint2 in value && value[Hint2] === "Recursive";
}
function IsRef4(value) {
  return IsKindOf4(value, "Ref") && IsOptionalString2(value.$id) && IsString4(value.$ref);
}
function IsRegExp6(value) {
  return IsKindOf4(value, "RegExp") && IsOptionalString2(value.$id) && IsString4(value.source) && IsString4(value.flags) && IsOptionalNumber2(value.maxLength) && IsOptionalNumber2(value.minLength);
}
function IsString6(value) {
  return IsKindOf4(value, "String") && value.type === "string" && IsOptionalString2(value.$id) && IsOptionalNumber2(value.minLength) && IsOptionalNumber2(value.maxLength) && IsOptionalPattern2(value.pattern) && IsOptionalFormat2(value.format);
}
function IsSymbol6(value) {
  return IsKindOf4(value, "Symbol") && value.type === "symbol" && IsOptionalString2(value.$id);
}
function IsTemplateLiteral4(value) {
  return IsKindOf4(value, "TemplateLiteral") && value.type === "string" && IsString4(value.pattern) && value.pattern[0] === "^" && value.pattern[value.pattern.length - 1] === "$";
}
function IsThis4(value) {
  return IsKindOf4(value, "This") && IsOptionalString2(value.$id) && IsString4(value.$ref);
}
function IsTransform4(value) {
  return IsObject5(value) && TransformKind2 in value;
}
function IsTuple4(value) {
  return IsKindOf4(value, "Tuple") && value.type === "array" && IsOptionalString2(value.$id) && IsNumber5(value.minItems) && IsNumber5(value.maxItems) && value.minItems === value.maxItems && // empty
  (IsUndefined5(value.items) && IsUndefined5(value.additionalItems) && value.minItems === 0 || IsArray5(value.items) && value.items.every((schema) => IsSchema4(schema)));
}
function IsUndefined8(value) {
  return IsKindOf4(value, "Undefined") && value.type === "undefined" && IsOptionalString2(value.$id);
}
function IsUnionLiteral2(value) {
  return IsUnion4(value) && value.anyOf.every((schema) => IsLiteralString2(schema) || IsLiteralNumber2(schema));
}
function IsUnion4(value) {
  return IsKindOf4(value, "Union") && IsOptionalString2(value.$id) && IsObject5(value) && IsArray5(value.anyOf) && value.anyOf.every((schema) => IsSchema4(schema));
}
function IsUint8Array6(value) {
  return IsKindOf4(value, "Uint8Array") && value.type === "Uint8Array" && IsOptionalString2(value.$id) && IsOptionalNumber2(value.minByteLength) && IsOptionalNumber2(value.maxByteLength);
}
function IsUnknown4(value) {
  return IsKindOf4(value, "Unknown") && IsOptionalString2(value.$id);
}
function IsUnsafe4(value) {
  return IsKindOf4(value, "Unsafe");
}
function IsVoid4(value) {
  return IsKindOf4(value, "Void") && value.type === "void" && IsOptionalString2(value.$id);
}
function IsKind4(value) {
  return IsObject5(value) && Kind2 in value && IsString4(value[Kind2]) && !KnownTypes2.includes(value[Kind2]);
}
function IsSchema4(value) {
  return IsObject5(value) && (IsAny4(value) || IsArgument4(value) || IsArray8(value) || IsBoolean6(value) || IsBigInt6(value) || IsAsyncIterator6(value) || IsComputed4(value) || IsConstructor4(value) || IsDate6(value) || IsFunction6(value) || IsInteger4(value) || IsIntersect4(value) || IsIterator6(value) || IsLiteral4(value) || IsMappedKey4(value) || IsMappedResult4(value) || IsNever4(value) || IsNot4(value) || IsNull6(value) || IsNumber8(value) || IsObject8(value) || IsPromise4(value) || IsRecord4(value) || IsRef4(value) || IsRegExp6(value) || IsString6(value) || IsSymbol6(value) || IsTemplateLiteral4(value) || IsThis4(value) || IsTuple4(value) || IsUndefined8(value) || IsUnion4(value) || IsUint8Array6(value) || IsUnknown4(value) || IsUnsafe4(value) || IsVoid4(value) || IsKind4(value));
}

// node_modules/@sinclair/typebox/build/esm/type/patterns/patterns.mjs
init_process_shim();
var PatternBoolean2 = "(true|false)";
var PatternNumber2 = "(0|[1-9][0-9]*)";
var PatternString2 = "(.*)";
var PatternNever2 = "(?!.*)";
var PatternBooleanExact2 = `^${PatternBoolean2}$`;
var PatternNumberExact2 = `^${PatternNumber2}$`;
var PatternStringExact2 = `^${PatternString2}$`;
var PatternNeverExact2 = `^${PatternNever2}$`;

// node_modules/@sinclair/typebox/build/esm/type/sets/set.mjs
init_process_shim();
function SetIncludes2(T3, S5) {
  return T3.includes(S5);
}
function SetDistinct2(T3) {
  return [...new Set(T3)];
}
function SetIntersect2(T3, S5) {
  return T3.filter((L3) => S5.includes(L3));
}
function SetIntersectManyResolve2(T3, Init) {
  return T3.reduce((Acc, L3) => {
    return SetIntersect2(Acc, L3);
  }, Init);
}
function SetIntersectMany2(T3) {
  return T3.length === 1 ? T3[0] : T3.length > 1 ? SetIntersectManyResolve2(T3.slice(1), T3[0]) : [];
}
function SetUnionMany2(T3) {
  const Acc = [];
  for (const L3 of T3)
    Acc.push(...L3);
  return Acc;
}

// node_modules/@sinclair/typebox/build/esm/type/any/any.mjs
init_process_shim();
function Any2(options) {
  return CreateType2({ [Kind2]: "Any" }, options);
}

// node_modules/@sinclair/typebox/build/esm/type/array/array.mjs
init_process_shim();
function Array3(items, options) {
  return CreateType2({ [Kind2]: "Array", type: "array", items }, options);
}

// node_modules/@sinclair/typebox/build/esm/type/argument/argument.mjs
init_process_shim();
function Argument2(index) {
  return CreateType2({ [Kind2]: "Argument", index });
}

// node_modules/@sinclair/typebox/build/esm/type/async-iterator/async-iterator.mjs
init_process_shim();
function AsyncIterator3(items, options) {
  return CreateType2({ [Kind2]: "AsyncIterator", type: "AsyncIterator", items }, options);
}

// node_modules/@sinclair/typebox/build/esm/type/awaited/awaited.mjs
init_process_shim();

// node_modules/@sinclair/typebox/build/esm/type/computed/computed.mjs
init_process_shim();
function Computed2(target, parameters, options) {
  return CreateType2({ [Kind2]: "Computed", target, parameters }, options);
}

// node_modules/@sinclair/typebox/build/esm/type/intersect/intersect-evaluated.mjs
init_process_shim();

// node_modules/@sinclair/typebox/build/esm/type/discard/discard.mjs
init_process_shim();
function DiscardKey2(value, key) {
  const { [key]: _3, ...rest } = value;
  return rest;
}
function Discard2(value, keys2) {
  return keys2.reduce((acc, key) => DiscardKey2(acc, key), value);
}

// node_modules/@sinclair/typebox/build/esm/type/never/never.mjs
init_process_shim();
function Never2(options) {
  return CreateType2({ [Kind2]: "Never", not: {} }, options);
}

// node_modules/@sinclair/typebox/build/esm/type/optional/optional-from-mapped-result.mjs
init_process_shim();

// node_modules/@sinclair/typebox/build/esm/type/mapped/mapped-result.mjs
init_process_shim();
function MappedResult2(properties) {
  return CreateType2({
    [Kind2]: "MappedResult",
    properties
  });
}

// node_modules/@sinclair/typebox/build/esm/type/mapped/mapped.mjs
init_process_shim();

// node_modules/@sinclair/typebox/build/esm/type/constructor/constructor.mjs
init_process_shim();
function Constructor2(parameters, returns, options) {
  return CreateType2({ [Kind2]: "Constructor", type: "Constructor", parameters, returns }, options);
}

// node_modules/@sinclair/typebox/build/esm/type/function/function.mjs
init_process_shim();
function Function3(parameters, returns, options) {
  return CreateType2({ [Kind2]: "Function", type: "Function", parameters, returns }, options);
}

// node_modules/@sinclair/typebox/build/esm/type/indexed/indexed-from-mapped-key.mjs
init_process_shim();

// node_modules/@sinclair/typebox/build/esm/type/indexed/indexed.mjs
init_process_shim();

// node_modules/@sinclair/typebox/build/esm/type/union/union-evaluated.mjs
init_process_shim();

// node_modules/@sinclair/typebox/build/esm/type/union/union-create.mjs
init_process_shim();
function UnionCreate2(T3, options) {
  return CreateType2({ [Kind2]: "Union", anyOf: T3 }, options);
}

// node_modules/@sinclair/typebox/build/esm/type/union/union-evaluated.mjs
function IsUnionOptional2(types2) {
  return types2.some((type) => IsOptional3(type));
}
function RemoveOptionalFromRest3(types2) {
  return types2.map((left) => IsOptional3(left) ? RemoveOptionalFromType3(left) : left);
}
function RemoveOptionalFromType3(T3) {
  return Discard2(T3, [OptionalKind2]);
}
function ResolveUnion2(types2, options) {
  const isOptional = IsUnionOptional2(types2);
  return isOptional ? Optional2(UnionCreate2(RemoveOptionalFromRest3(types2), options)) : UnionCreate2(RemoveOptionalFromRest3(types2), options);
}
function UnionEvaluated2(T3, options) {
  return T3.length === 1 ? CreateType2(T3[0], options) : T3.length === 0 ? Never2(options) : ResolveUnion2(T3, options);
}

// node_modules/@sinclair/typebox/build/esm/type/union/union.mjs
init_process_shim();
function Union2(types2, options) {
  return types2.length === 0 ? Never2(options) : types2.length === 1 ? CreateType2(types2[0], options) : UnionCreate2(types2, options);
}

// node_modules/@sinclair/typebox/build/esm/type/indexed/indexed-property-keys.mjs
init_process_shim();

// node_modules/@sinclair/typebox/build/esm/type/template-literal/finite.mjs
init_process_shim();

// node_modules/@sinclair/typebox/build/esm/type/template-literal/parse.mjs
init_process_shim();
var TemplateLiteralParserError2 = class extends TypeBoxError2 {
};
function Unescape2(pattern) {
  return pattern.replace(/\\\$/g, "$").replace(/\\\*/g, "*").replace(/\\\^/g, "^").replace(/\\\|/g, "|").replace(/\\\(/g, "(").replace(/\\\)/g, ")");
}
function IsNonEscaped2(pattern, index, char) {
  return pattern[index] === char && pattern.charCodeAt(index - 1) !== 92;
}
function IsOpenParen2(pattern, index) {
  return IsNonEscaped2(pattern, index, "(");
}
function IsCloseParen2(pattern, index) {
  return IsNonEscaped2(pattern, index, ")");
}
function IsSeparator2(pattern, index) {
  return IsNonEscaped2(pattern, index, "|");
}
function IsGroup2(pattern) {
  if (!(IsOpenParen2(pattern, 0) && IsCloseParen2(pattern, pattern.length - 1)))
    return false;
  let count = 0;
  for (let index = 0; index < pattern.length; index++) {
    if (IsOpenParen2(pattern, index))
      count += 1;
    if (IsCloseParen2(pattern, index))
      count -= 1;
    if (count === 0 && index !== pattern.length - 1)
      return false;
  }
  return true;
}
function InGroup2(pattern) {
  return pattern.slice(1, pattern.length - 1);
}
function IsPrecedenceOr2(pattern) {
  let count = 0;
  for (let index = 0; index < pattern.length; index++) {
    if (IsOpenParen2(pattern, index))
      count += 1;
    if (IsCloseParen2(pattern, index))
      count -= 1;
    if (IsSeparator2(pattern, index) && count === 0)
      return true;
  }
  return false;
}
function IsPrecedenceAnd2(pattern) {
  for (let index = 0; index < pattern.length; index++) {
    if (IsOpenParen2(pattern, index))
      return true;
  }
  return false;
}
function Or2(pattern) {
  let [count, start] = [0, 0];
  const expressions = [];
  for (let index = 0; index < pattern.length; index++) {
    if (IsOpenParen2(pattern, index))
      count += 1;
    if (IsCloseParen2(pattern, index))
      count -= 1;
    if (IsSeparator2(pattern, index) && count === 0) {
      const range3 = pattern.slice(start, index);
      if (range3.length > 0)
        expressions.push(TemplateLiteralParse2(range3));
      start = index + 1;
    }
  }
  const range2 = pattern.slice(start);
  if (range2.length > 0)
    expressions.push(TemplateLiteralParse2(range2));
  if (expressions.length === 0)
    return { type: "const", const: "" };
  if (expressions.length === 1)
    return expressions[0];
  return { type: "or", expr: expressions };
}
function And2(pattern) {
  function Group(value, index) {
    if (!IsOpenParen2(value, index))
      throw new TemplateLiteralParserError2(`TemplateLiteralParser: Index must point to open parens`);
    let count = 0;
    for (let scan2 = index; scan2 < value.length; scan2++) {
      if (IsOpenParen2(value, scan2))
        count += 1;
      if (IsCloseParen2(value, scan2))
        count -= 1;
      if (count === 0)
        return [index, scan2];
    }
    throw new TemplateLiteralParserError2(`TemplateLiteralParser: Unclosed group parens in expression`);
  }
  function Range2(pattern2, index) {
    for (let scan2 = index; scan2 < pattern2.length; scan2++) {
      if (IsOpenParen2(pattern2, scan2))
        return [index, scan2];
    }
    return [index, pattern2.length];
  }
  const expressions = [];
  for (let index = 0; index < pattern.length; index++) {
    if (IsOpenParen2(pattern, index)) {
      const [start, end] = Group(pattern, index);
      const range2 = pattern.slice(start, end + 1);
      expressions.push(TemplateLiteralParse2(range2));
      index = end;
    } else {
      const [start, end] = Range2(pattern, index);
      const range2 = pattern.slice(start, end);
      if (range2.length > 0)
        expressions.push(TemplateLiteralParse2(range2));
      index = end - 1;
    }
  }
  return expressions.length === 0 ? { type: "const", const: "" } : expressions.length === 1 ? expressions[0] : { type: "and", expr: expressions };
}
function TemplateLiteralParse2(pattern) {
  return IsGroup2(pattern) ? TemplateLiteralParse2(InGroup2(pattern)) : IsPrecedenceOr2(pattern) ? Or2(pattern) : IsPrecedenceAnd2(pattern) ? And2(pattern) : { type: "const", const: Unescape2(pattern) };
}
function TemplateLiteralParseExact2(pattern) {
  return TemplateLiteralParse2(pattern.slice(1, pattern.length - 1));
}

// node_modules/@sinclair/typebox/build/esm/type/template-literal/finite.mjs
var TemplateLiteralFiniteError2 = class extends TypeBoxError2 {
};
function IsNumberExpression2(expression) {
  return expression.type === "or" && expression.expr.length === 2 && expression.expr[0].type === "const" && expression.expr[0].const === "0" && expression.expr[1].type === "const" && expression.expr[1].const === "[1-9][0-9]*";
}
function IsBooleanExpression2(expression) {
  return expression.type === "or" && expression.expr.length === 2 && expression.expr[0].type === "const" && expression.expr[0].const === "true" && expression.expr[1].type === "const" && expression.expr[1].const === "false";
}
function IsStringExpression2(expression) {
  return expression.type === "const" && expression.const === ".*";
}
function IsTemplateLiteralExpressionFinite2(expression) {
  return IsNumberExpression2(expression) || IsStringExpression2(expression) ? false : IsBooleanExpression2(expression) ? true : expression.type === "and" ? expression.expr.every((expr) => IsTemplateLiteralExpressionFinite2(expr)) : expression.type === "or" ? expression.expr.every((expr) => IsTemplateLiteralExpressionFinite2(expr)) : expression.type === "const" ? true : (() => {
    throw new TemplateLiteralFiniteError2(`Unknown expression type`);
  })();
}
function IsTemplateLiteralFinite2(schema) {
  const expression = TemplateLiteralParseExact2(schema.pattern);
  return IsTemplateLiteralExpressionFinite2(expression);
}

// node_modules/@sinclair/typebox/build/esm/type/template-literal/generate.mjs
init_process_shim();
var TemplateLiteralGenerateError2 = class extends TypeBoxError2 {
};
function* GenerateReduce2(buffer) {
  if (buffer.length === 1)
    return yield* buffer[0];
  for (const left of buffer[0]) {
    for (const right of GenerateReduce2(buffer.slice(1))) {
      yield `${left}${right}`;
    }
  }
}
function* GenerateAnd2(expression) {
  return yield* GenerateReduce2(expression.expr.map((expr) => [...TemplateLiteralExpressionGenerate2(expr)]));
}
function* GenerateOr2(expression) {
  for (const expr of expression.expr)
    yield* TemplateLiteralExpressionGenerate2(expr);
}
function* GenerateConst2(expression) {
  return yield expression.const;
}
function* TemplateLiteralExpressionGenerate2(expression) {
  return expression.type === "and" ? yield* GenerateAnd2(expression) : expression.type === "or" ? yield* GenerateOr2(expression) : expression.type === "const" ? yield* GenerateConst2(expression) : (() => {
    throw new TemplateLiteralGenerateError2("Unknown expression");
  })();
}
function TemplateLiteralGenerate2(schema) {
  const expression = TemplateLiteralParseExact2(schema.pattern);
  return IsTemplateLiteralExpressionFinite2(expression) ? [...TemplateLiteralExpressionGenerate2(expression)] : [];
}

// node_modules/@sinclair/typebox/build/esm/type/template-literal/syntax.mjs
init_process_shim();

// node_modules/@sinclair/typebox/build/esm/type/literal/literal.mjs
init_process_shim();
function Literal2(value, options) {
  return CreateType2({
    [Kind2]: "Literal",
    const: value,
    type: typeof value
  }, options);
}

// node_modules/@sinclair/typebox/build/esm/type/boolean/boolean.mjs
init_process_shim();
function Boolean3(options) {
  return CreateType2({ [Kind2]: "Boolean", type: "boolean" }, options);
}

// node_modules/@sinclair/typebox/build/esm/type/bigint/bigint.mjs
init_process_shim();
function BigInt3(options) {
  return CreateType2({ [Kind2]: "BigInt", type: "bigint" }, options);
}

// node_modules/@sinclair/typebox/build/esm/type/number/number.mjs
init_process_shim();
function Number3(options) {
  return CreateType2({ [Kind2]: "Number", type: "number" }, options);
}

// node_modules/@sinclair/typebox/build/esm/type/string/string.mjs
init_process_shim();
function String3(options) {
  return CreateType2({ [Kind2]: "String", type: "string" }, options);
}

// node_modules/@sinclair/typebox/build/esm/type/template-literal/syntax.mjs
function* FromUnion11(syntax) {
  const trim = syntax.trim().replace(/"|'/g, "");
  return trim === "boolean" ? yield Boolean3() : trim === "number" ? yield Number3() : trim === "bigint" ? yield BigInt3() : trim === "string" ? yield String3() : yield (() => {
    const literals = trim.split("|").map((literal) => Literal2(literal.trim()));
    return literals.length === 0 ? Never2() : literals.length === 1 ? literals[0] : UnionEvaluated2(literals);
  })();
}
function* FromTerminal2(syntax) {
  if (syntax[1] !== "{") {
    const L3 = Literal2("$");
    const R3 = FromSyntax2(syntax.slice(1));
    return yield* [L3, ...R3];
  }
  for (let i7 = 2; i7 < syntax.length; i7++) {
    if (syntax[i7] === "}") {
      const L3 = FromUnion11(syntax.slice(2, i7));
      const R3 = FromSyntax2(syntax.slice(i7 + 1));
      return yield* [...L3, ...R3];
    }
  }
  yield Literal2(syntax);
}
function* FromSyntax2(syntax) {
  for (let i7 = 0; i7 < syntax.length; i7++) {
    if (syntax[i7] === "$") {
      const L3 = Literal2(syntax.slice(0, i7));
      const R3 = FromTerminal2(syntax.slice(i7));
      return yield* [L3, ...R3];
    }
  }
  yield Literal2(syntax);
}
function TemplateLiteralSyntax2(syntax) {
  return [...FromSyntax2(syntax)];
}

// node_modules/@sinclair/typebox/build/esm/type/template-literal/pattern.mjs
init_process_shim();
var TemplateLiteralPatternError2 = class extends TypeBoxError2 {
};
function Escape2(value) {
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function Visit5(schema, acc) {
  return IsTemplateLiteral3(schema) ? schema.pattern.slice(1, schema.pattern.length - 1) : IsUnion3(schema) ? `(${schema.anyOf.map((schema2) => Visit5(schema2, acc)).join("|")})` : IsNumber7(schema) ? `${acc}${PatternNumber2}` : IsInteger3(schema) ? `${acc}${PatternNumber2}` : IsBigInt5(schema) ? `${acc}${PatternNumber2}` : IsString5(schema) ? `${acc}${PatternString2}` : IsLiteral3(schema) ? `${acc}${Escape2(schema.const.toString())}` : IsBoolean5(schema) ? `${acc}${PatternBoolean2}` : (() => {
    throw new TemplateLiteralPatternError2(`Unexpected Kind '${schema[Kind2]}'`);
  })();
}
function TemplateLiteralPattern2(kinds) {
  return `^${kinds.map((schema) => Visit5(schema, "")).join("")}$`;
}

// node_modules/@sinclair/typebox/build/esm/type/template-literal/union.mjs
init_process_shim();
function TemplateLiteralToUnion2(schema) {
  const R3 = TemplateLiteralGenerate2(schema);
  const L3 = R3.map((S5) => Literal2(S5));
  return UnionEvaluated2(L3);
}

// node_modules/@sinclair/typebox/build/esm/type/template-literal/template-literal.mjs
init_process_shim();
function TemplateLiteral2(unresolved, options) {
  const pattern = IsString4(unresolved) ? TemplateLiteralPattern2(TemplateLiteralSyntax2(unresolved)) : TemplateLiteralPattern2(unresolved);
  return CreateType2({ [Kind2]: "TemplateLiteral", type: "string", pattern }, options);
}

// node_modules/@sinclair/typebox/build/esm/type/indexed/indexed-property-keys.mjs
function FromTemplateLiteral4(templateLiteral) {
  const keys2 = TemplateLiteralGenerate2(templateLiteral);
  return keys2.map((key) => key.toString());
}
function FromUnion12(types2) {
  const result = [];
  for (const type of types2)
    result.push(...IndexPropertyKeys2(type));
  return result;
}
function FromLiteral3(literalValue) {
  return [literalValue.toString()];
}
function IndexPropertyKeys2(type) {
  return [...new Set(IsTemplateLiteral3(type) ? FromTemplateLiteral4(type) : IsUnion3(type) ? FromUnion12(type.anyOf) : IsLiteral3(type) ? FromLiteral3(type.const) : IsNumber7(type) ? ["[number]"] : IsInteger3(type) ? ["[number]"] : [])];
}

// node_modules/@sinclair/typebox/build/esm/type/indexed/indexed-from-mapped-result.mjs
init_process_shim();
function FromProperties20(type, properties, options) {
  const result = {};
  for (const K2 of Object.getOwnPropertyNames(properties)) {
    result[K2] = Index2(type, IndexPropertyKeys2(properties[K2]), options);
  }
  return result;
}
function FromMappedResult13(type, mappedResult, options) {
  return FromProperties20(type, mappedResult.properties, options);
}
function IndexFromMappedResult2(type, mappedResult, options) {
  const properties = FromMappedResult13(type, mappedResult, options);
  return MappedResult2(properties);
}

// node_modules/@sinclair/typebox/build/esm/type/indexed/indexed.mjs
function FromRest8(types2, key) {
  return types2.map((type) => IndexFromPropertyKey2(type, key));
}
function FromIntersectRest2(types2) {
  return types2.filter((type) => !IsNever3(type));
}
function FromIntersect9(types2, key) {
  return IntersectEvaluated2(FromIntersectRest2(FromRest8(types2, key)));
}
function FromUnionRest2(types2) {
  return types2.some((L3) => IsNever3(L3)) ? [] : types2;
}
function FromUnion13(types2, key) {
  return UnionEvaluated2(FromUnionRest2(FromRest8(types2, key)));
}
function FromTuple6(types2, key) {
  return key in types2 ? types2[key] : key === "[number]" ? UnionEvaluated2(types2) : Never2();
}
function FromArray7(type, key) {
  return key === "[number]" ? type : Never2();
}
function FromProperty4(properties, propertyKey) {
  return propertyKey in properties ? properties[propertyKey] : Never2();
}
function IndexFromPropertyKey2(type, propertyKey) {
  return IsIntersect3(type) ? FromIntersect9(type.allOf, propertyKey) : IsUnion3(type) ? FromUnion13(type.anyOf, propertyKey) : IsTuple3(type) ? FromTuple6(type.items ?? [], propertyKey) : IsArray7(type) ? FromArray7(type.items, propertyKey) : IsObject7(type) ? FromProperty4(type.properties, propertyKey) : Never2();
}
function IndexFromPropertyKeys2(type, propertyKeys) {
  return propertyKeys.map((propertyKey) => IndexFromPropertyKey2(type, propertyKey));
}
function FromSchema2(type, propertyKeys) {
  return UnionEvaluated2(IndexFromPropertyKeys2(type, propertyKeys));
}
function Index2(type, key, options) {
  if (IsRef3(type) || IsRef3(key)) {
    const error = `Index types using Ref parameters require both Type and Key to be of TSchema`;
    if (!IsSchema3(type) || !IsSchema3(key))
      throw new TypeBoxError2(error);
    return Computed2("Index", [type, key]);
  }
  if (IsMappedResult3(key))
    return IndexFromMappedResult2(type, key, options);
  if (IsMappedKey3(key))
    return IndexFromMappedKey2(type, key, options);
  return CreateType2(IsSchema3(key) ? FromSchema2(type, IndexPropertyKeys2(key)) : FromSchema2(type, key), options);
}

// node_modules/@sinclair/typebox/build/esm/type/indexed/indexed-from-mapped-key.mjs
function MappedIndexPropertyKey2(type, key, options) {
  return { [key]: Index2(type, [key], Clone2(options)) };
}
function MappedIndexPropertyKeys2(type, propertyKeys, options) {
  return propertyKeys.reduce((result, left) => {
    return { ...result, ...MappedIndexPropertyKey2(type, left, options) };
  }, {});
}
function MappedIndexProperties2(type, mappedKey, options) {
  return MappedIndexPropertyKeys2(type, mappedKey.keys, options);
}
function IndexFromMappedKey2(type, mappedKey, options) {
  const properties = MappedIndexProperties2(type, mappedKey, options);
  return MappedResult2(properties);
}

// node_modules/@sinclair/typebox/build/esm/type/iterator/iterator.mjs
init_process_shim();
function Iterator2(items, options) {
  return CreateType2({ [Kind2]: "Iterator", type: "Iterator", items }, options);
}

// node_modules/@sinclair/typebox/build/esm/type/object/object.mjs
init_process_shim();
function RequiredArray2(properties) {
  return globalThis.Object.keys(properties).filter((key) => !IsOptional3(properties[key]));
}
function _Object2(properties, options) {
  const required = RequiredArray2(properties);
  const schema = required.length > 0 ? { [Kind2]: "Object", type: "object", required, properties } : { [Kind2]: "Object", type: "object", properties };
  return CreateType2(schema, options);
}
var Object3 = _Object2;

// node_modules/@sinclair/typebox/build/esm/type/promise/promise.mjs
init_process_shim();
function Promise3(item, options) {
  return CreateType2({ [Kind2]: "Promise", type: "Promise", item }, options);
}

// node_modules/@sinclair/typebox/build/esm/type/readonly/readonly-from-mapped-result.mjs
init_process_shim();

// node_modules/@sinclair/typebox/build/esm/type/readonly/readonly.mjs
init_process_shim();
function RemoveReadonly2(schema) {
  return CreateType2(Discard2(schema, [ReadonlyKind2]));
}
function AddReadonly2(schema) {
  return CreateType2({ ...schema, [ReadonlyKind2]: "Readonly" });
}
function ReadonlyWithFlag2(schema, F2) {
  return F2 === false ? RemoveReadonly2(schema) : AddReadonly2(schema);
}
function Readonly2(schema, enable) {
  const F2 = enable ?? true;
  return IsMappedResult3(schema) ? ReadonlyFromMappedResult2(schema, F2) : ReadonlyWithFlag2(schema, F2);
}

// node_modules/@sinclair/typebox/build/esm/type/readonly/readonly-from-mapped-result.mjs
function FromProperties21(K2, F2) {
  const Acc = {};
  for (const K22 of globalThis.Object.getOwnPropertyNames(K2))
    Acc[K22] = Readonly2(K2[K22], F2);
  return Acc;
}
function FromMappedResult14(R3, F2) {
  return FromProperties21(R3.properties, F2);
}
function ReadonlyFromMappedResult2(R3, F2) {
  const P3 = FromMappedResult14(R3, F2);
  return MappedResult2(P3);
}

// node_modules/@sinclair/typebox/build/esm/type/tuple/tuple.mjs
init_process_shim();
function Tuple2(types2, options) {
  return CreateType2(types2.length > 0 ? { [Kind2]: "Tuple", type: "array", items: types2, additionalItems: false, minItems: types2.length, maxItems: types2.length } : { [Kind2]: "Tuple", type: "array", minItems: types2.length, maxItems: types2.length }, options);
}

// node_modules/@sinclair/typebox/build/esm/type/mapped/mapped.mjs
function FromMappedResult15(K2, P3) {
  return K2 in P3 ? FromSchemaType2(K2, P3[K2]) : MappedResult2(P3);
}
function MappedKeyToKnownMappedResultProperties2(K2) {
  return { [K2]: Literal2(K2) };
}
function MappedKeyToUnknownMappedResultProperties2(P3) {
  const Acc = {};
  for (const L3 of P3)
    Acc[L3] = Literal2(L3);
  return Acc;
}
function MappedKeyToMappedResultProperties2(K2, P3) {
  return SetIncludes2(P3, K2) ? MappedKeyToKnownMappedResultProperties2(K2) : MappedKeyToUnknownMappedResultProperties2(P3);
}
function FromMappedKey5(K2, P3) {
  const R3 = MappedKeyToMappedResultProperties2(K2, P3);
  return FromMappedResult15(K2, R3);
}
function FromRest9(K2, T3) {
  return T3.map((L3) => FromSchemaType2(K2, L3));
}
function FromProperties22(K2, T3) {
  const Acc = {};
  for (const K22 of globalThis.Object.getOwnPropertyNames(T3))
    Acc[K22] = FromSchemaType2(K2, T3[K22]);
  return Acc;
}
function FromSchemaType2(K2, T3) {
  const options = { ...T3 };
  return (
    // unevaluated modifier types
    IsOptional3(T3) ? Optional2(FromSchemaType2(K2, Discard2(T3, [OptionalKind2]))) : IsReadonly3(T3) ? Readonly2(FromSchemaType2(K2, Discard2(T3, [ReadonlyKind2]))) : (
      // unevaluated mapped types
      IsMappedResult3(T3) ? FromMappedResult15(K2, T3.properties) : IsMappedKey3(T3) ? FromMappedKey5(K2, T3.keys) : (
        // unevaluated types
        IsConstructor3(T3) ? Constructor2(FromRest9(K2, T3.parameters), FromSchemaType2(K2, T3.returns), options) : IsFunction5(T3) ? Function3(FromRest9(K2, T3.parameters), FromSchemaType2(K2, T3.returns), options) : IsAsyncIterator5(T3) ? AsyncIterator3(FromSchemaType2(K2, T3.items), options) : IsIterator5(T3) ? Iterator2(FromSchemaType2(K2, T3.items), options) : IsIntersect3(T3) ? Intersect2(FromRest9(K2, T3.allOf), options) : IsUnion3(T3) ? Union2(FromRest9(K2, T3.anyOf), options) : IsTuple3(T3) ? Tuple2(FromRest9(K2, T3.items ?? []), options) : IsObject7(T3) ? Object3(FromProperties22(K2, T3.properties), options) : IsArray7(T3) ? Array3(FromSchemaType2(K2, T3.items), options) : IsPromise3(T3) ? Promise3(FromSchemaType2(K2, T3.item), options) : T3
      )
    )
  );
}
function MappedFunctionReturnType2(K2, T3) {
  const Acc = {};
  for (const L3 of K2)
    Acc[L3] = FromSchemaType2(L3, T3);
  return Acc;
}
function Mapped2(key, map, options) {
  const K2 = IsSchema3(key) ? IndexPropertyKeys2(key) : key;
  const RT = map({ [Kind2]: "MappedKey", keys: K2 });
  const R3 = MappedFunctionReturnType2(K2, RT);
  return Object3(R3, options);
}

// node_modules/@sinclair/typebox/build/esm/type/optional/optional.mjs
init_process_shim();
function RemoveOptional2(schema) {
  return CreateType2(Discard2(schema, [OptionalKind2]));
}
function AddOptional2(schema) {
  return CreateType2({ ...schema, [OptionalKind2]: "Optional" });
}
function OptionalWithFlag2(schema, F2) {
  return F2 === false ? RemoveOptional2(schema) : AddOptional2(schema);
}
function Optional2(schema, enable) {
  const F2 = enable ?? true;
  return IsMappedResult3(schema) ? OptionalFromMappedResult2(schema, F2) : OptionalWithFlag2(schema, F2);
}

// node_modules/@sinclair/typebox/build/esm/type/optional/optional-from-mapped-result.mjs
function FromProperties23(P3, F2) {
  const Acc = {};
  for (const K2 of globalThis.Object.getOwnPropertyNames(P3))
    Acc[K2] = Optional2(P3[K2], F2);
  return Acc;
}
function FromMappedResult16(R3, F2) {
  return FromProperties23(R3.properties, F2);
}
function OptionalFromMappedResult2(R3, F2) {
  const P3 = FromMappedResult16(R3, F2);
  return MappedResult2(P3);
}

// node_modules/@sinclair/typebox/build/esm/type/intersect/intersect-create.mjs
init_process_shim();
function IntersectCreate2(T3, options = {}) {
  const allObjects = T3.every((schema) => IsObject7(schema));
  const clonedUnevaluatedProperties = IsSchema3(options.unevaluatedProperties) ? { unevaluatedProperties: options.unevaluatedProperties } : {};
  return CreateType2(options.unevaluatedProperties === false || IsSchema3(options.unevaluatedProperties) || allObjects ? { ...clonedUnevaluatedProperties, [Kind2]: "Intersect", type: "object", allOf: T3 } : { ...clonedUnevaluatedProperties, [Kind2]: "Intersect", allOf: T3 }, options);
}

// node_modules/@sinclair/typebox/build/esm/type/intersect/intersect-evaluated.mjs
function IsIntersectOptional2(types2) {
  return types2.every((left) => IsOptional3(left));
}
function RemoveOptionalFromType4(type) {
  return Discard2(type, [OptionalKind2]);
}
function RemoveOptionalFromRest4(types2) {
  return types2.map((left) => IsOptional3(left) ? RemoveOptionalFromType4(left) : left);
}
function ResolveIntersect2(types2, options) {
  return IsIntersectOptional2(types2) ? Optional2(IntersectCreate2(RemoveOptionalFromRest4(types2), options)) : IntersectCreate2(RemoveOptionalFromRest4(types2), options);
}
function IntersectEvaluated2(types2, options = {}) {
  if (types2.length === 1)
    return CreateType2(types2[0], options);
  if (types2.length === 0)
    return Never2(options);
  if (types2.some((schema) => IsTransform3(schema)))
    throw new Error("Cannot intersect transform types");
  return ResolveIntersect2(types2, options);
}

// node_modules/@sinclair/typebox/build/esm/type/intersect/intersect.mjs
init_process_shim();
function Intersect2(types2, options) {
  if (types2.length === 1)
    return CreateType2(types2[0], options);
  if (types2.length === 0)
    return Never2(options);
  if (types2.some((schema) => IsTransform3(schema)))
    throw new Error("Cannot intersect transform types");
  return IntersectCreate2(types2, options);
}

// node_modules/@sinclair/typebox/build/esm/type/ref/ref.mjs
init_process_shim();
function Ref2(...args) {
  const [$ref, options] = typeof args[0] === "string" ? [args[0], args[1]] : [args[0].$id, args[1]];
  if (typeof $ref !== "string")
    throw new TypeBoxError2("Ref: $ref must be a string");
  return CreateType2({ [Kind2]: "Ref", $ref }, options);
}

// node_modules/@sinclair/typebox/build/esm/type/awaited/awaited.mjs
function FromComputed6(target, parameters) {
  return Computed2("Awaited", [Computed2(target, parameters)]);
}
function FromRef5($ref) {
  return Computed2("Awaited", [Ref2($ref)]);
}
function FromIntersect10(types2) {
  return Intersect2(FromRest10(types2));
}
function FromUnion14(types2) {
  return Union2(FromRest10(types2));
}
function FromPromise4(type) {
  return Awaited2(type);
}
function FromRest10(types2) {
  return types2.map((type) => Awaited2(type));
}
function Awaited2(type, options) {
  return CreateType2(IsComputed3(type) ? FromComputed6(type.target, type.parameters) : IsIntersect3(type) ? FromIntersect10(type.allOf) : IsUnion3(type) ? FromUnion14(type.anyOf) : IsPromise3(type) ? FromPromise4(type.item) : IsRef3(type) ? FromRef5(type.$ref) : type, options);
}

// node_modules/@sinclair/typebox/build/esm/type/composite/composite.mjs
init_process_shim();

// node_modules/@sinclair/typebox/build/esm/type/keyof/keyof-from-mapped-result.mjs
init_process_shim();

// node_modules/@sinclair/typebox/build/esm/type/keyof/keyof.mjs
init_process_shim();

// node_modules/@sinclair/typebox/build/esm/type/keyof/keyof-property-keys.mjs
init_process_shim();
function FromRest11(types2) {
  const result = [];
  for (const L3 of types2)
    result.push(KeyOfPropertyKeys2(L3));
  return result;
}
function FromIntersect11(types2) {
  const propertyKeysArray = FromRest11(types2);
  const propertyKeys = SetUnionMany2(propertyKeysArray);
  return propertyKeys;
}
function FromUnion15(types2) {
  const propertyKeysArray = FromRest11(types2);
  const propertyKeys = SetIntersectMany2(propertyKeysArray);
  return propertyKeys;
}
function FromTuple7(types2) {
  return types2.map((_3, indexer) => indexer.toString());
}
function FromArray8(_3) {
  return ["[number]"];
}
function FromProperties24(T3) {
  return globalThis.Object.getOwnPropertyNames(T3);
}
function FromPatternProperties2(patternProperties) {
  if (!includePatternProperties2)
    return [];
  const patternPropertyKeys = globalThis.Object.getOwnPropertyNames(patternProperties);
  return patternPropertyKeys.map((key) => {
    return key[0] === "^" && key[key.length - 1] === "$" ? key.slice(1, key.length - 1) : key;
  });
}
function KeyOfPropertyKeys2(type) {
  return IsIntersect3(type) ? FromIntersect11(type.allOf) : IsUnion3(type) ? FromUnion15(type.anyOf) : IsTuple3(type) ? FromTuple7(type.items ?? []) : IsArray7(type) ? FromArray8(type.items) : IsObject7(type) ? FromProperties24(type.properties) : IsRecord3(type) ? FromPatternProperties2(type.patternProperties) : [];
}
var includePatternProperties2 = false;

// node_modules/@sinclair/typebox/build/esm/type/keyof/keyof.mjs
function FromComputed7(target, parameters) {
  return Computed2("KeyOf", [Computed2(target, parameters)]);
}
function FromRef6($ref) {
  return Computed2("KeyOf", [Ref2($ref)]);
}
function KeyOfFromType2(type, options) {
  const propertyKeys = KeyOfPropertyKeys2(type);
  const propertyKeyTypes = KeyOfPropertyKeysToRest2(propertyKeys);
  const result = UnionEvaluated2(propertyKeyTypes);
  return CreateType2(result, options);
}
function KeyOfPropertyKeysToRest2(propertyKeys) {
  return propertyKeys.map((L3) => L3 === "[number]" ? Number3() : Literal2(L3));
}
function KeyOf2(type, options) {
  return IsComputed3(type) ? FromComputed7(type.target, type.parameters) : IsRef3(type) ? FromRef6(type.$ref) : IsMappedResult3(type) ? KeyOfFromMappedResult2(type, options) : KeyOfFromType2(type, options);
}

// node_modules/@sinclair/typebox/build/esm/type/keyof/keyof-from-mapped-result.mjs
function FromProperties25(properties, options) {
  const result = {};
  for (const K2 of globalThis.Object.getOwnPropertyNames(properties))
    result[K2] = KeyOf2(properties[K2], Clone2(options));
  return result;
}
function FromMappedResult17(mappedResult, options) {
  return FromProperties25(mappedResult.properties, options);
}
function KeyOfFromMappedResult2(mappedResult, options) {
  const properties = FromMappedResult17(mappedResult, options);
  return MappedResult2(properties);
}

// node_modules/@sinclair/typebox/build/esm/type/composite/composite.mjs
function CompositeKeys2(T3) {
  const Acc = [];
  for (const L3 of T3)
    Acc.push(...KeyOfPropertyKeys2(L3));
  return SetDistinct2(Acc);
}
function FilterNever2(T3) {
  return T3.filter((L3) => !IsNever3(L3));
}
function CompositeProperty2(T3, K2) {
  const Acc = [];
  for (const L3 of T3)
    Acc.push(...IndexFromPropertyKeys2(L3, [K2]));
  return FilterNever2(Acc);
}
function CompositeProperties2(T3, K2) {
  const Acc = {};
  for (const L3 of K2) {
    Acc[L3] = IntersectEvaluated2(CompositeProperty2(T3, L3));
  }
  return Acc;
}
function Composite2(T3, options) {
  const K2 = CompositeKeys2(T3);
  const P3 = CompositeProperties2(T3, K2);
  const R3 = Object3(P3, options);
  return R3;
}

// node_modules/@sinclair/typebox/build/esm/type/const/const.mjs
init_process_shim();

// node_modules/@sinclair/typebox/build/esm/type/date/date.mjs
init_process_shim();
function Date3(options) {
  return CreateType2({ [Kind2]: "Date", type: "Date" }, options);
}

// node_modules/@sinclair/typebox/build/esm/type/null/null.mjs
init_process_shim();
function Null2(options) {
  return CreateType2({ [Kind2]: "Null", type: "null" }, options);
}

// node_modules/@sinclair/typebox/build/esm/type/symbol/symbol.mjs
init_process_shim();
function Symbol3(options) {
  return CreateType2({ [Kind2]: "Symbol", type: "symbol" }, options);
}

// node_modules/@sinclair/typebox/build/esm/type/undefined/undefined.mjs
init_process_shim();
function Undefined2(options) {
  return CreateType2({ [Kind2]: "Undefined", type: "undefined" }, options);
}

// node_modules/@sinclair/typebox/build/esm/type/uint8array/uint8array.mjs
init_process_shim();
function Uint8Array3(options) {
  return CreateType2({ [Kind2]: "Uint8Array", type: "Uint8Array" }, options);
}

// node_modules/@sinclair/typebox/build/esm/type/unknown/unknown.mjs
init_process_shim();
function Unknown2(options) {
  return CreateType2({ [Kind2]: "Unknown" }, options);
}

// node_modules/@sinclair/typebox/build/esm/type/const/const.mjs
function FromArray9(T3) {
  return T3.map((L3) => FromValue2(L3, false));
}
function FromProperties26(value) {
  const Acc = {};
  for (const K2 of globalThis.Object.getOwnPropertyNames(value))
    Acc[K2] = Readonly2(FromValue2(value[K2], false));
  return Acc;
}
function ConditionalReadonly2(T3, root) {
  return root === true ? T3 : Readonly2(T3);
}
function FromValue2(value, root) {
  return IsAsyncIterator4(value) ? ConditionalReadonly2(Any2(), root) : IsIterator4(value) ? ConditionalReadonly2(Any2(), root) : IsArray5(value) ? Readonly2(Tuple2(FromArray9(value))) : IsUint8Array4(value) ? Uint8Array3() : IsDate4(value) ? Date3() : IsObject5(value) ? ConditionalReadonly2(Object3(FromProperties26(value)), root) : IsFunction4(value) ? ConditionalReadonly2(Function3([], Unknown2()), root) : IsUndefined5(value) ? Undefined2() : IsNull4(value) ? Null2() : IsSymbol4(value) ? Symbol3() : IsBigInt4(value) ? BigInt3() : IsNumber5(value) ? Literal2(value) : IsBoolean4(value) ? Literal2(value) : IsString4(value) ? Literal2(value) : Object3({});
}
function Const2(T3, options) {
  return CreateType2(FromValue2(T3, true), options);
}

// node_modules/@sinclair/typebox/build/esm/type/constructor-parameters/constructor-parameters.mjs
init_process_shim();
function ConstructorParameters2(schema, options) {
  return IsConstructor3(schema) ? Tuple2(schema.parameters, options) : Never2(options);
}

// node_modules/@sinclair/typebox/build/esm/type/enum/enum.mjs
init_process_shim();
function Enum2(item, options) {
  if (IsUndefined5(item))
    throw new Error("Enum undefined or empty");
  const values1 = globalThis.Object.getOwnPropertyNames(item).filter((key) => isNaN(key)).map((key) => item[key]);
  const values2 = [...new Set(values1)];
  const anyOf = values2.map((value) => Literal2(value));
  return Union2(anyOf, { ...options, [Hint2]: "Enum" });
}

// node_modules/@sinclair/typebox/build/esm/type/exclude/exclude-from-mapped-result.mjs
init_process_shim();

// node_modules/@sinclair/typebox/build/esm/type/exclude/exclude.mjs
init_process_shim();

// node_modules/@sinclair/typebox/build/esm/type/extends/extends-check.mjs
init_process_shim();
var ExtendsResolverError2 = class extends TypeBoxError2 {
};
var ExtendsResult2;
(function(ExtendsResult3) {
  ExtendsResult3[ExtendsResult3["Union"] = 0] = "Union";
  ExtendsResult3[ExtendsResult3["True"] = 1] = "True";
  ExtendsResult3[ExtendsResult3["False"] = 2] = "False";
})(ExtendsResult2 || (ExtendsResult2 = {}));
function IntoBooleanResult2(result) {
  return result === ExtendsResult2.False ? result : ExtendsResult2.True;
}
function Throw2(message) {
  throw new ExtendsResolverError2(message);
}
function IsStructuralRight2(right) {
  return type_exports3.IsNever(right) || type_exports3.IsIntersect(right) || type_exports3.IsUnion(right) || type_exports3.IsUnknown(right) || type_exports3.IsAny(right);
}
function StructuralRight2(left, right) {
  return type_exports3.IsNever(right) ? FromNeverRight2(left, right) : type_exports3.IsIntersect(right) ? FromIntersectRight2(left, right) : type_exports3.IsUnion(right) ? FromUnionRight2(left, right) : type_exports3.IsUnknown(right) ? FromUnknownRight2(left, right) : type_exports3.IsAny(right) ? FromAnyRight2(left, right) : Throw2("StructuralRight");
}
function FromAnyRight2(left, right) {
  return ExtendsResult2.True;
}
function FromAny2(left, right) {
  return type_exports3.IsIntersect(right) ? FromIntersectRight2(left, right) : type_exports3.IsUnion(right) && right.anyOf.some((schema) => type_exports3.IsAny(schema) || type_exports3.IsUnknown(schema)) ? ExtendsResult2.True : type_exports3.IsUnion(right) ? ExtendsResult2.Union : type_exports3.IsUnknown(right) ? ExtendsResult2.True : type_exports3.IsAny(right) ? ExtendsResult2.True : ExtendsResult2.Union;
}
function FromArrayRight2(left, right) {
  return type_exports3.IsUnknown(left) ? ExtendsResult2.False : type_exports3.IsAny(left) ? ExtendsResult2.Union : type_exports3.IsNever(left) ? ExtendsResult2.True : ExtendsResult2.False;
}
function FromArray10(left, right) {
  return type_exports3.IsObject(right) && IsObjectArrayLike2(right) ? ExtendsResult2.True : IsStructuralRight2(right) ? StructuralRight2(left, right) : !type_exports3.IsArray(right) ? ExtendsResult2.False : IntoBooleanResult2(Visit6(left.items, right.items));
}
function FromAsyncIterator4(left, right) {
  return IsStructuralRight2(right) ? StructuralRight2(left, right) : !type_exports3.IsAsyncIterator(right) ? ExtendsResult2.False : IntoBooleanResult2(Visit6(left.items, right.items));
}
function FromBigInt2(left, right) {
  return IsStructuralRight2(right) ? StructuralRight2(left, right) : type_exports3.IsObject(right) ? FromObjectRight2(left, right) : type_exports3.IsRecord(right) ? FromRecordRight2(left, right) : type_exports3.IsBigInt(right) ? ExtendsResult2.True : ExtendsResult2.False;
}
function FromBooleanRight2(left, right) {
  return type_exports3.IsLiteralBoolean(left) ? ExtendsResult2.True : type_exports3.IsBoolean(left) ? ExtendsResult2.True : ExtendsResult2.False;
}
function FromBoolean2(left, right) {
  return IsStructuralRight2(right) ? StructuralRight2(left, right) : type_exports3.IsObject(right) ? FromObjectRight2(left, right) : type_exports3.IsRecord(right) ? FromRecordRight2(left, right) : type_exports3.IsBoolean(right) ? ExtendsResult2.True : ExtendsResult2.False;
}
function FromConstructor4(left, right) {
  return IsStructuralRight2(right) ? StructuralRight2(left, right) : type_exports3.IsObject(right) ? FromObjectRight2(left, right) : !type_exports3.IsConstructor(right) ? ExtendsResult2.False : left.parameters.length > right.parameters.length ? ExtendsResult2.False : !left.parameters.every((schema, index) => IntoBooleanResult2(Visit6(right.parameters[index], schema)) === ExtendsResult2.True) ? ExtendsResult2.False : IntoBooleanResult2(Visit6(left.returns, right.returns));
}
function FromDate2(left, right) {
  return IsStructuralRight2(right) ? StructuralRight2(left, right) : type_exports3.IsObject(right) ? FromObjectRight2(left, right) : type_exports3.IsRecord(right) ? FromRecordRight2(left, right) : type_exports3.IsDate(right) ? ExtendsResult2.True : ExtendsResult2.False;
}
function FromFunction4(left, right) {
  return IsStructuralRight2(right) ? StructuralRight2(left, right) : type_exports3.IsObject(right) ? FromObjectRight2(left, right) : !type_exports3.IsFunction(right) ? ExtendsResult2.False : left.parameters.length > right.parameters.length ? ExtendsResult2.False : !left.parameters.every((schema, index) => IntoBooleanResult2(Visit6(right.parameters[index], schema)) === ExtendsResult2.True) ? ExtendsResult2.False : IntoBooleanResult2(Visit6(left.returns, right.returns));
}
function FromIntegerRight2(left, right) {
  return type_exports3.IsLiteral(left) && value_exports2.IsNumber(left.const) ? ExtendsResult2.True : type_exports3.IsNumber(left) || type_exports3.IsInteger(left) ? ExtendsResult2.True : ExtendsResult2.False;
}
function FromInteger2(left, right) {
  return type_exports3.IsInteger(right) || type_exports3.IsNumber(right) ? ExtendsResult2.True : IsStructuralRight2(right) ? StructuralRight2(left, right) : type_exports3.IsObject(right) ? FromObjectRight2(left, right) : type_exports3.IsRecord(right) ? FromRecordRight2(left, right) : ExtendsResult2.False;
}
function FromIntersectRight2(left, right) {
  return right.allOf.every((schema) => Visit6(left, schema) === ExtendsResult2.True) ? ExtendsResult2.True : ExtendsResult2.False;
}
function FromIntersect12(left, right) {
  return left.allOf.some((schema) => Visit6(schema, right) === ExtendsResult2.True) ? ExtendsResult2.True : ExtendsResult2.False;
}
function FromIterator4(left, right) {
  return IsStructuralRight2(right) ? StructuralRight2(left, right) : !type_exports3.IsIterator(right) ? ExtendsResult2.False : IntoBooleanResult2(Visit6(left.items, right.items));
}
function FromLiteral4(left, right) {
  return type_exports3.IsLiteral(right) && right.const === left.const ? ExtendsResult2.True : IsStructuralRight2(right) ? StructuralRight2(left, right) : type_exports3.IsObject(right) ? FromObjectRight2(left, right) : type_exports3.IsRecord(right) ? FromRecordRight2(left, right) : type_exports3.IsString(right) ? FromStringRight2(left, right) : type_exports3.IsNumber(right) ? FromNumberRight2(left, right) : type_exports3.IsInteger(right) ? FromIntegerRight2(left, right) : type_exports3.IsBoolean(right) ? FromBooleanRight2(left, right) : ExtendsResult2.False;
}
function FromNeverRight2(left, right) {
  return ExtendsResult2.False;
}
function FromNever2(left, right) {
  return ExtendsResult2.True;
}
function UnwrapTNot2(schema) {
  let [current2, depth] = [schema, 0];
  while (true) {
    if (!type_exports3.IsNot(current2))
      break;
    current2 = current2.not;
    depth += 1;
  }
  return depth % 2 === 0 ? current2 : Unknown2();
}
function FromNot2(left, right) {
  return type_exports3.IsNot(left) ? Visit6(UnwrapTNot2(left), right) : type_exports3.IsNot(right) ? Visit6(left, UnwrapTNot2(right)) : Throw2("Invalid fallthrough for Not");
}
function FromNull2(left, right) {
  return IsStructuralRight2(right) ? StructuralRight2(left, right) : type_exports3.IsObject(right) ? FromObjectRight2(left, right) : type_exports3.IsRecord(right) ? FromRecordRight2(left, right) : type_exports3.IsNull(right) ? ExtendsResult2.True : ExtendsResult2.False;
}
function FromNumberRight2(left, right) {
  return type_exports3.IsLiteralNumber(left) ? ExtendsResult2.True : type_exports3.IsNumber(left) || type_exports3.IsInteger(left) ? ExtendsResult2.True : ExtendsResult2.False;
}
function FromNumber2(left, right) {
  return IsStructuralRight2(right) ? StructuralRight2(left, right) : type_exports3.IsObject(right) ? FromObjectRight2(left, right) : type_exports3.IsRecord(right) ? FromRecordRight2(left, right) : type_exports3.IsInteger(right) || type_exports3.IsNumber(right) ? ExtendsResult2.True : ExtendsResult2.False;
}
function IsObjectPropertyCount2(schema, count) {
  return Object.getOwnPropertyNames(schema.properties).length === count;
}
function IsObjectStringLike2(schema) {
  return IsObjectArrayLike2(schema);
}
function IsObjectSymbolLike2(schema) {
  return IsObjectPropertyCount2(schema, 0) || IsObjectPropertyCount2(schema, 1) && "description" in schema.properties && type_exports3.IsUnion(schema.properties.description) && schema.properties.description.anyOf.length === 2 && (type_exports3.IsString(schema.properties.description.anyOf[0]) && type_exports3.IsUndefined(schema.properties.description.anyOf[1]) || type_exports3.IsString(schema.properties.description.anyOf[1]) && type_exports3.IsUndefined(schema.properties.description.anyOf[0]));
}
function IsObjectNumberLike2(schema) {
  return IsObjectPropertyCount2(schema, 0);
}
function IsObjectBooleanLike2(schema) {
  return IsObjectPropertyCount2(schema, 0);
}
function IsObjectBigIntLike2(schema) {
  return IsObjectPropertyCount2(schema, 0);
}
function IsObjectDateLike2(schema) {
  return IsObjectPropertyCount2(schema, 0);
}
function IsObjectUint8ArrayLike2(schema) {
  return IsObjectArrayLike2(schema);
}
function IsObjectFunctionLike2(schema) {
  const length = Number3();
  return IsObjectPropertyCount2(schema, 0) || IsObjectPropertyCount2(schema, 1) && "length" in schema.properties && IntoBooleanResult2(Visit6(schema.properties["length"], length)) === ExtendsResult2.True;
}
function IsObjectConstructorLike2(schema) {
  return IsObjectPropertyCount2(schema, 0);
}
function IsObjectArrayLike2(schema) {
  const length = Number3();
  return IsObjectPropertyCount2(schema, 0) || IsObjectPropertyCount2(schema, 1) && "length" in schema.properties && IntoBooleanResult2(Visit6(schema.properties["length"], length)) === ExtendsResult2.True;
}
function IsObjectPromiseLike2(schema) {
  const then = Function3([Any2()], Any2());
  return IsObjectPropertyCount2(schema, 0) || IsObjectPropertyCount2(schema, 1) && "then" in schema.properties && IntoBooleanResult2(Visit6(schema.properties["then"], then)) === ExtendsResult2.True;
}
function Property2(left, right) {
  return Visit6(left, right) === ExtendsResult2.False ? ExtendsResult2.False : type_exports3.IsOptional(left) && !type_exports3.IsOptional(right) ? ExtendsResult2.False : ExtendsResult2.True;
}
function FromObjectRight2(left, right) {
  return type_exports3.IsUnknown(left) ? ExtendsResult2.False : type_exports3.IsAny(left) ? ExtendsResult2.Union : type_exports3.IsNever(left) || type_exports3.IsLiteralString(left) && IsObjectStringLike2(right) || type_exports3.IsLiteralNumber(left) && IsObjectNumberLike2(right) || type_exports3.IsLiteralBoolean(left) && IsObjectBooleanLike2(right) || type_exports3.IsSymbol(left) && IsObjectSymbolLike2(right) || type_exports3.IsBigInt(left) && IsObjectBigIntLike2(right) || type_exports3.IsString(left) && IsObjectStringLike2(right) || type_exports3.IsSymbol(left) && IsObjectSymbolLike2(right) || type_exports3.IsNumber(left) && IsObjectNumberLike2(right) || type_exports3.IsInteger(left) && IsObjectNumberLike2(right) || type_exports3.IsBoolean(left) && IsObjectBooleanLike2(right) || type_exports3.IsUint8Array(left) && IsObjectUint8ArrayLike2(right) || type_exports3.IsDate(left) && IsObjectDateLike2(right) || type_exports3.IsConstructor(left) && IsObjectConstructorLike2(right) || type_exports3.IsFunction(left) && IsObjectFunctionLike2(right) ? ExtendsResult2.True : type_exports3.IsRecord(left) && type_exports3.IsString(RecordKey3(left)) ? (() => {
    return right[Hint2] === "Record" ? ExtendsResult2.True : ExtendsResult2.False;
  })() : type_exports3.IsRecord(left) && type_exports3.IsNumber(RecordKey3(left)) ? (() => {
    return IsObjectPropertyCount2(right, 0) ? ExtendsResult2.True : ExtendsResult2.False;
  })() : ExtendsResult2.False;
}
function FromObject8(left, right) {
  return IsStructuralRight2(right) ? StructuralRight2(left, right) : type_exports3.IsRecord(right) ? FromRecordRight2(left, right) : !type_exports3.IsObject(right) ? ExtendsResult2.False : (() => {
    for (const key of Object.getOwnPropertyNames(right.properties)) {
      if (!(key in left.properties) && !type_exports3.IsOptional(right.properties[key])) {
        return ExtendsResult2.False;
      }
      if (type_exports3.IsOptional(right.properties[key])) {
        return ExtendsResult2.True;
      }
      if (Property2(left.properties[key], right.properties[key]) === ExtendsResult2.False) {
        return ExtendsResult2.False;
      }
    }
    return ExtendsResult2.True;
  })();
}
function FromPromise5(left, right) {
  return IsStructuralRight2(right) ? StructuralRight2(left, right) : type_exports3.IsObject(right) && IsObjectPromiseLike2(right) ? ExtendsResult2.True : !type_exports3.IsPromise(right) ? ExtendsResult2.False : IntoBooleanResult2(Visit6(left.item, right.item));
}
function RecordKey3(schema) {
  return PatternNumberExact2 in schema.patternProperties ? Number3() : PatternStringExact2 in schema.patternProperties ? String3() : Throw2("Unknown record key pattern");
}
function RecordValue3(schema) {
  return PatternNumberExact2 in schema.patternProperties ? schema.patternProperties[PatternNumberExact2] : PatternStringExact2 in schema.patternProperties ? schema.patternProperties[PatternStringExact2] : Throw2("Unable to get record value schema");
}
function FromRecordRight2(left, right) {
  const [Key, Value] = [RecordKey3(right), RecordValue3(right)];
  return type_exports3.IsLiteralString(left) && type_exports3.IsNumber(Key) && IntoBooleanResult2(Visit6(left, Value)) === ExtendsResult2.True ? ExtendsResult2.True : type_exports3.IsUint8Array(left) && type_exports3.IsNumber(Key) ? Visit6(left, Value) : type_exports3.IsString(left) && type_exports3.IsNumber(Key) ? Visit6(left, Value) : type_exports3.IsArray(left) && type_exports3.IsNumber(Key) ? Visit6(left, Value) : type_exports3.IsObject(left) ? (() => {
    for (const key of Object.getOwnPropertyNames(left.properties)) {
      if (Property2(Value, left.properties[key]) === ExtendsResult2.False) {
        return ExtendsResult2.False;
      }
    }
    return ExtendsResult2.True;
  })() : ExtendsResult2.False;
}
function FromRecord4(left, right) {
  return IsStructuralRight2(right) ? StructuralRight2(left, right) : type_exports3.IsObject(right) ? FromObjectRight2(left, right) : !type_exports3.IsRecord(right) ? ExtendsResult2.False : Visit6(RecordValue3(left), RecordValue3(right));
}
function FromRegExp2(left, right) {
  const L3 = type_exports3.IsRegExp(left) ? String3() : left;
  const R3 = type_exports3.IsRegExp(right) ? String3() : right;
  return Visit6(L3, R3);
}
function FromStringRight2(left, right) {
  return type_exports3.IsLiteral(left) && value_exports2.IsString(left.const) ? ExtendsResult2.True : type_exports3.IsString(left) ? ExtendsResult2.True : ExtendsResult2.False;
}
function FromString2(left, right) {
  return IsStructuralRight2(right) ? StructuralRight2(left, right) : type_exports3.IsObject(right) ? FromObjectRight2(left, right) : type_exports3.IsRecord(right) ? FromRecordRight2(left, right) : type_exports3.IsString(right) ? ExtendsResult2.True : ExtendsResult2.False;
}
function FromSymbol2(left, right) {
  return IsStructuralRight2(right) ? StructuralRight2(left, right) : type_exports3.IsObject(right) ? FromObjectRight2(left, right) : type_exports3.IsRecord(right) ? FromRecordRight2(left, right) : type_exports3.IsSymbol(right) ? ExtendsResult2.True : ExtendsResult2.False;
}
function FromTemplateLiteral5(left, right) {
  return type_exports3.IsTemplateLiteral(left) ? Visit6(TemplateLiteralToUnion2(left), right) : type_exports3.IsTemplateLiteral(right) ? Visit6(left, TemplateLiteralToUnion2(right)) : Throw2("Invalid fallthrough for TemplateLiteral");
}
function IsArrayOfTuple2(left, right) {
  return type_exports3.IsArray(right) && left.items !== void 0 && left.items.every((schema) => Visit6(schema, right.items) === ExtendsResult2.True);
}
function FromTupleRight2(left, right) {
  return type_exports3.IsNever(left) ? ExtendsResult2.True : type_exports3.IsUnknown(left) ? ExtendsResult2.False : type_exports3.IsAny(left) ? ExtendsResult2.Union : ExtendsResult2.False;
}
function FromTuple8(left, right) {
  return IsStructuralRight2(right) ? StructuralRight2(left, right) : type_exports3.IsObject(right) && IsObjectArrayLike2(right) ? ExtendsResult2.True : type_exports3.IsArray(right) && IsArrayOfTuple2(left, right) ? ExtendsResult2.True : !type_exports3.IsTuple(right) ? ExtendsResult2.False : value_exports2.IsUndefined(left.items) && !value_exports2.IsUndefined(right.items) || !value_exports2.IsUndefined(left.items) && value_exports2.IsUndefined(right.items) ? ExtendsResult2.False : value_exports2.IsUndefined(left.items) && !value_exports2.IsUndefined(right.items) ? ExtendsResult2.True : left.items.every((schema, index) => Visit6(schema, right.items[index]) === ExtendsResult2.True) ? ExtendsResult2.True : ExtendsResult2.False;
}
function FromUint8Array2(left, right) {
  return IsStructuralRight2(right) ? StructuralRight2(left, right) : type_exports3.IsObject(right) ? FromObjectRight2(left, right) : type_exports3.IsRecord(right) ? FromRecordRight2(left, right) : type_exports3.IsUint8Array(right) ? ExtendsResult2.True : ExtendsResult2.False;
}
function FromUndefined2(left, right) {
  return IsStructuralRight2(right) ? StructuralRight2(left, right) : type_exports3.IsObject(right) ? FromObjectRight2(left, right) : type_exports3.IsRecord(right) ? FromRecordRight2(left, right) : type_exports3.IsVoid(right) ? FromVoidRight2(left, right) : type_exports3.IsUndefined(right) ? ExtendsResult2.True : ExtendsResult2.False;
}
function FromUnionRight2(left, right) {
  return right.anyOf.some((schema) => Visit6(left, schema) === ExtendsResult2.True) ? ExtendsResult2.True : ExtendsResult2.False;
}
function FromUnion16(left, right) {
  return left.anyOf.every((schema) => Visit6(schema, right) === ExtendsResult2.True) ? ExtendsResult2.True : ExtendsResult2.False;
}
function FromUnknownRight2(left, right) {
  return ExtendsResult2.True;
}
function FromUnknown2(left, right) {
  return type_exports3.IsNever(right) ? FromNeverRight2(left, right) : type_exports3.IsIntersect(right) ? FromIntersectRight2(left, right) : type_exports3.IsUnion(right) ? FromUnionRight2(left, right) : type_exports3.IsAny(right) ? FromAnyRight2(left, right) : type_exports3.IsString(right) ? FromStringRight2(left, right) : type_exports3.IsNumber(right) ? FromNumberRight2(left, right) : type_exports3.IsInteger(right) ? FromIntegerRight2(left, right) : type_exports3.IsBoolean(right) ? FromBooleanRight2(left, right) : type_exports3.IsArray(right) ? FromArrayRight2(left, right) : type_exports3.IsTuple(right) ? FromTupleRight2(left, right) : type_exports3.IsObject(right) ? FromObjectRight2(left, right) : type_exports3.IsUnknown(right) ? ExtendsResult2.True : ExtendsResult2.False;
}
function FromVoidRight2(left, right) {
  return type_exports3.IsUndefined(left) ? ExtendsResult2.True : type_exports3.IsUndefined(left) ? ExtendsResult2.True : ExtendsResult2.False;
}
function FromVoid2(left, right) {
  return type_exports3.IsIntersect(right) ? FromIntersectRight2(left, right) : type_exports3.IsUnion(right) ? FromUnionRight2(left, right) : type_exports3.IsUnknown(right) ? FromUnknownRight2(left, right) : type_exports3.IsAny(right) ? FromAnyRight2(left, right) : type_exports3.IsObject(right) ? FromObjectRight2(left, right) : type_exports3.IsVoid(right) ? ExtendsResult2.True : ExtendsResult2.False;
}
function Visit6(left, right) {
  return (
    // resolvable
    type_exports3.IsTemplateLiteral(left) || type_exports3.IsTemplateLiteral(right) ? FromTemplateLiteral5(left, right) : type_exports3.IsRegExp(left) || type_exports3.IsRegExp(right) ? FromRegExp2(left, right) : type_exports3.IsNot(left) || type_exports3.IsNot(right) ? FromNot2(left, right) : (
      // standard
      type_exports3.IsAny(left) ? FromAny2(left, right) : type_exports3.IsArray(left) ? FromArray10(left, right) : type_exports3.IsBigInt(left) ? FromBigInt2(left, right) : type_exports3.IsBoolean(left) ? FromBoolean2(left, right) : type_exports3.IsAsyncIterator(left) ? FromAsyncIterator4(left, right) : type_exports3.IsConstructor(left) ? FromConstructor4(left, right) : type_exports3.IsDate(left) ? FromDate2(left, right) : type_exports3.IsFunction(left) ? FromFunction4(left, right) : type_exports3.IsInteger(left) ? FromInteger2(left, right) : type_exports3.IsIntersect(left) ? FromIntersect12(left, right) : type_exports3.IsIterator(left) ? FromIterator4(left, right) : type_exports3.IsLiteral(left) ? FromLiteral4(left, right) : type_exports3.IsNever(left) ? FromNever2(left, right) : type_exports3.IsNull(left) ? FromNull2(left, right) : type_exports3.IsNumber(left) ? FromNumber2(left, right) : type_exports3.IsObject(left) ? FromObject8(left, right) : type_exports3.IsRecord(left) ? FromRecord4(left, right) : type_exports3.IsString(left) ? FromString2(left, right) : type_exports3.IsSymbol(left) ? FromSymbol2(left, right) : type_exports3.IsTuple(left) ? FromTuple8(left, right) : type_exports3.IsPromise(left) ? FromPromise5(left, right) : type_exports3.IsUint8Array(left) ? FromUint8Array2(left, right) : type_exports3.IsUndefined(left) ? FromUndefined2(left, right) : type_exports3.IsUnion(left) ? FromUnion16(left, right) : type_exports3.IsUnknown(left) ? FromUnknown2(left, right) : type_exports3.IsVoid(left) ? FromVoid2(left, right) : Throw2(`Unknown left type operand '${left[Kind2]}'`)
    )
  );
}
function ExtendsCheck2(left, right) {
  return Visit6(left, right);
}

// node_modules/@sinclair/typebox/build/esm/type/extends/extends-from-mapped-key.mjs
init_process_shim();

// node_modules/@sinclair/typebox/build/esm/type/extends/extends.mjs
init_process_shim();

// node_modules/@sinclair/typebox/build/esm/type/extends/extends-from-mapped-result.mjs
init_process_shim();
function FromProperties27(P3, Right, True, False, options) {
  const Acc = {};
  for (const K2 of globalThis.Object.getOwnPropertyNames(P3))
    Acc[K2] = Extends2(P3[K2], Right, True, False, Clone2(options));
  return Acc;
}
function FromMappedResult18(Left, Right, True, False, options) {
  return FromProperties27(Left.properties, Right, True, False, options);
}
function ExtendsFromMappedResult2(Left, Right, True, False, options) {
  const P3 = FromMappedResult18(Left, Right, True, False, options);
  return MappedResult2(P3);
}

// node_modules/@sinclair/typebox/build/esm/type/extends/extends.mjs
function ExtendsResolve2(left, right, trueType, falseType) {
  const R3 = ExtendsCheck2(left, right);
  return R3 === ExtendsResult2.Union ? Union2([trueType, falseType]) : R3 === ExtendsResult2.True ? trueType : falseType;
}
function Extends2(L3, R3, T3, F2, options) {
  return IsMappedResult3(L3) ? ExtendsFromMappedResult2(L3, R3, T3, F2, options) : IsMappedKey3(L3) ? CreateType2(ExtendsFromMappedKey2(L3, R3, T3, F2, options)) : CreateType2(ExtendsResolve2(L3, R3, T3, F2), options);
}

// node_modules/@sinclair/typebox/build/esm/type/extends/extends-from-mapped-key.mjs
function FromPropertyKey4(K2, U2, L3, R3, options) {
  return {
    [K2]: Extends2(Literal2(K2), U2, L3, R3, Clone2(options))
  };
}
function FromPropertyKeys4(K2, U2, L3, R3, options) {
  return K2.reduce((Acc, LK) => {
    return { ...Acc, ...FromPropertyKey4(LK, U2, L3, R3, options) };
  }, {});
}
function FromMappedKey6(K2, U2, L3, R3, options) {
  return FromPropertyKeys4(K2.keys, U2, L3, R3, options);
}
function ExtendsFromMappedKey2(T3, U2, L3, R3, options) {
  const P3 = FromMappedKey6(T3, U2, L3, R3, options);
  return MappedResult2(P3);
}

// node_modules/@sinclair/typebox/build/esm/type/exclude/exclude-from-template-literal.mjs
init_process_shim();
function ExcludeFromTemplateLiteral2(L3, R3) {
  return Exclude2(TemplateLiteralToUnion2(L3), R3);
}

// node_modules/@sinclair/typebox/build/esm/type/exclude/exclude.mjs
function ExcludeRest2(L3, R3) {
  const excluded = L3.filter((inner2) => ExtendsCheck2(inner2, R3) === ExtendsResult2.False);
  return excluded.length === 1 ? excluded[0] : Union2(excluded);
}
function Exclude2(L3, R3, options = {}) {
  if (IsTemplateLiteral3(L3))
    return CreateType2(ExcludeFromTemplateLiteral2(L3, R3), options);
  if (IsMappedResult3(L3))
    return CreateType2(ExcludeFromMappedResult2(L3, R3), options);
  return CreateType2(IsUnion3(L3) ? ExcludeRest2(L3.anyOf, R3) : ExtendsCheck2(L3, R3) !== ExtendsResult2.False ? Never2() : L3, options);
}

// node_modules/@sinclair/typebox/build/esm/type/exclude/exclude-from-mapped-result.mjs
function FromProperties28(P3, U2) {
  const Acc = {};
  for (const K2 of globalThis.Object.getOwnPropertyNames(P3))
    Acc[K2] = Exclude2(P3[K2], U2);
  return Acc;
}
function FromMappedResult19(R3, T3) {
  return FromProperties28(R3.properties, T3);
}
function ExcludeFromMappedResult2(R3, T3) {
  const P3 = FromMappedResult19(R3, T3);
  return MappedResult2(P3);
}

// node_modules/@sinclair/typebox/build/esm/type/extract/extract-from-mapped-result.mjs
init_process_shim();

// node_modules/@sinclair/typebox/build/esm/type/extract/extract.mjs
init_process_shim();

// node_modules/@sinclair/typebox/build/esm/type/extract/extract-from-template-literal.mjs
init_process_shim();
function ExtractFromTemplateLiteral2(L3, R3) {
  return Extract2(TemplateLiteralToUnion2(L3), R3);
}

// node_modules/@sinclair/typebox/build/esm/type/extract/extract.mjs
function ExtractRest2(L3, R3) {
  const extracted = L3.filter((inner2) => ExtendsCheck2(inner2, R3) !== ExtendsResult2.False);
  return extracted.length === 1 ? extracted[0] : Union2(extracted);
}
function Extract2(L3, R3, options) {
  if (IsTemplateLiteral3(L3))
    return CreateType2(ExtractFromTemplateLiteral2(L3, R3), options);
  if (IsMappedResult3(L3))
    return CreateType2(ExtractFromMappedResult2(L3, R3), options);
  return CreateType2(IsUnion3(L3) ? ExtractRest2(L3.anyOf, R3) : ExtendsCheck2(L3, R3) !== ExtendsResult2.False ? L3 : Never2(), options);
}

// node_modules/@sinclair/typebox/build/esm/type/extract/extract-from-mapped-result.mjs
function FromProperties29(P3, T3) {
  const Acc = {};
  for (const K2 of globalThis.Object.getOwnPropertyNames(P3))
    Acc[K2] = Extract2(P3[K2], T3);
  return Acc;
}
function FromMappedResult20(R3, T3) {
  return FromProperties29(R3.properties, T3);
}
function ExtractFromMappedResult2(R3, T3) {
  const P3 = FromMappedResult20(R3, T3);
  return MappedResult2(P3);
}

// node_modules/@sinclair/typebox/build/esm/type/instance-type/instance-type.mjs
init_process_shim();
function InstanceType2(schema, options) {
  return IsConstructor3(schema) ? CreateType2(schema.returns, options) : Never2(options);
}

// node_modules/@sinclair/typebox/build/esm/type/instantiate/instantiate.mjs
init_process_shim();

// node_modules/@sinclair/typebox/build/esm/type/readonly-optional/readonly-optional.mjs
init_process_shim();
function ReadonlyOptional2(schema) {
  return Readonly2(Optional2(schema));
}

// node_modules/@sinclair/typebox/build/esm/type/record/record.mjs
init_process_shim();
function RecordCreateFromPattern2(pattern, T3, options) {
  return CreateType2({ [Kind2]: "Record", type: "object", patternProperties: { [pattern]: T3 } }, options);
}
function RecordCreateFromKeys2(K2, T3, options) {
  const result = {};
  for (const K22 of K2)
    result[K22] = T3;
  return Object3(result, { ...options, [Hint2]: "Record" });
}
function FromTemplateLiteralKey2(K2, T3, options) {
  return IsTemplateLiteralFinite2(K2) ? RecordCreateFromKeys2(IndexPropertyKeys2(K2), T3, options) : RecordCreateFromPattern2(K2.pattern, T3, options);
}
function FromUnionKey2(key, type, options) {
  return RecordCreateFromKeys2(IndexPropertyKeys2(Union2(key)), type, options);
}
function FromLiteralKey2(key, type, options) {
  return RecordCreateFromKeys2([key.toString()], type, options);
}
function FromRegExpKey2(key, type, options) {
  return RecordCreateFromPattern2(key.source, type, options);
}
function FromStringKey2(key, type, options) {
  const pattern = IsUndefined5(key.pattern) ? PatternStringExact2 : key.pattern;
  return RecordCreateFromPattern2(pattern, type, options);
}
function FromAnyKey2(_3, type, options) {
  return RecordCreateFromPattern2(PatternStringExact2, type, options);
}
function FromNeverKey2(_key, type, options) {
  return RecordCreateFromPattern2(PatternNeverExact2, type, options);
}
function FromBooleanKey2(_key, type, options) {
  return Object3({ true: type, false: type }, options);
}
function FromIntegerKey2(_key, type, options) {
  return RecordCreateFromPattern2(PatternNumberExact2, type, options);
}
function FromNumberKey2(_3, type, options) {
  return RecordCreateFromPattern2(PatternNumberExact2, type, options);
}
function Record2(key, type, options = {}) {
  return IsUnion3(key) ? FromUnionKey2(key.anyOf, type, options) : IsTemplateLiteral3(key) ? FromTemplateLiteralKey2(key, type, options) : IsLiteral3(key) ? FromLiteralKey2(key.const, type, options) : IsBoolean5(key) ? FromBooleanKey2(key, type, options) : IsInteger3(key) ? FromIntegerKey2(key, type, options) : IsNumber7(key) ? FromNumberKey2(key, type, options) : IsRegExp5(key) ? FromRegExpKey2(key, type, options) : IsString5(key) ? FromStringKey2(key, type, options) : IsAny3(key) ? FromAnyKey2(key, type, options) : IsNever3(key) ? FromNeverKey2(key, type, options) : Never2(options);
}
function RecordPattern2(record) {
  return globalThis.Object.getOwnPropertyNames(record.patternProperties)[0];
}
function RecordKey4(type) {
  const pattern = RecordPattern2(type);
  return pattern === PatternStringExact2 ? String3() : pattern === PatternNumberExact2 ? Number3() : String3({ pattern });
}
function RecordValue4(type) {
  return type.patternProperties[RecordPattern2(type)];
}

// node_modules/@sinclair/typebox/build/esm/type/instantiate/instantiate.mjs
function FromConstructor5(args, type) {
  type.parameters = FromTypes3(args, type.parameters);
  type.returns = FromType3(args, type.returns);
  return type;
}
function FromFunction5(args, type) {
  type.parameters = FromTypes3(args, type.parameters);
  type.returns = FromType3(args, type.returns);
  return type;
}
function FromIntersect13(args, type) {
  type.allOf = FromTypes3(args, type.allOf);
  return type;
}
function FromUnion17(args, type) {
  type.anyOf = FromTypes3(args, type.anyOf);
  return type;
}
function FromTuple9(args, type) {
  if (IsUndefined5(type.items))
    return type;
  type.items = FromTypes3(args, type.items);
  return type;
}
function FromArray11(args, type) {
  type.items = FromType3(args, type.items);
  return type;
}
function FromAsyncIterator5(args, type) {
  type.items = FromType3(args, type.items);
  return type;
}
function FromIterator5(args, type) {
  type.items = FromType3(args, type.items);
  return type;
}
function FromPromise6(args, type) {
  type.item = FromType3(args, type.item);
  return type;
}
function FromObject9(args, type) {
  const mappedProperties = FromProperties30(args, type.properties);
  return { ...type, ...Object3(mappedProperties) };
}
function FromRecord5(args, type) {
  const mappedKey = FromType3(args, RecordKey4(type));
  const mappedValue = FromType3(args, RecordValue4(type));
  const result = Record2(mappedKey, mappedValue);
  return { ...type, ...result };
}
function FromArgument2(args, argument) {
  return argument.index in args ? args[argument.index] : Unknown2();
}
function FromProperty5(args, type) {
  const isReadonly = IsReadonly3(type);
  const isOptional = IsOptional3(type);
  const mapped = FromType3(args, type);
  return isReadonly && isOptional ? ReadonlyOptional2(mapped) : isReadonly && !isOptional ? Readonly2(mapped) : !isReadonly && isOptional ? Optional2(mapped) : mapped;
}
function FromProperties30(args, properties) {
  return globalThis.Object.getOwnPropertyNames(properties).reduce((result, key) => {
    return { ...result, [key]: FromProperty5(args, properties[key]) };
  }, {});
}
function FromTypes3(args, types2) {
  return types2.map((type) => FromType3(args, type));
}
function FromType3(args, type) {
  return IsConstructor3(type) ? FromConstructor5(args, type) : IsFunction5(type) ? FromFunction5(args, type) : IsIntersect3(type) ? FromIntersect13(args, type) : IsUnion3(type) ? FromUnion17(args, type) : IsTuple3(type) ? FromTuple9(args, type) : IsArray7(type) ? FromArray11(args, type) : IsAsyncIterator5(type) ? FromAsyncIterator5(args, type) : IsIterator5(type) ? FromIterator5(args, type) : IsPromise3(type) ? FromPromise6(args, type) : IsObject7(type) ? FromObject9(args, type) : IsRecord3(type) ? FromRecord5(args, type) : IsArgument3(type) ? FromArgument2(args, type) : type;
}
function Instantiate2(type, args) {
  return FromType3(args, CloneType2(type));
}

// node_modules/@sinclair/typebox/build/esm/type/integer/integer.mjs
init_process_shim();
function Integer2(options) {
  return CreateType2({ [Kind2]: "Integer", type: "integer" }, options);
}

// node_modules/@sinclair/typebox/build/esm/type/intrinsic/capitalize.mjs
init_process_shim();

// node_modules/@sinclair/typebox/build/esm/type/intrinsic/intrinsic.mjs
init_process_shim();

// node_modules/@sinclair/typebox/build/esm/type/intrinsic/intrinsic-from-mapped-key.mjs
init_process_shim();
function MappedIntrinsicPropertyKey2(K2, M4, options) {
  return {
    [K2]: Intrinsic2(Literal2(K2), M4, Clone2(options))
  };
}
function MappedIntrinsicPropertyKeys2(K2, M4, options) {
  const result = K2.reduce((Acc, L3) => {
    return { ...Acc, ...MappedIntrinsicPropertyKey2(L3, M4, options) };
  }, {});
  return result;
}
function MappedIntrinsicProperties2(T3, M4, options) {
  return MappedIntrinsicPropertyKeys2(T3["keys"], M4, options);
}
function IntrinsicFromMappedKey2(T3, M4, options) {
  const P3 = MappedIntrinsicProperties2(T3, M4, options);
  return MappedResult2(P3);
}

// node_modules/@sinclair/typebox/build/esm/type/intrinsic/intrinsic.mjs
function ApplyUncapitalize2(value) {
  const [first, rest] = [value.slice(0, 1), value.slice(1)];
  return [first.toLowerCase(), rest].join("");
}
function ApplyCapitalize2(value) {
  const [first, rest] = [value.slice(0, 1), value.slice(1)];
  return [first.toUpperCase(), rest].join("");
}
function ApplyUppercase2(value) {
  return value.toUpperCase();
}
function ApplyLowercase2(value) {
  return value.toLowerCase();
}
function FromTemplateLiteral6(schema, mode, options) {
  const expression = TemplateLiteralParseExact2(schema.pattern);
  const finite = IsTemplateLiteralExpressionFinite2(expression);
  if (!finite)
    return { ...schema, pattern: FromLiteralValue2(schema.pattern, mode) };
  const strings = [...TemplateLiteralExpressionGenerate2(expression)];
  const literals = strings.map((value) => Literal2(value));
  const mapped = FromRest12(literals, mode);
  const union = Union2(mapped);
  return TemplateLiteral2([union], options);
}
function FromLiteralValue2(value, mode) {
  return typeof value === "string" ? mode === "Uncapitalize" ? ApplyUncapitalize2(value) : mode === "Capitalize" ? ApplyCapitalize2(value) : mode === "Uppercase" ? ApplyUppercase2(value) : mode === "Lowercase" ? ApplyLowercase2(value) : value : value.toString();
}
function FromRest12(T3, M4) {
  return T3.map((L3) => Intrinsic2(L3, M4));
}
function Intrinsic2(schema, mode, options = {}) {
  return (
    // Intrinsic-Mapped-Inference
    IsMappedKey3(schema) ? IntrinsicFromMappedKey2(schema, mode, options) : (
      // Standard-Inference
      IsTemplateLiteral3(schema) ? FromTemplateLiteral6(schema, mode, options) : IsUnion3(schema) ? Union2(FromRest12(schema.anyOf, mode), options) : IsLiteral3(schema) ? Literal2(FromLiteralValue2(schema.const, mode), options) : (
        // Default Type
        CreateType2(schema, options)
      )
    )
  );
}

// node_modules/@sinclair/typebox/build/esm/type/intrinsic/capitalize.mjs
function Capitalize2(T3, options = {}) {
  return Intrinsic2(T3, "Capitalize", options);
}

// node_modules/@sinclair/typebox/build/esm/type/intrinsic/lowercase.mjs
init_process_shim();
function Lowercase2(T3, options = {}) {
  return Intrinsic2(T3, "Lowercase", options);
}

// node_modules/@sinclair/typebox/build/esm/type/intrinsic/uncapitalize.mjs
init_process_shim();
function Uncapitalize2(T3, options = {}) {
  return Intrinsic2(T3, "Uncapitalize", options);
}

// node_modules/@sinclair/typebox/build/esm/type/intrinsic/uppercase.mjs
init_process_shim();
function Uppercase2(T3, options = {}) {
  return Intrinsic2(T3, "Uppercase", options);
}

// node_modules/@sinclair/typebox/build/esm/type/module/module.mjs
init_process_shim();

// node_modules/@sinclair/typebox/build/esm/type/module/compute.mjs
init_process_shim();

// node_modules/@sinclair/typebox/build/esm/type/omit/omit-from-mapped-key.mjs
init_process_shim();

// node_modules/@sinclair/typebox/build/esm/type/omit/omit.mjs
init_process_shim();

// node_modules/@sinclair/typebox/build/esm/type/omit/omit-from-mapped-result.mjs
init_process_shim();
function FromProperties31(properties, propertyKeys, options) {
  const result = {};
  for (const K2 of globalThis.Object.getOwnPropertyNames(properties))
    result[K2] = Omit2(properties[K2], propertyKeys, Clone2(options));
  return result;
}
function FromMappedResult21(mappedResult, propertyKeys, options) {
  return FromProperties31(mappedResult.properties, propertyKeys, options);
}
function OmitFromMappedResult2(mappedResult, propertyKeys, options) {
  const properties = FromMappedResult21(mappedResult, propertyKeys, options);
  return MappedResult2(properties);
}

// node_modules/@sinclair/typebox/build/esm/type/omit/omit.mjs
function FromIntersect14(types2, propertyKeys) {
  return types2.map((type) => OmitResolve2(type, propertyKeys));
}
function FromUnion18(types2, propertyKeys) {
  return types2.map((type) => OmitResolve2(type, propertyKeys));
}
function FromProperty6(properties, key) {
  const { [key]: _3, ...R3 } = properties;
  return R3;
}
function FromProperties32(properties, propertyKeys) {
  return propertyKeys.reduce((T3, K2) => FromProperty6(T3, K2), properties);
}
function FromObject10(type, propertyKeys, properties) {
  const options = Discard2(type, [TransformKind2, "$id", "required", "properties"]);
  const mappedProperties = FromProperties32(properties, propertyKeys);
  return Object3(mappedProperties, options);
}
function UnionFromPropertyKeys3(propertyKeys) {
  const result = propertyKeys.reduce((result2, key) => IsLiteralValue3(key) ? [...result2, Literal2(key)] : result2, []);
  return Union2(result);
}
function OmitResolve2(type, propertyKeys) {
  return IsIntersect3(type) ? Intersect2(FromIntersect14(type.allOf, propertyKeys)) : IsUnion3(type) ? Union2(FromUnion18(type.anyOf, propertyKeys)) : IsObject7(type) ? FromObject10(type, propertyKeys, type.properties) : Object3({});
}
function Omit2(type, key, options) {
  const typeKey = IsArray5(key) ? UnionFromPropertyKeys3(key) : key;
  const propertyKeys = IsSchema3(key) ? IndexPropertyKeys2(key) : key;
  const isTypeRef = IsRef3(type);
  const isKeyRef = IsRef3(key);
  return IsMappedResult3(type) ? OmitFromMappedResult2(type, propertyKeys, options) : IsMappedKey3(key) ? OmitFromMappedKey2(type, key, options) : isTypeRef && isKeyRef ? Computed2("Omit", [type, typeKey], options) : !isTypeRef && isKeyRef ? Computed2("Omit", [type, typeKey], options) : isTypeRef && !isKeyRef ? Computed2("Omit", [type, typeKey], options) : CreateType2({ ...OmitResolve2(type, propertyKeys), ...options });
}

// node_modules/@sinclair/typebox/build/esm/type/omit/omit-from-mapped-key.mjs
function FromPropertyKey5(type, key, options) {
  return { [key]: Omit2(type, [key], Clone2(options)) };
}
function FromPropertyKeys5(type, propertyKeys, options) {
  return propertyKeys.reduce((Acc, LK) => {
    return { ...Acc, ...FromPropertyKey5(type, LK, options) };
  }, {});
}
function FromMappedKey7(type, mappedKey, options) {
  return FromPropertyKeys5(type, mappedKey.keys, options);
}
function OmitFromMappedKey2(type, mappedKey, options) {
  const properties = FromMappedKey7(type, mappedKey, options);
  return MappedResult2(properties);
}

// node_modules/@sinclair/typebox/build/esm/type/pick/pick-from-mapped-key.mjs
init_process_shim();

// node_modules/@sinclair/typebox/build/esm/type/pick/pick.mjs
init_process_shim();

// node_modules/@sinclair/typebox/build/esm/type/pick/pick-from-mapped-result.mjs
init_process_shim();
function FromProperties33(properties, propertyKeys, options) {
  const result = {};
  for (const K2 of globalThis.Object.getOwnPropertyNames(properties))
    result[K2] = Pick2(properties[K2], propertyKeys, Clone2(options));
  return result;
}
function FromMappedResult22(mappedResult, propertyKeys, options) {
  return FromProperties33(mappedResult.properties, propertyKeys, options);
}
function PickFromMappedResult2(mappedResult, propertyKeys, options) {
  const properties = FromMappedResult22(mappedResult, propertyKeys, options);
  return MappedResult2(properties);
}

// node_modules/@sinclair/typebox/build/esm/type/pick/pick.mjs
function FromIntersect15(types2, propertyKeys) {
  return types2.map((type) => PickResolve2(type, propertyKeys));
}
function FromUnion19(types2, propertyKeys) {
  return types2.map((type) => PickResolve2(type, propertyKeys));
}
function FromProperties34(properties, propertyKeys) {
  const result = {};
  for (const K2 of propertyKeys)
    if (K2 in properties)
      result[K2] = properties[K2];
  return result;
}
function FromObject11(Type4, keys2, properties) {
  const options = Discard2(Type4, [TransformKind2, "$id", "required", "properties"]);
  const mappedProperties = FromProperties34(properties, keys2);
  return Object3(mappedProperties, options);
}
function UnionFromPropertyKeys4(propertyKeys) {
  const result = propertyKeys.reduce((result2, key) => IsLiteralValue3(key) ? [...result2, Literal2(key)] : result2, []);
  return Union2(result);
}
function PickResolve2(type, propertyKeys) {
  return IsIntersect3(type) ? Intersect2(FromIntersect15(type.allOf, propertyKeys)) : IsUnion3(type) ? Union2(FromUnion19(type.anyOf, propertyKeys)) : IsObject7(type) ? FromObject11(type, propertyKeys, type.properties) : Object3({});
}
function Pick2(type, key, options) {
  const typeKey = IsArray5(key) ? UnionFromPropertyKeys4(key) : key;
  const propertyKeys = IsSchema3(key) ? IndexPropertyKeys2(key) : key;
  const isTypeRef = IsRef3(type);
  const isKeyRef = IsRef3(key);
  return IsMappedResult3(type) ? PickFromMappedResult2(type, propertyKeys, options) : IsMappedKey3(key) ? PickFromMappedKey2(type, key, options) : isTypeRef && isKeyRef ? Computed2("Pick", [type, typeKey], options) : !isTypeRef && isKeyRef ? Computed2("Pick", [type, typeKey], options) : isTypeRef && !isKeyRef ? Computed2("Pick", [type, typeKey], options) : CreateType2({ ...PickResolve2(type, propertyKeys), ...options });
}

// node_modules/@sinclair/typebox/build/esm/type/pick/pick-from-mapped-key.mjs
function FromPropertyKey6(type, key, options) {
  return {
    [key]: Pick2(type, [key], Clone2(options))
  };
}
function FromPropertyKeys6(type, propertyKeys, options) {
  return propertyKeys.reduce((result, leftKey) => {
    return { ...result, ...FromPropertyKey6(type, leftKey, options) };
  }, {});
}
function FromMappedKey8(type, mappedKey, options) {
  return FromPropertyKeys6(type, mappedKey.keys, options);
}
function PickFromMappedKey2(type, mappedKey, options) {
  const properties = FromMappedKey8(type, mappedKey, options);
  return MappedResult2(properties);
}

// node_modules/@sinclair/typebox/build/esm/type/partial/partial-from-mapped-result.mjs
init_process_shim();

// node_modules/@sinclair/typebox/build/esm/type/partial/partial.mjs
init_process_shim();
function FromComputed8(target, parameters) {
  return Computed2("Partial", [Computed2(target, parameters)]);
}
function FromRef7($ref) {
  return Computed2("Partial", [Ref2($ref)]);
}
function FromProperties35(properties) {
  const partialProperties = {};
  for (const K2 of globalThis.Object.getOwnPropertyNames(properties))
    partialProperties[K2] = Optional2(properties[K2]);
  return partialProperties;
}
function FromObject12(type, properties) {
  const options = Discard2(type, [TransformKind2, "$id", "required", "properties"]);
  const mappedProperties = FromProperties35(properties);
  return Object3(mappedProperties, options);
}
function FromRest13(types2) {
  return types2.map((type) => PartialResolve2(type));
}
function PartialResolve2(type) {
  return (
    // Mappable
    IsComputed3(type) ? FromComputed8(type.target, type.parameters) : IsRef3(type) ? FromRef7(type.$ref) : IsIntersect3(type) ? Intersect2(FromRest13(type.allOf)) : IsUnion3(type) ? Union2(FromRest13(type.anyOf)) : IsObject7(type) ? FromObject12(type, type.properties) : (
      // Intrinsic
      IsBigInt5(type) ? type : IsBoolean5(type) ? type : IsInteger3(type) ? type : IsLiteral3(type) ? type : IsNull5(type) ? type : IsNumber7(type) ? type : IsString5(type) ? type : IsSymbol5(type) ? type : IsUndefined7(type) ? type : (
        // Passthrough
        Object3({})
      )
    )
  );
}
function Partial2(type, options) {
  if (IsMappedResult3(type)) {
    return PartialFromMappedResult2(type, options);
  } else {
    return CreateType2({ ...PartialResolve2(type), ...options });
  }
}

// node_modules/@sinclair/typebox/build/esm/type/partial/partial-from-mapped-result.mjs
function FromProperties36(K2, options) {
  const Acc = {};
  for (const K22 of globalThis.Object.getOwnPropertyNames(K2))
    Acc[K22] = Partial2(K2[K22], Clone2(options));
  return Acc;
}
function FromMappedResult23(R3, options) {
  return FromProperties36(R3.properties, options);
}
function PartialFromMappedResult2(R3, options) {
  const P3 = FromMappedResult23(R3, options);
  return MappedResult2(P3);
}

// node_modules/@sinclair/typebox/build/esm/type/required/required-from-mapped-result.mjs
init_process_shim();

// node_modules/@sinclair/typebox/build/esm/type/required/required.mjs
init_process_shim();
function FromComputed9(target, parameters) {
  return Computed2("Required", [Computed2(target, parameters)]);
}
function FromRef8($ref) {
  return Computed2("Required", [Ref2($ref)]);
}
function FromProperties37(properties) {
  const requiredProperties = {};
  for (const K2 of globalThis.Object.getOwnPropertyNames(properties))
    requiredProperties[K2] = Discard2(properties[K2], [OptionalKind2]);
  return requiredProperties;
}
function FromObject13(type, properties) {
  const options = Discard2(type, [TransformKind2, "$id", "required", "properties"]);
  const mappedProperties = FromProperties37(properties);
  return Object3(mappedProperties, options);
}
function FromRest14(types2) {
  return types2.map((type) => RequiredResolve2(type));
}
function RequiredResolve2(type) {
  return (
    // Mappable
    IsComputed3(type) ? FromComputed9(type.target, type.parameters) : IsRef3(type) ? FromRef8(type.$ref) : IsIntersect3(type) ? Intersect2(FromRest14(type.allOf)) : IsUnion3(type) ? Union2(FromRest14(type.anyOf)) : IsObject7(type) ? FromObject13(type, type.properties) : (
      // Intrinsic
      IsBigInt5(type) ? type : IsBoolean5(type) ? type : IsInteger3(type) ? type : IsLiteral3(type) ? type : IsNull5(type) ? type : IsNumber7(type) ? type : IsString5(type) ? type : IsSymbol5(type) ? type : IsUndefined7(type) ? type : (
        // Passthrough
        Object3({})
      )
    )
  );
}
function Required2(type, options) {
  if (IsMappedResult3(type)) {
    return RequiredFromMappedResult2(type, options);
  } else {
    return CreateType2({ ...RequiredResolve2(type), ...options });
  }
}

// node_modules/@sinclair/typebox/build/esm/type/required/required-from-mapped-result.mjs
function FromProperties38(P3, options) {
  const Acc = {};
  for (const K2 of globalThis.Object.getOwnPropertyNames(P3))
    Acc[K2] = Required2(P3[K2], options);
  return Acc;
}
function FromMappedResult24(R3, options) {
  return FromProperties38(R3.properties, options);
}
function RequiredFromMappedResult2(R3, options) {
  const P3 = FromMappedResult24(R3, options);
  return MappedResult2(P3);
}

// node_modules/@sinclair/typebox/build/esm/type/module/compute.mjs
function DereferenceParameters2(moduleProperties, types2) {
  return types2.map((type) => {
    return IsRef3(type) ? Dereference2(moduleProperties, type.$ref) : FromType4(moduleProperties, type);
  });
}
function Dereference2(moduleProperties, ref) {
  return ref in moduleProperties ? IsRef3(moduleProperties[ref]) ? Dereference2(moduleProperties, moduleProperties[ref].$ref) : FromType4(moduleProperties, moduleProperties[ref]) : Never2();
}
function FromAwaited2(parameters) {
  return Awaited2(parameters[0]);
}
function FromIndex2(parameters) {
  return Index2(parameters[0], parameters[1]);
}
function FromKeyOf2(parameters) {
  return KeyOf2(parameters[0]);
}
function FromPartial2(parameters) {
  return Partial2(parameters[0]);
}
function FromOmit2(parameters) {
  return Omit2(parameters[0], parameters[1]);
}
function FromPick2(parameters) {
  return Pick2(parameters[0], parameters[1]);
}
function FromRequired2(parameters) {
  return Required2(parameters[0]);
}
function FromComputed10(moduleProperties, target, parameters) {
  const dereferenced = DereferenceParameters2(moduleProperties, parameters);
  return target === "Awaited" ? FromAwaited2(dereferenced) : target === "Index" ? FromIndex2(dereferenced) : target === "KeyOf" ? FromKeyOf2(dereferenced) : target === "Partial" ? FromPartial2(dereferenced) : target === "Omit" ? FromOmit2(dereferenced) : target === "Pick" ? FromPick2(dereferenced) : target === "Required" ? FromRequired2(dereferenced) : Never2();
}
function FromArray12(moduleProperties, type) {
  return Array3(FromType4(moduleProperties, type));
}
function FromAsyncIterator6(moduleProperties, type) {
  return AsyncIterator3(FromType4(moduleProperties, type));
}
function FromConstructor6(moduleProperties, parameters, instanceType) {
  return Constructor2(FromTypes4(moduleProperties, parameters), FromType4(moduleProperties, instanceType));
}
function FromFunction6(moduleProperties, parameters, returnType) {
  return Function3(FromTypes4(moduleProperties, parameters), FromType4(moduleProperties, returnType));
}
function FromIntersect16(moduleProperties, types2) {
  return Intersect2(FromTypes4(moduleProperties, types2));
}
function FromIterator6(moduleProperties, type) {
  return Iterator2(FromType4(moduleProperties, type));
}
function FromObject14(moduleProperties, properties) {
  return Object3(globalThis.Object.keys(properties).reduce((result, key) => {
    return { ...result, [key]: FromType4(moduleProperties, properties[key]) };
  }, {}));
}
function FromRecord6(moduleProperties, type) {
  const [value, pattern] = [FromType4(moduleProperties, RecordValue4(type)), RecordPattern2(type)];
  const result = CloneType2(type);
  result.patternProperties[pattern] = value;
  return result;
}
function FromTransform2(moduleProperties, transform) {
  return IsRef3(transform) ? { ...Dereference2(moduleProperties, transform.$ref), [TransformKind2]: transform[TransformKind2] } : transform;
}
function FromTuple10(moduleProperties, types2) {
  return Tuple2(FromTypes4(moduleProperties, types2));
}
function FromUnion20(moduleProperties, types2) {
  return Union2(FromTypes4(moduleProperties, types2));
}
function FromTypes4(moduleProperties, types2) {
  return types2.map((type) => FromType4(moduleProperties, type));
}
function FromType4(moduleProperties, type) {
  return (
    // Modifiers
    IsOptional3(type) ? CreateType2(FromType4(moduleProperties, Discard2(type, [OptionalKind2])), type) : IsReadonly3(type) ? CreateType2(FromType4(moduleProperties, Discard2(type, [ReadonlyKind2])), type) : (
      // Transform
      IsTransform3(type) ? CreateType2(FromTransform2(moduleProperties, type), type) : (
        // Types
        IsArray7(type) ? CreateType2(FromArray12(moduleProperties, type.items), type) : IsAsyncIterator5(type) ? CreateType2(FromAsyncIterator6(moduleProperties, type.items), type) : IsComputed3(type) ? CreateType2(FromComputed10(moduleProperties, type.target, type.parameters)) : IsConstructor3(type) ? CreateType2(FromConstructor6(moduleProperties, type.parameters, type.returns), type) : IsFunction5(type) ? CreateType2(FromFunction6(moduleProperties, type.parameters, type.returns), type) : IsIntersect3(type) ? CreateType2(FromIntersect16(moduleProperties, type.allOf), type) : IsIterator5(type) ? CreateType2(FromIterator6(moduleProperties, type.items), type) : IsObject7(type) ? CreateType2(FromObject14(moduleProperties, type.properties), type) : IsRecord3(type) ? CreateType2(FromRecord6(moduleProperties, type)) : IsTuple3(type) ? CreateType2(FromTuple10(moduleProperties, type.items || []), type) : IsUnion3(type) ? CreateType2(FromUnion20(moduleProperties, type.anyOf), type) : type
      )
    )
  );
}
function ComputeType2(moduleProperties, key) {
  return key in moduleProperties ? FromType4(moduleProperties, moduleProperties[key]) : Never2();
}
function ComputeModuleProperties2(moduleProperties) {
  return globalThis.Object.getOwnPropertyNames(moduleProperties).reduce((result, key) => {
    return { ...result, [key]: ComputeType2(moduleProperties, key) };
  }, {});
}

// node_modules/@sinclair/typebox/build/esm/type/module/module.mjs
var TModule2 = class {
  constructor($defs) {
    const computed = ComputeModuleProperties2($defs);
    const identified = this.WithIdentifiers(computed);
    this.$defs = identified;
  }
  /** `[Json]` Imports a Type by Key. */
  Import(key, options) {
    const $defs = { ...this.$defs, [key]: CreateType2(this.$defs[key], options) };
    return CreateType2({ [Kind2]: "Import", $defs, $ref: key });
  }
  // prettier-ignore
  WithIdentifiers($defs) {
    return globalThis.Object.getOwnPropertyNames($defs).reduce((result, key) => {
      return { ...result, [key]: { ...$defs[key], $id: key } };
    }, {});
  }
};
function Module2(properties) {
  return new TModule2(properties);
}

// node_modules/@sinclair/typebox/build/esm/type/not/not.mjs
init_process_shim();
function Not2(type, options) {
  return CreateType2({ [Kind2]: "Not", not: type }, options);
}

// node_modules/@sinclair/typebox/build/esm/type/parameters/parameters.mjs
init_process_shim();
function Parameters2(schema, options) {
  return IsFunction5(schema) ? Tuple2(schema.parameters, options) : Never2();
}

// node_modules/@sinclair/typebox/build/esm/type/recursive/recursive.mjs
init_process_shim();
var Ordinal2 = 0;
function Recursive2(callback, options = {}) {
  if (IsUndefined5(options.$id))
    options.$id = `T${Ordinal2++}`;
  const thisType = CloneType2(callback({ [Kind2]: "This", $ref: `${options.$id}` }));
  thisType.$id = options.$id;
  return CreateType2({ [Hint2]: "Recursive", ...thisType }, options);
}

// node_modules/@sinclair/typebox/build/esm/type/regexp/regexp.mjs
init_process_shim();
function RegExp3(unresolved, options) {
  const expr = IsString4(unresolved) ? new globalThis.RegExp(unresolved) : unresolved;
  return CreateType2({ [Kind2]: "RegExp", type: "RegExp", source: expr.source, flags: expr.flags }, options);
}

// node_modules/@sinclair/typebox/build/esm/type/rest/rest.mjs
init_process_shim();
function RestResolve2(T3) {
  return IsIntersect3(T3) ? T3.allOf : IsUnion3(T3) ? T3.anyOf : IsTuple3(T3) ? T3.items ?? [] : [];
}
function Rest2(T3) {
  return RestResolve2(T3);
}

// node_modules/@sinclair/typebox/build/esm/type/return-type/return-type.mjs
init_process_shim();
function ReturnType2(schema, options) {
  return IsFunction5(schema) ? CreateType2(schema.returns, options) : Never2(options);
}

// node_modules/@sinclair/typebox/build/esm/type/transform/transform.mjs
init_process_shim();
var TransformDecodeBuilder2 = class {
  constructor(schema) {
    this.schema = schema;
  }
  Decode(decode2) {
    return new TransformEncodeBuilder2(this.schema, decode2);
  }
};
var TransformEncodeBuilder2 = class {
  constructor(schema, decode2) {
    this.schema = schema;
    this.decode = decode2;
  }
  EncodeTransform(encode2, schema) {
    const Encode = (value) => schema[TransformKind2].Encode(encode2(value));
    const Decode = (value) => this.decode(schema[TransformKind2].Decode(value));
    const Codec = { Encode, Decode };
    return { ...schema, [TransformKind2]: Codec };
  }
  EncodeSchema(encode2, schema) {
    const Codec = { Decode: this.decode, Encode: encode2 };
    return { ...schema, [TransformKind2]: Codec };
  }
  Encode(encode2) {
    return IsTransform3(this.schema) ? this.EncodeTransform(encode2, this.schema) : this.EncodeSchema(encode2, this.schema);
  }
};
function Transform2(schema) {
  return new TransformDecodeBuilder2(schema);
}

// node_modules/@sinclair/typebox/build/esm/type/unsafe/unsafe.mjs
init_process_shim();
function Unsafe2(options = {}) {
  return CreateType2({ [Kind2]: options[Kind2] ?? "Unsafe" }, options);
}

// node_modules/@sinclair/typebox/build/esm/type/void/void.mjs
init_process_shim();
function Void2(options) {
  return CreateType2({ [Kind2]: "Void", type: "void" }, options);
}

// node_modules/@sinclair/typebox/build/esm/type/type/index.mjs
init_process_shim();

// node_modules/@sinclair/typebox/build/esm/type/type/type.mjs
var type_exports4 = {};
__export(type_exports4, {
  Any: () => Any2,
  Argument: () => Argument2,
  Array: () => Array3,
  AsyncIterator: () => AsyncIterator3,
  Awaited: () => Awaited2,
  BigInt: () => BigInt3,
  Boolean: () => Boolean3,
  Capitalize: () => Capitalize2,
  Composite: () => Composite2,
  Const: () => Const2,
  Constructor: () => Constructor2,
  ConstructorParameters: () => ConstructorParameters2,
  Date: () => Date3,
  Enum: () => Enum2,
  Exclude: () => Exclude2,
  Extends: () => Extends2,
  Extract: () => Extract2,
  Function: () => Function3,
  Index: () => Index2,
  InstanceType: () => InstanceType2,
  Instantiate: () => Instantiate2,
  Integer: () => Integer2,
  Intersect: () => Intersect2,
  Iterator: () => Iterator2,
  KeyOf: () => KeyOf2,
  Literal: () => Literal2,
  Lowercase: () => Lowercase2,
  Mapped: () => Mapped2,
  Module: () => Module2,
  Never: () => Never2,
  Not: () => Not2,
  Null: () => Null2,
  Number: () => Number3,
  Object: () => Object3,
  Omit: () => Omit2,
  Optional: () => Optional2,
  Parameters: () => Parameters2,
  Partial: () => Partial2,
  Pick: () => Pick2,
  Promise: () => Promise3,
  Readonly: () => Readonly2,
  ReadonlyOptional: () => ReadonlyOptional2,
  Record: () => Record2,
  Recursive: () => Recursive2,
  Ref: () => Ref2,
  RegExp: () => RegExp3,
  Required: () => Required2,
  Rest: () => Rest2,
  ReturnType: () => ReturnType2,
  String: () => String3,
  Symbol: () => Symbol3,
  TemplateLiteral: () => TemplateLiteral2,
  Transform: () => Transform2,
  Tuple: () => Tuple2,
  Uint8Array: () => Uint8Array3,
  Uncapitalize: () => Uncapitalize2,
  Undefined: () => Undefined2,
  Union: () => Union2,
  Unknown: () => Unknown2,
  Unsafe: () => Unsafe2,
  Uppercase: () => Uppercase2,
  Void: () => Void2
});
init_process_shim();

// node_modules/@sinclair/typebox/build/esm/type/type/index.mjs
var Type3 = type_exports4;

// src/prompts/prompts.ts
init_process_shim();
var ASK_USER_WHICH_ELEMENT_TOOL_DESCRIPTION = `# Ask User Which Element

Ask user to visually select a DOM element on the page via interactive picker.

## When to Use
- User says "this element", "that button", "that table" without specifics
- Need visual confirmation of target element for scraping

## Returns
CSS selector, XPath, HTML structure, bounding box, computed styles, attributes, text content.

## Critical
Use the returned selector in browserjs() code within the repl tool to interact with the element.
`;

// src/utils/i18n-extension.ts
init_process_shim();
var sitegeistTranslations = {
  en: {
    "Permission request failed": "Permission request failed",
    "JavaScript Execution Permission Required": "JavaScript Execution Permission Required",
    "This extension needs permission to execute JavaScript code on web pages": "This extension needs permission to execute JavaScript code on web pages",
    "The JavaScript REPL tool allows the AI to read and interact with web pages on your behalf. This requires the userScripts permission to execute code safely and securely.": "The JavaScript REPL tool allows the AI to read and interact with web pages on your behalf. This requires the userScripts permission to execute code safely and securely.",
    "The AI can read and modify web page content when you ask it to": "The AI can read and modify web page content when you ask it to",
    "Code runs in an isolated environment with security safeguards": "Code runs in an isolated environment with security safeguards",
    "Network access is blocked to prevent data exfiltration": "Network access is blocked to prevent data exfiltration",
    "You can revoke this permission at any time in browser settings": "You can revoke this permission at any time in browser settings",
    "Writing JavaScript code...": "Writing JavaScript code...",
    "Execute JavaScript": "Execute JavaScript",
    "Preparing JavaScript...": "Preparing JavaScript...",
    "Getting skill": "Getting skill",
    "Got skill": "Got skill",
    "Listing skills": "Listing skills",
    "Creating skill": "Creating skill",
    "Created skill": "Created skill",
    "Updating skill": "Updating skill",
    "Updated skill": "Updated skill",
    "Rewriting skill": "Rewriting skill",
    "Rewritten skill": "Patched skill",
    "Deleting skill": "Deleting skill",
    "Processing skill...": "Processing skill...",
    "No skills found": "No skills found",
    "Skills for domain": "Skills for domain",
    "Deleted skill": "Deleted skill",
    Examples: "Examples",
    Library: "Library",
    "Command failed:": "Command failed:",
    "Why is this needed?": "Why is this needed?",
    "What this means:": "What this means:",
    "Continue Anyway": "Continue Anyway",
    "Requesting...": "Requesting...",
    "Grant Permission": "Grant Permission",
    "Navigating to": "Navigating to",
    "Click to open": "Click to open",
    "Waiting...": "Waiting...",
    Current: "Current",
    Locked: "Locked",
    "Export failed. Check console for details.": "Export failed. Check console for details.",
    "Invalid import file format": "Invalid import file format",
    "Found {count} duplicate sessions. Click OK to overwrite, Cancel to skip duplicates.": "Found {count} duplicate sessions. Click OK to overwrite, Cancel to skip duplicates.",
    "Imported {imported} sessions, skipped {skipped} duplicates": "Imported {imported} sessions, skipped {skipped} duplicates",
    "Imported {count} sessions": "Imported {count} sessions",
    "Import failed. Check console for details.": "Import failed. Check console for details.",
    Import: "Import",
    "Export All": "Export All",
    Export: "Export",
    "No sessions older than {days} days": "No sessions older than {days} days",
    "Delete {count} sessions older than {days} days?": "Delete {count} sessions older than {days} days?",
    "Failed to delete sessions. Check console for details.": "Failed to delete sessions. Check console for details.",
    "Delete Old": "Delete",
    "All sessions": "All sessions",
    "No sessions to delete": "No sessions to delete",
    "Delete ALL {count} sessions? This cannot be undone!": "Delete ALL {count} sessions? This cannot be undone!",
    "Older than 7 days": "Older than 7 days",
    "Older than 30 days": "Older than 30 days",
    "Older than 90 days": "Older than 90 days",
    "Search sessions...": "Search sessions...",
    "Total: {count} sessions \xB7 {messages} messages \xB7 ${cost}": "Total: {count} sessions \xB7 {messages} messages \xB7 ${cost}",
    "Open tabs": "Open tabs",
    "Waiting for selection": "Waiting for selection",
    "Preparing element selector...": "Preparing element selector...",
    About: "About",
    "AI-powered browser extension for web navigation and interaction": "AI-powered browser extension for web navigation and interaction",
    "Version:": "Version:",
    Website: "Website",
    Imprint: "Imprint",
    Privacy: "Privacy",
    "Checking for updates...": "Checking for updates...",
    "Update Available": "Update Available",
    "A new version ({version}) is available": "A new version ({version}) is available",
    Update: "Update",
    "You're up to date": "You're up to date",
    "Update Required": "Update Required",
    "A new version ({version}) is available. Please update to continue.": "A new version ({version}) is available. Please update to continue.",
    "Update Now": "Update Now"
  },
  de: {
    "Permission request failed": "Berechtigungsanfrage fehlgeschlagen",
    "JavaScript Execution Permission Required": "JavaScript-Ausf\xFChrungsberechtigung erforderlich",
    "This extension needs permission to execute JavaScript code on web pages": "Diese Erweiterung ben\xF6tigt die Berechtigung, JavaScript-Code auf Webseiten auszuf\xFChren",
    "The JavaScript REPL tool allows the AI to read and interact with web pages on your behalf. This requires the userScripts permission to execute code safely and securely.": "Das JavaScript-REPL-Tool erm\xF6glicht es der KI, Webseiten in Ihrem Auftrag zu lesen und damit zu interagieren. Dies erfordert die userScripts-Berechtigung, um Code sicher auszuf\xFChren.",
    "The AI can read and modify web page content when you ask it to": "Die KI kann Webseiteninhalte lesen und \xE4ndern, wenn Sie es verlangen",
    "Code runs in an isolated environment with security safeguards": "Code wird in einer isolierten Umgebung mit Sicherheitsvorkehrungen ausgef\xFChrt",
    "Network access is blocked to prevent data exfiltration": "Netzwerkzugriff ist blockiert, um Datenexfiltration zu verhindern",
    "You can revoke this permission at any time in browser settings": "Sie k\xF6nnen diese Berechtigung jederzeit in den Browsereinstellungen widerrufen",
    "Writing JavaScript code...": "Schreibe JavaScript-Code...",
    "Execute JavaScript": "F\xFChre JavaScript aus",
    "Preparing JavaScript...": "Bereite JavaScript vor...",
    "Getting skill": "Hole Skill",
    "Got skill": "Skill erhalten",
    "Listing skills": "Liste Skills auf",
    "Creating skill": "Erstelle Skill",
    "Created skill": "Skill erstellt",
    "Updating skill": "Aktualisiere Skill",
    "Updated skill": "Skill aktualisiert",
    "Rewriting skill": "Patche Skill",
    "Rewritten skill": "Skill gepatcht",
    "Deleting skill": "L\xF6sche Skill",
    "Processing skill...": "Verarbeite Skill...",
    "No skills found": "Keine Skills gefunden",
    "Skills for domain": "Skills f\xFCr Domain",
    "Deleted skill": "Skill gel\xF6scht",
    Examples: "Beispiele",
    Library: "Bibliothek",
    "Command failed:": "Befehl fehlgeschlagen:",
    "Why is this needed?": "Warum ist das notwendig?",
    "What this means:": "Was das bedeutet:",
    "Continue Anyway": "Trotzdem fortfahren",
    "Requesting...": "Anfrage l\xE4uft...",
    "Grant Permission": "Berechtigung erteilen",
    "Navigating to": "Navigiere zu",
    "Click to open": "Klicken zum \xD6ffnen",
    "Waiting...": "Warte...",
    Current: "Aktuell",
    Locked: "Gesperrt",
    "Export failed. Check console for details.": "Export fehlgeschlagen. Pr\xFCfen Sie die Konsole f\xFCr Details.",
    "Invalid import file format": "Ung\xFCltiges Import-Dateiformat",
    "Found {count} duplicate sessions. Click OK to overwrite, Cancel to skip duplicates.": "{count} doppelte Sitzungen gefunden. OK zum \xDCberschreiben, Abbrechen zum \xDCberspringen.",
    "Imported {imported} sessions, skipped {skipped} duplicates": "{imported} Sitzungen importiert, {skipped} Duplikate \xFCbersprungen",
    "Imported {count} sessions": "{count} Sitzungen importiert",
    "Import failed. Check console for details.": "Import fehlgeschlagen. Pr\xFCfen Sie die Konsole f\xFCr Details.",
    Import: "Importieren",
    "Export All": "Alle exportieren",
    Export: "Exportieren",
    "No sessions older than {days} days": "Keine Sitzungen \xE4lter als {days} Tage",
    "Delete {count} sessions older than {days} days?": "{count} Sitzungen \xE4lter als {days} Tage l\xF6schen?",
    "Failed to delete sessions. Check console for details.": "L\xF6schen fehlgeschlagen. Pr\xFCfen Sie die Konsole f\xFCr Details.",
    "Delete Old": "L\xF6schen",
    "All sessions": "Alle Sitzungen",
    "No sessions to delete": "Keine Sitzungen zum L\xF6schen",
    "Delete ALL {count} sessions? This cannot be undone!": "ALLE {count} Sitzungen l\xF6schen? Dies kann nicht r\xFCckg\xE4ngig gemacht werden!",
    "Older than 7 days": "\xC4lter als 7 Tage",
    "Older than 30 days": "\xC4lter als 30 Tage",
    "Older than 90 days": "\xC4lter als 90 Tage",
    "Search sessions...": "Sitzungen durchsuchen...",
    "Total: {count} sessions \xB7 {messages} messages \xB7 ${cost}": "Gesamt: {count} Sitzungen \xB7 {messages} Nachrichten \xB7 ${cost}",
    "Open tabs": "Offene Tabs",
    "Waiting for selection": "Warte auf Auswahl",
    "Preparing element selector...": "Bereite Element-Auswahl vor...",
    About: "\xDCber",
    "AI-powered browser extension for web navigation and interaction": "KI-gest\xFCtzte Browser-Erweiterung f\xFCr Webnavigation und -interaktion",
    "Version:": "Version:",
    Website: "Webseite",
    Imprint: "Impressum",
    Privacy: "Datenschutz",
    "Checking for updates...": "Suche nach Updates...",
    "Update Available": "Update verf\xFCgbar",
    "A new version ({version}) is available": "Eine neue Version ({version}) ist verf\xFCgbar",
    Update: "Aktualisieren",
    "You're up to date": "Sie sind auf dem neuesten Stand",
    "Update Required": "Update erforderlich",
    "A new version ({version}) is available. Please update to continue.": "Eine neue Version ({version}) ist verf\xFCgbar. Bitte aktualisieren Sie, um fortzufahren.",
    "Update Now": "Jetzt aktualisieren"
  }
};
var mergedTranslations = {
  en: { ...translations2.en, ...sitegeistTranslations.en },
  de: { ...translations2.de, ...sitegeistTranslations.de }
};
setTranslations(mergedTranslations);

// src/tools/ask-user-which-element.ts
var selectElementSchema = Type3.Object({
  message: Type3.Optional(
    Type3.String({
      description: "Optional message to show the user while they select the element (e.g., 'Please click the table you want to extract')"
    })
  )
});
async function createElementPickerOverlay(message) {
  if (window.__sitegeistElementPicker) {
    throw new Error("Element picker is already active");
  }
  window.__sitegeistElementPicker = true;
  return new Promise((resolve) => {
    const overlay = document.createElement("div");
    overlay.id = "sitegeist-element-picker";
    overlay.style.cssText = `
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		z-index: 2147483647;
		pointer-events: none;
	`;
    const highlight = document.createElement("div");
    highlight.style.cssText = `
		position: absolute;
		pointer-events: none;
		border: 2px solid #3b82f6;
		background: rgba(59, 130, 246, 0.1);
		transition: all 0.1s ease;
		box-shadow: 0 0 0 1px rgba(59, 130, 246, 0.5);
	`;
    overlay.appendChild(highlight);
    const tooltip = document.createElement("div");
    tooltip.style.cssText = `
		position: absolute;
		pointer-events: none;
		background: #1f2937;
		color: white;
		padding: 8px 12px;
		border-radius: 6px;
		font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
		font-size: 12px;
		line-height: 1.4;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
		max-width: 300px;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	`;
    overlay.appendChild(tooltip);
    const banner = document.createElement("div");
    banner.style.cssText = `
		position: fixed;
		top: 20px;
		left: 50%;
		transform: translateX(-50%);
		background: #1f2937;
		color: white;
		padding: 12px 24px;
		border-radius: 8px;
		font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
		font-size: 14px;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
		pointer-events: auto;
		z-index: 2147483647;
		display: flex;
		align-items: center;
		gap: 12px;
	`;
    const bannerText = document.createElement("span");
    bannerText.textContent = message || "Click element to select \u2022 \u2191\u2193 to change depth";
    banner.appendChild(bannerText);
    const cancelButton = document.createElement("button");
    cancelButton.textContent = "Cancel (ESC)";
    cancelButton.style.cssText = `
		background: #374151;
		border: none;
		color: white;
		padding: 4px 12px;
		border-radius: 4px;
		font-size: 12px;
		cursor: pointer;
		transition: background 0.2s;
	`;
    cancelButton.addEventListener("mouseenter", () => {
      cancelButton.style.background = "#4b5563";
    });
    cancelButton.addEventListener("mouseleave", () => {
      cancelButton.style.background = "#374151";
    });
    banner.appendChild(cancelButton);
    document.body.appendChild(banner);
    document.body.appendChild(overlay);
    let isSelecting = true;
    let currentElement = null;
    let ancestorIndex = 0;
    function generateSelector(element) {
      if (element.id) {
        return `#${CSS.escape(element.id)}`;
      }
      const path6 = [];
      let current2 = element;
      while (current2 && current2 !== document.body) {
        let selector = current2.tagName.toLowerCase();
        if (current2.className && typeof current2.className === "string") {
          const classes = current2.className.split(/\s+/).filter((c6) => c6 && !c6.startsWith("sitegeist-"));
          if (classes.length > 0) {
            selector += `.${classes.map((c6) => CSS.escape(c6)).join(".")}`;
          }
        }
        if (current2.parentElement) {
          const siblings = Array.from(current2.parentElement.children).filter(
            (el) => el.tagName === current2.tagName
          );
          if (siblings.length > 1) {
            const index = siblings.indexOf(current2) + 1;
            selector += `:nth-child(${index})`;
          }
        }
        path6.unshift(selector);
        current2 = current2.parentElement;
      }
      return path6.join(" > ");
    }
    function generateXPath(element) {
      if (element.id) {
        return `//*[@id="${element.id}"]`;
      }
      const path6 = [];
      let current2 = element;
      while (current2 && current2 !== document.documentElement) {
        let index = 0;
        let sibling = current2.previousElementSibling;
        while (sibling) {
          if (sibling.tagName === current2.tagName) {
            index++;
          }
          sibling = sibling.previousElementSibling;
        }
        const tagName = current2.tagName.toLowerCase();
        const position = index > 0 ? `[${index + 1}]` : "";
        path6.unshift(`${tagName}${position}`);
        current2 = current2.parentElement;
      }
      return `/${path6.join("/")}`;
    }
    function getElementInfo(element) {
      const rect = element.getBoundingClientRect();
      const styles2 = window.getComputedStyle(element);
      const computedStyles = {
        display: styles2.display,
        position: styles2.position,
        width: styles2.width,
        height: styles2.height,
        color: styles2.color,
        backgroundColor: styles2.backgroundColor,
        fontSize: styles2.fontSize,
        fontWeight: styles2.fontWeight
      };
      const attributes = {};
      for (const attr of element.attributes) {
        attributes[attr.name] = attr.value;
      }
      const parentChain = [];
      let current2 = element;
      while (current2 && current2 !== document.documentElement) {
        parentChain.unshift(current2.tagName.toLowerCase());
        current2 = current2.parentElement;
      }
      const text3 = element.textContent?.trim().substring(0, 500) || "";
      const html = element.outerHTML.substring(0, 1e3);
      return {
        selector: generateSelector(element),
        xpath: generateXPath(element),
        html,
        tagName: element.tagName.toLowerCase(),
        attributes,
        text: text3,
        boundingBox: {
          x: rect.x + window.scrollX,
          y: rect.y + window.scrollY,
          width: rect.width,
          height: rect.height
        },
        computedStyles,
        parentChain
      };
    }
    function updateHighlight(element) {
      const rect = element.getBoundingClientRect();
      highlight.style.top = `${rect.top}px`;
      highlight.style.left = `${rect.left}px`;
      highlight.style.width = `${rect.width}px`;
      highlight.style.height = `${rect.height}px`;
      const tagName = element.tagName.toLowerCase();
      const id = element.id ? `#${element.id}` : "";
      const className = element.className ? `.${element.className.toString().split(/\s+/).join(".")}` : "";
      tooltip.textContent = `${tagName}${id}${className}`;
      const tooltipRect = tooltip.getBoundingClientRect();
      if (rect.top > tooltipRect.height + 10) {
        tooltip.style.top = `${rect.top - tooltipRect.height - 5}px`;
      } else {
        tooltip.style.top = `${rect.bottom + 5}px`;
      }
      tooltip.style.left = `${Math.min(rect.left, window.innerWidth - tooltipRect.width - 10)}px`;
    }
    function getAncestors(element) {
      const ancestors = [];
      let current2 = element;
      while (current2 && current2 !== document.body && current2 !== document.documentElement) {
        ancestors.push(current2);
        current2 = current2.parentElement;
      }
      return ancestors;
    }
    function getAllElementsAtPoint(x2, y4) {
      const elements = [];
      const elementsToHide = [];
      const seenElements = /* @__PURE__ */ new Set();
      const MAX_DEPTH = 50;
      let iterations = 0;
      try {
        let element = document.elementFromPoint(x2, y4);
        while (element && element !== document.documentElement && element !== document.body) {
          if (iterations++ > MAX_DEPTH) {
            console.warn("[select-element] Reached max depth, stopping element penetration");
            break;
          }
          if (element === overlay || overlay.contains(element) || element === banner || banner.contains(element)) {
            break;
          }
          if (seenElements.has(element)) {
            console.warn("[select-element] Already seen element, stopping to prevent loop");
            break;
          }
          seenElements.add(element);
          elements.push(element);
          if (element instanceof HTMLElement) {
            const original = element.style.pointerEvents;
            elementsToHide.push({ element, originalPointerEvents: original });
            element.style.pointerEvents = "none";
          }
          const nextElement = document.elementFromPoint(x2, y4);
          if (nextElement === element) {
            console.warn("[select-element] Got same element back, stopping");
            break;
          }
          element = nextElement;
        }
        return elements;
      } finally {
        for (const { element, originalPointerEvents } of elementsToHide) {
          element.style.pointerEvents = originalPointerEvents;
        }
      }
    }
    function handleMouseMove(e9) {
      if (!isSelecting) return;
      const elementsAtPoint = getAllElementsAtPoint(e9.clientX, e9.clientY);
      if (elementsAtPoint.length === 0) {
        return;
      }
      const element = elementsAtPoint[0];
      currentElement = element;
      ancestorIndex = 0;
      updateHighlight(element);
    }
    function handleClick(e9) {
      if (!isSelecting) return;
      if (e9.target === banner || banner.contains(e9.target)) {
        return;
      }
      e9.preventDefault();
      e9.stopPropagation();
      if (!currentElement) {
        const element = document.elementFromPoint(e9.clientX, e9.clientY);
        if (!element || element === overlay || overlay.contains(element) || element === banner || banner.contains(element)) {
          return;
        }
        currentElement = element;
      }
      const ancestors = getAncestors(currentElement);
      const selectedElement = ancestors[ancestorIndex] || currentElement;
      const elementInfo = getElementInfo(selectedElement);
      cleanup();
      resolve(elementInfo);
    }
    function cleanup() {
      isSelecting = false;
      document.removeEventListener("mousemove", handleMouseMove, true);
      document.removeEventListener("click", handleClick, true);
      document.removeEventListener("keydown", handleKeyDown, true);
      window.removeEventListener("sitegeist-element-cancel", handleCancel);
      overlay.remove();
      banner.remove();
      delete window.__sitegeistElementPicker;
    }
    function handleKeyDown(e9) {
      if (e9.key === "Escape") {
        e9.preventDefault();
        cleanup();
        resolve(null);
        return;
      }
      if (e9.key === "ArrowUp" || e9.key === "ArrowDown") {
        e9.preventDefault();
        if (!currentElement) return;
        const ancestors = getAncestors(currentElement);
        if (e9.key === "ArrowUp") {
          if (ancestorIndex < ancestors.length - 1) {
            ancestorIndex++;
            updateHighlight(ancestors[ancestorIndex]);
          }
        } else if (e9.key === "ArrowDown") {
          if (ancestorIndex > 0) {
            ancestorIndex--;
            updateHighlight(ancestors[ancestorIndex]);
          }
        }
      }
    }
    cancelButton.addEventListener("click", (e9) => {
      e9.stopPropagation();
      cleanup();
      resolve(null);
    });
    function handleCancel() {
      if (isSelecting) {
        cleanup();
        resolve(null);
      }
    }
    window.addEventListener("sitegeist-element-cancel", handleCancel, {
      once: true
    });
    document.addEventListener("mousemove", handleMouseMove, true);
    document.addEventListener("click", handleClick, true);
    document.addEventListener("keydown", handleKeyDown, true);
  });
}
var AskUserWhichElementTool = class {
  constructor() {
    this.label = "Ask User Which Element";
    this.name = "ask_user_which_element";
    this.description = ASK_USER_WHICH_ELEMENT_TOOL_DESCRIPTION;
    this.parameters = selectElementSchema;
  }
  async execute(_toolCallId, args, signal) {
    try {
      if (signal?.aborted) {
        throw new Error("Tool execution was aborted");
      }
      const [tab] = await chrome.tabs.query({
        active: true,
        currentWindow: true
      });
      if (!tab || !tab.id) {
        throw new Error("No active tab found");
      }
      if (tab.url?.startsWith("chrome://") || tab.url?.startsWith("chrome-extension://") || tab.url?.startsWith("moz-extension://") || tab.url?.startsWith("about:")) {
        throw new Error(`Cannot select elements on ${tab.url}. Extension pages and internal URLs are protected.`);
      }
      const scriptCode = `(${createElementPickerOverlay.toString()})(${JSON.stringify(args.message || "")})`;
      let results;
      try {
        if (chrome.userScripts && typeof chrome.userScripts.execute === "function") {
          const executePromise = chrome.userScripts.execute({
            target: { tabId: tab.id, allFrames: false },
            world: "USER_SCRIPT",
            injectImmediately: true,
            js: [{ code: scriptCode }]
          });
          if (signal) {
            const abortPromise = new Promise((_3, reject) => {
              if (signal.aborted) {
                reject(new Error("Aborted"));
              } else {
                signal.addEventListener("abort", () => {
                  const cleanupCode = `window.dispatchEvent(new CustomEvent("sitegeist-element-cancel"));`;
                  chrome.userScripts?.execute({
                    target: { tabId: tab.id, allFrames: false },
                    world: "USER_SCRIPT",
                    injectImmediately: true,
                    js: [{ code: cleanupCode }]
                  }).catch(() => {
                  });
                  reject(new Error("Aborted"));
                });
              }
            });
            results = await Promise.race([executePromise, abortPromise]);
          } else {
            results = await executePromise;
          }
        } else {
          throw new Error(
            "userScripts.execute() not available. This tool requires Chrome 138+ with User Scripts enabled."
          );
        }
        const result = results[0]?.result;
        if (!result) {
          throw new Error("Element selection was cancelled");
        }
        let output = `Element selected: <${result.tagName}>
`;
        output += `Selector: ${result.selector}
`;
        output += `XPath: ${result.xpath}
`;
        if (result.attributes.id) {
          output += `ID: ${result.attributes.id}
`;
        }
        if (result.attributes.class) {
          output += `Classes: ${result.attributes.class}
`;
        }
        if (result.text) {
          const displayText = result.text.length > 100 ? `${result.text.substring(0, 100)}...` : result.text;
          output += `Text: ${displayText}
`;
        }
        output += `Position: (${Math.round(result.boundingBox.x)}, ${Math.round(result.boundingBox.y)})
`;
        output += `Size: ${Math.round(result.boundingBox.width)}x${Math.round(result.boundingBox.height)}
`;
        return {
          content: [{ type: "text", text: output }],
          details: result
        };
      } catch (error) {
        const err = error;
        console.error("[select-element] Caught error, re-throwing:", err.message);
        throw err;
      }
    } catch (error) {
      const err = error;
      console.error("[select-element] Caught error, re-throwing:", err.message);
      throw err;
    }
  }
};
var askUserWhichElementTool = new AskUserWhichElementTool();
var selectElementRenderer = {
  render(params, result, isStreaming) {
    const state = result ? result.isError ? "error" : "complete" : params ? "inprogress" : "inprogress";
    const detailsContentRef = e5();
    const detailsChevronRef = e5();
    if (result && !result.isError && result.details) {
      const el = result.details;
      return {
        content: b2`
					<div>
						${renderCollapsibleHeader(
          state,
          MousePointer2,
          `Selected: <${el.tagName}>`,
          detailsContentRef,
          detailsChevronRef,
          false
        )}
						<div
							${n5(detailsContentRef)}
							class="max-h-0 overflow-hidden transition-all duration-300 space-y-3"
						>
							<!-- CSS Selector -->
							<div>
								<div class="text-xs text-muted-foreground mb-1">CSS Selector</div>
								<div class="font-mono text-xs bg-muted px-2 py-1 rounded">
									${el.selector}
								</div>
							</div>

							<!-- XPath -->
							<div>
								<div class="text-xs text-muted-foreground mb-1">XPath</div>
								<div
									class="font-mono text-xs bg-muted px-2 py-1 rounded break-all"
								>
									${el.xpath}
								</div>
							</div>

							<!-- Attributes -->
							${Object.keys(el.attributes).length > 0 ? b2`
										<div>
											<div class="text-xs text-muted-foreground mb-1">
												Attributes
											</div>
											<div class="text-xs space-y-1">
												${Object.entries(el.attributes).map(
          ([key, value]) => b2`
														<div class="flex gap-2">
															<span class="text-muted-foreground">${key}:</span>
															<span class="font-mono">${value}</span>
														</div>
													`
        )}
											</div>
										</div>
								  ` : ""}

							<!-- Text Content -->
							${el.text ? b2`
										<div>
											<div class="text-xs text-muted-foreground mb-1">
												Text Content
											</div>
											<div class="text-xs text-muted-foreground">
												${el.text.substring(0, 200)}${el.text.length > 200 ? "..." : ""}
											</div>
										</div>
								  ` : ""}

							<!-- Bounding Box -->
							<div>
								<div class="text-xs text-muted-foreground mb-1">
									Position & Size
								</div>
								<div class="text-xs space-y-1">
									<div>
										Position: (${Math.round(el.boundingBox.x)},
										${Math.round(el.boundingBox.y)})
									</div>
									<div>
										Size: ${Math.round(el.boundingBox.width)}x${Math.round(el.boundingBox.height)}
									</div>
								</div>
							</div>

							<!-- Computed Styles (selected ones) -->
							${Object.keys(el.computedStyles).length > 0 ? b2`
										<div>
											<div class="text-xs text-muted-foreground mb-1">
												Computed Styles
											</div>
											<div class="text-xs space-y-1">
												${Object.entries(el.computedStyles).map(
          ([key, value]) => b2`
														<div class="flex gap-2">
															<span class="text-muted-foreground">${key}:</span>
															<span class="font-mono">${value}</span>
														</div>
													`
        )}
											</div>
										</div>
								  ` : ""}

							<!-- Parent Chain -->
							${el.parentChain.length > 0 ? b2`
										<div>
											<div class="text-xs text-muted-foreground mb-1">
												Parent Chain
											</div>
											<div class="text-xs font-mono text-muted-foreground">
												${el.parentChain.join(" > ")}
											</div>
										</div>
								  ` : ""}
						</div>
					</div>
				`,
        isCustom: false
      };
    }
    if (result?.isError) {
      const message = params?.message || "Click an element to select it";
      return {
        content: renderHeader(state, MousePointer2, message),
        isCustom: false
      };
    }
    if (params || isStreaming) {
      const message = params?.message || "Click an element to select it";
      return {
        content: b2`
					<div class="my-2">
						<div
							class="inline-flex items-center gap-2 px-3 py-2 text-sm text-card-foreground bg-card border border-border rounded-lg max-w-full shadow-lg"
						>
							<div class="w-4 h-4 flex-shrink-0 flex items-center justify-center">
								${icon(LoaderCircle2, "sm", "animate-spin")}
							</div>
							<div class="w-4 h-4 flex-shrink-0 flex items-center justify-center">
								${icon(MousePointer2, "sm")}
							</div>
							<span class="truncate font-medium"
								>${i18n("Waiting for selection")}: ${message}</span
							>
						</div>
					</div>
				`,
        isCustom: true
      };
    }
    return {
      content: b2`
				<div class="my-2">
					<div
						class="inline-flex items-center gap-2 px-3 py-2 text-sm text-card-foreground bg-card border border-border rounded-lg max-w-full shadow-lg"
					>
						<div class="w-4 h-4 flex-shrink-0 flex items-center justify-center">
							${icon(LoaderCircle2, "sm", "animate-spin")}
						</div>
						<div class="w-4 h-4 flex-shrink-0 flex items-center justify-center">
							${icon(MousePointer2, "sm")}
						</div>
						<span class="truncate font-medium"
							>${i18n("Preparing element selector...")}</span
						>
					</div>
				</div>
			`,
      isCustom: true
    };
  }
};
registerToolRenderer(askUserWhichElementTool.name, selectElementRenderer);

// src/debug.ts
var models = [
  getModel("anthropic", "claude-sonnet-4-5-20250929"),
  getModel("openai", "gpt-5-codex"),
  getModel("google", "gemini-2.5-pro"),
  getModel("openrouter", "z-ai/glm-4.6")
];
var storage = new SitegeistAppStorage();
setAppStorage(storage);
var TEST_PROMPTS = [
  {
    name: "Multi-step calculation",
    steps: [
      "Calculate the sum of numbers from 1 to 100",
      "Now multiply that result by 3",
      "Create a bar chart showing the original sum and the multiplied value"
    ]
  },
  {
    name: "HTML artifact iteration",
    steps: [
      "Create an HTML artifact with a red background and 'Hello World' text",
      "Change the background to blue",
      "Add a button that shows an alert when clicked"
    ]
  },
  {
    name: "Data processing multi-step",
    steps: [
      "Generate an array of 20000 random numbers between 1 and 100. Calculate the mean, median, and standard deviation. Create a Chart.js visualization showing the distribution. Use a separate tool call for each step."
    ]
  },
  {
    name: "Data processing single step",
    steps: [
      "Generate an array of 20000 random numbers between 1 and 100. Calculate the mean, median, and standard deviation. Create a Chart.js visualization showing the distribution."
    ]
  },
  {
    name: "Web scraping workflow",
    steps: [
      "Search Google for 'JavaScript tutorials'",
      "Extract the first 3 result titles",
      "Write them to a tutorials.md artifact with proper markdown formatting"
    ]
  }
];
var renderDebugPage = async () => {
  const stored = await chrome.storage.local.get(["debuggerMode", "showJsonMode"]);
  let debuggerMode = stored.debuggerMode || false;
  let showJsonMode2 = stored.showJsonMode || false;
  const updateDebuggerMode = async (enabled) => {
    debuggerMode = enabled;
    await chrome.storage.local.set({ debuggerMode: enabled });
    renderDebugPage();
  };
  const updateShowJsonMode = async (enabled) => {
    showJsonMode2 = enabled;
    await chrome.storage.local.set({ showJsonMode: enabled });
    renderDebugPage();
  };
  const triggerSelectElement = async () => {
    try {
      const result = await askUserWhichElementTool.execute("debug-test", {});
      console.log("[debug] Select element result:", result);
      const text3 = result.content.find((c6) => c6.type === "text")?.text || "No output";
      alert(`Selected element:
${text3}`);
    } catch (error) {
      console.error("[debug] Select element error:", error);
      alert(`Error: ${error instanceof Error ? error.message : String(error)}`);
    }
  };
  const debugHtml = b2`
		<div class="w-full h-full flex flex-col bg-background text-foreground overflow-hidden">
			<!-- Header -->
			<div class="flex items-center justify-between gap-2 px-3 py-2 border-b border-border shrink-0">
				<div class="flex items-center gap-2">
					${Button({
    variant: "ghost",
    size: "sm",
    children: icon(ArrowLeft, "sm"),
    onClick: () => {
      window.location.href = "./sidepanel.html";
    },
    title: "Back to chat"
  })}
					<span class="text-sm font-semibold">Debug</span>
					${Button({
    variant: "ghost",
    size: "sm",
    children: b2`<span class="flex items-center gap-1.5">${icon(Sparkles2, "xs")} <span class="text-xs">Icons</span></span>`,
    onClick: () => {
      window.location.href = "./icons.html";
    },
    title: "Generate extension icons"
  })}
				</div>
				<div class="flex items-center gap-4">
					<div class="flex items-center gap-2">
						${icon(Bug, "sm")}
						<span class="text-xs text-muted-foreground">Debugger Tool</span>
						${Switch(
    debuggerMode,
    (checked) => {
      updateDebuggerMode(checked);
    },
    void 0,
    false,
    ""
  )}
					</div>
					<div class="flex items-center gap-2">
						<span class="text-xs text-muted-foreground">Show JSON</span>
						${Switch(
    showJsonMode2,
    (checked) => {
      updateShowJsonMode(checked);
    },
    void 0,
    false,
    ""
  )}
					</div>
				</div>
			</div>

			<!-- Debug content -->
			<div class="flex-1 overflow-auto p-4">
				<div class="space-y-6">
					<!-- Element Picker Tool Section -->
					<div>
						<h2 class="text-lg font-semibold mb-3">Element Picker Tool</h2>
						<div class="border border-border rounded-lg bg-card p-4">
							<p class="text-sm text-muted-foreground mb-3">
								Manually trigger the ask_user_which_element tool to test element picking on the active tab.
							</p>
							${Button({
    variant: "outline",
    size: "md",
    children: b2`<span class="flex items-center gap-2"
									>${icon(MousePointer2, "sm")} <span>Launch Element Picker</span></span
								>`,
    onClick: triggerSelectElement,
    title: "Open element picker on active tab"
  })}
						</div>
					</div>

					<!-- REPL Panel Section -->
					<div>
						<h2 class="text-lg font-semibold mb-3">JavaScript REPL</h2>
						<div class="border border-border rounded-lg overflow-hidden" style="height: 600px;">
							<repl-panel></repl-panel>
						</div>
					</div>

					<!-- Test Prompts Section -->
					<div>
						<h2 class="text-lg font-semibold mb-3">Test Prompts</h2>
						<div class="space-y-3">
							${TEST_PROMPTS.map(
    (test) => b2`
									<div class="border border-border rounded-lg bg-card overflow-hidden">
										<div class="p-3 bg-accent/30">
											<div class="font-medium text-sm">${test.name}</div>
										</div>
										<div class="p-3 space-y-2">
											${test.steps.map(
      (step, i7) => b2`
													<div class="flex gap-2 text-sm text-muted-foreground">
														<span class="text-xs font-mono shrink-0">${i7 + 1}.</span>
														<span>${step}</span>
													</div>
												`
    )}
										</div>
										<div class="p-3 pt-0 flex gap-2 flex-wrap">
											${models.map(
      (model) => b2`
															${Button({
        variant: "outline",
        size: "sm",
        children: b2`<span class="flex items-center gap-1.5"
																	>${icon(Play, "xs")} <span class="text-xs">${model.name}</span></span
																>`,
        onClick: () => {
          const encodedSteps = encodeURIComponent(JSON.stringify(test.steps));
          window.location.href = `./sidepanel.html?teststeps=${encodedSteps}&provider=${encodeURIComponent(
            model.provider
          )}&model=${encodeURIComponent(model.id)}`;
        },
        title: `Run with ${model.name}`
      })}
														`
    )}
										</div>
									</div>
								`
  )}
						</div>
					</div>
				</div>
			</div>
		</div>
	`;
  D(debugHtml, document.body);
};
window.addEventListener("keydown", (e9) => {
  if ((e9.metaKey || e9.ctrlKey) && e9.key === "u") {
    e9.preventDefault();
    window.location.href = "./sidepanel.html";
  }
});
renderDebugPage();
/*! Bundled license information:

jszip/dist/jszip.min.js:
  (*!
  
  JSZip v3.10.1 - A JavaScript class for generating and reading zip files
  <http://stuartk.com/jszip>
  
  (c) 2009-2016 Stuart Knightley <stuart [at] stuartk.com>
  Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/main/LICENSE.markdown.
  
  JSZip uses the library pako released under the MIT license :
  https://github.com/nodeca/pako/blob/main/LICENSE
  *)

@lit/reactive-element/css-tag.js:
  (**
   * @license
   * Copyright 2019 Google LLC
   * SPDX-License-Identifier: BSD-3-Clause
   *)

@lit/reactive-element/reactive-element.js:
lit-html/lit-html.js:
lit-element/lit-element.js:
lit-html/directive.js:
lit-html/async-directive.js:
lit-html/directives/unsafe-html.js:
@lit/reactive-element/decorators/custom-element.js:
@lit/reactive-element/decorators/property.js:
@lit/reactive-element/decorators/state.js:
@lit/reactive-element/decorators/event-options.js:
@lit/reactive-element/decorators/base.js:
@lit/reactive-element/decorators/query.js:
@lit/reactive-element/decorators/query-all.js:
@lit/reactive-element/decorators/query-async.js:
@lit/reactive-element/decorators/query-assigned-nodes.js:
lit-html/directives/repeat.js:
  (**
   * @license
   * Copyright 2017 Google LLC
   * SPDX-License-Identifier: BSD-3-Clause
   *)

lit-html/is-server.js:
  (**
   * @license
   * Copyright 2022 Google LLC
   * SPDX-License-Identifier: BSD-3-Clause
   *)

lit-html/directive-helpers.js:
lit-html/directives/ref.js:
  (**
   * @license
   * Copyright 2020 Google LLC
   * SPDX-License-Identifier: BSD-3-Clause
   *)

lucide/dist/esm/defaultAttributes.js:
lucide/dist/esm/createElement.js:
lucide/dist/esm/icons/check.js:
lucide/dist/esm/icons/code.js:
lucide/dist/esm/icons/copy.js:
lucide/dist/esm/icons/download.js:
lucide/dist/esm/icons/eye.js:
lucide/dist/esm/lucide.js:
lucide/dist/esm/icons/brain.js:
lucide/dist/esm/icons/check.js:
lucide/dist/esm/icons/chevron-down.js:
lucide/dist/esm/icons/chevron-right.js:
lucide/dist/esm/icons/chevron-up.js:
lucide/dist/esm/icons/chevrons-down.js:
lucide/dist/esm/icons/chevrons-up-down.js:
lucide/dist/esm/icons/code.js:
lucide/dist/esm/icons/copy.js:
lucide/dist/esm/icons/download.js:
lucide/dist/esm/icons/file-code-2.js:
lucide/dist/esm/icons/file-spreadsheet.js:
lucide/dist/esm/icons/file-text.js:
lucide/dist/esm/icons/image.js:
lucide/dist/esm/icons/loader-circle.js:
lucide/dist/esm/icons/loader.js:
lucide/dist/esm/icons/lock.js:
lucide/dist/esm/icons/paperclip.js:
lucide/dist/esm/icons/refresh-cw.js:
lucide/dist/esm/icons/send.js:
lucide/dist/esm/icons/sparkles.js:
lucide/dist/esm/icons/square-terminal.js:
lucide/dist/esm/icons/square.js:
lucide/dist/esm/icons/x.js:
lucide/dist/esm/lucide.js:
lucide/dist/esm/icons/arrow-left.js:
lucide/dist/esm/icons/bug.js:
lucide/dist/esm/icons/loader-circle.js:
lucide/dist/esm/icons/mouse-pointer-2.js:
lucide/dist/esm/icons/play.js:
lucide/dist/esm/icons/sparkles.js:
lucide/dist/esm/icons/square.js:
lucide/dist/esm/lucide.js:
  (**
   * @license lucide v0.544.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

@google/genai/dist/web/index.mjs:
@google/genai/dist/web/index.mjs:
@google/genai/dist/web/index.mjs:
@google/genai/dist/web/index.mjs:
@google/genai/dist/web/index.mjs:
  (**
   * @license
   * Copyright 2025 Google LLC
   * SPDX-License-Identifier: Apache-2.0
   *)

@lit/reactive-element/decorators/query-assigned-elements.js:
  (**
   * @license
   * Copyright 2021 Google LLC
   * SPDX-License-Identifier: BSD-3-Clause
   *)

docx-preview/dist/docx-preview.mjs:
  (*
   * @license
   * docx-preview <https://github.com/VolodymyrBaydalka/docxjs>
   * Released under Apache License 2.0  <https://github.com/VolodymyrBaydalka/docxjs/blob/master/LICENSE>
   * Copyright Volodymyr Baydalka
   *)

xlsx/xlsx.mjs:
  (*! xlsx.js (C) 2013-present SheetJS -- http://sheetjs.com *)

xlsx/xlsx.mjs:
  (*! sheetjs (C) 2013-present SheetJS -- http://sheetjs.com *)
*/
//# sourceMappingURL=debug.js.map
